refactor: keep in mind the stack layout is crucial. Move context switching & signal...
[lunaix-os.git] / lunaix-os / kernel / lxinit.c
1 #include <hal/cpu.h>
2 #include <lunaix/clock.h>
3 #include <lunaix/keyboard.h>
4 #include <lunaix/lunistd.h>
5 #include <lunaix/mm/kalloc.h>
6 #include <lunaix/mm/vmm.h>
7 #include <lunaix/proc.h>
8 #include <lunaix/spike.h>
9 #include <lunaix/syslog.h>
10 #include <lunaix/timer.h>
11 #include <lunaix/tty/tty.h>
12
13 extern uint8_t __kernel_start;
14
15 LOG_MODULE("INIT")
16
17 // #define FORK_BOMB_DEMO
18 // #define WAIT_DEMO
19
20 void
21 _lxinit_main()
22 {
23 #ifdef FORK_BOMB_DEMO
24     // fork炸弹
25     for (;;) {
26         pid_t p;
27         if ((p = fork())) {
28             kprintf(KDEBUG "Pinkie Pie #%d: FUN!\n", p);
29         }
30     }
31 #endif
32
33     int status;
34 #ifdef WAIT_DEMO
35     // 测试wait
36     kprintf("I am parent, going to fork my child and wait.\n");
37     if (!fork()) {
38         kprintf("I am child, going to sleep for 2 seconds\n");
39         sleep(2);
40         kprintf("I am child, I am about to terminated\n");
41         _exit(1);
42     }
43     pid_t child = wait(&status);
44     kprintf("I am parent, my child (%d) terminated normally with code: %d.\n",
45             child,
46             WEXITSTATUS(status));
47 #endif
48
49     pid_t p = 0;
50
51     if (!fork()) {
52         kprintf("Test no hang!\n");
53         sleep(6);
54         _exit(0);
55     }
56
57     waitpid(-1, &status, WNOHANG);
58
59     for (size_t i = 0; i < 5; i++) {
60         pid_t pid = 0;
61         if (!(pid = fork())) {
62             sleep(i);
63             if (i == 3) {
64                 i = *(int*)0xdeadc0de; // seg fault!
65             }
66             tty_put_char('0' + i);
67             tty_put_char('\n');
68             _exit(0);
69         }
70         kprintf(KINFO "Forked %d\n", pid);
71     }
72
73     while ((p = wait(&status)) >= 0) {
74         short code = WEXITSTATUS(status);
75         if (WIFEXITED(status)) {
76             kprintf(KINFO "Process %d exited with code %d\n", p, code);
77         } else {
78             kprintf(KWARN "Process %d aborted with code %d\n", p, code);
79         }
80     }
81
82     char buf[64];
83
84     kprintf(KINFO "Hello processes!\n");
85
86     cpu_get_brand(buf);
87     kprintf("CPU: %s\n\n", buf);
88
89     // no lxmalloc here! This can only be used within kernel, but here, we are
90     // in a dedicated process! any access to kernel method must be done via
91     // syscall
92
93     struct kdb_keyinfo_pkt keyevent;
94     while (1) {
95         if (!kbd_recv_key(&keyevent)) {
96             // yield();
97             continue;
98         }
99         if ((keyevent.state & KBD_KEY_FPRESSED) &&
100             (keyevent.keycode & 0xff00) <= KEYPAD) {
101             tty_put_char((char)(keyevent.keycode & 0x00ff));
102             tty_sync_cursor();
103         }
104     }
105
106     spin();
107 }