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(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[])
68 char *newroot, *console=NULL;
72 // Parse args (-c console)
74 opt_complementary="-2";
75 getopt32(argc,argv,"c:",&console);
77 // Change to new root directory and verify it's a different fs.
79 newroot=argv[optind++];
81 if (chdir(newroot) || lstat(".", &st1) || lstat("/", &st2) ||
82 st1.st_dev == st2.st_dev)
84 bb_error_msg_and_die("bad newroot %s",newroot);
88 // Additional sanity checks: we're about to rm -rf /, so be REALLY SURE
89 // we mean it. (I could make this a CONFIG option, but I would get email
90 // from all the people who WILL eat their filesystemss.)
92 if (lstat("/init", &st1) || !S_ISREG(st1.st_mode) || statfs("/", &stfs) ||
93 (stfs.f_type != RAMFS_MAGIC && stfs.f_type != TMPFS_MAGIC) ||
96 bb_error_msg_and_die("not rootfs");
99 // Zap everything out of rootdev
101 delete_contents("/");
103 // Overmount / with newdir and chroot into it. The chdir is needed to
104 // recalculate "." and ".." links.
106 if (mount(".", "/", NULL, MS_MOVE, NULL) || chroot(".") || chdir("/"))
107 bb_error_msg_and_die("moving root");
109 // If a new console specified, redirect stdin/stdout/stderr to that.
113 if(open(console, O_RDWR) < 0)
114 bb_error_msg_and_die("Bad console '%s'",console);
119 // Exec real init. (This is why we must be pid 1.)
120 execv(argv[optind],argv+optind);
121 bb_error_msg_and_die("Bad init '%s'",argv[optind]);