Source reorganization

This commit is contained in:
topjohnwu
2018-11-03 00:26:04 -04:00
parent a7824af5a8
commit ef6677f43d
5 changed files with 4 additions and 4 deletions

42
native/jni/misc/applets.c Normal file
View File

@@ -0,0 +1,42 @@
#include <libgen.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "magisk.h"
#include "selinux.h"
int (*applet_main[]) (int, char *[]) =
{ magisk_main, su_client_main, resetprop_main, magiskhide_main, imgtool_main, NULL };
char *argv0;
__attribute__((noreturn)) static void call_applets(int argc, char *argv[]) {
// Applets
for (int i = 0; applet_names[i]; ++i) {
if (strcmp(basename(argv[0]), applet_names[i]) == 0) {
strcpy(argv0, basename(argv[0]));
exit((*applet_main[i])(argc, argv));
}
}
fprintf(stderr, "%s: applet not found\n", argv[0]);
exit(1);
}
int main(int argc, char *argv[]) {
umask(0);
argv0 = argv[0];
dload_selinux();
cmdline_logging();
if (strcmp(basename(argv0), "magisk.bin") == 0 ||
(strcmp(basename(argv[0]), "magisk") == 0
&& argc > 1 && argv[1][0] != '-')) {
--argc;
++argv;
}
call_applets(argc, argv);
}

78
native/jni/misc/b64xz.c Normal file
View File

@@ -0,0 +1,78 @@
/* b64xz.c - Base64-XZ Extractor
*
* This program converts data from stdin to stdout.
* The input should be compressed with xz (integrity check only support CRC32 or none) and then
* encoded into base64 format. What b64xz does is basically the reverse of the
* mentioned process: decode base64 to bytes, decompress xz, then dump to stdout
*
* The compiled binary will be hex-dumped into update-binary
* Busybox will be xz-compressed, base64 encoded and dumped into update-binary
* This program is to recover busybox for Magisk installation environment
*/
#include <unistd.h>
#include <xz.h>
static const char trans_tbl[] =
"|$$$}rstuvwxyz{$$$$$$$>?@ABCDEFGHIJKLMNOPQRSTUVW$$$$$$XYZ[\\]^_`abcdefghijklmnopq";
static void decodeblock(uint8_t* in, uint8_t* out) {
out[0] = (uint8_t)(in[0] << 2 | in[1] >> 4);
out[1] = (uint8_t)(in[1] << 4 | in[2] >> 2);
out[2] = (uint8_t)(((in[2] << 6) & 0xc0) | in[3]);
}
static int unxz(struct xz_dec *dec, const void *buf, unsigned size) {
uint8_t out[8192];
struct xz_buf b = {
.in = buf,
.in_pos = 0,
.in_size = size,
.out = out,
.out_pos = 0,
.out_size = sizeof(out)
};
enum xz_ret ret;
do {
ret = xz_dec_run(dec, &b);
if (ret != XZ_OK && ret != XZ_STREAM_END)
return 1;
write(STDOUT_FILENO, out, b.out_pos);
b.out_pos = 0;
} while (b.in_pos != size);
return 0;
}
int main(int argc, char const* argv[]) {
if (argc > 1)
return 0;
uint8_t in[4], buf[6144];
unsigned len = 0, pos = 0;
int8_t c;
xz_crc32_init();
struct xz_dec *dec = xz_dec_init(XZ_DYNALLOC, 1 << 26);
if (dec == NULL)
return 1;
while (read(STDIN_FILENO, &c, sizeof(c)) == 1) {
c = ((c < 43 || c > 122) ? -1 : (trans_tbl[c - 43] == '$' ? -1 : trans_tbl[c - 43] - 62));
if (c >= 0)
in[len++] = c;
if (len < 4)
continue;
len = 0;
decodeblock(in, buf + pos);
pos += 3;
if (pos == sizeof(buf)) {
if (unxz(dec, buf, pos))
return 1;
pos = 0;
}
}
if (pos && unxz(dec, buf, pos))
return 1;
xz_dec_end(dec);
return 0;
}

297
native/jni/misc/img.c Normal file
View File

