liminix

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

preinit.c (1886B)


      1 #ifdef PREINIT_USE_LIBC
      2 #include <string.h>
      3 #include <unistd.h>
      4 #include <fcntl.h>
      5 #include <sys/mount.h>
      6 #include <sys/wait.h>
      7 #include <string.h>
      8 #else
      9 #include <nolibc.h>
     10 #endif
     11 #include <asm/setup.h>
     12 
     13 #define ERR(x) write(2, x, strlen(x))
     14 #define AVER(c) do { if(c < 0) ERR("failed: "  #c); } while(0)
     15 
     16 static int begins_with(char * str, char * prefix)
     17 {
     18 	while(*prefix) {
     19 		if(*str == '\0') return 0;
     20 		if(*str != *prefix) return 0;
     21 		str++;
     22 		prefix++;
     23 	}
     24 	return 1;
     25 }
     26 
     27 static void fork_exec(char * command, char *args[])
     28 {
     29 	int fork_pid = fork();
     30 	AVER(fork_pid);
     31 	if(fork_pid > 0)
     32 		wait(NULL);
     33 	else
     34 		AVER(execve(command, args, NULL));
     35 }
     36 
     37 char banner[]  = "Running pre-init...\n";
     38 char buf[COMMAND_LINE_SIZE];
     39 
     40 int main(int argc, char *argv[], char *envp[])
     41 {
     42 #ifndef PREINIT_USE_LIBC
     43         asm("la $gp, _gp\nsw $gp,16($sp)");
     44 #endif	
     45 	char *rootdevice = 0;
     46 	char *p = buf;
     47 	write(1, banner, strlen(banner));
     48 
     49 	mount("none", "/proc", "proc", 0, NULL);
     50 
     51 	int cmdline = open("/proc/cmdline", O_RDONLY, 0);
     52 
     53 	if(cmdline>=0) {
     54 		int len = read(cmdline, buf, sizeof buf - 1);
     55 		buf[len]='\0';
     56 		write(1, "cmdline ", 8);
     57 		write(1, buf, len);
     58 	};
     59 
     60 	while(*p) {
     61 		if(begins_with(p, "root=")) {
     62 			rootdevice = p + 5;
     63 			while(*p && (*p != ' ')) p++;
     64 			*p= '\0';
     65 		}
     66 		while(*p && (*p != ' ')) p++;
     67 		p++;
     68 	}
     69 
     70 	if(rootdevice) {
     71 		write(1, "rootdevice ", 11);
     72 		write(1, rootdevice, strlen(rootdevice));
     73 		write(1, "\n", 1);
     74 
     75 		AVER(mount(rootdevice, "/target/persist", "jffs2", 0, NULL));
     76 		AVER(mount("/target/persist/nix", "/target/nix",
     77 			   "bind", MS_BIND, NULL));
     78 
     79 		char *exec_args[] = { "activate",  "/target", NULL };
     80 		fork_exec("/target/persist/activate", exec_args);
     81 		AVER(chdir("/target"));
     82 
     83 		AVER(mount("/target", "/", "bind", MS_BIND | MS_REC, NULL));
     84 		AVER(chroot(".")); 
     85 		argv[0] = "init";
     86 		argv[1] = NULL;
     87 
     88 		AVER(execve("/persist/init", argv, envp));
     89 	}
     90 }