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.
13 #include <sys/mount.h>
15 #include <sys/types.h>
21 // Make up for header deficiencies.
24 #define RAMFS_MAGIC 0x858458f6
28 #define TMPFS_MAGIC 0x01021994
37 // Recursively delete contents of rootfs.
39 static void delete_contents(char *directory)
45 // Don't descend into other filesystems
46 if (lstat(directory,&st) || st.st_dev != rootdev) return;
48 // Recursively delete the contents of directories.
49 if (S_ISDIR(st.st_mode)) {
50 if((dir = opendir(directory))) {
51 while ((d = readdir(dir))) {
52 char *newdir=d->d_name;
55 if(*newdir=='.' && (!newdir[1] || (newdir[1]=='.' && !newdir[2])))
58 // Recurse to delete contents
59 newdir = alloca(strlen(directory) + strlen(d->d_name) + 2);
60 sprintf(newdir, "%s/%s", directory, d->d_name);
61 delete_contents(newdir);
65 // Directory should now be empty. Zap it.
69 // It wasn't a directory. Zap it.
71 } else unlink(directory);
74 int switch_root_main(int argc, char *argv[])
76 char *newroot, *console=NULL;
80 // Parse args (-c console)
82 bb_opt_complementally="-2";
83 bb_getopt_ulflags(argc,argv,"c:",&console);
85 // Change to new root directory and verify it's a different fs.
87 newroot=argv[optind++];
89 if (chdir(newroot) || lstat(".", &st1) || lstat("/", &st2) ||
90 st1.st_dev == st2.st_dev)
92 bb_error_msg_and_die("bad newroot %s",newroot);
96 // Additional sanity checks: we're about to rm -rf /, so be REALLY SURE
97 // we mean it. (I could make this a CONFIG option, but I would get email
98 // from all the people who WILL eat their filesystemss.)
100 if (lstat("/init", &st1) || !S_ISREG(st1.st_mode) || statfs("/", &stfs) ||
101 (stfs.f_type != RAMFS_MAGIC && stfs.f_type != TMPFS_MAGIC) ||
104 bb_error_msg_and_die("not rootfs");
107 // Zap everything out of rootdev
109 delete_contents("/");
111 // Overmount / with newdir and chroot into it. The chdir is needed to
112 // recalculate "." and ".." links.
114 if (mount(".", "/", NULL, MS_MOVE, NULL) || chroot(".") || chdir("/"))
115 bb_error_msg_and_die("moving root");
117 // If a new console specified, redirect stdin/stdout/stderr to that.
121 if(open(console, O_RDWR) < 0)
122 bb_error_msg_and_die("Bad console '%s'",console);
127 // Exec real init. (This is why we must be pid 1.)
128 execv(argv[optind],argv+optind);
129 bb_error_msg_and_die("Bad init '%s'",argv[optind]);