@@ -0,0 +1,297 @@
/* img.c - All image related functions
*/
#include <unistd.h>
#include <libgen.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/mount.h>
#include <sys/sendfile.h>
#include <sys/statfs.h>
#include <sys/sysmacros.h>
#include <linux/loop.h>
#include "magisk.h"
#include "utils.h"
#include "img.h"
#include "flags.h"
#define round_size(a) ((((a) / 32) + 2) * 32)
#define SOURCE_TMP "/dev/.img_src"
#define TARGET_TMP "/dev/.img_tgt"
#define MERGE_TMP "/dev/.img_mrg"
struct fs_info {
unsigned size;
unsigned free;
unsigned used;
};
static char *loopsetup(const char *img) {
char device[32];
struct loop_info64 info;
int lfd = -1, ffd;
memset(&info, 0, sizeof(info));
if (access(BLOCKDIR, F_OK) == 0) {
for (int i = 8; i < 100; ++i) {
sprintf(device, BLOCKDIR "/loop%02d", i);
if (access(device, F_OK) != 0)
mknod(device, S_IFBLK | 0600, makedev(7, i * 8));
lfd = open(device, O_RDWR);
if (lfd < 0) /* Kernel does not support this */
break;
if (ioctl(lfd, LOOP_GET_STATUS64, &info) == -1)
break;
close(lfd);
lfd = -1;
}
}
// Fallback to existing loop in dev, but in reverse order
if (lfd < 0) {
for (int i = 7; i >= 0; --i) {
sprintf(device, "/dev/block/loop%d", i);
lfd = xopen(device, O_RDWR);
if (ioctl(lfd, LOOP_GET_STATUS64, &info) == -1)
break;
close(lfd);
lfd = -1;
}
}
if (lfd < 0)
return NULL;
ffd = xopen(img, O_RDWR);
if (ioctl(lfd, LOOP_SET_FD, ffd) == -1)
return NULL;
strncpy((char *) info.lo_file_name, img, sizeof(info.lo_file_name));
ioctl(lfd, LOOP_SET_STATUS64, &info);
close(lfd);
close(ffd);
return strdup(device);
}
static void check_filesystem(struct fs_info *info, const char *img, const char *mount) {
struct stat st;
struct statfs fs;
stat(img, &st);
statfs(mount, &fs);
info->size = st.st_size / 1048576;
info->free = fs.f_bfree * (uint64_t)fs.f_frsize / 1048576;
info->used = (fs.f_blocks - fs.f_bfree) * (uint64_t)fs.f_frsize / 1048576;
}
static void usage() {
fprintf(stderr,
"ImgTool v" xstr(MAGISK_VERSION) "(" xstr(MAGISK_VER_CODE) ") (by topjohnwu) - EXT4 Image Tools\n"
"\n"
"Usage: imgtool <action> [args...]\n"
"\n"
"Actions:\n"
" create IMG SIZE create ext4 image. SIZE is interpreted in MB\n"
" resize IMG SIZE resize ext4 image. SIZE is interpreted in MB\n"
" mount IMG PATH mount IMG to PATH and prints the loop device\n"
" umount PATH LOOP unmount PATH and delete LOOP device\n"
" merge SRC TGT merge SRC to TGT\n"
" trim IMG trim IMG to save space\n"
);
exit(1);
}
int imgtool_main(int argc, char *argv[]) {
if (argc < 2)
usage();
if (strcmp(argv[1], "create") == 0) {
if (argc < 4)
usage();
return create_img(argv[2], atoi(argv[3]));
} else if (strcmp(argv[1], "resize") == 0) {
if (argc < 4)
usage();
return resize_img(argv[2], atoi(argv[3]));
} else if (strcmp(argv[1], "mount") == 0) {
if (argc < 4)
usage();
// Redirect 1 > /dev/null
int fd = open("/dev/null", O_WRONLY);
int out = dup(STDOUT_FILENO);
xdup2(fd, STDOUT_FILENO);
char *loop = mount_image(argv[2], argv[3]);
// Restore stdin
xdup2(out, STDOUT_FILENO);
close(fd);
close(out);
if (loop == NULL) {
fprintf(stderr, "Cannot mount image!\n");
return 1;
} else {
printf("%s\n", loop);
free(loop);
return 0;
}
} else if (strcmp(argv[1], "umount") == 0) {
if (argc < 4)
usage();
umount_image(argv[2], argv[3]);
return 0;
} else if (strcmp(argv[1], "merge") == 0) {
if (argc < 4)
usage();
return merge_img(argv[2], argv[3]);
} else if (strcmp(argv[1], "trim") == 0) {
if (argc < 3)
usage();
xmkdir(SOURCE_TMP, 0755);
char *loop = mount_image(argv[2], SOURCE_TMP);
int ret = trim_img(argv[2], SOURCE_TMP, loop);
umount_image(SOURCE_TMP, loop);
rmdir(SOURCE_TMP);
free(loop);
return ret;
}
usage();
return 1;
}
int create_img(const char *img, int size) {
if (size == 128) /* WTF...? */
size = 132;
unlink(img);
LOGI("Create %s with size %dM\n", img, size);
char size_str[16];
snprintf(size_str, sizeof(size_str), "%dM", size);
if (access("/system/bin/make_ext4fs", X_OK) == 0)
return exec_command_sync("/system/bin/make_ext4fs", "-b", "4096", "-l", size_str, img, NULL);
else if (access("/system/bin/mke2fs", X_OK) == 0)
// On Android P there is no make_ext4fs, use mke2fs
return exec_command_sync("/system/bin/mke2fs", "-b", "4096", "-t", "ext4", img, size_str, NULL);
else
return 1;
}
int resize_img(const char *img, int size) {
LOGI("Resize %s to %dM\n", img, size);
exec_command_sync("/system/bin/e2fsck", "-yf", img, NULL);
char ss[16];
snprintf(ss, sizeof(ss), "%dM", size);
return exec_command_sync("/system/bin/resize2fs", img, ss, NULL);
}
char *mount_image(const char *img, const char *target) {
if (access(img, F_OK) == -1 || access(target, F_OK) == -1)
return NULL;
exec_command_sync("/system/bin/e2fsck", "-yf", img, NULL);
char *device = loopsetup(img);
if (device)
xmount(device, target, "ext4", MS_NOATIME, NULL);
return device;
}
int umount_image(const char *target, const char *device) {
int ret = 0;
ret |= xumount(target);
int fd = xopen(device, O_RDWR);
ret |= ioctl(fd, LOOP_CLR_FD);
close(fd);
return ret;
}
int merge_img(const char *source, const char *target) {
if (access(source, F_OK) == -1)
return 0;
if (access(target, F_OK) == -1) {
LOGI("* Move %s -> %s\n", source, target);
if (rename(source, target) < 0) {
// Copy and remove
int tgt = creat(target, 0644);
int src = xopen(source, O_RDONLY | O_CLOEXEC);
sendfile(tgt, src, 0, INT_MAX);
close(tgt);
close(src);
unlink(source);
}
return 0;
}
char buf[PATH_MAX];
xmkdir(SOURCE_TMP, 0755);
xmkdir(TARGET_TMP, 0755);
char *s_loop, *t_loop, *m_loop;
s_loop = mount_image(source, SOURCE_TMP);
if (s_loop == NULL)
return 1;
t_loop = mount_image(target, TARGET_TMP);
if (t_loop == NULL)
return 1;
snprintf(buf, sizeof(buf), "%s/%s", SOURCE_TMP, "lost+found");
rm_rf(buf);
snprintf(buf, sizeof(buf), "%s/%s", TARGET_TMP, "lost+found");
rm_rf(buf);
DIR *dir;
struct dirent *entry;
if (!(dir = xopendir(SOURCE_TMP)))
return 1;
while ((entry = xreaddir(dir))) {
if (entry->d_type == DT_DIR) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0 ||
strcmp(entry->d_name, ".core") == 0)
continue;
// Cleanup old module if exists
snprintf(buf, sizeof(buf), "%s/%s", TARGET_TMP, entry->d_name);
if (access(buf, F_OK) == 0)
rm_rf(buf);
LOGI("Upgrade/New module: %s\n", entry->d_name);
}
}
closedir(dir);
struct fs_info src, tgt;
check_filesystem(&src, source, SOURCE_TMP);
check_filesystem(&tgt, target, TARGET_TMP);
snprintf(buf, sizeof(buf), "%s/tmp.img", dirname(target));
create_img(buf, round_size(src.used + tgt.used));
xmkdir(MERGE_TMP, 0755);
m_loop = mount_image(buf, MERGE_TMP);
if (m_loop == NULL)
return 1;
LOGI("* Merging %s + %s -> %s", source, target, buf);
cp_afc(TARGET_TMP, MERGE_TMP);
cp_afc(SOURCE_TMP, MERGE_TMP);
// Unmount all loop devices
umount_image(SOURCE_TMP, s_loop);
umount_image(TARGET_TMP, t_loop);
umount_image(MERGE_TMP, m_loop);
rmdir(SOURCE_TMP);
rmdir(TARGET_TMP);
rmdir(MERGE_TMP);
free(s_loop);
free(t_loop);
free(m_loop);
// Cleanup
unlink(source);
LOGI("* Move %s -> %s", buf, target);
rename(buf, target);
return 0;
}
int trim_img(const char *img, const char *mount, char *loop) {
struct fs_info info;
check_filesystem(&info, img, mount);
int new_size = round_size(info.used);
if (info.size > new_size) {
umount_image(mount, loop);
resize_img(img, new_size);
char *loop2 = mount_image(img, mount);
if (loop2 == NULL)
return 1;
strcpy(loop, loop2);
free(loop2);
}
return 0;
}

