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 GPL version 2, see file LICENSE in this tarball for details.
13 // Make up for header deficiencies.
16 #define RAMFS_MAGIC 0x858458f6
20 #define TMPFS_MAGIC 0x01021994
29 // Recursively delete contents of rootfs.
31 static void delete_contents(const char *directory)
37 // Don't descend into other filesystems
38 if (lstat(directory, &st) || st.st_dev != rootdev) return;
40 // Recursively delete the contents of directories.
41 if (S_ISDIR(st.st_mode)) {
42 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.
62 // It wasn't a directory. Zap it.
64 } else unlink(directory);
67 int switch_root_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
68 int switch_root_main(int argc ATTRIBUTE_UNUSED, char **argv)
70 char *newroot, *console = NULL;
74 // Parse args (-c console)
76 opt_complementary = "-2"; // minimum 2 params
77 getopt32(argv, "+c:", &console); // '+': stop parsing at first non-option
80 // Change to new root directory and verify it's a different fs.
85 if (lstat(".", &st1) || lstat("/", &st2) || st1.st_dev == st2.st_dev) {
86 bb_error_msg_and_die("bad newroot %s", newroot);
90 // Additional sanity checks: we're about to rm -rf /, so be REALLY SURE
91 // we mean it. (I could make this a CONFIG option, but I would get email
92 // from all the people who WILL eat their filesystems.)
94 if (lstat("/init", &st1) || !S_ISREG(st1.st_mode) || statfs("/", &stfs) ||
95 (stfs.f_type != RAMFS_MAGIC && stfs.f_type != TMPFS_MAGIC) ||
98 bb_error_msg_and_die("not rootfs");
101 // Zap everything out of rootdev
103 delete_contents("/");
105 // Overmount / with newdir and chroot into it. The chdir is needed to
106 // recalculate "." and ".." links.
108 if (mount(".", "/", NULL, MS_MOVE, NULL))
109 bb_error_msg_and_die("error moving root");
113 // If a new console specified, redirect stdin/stdout/stderr to that.
117 xopen(console, O_RDWR);
122 // Exec real init. (This is why we must be pid 1.)
123 execv(argv[0], argv);
124 bb_perror_msg_and_die("bad init %s", argv[0]);