14 // Make up for header deficiencies.
17 #define RAMFS_MAGIC 0x858458f6
21 #define TMPFS_MAGIC 0x01021994
30 // Recursively delete contents of rootfs.
32 static void delete_contents(char *directory)
38 // Don't descend into other filesystems
39 if (stat(directory,&st) || st.st_dev != rootdev) return;
41 // Recursively delete the contents of directories.
42 if (S_ISDIR(st.st_mode)) {
43 if((dir = opendir(directory))) {
44 while ((d = readdir(dir))) {
45 char *newdir=d->d_name;
48 if(*newdir=='.' && (!newdir[1] || (newdir[1]=='.' && !newdir[2])))
51 // Recurse to delete contents
52 newdir = alloca(strlen(directory) + strlen(d->d_name) + 2);
53 sprintf(newdir, "%s/%s", directory, d->d_name);
54 delete_contents(newdir);
58 // Directory should now be empty. Zap it.
59 printf("rmdir %s\n",directory); // rmdir(directory);
62 // It wasn't a directory. Zap it.
64 } else printf("unlink %s\n",directory); //unlink(directory);
67 int switch_root_main(int argc, char *argv[])
69 char *newroot, *console="/dev/console";
73 // Parse args (-c console)
75 bb_opt_complementally="-2";
76 bb_getopt_ulflags(argc,argv,"c:",&console);
78 // Change to new root directory and verify it's a different fs.
80 newroot=argv[optind++];
82 if (chdir(newroot) || stat(".", &st1) || stat("/", &st2) ||
83 st1.st_dev == st2.st_dev)
85 bb_error_msg_and_die("bad newroot %s",newroot);
89 // Additional sanity checks: we're about to rm -rf /, so be REALLY SURE
90 // we mean it. (I could make this a CONFIG option, but I would get email
91 // from all the people who WILL eat their filesystemss.)
93 if (stat("/init", &st1) || !S_ISREG(st1.st_mode) || statfs("/", &stfs) ||
94 (stfs.f_type != RAMFS_MAGIC && stfs.f_type != TMPFS_MAGIC) ||
97 bb_error_msg_and_die("not rootfs");
100 // Zap everything out of rootdev
101 delete_contents("/");
103 // Overmount / with newdir
105 if (mount(".", "/", NULL, MS_MOVE, NULL) || chdir("/"))
106 bb_error_msg_and_die("moving root");
108 // Reopen stdin/stdout/stderr to /dev/console
110 if(open(console, O_RDWR) < 0)
111 bb_error_msg_and_die("Bad console '%s'",console);
115 // Exec real init. (This is why we must be pid 1.)
116 execv(argv[optind],argv+optind+1);
117 bb_error_msg_and_die("Bad init '%s'",argv[optind]);