1
2
3
4
5
6
7
8
9#include "libbb.h"
10#include <sys/vfs.h>
11
12
13#ifndef RAMFS_MAGIC
14#define RAMFS_MAGIC ((unsigned)0x858458f6)
15#endif
16
17#ifndef TMPFS_MAGIC
18#define TMPFS_MAGIC ((unsigned)0x01021994)
19#endif
20
21#ifndef MS_MOVE
22#define MS_MOVE 8192
23#endif
24
25
26static void delete_contents(const char *directory, dev_t rootdev)
27{
28 DIR *dir;
29 struct dirent *d;
30 struct stat st;
31
32
33 if (lstat(directory, &st) || st.st_dev != rootdev)
34 return;
35
36
37 if (S_ISDIR(st.st_mode)) {
38 dir = opendir(directory);
39 if (dir) {
40 while ((d = readdir(dir))) {
41 char *newdir = d->d_name;
42
43
44 if (DOT_OR_DOTDOT(newdir))
45 continue;
46
47
48 newdir = concat_path_file(directory, newdir);
49 delete_contents(newdir, rootdev);
50 free(newdir);
51 }
52 closedir(dir);
53
54
55 rmdir(directory);
56 }
57
58
59 } else unlink(directory);
60}
61
62int switch_root_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
63int switch_root_main(int argc UNUSED_PARAM, char **argv)
64{
65 char *newroot, *console = NULL;
66 struct stat st1, st2;
67 struct statfs stfs;
68 dev_t rootdev;
69
70
71 opt_complementary = "-2";
72 getopt32(argv, "+c:", &console);
73 argv += optind;
74
75
76 newroot = *argv++;
77
78 xchdir(newroot);
79 if (lstat(".", &st1) || lstat("/", &st2) || st1.st_dev == st2.st_dev) {
80 bb_error_msg_and_die("bad newroot %s", newroot);
81 }
82 rootdev = st2.st_dev;
83
84
85
86
87 if (lstat("/init", &st1) || !S_ISREG(st1.st_mode) || statfs("/", &stfs)
88 || (((unsigned)stfs.f_type != RAMFS_MAGIC) && ((unsigned)stfs.f_type != TMPFS_MAGIC))
89 || (getpid() != 1)
90 ) {
91 bb_error_msg_and_die("not rootfs");
92 }
93
94
95 delete_contents("/", rootdev);
96
97
98
99 if (mount(".", "/", NULL, MS_MOVE, NULL))
100 bb_error_msg_and_die("error moving root");
101 xchroot(".");
102 xchdir("/");
103
104
105 if (console) {
106 close(0);
107 xopen(console, O_RDWR);
108 xdup2(0, 1);
109 xdup2(0, 2);
110 }
111
112
113 execv(argv[0], argv);
114 bb_perror_msg_and_die("bad init %s", argv[0]);
115}
116