From 831c7a689f6968386fa8190f27c55e5e8c55bbc2 Mon Sep 17 00:00:00 2001 From: pointer-to-bios Date: Sun, 21 Jan 2024 19:49:22 +0800 Subject: [PATCH 01/17] =?UTF-8?q?=E4=BC=98=E5=8C=96=E5=86=85=E5=AD=98?= =?UTF-8?q?=E7=AE=A1=E7=90=86=E6=A8=A1=E5=9D=97=E7=9A=84=E5=86=85=E5=AD=98?= =?UTF-8?q?=E5=88=86=E9=85=8D=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/kernel/memm.h | 4 ++++ src/kernel/memm/memm.c | 19 +++++++++++++------ src/kernel/memm/memm.rs | 5 +++-- src/libk/lst.c | 4 ++-- 4 files changed, 22 insertions(+), 10 deletions(-) diff --git a/include/kernel/memm.h b/include/kernel/memm.h index 27557a7..d3f730f 100644 --- a/include/kernel/memm.h +++ b/include/kernel/memm.h @@ -143,6 +143,10 @@ void *memm_allocate(usize size, usize pid); #define memm_addr_get_allocator(mem) \ ((*(allocator_t **)(mem - 16))) +void *memm_kernel_allocate(usize size); + +void *memm_user_allocate(usize size, usize pid); + /* 释放内存 */ diff --git a/src/kernel/memm/memm.c b/src/kernel/memm/memm.c index aecfe24..2b152e6 100644 --- a/src/kernel/memm/memm.c +++ b/src/kernel/memm/memm.c @@ -192,7 +192,7 @@ void *memm_allocate(usize size, usize pid) MEMM_RAW_ALLOCATOR, pid); allocator = new_allocator; - allocator_iterator_t *allind = memm_allocate(sizeof(allocator_iterator_t), 0); + allocator_iterator_t *allind = memm_kernel_allocate(sizeof(allocator_iterator_t)); allind->allocator = new_allocator; allind->left = nullptr; allind->right = nullptr; @@ -201,14 +201,21 @@ void *memm_allocate(usize size, usize pid) after_allocation: memm_addr_set_allocator(ptr, allocator); - if (pid != 0) - { // TODO 进程管理中应该有一个用户地址-内核地址映射表 - // 在进程分配时将页映射到用户空间中,并将这个映射关系记录进这个表中 - // 需要返回的是用户空间的地址 - } return ptr; } +void *memm_kernel_allocate(usize size) +{ + return memm_allocate(size, 0); +} + +void *memm_user_allocate(usize size, usize pid) +{ + void *res = memm_allocate(size, pid); + // TODO 将内存空间映射到用户空间 + return res; +} + void memm_free(void *mem) { allocator_t *allocator = memm_addr_get_allocator(mem); diff --git a/src/kernel/memm/memm.rs b/src/kernel/memm/memm.rs index 471c332..fc41bf3 100644 --- a/src/kernel/memm/memm.rs +++ b/src/kernel/memm/memm.rs @@ -3,7 +3,8 @@ extern crate core; use core::alloc::{GlobalAlloc, Layout}; extern "C" { - pub fn memm_allocate(size: usize, pid: usize) -> *mut u8; + pub fn memm_kernel_allocate(size: usize) -> *mut u8; + pub fn memm_user_allocate(size: usize, pid: usize); pub fn memm_free(mem: *mut u8); } @@ -11,7 +12,7 @@ pub struct KernelAllocator {} unsafe impl GlobalAlloc for KernelAllocator { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { - memm_allocate(layout.size(), 0) + memm_kernel_allocate(layout.size()) } unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { diff --git a/src/libk/lst.c b/src/libk/lst.c index cbfcce0..71b1cef 100644 --- a/src/libk/lst.c +++ b/src/libk/lst.c @@ -7,7 +7,7 @@ lst_iterator_t *lst_new(usize start, usize end) { - lst_iterator_t *lst = memm_allocate(sizeof(lst_iterator_t), 0); + lst_iterator_t *lst = memm_kernel_allocate(sizeof(lst_iterator_t), 0); lst->line.left = start; lst->line.right = end; lst->next = nullptr; @@ -128,7 +128,7 @@ bool lst_add(lst_iterator_t *lst, usize left, usize right, bool force) lst->line.left = left; else { - lst_iterator_t *new_node = memm_allocate(sizeof(lst_iterator_t), 0); + lst_iterator_t *new_node = memm_kernel_allocate(sizeof(lst_iterator_t)); new_node->line = line; new_node->next = lst; if (last != nullptr) -- 2.45.0 From 69b6d55d4d2d7271dd41d9a340b9a5832ee094b3 Mon Sep 17 00:00:00 2001 From: pointer-to-bios Date: Mon, 22 Jan 2024 00:48:56 +0800 Subject: [PATCH 02/17] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E5=A4=9Atty=E7=9A=84=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/kernel/tty.h | 17 ++++++- src/kernel/main.rs | 5 +- src/kernel/tty/tty.c | 106 ++++++++++++++++++++++++++++-------------- src/kernel/tty/tty.rs | 32 ++++++++----- src/libk/lst.c | 2 +- 5 files changed, 110 insertions(+), 52 deletions(-) diff --git a/include/kernel/tty.h b/include/kernel/tty.h index 6079eeb..1a8395d 100644 --- a/include/kernel/tty.h +++ b/include/kernel/tty.h @@ -12,7 +12,7 @@ typedef enum __tty_type // 用于图形功能初始化后,直接连接图形接口 tty_type_display = 2, // 用于图形终端的终端模拟器 - tty_type_vtty = 3, + tty_type_vterm = 3, } tty_type; typedef enum __framebuffer_pixel_type @@ -58,6 +58,7 @@ typedef struct __tty tty_type type; tty_typeinfo typeinfo; tty_mode mode; + bool enabled; tty_text_state text; } tty; @@ -67,6 +68,7 @@ typedef struct __tty_controller_t #define TTY_MAX_NUM 128 tty *ttys[TTY_MAX_NUM]; bool map[TTY_MAX_NUM]; + tty *enabled[TTY_MAX_NUM]; } tty_controller_t; /** @@ -118,6 +120,19 @@ void tty_text_print(tty *ttyx, char *string, u32 color, u32 bgcolor); #define gen_color(r, g, b) (((r) << 16) | ((g) << 8) | (b)) +/** + * @brief 打开某个tty + * + * @param ttyx + * @return true 打开成功 + * @return false 已经打开 + * 或作为raw_framebuffer类型的tty,framebuffer已被其它raw_framebuffer + * 类型的tty占用 + */ +bool tty_enable(tty *ttyx); + +void tty_disable(tty *ttyx); + #define TTY_FONT_SCALE 2 typedef struct __tty_font_t diff --git a/src/kernel/main.rs b/src/kernel/main.rs index 099a7ee..cf8c6e4 100644 --- a/src/kernel/main.rs +++ b/src/kernel/main.rs @@ -1,12 +1,9 @@ -use std::panic; - use crate::kernel::tty::tty::{Color, MessageBuilder, Tty}; #[no_mangle] extern "C" fn kmain_rust() { let tty = Tty::from_id(0).unwrap(); - // let ttyptr = unsafe { tty.get_c_tty_t() }; - + tty.enable(); let hello = MessageBuilder::new() .message("Hello, ".to_string()) .message("Metaverse".to_string()) diff --git a/src/kernel/tty/tty.c b/src/kernel/tty/tty.c index b7c5b36..a2af9b2 100644 --- a/src/kernel/tty/tty.c +++ b/src/kernel/tty/tty.c @@ -11,26 +11,27 @@ tty_controller_t *tty_controller_new() { memset(tty_ctrler.ttys, 0, sizeof(tty_ctrler.ttys)); memset(tty_ctrler.map, 0, sizeof(tty_ctrler.map)); + memset(tty_ctrler.enabled, 0, sizeof(tty_ctrler.enabled)); return &tty_ctrler; } tty *tty_new(tty_type type, tty_mode mode) { - tty *__tty = memm_allocate(sizeof(tty), 0); - memset(__tty, 0, sizeof(tty)); - __tty->type = type; - __tty->mode = mode; tty *res = nullptr; for (usize i = 0; i < TTY_MAX_NUM; ++i) { if (tty_ctrler.map[i] == false) { - res = __tty; - __tty->id = i; - tty_ctrler.ttys[i] = __tty; + res = memm_kernel_allocate(sizeof(tty)); + res->id = i; + tty_ctrler.ttys[i] = res; tty_ctrler.map[i] = true; + break; } } + res->type = type; + res->mode = mode; + res->enabled = false; return res; } @@ -55,6 +56,8 @@ void tty_set_framebuffer(tty *ttyx, framebuffer *fb) { ttyx->text.width = fb->width / tty_get_font()->char_width; ttyx->text.height = fb->height / tty_get_font()->char_height; + ttyx->text.line = 0; + ttyx->text.column = 0; } } @@ -87,12 +90,13 @@ inline static void putchar( { for (usize b = 0; b < TTY_FONT_SCALE; ++b) { - put_pixel(ttyx->typeinfo.raw_framebuffer.pointer, - ttyx->typeinfo.raw_framebuffer.width, - ttyx->typeinfo.raw_framebuffer.pixsize, - ttyx->text.column * font->char_width * TTY_FONT_SCALE + i * TTY_FONT_SCALE + a, - ttyx->text.line * font->char_height * TTY_FONT_SCALE + j * TTY_FONT_SCALE + b, - color); + put_pixel( + ttyx->typeinfo.raw_framebuffer.pointer, + ttyx->typeinfo.raw_framebuffer.width, + ttyx->typeinfo.raw_framebuffer.pixsize, + ttyx->text.column * font->char_width * TTY_FONT_SCALE + i * TTY_FONT_SCALE + a, + ttyx->text.line * font->char_height * TTY_FONT_SCALE + j * TTY_FONT_SCALE + b, + color); } } } @@ -102,12 +106,13 @@ inline static void putchar( { for (usize b = 0; b < TTY_FONT_SCALE; ++b) { - put_pixel(ttyx->typeinfo.raw_framebuffer.pointer, - ttyx->typeinfo.raw_framebuffer.width, - ttyx->typeinfo.raw_framebuffer.pixsize, - ttyx->text.column * font->char_width * TTY_FONT_SCALE + i * TTY_FONT_SCALE + a, - ttyx->text.line * font->char_height * TTY_FONT_SCALE + j * TTY_FONT_SCALE + b, - bgcolor); + put_pixel( + ttyx->typeinfo.raw_framebuffer.pointer, + ttyx->typeinfo.raw_framebuffer.width, + ttyx->typeinfo.raw_framebuffer.pixsize, + ttyx->text.column * font->char_width * TTY_FONT_SCALE + i * TTY_FONT_SCALE + a, + ttyx->text.line * font->char_height * TTY_FONT_SCALE + j * TTY_FONT_SCALE + b, + bgcolor); } } } @@ -121,17 +126,20 @@ inline static void newline(tty *ttyx) ttyx->text.line++; if (ttyx->text.line == ttyx->text.height) { - scroll_buffer(ttyx->typeinfo.raw_framebuffer.pointer, - ttyx->typeinfo.raw_framebuffer.width, - ttyx->typeinfo.raw_framebuffer.height, - ttyx->typeinfo.raw_framebuffer.pixsize, - tty_get_font()->char_height * TTY_FONT_SCALE); + scroll_buffer( + ttyx->typeinfo.raw_framebuffer.pointer, + ttyx->typeinfo.raw_framebuffer.width, + ttyx->typeinfo.raw_framebuffer.height, + ttyx->typeinfo.raw_framebuffer.pixsize, + tty_get_font()->char_height * TTY_FONT_SCALE); ttyx->text.line--; } } void tty_text_print(tty *ttyx, char *string, u32 color, u32 bgcolor) { + if (ttyx->enabled == false) + return; if (ttyx->mode != tty_mode_text) return; if (ttyx->typeinfo.raw_framebuffer.pixtype == bgr) @@ -147,8 +155,8 @@ void tty_text_print(tty *ttyx, char *string, u32 color, u32 bgcolor) } } tty_font_t *font = tty_get_font(); - simple_lock_lock(ttyx->text.lock); usize len = strlen(string); + simple_lock_lock(ttyx->text.lock); for (char *str = string; string - str < len; string++) { char c = *string; @@ -173,11 +181,12 @@ void tty_text_print(tty *ttyx, char *string, u32 color, u32 bgcolor) ttyx->text.line++; if (ttyx->text.line == ttyx->text.height) { - scroll_buffer(ttyx->typeinfo.raw_framebuffer.pointer, - ttyx->typeinfo.raw_framebuffer.width, - ttyx->typeinfo.raw_framebuffer.height, - ttyx->typeinfo.raw_framebuffer.pixsize, - font->char_height * TTY_FONT_SCALE); + scroll_buffer( + ttyx->typeinfo.raw_framebuffer.pointer, + ttyx->typeinfo.raw_framebuffer.width, + ttyx->typeinfo.raw_framebuffer.height, + ttyx->typeinfo.raw_framebuffer.pixsize, + font->char_height * TTY_FONT_SCALE); ttyx->text.line--; } continue; @@ -192,11 +201,12 @@ void tty_text_print(tty *ttyx, char *string, u32 color, u32 bgcolor) } else if (c == '\f') { // 滚动一行 - scroll_buffer(ttyx->typeinfo.raw_framebuffer.pointer, - ttyx->typeinfo.raw_framebuffer.width, - ttyx->typeinfo.raw_framebuffer.height, - ttyx->typeinfo.raw_framebuffer.pixsize, - font->char_height * TTY_FONT_SCALE); + scroll_buffer( + ttyx->typeinfo.raw_framebuffer.pointer, + ttyx->typeinfo.raw_framebuffer.width, + ttyx->typeinfo.raw_framebuffer.height, + ttyx->typeinfo.raw_framebuffer.pixsize, + font->char_height * TTY_FONT_SCALE); continue; } // 打印字符c @@ -213,3 +223,29 @@ void tty_text_print(tty *ttyx, char *string, u32 color, u32 bgcolor) putchar(ttyx, '\0', gen_color(0x88, 0x88, 0x88), 0); simple_lock_unlock(ttyx->text.lock); } + +bool tty_enable(tty *ttyx) +{ + if (tty_ctrler.enabled[ttyx->id]) + return false; + if (ttyx->type == tty_type_raw_framebuffer) + { + for (usize i = 0; i < TTY_MAX_NUM; ++i) + { + if (ttyx->id != i && + tty_ctrler.enabled[i] != nullptr && + tty_ctrler.ttys[i]->type == tty_type_raw_framebuffer) + return false; + } + } + + ttyx->enabled = true; + tty_ctrler.enabled[ttyx->id] = ttyx; + return true; +} + +void tty_disable(tty *ttyx) +{ + ttyx->enabled = false; + tty_ctrler.enabled[ttyx->id] = false; +} diff --git a/src/kernel/tty/tty.rs b/src/kernel/tty/tty.rs index 2d6aa59..1f33a1a 100644 --- a/src/kernel/tty/tty.rs +++ b/src/kernel/tty/tty.rs @@ -1,20 +1,20 @@ -use std::{ - io::{BufWriter, Write}, - ptr::null_mut, -}; +use std::ptr::null_mut; extern "C" { fn tty_new(tty_type: u8, mode: u8) -> *mut u8; fn tty_get(id: usize) -> *mut *mut u8; pub fn tty_text_print(ttyx: *mut u8, string: *mut u8, color: u32, bgcolor: u32); fn tty_get_id(tty: *mut u8) -> usize; + + fn tty_enable(tty: *mut u8) -> bool; + fn tty_disable(tty: *mut u8); } pub enum Type { Invalid = 0, RawFramebuffer = 1, Display = 2, - VirtualTty = 3, + VirtualTerm = 3, } pub enum Mode { @@ -50,12 +50,20 @@ impl Tty { unsafe { tty_get_id(self.tty_pointer) } } + pub fn enable(&self) { + unsafe { tty_enable(self.tty_pointer) }; + } + + pub fn disable(&self) { + unsafe { tty_disable(self.tty_pointer) }; + } + pub fn print(&self, msg: Message) { for MessageSection { mut msg, fgcolor, bgcolor, - } in msg.into_iter() + } in msg.0.into_iter() { unsafe { let string = msg.as_bytes_mut() as *mut [u8] as *mut u8; @@ -89,7 +97,7 @@ pub struct MessageSection { bgcolor: Color, } -type Message = Vec; +pub struct Message(Vec); pub struct MessageBuilder { msg: Message, @@ -97,11 +105,13 @@ pub struct MessageBuilder { impl MessageBuilder { pub fn new() -> Self { - Self { msg: vec![] } + Self { + msg: Message(vec![]), + } } pub fn message(mut self, msg: String) -> Self { - self.msg.push(MessageSection { + self.msg.0.push(MessageSection { msg, fgcolor: Color(0xee, 0xee, 0xee), bgcolor: Color(0, 0, 0), @@ -110,14 +120,14 @@ impl MessageBuilder { } pub fn background_color(mut self, color: Color) -> Self { - if let Some(msg) = self.msg.last_mut() { + if let Some(msg) = self.msg.0.last_mut() { msg.bgcolor = color; } self } pub fn foreground_color(mut self, color: Color) -> Self { - if let Some(msg) = self.msg.last_mut() { + if let Some(msg) = self.msg.0.last_mut() { msg.fgcolor = color; } self diff --git a/src/libk/lst.c b/src/libk/lst.c index 71b1cef..b858723 100644 --- a/src/libk/lst.c +++ b/src/libk/lst.c @@ -7,7 +7,7 @@ lst_iterator_t *lst_new(usize start, usize end) { - lst_iterator_t *lst = memm_kernel_allocate(sizeof(lst_iterator_t), 0); + lst_iterator_t *lst = memm_kernel_allocate(sizeof(lst_iterator_t)); lst->line.left = start; lst->line.right = end; lst->next = nullptr; -- 2.45.0 From d02f4733e6b741b535c758a88f7c5510207d7234 Mon Sep 17 00:00:00 2001 From: pointer-to-bios Date: Mon, 22 Jan 2024 16:40:08 +0800 Subject: [PATCH 03/17] =?UTF-8?q?=E6=9B=B4=E6=96=B0rustlib=E5=AD=90?= =?UTF-8?q?=E4=BB=93=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rustlib | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rustlib b/rustlib index f8d0d53..0d9cd08 160000 --- a/rustlib +++ b/rustlib @@ -1 +1 @@ -Subproject commit f8d0d53a23b5a91848d8f6491122b69f79994537 +Subproject commit 0d9cd0822c355e784c6f4ff5ac2fd88f6d917ea7 -- 2.45.0 From 7afa51d9eaf2bf51f6e843af5a2b08d31a6eb210 Mon Sep 17 00:00:00 2001 From: pointer-to-bios Date: Mon, 22 Jan 2024 17:24:47 +0800 Subject: [PATCH 04/17] =?UTF-8?q?=E5=B0=86rust=E7=9A=84=E6=89=80=E6=9C=89?= =?UTF-8?q?=E6=AE=B5=E6=94=BE=E5=9C=A8kend=E5=89=8D=EF=BC=8C=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0release=E6=A8=A1=E5=BC=8F=E4=B8=8Brustc=E7=9A=84?= =?UTF-8?q?=E4=BC=98=E5=8C=96=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Makefile | 7 +++++-- src/metaverse.lds | 42 +++++++++++++++++++++++++++++++++++++++++- 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/src/Makefile b/src/Makefile index cbfd441..fe78fe8 100644 --- a/src/Makefile +++ b/src/Makefile @@ -26,8 +26,11 @@ RSCFLAGS = --emit obj --crate-type lib \ -L crate="${PWD}/../rustlib/${ARCH}/src/" \ -C code-model=large \ -C relocation-model=static \ - -C embed-bitcode=no \ - -C opt-level=z + -C embed-bitcode=no + +ifdef release + RSCFLAGS := -O +endif ifeq (${ARCH},x86_64) RSCFLAGS := ${RSCFLAGS} -C target-feature=-sse,-avx diff --git a/src/metaverse.lds b/src/metaverse.lds index 7bb371b..c1e7568 100644 --- a/src/metaverse.lds +++ b/src/metaverse.lds @@ -62,8 +62,48 @@ SECTIONS { {} .igot.plt : {} + .tbss : + { + *(.tbss) + } + .tdata : + { + *(.tdata) + } + .debug_line : + { + *(.debug_line) + } + .debug_abbrev : + { + *(.debug_abbrev) + } + .debug_info : + { + *(.debug_info) + } + .debug_str : + { + *(.debug_str) + } + .debug_aranges : + { + *(.debug_aranges) + } + .debug_ranges : + { + *(.debug_ranges) + } + .debug_pubnames : + { + *(.debug_pubnames) + } + .debug_pubtypes : + { + *(.debug_pubtypes) + } .kend : { *(.kend) } -} \ No newline at end of file +} -- 2.45.0 From bfd7530ae23e7ddaa826f8065b10a330191a9f35 Mon Sep 17 00:00:00 2001 From: pointer-to-bios Date: Tue, 23 Jan 2024 04:42:58 +0800 Subject: [PATCH 05/17] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=86=85=E6=A0=B8?= =?UTF-8?q?=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/kernel/clock/time.h | 15 +++ include/kernel/tty.h | 17 +++- src/kernel/Makefile | 4 +- src/kernel/clock/mod.rs | 1 + src/kernel/clock/time.c | 20 ++++ src/kernel/clock/time.rs | 165 +++++++++++++++++++++++++++++++ src/kernel/klog.rs | 160 ++++++++++++++++++++++++++++++ src/kernel/klog/klog.rs | 0 src/kernel/main.rs | 22 +++-- src/kernel/memm/memm.rs | 2 +- src/kernel/mod.rs | 5 +- src/kernel/sync/mod.rs | 1 + src/kernel/sync/rwlock.rs | 130 ++++++++++++++++++++++++ src/kernel/tty/tty.c | 36 +++++++ src/kernel/tty/tty.rs | 192 +++++++++++++++++++++++++++++++++++- 15 files changed, 749 insertions(+), 21 deletions(-) create mode 100644 include/kernel/clock/time.h create mode 100644 src/kernel/clock/mod.rs create mode 100644 src/kernel/clock/time.c create mode 100644 src/kernel/clock/time.rs create mode 100644 src/kernel/klog.rs delete mode 100644 src/kernel/klog/klog.rs create mode 100644 src/kernel/sync/mod.rs create mode 100644 src/kernel/sync/rwlock.rs diff --git a/include/kernel/clock/time.h b/include/kernel/clock/time.h new file mode 100644 index 0000000..b6cb4de --- /dev/null +++ b/include/kernel/clock/time.h @@ -0,0 +1,15 @@ +#ifndef TIME_H +#define TIME_H + +#include + +// 使用UNIX时间戳 +usize system_time_get(); + +// 如果硬件支持更高的计时精度, +// 此函数提供从系统unix时间开始到现在的纳秒为单位的时间 +usize system_time_ns_get(); + +void system_time_increase(); + +#endif diff --git a/include/kernel/tty.h b/include/kernel/tty.h index 1a8395d..2a1e6c3 100644 --- a/include/kernel/tty.h +++ b/include/kernel/tty.h @@ -6,7 +6,7 @@ typedef enum __tty_type { - invalid = 0, + tty_type_invalid = 0, // 用于在内核刚刚被引导,只有bootloader提供的显示功能时使用 tty_type_raw_framebuffer = 1, // 用于图形功能初始化后,直接连接图形接口 @@ -40,8 +40,9 @@ typedef struct __framebuffer framebuffer; // 文本模式中的字符由tty模块渲染 typedef enum __tty_mode { - tty_mode_text = 0, - tty_mode_graphics = 1, + tty_mode_invalid = 0, + tty_mode_text = 1, + tty_mode_graphics = 2, } tty_mode; typedef struct __tty_text_state @@ -55,6 +56,7 @@ typedef struct __tty_text_state typedef struct __tty { usize id; + usize width, height; tty_type type; tty_typeinfo typeinfo; tty_mode mode; @@ -120,6 +122,14 @@ void tty_text_print(tty *ttyx, char *string, u32 color, u32 bgcolor); #define gen_color(r, g, b) (((r) << 16) | ((g) << 8) | (b)) +usize tty_get_width(tty *ttyx); +usize tty_get_height(tty *ttyx); + +tty_type tty_get_type(tty *ttyx); +tty_mode tty_get_mode(tty *ttyx); + +bool tty_is_enabled(tty *ttyx); + /** * @brief 打开某个tty * @@ -130,7 +140,6 @@ void tty_text_print(tty *ttyx, char *string, u32 color, u32 bgcolor); * 类型的tty占用 */ bool tty_enable(tty *ttyx); - void tty_disable(tty *ttyx); #define TTY_FONT_SCALE 2 diff --git a/src/kernel/Makefile b/src/kernel/Makefile index 8a1f78a..093fa03 100644 --- a/src/kernel/Makefile +++ b/src/kernel/Makefile @@ -11,7 +11,7 @@ ifdef release CCFLAGS := ${CCFLAGS} -O2 endif -C_SRCS = main.c tty.c font.c memm.c memm_${ARCH}.c raw.c +C_SRCS = main.c tty.c font.c memm.c memm_${ARCH}.c raw.c time.c C_OBJS = ${C_SRCS:.c=.c.o} ################################ @@ -38,7 +38,7 @@ STRIP_SECS = -R .note.GNU-stack OBJCOPY_FLAGS = ${STRIP_SECS} # 子目录 -VPATH = memm/ memm/allocator tty/ klog/ arch/${ARCH} +VPATH = memm/ memm/allocator tty/ klog/ arch/${ARCH} clock/ %.c.o: %.c @echo -e "\e[1m\e[33m${CC}\e[0m \e[32m$<\e[0m \e[34m-->\e[0m \e[1m\e[32m$@\e[0m" diff --git a/src/kernel/clock/mod.rs b/src/kernel/clock/mod.rs new file mode 100644 index 0000000..077885d --- /dev/null +++ b/src/kernel/clock/mod.rs @@ -0,0 +1 @@ +pub mod time; diff --git a/src/kernel/clock/time.c b/src/kernel/clock/time.c new file mode 100644 index 0000000..c9af49b --- /dev/null +++ b/src/kernel/clock/time.c @@ -0,0 +1,20 @@ +#include +#include + +usize system_time; +usize system_time_ns; + +usize system_time_get() +{ + return system_time; +} + +usize system_time_ns_get() +{ + return system_time_ns; +} + +void system_time_increase() +{ + system_time++; +} diff --git a/src/kernel/clock/time.rs b/src/kernel/clock/time.rs new file mode 100644 index 0000000..b0b0e66 --- /dev/null +++ b/src/kernel/clock/time.rs @@ -0,0 +1,165 @@ +use std::{cmp::Ordering, fmt::Debug, ops::Sub, time::Duration}; + +extern "C" { + fn system_time_get() -> usize; + fn system_time_ns_get() -> usize; +} + +#[derive(Debug)] +pub struct SystemTimeError(Duration); + +#[derive(Clone, Copy, Hash)] +pub struct SystemTime { + unix_time: usize, + ns_time: usize, +} + +impl Debug for SystemTime { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + 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; + write!( + f, + "[{:02}-{:02}-{:02} {:02}:{:02}:{:02}.{:03}]", + year, month, day, hour, minute, second, milisec + ) + } +} + +impl Eq for SystemTime {} +impl PartialEq for SystemTime { + fn eq(&self, other: &Self) -> bool { + self.unix_time == other.unix_time && self.ns_time == other.ns_time + } +} + +impl Ord for SystemTime { + fn cmp(&self, other: &Self) -> Ordering { + match self.unix_time.cmp(&other.unix_time) { + Ordering::Equal => self.ns_time.cmp(&other.ns_time), + ord => ord, + } + } +} + +impl PartialOrd for SystemTime { + fn partial_cmp(&self, other: &Self) -> Option { + match self.unix_time.partial_cmp(&other.unix_time) { + Some(Ordering::Equal) => self.ns_time.partial_cmp(&other.ns_time), + ord => ord, + } + } +} + +impl Sub for SystemTime { + type Output = Result; + + fn sub(self, rhs: SystemTime) -> Self::Output { + if self < rhs { + let earl = (rhs - self).unwrap(); + Err(SystemTimeError(earl)) + } else { + let usdiff = self.ns_time as isize - self.ns_time as isize; + let usdiff = if usdiff >= 0 { + Duration::from_nanos(usdiff as usize as u64) + } else { + Duration::from_nanos(0) - Duration::from_nanos((-usdiff) as usize as u64) + }; + Ok(Duration::from_millis((self.unix_time - rhs.unix_time) as u64) + usdiff) + } + } +} + +impl SystemTime { + pub fn now() -> Self { + unsafe { + Self { + unix_time: system_time_get(), + ns_time: system_time_ns_get(), + } + } + } + + pub fn duration_since(&self, earlier: &SystemTime) -> Result { + *self - *earlier + } + + pub fn elapsed(&self) -> Result { + SystemTime::now() - *self + } +} diff --git a/src/kernel/klog.rs b/src/kernel/klog.rs new file mode 100644 index 0000000..41e4f23 --- /dev/null +++ b/src/kernel/klog.rs @@ -0,0 +1,160 @@ +use super::{ + clock::time::SystemTime, + tty::tty::{Color, Message, MessageBuilder}, +}; + +#[derive(PartialEq)] +pub enum LoggerLevel { + Fatal, + Error, + Warning, + Info, + Debug, + Trace, +} + +pub struct KernelLogger { + fatal_queue: Vec<(SystemTime, Message)>, + error_queue: Vec<(SystemTime, Message)>, + warning_queue: Vec<(SystemTime, Message)>, + info_queue: Vec<(SystemTime, Message)>, + debug_queue: Vec<(SystemTime, Message)>, + trace_queue: Vec<(SystemTime, Message)>, +} + +impl KernelLogger { + pub fn new() -> Self { + Self { + fatal_queue: vec![], + error_queue: vec![], + warning_queue: vec![], + info_queue: vec![], + debug_queue: vec![], + trace_queue: vec![], + } + } + + pub fn fatal(&mut self, msg: Message) { + let msg = MessageBuilder::new() + .message("Fatal: ".to_string()) + .foreground_color(Color(0xee, 0xa, 0xa)) + .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: ".to_string()) + .foreground_color(Color(0xaa, 0x22, 0x22)) + .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: ".to_string()) + .foreground_color(Color(0xaa, 0xa, 0xaa)) + .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: ".to_string()) + .foreground_color(Color(0xa, 0xee, 0xa)) + .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: ".to_string()) + .foreground_color(Color(0xee, 0xee, 0xee)) + .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: ".to_string()) + .foreground_color(Color(0xee, 0xee, 0xee)) + .append(MessageBuilder::from_message(&msg)) + .build(); + self.trace_queue.push((SystemTime::now(), msg)); + } + + pub fn iter(&self, level: LoggerLevel) -> LogIterator { + let mut logs = vec![]; + if level == LoggerLevel::Fatal { + logs.push(&self.fatal_queue); + } + if level == LoggerLevel::Fatal || level == LoggerLevel::Error { + logs.push(&self.error_queue); + } + if level == LoggerLevel::Fatal + || level == LoggerLevel::Error + || level == LoggerLevel::Warning + { + logs.push(&self.warning_queue); + } + if level == LoggerLevel::Fatal + || level == LoggerLevel::Error + || level == LoggerLevel::Warning + || level == LoggerLevel::Info + { + logs.push(&self.info_queue); + } + if level == LoggerLevel::Fatal + || level == LoggerLevel::Error + || level == LoggerLevel::Warning + || level == LoggerLevel::Info + || level == LoggerLevel::Debug + { + logs.push(&self.debug_queue); + } + if level == LoggerLevel::Fatal + || level == LoggerLevel::Error + || level == LoggerLevel::Warning + || level == LoggerLevel::Info + || level == LoggerLevel::Debug + || level == LoggerLevel::Trace + { + logs.push(&self.trace_queue); + } + let mut res = vec![]; + while let Some(msg) = { + logs.iter_mut() + .filter_map(|&mut l| l.first().cloned()) + .min_by_key(|&(syst, _)| syst) + } { + res.push(msg); + } + LogIterator { logs: res } + } +} + +pub struct LogIterator { + logs: Vec<(SystemTime, Message)>, +} + +impl Iterator for LogIterator { + type Item = Message; + + fn next(&mut self) -> Option { + if let Some((time, msg)) = self.logs.first() { + Some( + MessageBuilder::new() + .message(format!("{:?}", time)) + .append(MessageBuilder::from_message(msg)) + .build(), + ) + } else { + None + } + } +} diff --git a/src/kernel/klog/klog.rs b/src/kernel/klog/klog.rs deleted file mode 100644 index e69de29..0000000 diff --git a/src/kernel/main.rs b/src/kernel/main.rs index cf8c6e4..5d0373a 100644 --- a/src/kernel/main.rs +++ b/src/kernel/main.rs @@ -1,15 +1,19 @@ -use crate::kernel::tty::tty::{Color, MessageBuilder, Tty}; +use super::{ + klog::{KernelLogger, LoggerLevel}, + tty::tty::{Color, ColorPair, Message, Tty}, +}; #[no_mangle] extern "C" fn kmain_rust() { + let mut logger = KernelLogger::new(); + logger.info(Message::from(format!( + "Hello, {:?}Metaverse{:?}!", + ColorPair::color(Color(0xa, 0xee, 0xa), Color(0, 0, 0)), + ColorPair::Reset + ))); let tty = Tty::from_id(0).unwrap(); - tty.enable(); - let hello = MessageBuilder::new() - .message("Hello, ".to_string()) - .message("Metaverse".to_string()) - .foreground_color(Color(0xa, 0xee, 0xa)) - .message("!\n".to_string()) - .build(); - tty.print(hello); + for msg in logger.iter(LoggerLevel::Info) { + tty.print(msg); + } loop {} } diff --git a/src/kernel/memm/memm.rs b/src/kernel/memm/memm.rs index fc41bf3..3995400 100644 --- a/src/kernel/memm/memm.rs +++ b/src/kernel/memm/memm.rs @@ -4,7 +4,7 @@ use core::alloc::{GlobalAlloc, Layout}; extern "C" { pub fn memm_kernel_allocate(size: usize) -> *mut u8; - pub fn memm_user_allocate(size: usize, pid: usize); + // pub fn memm_user_allocate(size: usize, pid: usize); pub fn memm_free(mem: *mut u8); } diff --git a/src/kernel/mod.rs b/src/kernel/mod.rs index 14f7bad..583319c 100644 --- a/src/kernel/mod.rs +++ b/src/kernel/mod.rs @@ -1,3 +1,6 @@ +pub mod clock; +pub mod klog; +pub mod main; pub mod memm; pub mod tty; -pub mod main; +pub mod sync; diff --git a/src/kernel/sync/mod.rs b/src/kernel/sync/mod.rs new file mode 100644 index 0000000..2ba968f --- /dev/null +++ b/src/kernel/sync/mod.rs @@ -0,0 +1 @@ +pub mod rwlock; diff --git a/src/kernel/sync/rwlock.rs b/src/kernel/sync/rwlock.rs new file mode 100644 index 0000000..be7a430 --- /dev/null +++ b/src/kernel/sync/rwlock.rs @@ -0,0 +1,130 @@ +use std::{ + ops::{Deref, DerefMut}, + ptr::null_mut, +}; + +/// ## RwLock +/// 读写锁 +/// +/// * 对于写入操作: +/// +/// 锁没有占用时,获取锁,并执行闭包。 +/// +/// 当锁已经被占用,将闭包悬挂。 +/// +/// 释放锁时,将所有悬挂的闭包都执行。 +/// +/// 正在释放锁时,`write`方法返回`Err(())` +/// +/// ``` +/// let num = 6; +/// let num = RwLock::new(num); +/// if let Err(()) = num.write( +/// |n| *n = 10 +/// ) {} +/// let numstr = format!("{}", num.read()); +/// ```` +pub struct RwLock<'a, T> { + obj: T, + locked: bool, + dealing_hanged: bool, + ptr: *mut RwLockWriteGuard<'a, T>, + hanging: Vec<&'a dyn Fn(&mut T)>, +} + +unsafe impl Send for RwLock<'_, T> {} +unsafe impl Sync for RwLock<'_, T> {} + +impl<'a, T> RwLock<'a, T> { + pub fn new(obj: T) -> Self { + Self { + obj, + locked: false, + dealing_hanged: false, + ptr: null_mut(), + hanging: vec![], + } + } + + pub fn read(&self) -> RwLockReadGuard { + RwLockReadGuard { obj: &self.obj } + } + + pub fn write(&'a mut self, f: &'a dyn Fn(&mut T)) -> Result, ()> { + if self.dealing_hanged { + Err(()) + } else if !self.locked { + self.locked = true; + f(&mut self.obj); + let ptr = { self as *mut RwLock<'a, T> }; + let obj = &mut self.obj; + let mut res = RwLockWriteGuard { + obj, + ptr, + must_deal_hang: false, + }; + self.ptr = &mut res as *mut RwLockWriteGuard<'_, T>; + Ok(res) + } else { + self.hanging.push(f); + let ptr = { self as *mut RwLock<'a, T> }; + let obj = &mut self.obj; + Ok(RwLockWriteGuard { + obj, + ptr, + must_deal_hang: false, + }) + } + } +} + +pub struct RwLockReadGuard<'a, T> { + obj: &'a T, +} + +impl<'a, T> Deref for RwLockReadGuard<'a, T> { + type Target = T; + + fn deref(&self) -> &Self::Target { + self.obj + } +} + +impl<'a, T> Drop for RwLockReadGuard<'a, T> { + fn drop(&mut self) {} +} + +pub struct RwLockWriteGuard<'a, T> { + obj: &'a mut T, + ptr: *mut RwLock<'a, T>, + must_deal_hang: bool, +} + +impl<'a, T> Deref for RwLockWriteGuard<'a, T> { + type Target = T; + + fn deref(&self) -> &Self::Target { + self.obj + } +} + +impl<'a, T> DerefMut for RwLockWriteGuard<'a, T> { + fn deref_mut(&mut self) -> &mut Self::Target { + self.obj + } +} + +impl<'a, T> Drop for RwLockWriteGuard<'a, T> { + fn drop(&mut self) { + if self.must_deal_hang { + let p = unsafe { &mut *self.ptr }; + p.dealing_hanged = true; + for f in p.hanging.iter() { + f(self.obj); + } + p.hanging.clear(); + p.dealing_hanged = false; + p.locked = false; + } + } +} diff --git a/src/kernel/tty/tty.c b/src/kernel/tty/tty.c index a2af9b2..809445c 100644 --- a/src/kernel/tty/tty.c +++ b/src/kernel/tty/tty.c @@ -32,6 +32,8 @@ tty *tty_new(tty_type type, tty_mode mode) res->type = type; res->mode = mode; res->enabled = false; + res->width = 0; + res->height = 0; return res; } @@ -52,6 +54,8 @@ void tty_set_framebuffer(tty *ttyx, framebuffer *fb) if (ttyx->type != tty_type_raw_framebuffer) return; memcpy(&ttyx->typeinfo.raw_framebuffer, fb, sizeof(framebuffer)); + ttyx->width = ttyx->typeinfo.raw_framebuffer.width; + ttyx->height = ttyx->typeinfo.raw_framebuffer.height; if (ttyx->mode == tty_mode_text) { ttyx->text.width = fb->width / tty_get_font()->char_width; @@ -140,6 +144,9 @@ void tty_text_print(tty *ttyx, char *string, u32 color, u32 bgcolor) { if (ttyx->enabled == false) return; + // TODO 暂时只支持framebuffer + if (ttyx->type != tty_type_raw_framebuffer) + return; if (ttyx->mode != tty_mode_text) return; if (ttyx->typeinfo.raw_framebuffer.pixtype == bgr) @@ -224,6 +231,35 @@ void tty_text_print(tty *ttyx, char *string, u32 color, u32 bgcolor) simple_lock_unlock(ttyx->text.lock); } +usize tty_get_width(tty *ttyx) +{ + if (ttyx->mode == tty_mode_text) + return ttyx->text.width; + return ttyx->width; +} + +usize tty_get_height(tty *ttyx) +{ + if (ttyx->mode == tty_mode_text) + return ttyx->text.height; + return ttyx->height; +} + +tty_type tty_get_type(tty *ttyx) +{ + return ttyx->type; +} + +tty_mode tty_get_mode(tty *ttyx) +{ + return ttyx->mode; +} + +bool tty_is_enabled(tty *ttyx) +{ + return ttyx->enabled; +} + bool tty_enable(tty *ttyx) { if (tty_ctrler.enabled[ttyx->id]) diff --git a/src/kernel/tty/tty.rs b/src/kernel/tty/tty.rs index 1f33a1a..9ab4c65 100644 --- a/src/kernel/tty/tty.rs +++ b/src/kernel/tty/tty.rs @@ -1,11 +1,19 @@ -use std::ptr::null_mut; +use std::{fmt::Debug, ptr::null_mut}; extern "C" { fn tty_new(tty_type: u8, mode: u8) -> *mut u8; fn tty_get(id: usize) -> *mut *mut u8; - pub fn tty_text_print(ttyx: *mut u8, string: *mut u8, color: u32, bgcolor: u32); + fn tty_text_print(ttyx: *mut u8, string: *mut u8, color: u32, bgcolor: u32); fn tty_get_id(tty: *mut u8) -> usize; + fn tty_get_width(tty: *mut u8) -> usize; + fn tty_get_height(tty: *mut u8) -> usize; + + fn tty_get_type(tty: *mut u8) -> u8; + fn tty_get_mode(tty: *mut u8) -> u8; + + fn tty_is_enabled(tty: *mut u8) -> bool; + fn tty_enable(tty: *mut u8) -> bool; fn tty_disable(tty: *mut u8); } @@ -17,9 +25,31 @@ pub enum Type { VirtualTerm = 3, } +impl From for Type { + fn from(value: u8) -> Self { + match value { + 1 => Type::RawFramebuffer, + 2 => Type::Display, + 3 => Type::VirtualTerm, + _ => Type::Invalid, + } + } +} + pub enum Mode { - Text = 0, - Graphics = 1, + Invalid = 0, + Text = 1, + Graphics = 2, +} + +impl From for Mode { + fn from(value: u8) -> Self { + match value { + 1 => Mode::Text, + 2 => Mode::Graphics, + _ => Mode::Invalid, + } + } } pub struct Tty { @@ -50,6 +80,29 @@ impl Tty { unsafe { tty_get_id(self.tty_pointer) } } + pub fn size(&self) -> Resolution { + unsafe { + Resolution { + width: tty_get_width(self.tty_pointer), + height: tty_get_height(self.tty_pointer), + } + } + } + + pub fn get_type(&self) -> Type { + let tp = unsafe { tty_get_type(self.tty_pointer) }; + Type::from(tp) + } + + pub fn mode(&self) -> Mode { + let mode = unsafe { tty_get_mode(self.tty_pointer) }; + Mode::from(mode) + } + + pub fn is_enabled(&self) -> bool { + unsafe { tty_is_enabled(self.tty_pointer) } + } + pub fn enable(&self) { unsafe { tty_enable(self.tty_pointer) }; } @@ -82,8 +135,45 @@ impl Tty { } } +#[derive(Clone, Copy)] pub struct Color(pub u8, pub u8, pub u8); +impl ToString for Color { + fn to_string(&self) -> String { + format!("Color({:02x}, {:02x}, {:02x})", self.0, self.1, self.2) + } +} + +impl Debug for Color { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{:02x}{:02x}{:02x}", self.0, self.1, self.2) + } +} + +pub enum ColorPair { + Reset, + Color { fore: Color, back: Color }, +} + +impl ColorPair { + pub fn reset() -> Self { + ColorPair::Reset + } + + pub fn color(fore: Color, back: Color) -> Self { + ColorPair::Color { fore, back } + } +} + +impl Debug for ColorPair { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ColorPair::Reset => write!(f, "\x1b{{}}"), + ColorPair::Color { fore, back } => write!(f, "\x1b{{{:?}{:?}}}", fore, back), + } + } +} + impl From for u32 { fn from(value: Color) -> Self { let res = (value.0 as u32) << 16 | (value.1 as u32) << 8 | (value.2 as u32); @@ -91,14 +181,79 @@ impl From for u32 { } } +pub struct Resolution { + pub width: usize, + pub height: usize, +} + +#[derive(Clone)] pub struct MessageSection { msg: String, fgcolor: Color, bgcolor: Color, } +#[derive(Clone)] pub struct Message(Vec); +impl From for Message { + fn from(value: String) -> Self { + let mut res = MessageBuilder::new(); + let mut msg = String::new(); + let mut color = ColorPair::Reset; + let mut coloring = false; + + let mut colorp_str = String::new(); + + for c in value.as_bytes() { + if *c as char == '\x1b' { + coloring = true; + res.message_mut(msg.clone()); + msg.clear(); + if let ColorPair::Color { fore, back } = color { + res.foreground_color_mut(fore); + res.background_color_mut(back); + } + continue; + } + if coloring { + if *c as char == '{' { + colorp_str.clear(); + } else if *c as char == '}' { + if colorp_str.is_empty() { + color = ColorPair::Reset; + } else { + let bts = colorp_str.as_bytes(); + let r = bts[0] << 4 + bts[1]; + let g = bts[2] << 4 + bts[3]; + let b = bts[4] << 4 + bts[5]; + let fore = Color(r, g, b); + let r = bts[6] << 4 + bts[7]; + let g = bts[8] << 4 + bts[9]; + let b = bts[10] << 4 + bts[11]; + let back = Color(r, g, b); + color = ColorPair::Color { fore, back }; + } + coloring = false; + } else { + colorp_str.push(*c as char); + } + continue; + } + msg.push(*c as char); + } + if !msg.is_empty() { + res.message_mut(msg.clone()); + msg.clear(); + if let ColorPair::Color { fore, back } = color { + res.foreground_color_mut(fore); + res.background_color_mut(back); + } + } + res.build() + } +} + pub struct MessageBuilder { msg: Message, } @@ -110,6 +265,10 @@ impl MessageBuilder { } } + pub fn from_message(msg: &Message) -> Self { + Self { msg: msg.clone() } + } + pub fn message(mut self, msg: String) -> Self { self.msg.0.push(MessageSection { msg, @@ -119,6 +278,14 @@ impl MessageBuilder { self } + pub fn message_mut(&mut self, msg: String) { + self.msg.0.push(MessageSection { + msg, + fgcolor: Color(0xee, 0xee, 0xee), + bgcolor: Color(0, 0, 0), + }); + } + pub fn background_color(mut self, color: Color) -> Self { if let Some(msg) = self.msg.0.last_mut() { msg.bgcolor = color; @@ -126,6 +293,12 @@ impl MessageBuilder { self } + pub fn background_color_mut(&mut self, color: Color) { + if let Some(msg) = self.msg.0.last_mut() { + msg.bgcolor = color; + } + } + pub fn foreground_color(mut self, color: Color) -> Self { if let Some(msg) = self.msg.0.last_mut() { msg.fgcolor = color; @@ -133,6 +306,17 @@ impl MessageBuilder { self } + pub fn foreground_color_mut(&mut self, color: Color) { + if let Some(msg) = self.msg.0.last_mut() { + msg.fgcolor = color; + } + } + + pub fn append(mut self, mut builder: Self) -> Self { + self.msg.0.append(&mut builder.msg.0); + self + } + pub fn build(self) -> Message { self.msg } -- 2.45.0 From 59ebdf8e7367e646874c6f6ee42a303e54f4d4ba Mon Sep 17 00:00:00 2001 From: pointer-to-bios Date: Wed, 24 Jan 2024 01:15:12 +0800 Subject: [PATCH 06/17] =?UTF-8?q?=E5=87=8F=E5=B0=8F=E7=94=9F=E6=88=90?= =?UTF-8?q?=E7=9A=84=E5=86=85=E6=A0=B8=E9=95=9C=E5=83=8F=E5=A4=A7=E5=B0=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Makefile | 3 ++- src/kernel/arch/x86_64/entry.s | 4 ---- src/metaverse.lds | 6 ------ 3 files changed, 2 insertions(+), 11 deletions(-) diff --git a/src/Makefile b/src/Makefile index fe78fe8..9ff80e0 100644 --- a/src/Makefile +++ b/src/Makefile @@ -33,7 +33,7 @@ ifdef release endif ifeq (${ARCH},x86_64) - RSCFLAGS := ${RSCFLAGS} -C target-feature=-sse,-avx + RSCFLAGS := ${RSCFLAGS} -C target-feature=-sse endif RUSTLIB_PATH = ../rustlib/${ARCH}/lib @@ -54,6 +54,7 @@ metaverse.elf: kernel libk rust metaverse.lds @echo -e "\e[1;33mld\e[0m \e[1;32m$@\e[0m \e[34m<--\e[0m \e[32m${SUBOBJS}\e[0m" @ld -T metaverse.lds -Map=metaverse.map -unresolved-symbols=ignore-all -o $@ ${SUBOBJS} ${RUST_LIBS} \ 2>&1 | "${SOURCE}/colorize" "warning:=yellow" "error:=red" "ld=lyellow" + @strip $@ .PHONY: kernel libk all clear postproc rust diff --git a/src/kernel/arch/x86_64/entry.s b/src/kernel/arch/x86_64/entry.s index c259f4a..04f86fd 100644 --- a/src/kernel/arch/x86_64/entry.s +++ b/src/kernel/arch/x86_64/entry.s @@ -39,10 +39,6 @@ multiboot2_header: dd 8 multiboot2_header_end: - section .kstack -kstack: - resb 0x1000000 - 0x400000 - section .kend global kend kend: diff --git a/src/metaverse.lds b/src/metaverse.lds index c1e7568..3ef868d 100644 --- a/src/metaverse.lds +++ b/src/metaverse.lds @@ -17,12 +17,6 @@ SECTIONS { { *(.cpumeta) } - . = 4M; - ..kstack : - { - kstack = .; - *(.kstack) - } . = 16M; .text : { -- 2.45.0 From 6d24ee84f407eddbc5506fe52098f0f35411b069 Mon Sep 17 00:00:00 2001 From: pointer-to-bios Date: Wed, 24 Jan 2024 02:31:17 +0800 Subject: [PATCH 07/17] =?UTF-8?q?rust=E4=B8=8D=E4=BD=BF=E7=94=A8=E6=A0=87?= =?UTF-8?q?=E5=87=86=E5=BA=93=EF=BC=8C=E5=8F=AA=E4=BD=BF=E7=94=A8core?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rustlib | 2 +- src/Makefile | 12 ++---------- src/kernel/clock/time.rs | 13 +++++++------ src/kernel/klog.rs | 6 +++++- src/kernel/sync/rwlock.rs | 17 ++++++++--------- src/kernel/tty/tty.rs | 27 +++++++++++++++------------ src/lib.rs | 4 +++- 7 files changed, 41 insertions(+), 40 deletions(-) diff --git a/rustlib b/rustlib index 0d9cd08..a7d79f8 160000 --- a/rustlib +++ b/rustlib @@ -1 +1 @@ -Subproject commit 0d9cd0822c355e784c6f4ff5ac2fd88f6d917ea7 +Subproject commit a7d79f8d3d865c93dad38796530e6a4dc53a0377 diff --git a/src/Makefile b/src/Makefile index 9ff80e0..6ea2cf8 100644 --- a/src/Makefile +++ b/src/Makefile @@ -37,16 +37,8 @@ ifeq (${ARCH},x86_64) endif RUSTLIB_PATH = ../rustlib/${ARCH}/lib -RUST_LIBS = "${RUSTLIB_PATH}/libaddr2line.rlib" "${RUSTLIB_PATH}/libadler.rlib" \ - "${RUSTLIB_PATH}/liballoc.rlib" "${RUSTLIB_PATH}/libcfg_if.rlib" "${RUSTLIB_PATH}/libcompiler_builtins.rlib" \ - "${RUSTLIB_PATH}/libcore.rlib" "${RUSTLIB_PATH}/libgetopts.rlib" "${RUSTLIB_PATH}/libgimli.rlib" \ - "${RUSTLIB_PATH}/libhashbrown.rlib" "${RUSTLIB_PATH}/libmemchr.rlib" "${RUSTLIB_PATH}/libminiz_oxide.rlib" \ - "${RUSTLIB_PATH}/libobject.rlib" "${RUSTLIB_PATH}/libpanic_abort.rlib" "${RUSTLIB_PATH}/libpanic_unwind.rlib" \ - "${RUSTLIB_PATH}/libproc_macro.rlib" "${RUSTLIB_PATH}/libprofiler_builtins.rlib" \ - "${RUSTLIB_PATH}/librustc_demangle.rlib" "${RUSTLIB_PATH}/librustc_std_workspace_alloc.rlib" \ - "${RUSTLIB_PATH}/librustc_std_workspace_core.rlib" "${RUSTLIB_PATH}/librustc_std_workspace_std.rlib" \ - "${RUSTLIB_PATH}/libstd_detect.rlib" "${RUSTLIB_PATH}/libstd.rlib" "${RUSTLIB_PATH}/libsysroot.rlib" \ - "${RUSTLIB_PATH}/libtest.rlib" "${RUSTLIB_PATH}/libunicode_width.rlib" "${RUSTLIB_PATH}/libunwind.rlib" +RUST_LIBS = "${RUSTLIB_PATH}/liballoc.rlib" "${RUSTLIB_PATH}/libcompiler_builtins.rlib" \ + "${RUSTLIB_PATH}/libcore.rlib" "${RUSTLIB_PATH}/librustc_std_workspace_core.rlib" ################################ diff --git a/src/kernel/clock/time.rs b/src/kernel/clock/time.rs index b0b0e66..7f56363 100644 --- a/src/kernel/clock/time.rs +++ b/src/kernel/clock/time.rs @@ -1,4 +1,6 @@ -use std::{cmp::Ordering, fmt::Debug, ops::Sub, time::Duration}; +use core::{cmp::Ordering, ops::Sub, time::Duration}; + +use alloc::{format, string::ToString}; extern "C" { fn system_time_get() -> usize; @@ -14,8 +16,8 @@ pub struct SystemTime { ns_time: usize, } -impl Debug for SystemTime { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +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; @@ -93,8 +95,7 @@ impl Debug for SystemTime { minute /= minute_dur; let milisec = second % second_dur; second /= second_dur; - write!( - f, + format!( "[{:02}-{:02}-{:02} {:02}:{:02}:{:02}.{:03}]", year, month, day, hour, minute, second, milisec ) @@ -118,7 +119,7 @@ impl Ord for SystemTime { } impl PartialOrd for SystemTime { - fn partial_cmp(&self, other: &Self) -> Option { + fn partial_cmp(&self, other: &Self) -> Option { match self.unix_time.partial_cmp(&other.unix_time) { Some(Ordering::Equal) => self.ns_time.partial_cmp(&other.ns_time), ord => ord, diff --git a/src/kernel/klog.rs b/src/kernel/klog.rs index 41e4f23..3e157fb 100644 --- a/src/kernel/klog.rs +++ b/src/kernel/klog.rs @@ -1,3 +1,7 @@ +use alloc::string::ToString; +use alloc::{format, vec::Vec}; +use alloc::vec; + use super::{ clock::time::SystemTime, tty::tty::{Color, Message, MessageBuilder}, @@ -149,7 +153,7 @@ impl Iterator for LogIterator { if let Some((time, msg)) = self.logs.first() { Some( MessageBuilder::new() - .message(format!("{:?}", time)) + .message(format!("{}", time.to_string())) .append(MessageBuilder::from_message(msg)) .build(), ) diff --git a/src/kernel/sync/rwlock.rs b/src/kernel/sync/rwlock.rs index be7a430..76d2f36 100644 --- a/src/kernel/sync/rwlock.rs +++ b/src/kernel/sync/rwlock.rs @@ -1,19 +1,18 @@ -use std::{ - ops::{Deref, DerefMut}, - ptr::null_mut, -}; +use core::{ops::{Deref, DerefMut}, ptr::null_mut}; + +use alloc::{vec, vec::Vec}; /// ## RwLock /// 读写锁 -/// +/// /// * 对于写入操作: -/// +/// /// 锁没有占用时,获取锁,并执行闭包。 -/// +/// /// 当锁已经被占用,将闭包悬挂。 -/// +/// /// 释放锁时,将所有悬挂的闭包都执行。 -/// +/// /// 正在释放锁时,`write`方法返回`Err(())` /// /// ``` diff --git a/src/kernel/tty/tty.rs b/src/kernel/tty/tty.rs index 9ab4c65..5cb1011 100644 --- a/src/kernel/tty/tty.rs +++ b/src/kernel/tty/tty.rs @@ -1,4 +1,11 @@ -use std::{fmt::Debug, ptr::null_mut}; +use core::ptr::null_mut; + +use alloc::{ + format, + string::{String, ToString}, + vec, + vec::Vec, +}; extern "C" { fn tty_new(tty_type: u8, mode: u8) -> *mut u8; @@ -140,13 +147,7 @@ pub struct Color(pub u8, pub u8, pub u8); impl ToString for Color { fn to_string(&self) -> String { - format!("Color({:02x}, {:02x}, {:02x})", self.0, self.1, self.2) - } -} - -impl Debug for Color { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:02x}{:02x}{:02x}", self.0, self.1, self.2) + format!("{:02x}{:02x}{:02x}", self.0, self.1, self.2) } } @@ -165,11 +166,13 @@ impl ColorPair { } } -impl Debug for ColorPair { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl ToString for ColorPair { + fn to_string(&self) -> String { match self { - ColorPair::Reset => write!(f, "\x1b{{}}"), - ColorPair::Color { fore, back } => write!(f, "\x1b{{{:?}{:?}}}", fore, back), + ColorPair::Reset => format!("\x1b{{}}"), + ColorPair::Color { fore, back } => { + format!("\x1b{{{}{}}}", fore.to_string(), back.to_string()) + } } } } diff --git a/src/lib.rs b/src/lib.rs index be290dc..9f726b0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,6 @@ -extern crate core; +#![no_std] + +extern crate alloc; pub mod kernel; pub mod libk; -- 2.45.0 From 85df2a7609d28e442ba1bbd01df99bee224df3f9 Mon Sep 17 00:00:00 2001 From: pointer-to-bios Date: Wed, 31 Jan 2024 21:11:19 +0800 Subject: [PATCH 08/17] =?UTF-8?q?=E4=BF=AE=E5=A4=8Draw=5Fallocator?= =?UTF-8?q?=E5=9C=A8=E6=9F=90=E4=BA=9B=E6=97=B6=E5=80=99=E6=AD=BB=E5=BE=AA?= =?UTF-8?q?=E7=8E=AF=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/kernel/memm/allocator/raw.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/kernel/memm/allocator/raw.c b/src/kernel/memm/allocator/raw.c index 79ed4e8..ce158de 100644 --- a/src/kernel/memm/allocator/raw.c +++ b/src/kernel/memm/allocator/raw.c @@ -17,17 +17,19 @@ void *raw_allocator_allocate(raw_allocator_t *allocator, usize size, usize align { usize real_size = size; align_to(real_size, 16); - raw_allocator_cell *cell = allocator->cells; - while ((void *)raw_allocator_next_cell(cell) < (void *)allocator + allocator->size) + raw_allocator_cell *cell = &allocator->cells; + while ((void *)cell < raw_allocator_end(allocator)) { while ( // 确保cell指向的内容还在这个allocator内 - (void *)raw_allocator_next_cell(cell) < raw_allocator_end(allocator) && + (void *)cell < raw_allocator_end(allocator) && cell->length != 0) { cell = raw_allocator_next_cell(cell); } if (real_size <= cell->capacity) break; + else + cell = raw_allocator_next_cell(cell); } if ((void *)cell < raw_allocator_end(allocator)) goto fitable_cell_finded; -- 2.45.0 From d931f612f809e56af3a07f78367b8b7bdd615f25 Mon Sep 17 00:00:00 2001 From: pointer-to-bios Date: Thu, 1 Feb 2024 01:40:51 +0800 Subject: [PATCH 09/17] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=86=85=E6=A0=B8?= =?UTF-8?q?=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Makefile | 1 - src/kernel/clock/time.rs | 6 +- src/kernel/klog.rs | 152 ++++++++++++++++++++-------------- src/kernel/main.rs | 20 +++-- src/kernel/tty/font.c | 2 +- src/kernel/tty/mod.rs | 45 ++++++++++ src/kernel/tty/tty.rs | 136 +++++++++--------------------- src/libk/mod.rs | 1 + src/libk/string/format/mod.rs | 38 +++++++++ src/libk/string/mod.rs | 1 + 10 files changed, 233 insertions(+), 169 deletions(-) create mode 100644 src/libk/string/format/mod.rs create mode 100644 src/libk/string/mod.rs diff --git a/src/Makefile b/src/Makefile index 6ea2cf8..3957d4b 100644 --- a/src/Makefile +++ b/src/Makefile @@ -46,7 +46,6 @@ metaverse.elf: kernel libk rust metaverse.lds @echo -e "\e[1;33mld\e[0m \e[1;32m$@\e[0m \e[34m<--\e[0m \e[32m${SUBOBJS}\e[0m" @ld -T metaverse.lds -Map=metaverse.map -unresolved-symbols=ignore-all -o $@ ${SUBOBJS} ${RUST_LIBS} \ 2>&1 | "${SOURCE}/colorize" "warning:=yellow" "error:=red" "ld=lyellow" - @strip $@ .PHONY: kernel libk all clear postproc rust diff --git a/src/kernel/clock/time.rs b/src/kernel/clock/time.rs index 7f56363..29f86bd 100644 --- a/src/kernel/clock/time.rs +++ b/src/kernel/clock/time.rs @@ -1,6 +1,8 @@ use core::{cmp::Ordering, ops::Sub, time::Duration}; -use alloc::{format, string::ToString}; +use alloc::string::ToString; + +use crate::format; extern "C" { fn system_time_get() -> usize; @@ -96,7 +98,7 @@ impl ToString for SystemTime { let milisec = second % second_dur; second /= second_dur; format!( - "[{:02}-{:02}-{:02} {:02}:{:02}:{:02}.{:03}]", + "[ {}-{}-{} {}:{}:{}.{} ]", year, month, day, hour, minute, second, milisec ) } diff --git a/src/kernel/klog.rs b/src/kernel/klog.rs index 3e157fb..8cc5416 100644 --- a/src/kernel/klog.rs +++ b/src/kernel/klog.rs @@ -1,6 +1,6 @@ use alloc::string::ToString; -use alloc::{format, vec::Vec}; use alloc::vec; +use alloc::vec::Vec; use super::{ clock::time::SystemTime, @@ -40,125 +40,157 @@ impl KernelLogger { pub fn fatal(&mut self, msg: Message) { let msg = MessageBuilder::new() - .message("Fatal: ".to_string()) + .message("Fatal: ") .foreground_color(Color(0xee, 0xa, 0xa)) - .append(MessageBuilder::from_message(&msg)) + .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: ".to_string()) + .message("Error: ") .foreground_color(Color(0xaa, 0x22, 0x22)) - .append(MessageBuilder::from_message(&msg)) + .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: ".to_string()) + .message("Warning: ") .foreground_color(Color(0xaa, 0xa, 0xaa)) - .append(MessageBuilder::from_message(&msg)) + .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: ".to_string()) + .message("Info: ") .foreground_color(Color(0xa, 0xee, 0xa)) - .append(MessageBuilder::from_message(&msg)) + .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: ".to_string()) + .message("Debug: ") .foreground_color(Color(0xee, 0xee, 0xee)) - .append(MessageBuilder::from_message(&msg)) + .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: ".to_string()) + .message("Trace: ") .foreground_color(Color(0xee, 0xee, 0xee)) - .append(MessageBuilder::from_message(&msg)) + .append(MessageBuilder::from_message(msg)) .build(); self.trace_queue.push((SystemTime::now(), msg)); } pub fn iter(&self, level: LoggerLevel) -> LogIterator { let mut logs = vec![]; - if level == LoggerLevel::Fatal { - logs.push(&self.fatal_queue); - } - if level == LoggerLevel::Fatal || level == LoggerLevel::Error { - logs.push(&self.error_queue); - } - if level == LoggerLevel::Fatal - || level == LoggerLevel::Error - || level == LoggerLevel::Warning - { - logs.push(&self.warning_queue); - } - if level == LoggerLevel::Fatal - || level == LoggerLevel::Error - || level == LoggerLevel::Warning - || level == LoggerLevel::Info - { - logs.push(&self.info_queue); - } - if level == LoggerLevel::Fatal - || level == LoggerLevel::Error - || level == LoggerLevel::Warning - || level == LoggerLevel::Info - || level == LoggerLevel::Debug - { - logs.push(&self.debug_queue); - } - if level == LoggerLevel::Fatal - || level == LoggerLevel::Error - || level == LoggerLevel::Warning - || level == LoggerLevel::Info - || level == LoggerLevel::Debug - || level == LoggerLevel::Trace - { - logs.push(&self.trace_queue); + match level { + LoggerLevel::Fatal => { + logs.push(&self.fatal_queue); + } + LoggerLevel::Error => { + logs.push(&self.fatal_queue); + logs.push(&self.error_queue); + } + LoggerLevel::Warning => { + logs.push(&self.fatal_queue); + logs.push(&self.error_queue); + logs.push(&self.warning_queue); + } + LoggerLevel::Info => { + logs.push(&self.fatal_queue); + logs.push(&self.error_queue); + logs.push(&self.warning_queue); + logs.push(&self.info_queue); + } + LoggerLevel::Debug => { + logs.push(&self.fatal_queue); + logs.push(&self.error_queue); + logs.push(&self.warning_queue); + logs.push(&self.info_queue); + logs.push(&self.debug_queue); + } + LoggerLevel::Trace => { + logs.push(&self.fatal_queue); + logs.push(&self.error_queue); + logs.push(&self.warning_queue); + logs.push(&self.info_queue); + logs.push(&self.debug_queue); + logs.push(&self.trace_queue); + } } let mut res = vec![]; - while let Some(msg) = { - logs.iter_mut() - .filter_map(|&mut l| l.first().cloned()) - .min_by_key(|&(syst, _)| syst) - } { - res.push(msg); + let mut indeces = Vec::new(); + for _ in 0..logs.len() { + indeces.push(0usize); + } + let all_end = |indeces: &Vec, logs: &Vec<&Vec<(SystemTime, Message)>>| { + for i in 0..indeces.len() { + if indeces[i] < logs.len() { + return false; + } + } + return true; + }; + while !all_end(&indeces, &logs) { + let mut min_ind = None; + let mut min = None; + for i in 0..indeces.len() { + if indeces[i] >= logs[i].len() { + continue; + } + if let Some(minx) = min.as_mut() { + if logs[i][indeces[i]].0 < *minx { + *minx = logs[i][indeces[i]].0; + min_ind = Some(i); + } + } else { + min = Some(logs[i][indeces[i]].0); + min_ind = Some(i); + } + } + if let Some(mini) = min_ind { + res.push(&logs[mini][indeces[mini]]); + indeces[mini] += 1; + } else { + break; + } } LogIterator { logs: res } } } -pub struct LogIterator { - logs: Vec<(SystemTime, Message)>, +pub struct LogIterator<'a> { + logs: Vec<&'a (SystemTime, Message)>, } -impl Iterator for LogIterator { +impl<'a> Iterator for LogIterator<'a> { type Item = Message; fn next(&mut self) -> Option { - if let Some((time, msg)) = self.logs.first() { + let res = if let Some((time, msg)) = self.logs.first() { Some( MessageBuilder::new() - .message(format!("{}", time.to_string())) - .append(MessageBuilder::from_message(msg)) + .message(&time.to_string()) + .append(MessageBuilder::from_message(msg.clone())) .build(), ) } else { None + }; + if let Some(_) = res { + self.logs.remove(0); } + res } } diff --git a/src/kernel/main.rs b/src/kernel/main.rs index 5d0373a..aa74b88 100644 --- a/src/kernel/main.rs +++ b/src/kernel/main.rs @@ -1,17 +1,21 @@ +use crate::message; + use super::{ klog::{KernelLogger, LoggerLevel}, - tty::tty::{Color, ColorPair, Message, Tty}, + tty::tty::{BuilderFunctions::*, Color, Tty}, }; #[no_mangle] -extern "C" fn kmain_rust() { - let mut logger = KernelLogger::new(); - logger.info(Message::from(format!( - "Hello, {:?}Metaverse{:?}!", - ColorPair::color(Color(0xa, 0xee, 0xa), Color(0, 0, 0)), - ColorPair::Reset - ))); +extern "C" fn kmain_rust() -> ! { let tty = Tty::from_id(0).unwrap(); + tty.enable(); + let mut logger = KernelLogger::new(); + logger.info(message!( + Msg("Hello, "), + Msg("Metaverse"), + FgColor(Color(0xa, 0xee, 0xa)), + Msg("!\n") + )); for msg in logger.iter(LoggerLevel::Info) { tty.print(msg); } diff --git a/src/kernel/tty/font.c b/src/kernel/tty/font.c index 684fc32..57d78f5 100644 --- a/src/kernel/tty/font.c +++ b/src/kernel/tty/font.c @@ -405,7 +405,7 @@ u64 font[256][64] = { 0b00000000, 0b00011000, /// 0b00101000, - 0b01001000, + 0b00001000, 0b00001000, 0b00001000, 0b00001000, diff --git a/src/kernel/tty/mod.rs b/src/kernel/tty/mod.rs index cd8fd47..ed058fa 100644 --- a/src/kernel/tty/mod.rs +++ b/src/kernel/tty/mod.rs @@ -1 +1,46 @@ pub mod tty; + +#[macro_export] +macro_rules! message_msg { + () => {}; + ( $builder : expr, $e : expr) => { + $builder.message_mut($e); + }; +} + +#[macro_export] +macro_rules! message_fgc { + () => {}; + ( $builder : expr, $e : expr) => { + $builder.foreground_color_mut($e); + }; +} + +#[macro_export] +macro_rules! message_bgc { + () => {}; + ( $builder : expr, $e : expr ) => { + $builder.background_color_mut($e); + }; +} + +#[macro_export] +macro_rules! message { + ( $( $e : expr ),* ) => {{ + use crate::{ + kernel::tty::tty::{MessageBuilder, BuilderFunctions}, + message_msg, message_fgc, message_bgc + }; + let mut tmp_builder = MessageBuilder::new(); + $( + if let BuilderFunctions::Msg(e) = $e { + message_msg!(tmp_builder, e); + } else if let BuilderFunctions::FgColor(c) = $e { + message_fgc!(tmp_builder, c); + } else if let BuilderFunctions::BgColor(c) = $e { + message_bgc!(tmp_builder, c); + } + )* + tmp_builder.build() + }}; +} diff --git a/src/kernel/tty/tty.rs b/src/kernel/tty/tty.rs index 5cb1011..38922ee 100644 --- a/src/kernel/tty/tty.rs +++ b/src/kernel/tty/tty.rs @@ -1,7 +1,6 @@ use core::ptr::null_mut; use alloc::{ - format, string::{String, ToString}, vec, vec::Vec, @@ -145,38 +144,6 @@ impl Tty { #[derive(Clone, Copy)] pub struct Color(pub u8, pub u8, pub u8); -impl ToString for Color { - fn to_string(&self) -> String { - format!("{:02x}{:02x}{:02x}", self.0, self.1, self.2) - } -} - -pub enum ColorPair { - Reset, - Color { fore: Color, back: Color }, -} - -impl ColorPair { - pub fn reset() -> Self { - ColorPair::Reset - } - - pub fn color(fore: Color, back: Color) -> Self { - ColorPair::Color { fore, back } - } -} - -impl ToString for ColorPair { - fn to_string(&self) -> String { - match self { - ColorPair::Reset => format!("\x1b{{}}"), - ColorPair::Color { fore, back } => { - format!("\x1b{{{}{}}}", fore.to_string(), back.to_string()) - } - } - } -} - impl From for u32 { fn from(value: Color) -> Self { let res = (value.0 as u32) << 16 | (value.1 as u32) << 8 | (value.2 as u32); @@ -196,71 +163,46 @@ pub struct MessageSection { bgcolor: Color, } +/// ## Message +/// +/// 用`MessageBuilder`构造一个`Message`对象 #[derive(Clone)] pub struct Message(Vec); -impl From for Message { - fn from(value: String) -> Self { - let mut res = MessageBuilder::new(); - let mut msg = String::new(); - let mut color = ColorPair::Reset; - let mut coloring = false; - - let mut colorp_str = String::new(); - - for c in value.as_bytes() { - if *c as char == '\x1b' { - coloring = true; - res.message_mut(msg.clone()); - msg.clear(); - if let ColorPair::Color { fore, back } = color { - res.foreground_color_mut(fore); - res.background_color_mut(back); - } - continue; - } - if coloring { - if *c as char == '{' { - colorp_str.clear(); - } else if *c as char == '}' { - if colorp_str.is_empty() { - color = ColorPair::Reset; - } else { - let bts = colorp_str.as_bytes(); - let r = bts[0] << 4 + bts[1]; - let g = bts[2] << 4 + bts[3]; - let b = bts[4] << 4 + bts[5]; - let fore = Color(r, g, b); - let r = bts[6] << 4 + bts[7]; - let g = bts[8] << 4 + bts[9]; - let b = bts[10] << 4 + bts[11]; - let back = Color(r, g, b); - color = ColorPair::Color { fore, back }; - } - coloring = false; - } else { - colorp_str.push(*c as char); - } - continue; - } - msg.push(*c as char); - } - if !msg.is_empty() { - res.message_mut(msg.clone()); - msg.clear(); - if let ColorPair::Color { fore, back } = color { - res.foreground_color_mut(fore); - res.background_color_mut(back); - } - } - res.build() - } -} - +/// ## MessageBuilder +/// +/// 使用链式调用模式构造一个消息. +/// +/// 一个`Message`包含多个`MessageSection`,每个`MessageSection`以`message()`调用开始, +/// `message()`调用后可接0个或多个属性设置。 +/// +/// ```rust +/// MessageBuilder::new() +/// .message("Hello, ") +/// .message("Metaverse").foreground_color(Color(0xa, 0xee, 0xa)) +/// .message("!\n") +/// .build(); +/// ``` +/// +/// 对于特殊情况可以使用非链式调用: +/// ```rust +/// let mut msg = MessageBuilder::new(); +/// msg.message_mut("Hello, "); +/// msg.message_mut("Metaverse"); +/// msg.foreground_color(Color(0xa, 0xee, 0xa)); +/// msg.message_mut("!\n"); +/// let msg = msg.build(); +/// ``` pub struct MessageBuilder { msg: Message, } +pub enum BuilderFunctions<'a> { + Msg(&'a str), + FgColor(Color), + BgColor(Color), +} + impl MessageBuilder { pub fn new() -> Self { Self { @@ -268,22 +210,22 @@ impl MessageBuilder { } } - pub fn from_message(msg: &Message) -> Self { - Self { msg: msg.clone() } + pub fn from_message(msg: Message) -> Self { + Self { msg } } - pub fn message(mut self, msg: String) -> Self { + pub fn message(mut self, msg: &str) -> Self { self.msg.0.push(MessageSection { - msg, + msg: msg.to_string(), fgcolor: Color(0xee, 0xee, 0xee), bgcolor: Color(0, 0, 0), }); self } - pub fn message_mut(&mut self, msg: String) { + pub fn message_mut(&mut self, msg: &str) { self.msg.0.push(MessageSection { - msg, + msg: msg.to_string(), fgcolor: Color(0xee, 0xee, 0xee), bgcolor: Color(0, 0, 0), }); diff --git a/src/libk/mod.rs b/src/libk/mod.rs index e69de29..d245b85 100644 --- a/src/libk/mod.rs +++ b/src/libk/mod.rs @@ -0,0 +1 @@ +pub mod string; diff --git a/src/libk/string/format/mod.rs b/src/libk/string/format/mod.rs new file mode 100644 index 0000000..8d63056 --- /dev/null +++ b/src/libk/string/format/mod.rs @@ -0,0 +1,38 @@ +use alloc::string::{String, ToString}; + +#[macro_export] +macro_rules! format { + ( $s : expr, $( $e : expr ),* ) => {{ + use crate::libk::string::format::Format; + let mut res = $s.to_string(); + $( + res.format($e); + )* + res + }}; + () => {}; +} + +pub trait Format { + fn format(&mut self, f: T); +} + +impl Format for String { + fn format(&mut self, f: T) { + let mut res = String::new(); + let mut formatting = false; + for c in self.chars().into_iter() { + if c == '{' { + formatting = true; + res += &f.to_string(); + } else if c == '}' { + formatting = false; + } + if !formatting { + res.push(c); + } + } + self.clear(); + self.push_str(&res); + } +} diff --git a/src/libk/string/mod.rs b/src/libk/string/mod.rs new file mode 100644 index 0000000..db7b59d --- /dev/null +++ b/src/libk/string/mod.rs @@ -0,0 +1 @@ +pub mod format; -- 2.45.0 From 4eec22a71eabf2106a931b5bdc1654b3ad5360ac Mon Sep 17 00:00:00 2001 From: pointer-to-bios Date: Fri, 2 Feb 2024 13:58:37 +0800 Subject: [PATCH 10/17] =?UTF-8?q?=E4=BF=AE=E6=AD=A3submodule=E6=8C=87?= =?UTF-8?q?=E5=90=91=E7=9A=84repo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitmodules | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitmodules b/.gitmodules index b970cd8..3712af8 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,3 @@ [submodule "rustlib"] path = rustlib - url = http://git.suthby.org:2024/metaverse/kernel-release.git + url = http://git.suthby.org:2024/metaverse/rustenv -- 2.45.0 From 2b2dc2d5bc4ad8ab52e28e773910cf8121cf7cfa Mon Sep 17 00:00:00 2001 From: pointer-to-bios Date: Sun, 4 Feb 2024 02:55:56 +0800 Subject: [PATCH 11/17] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E9=A2=9C=E8=89=B2?= =?UTF-8?q?=E5=B8=B8=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/kernel/klog.rs | 12 ++++++------ src/kernel/main.rs | 2 +- src/kernel/tty/tty.rs | 34 +++++++++++++++++++++++----------- 3 files changed, 30 insertions(+), 18 deletions(-) diff --git a/src/kernel/klog.rs b/src/kernel/klog.rs index 8cc5416..756d84d 100644 --- a/src/kernel/klog.rs +++ b/src/kernel/klog.rs @@ -41,7 +41,7 @@ impl KernelLogger { pub fn fatal(&mut self, msg: Message) { let msg = MessageBuilder::new() .message("Fatal: ") - .foreground_color(Color(0xee, 0xa, 0xa)) + .foreground_color(Color::RED) .append(MessageBuilder::from_message(msg)) .build(); self.fatal_queue.push((SystemTime::now(), msg)); @@ -50,7 +50,7 @@ impl KernelLogger { pub fn error(&mut self, msg: Message) { let msg = MessageBuilder::new() .message("Error: ") - .foreground_color(Color(0xaa, 0x22, 0x22)) + .foreground_color(Color::ORANGE) .append(MessageBuilder::from_message(msg)) .build(); self.error_queue.push((SystemTime::now(), msg)); @@ -59,7 +59,7 @@ impl KernelLogger { pub fn warning(&mut self, msg: Message) { let msg = MessageBuilder::new() .message("Warning: ") - .foreground_color(Color(0xaa, 0xa, 0xaa)) + .foreground_color(Color::PURPLE) .append(MessageBuilder::from_message(msg)) .build(); self.warning_queue.push((SystemTime::now(), msg)); @@ -68,7 +68,7 @@ impl KernelLogger { pub fn info(&mut self, msg: Message) { let msg = MessageBuilder::new() .message("Info: ") - .foreground_color(Color(0xa, 0xee, 0xa)) + .foreground_color(Color::GREEN) .append(MessageBuilder::from_message(msg)) .build(); self.info_queue.push((SystemTime::now(), msg)); @@ -77,7 +77,7 @@ impl KernelLogger { pub fn debug(&mut self, msg: Message) { let msg = MessageBuilder::new() .message("Debug: ") - .foreground_color(Color(0xee, 0xee, 0xee)) + .foreground_color(Color::WHITE) .append(MessageBuilder::from_message(msg)) .build(); self.debug_queue.push((SystemTime::now(), msg)); @@ -86,7 +86,7 @@ impl KernelLogger { pub fn trace(&mut self, msg: Message) { let msg = MessageBuilder::new() .message("Trace: ") - .foreground_color(Color(0xee, 0xee, 0xee)) + .foreground_color(Color::WHITE) .append(MessageBuilder::from_message(msg)) .build(); self.trace_queue.push((SystemTime::now(), msg)); diff --git a/src/kernel/main.rs b/src/kernel/main.rs index aa74b88..d50d8b1 100644 --- a/src/kernel/main.rs +++ b/src/kernel/main.rs @@ -13,7 +13,7 @@ extern "C" fn kmain_rust() -> ! { logger.info(message!( Msg("Hello, "), Msg("Metaverse"), - FgColor(Color(0xa, 0xee, 0xa)), + FgColor(Color::GREEN), Msg("!\n") )); for msg in logger.iter(LoggerLevel::Info) { diff --git a/src/kernel/tty/tty.rs b/src/kernel/tty/tty.rs index 38922ee..50b1470 100644 --- a/src/kernel/tty/tty.rs +++ b/src/kernel/tty/tty.rs @@ -7,21 +7,21 @@ use alloc::{ }; extern "C" { - fn tty_new(tty_type: u8, mode: u8) -> *mut u8; - fn tty_get(id: usize) -> *mut *mut u8; - fn tty_text_print(ttyx: *mut u8, string: *mut u8, color: u32, bgcolor: u32); - fn tty_get_id(tty: *mut u8) -> usize; + pub fn tty_new(tty_type: u8, mode: u8) -> *mut u8; + pub fn tty_get(id: usize) -> *mut *mut u8; + pub fn tty_text_print(ttyx: *mut u8, string: *mut u8, color: u32, bgcolor: u32); + pub fn tty_get_id(tty: *mut u8) -> usize; - fn tty_get_width(tty: *mut u8) -> usize; - fn tty_get_height(tty: *mut u8) -> usize; + pub fn tty_get_width(tty: *mut u8) -> usize; + pub fn tty_get_height(tty: *mut u8) -> usize; - fn tty_get_type(tty: *mut u8) -> u8; - fn tty_get_mode(tty: *mut u8) -> u8; + pub fn tty_get_type(tty: *mut u8) -> u8; + pub fn tty_get_mode(tty: *mut u8) -> u8; - fn tty_is_enabled(tty: *mut u8) -> bool; + pub fn tty_is_enabled(tty: *mut u8) -> bool; - fn tty_enable(tty: *mut u8) -> bool; - fn tty_disable(tty: *mut u8); + pub fn tty_enable(tty: *mut u8) -> bool; + pub fn tty_disable(tty: *mut u8); } pub enum Type { @@ -144,6 +144,18 @@ impl Tty { #[derive(Clone, Copy)] pub struct Color(pub u8, pub u8, pub u8); +impl Color { + pub const WHITE: Color = Color(0xee, 0xee, 0xee); + pub const BLACK: Color = Color(0, 0, 0); + pub const RED: Color = Color(0xee, 0x22, 0x22); + pub const GREEN: Color = Color(0x22, 0xee, 0x22); + pub const BLUE: Color = Color(0x22, 0x22, 0xee); + pub const YELLOW: Color = Color(0xee, 0x22, 0x22); + pub const ORANGE: Color = Color(0xee, 0xee, 0x22); + pub const PURPLE: Color = Color(0xee, 0, 0xee); + pub const PINK: Color = Color(0xee, 0x44, 0x66); +} + impl From for u32 { fn from(value: Color) -> Self { let res = (value.0 as u32) << 16 | (value.1 as u32) << 8 | (value.2 as u32); -- 2.45.0 From e5ddfed1fbc791a3af0187fc475438944d64b16b Mon Sep 17 00:00:00 2001 From: pointer-to-bios Date: Sun, 4 Feb 2024 02:58:09 +0800 Subject: [PATCH 12/17] =?UTF-8?q?=E6=9B=B4=E6=94=B9=E7=9B=AE=E6=A0=87?= =?UTF-8?q?=E7=B1=BB=E5=9E=8B=E4=B8=BAnone=E4=BB=A5=E7=94=9F=E6=88=90?= =?UTF-8?q?=E4=B8=8D=E4=BE=9D=E8=B5=96=E4=BB=BB=E4=BD=95=E5=B9=B3=E5=8F=B0?= =?UTF-8?q?=E7=9A=84=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.toml | 15 +++++++++++++++ rustlib | 2 +- src/Makefile | 8 +++++++- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index cef59e4..f89fb5e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,3 +2,18 @@ name = "metaverse" version = "0.1.0" edition = "2021" + +# 此Cargo.toml仅用于rust-analyzer识别rust部分的代码 +# 不应使用cargo编译 + +[build] +type = "staticlib" +rustflags = [ + "-C", "embed-bitcode=no", + "-C", "code-model=large", + "-C", "relocation-model=static", + "-L", "crate=${PWD}/../rustlib/${ARCH}/src/" +] + +[target.'cfg(target_arch = "x86_64")'] +target = "x86_64-unknown-none" diff --git a/rustlib b/rustlib index a7d79f8..087c479 160000 --- a/rustlib +++ b/rustlib @@ -1 +1 @@ -Subproject commit a7d79f8d3d865c93dad38796530e6a4dc53a0377 +Subproject commit 087c4795bbc23cd0baee060bda8c1159a971a542 diff --git a/src/Makefile b/src/Makefile index 3957d4b..7ccfc6c 100644 --- a/src/Makefile +++ b/src/Makefile @@ -22,12 +22,18 @@ endif ################################ # rust语言环境变量 -RSCFLAGS = --emit obj --crate-type lib \ +RSCFLAGS = --emit obj --crate-type staticlib --verbose \ + --crate-name=metaverse \ + --edition 2021 \ -L crate="${PWD}/../rustlib/${ARCH}/src/" \ -C code-model=large \ -C relocation-model=static \ -C embed-bitcode=no +ifeq (${ARCH},x86_64) + RSCFLAGS := ${RSCFLAGS} --target x86_64-unknown-none +endif + ifdef release RSCFLAGS := -O endif -- 2.45.0 From 024b24e5efa3b74e835016e29f1566810093d298 Mon Sep 17 00:00:00 2001 From: pointer-to-bios Date: Sun, 4 Feb 2024 02:58:45 +0800 Subject: [PATCH 13/17] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=86=85=E6=A0=B8?= =?UTF-8?q?=E7=9A=84panic=20handler?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/lib.rs | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 9f726b0..6166204 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,5 +2,68 @@ extern crate alloc; +use alloc::{ + string::{String, ToString}, + vec::Vec, +}; +use core::{panic::PanicInfo, ptr::null_mut}; + +use kernel::tty::tty::{self, tty_enable, tty_text_print, Color}; + pub mod kernel; pub mod libk; + +#[panic_handler] +unsafe fn kernel_panic_handler(info: &PanicInfo) -> ! { + let line_in_file = if let Some(loca) = info.location() { + loca.line().to_string() + } else { + String::new() + }; + let info = { + let mut v = Vec::new(); + v.push(("Kernel Panic: ", (Color::RED, Color::BLACK))); + v.push(( + if let Some(loca) = info.location() { + loca.file() + } else { + "NoFile" + }, + (Color::GREEN, Color::BLACK), + )); + v.push((":", (Color::WHITE, Color::BLACK))); + v.push(( + if let Some(_) = info.location() { + line_in_file.as_str() + } else { + "NoLine" + }, + (Color::WHITE, Color::BLACK), + )); + v.push((": ", (Color::WHITE, Color::BLACK))); + v.push(( + if let Some(&s) = info.payload().downcast_ref::<&str>() { + s + } else { + "Unknown panic." + }, + (Color::GREEN, Color::BLACK), + )); + v.push(("\n", (Color::BLACK, Color::BLACK))); + v + }; + let tty = tty::tty_get(0); + if tty != null_mut() { + let tty = *tty; + tty_enable(tty); + for (msgo, (fgc, bgc)) in info.into_iter() { + let msg = String::from(msgo).as_bytes_mut() as *mut [u8] as *mut u8; + let p = msg.offset(msgo.len() as isize); + let swp = *p; + *p = 0; + tty_text_print(tty, msg, u32::from(fgc), u32::from(bgc)); + *p = swp; + } + } + loop {} +} -- 2.45.0 From e99d51e81ffb61ea287fb073465e0db1c75360df Mon Sep 17 00:00:00 2001 From: pointer-to-bios Date: Sun, 4 Feb 2024 20:49:20 +0800 Subject: [PATCH 14/17] =?UTF-8?q?=E8=A7=A3=E5=86=B3=E6=8D=A2=E8=A1=8C?= =?UTF-8?q?=E6=97=B6=E5=85=89=E6=A0=87=E5=88=B7=E6=96=B0=E5=90=8E=E5=87=BA?= =?UTF-8?q?=E7=8E=B0=E4=B8=A4=E4=B8=AA=E5=85=89=E6=A0=87=E7=9A=84=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/kernel/tty/tty.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/kernel/tty/tty.c b/src/kernel/tty/tty.c index 809445c..2d63e9d 100644 --- a/src/kernel/tty/tty.c +++ b/src/kernel/tty/tty.c @@ -169,6 +169,7 @@ void tty_text_print(tty *ttyx, char *string, u32 color, u32 bgcolor) char c = *string; if (c == '\n') { // 换行 + putchar(ttyx, ' ', 0, 0); newline(ttyx); continue; } -- 2.45.0 From 0542277e313ef316a436610f6840dc9a62fc6dac Mon Sep 17 00:00:00 2001 From: pointer-to-bios Date: Mon, 5 Feb 2024 21:55:42 +0800 Subject: [PATCH 15/17] =?UTF-8?q?=E8=A7=A3=E5=86=B3=E5=86=85=E5=AD=98alloc?= =?UTF-8?q?ate=E5=87=BD=E6=95=B0=E6=9C=89=E5=8F=AF=E8=83=BD=E8=AE=BF?= =?UTF-8?q?=E9=97=AE=E6=9C=AA=E7=9F=A5=E5=86=85=E5=AD=98=E7=9A=84=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.toml | 9 --------- include/kernel/memm.h | 4 ++-- src/kernel/memm/memm.c | 3 ++- src/kernel/memm/memm.rs | 14 ++++++++++++-- src/metaverse.lds | 4 ++++ 5 files changed, 20 insertions(+), 14 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index f89fb5e..d2d3873 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,14 +6,5 @@ edition = "2021" # 此Cargo.toml仅用于rust-analyzer识别rust部分的代码 # 不应使用cargo编译 -[build] -type = "staticlib" -rustflags = [ - "-C", "embed-bitcode=no", - "-C", "code-model=large", - "-C", "relocation-model=static", - "-L", "crate=${PWD}/../rustlib/${ARCH}/src/" -] - [target.'cfg(target_arch = "x86_64")'] target = "x86_64-unknown-none" diff --git a/include/kernel/memm.h b/include/kernel/memm.h index d3f730f..f4714ae 100644 --- a/include/kernel/memm.h +++ b/include/kernel/memm.h @@ -139,9 +139,9 @@ allocator对象在进程与内核之间传递时一律使用内核空间的映 */ void *memm_allocate(usize size, usize pid); #define memm_addr_set_allocator(mem, allocator) \ - *(allocator_t **)(mem - 16) = allocator; + *(allocator_t **)((void *)(mem) - 16) = allocator; #define memm_addr_get_allocator(mem) \ - ((*(allocator_t **)(mem - 16))) + ((*(allocator_t **)((void *)(mem) - 16))) void *memm_kernel_allocate(usize size); diff --git a/src/kernel/memm/memm.c b/src/kernel/memm/memm.c index 2b152e6..787befa 100644 --- a/src/kernel/memm/memm.c +++ b/src/kernel/memm/memm.c @@ -200,7 +200,8 @@ void *memm_allocate(usize size, usize pid) ptr = new_allocator->allocate(&new_allocator->allocator_instance, orgsize, 0); after_allocation: - memm_addr_set_allocator(ptr, allocator); + if (ptr != nullptr) + memm_addr_set_allocator(ptr, allocator); return ptr; } diff --git a/src/kernel/memm/memm.rs b/src/kernel/memm/memm.rs index 3995400..fea17bf 100644 --- a/src/kernel/memm/memm.rs +++ b/src/kernel/memm/memm.rs @@ -1,6 +1,9 @@ extern crate core; -use core::alloc::{GlobalAlloc, Layout}; +use core::{ + alloc::{GlobalAlloc, Layout}, + ptr::null_mut, +}; extern "C" { pub fn memm_kernel_allocate(size: usize) -> *mut u8; @@ -12,7 +15,14 @@ pub struct KernelAllocator {} unsafe impl GlobalAlloc for KernelAllocator { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { - memm_kernel_allocate(layout.size()) + let res = memm_kernel_allocate(layout.size()); + if res == null_mut() { + panic!( + "Kernel allocator failed to allocate {} byte(s) memory.", + layout.size() + ); + } + res } unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { diff --git a/src/metaverse.lds b/src/metaverse.lds index 3ef868d..87da7f2 100644 --- a/src/metaverse.lds +++ b/src/metaverse.lds @@ -96,6 +96,10 @@ SECTIONS { { *(.debug_pubtypes) } + .debug_frame : + { + *(.debug_frame) + } .kend : { *(.kend) -- 2.45.0 From da4c7807b37826cfe5ff9d4954696eed4cb1d40a Mon Sep 17 00:00:00 2001 From: pointer-to-bios Date: Mon, 5 Feb 2024 21:57:33 +0800 Subject: [PATCH 16/17] =?UTF-8?q?=E6=94=BE=E5=BC=83=E4=BD=BF=E7=94=A8?= =?UTF-8?q?=E8=87=AA=E5=AE=9A=E4=B9=89=E7=9A=84format=E5=AE=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/kernel/clock/time.rs | 4 +--- src/libk/string/format/mod.rs | 38 ----------------------------------- src/libk/string/mod.rs | 1 - 3 files changed, 1 insertion(+), 42 deletions(-) delete mode 100644 src/libk/string/format/mod.rs diff --git a/src/kernel/clock/time.rs b/src/kernel/clock/time.rs index 29f86bd..a2eea96 100644 --- a/src/kernel/clock/time.rs +++ b/src/kernel/clock/time.rs @@ -1,8 +1,6 @@ use core::{cmp::Ordering, ops::Sub, time::Duration}; -use alloc::string::ToString; - -use crate::format; +use alloc::{format, string::ToString}; extern "C" { fn system_time_get() -> usize; diff --git a/src/libk/string/format/mod.rs b/src/libk/string/format/mod.rs deleted file mode 100644 index 8d63056..0000000 --- a/src/libk/string/format/mod.rs +++ /dev/null @@ -1,38 +0,0 @@ -use alloc::string::{String, ToString}; - -#[macro_export] -macro_rules! format { - ( $s : expr, $( $e : expr ),* ) => {{ - use crate::libk::string::format::Format; - let mut res = $s.to_string(); - $( - res.format($e); - )* - res - }}; - () => {}; -} - -pub trait Format { - fn format(&mut self, f: T); -} - -impl Format for String { - fn format(&mut self, f: T) { - let mut res = String::new(); - let mut formatting = false; - for c in self.chars().into_iter() { - if c == '{' { - formatting = true; - res += &f.to_string(); - } else if c == '}' { - formatting = false; - } - if !formatting { - res.push(c); - } - } - self.clear(); - self.push_str(&res); - } -} diff --git a/src/libk/string/mod.rs b/src/libk/string/mod.rs index db7b59d..e69de29 100644 --- a/src/libk/string/mod.rs +++ b/src/libk/string/mod.rs @@ -1 +0,0 @@ -pub mod format; -- 2.45.0 From fad16cd308d20cb9081066497dc1d8b262cf36df Mon Sep 17 00:00:00 2001 From: pointer-to-bios Date: Mon, 5 Feb 2024 22:09:18 +0800 Subject: [PATCH 17/17] =?UTF-8?q?=E5=AE=8C=E6=88=90=E5=86=85=E6=A0=B8?= =?UTF-8?q?=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- src/kernel/clock/time.rs | 2 +- src/lib.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 42c9a2b..4600d15 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ make debug * [x] 内存分配器 * [x] raw_allocator * [x] tty -* [ ] 内核日志 +* [x] 内核日志 * [ ] 文件系统 * [ ] vfs * [ ] fat32驱动(移植) diff --git a/src/kernel/clock/time.rs b/src/kernel/clock/time.rs index a2eea96..d286202 100644 --- a/src/kernel/clock/time.rs +++ b/src/kernel/clock/time.rs @@ -96,7 +96,7 @@ impl ToString for SystemTime { let milisec = second % second_dur; second /= second_dur; format!( - "[ {}-{}-{} {}:{}:{}.{} ]", + "[ {}-{}-{} {}:{}:{}.{} ] ", year, month, day, hour, minute, second, milisec ) } diff --git a/src/lib.rs b/src/lib.rs index 6166204..e8ac072 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -47,7 +47,7 @@ unsafe fn kernel_panic_handler(info: &PanicInfo) -> ! { } else { "Unknown panic." }, - (Color::GREEN, Color::BLACK), + (Color::BLUE, Color::BLACK), )); v.push(("\n", (Color::BLACK, Color::BLACK))); v -- 2.45.0