xref: /kvmtool/guest/init.c (revision 91d6a8e38a2ba56c7f5fef42e1ef60d4a08d51ce)
1 /*
2  * This is a simple init for shared rootfs guests. This part should be limited
3  * to doing mounts and running stage 2 of the init process.
4  */
5 #include <sys/mount.h>
6 #include <string.h>
7 #include <unistd.h>
8 #include <stdio.h>
9 #include <errno.h>
10 #include <linux/reboot.h>
11 
12 static int run_process(char *filename)
13 {
14 	char *new_argv[] = { filename, NULL };
15 	char *new_env[] = { "TERM=linux", NULL };
16 
17 	return execve(filename, new_argv, new_env);
18 }
19 
20 static int run_process_sandbox(char *filename)
21 {
22 	char *new_argv[] = { filename, "/virt/sandbox.sh", NULL };
23 	char *new_env[] = { "TERM=linux", NULL };
24 
25 	return execve(filename, new_argv, new_env);
26 }
27 
28 static void do_mounts(void)
29 {
30 	mount("hostfs", "/host", "9p", MS_RDONLY, "trans=virtio,version=9p2000.L");
31 	mount("", "/sys", "sysfs", 0, NULL);
32 	mount("proc", "/proc", "proc", 0, NULL);
33 	mount("devtmpfs", "/dev", "devtmpfs", 0, NULL);
34 }
35 
36 int main(int argc, char *argv[])
37 {
38 	pid_t child;
39 	int status;
40 
41 	puts("Mounting...");
42 
43 	do_mounts();
44 
45 	/* get session leader */
46 	setsid();
47 
48 	/* set controlling terminal */
49 	ioctl(0, TIOCSCTTY, 1);
50 
51 	child = fork();
52 	if (child < 0) {
53 		printf("Fatal: fork() failed with %d\n", child);
54 		return 0;
55 	} else if (child == 0) {
56 		if (access("/virt/sandbox.sh", R_OK) == 0)
57 			run_process_sandbox("/bin/sh");
58 		else
59 			run_process("/bin/sh");
60 	} else {
61 		waitpid(child, &status, 0);
62 	}
63 
64 	reboot(LINUX_REBOOT_CMD_RESTART);
65 
66 	printf("Init failed: %s\n", strerror(errno));
67 
68 	return 0;
69 }
70