Magisk/native/jni/init/mount.cpp

412 lines
9.9 KiB
C++
Raw Normal View History

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
2020-03-09 09:50:30 +01:00
#include <utils.hpp>
#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;
static string rtrim(string &&str) {
// Trim space, newline, and null byte from end of string
while (memchr(" \n\r", str[str.length() - 1], 4))
str.pop_back();
return std::move(str);
}
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) {
2019-05-27 09:29:43 +02:00
dev->partname[0] = '\0';
2019-05-27 11:55:46 +02:00
parse_prop_file(uevent, [=](string_view key, string_view value) -> bool {
if (key == "MAJOR")
2019-12-05 22:29:45 +01:00
dev->major = parse_int(value.data());
2019-05-27 11:55:46 +02:00
else if (key == "MINOR")
2019-12-05 22:29:45 +01:00
dev->minor = parse_int(value.data());
2019-05-27 11:55:46 +02:00
else if (key == "DEVNAME")
strcpy(dev->devname, value.data());
else if (key == "PARTNAME")
strcpy(dev->partname, value.data());
2019-05-27 09:29:43 +02:00
2019-05-27 11:55:46 +02:00
return true;
});
}
2019-05-27 09:29:43 +02:00
static void collect_devices() {
char path[128];
devinfo dev{};
2019-12-13 06:37:06 +01:00
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));
2020-10-28 12:17:34 +01:00
strcpy(dev.dmname, name.data());
}
2019-12-13 06:37:06 +01:00
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];
} blk_info;
2020-10-28 12:17:34 +01:00
static int64_t setup_block(bool write_block) {
2019-05-27 09:29:43 +02:00
if (dev_list.empty())
collect_devices();
xmkdir("/dev", 0755);
xmkdir("/dev/block", 0755);
for (int tries = 0; tries < 3; ++tries) {
for (auto &dev : dev_list) {
2020-10-28 12:17:34 +01:00
if (strcasecmp(dev.partname, blk_info.partname) == 0)
2020-05-04 07:49:54 +02:00
LOGD("Setup %s: [%s] (%d, %d)\n", dev.partname, dev.devname, dev.major, dev.minor);
2020-10-28 12:17:34 +01:00
else if (strcasecmp(dev.dmname, blk_info.partname) == 0)
LOGD("Setup %s: [%s] (%d, %d)\n", dev.dmname, dev.devname, dev.major, dev.minor);
2020-10-28 12:17:34 +01:00
else
continue;
if (write_block) {
sprintf(blk_info.block_dev, "/dev/block/%s", dev.devname);
}
2020-10-28 12:17:34 +01:00
dev_t rdev = makedev(dev.major, dev.minor);
mknod(blk_info.block_dev, S_IFBLK | 0600, rdev);
return rdev;
2019-05-27 09:29:43 +02:00
}
// Wait 10ms and try again
usleep(10000);
dev_list.clear();
collect_devices();
2019-05-27 09:29:43 +02:00
}
// The requested partname does not exist
return -1;
2019-05-27 09:29:43 +02:00
}
2019-06-30 20:39:13 +02:00
static bool is_lnk(const char *name) {
struct stat st;
if (lstat(name, &st))
return false;
return S_ISLNK(st.st_mode);
}
2020-05-04 07:49:54 +02:00
#define read_info(val) \
if (access(#val, F_OK) == 0) {\
entry.val = rtrim(full_read(#val)); \
}
Force init to load fstab from file in 2SI Patching DTBs is proven to be difficult and problematic as there are tons of different formats out there. Adding support for all the formats in magiskboot has been quite an headache in the past year, and it still definitely does not cover all possible cases of them out there. There is another issue: fake dt fstabs. Some super old devices do not have device trees in their boot images, so some custom ROM developers had came up with a "genius" solution: hardcode fstab entries directly in the kernel source code and create fake device tree nodes even if Android 10+ init can graciously take fstab files instead (-_-) 。。。 And there is YET another issue: DTBs are not always in boot images! Google is crazy enough to litter DTBs all over the place, it is like they cannot make up their minds (duh). This means the dt fstabs can be either concatnated after the kernel (1), in the DTB partition (2), in the DTBO partition (3), in the recovery_dtbo section in boot images (4), or in the dtb section in boot images (5). FIVE f**king places, how can anyone keep up with that! With Android 10+ that uses 2 stage inits, it is crutual for Magisk to be able to modify fstab mount points in order to let the original init mount partitions for us, but NOT switch root and continue booting. For devices using dt for early mount fstab, we used to patch the DTB at install time with magiskboot. However these changes are permanent and cannot be restored back at reinstallation. With this commit, Magisk will read dt fstabs and write them to ramdisk at boot time. And in that case, the init binary will also be patched to force it to NEVER use fstabs in device-tree. By doing so, we can unify ramdisk based 2SI fstab patching as basically we are just patching fstab files. This also means we can manipulate fstab whatever Magisk needs in the future without the need to going through the headache that is patching DTBs at installation.
2020-05-04 11:21:51 +02:00
void BaseInit::read_dt_fstab(vector<fstab_entry> &fstab) {
2020-05-04 07:49:54 +02:00
if (access(cmd->dt_dir, F_OK) != 0)
return;
Force init to load fstab from file in 2SI Patching DTBs is proven to be difficult and problematic as there are tons of different formats out there. Adding support for all the formats in magiskboot has been quite an headache in the past year, and it still definitely does not cover all possible cases of them out there. There is another issue: fake dt fstabs. Some super old devices do not have device trees in their boot images, so some custom ROM developers had came up with a "genius" solution: hardcode fstab entries directly in the kernel source code and create fake device tree nodes even if Android 10+ init can graciously take fstab files instead (-_-) 。。。 And there is YET another issue: DTBs are not always in boot images! Google is crazy enough to litter DTBs all over the place, it is like they cannot make up their minds (duh). This means the dt fstabs can be either concatnated after the kernel (1), in the DTB partition (2), in the DTBO partition (3), in the recovery_dtbo section in boot images (4), or in the dtb section in boot images (5). FIVE f**king places, how can anyone keep up with that! With Android 10+ that uses 2 stage inits, it is crutual for Magisk to be able to modify fstab mount points in order to let the original init mount partitions for us, but NOT switch root and continue booting. For devices using dt for early mount fstab, we used to patch the DTB at install time with magiskboot. However these changes are permanent and cannot be restored back at reinstallation. With this commit, Magisk will read dt fstabs and write them to ramdisk at boot time. And in that case, the init binary will also be patched to force it to NEVER use fstabs in device-tree. By doing so, we can unify ramdisk based 2SI fstab patching as basically we are just patching fstab files. This also means we can manipulate fstab whatever Magisk needs in the future without the need to going through the headache that is patching DTBs at installation.
2020-05-04 11:21:51 +02:00
char cwd[128];
getcwd(cwd, sizeof(cwd));
2020-05-04 07:49:54 +02:00
chdir(cmd->dt_dir);
Force init to load fstab from file in 2SI Patching DTBs is proven to be difficult and problematic as there are tons of different formats out there. Adding support for all the formats in magiskboot has been quite an headache in the past year, and it still definitely does not cover all possible cases of them out there. There is another issue: fake dt fstabs. Some super old devices do not have device trees in their boot images, so some custom ROM developers had came up with a "genius" solution: hardcode fstab entries directly in the kernel source code and create fake device tree nodes even if Android 10+ init can graciously take fstab files instead (-_-) 。。。 And there is YET another issue: DTBs are not always in boot images! Google is crazy enough to litter DTBs all over the place, it is like they cannot make up their minds (duh). This means the dt fstabs can be either concatnated after the kernel (1), in the DTB partition (2), in the DTBO partition (3), in the recovery_dtbo section in boot images (4), or in the dtb section in boot images (5). FIVE f**king places, how can anyone keep up with that! With Android 10+ that uses 2 stage inits, it is crutual for Magisk to be able to modify fstab mount points in order to let the original init mount partitions for us, but NOT switch root and continue booting. For devices using dt for early mount fstab, we used to patch the DTB at install time with magiskboot. However these changes are permanent and cannot be restored back at reinstallation. With this commit, Magisk will read dt fstabs and write them to ramdisk at boot time. And in that case, the init binary will also be patched to force it to NEVER use fstabs in device-tree. By doing so, we can unify ramdisk based 2SI fstab patching as basically we are just patching fstab files. This also means we can manipulate fstab whatever Magisk needs in the future without the need to going through the headache that is patching DTBs at installation.
2020-05-04 11:21:51 +02:00
run_finally cd([&]{ chdir(cwd); });
2020-05-04 07:49:54 +02:00
if (access("fstab", F_OK) != 0)
return;
chdir("fstab");
Force init to load fstab from file in 2SI Patching DTBs is proven to be difficult and problematic as there are tons of different formats out there. Adding support for all the formats in magiskboot has been quite an headache in the past year, and it still definitely does not cover all possible cases of them out there. There is another issue: fake dt fstabs. Some super old devices do not have device trees in their boot images, so some custom ROM developers had came up with a "genius" solution: hardcode fstab entries directly in the kernel source code and create fake device tree nodes even if Android 10+ init can graciously take fstab files instead (-_-) 。。。 And there is YET another issue: DTBs are not always in boot images! Google is crazy enough to litter DTBs all over the place, it is like they cannot make up their minds (duh). This means the dt fstabs can be either concatnated after the kernel (1), in the DTB partition (2), in the DTBO partition (3), in the recovery_dtbo section in boot images (4), or in the dtb section in boot images (5). FIVE f**king places, how can anyone keep up with that! With Android 10+ that uses 2 stage inits, it is crutual for Magisk to be able to modify fstab mount points in order to let the original init mount partitions for us, but NOT switch root and continue booting. For devices using dt for early mount fstab, we used to patch the DTB at install time with magiskboot. However these changes are permanent and cannot be restored back at reinstallation. With this commit, Magisk will read dt fstabs and write them to ramdisk at boot time. And in that case, the init binary will also be patched to force it to NEVER use fstabs in device-tree. By doing so, we can unify ramdisk based 2SI fstab patching as basically we are just patching fstab files. This also means we can manipulate fstab whatever Magisk needs in the future without the need to going through the headache that is patching DTBs at installation.
2020-05-04 11:21:51 +02:00
// Make sure dt fstab is enabled
if (access("status", F_OK) == 0) {
auto status = rtrim(full_read("status"));
if (status != "okay" && status != "ok")
return;
}
2020-05-04 07:49:54 +02:00
auto dir = xopen_dir(".");
for (dirent *dp; (dp = xreaddir(dir.get()));) {
if (dp->d_type != DT_DIR)
continue;
chdir(dp->d_name);
run_finally f([]{ chdir(".."); });
if (access("status", F_OK) == 0) {
auto status = rtrim(full_read("status"));
if (status != "okay" && status != "ok")
continue;
}
fstab_entry entry;
read_info(dev);
read_info(mnt_point) else {
entry.mnt_point = "/";
entry.mnt_point += dp->d_name;
2019-05-27 09:29:43 +02:00
}
2020-05-04 07:49:54 +02:00
read_info(type);
read_info(mnt_flags);
read_info(fsmgr_flags);
Force init to load fstab from file in 2SI Patching DTBs is proven to be difficult and problematic as there are tons of different formats out there. Adding support for all the formats in magiskboot has been quite an headache in the past year, and it still definitely does not cover all possible cases of them out there. There is another issue: fake dt fstabs. Some super old devices do not have device trees in their boot images, so some custom ROM developers had came up with a "genius" solution: hardcode fstab entries directly in the kernel source code and create fake device tree nodes even if Android 10+ init can graciously take fstab files instead (-_-) 。。。 And there is YET another issue: DTBs are not always in boot images! Google is crazy enough to litter DTBs all over the place, it is like they cannot make up their minds (duh). This means the dt fstabs can be either concatnated after the kernel (1), in the DTB partition (2), in the DTBO partition (3), in the recovery_dtbo section in boot images (4), or in the dtb section in boot images (5). FIVE f**king places, how can anyone keep up with that! With Android 10+ that uses 2 stage inits, it is crutual for Magisk to be able to modify fstab mount points in order to let the original init mount partitions for us, but NOT switch root and continue booting. For devices using dt for early mount fstab, we used to patch the DTB at install time with magiskboot. However these changes are permanent and cannot be restored back at reinstallation. With this commit, Magisk will read dt fstabs and write them to ramdisk at boot time. And in that case, the init binary will also be patched to force it to NEVER use fstabs in device-tree. By doing so, we can unify ramdisk based 2SI fstab patching as basically we are just patching fstab files. This also means we can manipulate fstab whatever Magisk needs in the future without the need to going through the headache that is patching DTBs at installation.
2020-05-04 11:21:51 +02:00
fstab.emplace_back(std::move(entry));
2019-05-27 09:29:43 +02:00
}
}
2020-10-27 04:46:15 +01:00
void MagiskInit::mount_with_dt() {
Force init to load fstab from file in 2SI Patching DTBs is proven to be difficult and problematic as there are tons of different formats out there. Adding support for all the formats in magiskboot has been quite an headache in the past year, and it still definitely does not cover all possible cases of them out there. There is another issue: fake dt fstabs. Some super old devices do not have device trees in their boot images, so some custom ROM developers had came up with a "genius" solution: hardcode fstab entries directly in the kernel source code and create fake device tree nodes even if Android 10+ init can graciously take fstab files instead (-_-) 。。。 And there is YET another issue: DTBs are not always in boot images! Google is crazy enough to litter DTBs all over the place, it is like they cannot make up their minds (duh). This means the dt fstabs can be either concatnated after the kernel (1), in the DTB partition (2), in the DTBO partition (3), in the recovery_dtbo section in boot images (4), or in the dtb section in boot images (5). FIVE f**king places, how can anyone keep up with that! With Android 10+ that uses 2 stage inits, it is crutual for Magisk to be able to modify fstab mount points in order to let the original init mount partitions for us, but NOT switch root and continue booting. For devices using dt for early mount fstab, we used to patch the DTB at install time with magiskboot. However these changes are permanent and cannot be restored back at reinstallation. With this commit, Magisk will read dt fstabs and write them to ramdisk at boot time. And in that case, the init binary will also be patched to force it to NEVER use fstabs in device-tree. By doing so, we can unify ramdisk based 2SI fstab patching as basically we are just patching fstab files. This also means we can manipulate fstab whatever Magisk needs in the future without the need to going through the headache that is patching DTBs at installation.
2020-05-04 11:21:51 +02:00
vector<fstab_entry> fstab;
2020-05-04 07:49:54 +02:00
read_dt_fstab(fstab);
Force init to load fstab from file in 2SI Patching DTBs is proven to be difficult and problematic as there are tons of different formats out there. Adding support for all the formats in magiskboot has been quite an headache in the past year, and it still definitely does not cover all possible cases of them out there. There is another issue: fake dt fstabs. Some super old devices do not have device trees in their boot images, so some custom ROM developers had came up with a "genius" solution: hardcode fstab entries directly in the kernel source code and create fake device tree nodes even if Android 10+ init can graciously take fstab files instead (-_-) 。。。 And there is YET another issue: DTBs are not always in boot images! Google is crazy enough to litter DTBs all over the place, it is like they cannot make up their minds (duh). This means the dt fstabs can be either concatnated after the kernel (1), in the DTB partition (2), in the DTBO partition (3), in the recovery_dtbo section in boot images (4), or in the dtb section in boot images (5). FIVE f**king places, how can anyone keep up with that! With Android 10+ that uses 2 stage inits, it is crutual for Magisk to be able to modify fstab mount points in order to let the original init mount partitions for us, but NOT switch root and continue booting. For devices using dt for early mount fstab, we used to patch the DTB at install time with magiskboot. However these changes are permanent and cannot be restored back at reinstallation. With this commit, Magisk will read dt fstabs and write them to ramdisk at boot time. And in that case, the init binary will also be patched to force it to NEVER use fstabs in device-tree. By doing so, we can unify ramdisk based 2SI fstab patching as basically we are just patching fstab files. This also means we can manipulate fstab whatever Magisk needs in the future without the need to going through the headache that is patching DTBs at installation.
2020-05-04 11:21:51 +02:00
for (const auto &entry : fstab) {
2020-05-04 07:49:54 +02:00
if (is_lnk(entry.mnt_point.data()))
continue;
// Derive partname from dev
sprintf(blk_info.partname, "%s%s", basename(entry.dev.data()), cmd->slot);
2020-10-28 12:17:34 +01:00
setup_block(true);
2020-05-04 07:49:54 +02:00
xmkdir(entry.mnt_point.data(), 0755);
xmount(blk_info.block_dev, entry.mnt_point.data(), entry.type.data(), MS_RDONLY, nullptr);
mount_list.push_back(entry.mnt_point);
}
2019-05-27 09:29:43 +02:00
}
static void switch_root(const string &path) {
LOGD("Switch root to %s\n", path.data());
2020-04-02 08:37:11 +02:00
int root = xopen("/", O_RDONLY);
vector<string> mounts;
parse_mnt("/proc/mounts", [&](mntent *me) {
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
// Skip root and self
if (me->mnt_dir == "/"sv || me->mnt_dir == path)
return true;
// Do not include subtrees
for (const auto &m : mounts) {
2020-02-21 06:08:44 +01:00
if (strncmp(me->mnt_dir, m.data(), m.length()) == 0 && me->mnt_dir[m.length()] == '/')
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 true;
}
mounts.emplace_back(me->mnt_dir);
return true;
});
for (auto &dir : mounts) {
auto new_path = path + dir;
mkdir(new_path.data(), 0755);
2020-02-21 06:08:44 +01:00
xmount(dir.data(), new_path.data(), nullptr, MS_MOVE, nullptr);
}
chdir(path.data());
xmount(path.data(), "/", nullptr, MS_MOVE, nullptr);
chroot(".");
2020-04-02 08:37:11 +02:00
LOGD("Cleaning rootfs\n");
frm_rf(root);
}
void MagiskInit::mount_rules_dir(const char *dev_base, const char *mnt_base) {
char path[128];
2020-05-04 07:49:54 +02:00
xrealpath(dev_base, blk_info.block_dev);
xrealpath(mnt_base, path);
char *b = blk_info.block_dev + strlen(blk_info.block_dev);
char *p = path + strlen(path);
auto do_mount = [&](const char *type) -> bool {
xmkdir(path, 0755);
bool success = xmount(blk_info.block_dev, path, type, 0, nullptr) == 0;
if (success)
mount_list.emplace_back(path);
return success;
};
// First try userdata
strcpy(blk_info.partname, "userdata");
strcpy(b, "/data");
strcpy(p, "/data");
2020-01-08 15:42:54 +01:00
if (setup_block(false) < 0) {
// Try NVIDIA naming scheme
strcpy(blk_info.partname, "UDA");
if (setup_block(false) < 0)
goto cache;
2020-01-08 15:42:54 +01:00
}
// Try to mount with either ext4 or f2fs
// Failure means either FDE or metadata encryption
if (!do_mount("ext4") && !do_mount("f2fs"))
goto cache;
strcpy(p, "/data/unencrypted");
if (access(path, F_OK) == 0) {
// FBE, need to use an unencrypted path
custom_rules_dir = path + "/magisk"s;
} else {
// Skip if /data/adb does not exist
strcpy(p, "/data/adb");
if (access(path, F_OK) != 0)
return;
// Unencrypted, directly use module paths
custom_rules_dir = string(mnt_base) + MODULEROOT;
}
goto success;
cache:
// Fallback to cache
strcpy(blk_info.partname, "cache");
strcpy(b, "/cache");
strcpy(p, "/cache");
if (setup_block(false) < 0) {
// Try NVIDIA naming scheme
strcpy(blk_info.partname, "CAC");
if (setup_block(false) < 0)
goto metadata;
}
if (!do_mount("ext4"))
goto metadata;
custom_rules_dir = path + "/magisk"s;
goto success;
metadata:
// Fallback to metadata
strcpy(blk_info.partname, "metadata");
strcpy(b, "/metadata");
strcpy(p, "/metadata");
if (setup_block(false) < 0 || !do_mount("ext4"))
goto persist;
custom_rules_dir = path + "/magisk"s;
goto success;
persist:
// Fallback to persist
strcpy(blk_info.partname, "persist");
strcpy(b, "/persist");
strcpy(p, "/persist");
if (setup_block(false) < 0 || !do_mount("ext4"))
return;
custom_rules_dir = path + "/magisk"s;
success:
// Create symlinks so we don't need to go through this logic again
strcpy(p, "/sepolicy.rules");
xsymlink(custom_rules_dir.data(), path);
2020-01-08 15:42:54 +01:00
}
void RootFSInit::early_mount() {
2020-09-02 11:49:32 +02:00
self = raw_data::read("/init");
2020-01-08 15:42:54 +01:00
2020-05-04 07:49:54 +02:00
LOGD("Restoring /init\n");
2020-01-08 15:42:54 +01:00
rename("/.backup/init", "/init");
2020-10-27 04:46:15 +01:00
mount_with_dt();
2020-01-08 15:42:54 +01:00
}
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
void SARBase::backup_files() {
2019-07-16 10:08:28 +02:00
if (access("/overlay.d", F_OK) == 0)
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
backup_folder("/overlay.d", overlays);
2019-07-16 10:08:28 +02:00
2020-09-02 11:49:32 +02:00
self = raw_data::read("/proc/self/exe");
if (access("/.backup/.magisk", R_OK) == 0)
2020-09-02 11:49:32 +02:00
config = raw_data::read("/.backup/.magisk");
2019-07-16 10:08:28 +02:00
}
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
void SARBase::mount_system_root() {
LOGD("Early mount system_root\n");
2020-05-04 07:49:54 +02:00
strcpy(blk_info.block_dev, "/dev/root");
// Try legacy SAR dm-verity
strcpy(blk_info.partname, "vroot");
auto dev = setup_block(false);
if (dev >= 0)
goto mount_root;
// Try NVIDIA naming scheme
strcpy(blk_info.partname, "APP");
dev = setup_block(false);
if (dev >= 0)
goto mount_root;
sprintf(blk_info.partname, "system%s", cmd->slot);
dev = setup_block(false);
if (dev >= 0)
goto mount_root;
// 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);
if (xmount("/dev/root", "/system_root", "ext4", MS_RDONLY, nullptr))
xmount("/dev/root", "/system_root", "erofs", MS_RDONLY, nullptr);
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
}
void SARInit::early_mount() {
backup_files();
mount_system_root();
switch_root("/system_root");
2019-06-25 11:47:16 +02:00
{
auto init = raw_data::mmap_ro("/init");
is_two_stage = init.contains("selinux_setup");
}
2020-12-05 19:23:49 +01:00
LOGD("is_two_stage: [%d]\n", is_two_stage);
if (!is_two_stage) {
// Make dev writable
xmkdir("/dev", 0755);
xmount("tmpfs", "/dev", "tmpfs", 0, "mode=755");
mount_list.emplace_back("/dev");
mount_with_dt();
}
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
}
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
2020-12-06 12:07:47 +01:00
void SecondStageInit::prepare() {
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
backup_files();
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
umount2("/init", MNT_DETACH);
umount2("/proc/self/exe", MNT_DETACH);
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 (access("/system_root", F_OK) == 0)
switch_root("/system_root");
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() {
2019-12-05 22:29:45 +01:00
// Unmount in reverse order
for (auto &p : reversed(mount_list)) {
if (xumount(p.data()) == 0)
LOGD("Unmount [%s]\n", p.data());
2019-12-05 22:29:45 +01:00
}
2020-12-06 12:07:47 +01:00
execv("/init", argv);
exit(1);
2019-12-05 22:29:45 +01:00
}
2020-04-12 14:34:56 +02:00
static void patch_socket_name(const char *path) {
2020-05-04 07:49:54 +02:00
char rstr[16];
gen_rand_str(rstr, sizeof(rstr));
2020-09-02 11:49:32 +02:00
auto bin = raw_data::mmap_rw(path);
bin.patch({ make_pair(MAIN_SOCKET, rstr) });
2020-04-12 14:34:56 +02:00
}
2020-10-27 04:46:15 +01:00
void MagiskInit::setup_tmp(const char *path) {
2020-04-12 14:34:56 +02:00
LOGD("Setup Magisk tmp at %s\n", path);
xmount("tmpfs", path, "tmpfs", 0, "mode=755");
chdir(path);
xmkdir(INTLROOT, 0755);
xmkdir(MIRRDIR, 0);
xmkdir(BLOCKDIR, 0);
2020-04-12 14:34:56 +02:00
int fd = xopen(INTLROOT "/config", O_WRONLY | O_CREAT, 0);
xwrite(fd, config.buf, config.sz);
close(fd);
fd = xopen("magiskinit", O_WRONLY | O_CREAT, 0755);
xwrite(fd, self.buf, self.sz);
close(fd);
dump_magisk("magisk", 0755);
patch_socket_name("magisk");
// Create applet symlinks
for (int i = 0; applet_names[i]; ++i)
xsymlink("./magisk", applet_names[i]);
xsymlink("./magiskinit", "magiskpolicy");
xsymlink("./magiskinit", "supolicy");
chdir("/");
}