Magisk/native/src/init/mount.cpp

265 lines
7.7 KiB
C++
Raw Normal View History

#include <set>
2020-12-06 12:07:47 +01:00
#include <sys/mount.h>
2019-05-27 09:29:43 +02:00
#include <sys/sysmacros.h>
2020-05-04 07:49:54 +02:00
#include <libgen.h>
2019-05-27 09:29:43 +02:00
2022-05-12 11:03:42 +02:00
#include <base.hpp>
2020-03-09 09:50:30 +01:00
#include <selinux.hpp>
#include <magisk.hpp>
2019-05-27 09:29:43 +02:00
2020-03-09 09:50:30 +01:00
#include "init.hpp"
2019-05-27 09:29:43 +02:00
using namespace std;
2019-05-27 11:55:46 +02:00
struct devinfo {
int major;
int minor;
char devname[32];
char partname[32];
char dmname[32];
2019-05-27 11:55:46 +02:00
};
static vector<devinfo> dev_list;
static void parse_device(devinfo *dev, const char *uevent) {
dev->partname[0] = '\0';
parse_prop_file(uevent, [=](string_view key, string_view value) -> bool {
if (key == "MAJOR")
dev->major = parse_int(value.data());
else if (key == "MINOR")
dev->minor = parse_int(value.data());
else if (key == "DEVNAME")
strcpy(dev->devname, value.data());
else if (key == "PARTNAME")
strcpy(dev->partname, value.data());
return true;
});
2019-05-27 11:55:46 +02:00
}
2019-05-27 09:29:43 +02:00
static void collect_devices() {
char path[128];
devinfo dev{};
if (auto dir = xopen_dir("/sys/dev/block"); dir) {
for (dirent *entry; (entry = readdir(dir.get()));) {
if (entry->d_name == "."sv || entry->d_name == ".."sv)
continue;
sprintf(path, "/sys/dev/block/%s/uevent", entry->d_name);
parse_device(&dev, path);
sprintf(path, "/sys/dev/block/%s/dm/name", entry->d_name);
if (access(path, F_OK) == 0) {
auto name = rtrim(full_read(path));
strcpy(dev.dmname, name.data());
}
dev_list.push_back(dev);
}
}
2019-05-27 09:29:43 +02:00
}
2020-05-04 07:49:54 +02:00
static struct {
char partname[32];
char block_dev[64];
2020-05-04 07:49:54 +02:00
} blk_info;
2022-03-17 05:31:22 +01:00
static int64_t setup_block() {
if (dev_list.empty())
collect_devices();
for (int tries = 0; tries < 3; ++tries) {
for (auto &dev : dev_list) {
if (strcasecmp(dev.partname, blk_info.partname) == 0)
LOGD("Setup %s: [%s] (%d, %d)\n", dev.partname, dev.devname, dev.major, dev.minor);
else if (strcasecmp(dev.dmname, blk_info.partname) == 0)
LOGD("Setup %s: [%s] (%d, %d)\n", dev.dmname, dev.devname, dev.major, dev.minor);
else
continue;
dev_t rdev = makedev(dev.major, dev.minor);
2021-01-25 09:19:10 +01:00
xmknod(blk_info.block_dev, S_IFBLK | 0600, rdev);
return rdev;
}
// Wait 10ms and try again
usleep(10000);
dev_list.clear();
collect_devices();
}
// The requested partname does not exist
return -1;
2019-05-27 09:29:43 +02:00
}
static void switch_root(const string &path) {
LOGD("Switch root to %s\n", path.data());
int root = xopen("/", O_RDONLY);
for (set<string, greater<>> mounts; auto &info : parse_mount_info("self")) {
if (info.target == "/" || info.target == path)
continue;
if (auto last_mount = mounts.upper_bound(info.target);
last_mount != mounts.end() && info.target.starts_with(*last_mount + '/')) {
continue;
}
mounts.emplace(info.target);
auto new_path = path + info.target;
2021-08-14 07:29:12 +02:00
xmkdir(new_path.data(), 0755);
xmount(info.target.data(), new_path.data(), nullptr, MS_MOVE, nullptr);
}
chdir(path.data());
xmount(path.data(), "/", nullptr, MS_MOVE, nullptr);
chroot(".");
LOGD("Cleaning rootfs\n");
frm_rf(root);
}
#define PREINITMNT MIRRDIR "/preinit"
static void mount_preinit_dir(string path, dev_t preinit_dev) {
if (!preinit_dev) return;
xmknod(PREINITDEV, S_IFBLK | 0600, preinit_dev);
xmkdir(PREINITMNT, 0);
bool mounted = false;
// First, find if it is already mounted
for (auto &info : parse_mount_info("self")) {
if (info.root == "/" && info.device == preinit_dev) {
// Already mounted, just bind mount
xmount(info.target.data(), PREINITMNT, nullptr, MS_BIND, nullptr);
mounted = true;
break;
}
}
if (mounted || mount(PREINITDEV, PREINITMNT, "ext4", MS_RDONLY, nullptr) == 0 ||
mount(PREINITDEV, PREINITMNT, "f2fs", MS_RDONLY, nullptr) == 0) {
string preinit_dir = resolve_preinit_dir(PREINITMNT);
// Create bind mount
xmkdirs(PREINITMIRR, 0);
if (access(preinit_dir.data(), F_OK)) {
LOGW("empty preinit: %s\n", preinit_dir.data());
} else {
LOGD("preinit: %s\n", preinit_dir.data());
xmount(preinit_dir.data(), PREINITMIRR, nullptr, MS_BIND, nullptr);
mount_list.emplace_back(path += "/" PREINITMIRR);
}
xumount2(PREINITMNT, MNT_DETACH);
} else {
PLOGE("Failed to mount rules %u:%u", major(preinit_dev), minor(preinit_dev));
unlink(PREINITDEV);
}
2020-01-08 15:42:54 +01:00
}
bool LegacySARInit::mount_system_root() {
LOGD("Mounting system_root\n");
2022-06-22 13:05:50 +02:00
// there's no /dev in stub cpio
xmkdir("/dev", 0777);
strcpy(blk_info.block_dev, "/dev/root");
do {
// Try legacy SAR dm-verity
strcpy(blk_info.partname, "vroot");
2022-03-17 05:31:22 +01:00
auto dev = setup_block();
if (dev >= 0)
goto mount_root;
// Try NVIDIA naming scheme
strcpy(blk_info.partname, "APP");
2022-03-17 05:31:22 +01:00
dev = setup_block();
if (dev >= 0)
goto mount_root;
2021-10-26 09:35:55 +02:00
sprintf(blk_info.partname, "system%s", config->slot);
2022-03-17 05:31:22 +01:00
dev = setup_block();
if (dev >= 0)
goto mount_root;
// Poll forever if rootwait was given in cmdline
2021-10-26 09:35:55 +02:00
} while (config->rootwait);
// We don't really know what to do at this point...
LOGE("Cannot find root partition, abort\n");
exit(1);
mount_root:
xmkdir("/system_root", 0755);
Introduce new boot flow to handle SAR 2SI The existing method for handling legacy SAR is: 1. Mount /sbin tmpfs overlay 2. Dump all patched/new files into /sbin 3. Magic mount root dir and re-exec patched stock init With Android 11 removing the /sbin folder, it is quite obvious that things completely break down right in step 1. To overcome this issue, we have to find a way to swap out the init binary AFTER we re-exec stock init. This is where 2SI comes to rescue! 2SI normal boot procedure is: 1st stage -> Load sepolicy -> 2nd stage -> boot continue... 2SI Magisk boot procedure is: MagiskInit 1st stage -> Stock 1st stage -> MagiskInit 2nd Stage -> -> Stock init load sepolicy -> Stock 2nd stage -> boot continue... As you can see, the trick is to make stock 1st stage init re-exec back into MagiskInit so we can do our setup. This is possible by manipulating some ramdisk files on initramfs based 2SI devices (old ass non SAR devices AND super modern devices like Pixel 3/4), but not possible on device that are stuck using legacy SAR (device that are not that modern but not too old, like Pixel 1/2. Fucking Google logic!!) This commit introduces a new way to intercept stock init re-exec flow: ptrace init with forked tracer, monitor PTRACE_EVENT_EXEC, then swap out the init file with bind mounts right before execv returns! Going through this flow however will lose some necessary backup files, so some bookkeeping has to be done by making the tracer hold these files in memory and act as a daemon. 2nd stage MagiskInit will ack the daemon to release these files at the correct time. It just works™ ¯\_(ツ)_/¯
2020-04-01 13:39:28 +02:00
if (xmount("/dev/root", "/system_root", "ext4", MS_RDONLY, nullptr)) {
if (xmount("/dev/root", "/system_root", "erofs", MS_RDONLY, nullptr)) {
// We don't really know what to do at this point...
LOGE("Cannot mount root partition, abort\n");
exit(1);
}
}
switch_root("/system_root");
2022-03-18 12:58:37 +01:00
// Make dev writable
xmount("tmpfs", "/dev", "tmpfs", 0, "mode=755");
mount_list.emplace_back("/dev");
// Use the apex folder to determine whether 2SI (Android 10+)
bool is_two_stage = access("/apex", F_OK) == 0;
LOGD("is_two_stage: [%d]\n", is_two_stage);
2022-01-20 05:28:01 +01:00
#if ENABLE_AVD_HACK
if (!is_two_stage) {
if (config->emulator) {
avd_hack = true;
2022-03-17 05:31:22 +01:00
// These values are hardcoded for API 28 AVD
xmkdir("/dev/block", 0755);
strcpy(blk_info.block_dev, "/dev/block/vde1");
strcpy(blk_info.partname, "vendor");
setup_block();
xmount(blk_info.block_dev, "/vendor", "ext4", MS_RDONLY, nullptr);
}
}
#endif
Logical Resizable Android Partitions support The way how logical partition, or "Logical Resizable Android Partitions" as they say in AOSP source code, is setup makes it impossible to early mount the partitions from the shared super partition with just a few lines of code; in fact, AOSP has a whole "fs_mgr" folder which consist of multiple complex libraries, with 15K lines of code just to deal with the device mapper shenanigans. In order to keep the already overly complicated MagiskInit more managable, I chose NOT to go the route of including fs_mgr directly into MagiskInit. Luckily, starting from Android Q, Google decided to split init startup into 3 stages, with the first stage doing _only_ early mount. This is great news, because we can simply let the stock init do its own thing for us, and we intercept the bootup sequence. So the workflow can be visualized roughly below: Magisk First Stage --> First Stage Mount --> Magisk Second Stage --+ (MagiskInit) (Original Init) (MagiskInit) + + + ...Rest of the boot... <-- Second Stage <-- Selinux Setup <--+ (__________________ Original Init ____________________) The catch here is that after doing all the first stage mounting, /init will pivot /system as root directory (/), leaving us impossible to regain control after we hand it over. So the solution here is to patch fstab in /first_stage_ramdisk on-the-fly to redirect /system to /system_root, making the original init do all the hard work for us and mount required early mount partitions, but skips the step of switching root directory. It will also conveniently hand over execution back to MagiskInit, which we will reuse the routine for patching root directory in normal system-as-root situations.
2019-06-29 09:47:29 +02:00
return is_two_stage;
Logical Resizable Android Partitions support The way how logical partition, or "Logical Resizable Android Partitions" as they say in AOSP source code, is setup makes it impossible to early mount the partitions from the shared super partition with just a few lines of code; in fact, AOSP has a whole "fs_mgr" folder which consist of multiple complex libraries, with 15K lines of code just to deal with the device mapper shenanigans. In order to keep the already overly complicated MagiskInit more managable, I chose NOT to go the route of including fs_mgr directly into MagiskInit. Luckily, starting from Android Q, Google decided to split init startup into 3 stages, with the first stage doing _only_ early mount. This is great news, because we can simply let the stock init do its own thing for us, and we intercept the bootup sequence. So the workflow can be visualized roughly below: Magisk First Stage --> First Stage Mount --> Magisk Second Stage --+ (MagiskInit) (Original Init) (MagiskInit) + + + ...Rest of the boot... <-- Second Stage <-- Selinux Setup <--+ (__________________ Original Init ____________________) The catch here is that after doing all the first stage mounting, /init will pivot /system as root directory (/), leaving us impossible to regain control after we hand it over. So the solution here is to patch fstab in /first_stage_ramdisk on-the-fly to redirect /system to /system_root, making the original init do all the hard work for us and mount required early mount partitions, but skips the step of switching root directory. It will also conveniently hand over execution back to MagiskInit, which we will reuse the routine for patching root directory in normal system-as-root situations.
2019-06-29 09:47:29 +02:00
}
2019-12-05 22:29:45 +01:00
2020-12-06 12:07:47 +01:00
void BaseInit::exec_init() {
// Unmount in reverse order
for (auto &p : reversed(mount_list)) {
2022-01-19 14:12:11 +01:00
if (xumount2(p.data(), MNT_DETACH) == 0)
LOGD("Unmount [%s]\n", p.data());
}
execv("/init", argv);
exit(1);
2019-12-05 22:29:45 +01:00
}
void BaseInit::prepare_data() {
LOGD("Setup data tmp\n");
xmkdir("/data", 0755);
2023-02-12 19:11:25 +01:00
xmount("magisk", "/data", "tmpfs", 0, "mode=755");
cp_afc("/init", "/data/magiskinit");
cp_afc("/.backup", "/data/.backup");
cp_afc("/overlay.d", "/data/overlay.d");
}
2020-10-27 04:46:15 +01:00
void MagiskInit::setup_tmp(const char *path) {
LOGD("Setup Magisk tmp at %s\n", path);
chdir("/data");
xmkdir(INTLROOT, 0755);
xmkdir(MIRRDIR, 0);
xmkdir(BLOCKDIR, 0);
xmkdir(WORKERDIR, 0);
mount_preinit_dir(path, preinit_dev);
2022-03-17 05:31:22 +01:00
cp_afc(".backup/.magisk", INTLROOT "/config");
rm_rf(".backup");
// Create applet symlinks
for (int i = 0; applet_names[i]; ++i)
xsymlink("./magisk", applet_names[i]);
2022-03-17 11:15:39 +01:00
xsymlink("./magiskpolicy", "supolicy");
xmount(".", path, nullptr, MS_BIND | MS_REC, nullptr);
chdir("/");
}