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.
12 #include <sys/mount.h>
14 #include <sys/types.h>
20 // Make up for header deficiencies.
23 #define RAMFS_MAGIC 0x858458f6
27 #define TMPFS_MAGIC 0x01021994
36 // Recursively delete contents of rootfs.
38 static void delete_contents(char *directory)
44 // Don't descend into other filesystems
45 if (lstat(directory,&st) || st.st_dev != rootdev) return;
47 // Recursively delete the contents of directories.
48 if (S_ISDIR(st.st_mode)) {
49 if((dir = opendir(directory))) {
50 while ((d = readdir(dir))) {
51 char *newdir=d->d_name;
54 if(*newdir=='.' && (!newdir[1] || (newdir[1]=='.' && !newdir[2])))
57 // Recurse to delete contents
58 newdir = alloca(strlen(directory) + strlen(d->d_name) + 2);
59 sprintf(newdir, "%s/%s", directory, d->d_name);
60 delete_contents(newdir);
64 // Directory should now be empty. Zap it.
68 // It wasn't a directory. Zap it.
70 } else unlink(directory);
73 int switch_root_main(int argc, char *argv[])
75 char *newroot, *console=NULL;
79 // Parse args (-c console)
81 bb_opt_complementally="-2";
82 bb_getopt_ulflags(argc,argv,"c:",&console);
84 // Change to new root directory and verify it's a different fs.
86 newroot=argv[optind++];
88 if (chdir(newroot) || lstat(".", &st1) || lstat("/", &st2) ||
89 st1.st_dev == st2.st_dev)
91 bb_error_msg_and_die("bad newroot %s",newroot);
95 // Additional sanity checks: we're about to rm -rf /, so be REALLY SURE
96 // we mean it. (I could make this a CONFIG option, but I would get email
97 // from all the people who WILL eat their filesystemss.)
99 if (lstat("/init", &st1) || !S_ISREG(st1.st_mode) || statfs("/", &stfs) ||
100 (stfs.f_type != RAMFS_MAGIC && stfs.f_type != TMPFS_MAGIC) ||
103 bb_error_msg_and_die("not rootfs");
106 // Zap everything out of rootdev
108 delete_contents("/");
110 // Overmount / with newdir and chroot into it. The chdir is needed to
111 // recalculate "." and ".." links.
113 if (mount(".", "/", NULL, MS_MOVE, NULL) || chroot(".") || chdir("/"))
114 bb_error_msg_and_die("moving root");
116 // If a new console specified, redirect stdin/stdout/stderr to that.
120 if(open(console, O_RDWR) < 0)
121 bb_error_msg_and_die("Bad console '%s'",console);
126 // Exec real init. (This is why we must be pid 1.)
127 execv(argv[optind],argv+optind);
128 bb_error_msg_and_die("Bad init '%s'",argv[optind]);