1 /* vi: set sw=4 ts=4: */
2 /* Copyright 2005 Rob Landley <rob@landley.net>
4 * Switch from rootfs to another filesystem as the root of the mount tree.
6 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
16 // Make up for header deficiencies.
19 #define RAMFS_MAGIC 0x858458f6
23 #define TMPFS_MAGIC 0x01021994
32 // Recursively delete contents of rootfs.
34 static void delete_contents(char *directory)
40 // Don't descend into other filesystems
41 if (lstat(directory,&st) || st.st_dev != rootdev) return;
43 // Recursively delete the contents of directories.
44 if (S_ISDIR(st.st_mode)) {
45 if((dir = opendir(directory))) {
46 while ((d = readdir(dir))) {
47 char *newdir=d->d_name;
50 if(*newdir=='.' && (!newdir[1] || (newdir[1]=='.' && !newdir[2])))
53 // Recurse to delete contents
54 newdir = alloca(strlen(directory) + strlen(d->d_name) + 2);
55 sprintf(newdir, "%s/%s", directory, d->d_name);
56 delete_contents(newdir);
60 // Directory should now be empty. Zap it.
64 // It wasn't a directory. Zap it.
66 } else unlink(directory);
69 int switch_root_main(int argc, char *argv[])
71 char *newroot, *console=NULL;
75 // Parse args (-c console)
77 bb_opt_complementally="-2";
78 bb_getopt_ulflags(argc,argv,"c:",&console);
80 // Change to new root directory and verify it's a different fs.
82 newroot=argv[optind++];
84 if (chdir(newroot) || lstat(".", &st1) || lstat("/", &st2) ||
85 st1.st_dev == st2.st_dev)
87 bb_error_msg_and_die("bad newroot %s",newroot);
91 // Additional sanity checks: we're about to rm -rf /, so be REALLY SURE
92 // we mean it. (I could make this a CONFIG option, but I would get email
93 // from all the people who WILL eat their filesystemss.)
95 if (lstat("/init", &st1) || !S_ISREG(st1.st_mode) || statfs("/", &stfs) ||
96 (stfs.f_type != RAMFS_MAGIC && stfs.f_type != TMPFS_MAGIC) ||
99 bb_error_msg_and_die("not rootfs");
102 // Zap everything out of rootdev
104 delete_contents("/");
106 // Overmount / with newdir and chroot into it. The chdir is needed to
107 // recalculate "." and ".." links.
109 if (mount(".", "/", NULL, MS_MOVE, NULL) || chroot(".") || chdir("/"))
110 bb_error_msg_and_die("moving root");
112 // If a new console specified, redirect stdin/stdout/stderr to that.
116 if(open(console, O_RDWR) < 0)
117 bb_error_msg_and_die("Bad console '%s'",console);
122 // Exec real init. (This is why we must be pid 1.)
123 execv(argv[optind],argv+optind);
124 bb_error_msg_and_die("Bad init '%s'",argv[optind]);