475
native/jni/misc/init.c Normal file
View File

@@ -0,0 +1,475 @@
/* init.c - Pre-init Magisk support
*
* This code has to be compiled statically to work properly.
*
* To unify Magisk support for both legacy "normal" devices and new skip_initramfs devices,
* magisk binary compilation is split into two parts - first part only compiles "magisk".
* The python build script will load the magisk main binary and compress with lzma2, dumping
* the results into "dump.h". The "magisk" binary is embedded into this binary, and will
* get extracted to the overlay folder along with init.magisk.rc.
*
* This tool does all pre-init operations to setup a Magisk environment, which pathces rootfs
* on the fly, providing fundamental support such as init, init.rc, and sepolicy patching.
*
* Magiskinit is also responsible for constructing a proper rootfs on skip_initramfs devices.
* On skip_initramfs devices, it will parse kernel cmdline, mount sysfs, parse through
* uevent files to make the system (or vendor if available) block device node, then copy
* rootfs files from system.
*
* This tool will be replaced with the real init to continue the boot process, but hardlinks are
* preserved as it also provides CLI for sepolicy patching (magiskpolicy)
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <dirent.h>
#include <fcntl.h>
#include <libgen.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mount.h>
#include <sys/mman.h>
#include <sys/sendfile.h>
#include <sys/sysmacros.h>
#include <xz.h>
#include "binaries.h"
#include "binaries_arch.h"
#include "magiskrc.h"
#include "utils.h"
#include "daemon.h"
#include "magisk.h"
#include "flags.h"
#define DEFAULT_DT_DIR "/proc/device-tree/firmware/android"
int (*init_applet_main[]) (int, char *[]) = { magiskpolicy_main, magiskpolicy_main, NULL };
struct cmdline {
char skip_initramfs;
char slot[3];
char dt_dir[128];
};
struct device {
dev_t major;
dev_t minor;
char devname[32];
char partname[32];
char path[64];
};
static void parse_cmdline(struct cmdline *cmd) {
// cleanup
memset(cmd, 0, sizeof(*cmd));
char cmdline[4096];
int fd = open("/proc/cmdline", O_RDONLY | O_CLOEXEC);
cmdline[read(fd, cmdline, sizeof(cmdline))] = '\0';
close(fd);
for (char *tok = strtok(cmdline, " "); tok; tok = strtok(NULL, " ")) {
if (strncmp(tok, "androidboot.slot_suffix", 23) == 0) {
sscanf(tok, "androidboot.slot_suffix=%s", cmd->slot);
} else if (strncmp(tok, "androidboot.slot", 16) == 0) {
cmd->slot[0] = '_';
sscanf(tok, "androidboot.slot=%c", cmd->slot + 1);
} else if (strcmp(tok, "skip_initramfs") == 0) {
cmd->skip_initramfs = 1;
} else if (strncmp(tok, "androidboot.android_dt_dir", 26) == 0) {
sscanf(tok, "androidboot.android_dt_dir=%s", cmd->dt_dir);
}
}
if (cmd->dt_dir[0] == '\0')
strcpy(cmd->dt_dir, DEFAULT_DT_DIR);
LOGD("cmdline: skip_initramfs[%d] slot[%s] dt_dir[%s]\n", cmd->skip_initramfs, cmd->slot, cmd->dt_dir);
}
static void parse_device(struct device *dev, const char *uevent) {
dev->partname[0] = '\0';
FILE *fp = xfopen(uevent, "r");
char buf[64];
while (fgets(buf, sizeof(buf), fp)) {
if (strncmp(buf, "MAJOR", 5) == 0) {
sscanf(buf, "MAJOR=%ld", (long*) &dev->major);
} else if (strncmp(buf, "MINOR", 5) == 0) {
sscanf(buf, "MINOR=%ld", (long*) &dev->minor);
} else if (strncmp(buf, "DEVNAME", 7) == 0) {
sscanf(buf, "DEVNAME=%s", dev->devname);
} else if (strncmp(buf, "PARTNAME", 8) == 0) {
sscanf(buf, "PARTNAME=%s", dev->partname);
}
}
fclose(fp);
LOGD("%s [%s] (%u, %u)\n", dev->devname, dev->partname, (unsigned) dev->major, (unsigned) dev->minor);
}
static int setup_block(struct device *dev, const char *partname) {
char path[128];
struct dirent *entry;
DIR *dir = opendir("/sys/dev/block");
if (dir == NULL)
return 1;
int found = 0;
while ((entry = readdir(dir))) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
sprintf(path, "/sys/dev/block/%s/uevent", entry->d_name);
parse_device(dev, path);
if (strcasecmp(dev->partname, partname) == 0) {
sprintf(dev->path, "/dev/block/%s", dev->devname);
found = 1;
break;
}
}
closedir(dir);
if (!found)
return 1;
mkdir("/dev", 0755);
mkdir("/dev/block", 0755);
mknod(dev->path, S_IFBLK | 0600, makedev(dev->major, dev->minor));
return 0;
}
static int read_fstab_dt(const struct cmdline *cmd, const char *mnt_point, char *partname) {
char buf[128];
struct stat st;
sprintf(buf, "/%s", mnt_point);
lstat(buf, &st);
// Don't early mount if the mount point is symlink
if (S_ISLNK(st.st_mode))
return 1;
sprintf(buf, "%s/fstab/%s/dev", cmd->dt_dir, mnt_point);
if (access(buf, F_OK) == 0) {
int fd = open(buf, O_RDONLY | O_CLOEXEC);
read(fd, buf, sizeof(buf));
close(fd);
char *name = strrchr(buf, '/') + 1;
sprintf(partname, "%s%s", name, strend(name, cmd->slot) ? cmd->slot : "");
return 0;
}
return 1;
}
static int verify_precompiled() {
DIR *dir;
struct dirent *entry;
int fd;
char sys_sha[64], ven_sha[64];
// init the strings with different value
sys_sha[0] = 0;
ven_sha[0] = 1;
dir = opendir(NONPLAT_POLICY_DIR);
while ((entry = readdir(dir))) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
if (strend(entry->d_name, ".sha256") == 0) {
fd = openat(dirfd(dir), entry->d_name, O_RDONLY | O_CLOEXEC);
read(fd, ven_sha, sizeof(ven_sha));
close(fd);
break;
}
}
closedir(dir);
dir = opendir(PLAT_POLICY_DIR);
while ((entry = readdir(dir))) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
if (strend(entry->d_name, ".sha256") == 0) {
fd = openat(dirfd(dir), entry->d_name, O_RDONLY | O_CLOEXEC);
read(fd, sys_sha, sizeof(sys_sha));
close(fd);
break;
}
}
closedir(dir);
LOGD("sys_sha[%.*s]\nven_sha[%.*s]\n", sizeof(sys_sha), sys_sha, sizeof(ven_sha), ven_sha);
return memcmp(sys_sha, ven_sha, sizeof(sys_sha)) == 0;
}
static int patch_sepolicy() {
int init_patch = 0;
if (access(SPLIT_PRECOMPILE, R_OK) == 0 && verify_precompiled()) {
init_patch = 1;
load_policydb(SPLIT_PRECOMPILE);
} else if (access(SPLIT_PLAT_CIL, R_OK) == 0) {
init_patch = 1;
compile_split_cil();
} else if (access("/sepolicy", R_OK) == 0) {
load_policydb("/sepolicy");
} else {
return 1;
}
sepol_magisk_rules();
sepol_allow(SEPOL_PROC_DOMAIN, ALL, ALL, ALL);
dump_policydb("/sepolicy");
// Remove the stupid debug sepolicy and use our own
if (access("/sepolicy_debug", F_OK) == 0) {
unlink("/sepolicy_debug");
link("/sepolicy", "/sepolicy_debug");
}
if (init_patch) {
// Force init to load /sepolicy
void *addr;
size_t size;
mmap_rw("/init", &addr, &size);
for (int i = 0; i < size; ++i) {
if (memcmp(addr + i, SPLIT_PLAT_CIL, sizeof(SPLIT_PLAT_CIL) - 1) == 0) {
memcpy(addr + i + sizeof(SPLIT_PLAT_CIL) - 4, "xxx", 3);
break;
}
}
munmap(addr, size);
}
return 0;
}
static int unxz(int fd, const void *buf, size_t size) {
uint8_t out[8192];
xz_crc32_init();
struct xz_dec *dec = xz_dec_init(XZ_DYNALLOC, 1 << 26);
struct xz_buf b = {
.in = buf,
.in_pos = 0,
.in_size = size,
.out = out,
.out_pos = 0,
.out_size = sizeof(out)
};
enum xz_ret ret;
do {
ret = xz_dec_run(dec, &b);
if (ret != XZ_OK && ret != XZ_STREAM_END)
return 1;
write(fd, out, b.out_pos);
b.out_pos = 0;
} while (b.in_pos != size);
return 0;
}
static int dump_magisk(const char *path, mode_t mode) {
int fd = creat(path, mode);
if (fd < 0)
return 1;
if (unxz(fd, magisk_xz, sizeof(magisk_xz)))
return 1;
close(fd);
return 0;
}
static int dump_manager(const char *path, mode_t mode) {
int fd = creat(path, mode);
if (fd < 0)
return 1;
if (unxz(fd, manager_xz, sizeof(manager_xz)))
return 1;
close(fd);
return 0;
}
static int dump_magiskrc(const char *path, mode_t mode) {
int fd = creat(path, mode);
if (fd < 0)
return 1;
char startup_svc[8], late_start_svc[8], rc[sizeof(magiskrc) + 100];
gen_rand_str(startup_svc, sizeof(startup_svc));
do {
gen_rand_str(late_start_svc, sizeof(late_start_svc));
} while (strcmp(startup_svc, late_start_svc) == 0);
int size = sprintf(rc, magiskrc, startup_svc, startup_svc, late_start_svc);
xwrite(fd, rc, size);
close(fd);
return 0;
}
static void patch_socket_name(const char *path) {
void *buf;
char name[sizeof(MAIN_SOCKET)];
size_t size;
mmap_rw(path, &buf, &size);
for (int i = 0; i < size; ++i) {
if (memcmp(buf + i, MAIN_SOCKET, sizeof(MAIN_SOCKET)) == 0) {
gen_rand_str(name, sizeof(name));
memcpy(buf + i, name, sizeof(name));
i += sizeof(name);
}
if (memcmp(buf + i, LOG_SOCKET, sizeof(LOG_SOCKET)) == 0) {
gen_rand_str(name, sizeof(name));
memcpy(buf + i, name, sizeof(name));
i += sizeof(name);
}
}
munmap(buf, size);
}
int main(int argc, char *argv[]) {
umask(0);
for (int i = 0; init_applet[i]; ++i) {
if (strcmp(basename(argv[0]), init_applet[i]) == 0)
return (*init_applet_main[i])(argc, argv);
}
if (argc > 1 && strcmp(argv[1], "-x") == 0) {
if (strcmp(argv[2], "magisk") == 0)
return dump_magisk(argv[3], 0755);
else if (strcmp(argv[2], "manager") == 0)
return dump_manager(argv[3], 0644);
else if (strcmp(argv[2], "magiskrc") == 0)
return dump_magiskrc(argv[3], 0755);
}
#ifdef MAGISK_DEBUG
log_cb.d = vprintf;
#endif
// Prevent file descriptor confusion
mknod("/null", S_IFCHR | 0666, makedev(1, 3));
int null = open("/null", O_RDWR | O_CLOEXEC);
unlink("/null");
xdup3(null, STDIN_FILENO, O_CLOEXEC);
xdup3(null, STDOUT_FILENO, O_CLOEXEC);
xdup3(null, STDERR_FILENO, O_CLOEXEC);
if (null > STDERR_FILENO)
close(null);
// Backup self
rename("/init", "/init.bak");
// Communicate with kernel using procfs and sysfs
mkdir("/proc", 0755);
xmount("proc", "/proc", "proc", 0, NULL);
mkdir("/sys", 0755);
xmount("sysfs", "/sys", "sysfs", 0, NULL);
struct cmdline cmd;
parse_cmdline(&cmd);
/* ***********
* Initialize
* ***********/
int root = open("/", O_RDONLY | O_CLOEXEC);
int mnt_system = 0;
int mnt_vendor = 0;
if (cmd.skip_initramfs) {
// Clear rootfs
excl_list = (const char *[]) { "overlay", ".backup", "proc", "sys", "init.bak", NULL };
frm_rf(root);
} else {
// Revert original init binary
link("/.backup/init", "/init");
}
// Do not go further if system_root device is booting as recovery
if (!cmd.skip_initramfs && access("/sbin/recovery", F_OK) == 0) {
// Remove Magisk traces
rm_rf("/.backup");
goto exec_init;
}
/* ************
* Early Mount
* ************/
struct device dev;
char partname[32];
if (cmd.skip_initramfs) {
sprintf(partname, "system%s", cmd.slot);
setup_block(&dev, partname);
xmkdir("/system_root", 0755);
xmount(dev.path, "/system_root", "ext4", MS_RDONLY, NULL);
int system_root = open("/system_root", O_RDONLY | O_CLOEXEC);
// Clone rootfs except /system
excl_list = (const char *[]) { "system", NULL };
clone_dir(system_root, root);
close(system_root);
xmkdir("/system", 0755);
xmount("/system_root/system", "/system", NULL, MS_BIND, NULL);
} else if (read_fstab_dt(&cmd, "system", partname) == 0) {
setup_block(&dev, partname);
xmount(dev.path, "/system", "ext4", MS_RDONLY, NULL);
mnt_system = 1;
}
if (read_fstab_dt(&cmd, "vendor", partname) == 0) {
setup_block(&dev, partname);
xmount(dev.path, "/vendor", "ext4", MS_RDONLY, NULL);
mnt_vendor = 1;
}
/* ****************
* Ramdisk Patches
* ****************/
// Handle ramdisk overlays
int fd = open("/overlay", O_RDONLY | O_CLOEXEC);
if (fd >= 0) {
mv_dir(fd, root);
close(fd);
rmdir("/overlay");
}
// Patch init.rc to load magisk scripts
int injected = 0;
char tok[4096];
FILE *fp = xfopen("/init.rc", "r");
fd = creat("/init.rc.new", 0750);
while(fgets(tok, sizeof(tok), fp)) {
if (!injected && strncmp(tok, "import", 6) == 0) {
if (strstr(tok, "init.magisk.rc")) {
injected = 1;
} else {
xwrite(fd, "import /init.magisk.rc\n", 23);
injected = 1;
}
} else if (strstr(tok, "selinux.reload_policy")) {
// Do not allow sepolicy patch
continue;
}
xwrite(fd, tok, strlen(tok));
}
fclose(fp);
close(fd);
rename("/init.rc.new", "/init.rc");
// Patch sepolicy
patch_sepolicy();
// Dump binaries
dump_magiskrc(MAGISKRC, 0750);
dump_magisk("/sbin/magisk", 0755);
patch_socket_name("/sbin/magisk");
rename("/init.bak", "/sbin/magiskinit");
exec_init:
// Clean up
close(root);
umount("/proc");
umount("/sys");
if (mnt_system)
umount("/system");
if (mnt_vendor)
umount("/vendor");
execv("/init", argv);
}