123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219 |
- #include <sys/vfs.h>
- #include <sys/mount.h>
- #include "libbb.h"
- #ifndef RAMFS_MAGIC
- # define RAMFS_MAGIC ((unsigned)0x858458f6)
- #endif
- #ifndef TMPFS_MAGIC
- # define TMPFS_MAGIC ((unsigned)0x01021994)
- #endif
- #ifndef MS_MOVE
- # define MS_MOVE 8192
- #endif
- static void delete_contents(const char *directory, dev_t rootdev)
- {
- DIR *dir;
- struct dirent *d;
- struct stat st;
-
- if (lstat(directory, &st) || st.st_dev != rootdev)
- return;
-
- if (S_ISDIR(st.st_mode)) {
- dir = opendir(directory);
- if (dir) {
- while ((d = readdir(dir))) {
- char *newdir = d->d_name;
-
- if (DOT_OR_DOTDOT(newdir))
- continue;
-
- newdir = concat_path_file(directory, newdir);
- delete_contents(newdir, rootdev);
- free(newdir);
- }
- closedir(dir);
-
- rmdir(directory);
- }
- } else {
-
- unlink(directory);
- }
- }
- int switch_root_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
- int switch_root_main(int argc UNUSED_PARAM, char **argv)
- {
- char *newroot, *console = NULL;
- struct stat st;
- struct statfs stfs;
- dev_t rootdev;
-
- opt_complementary = "-2";
- getopt32(argv, "+c:", &console);
- argv += optind;
- newroot = *argv++;
-
- xchdir(newroot);
- xstat("/", &st);
- rootdev = st.st_dev;
- xstat(".", &st);
- if (st.st_dev == rootdev || getpid() != 1) {
-
-
- bb_show_usage();
- }
-
-
-
- if (stat("/init", &st) != 0 || !S_ISREG(st.st_mode)) {
- bb_error_msg_and_die("/init is not a regular file");
- }
- statfs("/", &stfs);
- if ((unsigned)stfs.f_type != RAMFS_MAGIC
- && (unsigned)stfs.f_type != TMPFS_MAGIC
- ) {
- bb_error_msg_and_die("root filesystem is not ramfs/tmpfs");
- }
-
- delete_contents("/", rootdev);
-
- if (mount(".", "/", NULL, MS_MOVE, NULL)) {
-
- bb_perror_msg_and_die("error moving root");
- }
- xchroot(".");
-
-
-
- if (console) {
- close(0);
- xopen(console, O_RDWR);
- xdup2(0, 1);
- xdup2(0, 2);
- }
-
- execv(argv[0], argv);
- bb_perror_msg_and_die("can't execute '%s'", argv[0]);
- }
|