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 if((dir = opendir(directory))) {
43 while ((d = readdir(dir))) {
44 char *newdir=d->d_name;
47 if(*newdir=='.' && (!newdir[1] || (newdir[1]=='.' && !newdir[2])))
50 // Recurse to delete contents
51 newdir = alloca(strlen(directory) + strlen(d->d_name) + 2);
52 sprintf(newdir, "%s/%s", directory, d->d_name);
53 delete_contents(newdir);
57 // Directory should now be empty. Zap it.
61 // It wasn't a directory. Zap it.
63 } else unlink(directory);
66 int switch_root_main(int argc, char *argv[]);
67 int switch_root_main(int argc, char *argv[])
69 char *newroot, *console=NULL;
73 // Parse args (-c console)
75 opt_complementary = "-2";
76 getopt32(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) || lstat(".", &st1) || lstat("/", &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 (lstat("/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
102 delete_contents("/");
104 // Overmount / with newdir and chroot into it. The chdir is needed to
105 // recalculate "." and ".." links.
107 if (mount(".", "/", NULL, MS_MOVE, NULL) || chroot(".") || chdir("/"))
108 bb_error_msg_and_die("moving root");
110 // If a new console specified, redirect stdin/stdout/stderr to that.
114 if(open(console, O_RDWR) < 0)
115 bb_error_msg_and_die("bad console '%s'", console);
120 // Exec real init. (This is why we must be pid 1.)
121 execv(argv[optind], argv+optind);
122 bb_error_msg_and_die("bad init '%s'", argv[optind]);