Merge branch 'master' of github.com:Minep/lunaix-os
[lunaix-os.git] / lunaix-os / usr / init / init.c
1 #include <errno.h>
2 #include <fcntl.h>
3 #include <lunaix/lunaix.h>
4 #include <lunaix/mount.h>
5 #include <termios.h>
6 #include <stdio.h>
7 #include <unistd.h>
8
9 #define must_mount(src, target, fs, opts)                                      \
10     do {                                                                       \
11         int err = 0;                                                           \
12         if ((err = mount(src, target, fs, opts))) {                            \
13             syslog(2, "mount fs %s to %s failed (%d)\n", fs, target, errno);   \
14             return err;                                                        \
15         }                                                                      \
16     } while (0)
17
18 #define check(statement)                                      \
19     do {                                                                       \
20         int err = 0;                                                           \
21         if ((err = (statement))) {                            \
22             syslog(2, #statement " failed: %d", err);   \
23             return err;                                                        \
24         }                                                                      \
25     } while (0)
26
27 int
28 init_termios(int fd) {
29     struct termios term;
30
31     check(tcgetattr(fd, &term));
32
33     term.c_lflag = ICANON | IEXTEN | ISIG | ECHO | ECHOE | ECHONL;
34     term.c_iflag = ICRNL | IGNBRK;
35     term.c_oflag = ONLCR | OPOST;
36     term.c_cflag = CREAD | CLOCAL | CS8 | CPARENB;
37     term.c_cc[VERASE] = 0x08;
38
39     check(tcsetattr(fd, 0, &term));
40
41     return 0;
42 }
43
44 int
45 main(int argc, const char** argv)
46 {
47     int err = 0;
48
49     mkdir("/dev");
50     mkdir("/sys");
51     mkdir("/task");
52
53     must_mount(NULL, "/dev", "devfs", 0);
54     must_mount(NULL, "/sys", "twifs", MNT_RO);
55     must_mount(NULL, "/task", "taskfs", MNT_RO);
56
57     if ((err = open("/dev/tty", 0)) < 0) {
58         syslog(2, "fail to open tty (%d)\n", errno);
59         return err;
60     }
61
62     check(init_termios(err));
63
64     if ((err = dup(err)) < 0) {
65         syslog(2, "fail to setup tty i/o (%d)\n", errno);
66         return err;
67     }
68
69     if ((err = symlink("/usr", "/mnt/lunaix-os/usr"))) {
70         syslog(2, "symlink /usr:/mnt/lunaix-os/usr (%d)\n", errno);
71         return err;
72     }
73
74     pid_t pid;
75     if (!(pid = fork())) {
76         err = execve("/usr/bin/sh", NULL, NULL);
77         printf("fail to execute (%d)\n", errno);
78         _exit(err);
79     }
80
81     waitpid(pid, &err, 0);
82
83     if (WEXITSTATUS(err)) {
84         printf("shell exit abnormally (%d)", err);
85     }
86
87     return err;
88 }