-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkernel.c
More file actions
93 lines (90 loc) · 2.78 KB
/
Copy pathkernel.c
File metadata and controls
93 lines (90 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include "idt.h"
#include "io.h"
#include "keyboard.h"
#include "rtc.h"
#include "string.h"
#include "timer.h"
#include "vga.h"
char cmd_buf[128];
int buf_siz = 128;
int buf_pos = 0;
char *cmd_list[] = {
"help", "clear", "reboot", "shutdown", "echo", "ls", "cat", "mkdir",
"rmdir", "touch", "rm", "cp", "mv", "find", "grep", "wc",
"date", "time", "whoami", "uname", "ps", "kill",
};
void reboot() {
// 通过向 0x64 端口写入 0xFE 来触发软重启
outb(0x64, 0xFE);
}
void shutdown() { outw(0x604, 0x2000); }
void handle_command(char *cmd) {
if (strcmp(cmd, "help") == 0) {
printk("Available commands:\n");
for (int i = 0; i < sizeof(cmd_list) / sizeof(cmd_list[0]); i++) {
printk(" %s\n", cmd_list[i]);
}
} else if (strcmp(cmd, "clear") == 0) {
clear_screen();
} else if (strcmp(cmd, "reboot") == 0) {
reboot();
} else if (strcmp(cmd, "shutdown") == 0) {
shutdown();
} else if (strcmp(cmd, "time") == 0) {
cmd_time();
} else if (strcmp(cmd, "date") == 0) {
cmd_date();
} else if (strncmp(cmd, "echo ", 5) == 0) {
printk("%s\n", cmd + 5);
} else {
printk("Unknown command: %s\n", cmd);
}
}
void cmd_putchar(char c) {
if (c == '\n') {
putchar(c);
if (buf_pos > 0) {
handle_command(cmd_buf);
memset(cmd_buf, 0, buf_pos);
buf_pos = 0;
}
printk("ToyOS_Shell>");
} else if (c == '\b') {
if (buf_pos > 0) {
putchar(c);
cmd_buf[--buf_pos] = '\0';
}
} else {
if (buf_pos == buf_siz - 1) {
printk("\nCommand buffer full! Please press Enter to execute the "
"command.\n");
return;
}
putchar(c);
cmd_buf[buf_pos++] = c;
}
}
void kernel_main(unsigned long magic, unsigned long addr) {
// 1. 初始化你的格式化输出基础设施
clear_screen();
printk("ToyOS Kernel Booting...\n");
// 2. 加载中断大厦
idt_init();
printk("IDT and PIC configured.\n");
timer_init(100);
// 3. 临门一脚:执行 sti 指令,正式宣告 CPU 开启中断接听!
__asm__ volatile("sti");
printk("Interrupts enabled globally. Try press any key now!\n");
memset(cmd_buf, 0, buf_siz);
printk("ToyOS_Shell>");
// 4. 内核死循环,静静等待硬件中断去打破安宁
while (1) {
// CPU 可以在这里闲逛,一旦敲键盘,就会瞬间被硬核切入执行
char c = keyboard_getchar();
if (c == 0) {
__asm__ volatile("hlt");
continue;
}
cmd_putchar(c);
}
}