Architectural Support: x86_64 (#37)
[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     ({                                                                         \
20         int err = 0;                                                           \
21         if ((err = (statement)) < 0) {                                         \
22             syslog(2, #statement " failed: %d", err);                          \
23             _exit(1);                                                          \
24         }                                                                      \
25         err;                                                                   \
26     })
27
28 int
29 init_termios(int fd) {
30     struct termios term;
31
32     check(tcgetattr(fd, &term));
33
34     term.c_lflag = ICANON | IEXTEN | ISIG | ECHO | ECHOE | ECHONL;
35     term.c_iflag = ICRNL | IGNBRK;
36     term.c_oflag = ONLCR | OPOST;
37     term.c_cflag = CREAD | CLOCAL | CS8 | CPARENB;
38     term.c_cc[VERASE] = 0x7f;
39
40     check(tcsetattr(fd, 0, &term));
41
42     return 0;
43 }
44
45 const char* sh_argv[] = { "/usr/bin/sh", 0  };
46 const char* sh_envp[] = {  0  };
47
48 int
49 main(int argc, const char** argv)
50 {
51     mkdir("/dev");
52     mkdir("/sys");
53     mkdir("/task");
54
55     must_mount(NULL, "/dev", "devfs", 0);
56     must_mount(NULL, "/sys", "twifs", MNT_RO);
57     must_mount(NULL, "/task", "taskfs", MNT_RO);
58
59     int fd = check(open("/dev/tty", 0));
60
61     check(init_termios(fd));
62
63     check(dup(fd));
64
65     check(symlink("/usr", "/mnt/lunaix-os/usr"));
66
67     pid_t pid;
68     int err = 0;
69     if (!(pid = fork())) {
70
71         
72         err = execve(sh_argv[0], sh_argv, sh_envp);
73         printf("fail to execute (%d)\n", errno);
74         _exit(err);
75     }
76
77     waitpid(pid, &err, 0);
78
79     if (WEXITSTATUS(err)) {
80         printf("shell exit abnormally (%d)\n", err);
81     }
82
83     printf("init exiting\n");
84
85     return err;
86 }