id
int64
0
877k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
66
repo_stars
int64
94
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
11 values
repo_extraction_date
stringclasses
197 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
0
package.cpp
topjohnwu_Magisk/native/src/core/package.cpp
#include <base.hpp> #include <consts.hpp> #include <core.hpp> #include <db.hpp> #include <flags.h> using namespace std; using rust::Vec; #define ENFORCE_SIGNATURE (!MAGISK_DEBUG) // These functions will be called on every single zygote process specialization and su request, // so performance is absolutely critical. Most operations should either have its result cached // or simply skipped unless necessary. static pthread_mutex_t pkg_lock = PTHREAD_MUTEX_INITIALIZER; // pkg_lock protects all following variables static int stub_apk_fd = -1; static int repackaged_app_id = -1; // Only used by dyn static string repackaged_pkg; static Vec<uint8_t> repackaged_cert; static Vec<uint8_t> trusted_cert; static map<int, pair<string, time_t>> user_to_check; enum status { INSTALLED, NO_INSTALLED, CERT_MISMATCH, }; static bool operator==(const Vec<uint8_t> &a, const Vec<uint8_t> &b) { return a.size() == b.size() && memcmp(a.data(), b.data(), a.size()) == 0; } // app_id = app_no + AID_APP_START // app_no range: [0, 9999] vector<bool> get_app_no_list() { vector<bool> list; auto data_dir = xopen_dir(APP_DATA_DIR); if (!data_dir) return list; dirent *entry; while ((entry = xreaddir(data_dir.get()))) { // For each user int dfd = xopenat(dirfd(data_dir.get()), entry->d_name, O_RDONLY); if (auto dir = xopen_dir(dfd)) { while ((entry = xreaddir(dir.get()))) { // For each package struct stat st{}; xfstatat(dfd, entry->d_name, &st, 0); int app_id = to_app_id(st.st_uid); if (app_id >= AID_APP_START && app_id <= AID_APP_END) { int app_no = app_id - AID_APP_START; if (list.size() <= app_no) { list.resize(app_no + 1); } list[app_no] = true; } } } else { close(dfd); } } return list; } void preserve_stub_apk() { mutex_guard g(pkg_lock); string stub_path = get_magisk_tmp() + "/stub.apk"s; stub_apk_fd = xopen(stub_path.data(), O_RDONLY | O_CLOEXEC); unlink(stub_path.data()); trusted_cert = read_certificate(stub_apk_fd, MAGISK_VER_CODE); lseek(stub_apk_fd, 0, SEEK_SET); } static void install_stub() { if (stub_apk_fd < 0) return; struct stat st{}; fstat(stub_apk_fd, &st); char apk[] = "/data/stub.apk"; int dfd = xopen(apk, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); xsendfile(dfd, stub_apk_fd, nullptr, st.st_size); lseek(stub_apk_fd, 0, SEEK_SET); close(dfd); install_apk(apk); } static status check_dyn(int user, string &pkg) { struct stat st{}; char apk[PATH_MAX]; ssprintf(apk, sizeof(apk), "%s/%d/%s/dyn/current.apk", APP_DATA_DIR, user, pkg.data()); int dyn = open(apk, O_RDONLY | O_CLOEXEC); if (dyn < 0) { LOGW("pkg: no dyn APK, ignore\n"); return NO_INSTALLED; } auto cert = read_certificate(dyn, MAGISK_VER_CODE); fstat(dyn, &st); close(dyn); if (cert.empty() || cert != trusted_cert) { LOGE("pkg: dyn APK signature mismatch: %s\n", apk); #if ENFORCE_SIGNATURE clear_pkg(pkg.data(), user); return CERT_MISMATCH; #endif } repackaged_app_id = to_app_id(st.st_uid); user_to_check[user] = make_pair(apk, st.st_ctim.tv_sec); return INSTALLED; } static status check_stub(int user, string &pkg) { struct stat st{}; byte_array<PATH_MAX> buf; find_apk_path(pkg, buf); string apk((const char *) buf.buf(), buf.sz()); int fd = xopen(apk.data(), O_RDONLY | O_CLOEXEC); if (fd < 0) return NO_INSTALLED; auto cert = read_certificate(fd, -1); fstat(fd, &st); close(fd); if (cert.empty() || (pkg == repackaged_pkg && cert != repackaged_cert)) { LOGE("pkg: repackaged APK signature invalid: %s\n", apk.data()); uninstall_pkg(pkg.data()); return CERT_MISMATCH; } repackaged_pkg.swap(pkg); repackaged_cert.swap(cert); user_to_check[user] = make_pair(apk, st.st_ctim.tv_sec); return INSTALLED; } static status check_orig(int user) { struct stat st{}; byte_array<PATH_MAX> buf; find_apk_path(JAVA_PACKAGE_NAME, buf); string apk((const char *) buf.buf(), buf.sz()); int fd = xopen(apk.data(), O_RDONLY | O_CLOEXEC); if (fd < 0) return NO_INSTALLED; auto cert = read_certificate(fd, MAGISK_VER_CODE); fstat(fd, &st); close(fd); if (cert.empty() || cert != trusted_cert) { LOGE("pkg: APK signature mismatch: %s\n", apk.data()); #if ENFORCE_SIGNATURE uninstall_pkg(JAVA_PACKAGE_NAME); return CERT_MISMATCH; #endif } user_to_check[user] = make_pair(apk, st.st_ctim.tv_sec); return INSTALLED; } static int get_pkg_uid(int user, const char *pkg) { char path[PATH_MAX]; struct stat st{}; ssprintf(path, sizeof(path), "%s/%d/%s", APP_DATA_DIR, user, pkg); if (stat(path, &st) == 0) { return st.st_uid; } return -1; } int get_manager(int user, string *pkg, bool install) { mutex_guard g(pkg_lock); struct stat st{}; const auto &[path, time] = user_to_check[user]; if (stat(path.data(), &st) == 0 && st.st_ctim.tv_sec == time) { // no APK if (path == "/data/system/packages.xml") { if (install) install_stub(); if (pkg) pkg->clear(); return -1; } // dyn APK is still the same if (path.starts_with(APP_DATA_DIR)) { if (pkg) *pkg = repackaged_pkg; return user * AID_USER_OFFSET + repackaged_app_id; } // stub APK is still the same if (!repackaged_pkg.empty()) { if (check_dyn(user, repackaged_pkg) == INSTALLED) { if (pkg) *pkg = repackaged_pkg; return user * AID_USER_OFFSET + repackaged_app_id; } else { if (pkg) pkg->clear(); return -1; } } // orig APK is still the same int uid = get_pkg_uid(user, JAVA_PACKAGE_NAME); if (uid < 0) { if (pkg) pkg->clear(); return -1; } else { if (pkg) *pkg = JAVA_PACKAGE_NAME; return uid; } } db_strings str; get_db_strings(str, SU_MANAGER); if (!str[SU_MANAGER].empty()) { switch (check_stub(user, str[SU_MANAGER])) { case INSTALLED: if (check_dyn(user, repackaged_pkg) == INSTALLED) { if (pkg) *pkg = repackaged_pkg; return user * AID_USER_OFFSET + repackaged_app_id; } else { if (pkg) pkg->clear(); return -1; } case CERT_MISMATCH: install = true; case NO_INSTALLED: break; } } repackaged_pkg.clear(); repackaged_cert.clear(); switch (check_orig(user)) { case INSTALLED: { int uid = get_pkg_uid(user, JAVA_PACKAGE_NAME); if (uid < 0) { if (pkg) pkg->clear(); return -1; } else { if (pkg) *pkg = JAVA_PACKAGE_NAME; return uid; } } case CERT_MISMATCH: install = true; case NO_INSTALLED: break; } auto xml = "/data/system/packages.xml"; stat(xml, &st); user_to_check[user] = make_pair(xml, st.st_ctim.tv_sec); if (install) install_stub(); if (pkg) pkg->clear(); return -1; }
7,711
C++
.cpp
232
25.706897
95
0.561385
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1
selinux.cpp
topjohnwu_Magisk/native/src/core/selinux.cpp
#include <unistd.h> #include <sys/syscall.h> #include <sys/xattr.h> #include <consts.hpp> #include <base.hpp> #include <selinux.hpp> #include <core.hpp> #include <flags.h> using namespace std; int setcon(const char *con) { int fd = open("/proc/self/attr/current", O_WRONLY | O_CLOEXEC); if (fd < 0) return fd; size_t len = strlen(con) + 1; int rc = write(fd, con, len); close(fd); return rc != len; } int getfilecon(const char *path, byte_data con) { return syscall(__NR_getxattr, path, XATTR_NAME_SELINUX, con.buf(), con.sz()); } int lgetfilecon(const char *path, byte_data con) { return syscall(__NR_lgetxattr, path, XATTR_NAME_SELINUX, con.buf(), con.sz()); } int fgetfilecon(int fd, byte_data con) { return syscall(__NR_fgetxattr, fd, XATTR_NAME_SELINUX, con.buf(), con.sz()); } int setfilecon(const char *path, const char *con) { return syscall(__NR_setxattr, path, XATTR_NAME_SELINUX, con, strlen(con) + 1, 0); } int lsetfilecon(const char *path, const char *con) { return syscall(__NR_lsetxattr, path, XATTR_NAME_SELINUX, con, strlen(con) + 1, 0); } int fsetfilecon(int fd, const char *con) { return syscall(__NR_fsetxattr, fd, XATTR_NAME_SELINUX, con, strlen(con) + 1, 0); } int getfilecon_at(int dirfd, const char *name, byte_data con) { char path[4096]; fd_pathat(dirfd, name, path, sizeof(path)); return lgetfilecon(path, con); } void setfilecon_at(int dirfd, const char *name, const char *con) { char path[4096]; fd_pathat(dirfd, name, path, sizeof(path)); lsetfilecon(path, con); } #define UNLABEL_CON "u:object_r:unlabeled:s0" #define SYSTEM_CON "u:object_r:system_file:s0" #define ADB_CON "u:object_r:adb_data_file:s0" #define ROOT_CON "u:object_r:rootfs:s0" static void restore_syscon_from_null(int dirfd) { struct dirent *entry; char con[1024]; if (fgetfilecon(dirfd, { con, sizeof(con) }) >= 0) { if (con[0] == '\0' || strcmp(con, UNLABEL_CON) == 0) fsetfilecon(dirfd, SYSTEM_CON); } auto dir = xopen_dir(dirfd); while ((entry = xreaddir(dir.get()))) { int fd = openat(dirfd, entry->d_name, O_RDONLY | O_CLOEXEC); if (entry->d_type == DT_DIR) { restore_syscon_from_null(fd); continue; } else if (entry->d_type == DT_REG) { if (fgetfilecon(fd, { con, sizeof(con) }) >= 0) { if (con[0] == '\0' || strcmp(con, UNLABEL_CON) == 0) fsetfilecon(fd, SYSTEM_CON); } } else if (entry->d_type == DT_LNK) { if (getfilecon_at(dirfd, entry->d_name, { con, sizeof(con) }) >= 0) { if (con[0] == '\0' || strcmp(con, UNLABEL_CON) == 0) setfilecon_at(dirfd, entry->d_name, SYSTEM_CON); } } close(fd); } } static void restore_syscon(int dirfd) { struct dirent *entry; fsetfilecon(dirfd, SYSTEM_CON); fchown(dirfd, 0, 0); auto dir = xopen_dir(dirfd); while ((entry = xreaddir(dir.get()))) { int fd = xopenat(dirfd, entry->d_name, O_RDONLY | O_CLOEXEC); if (entry->d_type == DT_DIR) { restore_syscon(fd); continue; } else if (entry->d_type) { fsetfilecon(fd, SYSTEM_CON); fchown(fd, 0, 0); } close(fd); } } void restorecon() { int fd = xopen("/sys/fs/selinux/context", O_WRONLY | O_CLOEXEC); if (write(fd, ADB_CON, sizeof(ADB_CON)) >= 0) lsetfilecon(SECURE_DIR, ADB_CON); close(fd); lsetfilecon(MODULEROOT, SYSTEM_CON); restore_syscon_from_null(xopen(MODULEROOT, O_RDONLY | O_CLOEXEC)); restore_syscon(xopen(DATABIN, O_RDONLY | O_CLOEXEC)); } void restore_tmpcon() { const char *tmp = get_magisk_tmp(); if (tmp == "/sbin"sv) setfilecon(tmp, ROOT_CON); else chmod(tmp, 0711); auto dir = xopen_dir(tmp); int dfd = dirfd(dir.get()); for (dirent *entry; (entry = xreaddir(dir.get()));) setfilecon_at(dfd, entry->d_name, SYSTEM_CON); string logd = tmp + "/"s LOG_PIPE; setfilecon(logd.data(), MAGISK_LOG_CON); }
4,154
C++
.cpp
116
30.12931
86
0.606227
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2
applets.cpp
topjohnwu_Magisk/native/src/core/applets.cpp
#include <libgen.h> #include <sys/types.h> #include <sys/stat.h> #include <consts.hpp> #include <selinux.hpp> #include <base.hpp> using namespace std; struct Applet { string_view name; int (*fn)(int, char *[]); }; constexpr Applet applets[] = { { "su", su_client_main }, { "resetprop", resetprop_main }, }; constexpr Applet private_applets[] = { { "zygisk", zygisk_main }, }; int main(int argc, char *argv[]) { if (argc < 1) return 1; cmdline_logging(); init_argv0(argc, argv); string_view argv0 = basename(argv[0]); umask(0); if (argv[0][0] == '\0') { // When argv[0] is an empty string, we're calling private applets if (argc < 2) return 1; --argc; ++argv; for (const auto &app : private_applets) { if (argv[0] == app.name) { return app.fn(argc, argv); } } fprintf(stderr, "%s: applet not found\n", argv[0]); return 1; } if (argv0 == "magisk" || argv0 == "magisk32" || argv0 == "magisk64") { if (argc > 1 && argv[1][0] != '-') { // Calling applet with "magisk [applet] args..." --argc; ++argv; argv0 = argv[0]; } else { return magisk_main(argc, argv); } } for (const auto &app : applets) { if (argv0 == app.name) { return app.fn(argc, argv); } } fprintf(stderr, "%s: applet not found\n", argv0.data()); return 1; }
1,537
C++
.cpp
57
20.350877
74
0.521117
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3
daemon.cpp
topjohnwu_Magisk/native/src/core/daemon.cpp
#include <csignal> #include <libgen.h> #include <sys/un.h> #include <sys/mount.h> #include <consts.hpp> #include <base.hpp> #include <core.hpp> #include <selinux.hpp> #include <db.hpp> #include <flags.h> using namespace std; int SDK_INT = -1; static struct stat self_st; static map<int, poll_callback> *poll_map; static vector<pollfd> *poll_fds; static int poll_ctrl; enum { POLL_CTRL_NEW, POLL_CTRL_RM, }; void register_poll(const pollfd *pfd, poll_callback callback) { if (gettid() == getpid()) { // On main thread, directly modify poll_map->try_emplace(pfd->fd, callback); poll_fds->emplace_back(*pfd); } else { // Send it to poll_ctrl write_int(poll_ctrl, POLL_CTRL_NEW); xwrite(poll_ctrl, pfd, sizeof(*pfd)); xwrite(poll_ctrl, &callback, sizeof(callback)); } } void unregister_poll(int fd, bool auto_close) { if (fd < 0) return; if (gettid() == getpid()) { // On main thread, directly modify poll_map->erase(fd); for (auto &poll_fd : *poll_fds) { if (poll_fd.fd == fd) { if (auto_close) { close(poll_fd.fd); } // Cannot modify while iterating, invalidate it instead // It will be removed in the next poll loop poll_fd.fd = -1; break; } } } else { // Send it to poll_ctrl write_int(poll_ctrl, POLL_CTRL_RM); write_int(poll_ctrl, fd); write_int(poll_ctrl, auto_close); } } void clear_poll() { if (poll_fds) { for (auto &poll_fd : *poll_fds) { close(poll_fd.fd); } } delete poll_fds; delete poll_map; poll_fds = nullptr; poll_map = nullptr; } static void poll_ctrl_handler(pollfd *pfd) { int code = read_int(pfd->fd); switch (code) { case POLL_CTRL_NEW: { pollfd new_fd{}; poll_callback cb; xxread(pfd->fd, &new_fd, sizeof(new_fd)); xxread(pfd->fd, &cb, sizeof(cb)); register_poll(&new_fd, cb); break; } case POLL_CTRL_RM: { int fd = read_int(pfd->fd); bool auto_close = read_int(pfd->fd); unregister_poll(fd, auto_close); break; } default: __builtin_unreachable(); } } [[noreturn]] static void poll_loop() { // Register poll_ctrl auto pipefd = array<int, 2>{-1, -1}; xpipe2(pipefd, O_CLOEXEC); poll_ctrl = pipefd[1]; pollfd poll_ctrl_pfd = { pipefd[0], POLLIN, 0 }; register_poll(&poll_ctrl_pfd, poll_ctrl_handler); for (;;) { if (poll(poll_fds->data(), poll_fds->size(), -1) <= 0) continue; // MUST iterate with index because any poll_callback could add new elements to poll_fds for (int i = 0; i < poll_fds->size();) { auto &pfd = (*poll_fds)[i]; if (pfd.revents) { if (pfd.revents & POLLERR || pfd.revents & POLLNVAL) { poll_map->erase(pfd.fd); poll_fds->erase(poll_fds->begin() + i); continue; } if (auto it = poll_map->find(pfd.fd); it != poll_map->end()) { it->second(&pfd); } } ++i; } } } const MagiskD &MagiskD::get() { return *reinterpret_cast<const MagiskD*>(&rust::get_magiskd()); } const rust::MagiskD *MagiskD::operator->() const { return reinterpret_cast<const rust::MagiskD*>(this); } const rust::MagiskD &MagiskD::as_rust() const { return *operator->(); } void MagiskD::reboot() const { if (as_rust().is_recovery()) exec_command_sync("/system/bin/reboot", "recovery"); else exec_command_sync("/system/bin/reboot"); } static void handle_request_async(int client, int code, const sock_cred &cred) { switch (code) { case +RequestCode::DENYLIST: denylist_handler(client, &cred); break; case +RequestCode::SUPERUSER: su_daemon_handler(client, &cred); break; case +RequestCode::ZYGOTE_RESTART: LOGI("** zygote restarted\n"); prune_su_access(); scan_deny_apps(); reset_zygisk(false); close(client); break; case +RequestCode::SQLITE_CMD: exec_sql(client); break; case +RequestCode::REMOVE_MODULES: { int do_reboot = read_int(client); remove_modules(); write_int(client, 0); close(client); if (do_reboot) { MagiskD::get().reboot(); } break; } case +RequestCode::ZYGISK: zygisk_handler(client, &cred); break; default: __builtin_unreachable(); } } static void handle_request_sync(int client, int code) { switch (code) { case +RequestCode::CHECK_VERSION: #if MAGISK_DEBUG write_string(client, MAGISK_VERSION ":MAGISK:D"); #else write_string(client, MAGISK_VERSION ":MAGISK:R"); #endif break; case +RequestCode::CHECK_VERSION_CODE: write_int(client, MAGISK_VER_CODE); break; case +RequestCode::START_DAEMON: MagiskD::get()->setup_logfile(); break; case +RequestCode::STOP_DAEMON: { // Unmount all overlays denylist_handler(-1, nullptr); // Restore native bridge property auto nb = get_prop(NBPROP); auto len = sizeof(ZYGISKLDR) - 1; if (nb == ZYGISKLDR) { set_prop(NBPROP, "0"); } else if (nb.size() > len) { set_prop(NBPROP, nb.data() + len); } write_int(client, 0); // Terminate the daemon! exit(0); } default: __builtin_unreachable(); } } static bool is_client(pid_t pid) { // Verify caller is the same as server char path[32]; sprintf(path, "/proc/%d/exe", pid); struct stat st{}; return !(stat(path, &st) || st.st_dev != self_st.st_dev || st.st_ino != self_st.st_ino); } static void handle_request(pollfd *pfd) { owned_fd client = xaccept4(pfd->fd, nullptr, nullptr, SOCK_CLOEXEC); // Verify client credentials sock_cred cred; bool is_root; bool is_zygote; int code; if (!get_client_cred(client, &cred)) { // Client died return; } is_root = cred.uid == AID_ROOT; is_zygote = cred.context == "u:r:zygote:s0"; if (!is_root && !is_zygote && !is_client(cred.pid)) { // Unsupported client state write_int(client, +RespondCode::ACCESS_DENIED); return; } code = read_int(client); if (code < 0 || code >= +RequestCode::END || code == +RequestCode::_SYNC_BARRIER_ || code == +RequestCode::_STAGE_BARRIER_) { // Unknown request code return; } // Check client permissions switch (code) { case +RequestCode::POST_FS_DATA: case +RequestCode::LATE_START: case +RequestCode::BOOT_COMPLETE: case +RequestCode::ZYGOTE_RESTART: case +RequestCode::SQLITE_CMD: case +RequestCode::DENYLIST: case +RequestCode::STOP_DAEMON: if (!is_root) { write_int(client, +RespondCode::ROOT_REQUIRED); return; } break; case +RequestCode::REMOVE_MODULES: if (!is_root && cred.uid != AID_SHELL) { write_int(client, +RespondCode::ACCESS_DENIED); return; } break; case +RequestCode::ZYGISK: if (!is_zygote) { // Invalid client context write_int(client, +RespondCode::ACCESS_DENIED); return; } break; default: break; } write_int(client, +RespondCode::OK); if (code < +RequestCode::_SYNC_BARRIER_) { handle_request_sync(client, code); } else if (code < +RequestCode::_STAGE_BARRIER_) { exec_task([=, fd = client.release()] { handle_request_async(fd, code, cred); }); } else { exec_task([=, fd = client.release()] { MagiskD::get()->boot_stage_handler(fd, code); }); } } static void switch_cgroup(const char *cgroup, int pid) { char buf[32]; ssprintf(buf, sizeof(buf), "%s/cgroup.procs", cgroup); if (access(buf, F_OK) != 0) return; int fd = xopen(buf, O_WRONLY | O_APPEND | O_CLOEXEC); if (fd == -1) return; ssprintf(buf, sizeof(buf), "%d\n", pid); xwrite(fd, buf, strlen(buf)); close(fd); } static void daemon_entry() { android_logging(); // Block all signals sigset_t block_set; sigfillset(&block_set); pthread_sigmask(SIG_SETMASK, &block_set, nullptr); // Change process name set_nice_name("magiskd"); int fd = xopen("/dev/null", O_WRONLY); xdup2(fd, STDOUT_FILENO); xdup2(fd, STDERR_FILENO); if (fd > STDERR_FILENO) close(fd); fd = xopen("/dev/zero", O_RDONLY); xdup2(fd, STDIN_FILENO); if (fd > STDERR_FILENO) close(fd); setsid(); setcon(MAGISK_PROC_CON); rust::daemon_entry(); LOGI(NAME_WITH_VER(Magisk) " daemon started\n"); // Escape from cgroup int pid = getpid(); switch_cgroup("/acct", pid); switch_cgroup("/dev/cg2_bpf", pid); switch_cgroup("/sys/fs/cgroup", pid); if (get_prop("ro.config.per_app_memcg") != "false") { switch_cgroup("/dev/memcg/apps", pid); } // Get self stat xstat("/proc/self/exe", &self_st); // Get API level parse_prop_file("/system/build.prop", [](auto key, auto val) -> bool { if (key == "ro.build.version.sdk") { SDK_INT = parse_int(val); return false; } return true; }); if (SDK_INT < 0) { // In case some devices do not store this info in build.prop, fallback to getprop auto sdk = get_prop("ro.build.version.sdk"); if (!sdk.empty()) { SDK_INT = parse_int(sdk); } } LOGI("* Device API level: %d\n", SDK_INT); // Samsung workaround #7887 if (access("/system_ext/app/mediatek-res/mediatek-res.apk", F_OK) == 0) { set_prop("ro.vendor.mtk_model", "0"); } restore_tmpcon(); // Cleanups const char *tmp = get_magisk_tmp(); char path[64]; ssprintf(path, sizeof(path), "%s/" ROOTMNT, tmp); if (access(path, F_OK) == 0) { file_readline(true, path, [](string_view line) -> bool { umount2(line.data(), MNT_DETACH); return true; }); } if (getenv("REMOUNT_ROOT")) { xmount(nullptr, "/", nullptr, MS_REMOUNT | MS_RDONLY, nullptr); unsetenv("REMOUNT_ROOT"); } ssprintf(path, sizeof(path), "%s/" ROOTOVL, tmp); rm_rf(path); fd = xsocket(AF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0); sockaddr_un addr = {.sun_family = AF_LOCAL}; ssprintf(addr.sun_path, sizeof(addr.sun_path), "%s/" MAIN_SOCKET, tmp); unlink(addr.sun_path); if (xbind(fd, (sockaddr *) &addr, sizeof(addr))) exit(1); chmod(addr.sun_path, 0666); setfilecon(addr.sun_path, MAGISK_FILE_CON); xlisten(fd, 10); default_new(poll_map); default_new(poll_fds); default_new(module_list); // Register handler for main socket pollfd main_socket_pfd = { fd, POLLIN, 0 }; register_poll(&main_socket_pfd, handle_request); // Loop forever to listen for requests init_thread_pool(); poll_loop(); } const char *get_magisk_tmp() { static const char *path = nullptr; if (path == nullptr) { if (access("/debug_ramdisk/" INTLROOT, F_OK) == 0) { path = "/debug_ramdisk"; } else if (access("/sbin/" INTLROOT, F_OK) == 0) { path = "/sbin"; } else { path = ""; } } return path; } int connect_daemon(int req, bool create) { int fd = xsocket(AF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0); sockaddr_un addr = {.sun_family = AF_LOCAL}; const char *tmp = get_magisk_tmp(); ssprintf(addr.sun_path, sizeof(addr.sun_path), "%s/" MAIN_SOCKET, tmp); if (connect(fd, (sockaddr *) &addr, sizeof(addr))) { if (!create || getuid() != AID_ROOT) { LOGE("No daemon is currently running!\n"); close(fd); return -1; } char buf[64]; xreadlink("/proc/self/exe", buf, sizeof(buf)); if (tmp[0] == '\0' || !str_starts(buf, tmp)) { LOGE("Start daemon on magisk tmpfs\n"); close(fd); return -1; } if (fork_dont_care() == 0) { close(fd); daemon_entry(); } while (connect(fd, (sockaddr *) &addr, sizeof(addr))) usleep(10000); } write_int(fd, req); int res = read_int(fd); if (res < +RespondCode::ERROR || res >= +RespondCode::END) res = +RespondCode::ERROR; switch (res) { case +RespondCode::OK: break; case +RespondCode::ERROR: LOGE("Daemon error\n"); close(fd); return -1; case +RespondCode::ROOT_REQUIRED: LOGE("Root is required for this operation\n"); close(fd); return -1; case +RespondCode::ACCESS_DENIED: LOGE("Access denied\n"); close(fd); return -1; default: __builtin_unreachable(); } return fd; }
13,327
C++
.cpp
433
23.711316
95
0.565329
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4
scripting.cpp
topjohnwu_Magisk/native/src/core/scripting.cpp
#include <string> #include <vector> #include <sys/wait.h> #include <consts.hpp> #include <base.hpp> #include <selinux.hpp> #include <core.hpp> using namespace std; #define BBEXEC_CMD bbpath(), "sh" static const char *bbpath() { static string path; path = get_magisk_tmp(); path += "/" BBPATH "/busybox"; if (access(path.data(), X_OK) != 0) { path = DATABIN "/busybox"; } return path.data(); } static void set_script_env() { setenv("ASH_STANDALONE", "1", 1); char new_path[4096]; ssprintf(new_path, sizeof(new_path), "%s:%s", getenv("PATH"), get_magisk_tmp()); setenv("PATH", new_path, 1); if (zygisk_enabled) setenv("ZYGISK_ENABLED", "1", 1); }; void exec_script(const char *script) { exec_t exec { .pre_exec = set_script_env, .fork = fork_no_orphan }; exec_command_sync(exec, BBEXEC_CMD, script); } static timespec pfs_timeout; #define PFS_SETUP() \ if (pfs) { \ if (int pid = xfork()) { \ if (pid < 0) \ return; \ /* In parent process, simply wait for child to finish */ \ waitpid(pid, nullptr, 0); \ return; \ } \ timer_pid = xfork(); \ if (timer_pid == 0) { \ /* In timer process, count down */ \ clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &pfs_timeout, nullptr); \ exit(0); \ } \ } #define PFS_WAIT() \ if (pfs) { \ /* If we ran out of time, don't block */ \ if (timer_pid < 0) \ continue; \ if (int pid = waitpid(-1, nullptr, 0); pid == timer_pid) { \ LOGW("* post-fs-data scripts blocking phase timeout\n"); \ timer_pid = -1; \ } \ } #define PFS_DONE() \ if (pfs) { \ if (timer_pid > 0) \ kill(timer_pid, SIGKILL); \ exit(0); \ } void exec_common_scripts(const char *stage) { LOGI("* Running %s.d scripts\n", stage); char path[4096]; char *name = path + sprintf(path, SECURE_DIR "/%s.d", stage); auto dir = xopen_dir(path); if (!dir) return; bool pfs = stage == "post-fs-data"sv; int timer_pid = -1; if (pfs) { // Setup timer clock_gettime(CLOCK_MONOTONIC, &pfs_timeout); pfs_timeout.tv_sec += POST_FS_DATA_SCRIPT_MAX_TIME; } PFS_SETUP() *(name++) = '/'; int dfd = dirfd(dir.get()); for (dirent *entry; (entry = xreaddir(dir.get()));) { if (entry->d_type == DT_REG) { if (faccessat(dfd, entry->d_name, X_OK, 0) != 0) continue; LOGI("%s.d: exec [%s]\n", stage, entry->d_name); strcpy(name, entry->d_name); exec_t exec { .pre_exec = set_script_env, .fork = pfs ? xfork : fork_dont_care }; exec_command(exec, BBEXEC_CMD, path); PFS_WAIT() } } PFS_DONE() } static bool operator>(const timespec &a, const timespec &b) { if (a.tv_sec != b.tv_sec) return a.tv_sec > b.tv_sec; return a.tv_nsec > b.tv_nsec; } void exec_module_scripts(const char *stage, const vector<string_view> &modules) { LOGI("* Running module %s scripts\n", stage); if (modules.empty()) return; bool pfs = stage == "post-fs-data"sv; if (pfs) { timespec now{}; clock_gettime(CLOCK_MONOTONIC, &now); // If we had already timed out, treat it as service mode if (now > pfs_timeout) pfs = false; } int timer_pid = -1; PFS_SETUP() char path[4096]; for (auto &m : modules) { const char *module = m.data(); sprintf(path, MODULEROOT "/%s/%s.sh", module, stage); if (access(path, F_OK) == -1) continue; LOGI("%s: exec [%s.sh]\n", module, stage); exec_t exec { .pre_exec = set_script_env, .fork = pfs ? xfork : fork_dont_care }; exec_command(exec, BBEXEC_CMD, path); PFS_WAIT() } PFS_DONE() } constexpr char install_script[] = R"EOF( APK=%s log -t Magisk "pm_install: $APK" log -t Magisk "pm_install: $(pm install -g -r $APK 2>&1)" appops set %s REQUEST_INSTALL_PACKAGES allow rm -f $APK )EOF"; void install_apk(const char *apk) { setfilecon(apk, MAGISK_FILE_CON); char cmds[sizeof(install_script) + 4096]; ssprintf(cmds, sizeof(cmds), install_script, apk, JAVA_PACKAGE_NAME); exec_command_async("/system/bin/sh", "-c", cmds); } constexpr char uninstall_script[] = R"EOF( PKG=%s log -t Magisk "pm_uninstall: $PKG" log -t Magisk "pm_uninstall: $(pm uninstall $PKG 2>&1)" )EOF"; void uninstall_pkg(const char *pkg) { char cmds[sizeof(uninstall_script) + 256]; ssprintf(cmds, sizeof(cmds), uninstall_script, pkg); exec_command_async("/system/bin/sh", "-c", cmds); } constexpr char clear_script[] = R"EOF( PKG=%s USER=%d log -t Magisk "pm_clear: $PKG (user=$USER)" log -t Magisk "pm_clear: $(pm clear --user $USER $PKG 2>&1)" )EOF"; void clear_pkg(const char *pkg, int user_id) { char cmds[sizeof(clear_script) + 288]; ssprintf(cmds, sizeof(cmds), clear_script, pkg, user_id); exec_command_async("/system/bin/sh", "-c", cmds); } [[noreturn]] __printflike(2, 3) static void abort(FILE *fp, const char *fmt, ...) { va_list valist; va_start(valist, fmt); vfprintf(fp, fmt, valist); fprintf(fp, "\n\n"); va_end(valist); exit(1); } constexpr char install_module_script[] = R"EOF( exec %s sh -c ' . /data/adb/magisk/util_functions.sh install_module exit 0' )EOF"; void install_module(const char *file) { if (getuid() != 0) abort(stderr, "Run this command with root"); if (access(DATABIN, F_OK) || access(bbpath(), X_OK) || access(DATABIN "/util_functions.sh", F_OK)) abort(stderr, "Incomplete Magisk install"); if (access(file, F_OK)) abort(stderr, "'%s' does not exist", file); char *zip = realpath(file, nullptr); setenv("OUTFD", "1", 1); setenv("ZIPFILE", zip, 1); setenv("ASH_STANDALONE", "1", 1); setenv("MAGISKTMP", get_magisk_tmp(), 0); free(zip); int fd = xopen("/dev/null", O_RDONLY); xdup2(fd, STDERR_FILENO); close(fd); char cmds[256]; ssprintf(cmds, sizeof(cmds), install_module_script, bbpath()); const char *argv[] = { "/system/bin/sh", "-c", cmds, nullptr }; execve(argv[0], (char **) argv, environ); abort(stdout, "Failed to execute BusyBox shell"); }
6,402
C++
.cpp
206
25.805825
84
0.587768
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
5
bootstages.cpp
topjohnwu_Magisk/native/src/core/bootstages.cpp
#include <sys/mount.h> #include <sys/wait.h> #include <sys/sysmacros.h> #include <linux/input.h> #include <libgen.h> #include <set> #include <string> #include <consts.hpp> #include <db.hpp> #include <base.hpp> #include <core.hpp> #include <selinux.hpp> using namespace std; bool zygisk_enabled = false; /********* * Setup * *********/ static bool magisk_env() { char buf[4096]; LOGI("* Initializing Magisk environment\n"); ssprintf(buf, sizeof(buf), "%s/0/%s/install", APP_DATA_DIR, JAVA_PACKAGE_NAME); // Alternative binaries paths const char *alt_bin[] = { "/cache/data_adb/magisk", "/data/magisk", buf }; for (auto alt : alt_bin) { if (access(alt, F_OK) == 0) { rm_rf(DATABIN); cp_afc(alt, DATABIN); rm_rf(alt); } } rm_rf("/cache/data_adb"); // Directories in /data/adb chmod(SECURE_DIR, 0700); xmkdir(DATABIN, 0755); xmkdir(MODULEROOT, 0755); xmkdir(SECURE_DIR "/post-fs-data.d", 0755); xmkdir(SECURE_DIR "/service.d", 0755); restorecon(); if (access(DATABIN "/busybox", X_OK)) return false; ssprintf(buf, sizeof(buf), "%s/" BBPATH "/busybox", get_magisk_tmp()); mkdir(dirname(buf), 0755); cp_afc(DATABIN "/busybox", buf); exec_command_async(buf, "--install", "-s", dirname(buf)); // magisk32 and magiskpolicy are not installed into ramdisk and has to be copied // from data to magisk tmp if (access(DATABIN "/magisk32", X_OK) == 0) { ssprintf(buf, sizeof(buf), "%s/magisk32", get_magisk_tmp()); cp_afc(DATABIN "/magisk32", buf); } if (access(DATABIN "/magiskpolicy", X_OK) == 0) { ssprintf(buf, sizeof(buf), "%s/magiskpolicy", get_magisk_tmp()); cp_afc(DATABIN "/magiskpolicy", buf); } return true; } void unlock_blocks() { int fd, dev, OFF = 0; auto dir = xopen_dir("/dev/block"); if (!dir) return; dev = dirfd(dir.get()); for (dirent *entry; (entry = readdir(dir.get()));) { if (entry->d_type == DT_BLK) { if ((fd = openat(dev, entry->d_name, O_RDONLY | O_CLOEXEC)) < 0) continue; if (ioctl(fd, BLKROSET, &OFF) < 0) PLOGE("unlock %s", entry->d_name); close(fd); } } } #define test_bit(bit, array) (array[bit / 8] & (1 << (bit % 8))) static bool check_key_combo() { uint8_t bitmask[(KEY_MAX + 1) / 8]; vector<int> events; constexpr char name[] = "/dev/.ev"; // First collect candidate events that accepts volume down for (int minor = 64; minor < 96; ++minor) { if (xmknod(name, S_IFCHR | 0444, makedev(13, minor))) continue; int fd = open(name, O_RDONLY | O_CLOEXEC); unlink(name); if (fd < 0) continue; memset(bitmask, 0, sizeof(bitmask)); ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(bitmask)), bitmask); if (test_bit(KEY_VOLUMEDOWN, bitmask)) events.push_back(fd); else close(fd); } if (events.empty()) return false; run_finally fin([&]{ std::for_each(events.begin(), events.end(), close); }); // Check if volume down key is held continuously for more than 3 seconds for (int i = 0; i < 300; ++i) { bool pressed = false; for (const int &fd : events) { memset(bitmask, 0, sizeof(bitmask)); ioctl(fd, EVIOCGKEY(sizeof(bitmask)), bitmask); if (test_bit(KEY_VOLUMEDOWN, bitmask)) { pressed = true; break; } } if (!pressed) return false; // Check every 10ms usleep(10000); } LOGD("KEY_VOLUMEDOWN detected: enter safe mode\n"); return true; } static bool check_safe_mode() { int bootloop_cnt; db_settings dbs; get_db_settings(dbs, BOOTLOOP_COUNT); bootloop_cnt = dbs[BOOTLOOP_COUNT]; // Increment the bootloop counter set_db_settings(BOOTLOOP_COUNT, bootloop_cnt + 1); return bootloop_cnt >= 2 || get_prop("persist.sys.safemode", true) == "1" || get_prop("ro.sys.safemode") == "1" || check_key_combo(); } /*********************** * Boot Stage Handlers * ***********************/ bool MagiskD::post_fs_data() const { as_rust().setup_logfile(); LOGI("** post-fs-data mode running\n"); preserve_stub_apk(); prune_su_access(); bool safe_mode = false; if (access(SECURE_DIR, F_OK) != 0) { if (SDK_INT < 24) { xmkdir(SECURE_DIR, 0700); } else { LOGE(SECURE_DIR " is not present, abort\n"); safe_mode = true; return safe_mode; } } if (!magisk_env()) { LOGE("* Magisk environment incomplete, abort\n"); safe_mode = true; return safe_mode; } if (check_safe_mode()) { LOGI("* Safe mode triggered\n"); safe_mode = true; // Disable all modules and zygisk so next boot will be clean disable_modules(); set_db_settings(ZYGISK_CONFIG, false); return safe_mode; } exec_common_scripts("post-fs-data"); db_settings dbs; get_db_settings(dbs, ZYGISK_CONFIG); zygisk_enabled = dbs[ZYGISK_CONFIG]; initialize_denylist(); setup_mounts(); handle_modules(); load_modules(); return safe_mode; } void MagiskD::late_start() const { as_rust().setup_logfile(); LOGI("** late_start service mode running\n"); exec_common_scripts("service"); exec_module_scripts("service"); } void MagiskD::boot_complete() const { as_rust().setup_logfile(); LOGI("** boot-complete triggered\n"); // Reset the bootloop counter once we have boot-complete set_db_settings(BOOTLOOP_COUNT, 0); // At this point it's safe to create the folder if (access(SECURE_DIR, F_OK) != 0) xmkdir(SECURE_DIR, 0700); // Ensure manager exists get_manager(0, nullptr, true); reset_zygisk(true); }
6,013
C++
.cpp
183
26.42623
84
0.582974
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6
socket.cpp
topjohnwu_Magisk/native/src/core/socket.cpp
#include <fcntl.h> #include <endian.h> #include <socket.hpp> #include <base.hpp> using namespace std; bool get_client_cred(int fd, sock_cred *cred) { socklen_t len = sizeof(ucred); if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, cred, &len) != 0) return false; char buf[4096]; len = sizeof(buf); if (getsockopt(fd, SOL_SOCKET, SO_PEERSEC, buf, &len) != 0) len = 0; buf[len] = '\0'; cred->context = buf; return true; } static int send_fds(int sockfd, void *cmsgbuf, size_t bufsz, const int *fds, int cnt) { iovec iov = { .iov_base = &cnt, .iov_len = sizeof(cnt), }; msghdr msg = { .msg_iov = &iov, .msg_iovlen = 1, }; if (cnt) { msg.msg_control = cmsgbuf; msg.msg_controllen = bufsz; cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); cmsg->cmsg_len = CMSG_LEN(sizeof(int) * cnt); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; memcpy(CMSG_DATA(cmsg), fds, sizeof(int) * cnt); } return xsendmsg(sockfd, &msg, 0); } int send_fds(int sockfd, const int *fds, int cnt) { if (cnt == 0) { return send_fds(sockfd, nullptr, 0, nullptr, 0); } vector<char> cmsgbuf; cmsgbuf.resize(CMSG_SPACE(sizeof(int) * cnt)); return send_fds(sockfd, cmsgbuf.data(), cmsgbuf.size(), fds, cnt); } int send_fd(int sockfd, int fd) { if (fd < 0) { return send_fds(sockfd, nullptr, 0, nullptr, 0); } char cmsgbuf[CMSG_SPACE(sizeof(int))]; return send_fds(sockfd, cmsgbuf, sizeof(cmsgbuf), &fd, 1); } static void *recv_fds(int sockfd, char *cmsgbuf, size_t bufsz, int cnt) { iovec iov = { .iov_base = &cnt, .iov_len = sizeof(cnt), }; msghdr msg = { .msg_iov = &iov, .msg_iovlen = 1, .msg_control = cmsgbuf, .msg_controllen = bufsz }; xrecvmsg(sockfd, &msg, MSG_WAITALL); if (msg.msg_controllen != bufsz) { LOGE("recv_fd: msg_flags = %d, msg_controllen(%zu) != %zu\n", msg.msg_flags, msg.msg_controllen, bufsz); return nullptr; } cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); if (cmsg == nullptr) { LOGE("recv_fd: cmsg == nullptr\n"); return nullptr; } if (cmsg->cmsg_len != CMSG_LEN(sizeof(int) * cnt)) { LOGE("recv_fd: cmsg_len(%zu) != %zu\n", cmsg->cmsg_len, CMSG_LEN(sizeof(int) * cnt)); return nullptr; } if (cmsg->cmsg_level != SOL_SOCKET) { LOGE("recv_fd: cmsg_level != SOL_SOCKET\n"); return nullptr; } if (cmsg->cmsg_type != SCM_RIGHTS) { LOGE("recv_fd: cmsg_type != SCM_RIGHTS\n"); return nullptr; } return CMSG_DATA(cmsg); } vector<int> recv_fds(int sockfd) { vector<int> results; // Peek fd count to allocate proper buffer int cnt; recv(sockfd, &cnt, sizeof(cnt), MSG_PEEK); if (cnt == 0) { // Consume data recv(sockfd, &cnt, sizeof(cnt), MSG_WAITALL); return results; } vector<char> cmsgbuf; cmsgbuf.resize(CMSG_SPACE(sizeof(int) * cnt)); void *data = recv_fds(sockfd, cmsgbuf.data(), cmsgbuf.size(), cnt); if (data == nullptr) return results; results.resize(cnt); memcpy(results.data(), data, sizeof(int) * cnt); return results; } int recv_fd(int sockfd) { // Peek fd count int cnt; recv(sockfd, &cnt, sizeof(cnt), MSG_PEEK); if (cnt == 0) { // Consume data recv(sockfd, &cnt, sizeof(cnt), MSG_WAITALL); return -1; } char cmsgbuf[CMSG_SPACE(sizeof(int))]; void *data = recv_fds(sockfd, cmsgbuf, sizeof(cmsgbuf), 1); if (data == nullptr) return -1; int result; memcpy(&result, data, sizeof(int)); return result; } int read_int(int fd) { int val; if (xxread(fd, &val, sizeof(val)) != sizeof(val)) return -1; return val; } int read_int_be(int fd) { return ntohl(read_int(fd)); } void write_int(int fd, int val) { if (fd < 0) return; xwrite(fd, &val, sizeof(val)); } void write_int_be(int fd, int val) { write_int(fd, htonl(val)); } bool read_string(int fd, std::string &str) { int len = read_int(fd); str.clear(); if (len < 0) return false; str.resize(len); return xxread(fd, str.data(), len) == len; } string read_string(int fd) { string str; read_string(fd, str); return str; } void write_string(int fd, string_view str) { if (fd < 0) return; write_int(fd, str.size()); xwrite(fd, str.data(), str.size()); }
4,615
C++
.cpp
158
23.759494
93
0.581884
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
7
magisk.cpp
topjohnwu_Magisk/native/src/core/magisk.cpp
#include <sys/mount.h> #include <libgen.h> #include <base.hpp> #include <consts.hpp> #include <core.hpp> #include <selinux.hpp> #include <flags.h> using namespace std; [[noreturn]] static void usage() { fprintf(stderr, R"EOF(Magisk - Multi-purpose Utility Usage: magisk [applet [arguments]...] or: magisk [options]... Options: -c print current binary version -v print running daemon version -V print running daemon version code --list list all available applets --remove-modules [-n] remove all modules, reboot if -n is not provided --install-module ZIP install a module zip file Advanced Options (Internal APIs): --daemon manually start magisk daemon --stop remove all magisk changes and stop daemon --[init trigger] callback on init triggers. Valid triggers: post-fs-data, service, boot-complete, zygote-restart --unlock-blocks set BLKROSET flag to OFF for all block devices --restorecon restore selinux context on Magisk files --clone-attr SRC DEST clone permission, owner, and selinux context --clone SRC DEST clone SRC to DEST --sqlite SQL exec SQL commands to Magisk database --path print Magisk tmpfs mount path --denylist ARGS denylist config CLI --preinit-device resolve a device to store preinit files Available applets: )EOF"); for (int i = 0; applet_names[i]; ++i) fprintf(stderr, i ? ", %s" : " %s", applet_names[i]); fprintf(stderr, "\n\n"); exit(1); } int magisk_main(int argc, char *argv[]) { if (argc < 2) usage(); if (argv[1] == "-c"sv) { #if MAGISK_DEBUG printf(MAGISK_VERSION ":MAGISK:D (" str(MAGISK_VER_CODE) ")\n"); #else printf(MAGISK_VERSION ":MAGISK:R (" str(MAGISK_VER_CODE) ")\n"); #endif return 0; } else if (argv[1] == "-v"sv) { int fd = connect_daemon(+RequestCode::CHECK_VERSION); string v = read_string(fd); printf("%s\n", v.data()); return 0; } else if (argv[1] == "-V"sv) { int fd = connect_daemon(+RequestCode::CHECK_VERSION_CODE); printf("%d\n", read_int(fd)); return 0; } else if (argv[1] == "--list"sv) { for (int i = 0; applet_names[i]; ++i) printf("%s\n", applet_names[i]); return 0; } else if (argv[1] == "--unlock-blocks"sv) { unlock_blocks(); return 0; } else if (argv[1] == "--restorecon"sv) { restorecon(); return 0; } else if (argc >= 4 && argv[1] == "--clone-attr"sv) { clone_attr(argv[2], argv[3]); return 0; } else if (argc >= 4 && argv[1] == "--clone"sv) { cp_afc(argv[2], argv[3]); return 0; } else if (argv[1] == "--daemon"sv) { close(connect_daemon(+RequestCode::START_DAEMON, true)); return 0; } else if (argv[1] == "--stop"sv) { int fd = connect_daemon(+RequestCode::STOP_DAEMON); return read_int(fd); } else if (argv[1] == "--post-fs-data"sv) { int fd = connect_daemon(+RequestCode::POST_FS_DATA, true); struct pollfd pfd = { fd, POLLIN, 0 }; poll(&pfd, 1, 1000 * POST_FS_DATA_WAIT_TIME); return 0; } else if (argv[1] == "--service"sv) { close(connect_daemon(+RequestCode::LATE_START, true)); return 0; } else if (argv[1] == "--boot-complete"sv) { close(connect_daemon(+RequestCode::BOOT_COMPLETE)); return 0; } else if (argv[1] == "--zygote-restart"sv) { close(connect_daemon(+RequestCode::ZYGOTE_RESTART)); return 0; } else if (argv[1] == "--denylist"sv) { return denylist_cli(argc - 1, argv + 1); } else if (argc >= 3 && argv[1] == "--sqlite"sv) { int fd = connect_daemon(+RequestCode::SQLITE_CMD); write_string(fd, argv[2]); string res; for (;;) { read_string(fd, res); if (res.empty()) return 0; printf("%s\n", res.data()); } } else if (argv[1] == "--remove-modules"sv) { int do_reboot; if (argc == 3 && argv[2] == "-n"sv) { do_reboot = 0; } else if (argc == 2) { do_reboot = 1; } else { usage(); } int fd = connect_daemon(+RequestCode::REMOVE_MODULES); write_int(fd, do_reboot); return read_int(fd); } else if (argv[1] == "--path"sv) { const char *path = get_magisk_tmp(); if (path[0] != '\0') { printf("%s\n", path); return 0; } return 1; } else if (argc >= 3 && argv[1] == "--install-module"sv) { install_module(argv[2]); } else if (argv[1] == "--preinit-device"sv) { auto name = find_preinit_device(); if (!name.empty()) { printf("%s\n", name.c_str()); return 0; } return 1; } #if 0 /* Entry point for testing stuffs */ else if (argv[1] == "--test"sv) { rust_test_entry(); return 0; } #endif usage(); }
5,251
C++
.cpp
145
29.365517
81
0.537767
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
8
thread.cpp
topjohnwu_Magisk/native/src/core/thread.cpp
// Cached thread pool implementation #include <base.hpp> #include <core.hpp> using namespace std; #define THREAD_IDLE_MAX_SEC 60 #define CORE_POOL_SIZE 3 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t send_task = PTHREAD_COND_INITIALIZER_MONOTONIC_NP; static pthread_cond_t recv_task = PTHREAD_COND_INITIALIZER_MONOTONIC_NP; // The following variables should be guarded by lock static int idle_threads = 0; static int total_threads = 0; static function<void()> pending_task; static void operator+=(timespec &a, const timespec &b) { a.tv_sec += b.tv_sec; a.tv_nsec += b.tv_nsec; if (a.tv_nsec >= 1000000000L) { a.tv_sec++; a.tv_nsec -= 1000000000L; } } static void reset_pool() { clear_poll(); pthread_mutex_unlock(&lock); pthread_mutex_destroy(&lock); pthread_mutex_init(&lock, nullptr); pthread_cond_destroy(&send_task); send_task = PTHREAD_COND_INITIALIZER_MONOTONIC_NP; pthread_cond_destroy(&recv_task); recv_task = PTHREAD_COND_INITIALIZER_MONOTONIC_NP; idle_threads = 0; total_threads = 0; pending_task = nullptr; } static void *thread_pool_loop(void * const is_core_pool) { // Block all signals sigset_t mask; sigfillset(&mask); for (;;) { // Restore sigmask pthread_sigmask(SIG_SETMASK, &mask, nullptr); function<void()> local_task; { mutex_guard g(lock); ++idle_threads; if (!pending_task) { if (is_core_pool) { pthread_cond_wait(&send_task, &lock); } else { timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); ts += { THREAD_IDLE_MAX_SEC, 0 }; if (pthread_cond_timedwait(&send_task, &lock, &ts) == ETIMEDOUT) { // Terminate thread after max idle time --idle_threads; --total_threads; return nullptr; } } } if (pending_task) { local_task.swap(pending_task); pthread_cond_signal(&recv_task); } --idle_threads; } if (local_task) local_task(); if (getpid() == gettid()) exit(0); } } void init_thread_pool() { pthread_atfork(nullptr, nullptr, &reset_pool); } void exec_task(function<void()> &&task) { mutex_guard g(lock); pending_task.swap(task); if (idle_threads == 0) { ++total_threads; long is_core_pool = total_threads <= CORE_POOL_SIZE; new_daemon_thread(thread_pool_loop, (void *) is_core_pool); } else { pthread_cond_signal(&send_task); } pthread_cond_wait(&recv_task, &lock); }
2,848
C++
.cpp
87
24.517241
86
0.575482
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
9
applet_stub.cpp
topjohnwu_Magisk/native/src/core/applet_stub.cpp
#include <sys/stat.h> #include <consts.hpp> #include <selinux.hpp> #include <base.hpp> int main(int argc, char *argv[]) { if (argc < 1) return 1; cmdline_logging(); init_argv0(argc, argv); umask(0); return APPLET_STUB_MAIN(argc, argv); }
268
C++
.cpp
12
18.833333
40
0.641732
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10
module.cpp
topjohnwu_Magisk/native/src/core/module.cpp
#include <sys/mman.h> #include <sys/syscall.h> #include <sys/mount.h> #include <map> #include <utility> #include <base.hpp> #include <consts.hpp> #include <core.hpp> #include <selinux.hpp> #include "node.hpp" using namespace std; #define VLOGD(tag, from, to) LOGD("%-8s: %s <- %s\n", tag, to, from) static int bind_mount(const char *reason, const char *from, const char *to) { int ret = xmount(from, to, nullptr, MS_BIND | MS_REC, nullptr); if (ret == 0) VLOGD(reason, from, to); return ret; } /************************* * Node Tree Construction *************************/ tmpfs_node::tmpfs_node(node_entry *node) : dir_node(node, this) { if (!replace()) { if (auto dir = open_dir(node_path().data())) { set_exist(true); for (dirent *entry; (entry = xreaddir(dir.get()));) { // create a dummy inter_node to upgrade later emplace<inter_node>(entry->d_name, entry); } } } for (auto it = children.begin(); it != children.end(); ++it) { // Upgrade resting inter_node children to tmpfs_node if (isa<inter_node>(it->second)) it = upgrade<tmpfs_node>(it); } } bool dir_node::prepare() { // If direct replace or not exist, mount ourselves as tmpfs bool upgrade_to_tmpfs = replace() || !exist(); for (auto it = children.begin(); it != children.end();) { // We also need to upgrade to tmpfs node if any child: // - Target does not exist // - Source or target is a symlink (since we cannot bind mount symlink) bool cannot_mnt; if (struct stat st{}; lstat(it->second->node_path().data(), &st) != 0) { cannot_mnt = true; } else { it->second->set_exist(true); cannot_mnt = it->second->is_lnk() || S_ISLNK(st.st_mode); } if (cannot_mnt) { if (_node_type > type_id<tmpfs_node>()) { // Upgrade will fail, remove the unsupported child node LOGW("Unable to add: %s, skipped\n", it->second->node_path().data()); delete it->second; it = children.erase(it); continue; } upgrade_to_tmpfs = true; } if (auto dn = dyn_cast<dir_node>(it->second)) { if (replace()) { // Propagate skip mirror state to all children dn->set_replace(true); } if (dn->prepare()) { // Upgrade child to tmpfs it = upgrade<tmpfs_node>(it); } } ++it; } return upgrade_to_tmpfs; } void dir_node::collect_module_files(const char *module, int dfd) { auto dir = xopen_dir(xopenat(dfd, name().data(), O_RDONLY | O_CLOEXEC)); if (!dir) return; for (dirent *entry; (entry = xreaddir(dir.get()));) { if (entry->d_name == ".replace"sv) { set_replace(true); continue; } if (entry->d_type == DT_DIR) { inter_node *node; if (auto it = children.find(entry->d_name); it == children.end()) { node = emplace<inter_node>(entry->d_name, entry->d_name); } else { node = dyn_cast<inter_node>(it->second); } if (node) { node->collect_module_files(module, dirfd(dir.get())); } } else { emplace<module_node>(entry->d_name, module, entry); } } } /************************ * Mount Implementations ************************/ void node_entry::create_and_mount(const char *reason, const string &src, bool ro) { const string dest = isa<tmpfs_node>(parent()) ? worker_path() : node_path(); if (is_lnk()) { VLOGD("cp_link", src.data(), dest.data()); cp_afc(src.data(), dest.data()); } else { if (is_dir()) xmkdir(dest.data(), 0); else if (is_reg()) close(xopen(dest.data(), O_RDONLY | O_CREAT | O_CLOEXEC, 0)); else return; bind_mount(reason, src.data(), dest.data()); if (ro) { xmount(nullptr, dest.data(), nullptr, MS_REMOUNT | MS_BIND | MS_RDONLY, nullptr); } } } void module_node::mount() { std::string path = module + (parent()->root()->prefix + node_path()); string mnt_src = module_mnt + path; { string src = MODULEROOT "/" + path; if (exist()) clone_attr(node_path().data(), src.data()); } if (isa<tmpfs_node>(parent())) { create_and_mount("module", mnt_src); } else { bind_mount("module", mnt_src.data(), node_path().data()); } } void tmpfs_node::mount() { if (!is_dir()) { create_and_mount("mirror", node_path()); return; } if (!isa<tmpfs_node>(parent())) { auto worker_dir = worker_path(); mkdirs(worker_dir.data(), 0); clone_attr(exist() ? node_path().data() : parent()->node_path().data(), worker_dir.data()); dir_node::mount(); bind_mount(replace() ? "replace" : "move", worker_dir.data(), node_path().data()); xmount(nullptr, node_path().data(), nullptr, MS_REMOUNT | MS_BIND | MS_RDONLY, nullptr); } else { const string dest = worker_path(); // We don't need another layer of tmpfs if parent is tmpfs mkdir(dest.data(), 0); clone_attr(exist() ? node_path().data() : parent()->worker_path().data(), dest.data()); dir_node::mount(); } } /**************** * Magisk Stuffs ****************/ class magisk_node : public node_entry { public: explicit magisk_node(const char *name) : node_entry(name, DT_REG, this) {} void mount() override { const string src = get_magisk_tmp() + "/"s + name(); if (access(src.data(), F_OK)) return; const string dir_name = isa<tmpfs_node>(parent()) ? parent()->worker_path() : parent()->node_path(); if (name() == "magisk") { for (int i = 0; applet_names[i]; ++i) { string dest = dir_name + "/" + applet_names[i]; VLOGD("create", "./magisk", dest.data()); xsymlink("./magisk", dest.data()); } } else { string dest = dir_name + "/supolicy"; VLOGD("create", "./magiskpolicy", dest.data()); xsymlink("./magiskpolicy", dest.data()); } create_and_mount("magisk", src, true); } }; class zygisk_node : public node_entry { public: explicit zygisk_node(const char *name, bool is64bit) : node_entry(name, DT_REG, this), is64bit(is64bit) {} void mount() override { #if defined(__LP64__) const string src = get_magisk_tmp() + "/magisk"s + (is64bit ? "" : "32"); #else const string src = get_magisk_tmp() + "/magisk"s; (void) is64bit; #endif if (access(src.data(), F_OK)) return; create_and_mount("zygisk", src, true); } private: bool is64bit; }; static void inject_magisk_bins(root_node *system) { auto bin = system->get_child<inter_node>("bin"); if (!bin) { bin = new inter_node("bin"); system->insert(bin); } // Insert binaries bin->insert(new magisk_node("magisk")); bin->insert(new magisk_node("magiskpolicy")); // Also delete all applets to make sure no modules can override it for (int i = 0; applet_names[i]; ++i) delete bin->extract(applet_names[i]); delete bin->extract("supolicy"); } static void inject_zygisk_libs(root_node *system) { if (access("/system/bin/linker", F_OK) == 0) { auto lib = system->get_child<inter_node>("lib"); if (!lib) { lib = new inter_node("lib"); system->insert(lib); } lib->insert(new zygisk_node(native_bridge.data(), false)); } if (access("/system/bin/linker64", F_OK) == 0) { auto lib64 = system->get_child<inter_node>("lib64"); if (!lib64) { lib64 = new inter_node("lib64"); system->insert(lib64); } lib64->insert(new zygisk_node(native_bridge.data(), true)); } } vector<module_info> *module_list; void load_modules() { node_entry::module_mnt = get_magisk_tmp() + "/"s MODULEMNT "/"; auto root = make_unique<root_node>(""); auto system = new root_node("system"); root->insert(system); char buf[4096]; LOGI("* Loading modules\n"); for (const auto &m : *module_list) { const char *module = m.name.data(); char *b = buf + ssprintf(buf, sizeof(buf), "%s/" MODULEMNT "/%s/", get_magisk_tmp(), module); // Read props strcpy(b, "system.prop"); if (access(buf, F_OK) == 0) { LOGI("%s: loading [system.prop]\n", module); // Do NOT go through property service as it could cause boot lock load_prop_file(buf, true); } // Check whether skip mounting strcpy(b, "skip_mount"); if (access(buf, F_OK) == 0) continue; // Double check whether the system folder exists strcpy(b, "system"); if (access(buf, F_OK) != 0) continue; LOGI("%s: loading mount files\n", module); b[-1] = '\0'; int fd = xopen(buf, O_RDONLY | O_CLOEXEC); system->collect_module_files(module, fd); close(fd); } if (get_magisk_tmp() != "/sbin"sv || !str_contains(getenv("PATH") ?: "", "/sbin")) { // Need to inject our binaries into /system/bin inject_magisk_bins(system); } if (zygisk_enabled) { string native_bridge_orig = get_prop(NBPROP); if (native_bridge_orig.empty()) { native_bridge_orig = "0"; } native_bridge = native_bridge_orig != "0" ? ZYGISKLDR + native_bridge_orig : ZYGISKLDR; set_prop(NBPROP, native_bridge.data()); // Weather Huawei's Maple compiler is enabled. // If so, system server will be created by a special Zygote which ignores the native bridge // and make system server out of our control. Avoid it by disabling. if (get_prop("ro.maple.enable") == "1") { set_prop("ro.maple.enable", "0"); } inject_zygisk_libs(system); } if (!system->is_empty()) { // Handle special read-only partitions for (const char *part : { "/vendor", "/product", "/system_ext" }) { struct stat st{}; if (lstat(part, &st) == 0 && S_ISDIR(st.st_mode)) { if (auto old = system->extract(part + 1)) { auto new_node = new root_node(old); root->insert(new_node); } } } root->prepare(); root->mount(); } // cleanup mounts clean_mounts(); } /************************ * Filesystem operations ************************/ static void prepare_modules() { // Upgrade modules if (auto dir = open_dir(MODULEUPGRADE); dir) { int ufd = dirfd(dir.get()); int mfd = xopen(MODULEROOT, O_RDONLY | O_CLOEXEC); for (dirent *entry; (entry = xreaddir(dir.get()));) { if (entry->d_type == DT_DIR) { // Cleanup old module if exists if (faccessat(mfd, entry->d_name, F_OK, 0) == 0) { int modfd = xopenat(mfd, entry->d_name, O_RDONLY | O_CLOEXEC); if (faccessat(modfd, "disable", F_OK, 0) == 0) { auto disable = entry->d_name + "/disable"s; close(xopenat(ufd, disable.data(), O_RDONLY | O_CREAT | O_CLOEXEC, 0)); } frm_rf(modfd); unlinkat(mfd, entry->d_name, AT_REMOVEDIR); } LOGI("Upgrade / New module: %s\n", entry->d_name); renameat(ufd, entry->d_name, mfd, entry->d_name); } } close(mfd); rm_rf(MODULEUPGRADE); } } template<typename Func> static void foreach_module(Func fn) { auto dir = open_dir(MODULEROOT); if (!dir) return; int dfd = dirfd(dir.get()); for (dirent *entry; (entry = xreaddir(dir.get()));) { if (entry->d_type == DT_DIR && entry->d_name != ".core"sv) { int modfd = xopenat(dfd, entry->d_name, O_RDONLY | O_CLOEXEC); fn(dfd, entry, modfd); close(modfd); } } } static void collect_modules(bool open_zygisk) { foreach_module([=](int dfd, dirent *entry, int modfd) { if (faccessat(modfd, "remove", F_OK, 0) == 0) { LOGI("%s: remove\n", entry->d_name); auto uninstaller = MODULEROOT + "/"s + entry->d_name + "/uninstall.sh"; if (access(uninstaller.data(), F_OK) == 0) exec_script(uninstaller.data()); frm_rf(xdup(modfd)); unlinkat(dfd, entry->d_name, AT_REMOVEDIR); return; } unlinkat(modfd, "update", 0); if (faccessat(modfd, "disable", F_OK, 0) == 0) return; module_info info; if (zygisk_enabled) { // Riru and its modules are not compatible with zygisk if (entry->d_name == "riru-core"sv || faccessat(modfd, "riru", F_OK, 0) == 0) { LOGI("%s: ignore\n", entry->d_name); return; } if (open_zygisk) { #if defined(__arm__) info.z32 = openat(modfd, "zygisk/armeabi-v7a.so", O_RDONLY | O_CLOEXEC); #elif defined(__aarch64__) info.z32 = openat(modfd, "zygisk/armeabi-v7a.so", O_RDONLY | O_CLOEXEC); info.z64 = openat(modfd, "zygisk/arm64-v8a.so", O_RDONLY | O_CLOEXEC); #elif defined(__i386__) info.z32 = openat(modfd, "zygisk/x86.so", O_RDONLY | O_CLOEXEC); #elif defined(__x86_64__) info.z32 = openat(modfd, "zygisk/x86.so", O_RDONLY | O_CLOEXEC); info.z64 = openat(modfd, "zygisk/x86_64.so", O_RDONLY | O_CLOEXEC); #elif defined(__riscv) info.z32 = -1; info.z64 = openat(modfd, "zygisk/riscv64.so", O_RDONLY | O_CLOEXEC); #else #error Unsupported ABI #endif unlinkat(modfd, "zygisk/unloaded", 0); } } else { // Ignore zygisk modules when zygisk is not enabled if (faccessat(modfd, "zygisk", F_OK, 0) == 0) { LOGI("%s: ignore\n", entry->d_name); return; } } info.name = entry->d_name; module_list->push_back(info); }); if (zygisk_enabled) { bool use_memfd = true; auto convert_to_memfd = [&](int fd) -> int { if (fd < 0) return -1; if (use_memfd) { int memfd = syscall(__NR_memfd_create, "jit-cache", MFD_CLOEXEC); if (memfd >= 0) { xsendfile(memfd, fd, nullptr, INT_MAX); close(fd); return memfd; } else { // memfd_create failed, just use what we had use_memfd = false; } } return fd; }; std::for_each(module_list->begin(), module_list->end(), [&](module_info &info) { info.z32 = convert_to_memfd(info.z32); #if defined(__LP64__) info.z64 = convert_to_memfd(info.z64); #endif }); } } void handle_modules() { prepare_modules(); collect_modules(false); exec_module_scripts("post-fs-data"); // Recollect modules (module scripts could remove itself) module_list->clear(); collect_modules(true); } static int check_rules_dir(char *buf, size_t sz) { int off = ssprintf(buf, sz, "%s/" PREINITMIRR, get_magisk_tmp()); struct stat st1{}; struct stat st2{}; if (xstat(buf, &st1) < 0 || xstat(MODULEROOT, &st2) < 0) return 0; if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino) return 0; return off; } void disable_modules() { char buf[4096]; int off = check_rules_dir(buf, sizeof(buf)); foreach_module([&](int, dirent *entry, int modfd) { close(xopenat(modfd, "disable", O_RDONLY | O_CREAT | O_CLOEXEC, 0)); if (off) { ssprintf(buf + off, sizeof(buf) - off, "/%s/sepolicy.rule", entry->d_name); unlink(buf); } }); } void remove_modules() { char buf[4096]; int off = check_rules_dir(buf, sizeof(buf)); foreach_module([&](int, dirent *entry, int) { auto uninstaller = MODULEROOT + "/"s + entry->d_name + "/uninstall.sh"; if (access(uninstaller.data(), F_OK) == 0) exec_script(uninstaller.data()); if (off) { ssprintf(buf + off, sizeof(buf) - off, "/%s/sepolicy.rule", entry->d_name); unlink(buf); } }); rm_rf(MODULEROOT); } void exec_module_scripts(const char *stage) { vector<string_view> module_names; std::transform(module_list->begin(), module_list->end(), std::back_inserter(module_names), [](const module_info &info) -> string_view { return info.name; }); exec_module_scripts(stage, module_names); }
17,251
C++
.cpp
463
28.645788
108
0.533911
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11
db.cpp
topjohnwu_Magisk/native/src/core/db.cpp
#include <unistd.h> #include <dlfcn.h> #include <sys/stat.h> #include <consts.hpp> #include <base.hpp> #include <db.hpp> #include <core.hpp> #define DB_VERSION 12 using namespace std; struct sqlite3; static sqlite3 *mDB = nullptr; #define DBLOGV(...) //#define DBLOGV(...) LOGD("magiskdb: " __VA_ARGS__) // SQLite APIs #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */ using sqlite3_callback = int (*)(void*, int, char**, char**); static int (*sqlite3_open_v2)(const char *filename, sqlite3 **ppDb, int flags, const char *zVfs); static const char *(*sqlite3_errmsg)(sqlite3 *db); static int (*sqlite3_close)(sqlite3 *db); static void (*sqlite3_free)(void *v); static int (*sqlite3_exec)(sqlite3 *db, const char *sql, sqlite3_callback fn, void *v, char **errmsg); // Internal Android linker APIs static void (*android_get_LD_LIBRARY_PATH)(char *buffer, size_t buffer_size); static void (*android_update_LD_LIBRARY_PATH)(const char *ld_library_path); #define DLERR(ptr) if (!(ptr)) { \ LOGE("db: %s\n", dlerror()); \ return false; \ } #define DLOAD(handle, arg) {\ auto f = dlsym(handle, #arg); \ DLERR(f) \ *(void **) &(arg) = f; \ } #ifdef __LP64__ constexpr char apex_path[] = "/apex/com.android.runtime/lib64:/apex/com.android.art/lib64:/apex/com.android.i18n/lib64:"; #else constexpr char apex_path[] = "/apex/com.android.runtime/lib:/apex/com.android.art/lib:/apex/com.android.i18n/lib:"; #endif static int dl_init = 0; static bool dload_sqlite() { if (dl_init) return dl_init > 0; dl_init = -1; auto sqlite = dlopen("libsqlite.so", RTLD_LAZY); if (!sqlite) { // Should only happen on Android 10+ auto dl = dlopen("libdl_android.so", RTLD_LAZY); DLERR(dl); DLOAD(dl, android_get_LD_LIBRARY_PATH); DLOAD(dl, android_update_LD_LIBRARY_PATH); // Inject APEX into LD_LIBRARY_PATH char ld_path[4096]; memcpy(ld_path, apex_path, sizeof(apex_path)); constexpr int len = sizeof(apex_path) - 1; android_get_LD_LIBRARY_PATH(ld_path + len, sizeof(ld_path) - len); android_update_LD_LIBRARY_PATH(ld_path); sqlite = dlopen("libsqlite.so", RTLD_LAZY); // Revert LD_LIBRARY_PATH just in case android_update_LD_LIBRARY_PATH(ld_path + len); } DLERR(sqlite); DLOAD(sqlite, sqlite3_open_v2); DLOAD(sqlite, sqlite3_errmsg); DLOAD(sqlite, sqlite3_close); DLOAD(sqlite, sqlite3_exec); DLOAD(sqlite, sqlite3_free); dl_init = 1; return true; } int db_strings::get_idx(string_view key) const { int idx = 0; for (const char *k : DB_STRING_KEYS) { if (key == k) break; ++idx; } return idx; } db_settings::db_settings() { // Default settings data[ROOT_ACCESS] = ROOT_ACCESS_APPS_AND_ADB; data[SU_MULTIUSER_MODE] = MULTIUSER_MODE_OWNER_ONLY; data[SU_MNT_NS] = NAMESPACE_MODE_REQUESTER; data[DENYLIST_CONFIG] = false; data[ZYGISK_CONFIG] = MagiskD::get()->is_emulator(); data[BOOTLOOP_COUNT] = 0; } int db_settings::get_idx(string_view key) const { int idx = 0; for (const char *k : DB_SETTING_KEYS) { if (key == k) break; ++idx; } return idx; } static int ver_cb(void *ver, int, char **data, char **) { *((int *) ver) = parse_int(data[0]); return 0; } bool db_result::check_err() { if (!err.empty()) { LOGE("sqlite3_exec: %s\n", err.data()); return true; } return false; } static db_result sql_exec(sqlite3 *db, const char *sql, sqlite3_callback fn, void *v) { char *err = nullptr; sqlite3_exec(db, sql, fn, v, &err); if (err) { db_result r = err; sqlite3_free(err); return r; } return {}; } #define sql_exe_ret(...) if (auto r = sql_exec(__VA_ARGS__); !r) return r #define fn_run_ret(fn) if (auto r = fn(); !r) return r static db_result open_and_init_db(sqlite3 *&db) { if (!dload_sqlite()) return "Cannot load libsqlite.so"; int ret = sqlite3_open_v2(MAGISKDB, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, nullptr); if (ret) return sqlite3_errmsg(db); int ver = 0; bool upgrade = false; sql_exe_ret(db, "PRAGMA user_version", ver_cb, &ver); if (ver > DB_VERSION) { // Don't support downgrading database sqlite3_close(db); return "Downgrading database is not supported"; } auto create_policy = [&] { return sql_exec(db, "CREATE TABLE IF NOT EXISTS policies " "(uid INT, policy INT, until INT, logging INT, " "notification INT, PRIMARY KEY(uid))", nullptr, nullptr); }; auto create_settings = [&] { return sql_exec(db, "CREATE TABLE IF NOT EXISTS settings " "(key TEXT, value INT, PRIMARY KEY(key))", nullptr, nullptr); }; auto create_strings = [&] { return sql_exec(db, "CREATE TABLE IF NOT EXISTS strings " "(key TEXT, value TEXT, PRIMARY KEY(key))", nullptr, nullptr); }; auto create_denylist = [&] { return sql_exec(db, "CREATE TABLE IF NOT EXISTS denylist " "(package_name TEXT, process TEXT, PRIMARY KEY(package_name, process))", nullptr, nullptr); }; // Database changelog: // // 0 - 6: DB stored in app private data. There are no longer any code in the project to // migrate these data, so no need to take any of these versions into consideration. // 7 : create table `hidelist` (process TEXT, PRIMARY KEY(process)) // 8 : add new column (package_name TEXT) to table `hidelist` // 9 : rebuild table `hidelist` to change primary key (PRIMARY KEY(package_name, process)) // 10: remove table `logs` // 11: remove table `hidelist` and create table `denylist` (same data structure) // 12: rebuild table `policies` to drop column `package_name` if (/* 0, 1, 2, 3, 4, 5, 6 */ ver <= 6) { fn_run_ret(create_policy); fn_run_ret(create_settings); fn_run_ret(create_strings); fn_run_ret(create_denylist); // Directly jump to latest ver = DB_VERSION; upgrade = true; } if (ver == 7) { sql_exe_ret(db, "BEGIN TRANSACTION;" "ALTER TABLE hidelist RENAME TO hidelist_tmp;" "CREATE TABLE IF NOT EXISTS hidelist " "(package_name TEXT, process TEXT, PRIMARY KEY(package_name, process));" "INSERT INTO hidelist SELECT process as package_name, process FROM hidelist_tmp;" "DROP TABLE hidelist_tmp;" "COMMIT;", nullptr, nullptr); // Directly jump to version 9 ver = 9; upgrade = true; } if (ver == 8) { sql_exe_ret(db, "BEGIN TRANSACTION;" "ALTER TABLE hidelist RENAME TO hidelist_tmp;" "CREATE TABLE IF NOT EXISTS hidelist " "(package_name TEXT, process TEXT, PRIMARY KEY(package_name, process));" "INSERT INTO hidelist SELECT * FROM hidelist_tmp;" "DROP TABLE hidelist_tmp;" "COMMIT;", nullptr, nullptr); ver = 9; upgrade = true; } if (ver == 9) { sql_exe_ret(db, "DROP TABLE IF EXISTS logs", nullptr, nullptr); ver = 10; upgrade = true; } if (ver == 10) { sql_exe_ret(db, "DROP TABLE IF EXISTS hidelist;" "DELETE FROM settings WHERE key='magiskhide';", nullptr, nullptr); fn_run_ret(create_denylist); ver = 11; upgrade = true; } if (ver == 11) { sql_exe_ret(db, "BEGIN TRANSACTION;" "ALTER TABLE policies RENAME TO policies_tmp;" "CREATE TABLE IF NOT EXISTS policies " "(uid INT, policy INT, until INT, logging INT, " "notification INT, PRIMARY KEY(uid));" "INSERT INTO policies " "SELECT uid, policy, until, logging, notification FROM policies_tmp;" "DROP TABLE policies_tmp;" "COMMIT;", nullptr, nullptr); ver = 12; upgrade = true; } if (upgrade) { // Set version char query[32]; sprintf(query, "PRAGMA user_version=%d", ver); sql_exe_ret(db, query, nullptr, nullptr); } return {}; } db_result db_exec(const char *sql) { if (mDB == nullptr) { auto res = open_and_init_db(mDB); if (res.check_err()) { // Open fails, remove and reconstruct unlink(MAGISKDB); res = open_and_init_db(mDB); if (!res) return res; } } if (mDB) { sql_exe_ret(mDB, sql, nullptr, nullptr); } return {}; } static int sqlite_db_row_callback(void *cb, int col_num, char **data, char **col_name) { auto &func = *static_cast<const db_row_cb*>(cb); db_row row; for (int i = 0; i < col_num; ++i) row[col_name[i]] = data[i]; return func(row) ? 0 : 1; } db_result db_exec(const char *sql, const db_row_cb &fn) { if (mDB == nullptr) { auto res = open_and_init_db(mDB); if (res.check_err()) { // Open fails, remove and reconstruct unlink(MAGISKDB); res = open_and_init_db(mDB); if (!res) return res; } } if (mDB) { sql_exe_ret(mDB, sql, sqlite_db_row_callback, (void *) &fn); } return {}; } int get_db_settings(db_settings &cfg, int key) { db_result res; auto settings_cb = [&](db_row &row) -> bool { cfg[row["key"]] = parse_int(row["value"]); DBLOGV("query %s=[%s]\n", row["key"].data(), row["value"].data()); return true; }; if (key >= 0) { char query[128]; ssprintf(query, sizeof(query), "SELECT * FROM settings WHERE key='%s'", DB_SETTING_KEYS[key]); res = db_exec(query, settings_cb); } else { res = db_exec("SELECT * FROM settings", settings_cb); } return res.check_err() ? 1 : 0; } int set_db_settings(int key, int value) { char sql[128]; ssprintf(sql, sizeof(sql), "INSERT OR REPLACE INTO settings VALUES ('%s', %d)", DB_SETTING_KEYS[key], value); return db_exec(sql).check_err() ? 1 : 0; } int get_db_strings(db_strings &str, int key) { db_result res; auto string_cb = [&](db_row &row) -> bool { str[row["key"]] = row["value"]; DBLOGV("query %s=[%s]\n", row["key"].data(), row["value"].data()); return true; }; if (key >= 0) { char query[128]; ssprintf(query, sizeof(query), "SELECT * FROM strings WHERE key='%s'", DB_STRING_KEYS[key]); res = db_exec(query, string_cb); } else { res = db_exec("SELECT * FROM strings", string_cb); } return res.check_err() ? 1 : 0; } void rm_db_strings(int key) { char query[128]; ssprintf(query, sizeof(query), "DELETE FROM strings WHERE key == '%s'", DB_STRING_KEYS[key]); db_exec(query).check_err(); } void exec_sql(owned_fd client) { string sql = read_string(client); auto res = db_exec(sql.data(), [fd = (int) client](db_row &row) -> bool { string out; bool first = true; for (auto it : row) { if (first) first = false; else out += '|'; out += it.first; out += '='; out += it.second; } write_string(fd, out); return true; }); write_int(client, 0); res.check_err(); }
11,999
C++
.cpp
342
27.847953
121
0.574701
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12
resetprop.cpp
topjohnwu_Magisk/native/src/core/resetprop/resetprop.cpp
#include <dlfcn.h> #include <sys/types.h> #include <vector> #include <map> #include <base.hpp> #include <core.hpp> #include <resetprop.hpp> #define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_ #include <api/_system_properties.h> #include <system_properties/prop_info.h> using namespace std; #ifdef APPLET_STUB_MAIN #define system_property_set __system_property_set #define system_property_read(...) #define system_property_find __system_property_find #define system_property_read_callback __system_property_read_callback #define system_property_foreach __system_property_foreach #define system_property_wait __system_property_wait #else static int (*system_property_set)(const char*, const char*); static int (*system_property_read)(const prop_info*, char*, char*); static const prop_info *(*system_property_find)(const char*); static void (*system_property_read_callback)( const prop_info*, void (*)(void*, const char*, const char*, uint32_t), void*); static int (*system_property_foreach)(void (*)(const prop_info*, void*), void*); static bool (*system_property_wait)(const prop_info*, uint32_t, uint32_t*, const struct timespec*); #endif struct PropFlags { void setSkipSvc() { flags |= 1; } void setPersist() { flags |= (1 << 1); } void setContext() { flags |= (1 << 2); } void setPersistOnly() { flags |= (1 << 3); setPersist(); } void setWait() { flags |= (1 << 4); } bool isSkipSvc() const { return flags & 1; } bool isPersist() const { return flags & (1 << 1); } bool isContext() const { return flags & (1 << 2); } bool isPersistOnly() const { return flags & (1 << 3); } bool isWait() const { return flags & (1 << 4); } private: uint32_t flags = 0; }; [[noreturn]] static void usage(char* arg0) { fprintf(stderr, R"EOF(resetprop - System Property Manipulation Tool Usage: %s [flags] [arguments...] Read mode arguments: (no arguments) print all properties NAME get property of NAME Write mode arguments: NAME VALUE set property NAME as VALUE -f,--file FILE load and set properties from FILE -d,--delete NAME delete property Wait mode arguments (toggled with -w): NAME wait until property NAME changes NAME OLD_VALUE if value of property NAME is not OLD_VALUE, get value or else wait until property NAME changes General flags: -h,--help show this message -v print verbose output to stderr -w switch to wait mode Read mode flags: -p also read persistent props from storage -P only read persistent props from storage -Z get property context instead of value Write mode flags: -n set properties bypassing property_service -p always write persistent prop changes to storage )EOF", arg0); exit(1); } static bool check_legal_property_name(const char *name) { int namelen = strlen(name); if (namelen < 1) goto illegal; if (name[0] == '.') goto illegal; if (name[namelen - 1] == '.') goto illegal; /* Only allow alphanumeric, plus '.', '-', '@', ':', or '_' */ /* Don't allow ".." to appear in a property name */ for (size_t i = 0; i < namelen; i++) { if (name[i] == '.') { // i=0 is guaranteed to never have a dot. See above. if (name[i-1] == '.') goto illegal; continue; } if (name[i] == '_' || name[i] == '-' || name[i] == '@' || name[i] == ':') continue; if (name[i] >= 'a' && name[i] <= 'z') continue; if (name[i] >= 'A' && name[i] <= 'Z') continue; if (name[i] >= '0' && name[i] <= '9') continue; goto illegal; } return true; illegal: LOGE("Illegal property name: [%s]\n", name); return false; } static void read_prop_with_cb(const prop_info *pi, void *cb) { if (system_property_read_callback) { auto callback = [](void *cb, const char *name, const char *value, uint32_t serial) { static_cast<prop_cb*>(cb)->exec(name, value, serial); }; system_property_read_callback(pi, callback, cb); } else { char name[PROP_NAME_MAX]; char value[PROP_VALUE_MAX]; name[0] = '\0'; value[0] = '\0'; system_property_read(pi, name, value); static_cast<prop_cb*>(cb)->exec(name, value, pi->serial); } } template<class StringType> struct prop_to_string : prop_cb { void exec(const char *, const char *value, uint32_t s) override { val = value; serial = s; } StringType val; uint32_t serial; }; template<> void prop_to_string<rust::String>::exec(const char *, const char *value, uint32_t s) { // We do not want to crash when values are not UTF-8 val = rust::String::lossy(value); serial = s; } static int set_prop(const char *name, const char *value, PropFlags flags) { if (!check_legal_property_name(name)) return 1; auto pi = const_cast<prop_info *>(__system_property_find(name)); // Delete existing read-only properties if they are or will be long properties, // which cannot directly go through __system_property_update if (str_starts(name, "ro.")) { if (pi != nullptr && (pi->is_long() || strlen(value) >= PROP_VALUE_MAX)) { // Skip pruning nodes as we will add it back ASAP __system_property_delete(name, false); pi = nullptr; } flags.setSkipSvc(); } const char *msg = flags.isSkipSvc() ? "direct modification" : "property_service"; int ret; if (pi != nullptr) { if (flags.isSkipSvc()) { ret = __system_property_update(pi, value, strlen(value)); } else { ret = system_property_set(name, value); } LOGD("resetprop: update prop [%s]: [%s] by %s\n", name, value, msg); } else { if (flags.isSkipSvc()) { ret = __system_property_add(name, strlen(name), value, strlen(value)); } else { ret = system_property_set(name, value); } LOGD("resetprop: create prop [%s]: [%s] by %s\n", name, value, msg); } // When bypassing property_service, persistent props won't be stored in storage. // Explicitly handle this situation. if (ret == 0 && flags.isSkipSvc() && flags.isPersist() && str_starts(name, "persist.")) { ret = persist_set_prop(name, value) ? 0 : 1; } if (ret) { LOGW("resetprop: set prop error\n"); } return ret; } template<class StringType> static StringType get_prop(const char *name, PropFlags flags) { if (!check_legal_property_name(name)) return {}; prop_to_string<StringType> cb; if (flags.isContext()) { auto context = __system_property_get_context(name) ?: ""; LOGD("resetprop: prop context [%s]: [%s]\n", name, context); cb.exec(name, context, -1); return cb.val; } if (!flags.isPersistOnly()) { if (auto pi = system_property_find(name)) { read_prop_with_cb(pi, &cb); LOGD("resetprop: get prop [%s]: [%s]\n", name, cb.val.c_str()); } } if (cb.val.empty() && flags.isPersist() && str_starts(name, "persist.")) persist_get_prop(name, cb); if (cb.val.empty()) LOGD("resetprop: prop [%s] does not exist\n", name); return cb.val; } template<class StringType> static StringType wait_prop(const char *name, const char *old_value) { if (!check_legal_property_name(name)) return {}; const prop_info *pi; auto serial = __system_property_area_serial(); while (!(pi = system_property_find(name))) { LOGD("resetprop: waiting for prop [%s] to exist\n", name); system_property_wait(nullptr, serial, &serial, nullptr); } prop_to_string<StringType> cb; read_prop_with_cb(pi, &cb); while (old_value == nullptr || cb.val == old_value) { LOGD("resetprop: waiting for prop [%s]\n", name); uint32_t new_serial; system_property_wait(pi, cb.serial, &new_serial, nullptr); read_prop_with_cb(pi, &cb); if (old_value == nullptr) break; } LOGD("resetprop: get prop [%s]: [%s]\n", name, cb.val.c_str()); return cb.val; } static void print_props(PropFlags flags) { prop_list list; prop_collector collector(list); if (!flags.isPersistOnly()) system_property_foreach(read_prop_with_cb, &collector); if (flags.isPersist()) persist_get_props(collector); for (auto &[key, val] : list) { const char *v = flags.isContext() ? (__system_property_get_context(key.data()) ?: "") : val.data(); printf("[%s]: [%s]\n", key.data(), v); } } static int delete_prop(const char *name, PropFlags flags) { if (!check_legal_property_name(name)) return 1; LOGD("resetprop: delete prop [%s]\n", name); int ret = __system_property_delete(name, true); if (flags.isPersist() && str_starts(name, "persist.")) { if (persist_delete_prop(name)) ret = 0; } return ret; } static void load_file(const char *filename, PropFlags flags) { LOGD("resetprop: Parse prop file [%s]\n", filename); parse_prop_file(filename, [=](auto key, auto val) -> bool { set_prop(key.data(), val.data(), flags); return true; }); } struct Initialize { Initialize() { #ifndef APPLET_STUB_MAIN #define DLOAD(name) (*(void **) &name = dlsym(RTLD_DEFAULT, "__" #name)) // Load platform implementations DLOAD(system_property_set); DLOAD(system_property_read); DLOAD(system_property_find); DLOAD(system_property_read_callback); DLOAD(system_property_foreach); DLOAD(system_property_wait); #undef DLOAD if (system_property_wait == nullptr) { // The platform API only exist on API 26+ system_property_wait = __system_property_wait; } #endif if (__system_properties_init()) { LOGE("resetprop: __system_properties_init error\n"); } } }; static void InitOnce() { static struct Initialize init; } #define consume_next(val) \ if (argc != 2) usage(argv0); \ val = argv[1]; \ stop_parse = true; \ int resetprop_main(int argc, char *argv[]) { PropFlags flags; char *argv0 = argv[0]; set_log_level_state(LogLevel::Debug, false); const char *prop_file = nullptr; const char *prop_to_rm = nullptr; --argc; ++argv; // Parse flags and -- options while (argc && argv[0][0] == '-') { bool stop_parse = false; for (int idx = 1; true; ++idx) { switch (argv[0][idx]) { case '-': if (argv[0] == "--file"sv) { consume_next(prop_file); } else if (argv[0] == "--delete"sv) { consume_next(prop_to_rm); } else { usage(argv0); } break; case 'd': consume_next(prop_to_rm); continue; case 'f': consume_next(prop_file); continue; case 'n': flags.setSkipSvc(); continue; case 'p': flags.setPersist(); continue; case 'P': flags.setPersistOnly(); continue; case 'v': set_log_level_state(LogLevel::Debug, true); continue; case 'Z': flags.setContext(); continue; case 'w': flags.setWait(); continue; case '\0': break; default: usage(argv0); } break; } --argc; ++argv; if (stop_parse) break; } InitOnce(); if (prop_to_rm) { return delete_prop(prop_to_rm, flags); } if (prop_file) { load_file(prop_file, flags); return 0; } if (flags.isWait()) { if (argc == 0) usage(argv0); auto val = wait_prop<string>(argv[0], argv[1]); if (val.empty()) return 1; printf("%s\n", val.data()); return 0; } switch (argc) { case 0: print_props(flags); return 0; case 1: { auto val = get_prop<string>(argv[0], flags); if (val.empty()) return 1; printf("%s\n", val.data()); return 0; } case 2: return set_prop(argv[0], argv[1], flags); default: usage(argv0); } } /*************** * Public APIs ****************/ template<class StringType> static StringType get_prop_impl(const char *name, bool persist) { InitOnce(); PropFlags flags; if (persist) flags.setPersist(); return get_prop<StringType>(name, flags); } rust::String get_prop_rs(const char *name, bool persist) { return get_prop_impl<rust::String>(name, persist); } string get_prop(const char *name, bool persist) { return get_prop_impl<string>(name, persist); } int delete_prop(const char *name, bool persist) { InitOnce(); PropFlags flags; if (persist) flags.setPersist(); return delete_prop(name, flags); } int set_prop(const char *name, const char *value, bool skip_svc) { InitOnce(); PropFlags flags; if (skip_svc) flags.setSkipSvc(); return set_prop(name, value, flags); } void load_prop_file(const char *filename, bool skip_svc) { InitOnce(); PropFlags flags; if (skip_svc) flags.setSkipSvc(); load_file(filename, flags); }
13,763
C++
.cpp
395
28.124051
99
0.580245
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13
su_daemon.cpp
topjohnwu_Magisk/native/src/core/su/su_daemon.cpp
#include <unistd.h> #include <fcntl.h> #include <pwd.h> #include <sys/socket.h> #include <sys/wait.h> #include <sys/mount.h> #include <consts.hpp> #include <base.hpp> #include <selinux.hpp> #include "su.hpp" #include "pts.hpp" using namespace std; static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER; static shared_ptr<su_info> cached; su_info::su_info(int uid) : uid(uid), eval_uid(-1), access(DEFAULT_SU_ACCESS), mgr_uid(-1), timestamp(0), _lock(PTHREAD_MUTEX_INITIALIZER) {} su_info::~su_info() { pthread_mutex_destroy(&_lock); } mutex_guard su_info::lock() { return mutex_guard(_lock); } bool su_info::is_fresh() { timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); long current = ts.tv_sec * 1000L + ts.tv_nsec / 1000000L; return current - timestamp < 3000; /* 3 seconds */ } void su_info::refresh() { timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); timestamp = ts.tv_sec * 1000L + ts.tv_nsec / 1000000L; } void su_info::check_db() { eval_uid = uid; get_db_settings(cfg); // Check multiuser settings switch (cfg[SU_MULTIUSER_MODE]) { case MULTIUSER_MODE_OWNER_ONLY: if (to_user_id(uid) != 0) { eval_uid = -1; access = NO_SU_ACCESS; } break; case MULTIUSER_MODE_OWNER_MANAGED: eval_uid = to_app_id(uid); break; case MULTIUSER_MODE_USER: default: break; } if (eval_uid > 0) { char query[256]; ssprintf(query, sizeof(query), "SELECT policy, logging, notification FROM policies " "WHERE uid=%d AND (until=0 OR until>%li)", eval_uid, time(nullptr)); auto res = db_exec(query, [&](db_row &row) -> bool { access.policy = (policy_t) parse_int(row["policy"]); access.log = parse_int(row["logging"]); access.notify = parse_int(row["notification"]); LOGD("magiskdb: query policy=[%d] log=[%d] notify=[%d]\n", access.policy, access.log, access.notify); return true; }); if (res.check_err()) return; } // We need to check our manager if (access.log || access.notify) { mgr_uid = get_manager(to_user_id(eval_uid), &mgr_pkg, true); } } bool uid_granted_root(int uid) { if (uid == AID_ROOT) return true; db_settings cfg; get_db_settings(cfg); // Check user root access settings switch (cfg[ROOT_ACCESS]) { case ROOT_ACCESS_DISABLED: return false; case ROOT_ACCESS_APPS_ONLY: if (uid == AID_SHELL) return false; break; case ROOT_ACCESS_ADB_ONLY: if (uid != AID_SHELL) return false; break; case ROOT_ACCESS_APPS_AND_ADB: break; } // Check multiuser settings switch (cfg[SU_MULTIUSER_MODE]) { case MULTIUSER_MODE_OWNER_ONLY: if (to_user_id(uid) != 0) return false; break; case MULTIUSER_MODE_OWNER_MANAGED: uid = to_app_id(uid); break; case MULTIUSER_MODE_USER: default: break; } bool granted = false; char query[256]; ssprintf(query, sizeof(query), "SELECT policy FROM policies WHERE uid=%d AND (until=0 OR until>%li)", uid, time(nullptr)); auto res = db_exec(query, [&](db_row &row) -> bool { granted = parse_int(row["policy"]) == ALLOW; return true; }); if (res.check_err()) return false; return granted; } void prune_su_access() { cached.reset(); vector<bool> app_no_list = get_app_no_list(); vector<int> rm_uids; auto res = db_exec("SELECT uid FROM policies", [&](db_row &row) -> bool { int uid = parse_int(row["uid"]); int app_id = to_app_id(uid); if (app_id >= AID_APP_START && app_id <= AID_APP_END) { int app_no = app_id - AID_APP_START; if (app_no >= app_no_list.size() || !app_no_list[app_no]) { // The app_id is no longer installed rm_uids.push_back(uid); } } return true; }); if (res.check_err()) return; for (int uid : rm_uids) { char query[256]; ssprintf(query, sizeof(query), "DELETE FROM policies WHERE uid == %d", uid); db_exec(query).check_err(); } } static shared_ptr<su_info> get_su_info(unsigned uid) { if (uid == AID_ROOT) { auto info = make_shared<su_info>(uid); info->access = SILENT_SU_ACCESS; return info; } shared_ptr<su_info> info; { mutex_guard lock(cache_lock); if (!cached || cached->uid != uid || !cached->is_fresh()) cached = make_shared<su_info>(uid); cached->refresh(); info = cached; } mutex_guard lock = info->lock(); if (info->access.policy == QUERY) { // Not cached, get data from database info->check_db(); // If it's the manager, allow it silently if (to_app_id(info->uid) == to_app_id(info->mgr_uid)) { info->access = SILENT_SU_ACCESS; return info; } // Check su access settings switch (info->cfg[ROOT_ACCESS]) { case ROOT_ACCESS_DISABLED: LOGW("Root access is disabled!\n"); info->access = NO_SU_ACCESS; break; case ROOT_ACCESS_ADB_ONLY: if (info->uid != AID_SHELL) { LOGW("Root access limited to ADB only!\n"); info->access = NO_SU_ACCESS; } break; case ROOT_ACCESS_APPS_ONLY: if (info->uid == AID_SHELL) { LOGW("Root access is disabled for ADB!\n"); info->access = NO_SU_ACCESS; } break; case ROOT_ACCESS_APPS_AND_ADB: default: break; } if (info->access.policy != QUERY) return info; // If still not determined, check if manager exists if (info->mgr_uid < 0) { info->access = NO_SU_ACCESS; return info; } } return info; } // Set effective uid back to root, otherwise setres[ug]id will fail if uid isn't root static void set_identity(uid_t uid, const std::vector<uid_t> &groups) { if (seteuid(0)) { PLOGE("seteuid (root)"); } gid_t gid; if (groups.size() > 0) { if (setgroups(groups.size(), groups.data())) { PLOGE("setgroups"); } gid = groups[0]; } else { gid = uid; } if (setresgid(gid, gid, gid)) { PLOGE("setresgid (%u)", uid); } if (setresuid(uid, uid, uid)) { PLOGE("setresuid (%u)", uid); } } void su_daemon_handler(int client, const sock_cred *cred) { LOGD("su: request from uid=[%d], pid=[%d], client=[%d]\n", cred->uid, cred->pid, client); su_context ctx = { .info = get_su_info(cred->uid), .req = su_request(), .pid = cred->pid }; // Read su_request if (xxread(client, &ctx.req, sizeof(su_req_base)) < 0 || !read_string(client, ctx.req.shell) || !read_string(client, ctx.req.command) || !read_string(client, ctx.req.context) || !read_vector(client, ctx.req.gids)) { LOGW("su: remote process probably died, abort\n"); ctx.info.reset(); write_int(client, DENY); close(client); return; } // If still not determined, ask manager if (ctx.info->access.policy == QUERY) { int fd = app_request(ctx); if (fd < 0) { ctx.info->access.policy = DENY; } else { int ret = read_int_be(fd); ctx.info->access.policy = ret < 0 ? DENY : static_cast<policy_t>(ret); close(fd); } } if (ctx.info->access.log) app_log(ctx); else if (ctx.info->access.notify) app_notify(ctx); // Fail fast if (ctx.info->access.policy == DENY) { LOGW("su: request rejected (%u)\n", ctx.info->uid); ctx.info.reset(); write_int(client, DENY); close(client); return; } // Fork a child root process // // The child process will need to setsid, open a pseudo-terminal // if needed, and eventually exec shell. // The parent process will wait for the result and // send the return code back to our client. if (int child = xfork(); child) { ctx.info.reset(); // Wait result LOGD("su: waiting child pid=[%d]\n", child); int status, code; if (waitpid(child, &status, 0) > 0) code = WEXITSTATUS(status); else code = -1; LOGD("su: return code=[%d]\n", code); write(client, &code, sizeof(code)); close(client); return; } LOGD("su: fork handler\n"); // Abort upon any error occurred exit_on_error(true); // ack write_int(client, 0); // Become session leader xsetsid(); // The FDs for each of the streams int infd = recv_fd(client); int outfd = recv_fd(client); int errfd = recv_fd(client); // App need a PTY if (read_int(client)) { string pts; string ptmx; auto magiskpts = get_magisk_tmp() + "/"s SHELLPTS; if (access(magiskpts.data(), F_OK)) { pts = "/dev/pts"; ptmx = "/dev/ptmx"; } else { pts = magiskpts; ptmx = magiskpts + "/ptmx"; } int ptmx_fd = xopen(ptmx.data(), O_RDWR); grantpt(ptmx_fd); unlockpt(ptmx_fd); int pty_num = get_pty_num(ptmx_fd); if (pty_num < 0) { // Kernel issue? Fallback to /dev/pts close(ptmx_fd); pts = "/dev/pts"; ptmx_fd = xopen("/dev/ptmx", O_RDWR); grantpt(ptmx_fd); unlockpt(ptmx_fd); pty_num = get_pty_num(ptmx_fd); } send_fd(client, ptmx_fd); close(ptmx_fd); string pts_slave = pts + "/" + to_string(pty_num); LOGD("su: pts_slave=[%s]\n", pts_slave.data()); // Opening the TTY has to occur after the // fork() and setsid() so that it becomes // our controlling TTY and not the daemon's int ptsfd = xopen(pts_slave.data(), O_RDWR); if (infd < 0) infd = ptsfd; if (outfd < 0) outfd = ptsfd; if (errfd < 0) errfd = ptsfd; } // Swap out stdin, stdout, stderr xdup2(infd, STDIN_FILENO); xdup2(outfd, STDOUT_FILENO); xdup2(errfd, STDERR_FILENO); close(infd); close(outfd); close(errfd); close(client); // Handle namespaces if (ctx.req.target == -1) ctx.req.target = ctx.pid; else if (ctx.req.target == 0) ctx.info->cfg[SU_MNT_NS] = NAMESPACE_MODE_GLOBAL; else if (ctx.info->cfg[SU_MNT_NS] == NAMESPACE_MODE_GLOBAL) ctx.info->cfg[SU_MNT_NS] = NAMESPACE_MODE_REQUESTER; switch (ctx.info->cfg[SU_MNT_NS]) { case NAMESPACE_MODE_GLOBAL: LOGD("su: use global namespace\n"); break; case NAMESPACE_MODE_REQUESTER: LOGD("su: use namespace of pid=[%d]\n", ctx.req.target); if (switch_mnt_ns(ctx.req.target)) LOGD("su: setns failed, fallback to global\n"); break; case NAMESPACE_MODE_ISOLATE: LOGD("su: use new isolated namespace\n"); switch_mnt_ns(ctx.req.target); xunshare(CLONE_NEWNS); xmount(nullptr, "/", nullptr, MS_PRIVATE | MS_REC, nullptr); break; } const char *argv[4] = { nullptr }; argv[0] = ctx.req.login ? "-" : ctx.req.shell.data(); if (!ctx.req.command.empty()) { argv[1] = "-c"; argv[2] = ctx.req.command.data(); } // Setup environment umask(022); char path[32]; ssprintf(path, sizeof(path), "/proc/%d/cwd", ctx.pid); char cwd[4096]; if (realpath(path, cwd, sizeof(cwd)) > 0) chdir(cwd); ssprintf(path, sizeof(path), "/proc/%d/environ", ctx.pid); auto env = full_read(path); clearenv(); for (size_t pos = 0; pos < env.size(); ++pos) { putenv(env.data() + pos); pos = env.find_first_of('\0', pos); if (pos == std::string::npos) break; } if (!ctx.req.keepenv) { struct passwd *pw; pw = getpwuid(ctx.req.uid); if (pw) { setenv("HOME", pw->pw_dir, 1); setenv("USER", pw->pw_name, 1); setenv("LOGNAME", pw->pw_name, 1); setenv("SHELL", ctx.req.shell.data(), 1); } } // Unblock all signals sigset_t block_set; sigemptyset(&block_set); sigprocmask(SIG_SETMASK, &block_set, nullptr); if (!ctx.req.context.empty()) { auto f = xopen_file("/proc/self/attr/exec", "we"); if (f) fprintf(f.get(), "%s", ctx.req.context.data()); } set_identity(ctx.req.uid, ctx.req.gids); execvp(ctx.req.shell.data(), (char **) argv); fprintf(stderr, "Cannot execute %s: %s\n", ctx.req.shell.data(), strerror(errno)); PLOGE("exec"); }
13,266
C++
.cpp
408
24.583333
93
0.548637
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
14
connect.cpp
topjohnwu_Magisk/native/src/core/su/connect.cpp
#include <sys/types.h> #include <sys/wait.h> #include <base.hpp> #include <selinux.hpp> #include <consts.hpp> #include "su.hpp" using namespace std; #define CALL_PROVIDER \ "/system/bin/app_process", "/system/bin", "com.android.commands.content.Content", \ "call", "--uri", target, "--user", user, "--method", action #define START_ACTIVITY \ "/system/bin/app_process", "/system/bin", "com.android.commands.am.Am", \ "start", "-p", target, "--user", user, "-a", "android.intent.action.VIEW", \ "-f", "0x18800020", "--es", "action", action // 0x18800020 = FLAG_ACTIVITY_NEW_TASK|FLAG_ACTIVITY_MULTIPLE_TASK| // FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS|FLAG_INCLUDE_STOPPED_PACKAGES #define get_cmd(to) \ ((to).command.empty() ? \ ((to).shell.empty() ? DEFAULT_SHELL : (to).shell.data()) : \ (to).command.data()) class Extra { const char *key; enum { INT, BOOL, STRING, INTLIST, } type; union { int int_val; bool bool_val; const char *str_val; const vector<uint32_t> *intlist_val; }; string str; public: Extra(const char *k, int v): key(k), type(INT), int_val(v) {} Extra(const char *k, bool v): key(k), type(BOOL), bool_val(v) {} Extra(const char *k, const char *v): key(k), type(STRING), str_val(v) {} Extra(const char *k, const vector<uint32_t> *v): key(k), type(INTLIST), intlist_val(v) {} void add_intent(vector<const char *> &vec) { const char *val; switch (type) { case INT: vec.push_back("--ei"); str = to_string(int_val); val = str.data(); break; case BOOL: vec.push_back("--ez"); val = bool_val ? "true" : "false"; break; case STRING: vec.push_back("--es"); val = str_val; break; case INTLIST: vec.push_back("--es"); for (auto i : *intlist_val) { str += to_string(i); str += ","; } if (!str.empty()) str.pop_back(); val = str.data(); break; } vec.push_back(key); vec.push_back(val); } void add_bind(vector<const char *> &vec) { char buf[32]; str = key; switch (type) { case INT: str += ":i:"; ssprintf(buf, sizeof(buf), "%d", int_val); str += buf; break; case BOOL: str += ":b:"; str += bool_val ? "true" : "false"; break; case STRING: str += ":s:"; if (SDK_INT >= 30) { string tmp = str_val; replace_all(tmp, "\\", "\\\\"); replace_all(tmp, ":", "\\:"); str += tmp; } else { str += str_val; } break; case INTLIST: str += ":s:"; for (auto i : *intlist_val) { str += to_string(i); str += ","; } if (str.back() == ',') str.pop_back(); break; } vec.push_back("--extra"); vec.push_back(str.data()); } }; static bool check_no_error(int fd) { char buf[1024]; auto out = xopen_file(fd, "r"); while (fgets(buf, sizeof(buf), out.get())) { if (strncasecmp(buf, "Error", 5) == 0) { LOGD("exec_cmd: %s\n", buf); return false; } } return true; } static void exec_cmd(const char *action, vector<Extra> &data, const shared_ptr<su_info> &info, bool provider = true) { char target[128]; char user[4]; ssprintf(user, sizeof(user), "%d", to_user_id(info->eval_uid)); // First try content provider call method if (provider) { ssprintf(target, sizeof(target), "content://%s.provider", info->mgr_pkg.data()); vector<const char *> args{ CALL_PROVIDER }; for (auto &e : data) { e.add_bind(args); } args.push_back(nullptr); exec_t exec { .err = true, .fd = -1, .pre_exec = [] { setenv("CLASSPATH", "/system/framework/content.jar", 1); }, .argv = args.data() }; exec_command_sync(exec); if (check_no_error(exec.fd)) return; } // Then try start activity with package name strscpy(target, info->mgr_pkg.data(), sizeof(target)); vector<const char *> args{ START_ACTIVITY }; for (auto &e : data) { e.add_intent(args); } args.push_back(nullptr); exec_t exec { .fd = -2, .pre_exec = [] { setenv("CLASSPATH", "/system/framework/am.jar", 1); }, .fork = fork_dont_care, .argv = args.data() }; exec_command(exec); } void app_log(const su_context &ctx) { if (fork_dont_care() == 0) { vector<Extra> extras; extras.reserve(9); extras.emplace_back("from.uid", ctx.info->uid); extras.emplace_back("to.uid", static_cast<int>(ctx.req.uid)); extras.emplace_back("pid", ctx.pid); extras.emplace_back("policy", ctx.info->access.policy); extras.emplace_back("target", ctx.req.target); extras.emplace_back("context", ctx.req.context.data()); extras.emplace_back("gids", &ctx.req.gids); extras.emplace_back("command", get_cmd(ctx.req)); extras.emplace_back("notify", (bool) ctx.info->access.notify); exec_cmd("log", extras, ctx.info); exit(0); } } void app_notify(const su_context &ctx) { if (fork_dont_care() == 0) { vector<Extra> extras; extras.reserve(3); extras.emplace_back("from.uid", ctx.info->uid); extras.emplace_back("pid", ctx.pid); extras.emplace_back("policy", ctx.info->access.policy); exec_cmd("notify", extras, ctx.info); exit(0); } } int app_request(const su_context &ctx) { // Create FIFO char fifo[64]; ssprintf(fifo, sizeof(fifo), "%s/" INTLROOT "/su_request_%d", get_magisk_tmp(), ctx.pid); mkfifo(fifo, 0600); chown(fifo, ctx.info->mgr_uid, ctx.info->mgr_uid); setfilecon(fifo, MAGISK_FILE_CON); // Send request vector<Extra> extras; extras.reserve(3); extras.emplace_back("fifo", fifo); extras.emplace_back("uid", ctx.info->eval_uid); extras.emplace_back("pid", ctx.pid); exec_cmd("request", extras, ctx.info, false); // Wait for data input for at most 70 seconds // Open with O_RDWR to prevent FIFO open block int fd = xopen(fifo, O_RDWR | O_CLOEXEC); struct pollfd pfd = { .fd = fd, .events = POLLIN }; if (xpoll(&pfd, 1, 70 * 1000) <= 0) { close(fd); fd = -1; } unlink(fifo); return fd; }
6,835
C++
.cpp
211
24.49763
93
0.530445
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16
su.cpp
topjohnwu_Magisk/native/src/core/su/su.cpp
/* * Copyright 2017 - 2023, John Wu (@topjohnwu) * Copyright 2015, Pierre-Hugues Husson <phh@phh.me> * Copyright 2010, Adam Shanks (@ChainsDD) * Copyright 2008, Zinx Verituse (@zinxv) */ #include <unistd.h> #include <getopt.h> #include <fcntl.h> #include <pwd.h> #include <sched.h> #include <sys/types.h> #include <sys/stat.h> #include <consts.hpp> #include <base.hpp> #include <flags.h> #include "su.hpp" #include "pts.hpp" int quit_signals[] = { SIGALRM, SIGABRT, SIGHUP, SIGPIPE, SIGQUIT, SIGTERM, SIGINT, 0 }; [[noreturn]] static void usage(int status) { FILE *stream = (status == EXIT_SUCCESS) ? stdout : stderr; fprintf(stream, "MagiskSU\n\n" "Usage: su [options] [-] [user [argument...]]\n\n" "Options:\n" " -c, --command COMMAND Pass COMMAND to the invoked shell\n" " -g, --group GROUP Specify the primary group\n" " -G, --supp-group GROUP Specify a supplementary group.\n" " The first specified supplementary group is also used\n" " as a primary group if the option -g is not specified.\n" " -Z, --context CONTEXT Change SELinux context\n" " -t, --target PID PID to take mount namespace from\n" " -h, --help Display this help message and exit\n" " -, -l, --login Pretend the shell to be a login shell\n" " -m, -p,\n" " --preserve-environment Preserve the entire environment\n" " -s, --shell SHELL Use SHELL instead of the default " DEFAULT_SHELL "\n" " -v, --version Display version number and exit\n" " -V Display version code and exit\n" " -mm, -M,\n" " --mount-master Force run in the global mount namespace\n\n"); exit(status); } static void sighandler(int sig) { restore_stdin(); // Assume we'll only be called before death // See note before sigaction() in set_stdin_raw() // // Now, close all standard I/O to cause the pumps // to exit so we can continue and retrieve the exit // code close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); // Put back all the default handlers struct sigaction act; memset(&act, 0, sizeof(act)); act.sa_handler = SIG_DFL; for (int i = 0; quit_signals[i]; ++i) { sigaction(quit_signals[i], &act, nullptr); } } static void setup_sighandlers(void (*handler)(int)) { struct sigaction act; memset(&act, 0, sizeof(act)); act.sa_handler = handler; for (int i = 0; quit_signals[i]; ++i) { sigaction(quit_signals[i], &act, nullptr); } } int su_client_main(int argc, char *argv[]) { int c; struct option long_opts[] = { { "command", required_argument, nullptr, 'c' }, { "help", no_argument, nullptr, 'h' }, { "login", no_argument, nullptr, 'l' }, { "preserve-environment", no_argument, nullptr, 'p' }, { "shell", required_argument, nullptr, 's' }, { "version", no_argument, nullptr, 'v' }, { "context", required_argument, nullptr, 'Z' }, { "mount-master", no_argument, nullptr, 'M' }, { "target", required_argument, nullptr, 't' }, { "group", required_argument, nullptr, 'g' }, { "supp-group", required_argument, nullptr, 'G' }, { nullptr, 0, nullptr, 0 }, }; su_request su_req; for (int i = 0; i < argc; i++) { // Replace -cn and -z with -Z for backwards compatibility if (strcmp(argv[i], "-cn") == 0 || strcmp(argv[i], "-z") == 0) strcpy(argv[i], "-Z"); // Replace -mm with -M for supporting getopt_long else if (strcmp(argv[i], "-mm") == 0) strcpy(argv[i], "-M"); } while ((c = getopt_long(argc, argv, "c:hlmps:VvuZ:Mt:g:G:", long_opts, nullptr)) != -1) { switch (c) { case 'c': for (int i = optind - 1; i < argc; ++i) { if (!su_req.command.empty()) su_req.command += ' '; su_req.command += argv[i]; } optind = argc; break; case 'h': usage(EXIT_SUCCESS); case 'l': su_req.login = true; break; case 'm': case 'p': su_req.keepenv = true; break; case 's': su_req.shell = optarg; break; case 'V': printf("%d\n", MAGISK_VER_CODE); exit(EXIT_SUCCESS); case 'v': printf("%s\n", MAGISK_VERSION ":MAGISKSU"); exit(EXIT_SUCCESS); case 'Z': su_req.context = optarg; break; case 'M': case 't': if (su_req.target != -1) { fprintf(stderr, "Can't use -M and -t at the same time\n"); usage(EXIT_FAILURE); } if (optarg == nullptr) { su_req.target = 0; } else { su_req.target = parse_int(optarg); if (*optarg == '-' || su_req.target == -1) { fprintf(stderr, "Invalid PID: %s\n", optarg); usage(EXIT_FAILURE); } } break; case 'g': case 'G': if (int gid = parse_int(optarg); gid >= 0) { su_req.gids.insert(c == 'g' ? su_req.gids.begin() : su_req.gids.end(), gid); } else { fprintf(stderr, "Invalid GID: %s\n", optarg); usage(EXIT_FAILURE); } break; default: /* Bionic getopt_long doesn't terminate its error output by newline */ fprintf(stderr, "\n"); usage(2); } } if (optind < argc && strcmp(argv[optind], "-") == 0) { su_req.login = true; optind++; } /* username or uid */ if (optind < argc) { struct passwd *pw; pw = getpwnam(argv[optind]); if (pw) su_req.uid = pw->pw_uid; else su_req.uid = parse_int(argv[optind]); optind++; } int ptmx, fd; // Connect to client fd = connect_daemon(+RequestCode::SUPERUSER); // Send su_request xwrite(fd, &su_req, sizeof(su_req_base)); write_string(fd, su_req.shell); write_string(fd, su_req.command); write_string(fd, su_req.context); write_vector(fd, su_req.gids); // Wait for ack from daemon if (read_int(fd)) { // Fast fail fprintf(stderr, "%s\n", strerror(EACCES)); return EACCES; } // Determine which one of our streams are attached to a TTY int atty = 0; if (isatty(STDIN_FILENO)) atty |= ATTY_IN; if (isatty(STDOUT_FILENO)) atty |= ATTY_OUT; if (isatty(STDERR_FILENO)) atty |= ATTY_ERR; // Send stdin send_fd(fd, (atty & ATTY_IN) ? -1 : STDIN_FILENO); // Send stdout send_fd(fd, (atty & ATTY_OUT) ? -1 : STDOUT_FILENO); // Send stderr send_fd(fd, (atty & ATTY_ERR) ? -1 : STDERR_FILENO); if (atty) { // We need a PTY. Get one. write_int(fd, 1); ptmx = recv_fd(fd); } else { write_int(fd, 0); } if (atty) { setup_sighandlers(sighandler); watch_sigwinch_async(STDOUT_FILENO, ptmx); pump_stdin_async(ptmx); pump_stdout_blocking(ptmx); } // Get the exit code int code = read_int(fd); close(fd); return code; }
8,039
C++
.cpp
215
28.376744
96
0.496153
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
17
cli.cpp
topjohnwu_Magisk/native/src/core/deny/cli.cpp
#include <sys/wait.h> #include <sys/mount.h> #include <consts.hpp> #include <base.hpp> #include "deny.hpp" using namespace std; [[noreturn]] static void usage() { fprintf(stderr, R"EOF(DenyList Config CLI Usage: magisk --denylist [action [arguments...] ] Actions: status Return the enforcement status enable Enable denylist enforcement disable Disable denylist enforcement add PKG [PROC] Add a new target to the denylist rm PKG [PROC] Remove target(s) from the denylist ls Print the current denylist exec CMDs... Execute commands in isolated mount namespace and do all unmounts )EOF"); exit(1); } void denylist_handler(int client, const sock_cred *cred) { if (client < 0) { revert_unmount(); return; } int req = read_int(client); int res = DenyResponse::ERROR; switch (req) { case DenyRequest::ENFORCE: res = enable_deny(); break; case DenyRequest::DISABLE: res = disable_deny(); break; case DenyRequest::ADD: res = add_list(client); break; case DenyRequest::REMOVE: res = rm_list(client); break; case DenyRequest::LIST: ls_list(client); return; case DenyRequest::STATUS: res = denylist_enforced ? DenyResponse::ENFORCED : DenyResponse::NOT_ENFORCED; break; default: // Unknown request code break; } write_int(client, res); close(client); } int denylist_cli(int argc, char **argv) { if (argc < 2) usage(); int req; if (argv[1] == "enable"sv) req = DenyRequest::ENFORCE; else if (argv[1] == "disable"sv) req = DenyRequest::DISABLE; else if (argv[1] == "add"sv) req = DenyRequest::ADD; else if (argv[1] == "rm"sv) req = DenyRequest::REMOVE; else if (argv[1] == "ls"sv) req = DenyRequest::LIST; else if (argv[1] == "status"sv) req = DenyRequest::STATUS; else if (argv[1] == "exec"sv && argc > 2) { xunshare(CLONE_NEWNS); xmount(nullptr, "/", nullptr, MS_PRIVATE | MS_REC, nullptr); revert_unmount(); execvp(argv[2], argv + 2); exit(1); } else { usage(); } // Send request int fd = connect_daemon(+RequestCode::DENYLIST); write_int(fd, req); if (req == DenyRequest::ADD || req == DenyRequest::REMOVE) { write_string(fd, argv[2]); write_string(fd, argv[3] ? argv[3] : ""); } // Get response int res = read_int(fd); if (res < 0 || res >= DenyResponse::END) res = DenyResponse::ERROR; switch (res) { case DenyResponse::NOT_ENFORCED: fprintf(stderr, "Denylist is not enforced\n"); goto return_code; case DenyResponse::ENFORCED: fprintf(stderr, "Denylist is enforced\n"); goto return_code; case DenyResponse::ITEM_EXIST: fprintf(stderr, "Target already exists in denylist\n"); goto return_code; case DenyResponse::ITEM_NOT_EXIST: fprintf(stderr, "Target does not exist in denylist\n"); goto return_code; case DenyResponse::NO_NS: fprintf(stderr, "The kernel does not support mount namespace\n"); goto return_code; case DenyResponse::INVALID_PKG: fprintf(stderr, "Invalid package / process name\n"); goto return_code; case DenyResponse::ERROR: fprintf(stderr, "deny: Daemon error\n"); return -1; case DenyResponse::OK: break; default: __builtin_unreachable(); } if (req == DenyRequest::LIST) { string out; for (;;) { read_string(fd, out); if (out.empty()) break; printf("%s\n", out.data()); } } return_code: return req == DenyRequest::STATUS ? res != DenyResponse::ENFORCED : res != DenyResponse::OK; }
3,953
C++
.cpp
130
23.907692
96
0.5948
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
18
logcat.cpp
topjohnwu_Magisk/native/src/core/deny/logcat.cpp
#include <unistd.h> #include <string> #include <cinttypes> #include <android/log.h> #include <sys/syscall.h> #include <base.hpp> #include "deny.hpp" using namespace std; struct logger_entry { uint16_t len; /* length of the payload */ uint16_t hdr_size; /* sizeof(struct logger_entry) */ int32_t pid; /* generating process's pid */ uint32_t tid; /* generating process's tid */ uint32_t sec; /* seconds since Epoch */ uint32_t nsec; /* nanoseconds */ uint32_t lid; /* log id of the payload, bottom 4 bits currently */ uint32_t uid; /* generating process's uid */ }; #define LOGGER_ENTRY_MAX_LEN (5 * 1024) struct log_msg { union [[gnu::aligned(4)]] { unsigned char buf[LOGGER_ENTRY_MAX_LEN + 1]; struct logger_entry entry; }; }; struct AndroidLogEntry { time_t tv_sec; long tv_nsec; android_LogPriority priority; int32_t uid; int32_t pid; int32_t tid; const char *tag; size_t tagLen; size_t messageLen; const char *message; }; struct [[gnu::packed]] android_event_header_t { int32_t tag; // Little Endian Order }; struct [[gnu::packed]] android_event_int_t { int8_t type; // EVENT_TYPE_INT int32_t data; // Little Endian Order }; struct [[gnu::packed]] android_event_string_t { int8_t type; // EVENT_TYPE_STRING; int32_t length; // Little Endian Order char data[]; }; struct [[gnu::packed]] android_event_list_t { int8_t type; // EVENT_TYPE_LIST int8_t element_count; } ; // 30014 am_proc_start (User|1|5),(PID|1|5),(UID|1|5),(Process Name|3),(Type|3),(Component|3) struct [[gnu::packed]] android_event_am_proc_start { android_event_header_t tag; android_event_list_t list; android_event_int_t user; android_event_int_t pid; android_event_int_t uid; android_event_string_t process_name; // android_event_string_t type; // android_event_string_t component; }; // 3040 boot_progress_ams_ready (time|2|3) extern "C" { [[gnu::weak]] struct logger_list *android_logger_list_alloc(int mode, unsigned int tail, pid_t pid); [[gnu::weak]] void android_logger_list_free(struct logger_list *list); [[gnu::weak]] int android_logger_list_read(struct logger_list *list, struct log_msg *log_msg); [[gnu::weak]] struct logger *android_logger_open(struct logger_list *list, log_id_t id); [[gnu::weak]] int android_log_processLogBuffer(struct logger_entry *buf, AndroidLogEntry *entry); } // zygote pid -> mnt ns static map<int, struct stat> zygote_map; bool logcat_exit; static int read_ns(const int pid, struct stat *st) { char path[32]; sprintf(path, "/proc/%d/ns/mnt", pid); return stat(path, st); } static int parse_ppid(int pid) { char path[32]; int ppid; sprintf(path, "/proc/%d/stat", pid); auto stat = open_file(path, "re"); if (!stat) return -1; // PID COMM STATE PPID ..... fscanf(stat.get(), "%*d %*s %*c %d", &ppid); return ppid; } static void check_zygote() { zygote_map.clear(); int proc = open("/proc", O_RDONLY | O_CLOEXEC); auto proc_dir = xopen_dir(proc); if (!proc_dir) return; struct stat st{}; for (dirent *entry; (entry = readdir(proc_dir.get()));) { int pid = parse_int(entry->d_name); if (pid <= 0) continue; if (fstatat(proc, entry->d_name, &st, 0)) continue; if (st.st_uid != 0) continue; if (proc_context_match(pid, "u:r:zygote:s0") && parse_ppid(pid) == 1) { if (read_ns(pid, &st) == 0) { LOGI("logcat: zygote PID=[%d]\n", pid); zygote_map[pid] = st; } } } } static void process_main_buffer(struct log_msg *msg) { AndroidLogEntry entry{}; if (android_log_processLogBuffer(&msg->entry, &entry) < 0) return; entry.tagLen--; auto tag = string_view(entry.tag, entry.tagLen); static bool ready = false; if (tag == "AppZygote") { if (entry.uid != 1000) return; if (entry.message[0] == 'S') { ready = true; } else { ready = false; } return; } if (!ready || tag != "AppZygoteInit") return; if (!proc_context_match(msg->entry.pid, "u:r:app_zygote:s0")) return; ready = false; char cmdline[1024]; sprintf(cmdline, "/proc/%d/cmdline", msg->entry.pid); if (auto f = open_file(cmdline, "re")) { fgets(cmdline, sizeof(cmdline), f.get()); } else { return; } if (is_deny_target(entry.uid, cmdline)) { int pid = msg->entry.pid; kill(pid, SIGSTOP); if (fork_dont_care() == 0) { LOGI("logcat: revert [%s] PID=[%d] UID=[%d]\n", cmdline, pid, entry.uid); revert_unmount(pid); kill(pid, SIGCONT); _exit(0); } } else { LOGD("logcat: skip [%s] PID=[%d] UID=[%d]\n", cmdline, msg->entry.pid, entry.uid); } } static void process_events_buffer(struct log_msg *msg) { if (msg->entry.uid != 1000) return; auto event_data = &msg->buf[msg->entry.hdr_size]; auto event_header = reinterpret_cast<const android_event_header_t *>(event_data); if (event_header->tag == 30014) { auto am_proc_start = reinterpret_cast<const android_event_am_proc_start *>(event_data); auto proc = string_view(am_proc_start->process_name.data, am_proc_start->process_name.length); if (is_deny_target(am_proc_start->uid.data, proc)) { int pid = am_proc_start->pid.data; if (fork_dont_care() == 0) { int ppid = parse_ppid(pid); auto it = zygote_map.find(ppid); if (it == zygote_map.end()) { LOGW("logcat: skip [%.*s] PID=[%d] UID=[%d] PPID=[%d]; parent not zygote\n", (int) proc.length(), proc.data(), pid, am_proc_start->uid.data, ppid); _exit(0); } char path[16]; ssprintf(path, sizeof(path), "/proc/%d", pid); struct stat st{}; int fd = syscall(__NR_pidfd_open, pid, 0); if (fd > 0 && setns(fd, CLONE_NEWNS) == 0) { pid = getpid(); } else { close(fd); fd = -1; } while (read_ns(pid, &st) == 0 && it->second.st_ino == st.st_ino) { if (stat(path, &st) == 0 && st.st_uid == 0) { usleep(10 * 1000); } else { LOGW("logcat: skip [%.*s] PID=[%s] UID=[%d]; namespace not isolated\n", (int) proc.length(), proc.data(), path + 6, am_proc_start->uid.data); _exit(0); } if (fd > 0) setns(fd, CLONE_NEWNS); } close(fd); LOGI("logcat: revert [%.*s] PID=[%d] UID=[%d]\n", (int) proc.length(), proc.data(), pid, am_proc_start->uid.data); revert_unmount(pid); _exit(0); } } else { LOGD("logcat: skip [%.*s] PID=[%d] UID=[%d]\n", (int) proc.length(), proc.data(), am_proc_start->pid.data, am_proc_start->uid.data); } return; } if (event_header->tag == 3040) { LOGD("logcat: soft reboot\n"); check_zygote(); } } [[noreturn]] void run() { while (true) { const unique_ptr<logger_list, decltype(&android_logger_list_free)> logger_list{ android_logger_list_alloc(0, 1, 0), &android_logger_list_free}; for (log_id id: {LOG_ID_MAIN, LOG_ID_EVENTS}) { auto *logger = android_logger_open(logger_list.get(), id); if (logger == nullptr) continue; } struct log_msg msg{}; while (true) { if (!denylist_enforced) { break; } if (android_logger_list_read(logger_list.get(), &msg) <= 0) { break; } switch (msg.entry.lid) { case LOG_ID_EVENTS: process_events_buffer(&msg); break; case LOG_ID_MAIN: process_main_buffer(&msg); default: break; } } if (!denylist_enforced) { break; } sleep(1); } LOGD("logcat: terminate\n"); pthread_exit(nullptr); } void *logcat(void *) { check_zygote(); run(); }
8,702
C++
.cpp
243
27.242798
100
0.537694
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19
utils.cpp
topjohnwu_Magisk/native/src/core/deny/utils.cpp
#include <sys/types.h> #include <sys/stat.h> #include <sys/inotify.h> #include <unistd.h> #include <fcntl.h> #include <dirent.h> #include <set> #include <consts.hpp> #include <base.hpp> #include <db.hpp> #include <core.hpp> #include "deny.hpp" using namespace std; // For the following data structures: // If package name == ISOLATED_MAGIC, or app ID == -1, it means isolated service // Package name -> list of process names static unique_ptr<map<string, set<string, StringCmp>, StringCmp>> pkg_to_procs_; #define pkg_to_procs (*pkg_to_procs_) // app ID -> list of pkg names (string_view points to a pkg_to_procs key) static unique_ptr<map<int, set<string_view>>> app_id_to_pkgs_; #define app_id_to_pkgs (*app_id_to_pkgs_) // Locks the data structures above static pthread_mutex_t data_lock = PTHREAD_MUTEX_INITIALIZER; atomic<bool> denylist_enforced = false; static int get_app_id(const vector<int> &users, const string &pkg) { struct stat st{}; char buf[PATH_MAX]; for (const auto &user_id: users) { ssprintf(buf, sizeof(buf), "%s/%d/%s", APP_DATA_DIR, user_id, pkg.data()); if (stat(buf, &st) == 0) { return to_app_id(st.st_uid); } } return 0; } static void collect_users(vector<int> &users) { auto data_dir = xopen_dir(APP_DATA_DIR); if (!data_dir) return; dirent *entry; while ((entry = xreaddir(data_dir.get()))) { users.emplace_back(parse_int(entry->d_name)); } } static int get_app_id(const string &pkg) { if (pkg == ISOLATED_MAGIC) return -1; vector<int> users; collect_users(users); return get_app_id(users, pkg); } static void update_app_id(int app_id, const string &pkg, bool remove) { if (app_id <= 0) return; if (remove) { if (auto it = app_id_to_pkgs.find(app_id); it != app_id_to_pkgs.end()) { it->second.erase(pkg); if (it->second.empty()) { app_id_to_pkgs.erase(it); } } } else { app_id_to_pkgs[app_id].emplace(pkg); } } // Leave /proc fd opened as we're going to read from it repeatedly static DIR *procfp; template<class F> static void crawl_procfs(const F &fn) { rewinddir(procfp); dirent *dp; int pid; while ((dp = readdir(procfp))) { pid = parse_int(dp->d_name); if (pid > 0 && !fn(pid)) break; } } static inline bool str_eql(string_view a, string_view b) { return a == b; } template<bool str_op(string_view, string_view) = &str_eql> static bool proc_name_match(int pid, string_view name) { char buf[4019]; sprintf(buf, "/proc/%d/cmdline", pid); if (auto fp = open_file(buf, "re")) { fgets(buf, sizeof(buf), fp.get()); if (str_op(buf, name)) { return true; } } return false; } bool proc_context_match(int pid, string_view context) { char buf[PATH_MAX]; sprintf(buf, "/proc/%d/attr/current", pid); if (auto fp = open_file(buf, "re")) { fgets(buf, sizeof(buf), fp.get()); if (str_starts(buf, context)) { return true; } } return false; } template<bool matcher(int, string_view) = &proc_name_match> static void kill_process(const char *name, bool multi = false) { crawl_procfs([=](int pid) -> bool { if (matcher(pid, name)) { kill(pid, SIGKILL); LOGD("denylist: kill PID=[%d] (%s)\n", pid, name); return multi; } return true; }); } static bool validate(const char *pkg, const char *proc) { bool pkg_valid = false; bool proc_valid = true; if (str_eql(pkg, ISOLATED_MAGIC)) { pkg_valid = true; for (char c; (c = *proc); ++proc) { if (isalnum(c) || c == '_' || c == '.') continue; if (c == ':') break; proc_valid = false; break; } } else { for (char c; (c = *pkg); ++pkg) { if (isalnum(c) || c == '_') continue; if (c == '.') { pkg_valid = true; continue; } pkg_valid = false; break; } for (char c; (c = *proc); ++proc) { if (isalnum(c) || c == '_' || c == ':' || c == '.') continue; proc_valid = false; break; } } return pkg_valid && proc_valid; } static bool add_hide_set(const char *pkg, const char *proc) { auto p = pkg_to_procs[pkg].emplace(proc); if (!p.second) return false; LOGI("denylist add: [%s/%s]\n", pkg, proc); if (!denylist_enforced) return true; if (str_eql(pkg, ISOLATED_MAGIC)) { // Kill all matching isolated processes kill_process<&proc_name_match<str_starts>>(proc, true); } else { kill_process(proc); } return true; } void scan_deny_apps() { if (!app_id_to_pkgs_) return; app_id_to_pkgs.clear(); char sql[4096]; vector<int> users; collect_users(users); for (auto it = pkg_to_procs.begin(); it != pkg_to_procs.end();) { if (it->first == ISOLATED_MAGIC) { it++; continue; } int app_id = get_app_id(users, it->first); if (app_id == 0) { LOGI("denylist rm: [%s]\n", it->first.data()); ssprintf(sql, sizeof(sql), "DELETE FROM denylist WHERE package_name='%s'", it->first.data()); db_exec(sql).check_err(); it = pkg_to_procs.erase(it); } else { update_app_id(app_id, it->first, false); it++; } } } static void clear_data() { pkg_to_procs_.reset(nullptr); app_id_to_pkgs_.reset(nullptr); } static bool ensure_data() { if (pkg_to_procs_) return true; LOGI("denylist: initializing internal data structures\n"); default_new(pkg_to_procs_); auto res = db_exec("SELECT * FROM denylist", [](db_row &row) -> bool { add_hide_set(row["package_name"].data(), row["process"].data()); return true; }); if (res.check_err()) goto error; default_new(app_id_to_pkgs_); scan_deny_apps(); return true; error: clear_data(); return false; } static int add_list(const char *pkg, const char *proc) { if (proc[0] == '\0') proc = pkg; if (!validate(pkg, proc)) return DenyResponse::INVALID_PKG; { mutex_guard lock(data_lock); if (!ensure_data()) return DenyResponse::ERROR; int app_id = get_app_id(pkg); if (app_id == 0) return DenyResponse::INVALID_PKG; if (!add_hide_set(pkg, proc)) return DenyResponse::ITEM_EXIST; auto it = pkg_to_procs.find(pkg); update_app_id(app_id, it->first, false); } // Add to database char sql[4096]; ssprintf(sql, sizeof(sql), "INSERT INTO denylist (package_name, process) VALUES('%s', '%s')", pkg, proc); return db_exec(sql).check_err() ? DenyResponse::ERROR : DenyResponse::OK; } int add_list(int client) { string pkg = read_string(client); string proc = read_string(client); return add_list(pkg.data(), proc.data()); } static int rm_list(const char *pkg, const char *proc) { { mutex_guard lock(data_lock); if (!ensure_data()) return DenyResponse::ERROR; bool remove = false; auto it = pkg_to_procs.find(pkg); if (it != pkg_to_procs.end()) { if (proc[0] == '\0') { update_app_id(get_app_id(pkg), it->first, true); pkg_to_procs.erase(it); remove = true; LOGI("denylist rm: [%s]\n", pkg); } else if (it->second.erase(proc) != 0) { remove = true; LOGI("denylist rm: [%s/%s]\n", pkg, proc); if (it->second.empty()) { update_app_id(get_app_id(pkg), it->first, true); pkg_to_procs.erase(it); } } } if (!remove) return DenyResponse::ITEM_NOT_EXIST; } char sql[4096]; if (proc[0] == '\0') ssprintf(sql, sizeof(sql), "DELETE FROM denylist WHERE package_name='%s'", pkg); else ssprintf(sql, sizeof(sql), "DELETE FROM denylist WHERE package_name='%s' AND process='%s'", pkg, proc); return db_exec(sql).check_err() ? DenyResponse::ERROR : DenyResponse::OK; } int rm_list(int client) { string pkg = read_string(client); string proc = read_string(client); return rm_list(pkg.data(), proc.data()); } void ls_list(int client) { { mutex_guard lock(data_lock); if (!ensure_data()) { write_int(client, static_cast<int>(DenyResponse::ERROR)); return; } scan_deny_apps(); write_int(client,static_cast<int>(DenyResponse::OK)); for (const auto &[pkg, procs] : pkg_to_procs) { for (const auto &proc : procs) { write_int(client, pkg.size() + proc.size() + 1); xwrite(client, pkg.data(), pkg.size()); xwrite(client, "|", 1); xwrite(client, proc.data(), proc.size()); } } } write_int(client, 0); close(client); } int enable_deny() { if (denylist_enforced) { return DenyResponse::OK; } else { mutex_guard lock(data_lock); if (access("/proc/self/ns/mnt", F_OK) != 0) { LOGW("The kernel does not support mount namespace\n"); return DenyResponse::NO_NS; } if (procfp == nullptr && (procfp = opendir("/proc")) == nullptr) return DenyResponse::ERROR; LOGI("* Enable DenyList\n"); if (!ensure_data()) return DenyResponse::ERROR; denylist_enforced = true; if (!zygisk_enabled) { if (new_daemon_thread(&logcat)) { denylist_enforced = false; return DenyResponse::ERROR; } } // On Android Q+, also kill blastula pool and all app zygotes if (SDK_INT >= 29) { kill_process("usap32", true); kill_process("usap64", true); kill_process<&proc_context_match>("u:r:app_zygote:s0", true); } } set_db_settings(DENYLIST_CONFIG, true); return DenyResponse::OK; } int disable_deny() { if (denylist_enforced.exchange(false)) { LOGI("* Disable DenyList\n"); } set_db_settings(DENYLIST_CONFIG, false); return DenyResponse::OK; } void initialize_denylist() { if (!denylist_enforced) { db_settings dbs; get_db_settings(dbs, DENYLIST_CONFIG); if (dbs[DENYLIST_CONFIG]) enable_deny(); } } bool is_deny_target(int uid, string_view process) { mutex_guard lock(data_lock); if (!ensure_data()) return false; int app_id = to_app_id(uid); if (app_id >= 90000) { if (auto it = pkg_to_procs.find(ISOLATED_MAGIC); it != pkg_to_procs.end()) { for (const auto &s : it->second) { if (str_starts(process, s)) return true; } } return false; } else { auto it = app_id_to_pkgs.find(app_id); if (it == app_id_to_pkgs.end()) return false; for (const auto &pkg : it->second) { if (pkg_to_procs.find(pkg)->second.count(process)) return true; } } return false; }
11,628
C++
.cpp
365
24.271233
92
0.550161
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20
main.cpp
topjohnwu_Magisk/native/src/core/zygisk/main.cpp
#include <sys/mount.h> #include <android/dlext.h> #include <dlfcn.h> #include <consts.hpp> #include <base.hpp> #include <core.hpp> #include <selinux.hpp> #include "zygisk.hpp" using namespace std; static void zygiskd(int socket) { if (getuid() != 0 || fcntl(socket, F_GETFD) < 0) exit(-1); init_thread_pool(); #if defined(__LP64__) set_nice_name("zygiskd64"); LOGI("* Launching zygiskd64\n"); #else set_nice_name("zygiskd32"); LOGI("* Launching zygiskd32\n"); #endif // Load modules using comp_entry = void(*)(int); vector<comp_entry> modules; { vector<int> module_fds = recv_fds(socket); for (int fd : module_fds) { comp_entry entry = nullptr; struct stat s{}; if (fstat(fd, &s) == 0 && S_ISREG(s.st_mode)) { android_dlextinfo info { .flags = ANDROID_DLEXT_USE_LIBRARY_FD, .library_fd = fd, }; if (void *h = android_dlopen_ext("/jit-cache", RTLD_LAZY, &info)) { *(void **) &entry = dlsym(h, "zygisk_companion_entry"); } else { LOGW("Failed to dlopen zygisk module: %s\n", dlerror()); } } modules.push_back(entry); close(fd); } } // ack write_int(socket, 0); // Start accepting requests pollfd pfd = { socket, POLLIN, 0 }; for (;;) { poll(&pfd, 1, -1); if (pfd.revents && !(pfd.revents & POLLIN)) { // Something bad happened in magiskd, terminate zygiskd exit(0); } int client = recv_fd(socket); if (client < 0) { // Something bad happened in magiskd, terminate zygiskd exit(0); } int module_id = read_int(client); if (module_id >= 0 && module_id < modules.size() && modules[module_id]) { exec_task([=, entry = modules[module_id]] { struct stat s1; fstat(client, &s1); entry(client); // Only close client if it is the same file so we don't // accidentally close a re-used file descriptor. // This check is required because the module companion // handler could've closed the file descriptor already. if (struct stat s2; fstat(client, &s2) == 0) { if (s1.st_dev == s2.st_dev && s1.st_ino == s2.st_ino) { close(client); } } }); } else { close(client); } } } // Entrypoint where we need to re-exec ourselves // This should only ever be called internally int zygisk_main(int argc, char *argv[]) { android_logging(); if (argc == 3 && argv[1] == "companion"sv) { zygiskd(parse_int(argv[2])); } return 0; }
2,938
C++
.cpp
88
24
83
0.517606
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
21
entry.cpp
topjohnwu_Magisk/native/src/core/zygisk/entry.cpp
#include <libgen.h> #include <dlfcn.h> #include <sys/prctl.h> #include <sys/mount.h> #include <android/log.h> #include <android/dlext.h> #include <base.hpp> #include <consts.hpp> #include "zygisk.hpp" #include "module.hpp" using namespace std; string native_bridge = "0"; static bool is_compatible_with(uint32_t) { zygisk_logging(); hook_entry(); ZLOGD("load success\n"); return false; } extern "C" [[maybe_unused]] NativeBridgeCallbacks NativeBridgeItf { .version = 2, .padding = {}, .isCompatibleWith = &is_compatible_with, }; // The following code runs in zygote/app process static inline bool should_load_modules(uint32_t flags) { return (flags & UNMOUNT_MASK) != UNMOUNT_MASK && (flags & PROCESS_IS_MAGISK_APP) != PROCESS_IS_MAGISK_APP; } int remote_get_info(int uid, const char *process, uint32_t *flags, vector<int> &fds) { if (int fd = zygisk_request(ZygiskRequest::GET_INFO); fd >= 0) { write_int(fd, uid); write_string(fd, process); xxread(fd, flags, sizeof(*flags)); if (should_load_modules(*flags)) { fds = recv_fds(fd); } return fd; } return -1; } // The following code runs in magiskd static vector<int> get_module_fds(bool is_64_bit) { vector<int> fds; // All fds passed to send_fds have to be valid file descriptors. // To workaround this issue, send over STDOUT_FILENO as an indicator of an // invalid fd as it will always be /dev/null in magiskd #if defined(__LP64__) if (is_64_bit) { std::transform(module_list->begin(), module_list->end(), std::back_inserter(fds), [](const module_info &info) { return info.z64 < 0 ? STDOUT_FILENO : info.z64; }); } else #endif { std::transform(module_list->begin(), module_list->end(), std::back_inserter(fds), [](const module_info &info) { return info.z32 < 0 ? STDOUT_FILENO : info.z32; }); } return fds; } static bool get_exe(int pid, char *buf, size_t sz) { char exe[128]; if (ssprintf(exe, sizeof(exe), "/proc/%d/exe", pid) < 0) return false; return xreadlink(exe, buf, sz) > 0; } static pthread_mutex_t zygiskd_lock = PTHREAD_MUTEX_INITIALIZER; static int zygiskd_sockets[] = { -1, -1 }; #define zygiskd_socket zygiskd_sockets[is_64_bit] static void connect_companion(int client, bool is_64_bit) { mutex_guard g(zygiskd_lock); if (zygiskd_socket >= 0) { // Make sure the socket is still valid pollfd pfd = { zygiskd_socket, 0, 0 }; poll(&pfd, 1, 0); if (pfd.revents) { // Any revent means error close(zygiskd_socket); zygiskd_socket = -1; } } if (zygiskd_socket < 0) { int fds[2]; socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, fds); zygiskd_socket = fds[0]; if (fork_dont_care() == 0) { char exe[64]; #if defined(__LP64__) ssprintf(exe, sizeof(exe), "%s/magisk%s", get_magisk_tmp(), (is_64_bit ? "" : "32")); #else ssprintf(exe, sizeof(exe), "%s/magisk", get_magisk_tmp()); #endif // This fd has to survive exec fcntl(fds[1], F_SETFD, 0); char buf[16]; ssprintf(buf, sizeof(buf), "%d", fds[1]); execl(exe, "", "zygisk", "companion", buf, (char *) nullptr); exit(-1); } close(fds[1]); vector<int> module_fds = get_module_fds(is_64_bit); send_fds(zygiskd_socket, module_fds.data(), module_fds.size()); // Wait for ack if (read_int(zygiskd_socket) != 0) { LOGE("zygiskd startup error\n"); return; } } send_fd(zygiskd_socket, client); } extern bool uid_granted_root(int uid); static void get_process_info(int client, const sock_cred *cred) { int uid = read_int(client); string process = read_string(client); uint32_t flags = 0; if (is_deny_target(uid, process)) { flags |= PROCESS_ON_DENYLIST; } if (get_manager(to_user_id(uid)) == uid) { flags |= PROCESS_IS_MAGISK_APP; } if (denylist_enforced) { flags |= DENYLIST_ENFORCING; } if (uid_granted_root(uid)) { flags |= PROCESS_GRANTED_ROOT; } xwrite(client, &flags, sizeof(flags)); if (should_load_modules(flags)) { char buf[256]; if (!get_exe(cred->pid, buf, sizeof(buf))) { LOGW("zygisk: remote process %d probably died, abort\n", cred->pid); send_fd(client, -1); return; } vector<int> fds = get_module_fds(str_ends(buf, "64")); send_fds(client, fds.data(), fds.size()); } if (uid != 1000 || process != "system_server") return; // Collect module status from system_server int slots = read_int(client); dynamic_bitset bits; for (int i = 0; i < slots; ++i) { dynamic_bitset::slot_type l = 0; xxread(client, &l, sizeof(l)); bits.emplace_back(l); } for (int id = 0; id < module_list->size(); ++id) { if (!as_const(bits)[id]) { // Either not a zygisk module, or incompatible char buf[4096]; ssprintf(buf, sizeof(buf), MODULEROOT "/%s/zygisk", module_list->operator[](id).name.data()); if (int dirfd = open(buf, O_RDONLY | O_CLOEXEC); dirfd >= 0) { close(xopenat(dirfd, "unloaded", O_CREAT | O_RDONLY, 0644)); close(dirfd); } } } } static void get_moddir(int client) { int id = read_int(client); char buf[4096]; ssprintf(buf, sizeof(buf), MODULEROOT "/%s", module_list->operator[](id).name.data()); int dfd = xopen(buf, O_RDONLY | O_CLOEXEC); send_fd(client, dfd); close(dfd); } void zygisk_handler(int client, const sock_cred *cred) { int code = read_int(client); char buf[256]; switch (code) { case ZygiskRequest::GET_INFO: get_process_info(client, cred); break; case ZygiskRequest::CONNECT_COMPANION: if (get_exe(cred->pid, buf, sizeof(buf))) { connect_companion(client, str_ends(buf, "64")); } else { LOGW("zygisk: remote process %d probably died, abort\n", cred->pid); } break; case ZygiskRequest::GET_MODDIR: get_moddir(client); break; default: // Unknown code break; } close(client); } void reset_zygisk(bool restore) { if (!zygisk_enabled) return; static atomic_uint zygote_start_count{1}; if (!restore) { close(zygiskd_sockets[0]); close(zygiskd_sockets[1]); zygiskd_sockets[0] = zygiskd_sockets[1] = -1; } if (restore) { zygote_start_count = 1; } else if (zygote_start_count.fetch_add(1) > 3) { LOGW("zygote crashes too many times, rolling-back\n"); restore = true; } if (restore) { string native_bridge_orig = "0"; if (native_bridge.length() > strlen(ZYGISKLDR)) { native_bridge_orig = native_bridge.substr(strlen(ZYGISKLDR)); } set_prop(NBPROP, native_bridge_orig.data()); } else { set_prop(NBPROP, native_bridge.data()); } }
7,255
C++
.cpp
214
27.238318
97
0.589795
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22
hook.cpp
topjohnwu_Magisk/native/src/core/zygisk/hook.cpp
#include <sys/mount.h> #include <dlfcn.h> #include <unwind.h> #include <span> #include <lsplt.hpp> #include <base.hpp> #include <consts.hpp> #include "zygisk.hpp" #include "module.hpp" using namespace std; // ********************* // Zygisk Bootstrapping // ********************* // // Zygisk's lifecycle is driven by several PLT function hooks in libandroid_runtime, libart, and // libnative_bridge. As Zygote is starting up, these carefully selected functions will call into // the respective lifecycle callbacks in Zygisk to drive the progress forward. // // The entire bootstrap process is shown in the graph below. // Arrows represent control flow, and the blocks are sorted chronologically from top to bottom. // // libnative_bridge libandroid_runtime zygisk libart // // ┌───────┐ // │ start │ // └───┬─┬─┘ // │ │ ┌────────────────┐ // │ └────────────────────────────────────────►│LoadNativeBridge│ // │ └───────┬────────┘ // ┌────────────────┐ │ │ // │LoadNativeBridge│◄────────────┼───────────────────────────────────────────────────┘ // └───────┬────┬───┘ │ // │ │ │ ┌───────────────┐ // │ └─────────────────┼────────────────────►│NativeBridgeItf│ // │ │ └──────┬────────┘ // │ │ │ // │ │ ▼ // │ │ ┌────────┐ // │ │ │hook_plt│ // ▼ │ └────────┘ // ┌───────┐ │ // │dlclose│ │ // └───┬───┘ │ // │ │ // │ │ ┌───────────────────────┐ // └──────────────────────┼────────────────►│post_native_bridge_load│ // │ └───────────────────────┘ // ▼ // ┌──────────────────────┐ // │ strdup("ZygoteInit") │ // └───────────┬────┬─────┘ // │ │ ┌───────────────┐ // │ └───────────────►│hook_zygote_jni│ // │ └───────────────┘ ┌─────────┐ // │ │ │ // └────────────────────────────────────────────►│ JVM │ // │ │ // └──┬─┬────┘ // ┌───────────────────┐ │ │ // │nativeXXXSpecialize│◄─────────────────────────────────────┘ │ // └─────────────┬─────┘ │ // │ ┌─────────────┐ │ // └────────────────►│ZygiskContext│ │ // └─────────────┘ ▼ // ┌────────────────────┐ // │pthread_attr_destroy│ // └─────────┬──────────┘ // ┌────────────────┐ │ // │restore_plt_hook│◄───────────┘ // └────────────────┘ // // Some notes regarding the important functions/symbols during bootstrap: // // * NativeBridgeItf: this symbol is the entry point for android::LoadNativeBridge // * HookContext::hook_plt(): hook functions like |dlclose| and |strdup| // * dlclose: the final step in android::LoadNativeBridge. In this function, we unwind the call // stack to load the real native bridge if necessary, and fetch NativeBridgeRuntimeCallbacks. // * strdup: called in AndroidRuntime::start before calling ZygoteInit#main(...) // * HookContext::hook_zygote_jni(): replace the process specialization functions registered // with register_jni_procs. This marks the final step of the code injection bootstrap process. // * pthread_attr_destroy: called whenever the JVM tries to setup threads for itself. We use // this method to cleanup and unload Zygisk from the process. constexpr const char *kZygoteInit = "com.android.internal.os.ZygoteInit"; constexpr const char *kZygote = "com/android/internal/os/Zygote"; // Global contexts: // // HookContext lives as long as Zygisk is loaded in memory. It tracks the process's function // hooking state and bootstraps code injection until we replace the process specialization methods. // // ZygiskContext lives during the process specialization process. It implements Zygisk // features, such as loading modules and customizing process fork/specialization. ZygiskContext *g_ctx; struct HookContext; static HookContext *g_hook; using JNIMethods = std::span<JNINativeMethod>; struct HookContext { #include "jni_hooks.hpp" // std::array<JNINativeMethod> zygote_methods vector<tuple<dev_t, ino_t, const char *, void **>> plt_backup; const NativeBridgeRuntimeCallbacks *runtime_callbacks = nullptr; void *self_handle = nullptr; bool should_unmap = false; void hook_plt(); void hook_unloader(); void restore_plt_hook(); void hook_zygote_jni(); void restore_zygote_hook(JNIEnv *env); void hook_jni_methods(JNIEnv *env, const char *clz, JNIMethods methods); void post_native_bridge_load(void *handle); private: void register_hook(dev_t dev, ino_t inode, const char *symbol, void *new_func, void **old_func); }; // ----------------------------------------------------------------- #define DCL_HOOK_FUNC(ret, func, ...) \ ret (*old_##func)(__VA_ARGS__); \ ret new_##func(__VA_ARGS__) DCL_HOOK_FUNC(static char *, strdup, const char * str) { if (strcmp(kZygoteInit, str) == 0) { g_hook->hook_zygote_jni(); } return old_strdup(str); } // Skip actual fork and return cached result if applicable DCL_HOOK_FUNC(int, fork) { return (g_ctx && g_ctx->pid >= 0) ? g_ctx->pid : old_fork(); } // Unmount stuffs in the process's private mount namespace DCL_HOOK_FUNC(static int, unshare, int flags) { int res = old_unshare(flags); if (g_ctx && (flags & CLONE_NEWNS) != 0 && res == 0) { if (g_ctx->flags & DO_REVERT_UNMOUNT) { revert_unmount(); } // Restore errno back to 0 errno = 0; } return res; } // This is the last moment before the secontext of the process changes DCL_HOOK_FUNC(static int, selinux_android_setcontext, uid_t uid, bool isSystemServer, const char *seinfo, const char *pkgname) { // Pre-fetch logd before secontext transition zygisk_get_logd(); return old_selinux_android_setcontext(uid, isSystemServer, seinfo, pkgname); } // Close file descriptors to prevent crashing DCL_HOOK_FUNC(static void, android_log_close) { if (g_ctx == nullptr || !(g_ctx->flags & SKIP_CLOSE_LOG_PIPE)) { // This happens during forks like nativeForkApp, nativeForkUsap, // nativeForkSystemServer, and nativeForkAndSpecialize. zygisk_close_logd(); } old_android_log_close(); } // It should be safe to assume all dlclose's in libnativebridge are for zygisk_loader DCL_HOOK_FUNC(static int, dlclose, void *handle) { if (!g_hook->self_handle) { ZLOGV("dlclose zygisk_loader\n"); g_hook->post_native_bridge_load(handle); } return 0; } // We cannot directly call `dlclose` to unload ourselves, otherwise when `dlclose` returns, // it will return to our code which has been unmapped, causing segmentation fault. // Instead, we hook `pthread_attr_destroy` which will be called when VM daemon threads start. DCL_HOOK_FUNC(static int, pthread_attr_destroy, void *target) { int res = old_pthread_attr_destroy((pthread_attr_t *)target); // Only perform unloading on the main thread if (gettid() != getpid()) return res; ZLOGV("pthread_attr_destroy\n"); if (g_hook->should_unmap) { g_hook->restore_plt_hook(); if (g_hook->should_unmap) { ZLOGV("dlclosing self\n"); void *self_handle = g_hook->self_handle; delete g_hook; // Because both `pthread_attr_destroy` and `dlclose` have the same function signature, // we can use `musttail` to let the compiler reuse our stack frame and thus // `dlclose` will directly return to the caller of `pthread_attr_destroy`. [[clang::musttail]] return dlclose(self_handle); } } delete g_hook; return res; } #undef DCL_HOOK_FUNC // ----------------------------------------------------------------- ZygiskContext::ZygiskContext(JNIEnv *env, void *args) : env(env), args{args}, process(nullptr), pid(-1), flags(0), info_flags(0), hook_info_lock(PTHREAD_MUTEX_INITIALIZER) { g_ctx = this; } ZygiskContext::~ZygiskContext() { // This global pointer points to a variable on the stack. // Set this to nullptr to prevent leaking local variable. // This also disables most plt hooked functions. g_ctx = nullptr; if (!is_child()) return; zygisk_close_logd(); android_logging(); // Strip out all API function pointers for (auto &m : modules) { m.clearApi(); } // Cleanup g_hook->should_unmap = true; g_hook->restore_zygote_hook(env); g_hook->hook_unloader(); } // ----------------------------------------------------------------- inline void *unwind_get_region_start(_Unwind_Context *ctx) { auto fp = _Unwind_GetRegionStart(ctx); #if defined(__arm__) // On arm32, we need to check if the pc is in thumb mode, // if so, we need to set the lowest bit of fp to 1 auto pc = _Unwind_GetGR(ctx, 15); // r15 is pc if (pc & 1) { // Thumb mode fp |= 1; } #endif return reinterpret_cast<void *>(fp); } // As we use NativeBridgeRuntimeCallbacks to reload native bridge and to hook jni functions, // we need to find it by the native bridge's unwind context. // For abis that use registers to pass arguments, i.e. arm32, arm64, x86_64, the registers are // caller-saved, and they are not preserved in the unwind context. However, they will be saved // into the callee-saved registers, so we will search the callee-saved registers for the second // argument, which is the pointer to NativeBridgeRuntimeCallbacks. // For x86, whose abi uses stack to pass arguments, we can directly get the pointer to // NativeBridgeRuntimeCallbacks from the stack. static const NativeBridgeRuntimeCallbacks* find_runtime_callbacks(struct _Unwind_Context *ctx) { // Find the writable memory region of libart.so, where the NativeBridgeRuntimeCallbacks is located. auto [start, end] = []()-> tuple<uintptr_t, uintptr_t> { for (const auto &map : lsplt::MapInfo::Scan()) { if (map.path.ends_with("/libart.so") && map.perms == (PROT_WRITE | PROT_READ)) { ZLOGV("libart.so: start=%p, end=%p\n", reinterpret_cast<void *>(map.start), reinterpret_cast<void *>(map.end)); return {map.start, map.end}; } } return {0, 0}; }(); #if defined(__aarch64__) // r19-r28 are callee-saved registers for (int i = 19; i <= 28; ++i) { auto val = static_cast<uintptr_t>(_Unwind_GetGR(ctx, i)); ZLOGV("r%d = %p\n", i, reinterpret_cast<void *>(val)); if (val >= start && val < end) return reinterpret_cast<const NativeBridgeRuntimeCallbacks*>(val); } #elif defined(__arm__) // r4-r10 are callee-saved registers for (int i = 4; i <= 10; ++i) { auto val = static_cast<uintptr_t>(_Unwind_GetGR(ctx, i)); ZLOGV("r%d = %p\n", i, reinterpret_cast<void *>(val)); if (val >= start && val < end) return reinterpret_cast<const NativeBridgeRuntimeCallbacks*>(val); } #elif defined(__i386__) // get ebp, which points to the bottom of the stack frame auto ebp = static_cast<uintptr_t>(_Unwind_GetGR(ctx, 5)); // 1 pointer size above ebp is the old ebp // 2 pointer sizes above ebp is the return address // 3 pointer sizes above ebp is the 2nd arg auto val = *reinterpret_cast<uintptr_t *>(ebp + 3 * sizeof(void *)); ZLOGV("ebp + 3 * ptr_size = %p\n", reinterpret_cast<void *>(val)); if (val >= start && val < end) return reinterpret_cast<const NativeBridgeRuntimeCallbacks*>(val); #elif defined(__x86_64__) // r12-r15 and rbx are callee-saved registers, but the compiler is likely to use them reversely for (int i : {3, 15, 14, 13, 12}) { auto val = static_cast<uintptr_t>(_Unwind_GetGR(ctx, i)); ZLOGV("r%d = %p\n", i, reinterpret_cast<void *>(val)); if (val >= start && val < end) return reinterpret_cast<const NativeBridgeRuntimeCallbacks*>(val); } #elif defined(__riscv) // x8-x9, x18-x27 callee-saved registers for (int i : {8, 9, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27}) { auto val = static_cast<uintptr_t>(_Unwind_GetGR(ctx, i)); ZLOGV("x%d = %p\n", i, reinterpret_cast<void *>(val)); if (val >= start && val < end) return reinterpret_cast<const NativeBridgeRuntimeCallbacks*>(val); } #else #error "Unsupported architecture" #endif return nullptr; } void HookContext::post_native_bridge_load(void *handle) { self_handle = handle; using method_sig = const bool (*)(const char *, const NativeBridgeRuntimeCallbacks *); struct trace_arg { method_sig load_native_bridge; const NativeBridgeRuntimeCallbacks *callbacks; }; trace_arg arg{}; // Unwind to find the address of android::LoadNativeBridge and NativeBridgeRuntimeCallbacks _Unwind_Backtrace(+[](_Unwind_Context *ctx, void *arg) -> _Unwind_Reason_Code { void *fp = unwind_get_region_start(ctx); Dl_info info{}; dladdr(fp, &info); ZLOGV("backtrace: %p %s\n", fp, info.dli_fname ?: "???"); if (info.dli_fname && std::string_view(info.dli_fname).ends_with("/libnativebridge.so")) { auto payload = reinterpret_cast<trace_arg *>(arg); payload->load_native_bridge = reinterpret_cast<method_sig>(fp); payload->callbacks = find_runtime_callbacks(ctx); ZLOGV("NativeBridgeRuntimeCallbacks: %p\n", payload->callbacks); return _URC_END_OF_STACK; } return _URC_NO_REASON; }, &arg); if (!arg.load_native_bridge || !arg.callbacks) return; // Reload the real native bridge if necessary auto nb = get_prop(NBPROP); auto len = sizeof(ZYGISKLDR) - 1; if (nb.size() > len) { arg.load_native_bridge(nb.data() + len, arg.callbacks); } runtime_callbacks = arg.callbacks; } // ----------------------------------------------------------------- void HookContext::register_hook( dev_t dev, ino_t inode, const char *symbol, void *new_func, void **old_func) { if (!lsplt::RegisterHook(dev, inode, symbol, new_func, old_func)) { ZLOGE("Failed to register plt_hook \"%s\"\n", symbol); return; } plt_backup.emplace_back(dev, inode, symbol, old_func); } #define PLT_HOOK_REGISTER_SYM(DEV, INODE, SYM, NAME) \ register_hook(DEV, INODE, SYM, \ reinterpret_cast<void *>(new_##NAME), reinterpret_cast<void **>(&old_##NAME)) #define PLT_HOOK_REGISTER(DEV, INODE, NAME) \ PLT_HOOK_REGISTER_SYM(DEV, INODE, #NAME, NAME) void HookContext::hook_plt() { ino_t android_runtime_inode = 0; dev_t android_runtime_dev = 0; ino_t native_bridge_inode = 0; dev_t native_bridge_dev = 0; for (auto &map : lsplt::MapInfo::Scan()) { if (map.path.ends_with("/libandroid_runtime.so")) { android_runtime_inode = map.inode; android_runtime_dev = map.dev; } else if (map.path.ends_with("/libnativebridge.so")) { native_bridge_inode = map.inode; native_bridge_dev = map.dev; } } PLT_HOOK_REGISTER(native_bridge_dev, native_bridge_inode, dlclose); PLT_HOOK_REGISTER(android_runtime_dev, android_runtime_inode, fork); PLT_HOOK_REGISTER(android_runtime_dev, android_runtime_inode, unshare); PLT_HOOK_REGISTER(android_runtime_dev, android_runtime_inode, selinux_android_setcontext); PLT_HOOK_REGISTER(android_runtime_dev, android_runtime_inode, strdup); PLT_HOOK_REGISTER_SYM(android_runtime_dev, android_runtime_inode, "__android_log_close", android_log_close); if (!lsplt::CommitHook()) ZLOGE("plt_hook failed\n"); // Remove unhooked methods plt_backup.erase( std::remove_if(plt_backup.begin(), plt_backup.end(), [](auto &t) { return *std::get<3>(t) == nullptr;}), plt_backup.end()); } void HookContext::hook_unloader() { ino_t art_inode = 0; dev_t art_dev = 0; for (auto &map : lsplt::MapInfo::Scan()) { if (map.path.ends_with("/libart.so")) { art_inode = map.inode; art_dev = map.dev; break; } } PLT_HOOK_REGISTER(art_dev, art_inode, pthread_attr_destroy); if (!lsplt::CommitHook()) ZLOGE("plt_hook failed\n"); } void HookContext::restore_plt_hook() { // Unhook plt_hook for (const auto &[dev, inode, sym, old_func] : plt_backup) { if (!lsplt::RegisterHook(dev, inode, sym, *old_func, nullptr)) { ZLOGE("Failed to register plt_hook [%s]\n", sym); should_unmap = false; } } if (!lsplt::CommitHook()) { ZLOGE("Failed to restore plt_hook\n"); should_unmap = false; } } // ----------------------------------------------------------------- void HookContext::hook_jni_methods(JNIEnv *env, const char *clz, JNIMethods methods) { jclass clazz; if (!runtime_callbacks || !env || !clz || !(clazz = env->FindClass(clz))) { for (auto &method : methods) { method.fnPtr = nullptr; } return; } // Backup existing methods auto total = runtime_callbacks->getNativeMethodCount(env, clazz); auto old_methods = std::make_unique_for_overwrite<JNINativeMethod[]>(total); runtime_callbacks->getNativeMethods(env, clazz, old_methods.get(), total); auto new_methods = std::make_unique_for_overwrite<JNINativeMethod[]>(total); // Replace the method for (auto &method : methods) { // It's useful to allow nullptr function pointer for restoring hook if (!method.fnPtr) continue; // It's normal that the method is not found if (env->RegisterNatives(clazz, &method, 1) == JNI_ERR || env->ExceptionCheck() == JNI_TRUE) { if (auto exception = env->ExceptionOccurred()) { env->DeleteLocalRef(exception); } env->ExceptionClear(); method.fnPtr = nullptr; continue; } // Find the old function pointer and return to caller runtime_callbacks->getNativeMethods(env, clazz, new_methods.get(), total); for (auto i = 0; i < total; ++i) { auto &new_method = new_methods[i]; if (new_method.fnPtr == method.fnPtr && strcmp(new_method.name, method.name) == 0) { auto &old_method = old_methods[i]; ZLOGD("replace %s#%s%s %p -> %p\n", clz, method.name, method.signature, old_method.fnPtr, method.fnPtr); method.fnPtr = old_method.fnPtr; break; } } old_methods.swap(new_methods); } } void HookContext::hook_zygote_jni() { using method_sig = jint(*)(JavaVM **, jsize, jsize *); auto get_created_vms = reinterpret_cast<method_sig>( dlsym(RTLD_DEFAULT, "JNI_GetCreatedJavaVMs")); if (!get_created_vms) { for (auto &map: lsplt::MapInfo::Scan()) { if (!map.path.ends_with("/libnativehelper.so")) continue; void *h = dlopen(map.path.data(), RTLD_LAZY); if (!h) { ZLOGW("Cannot dlopen libnativehelper.so: %s\n", dlerror()); break; } get_created_vms = reinterpret_cast<method_sig>(dlsym(h, "JNI_GetCreatedJavaVMs")); dlclose(h); break; } if (!get_created_vms) { ZLOGW("JNI_GetCreatedJavaVMs not found\n"); return; } } JavaVM *vm = nullptr; jsize num = 0; jint res = get_created_vms(&vm, 1, &num); if (res != JNI_OK || vm == nullptr) { ZLOGW("JavaVM not found\n"); return; } JNIEnv *env = nullptr; res = vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6); if (res != JNI_OK || env == nullptr) { ZLOGW("JNIEnv not found\n"); } hook_jni_methods(env, kZygote, zygote_methods); } void HookContext::restore_zygote_hook(JNIEnv *env) { hook_jni_methods(env, kZygote, zygote_methods); } // ----------------------------------------------------------------- void hook_entry() { default_new(g_hook); g_hook->hook_plt(); } void hookJniNativeMethods(JNIEnv *env, const char *clz, JNINativeMethod *methods, int numMethods) { g_hook->hook_jni_methods(env, clz, { methods, (size_t) numMethods }); }
23,899
C++
.cpp
481
40.590437
112
0.541732
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
23
module.cpp
topjohnwu_Magisk/native/src/core/zygisk/module.cpp
#include <android/dlext.h> #include <dlfcn.h> #include <lsplt.hpp> #include <base.hpp> #include "zygisk.hpp" #include "module.hpp" using namespace std; ZygiskModule::ZygiskModule(int id, void *handle, void *entry) : id(id), handle(handle), entry{entry}, api{}, mod{nullptr} { // Make sure all pointers are null memset(&api, 0, sizeof(api)); api.base.impl = this; api.base.registerModule = &ZygiskModule::RegisterModuleImpl; } bool ZygiskModule::RegisterModuleImpl(ApiTable *api, long *module) { if (api == nullptr || module == nullptr) return false; long api_version = *module; // Unsupported version if (api_version > ZYGISK_API_VERSION) return false; // Set the actual module_abi* api->base.impl->mod = { module }; // Fill in API accordingly with module API version if (api_version >= 1) { api->v1.hookJniNativeMethods = hookJniNativeMethods; api->v1.pltHookRegister = [](auto a, auto b, auto c, auto d) { if (g_ctx) g_ctx->plt_hook_register(a, b, c, d); }; api->v1.pltHookExclude = [](auto a, auto b) { if (g_ctx) g_ctx->plt_hook_exclude(a, b); }; api->v1.pltHookCommit = []() { return g_ctx && g_ctx->plt_hook_commit(); }; api->v1.connectCompanion = [](ZygiskModule *m) { return m->connectCompanion(); }; api->v1.setOption = [](ZygiskModule *m, auto opt) { m->setOption(opt); }; } if (api_version >= 2) { api->v2.getModuleDir = [](ZygiskModule *m) { return m->getModuleDir(); }; api->v2.getFlags = [](auto) { return ZygiskModule::getFlags(); }; } if (api_version >= 4) { api->v4.pltHookCommit = lsplt::CommitHook; api->v4.pltHookRegister = [](dev_t dev, ino_t inode, const char *symbol, void *fn, void **backup) { if (dev == 0 || inode == 0 || symbol == nullptr || fn == nullptr) return; lsplt::RegisterHook(dev, inode, symbol, fn, backup); }; api->v4.exemptFd = [](int fd) { return g_ctx && g_ctx->exempt_fd(fd); }; } return true; } bool ZygiskModule::valid() const { if (mod.api_version == nullptr) return false; switch (*mod.api_version) { case 5: case 4: case 3: case 2: case 1: return mod.v1->impl && mod.v1->preAppSpecialize && mod.v1->postAppSpecialize && mod.v1->preServerSpecialize && mod.v1->postServerSpecialize; default: return false; } } int ZygiskModule::connectCompanion() const { if (int fd = zygisk_request(ZygiskRequest::CONNECT_COMPANION); fd >= 0) { write_int(fd, id); return fd; } return -1; } int ZygiskModule::getModuleDir() const { if (int fd = zygisk_request(ZygiskRequest::GET_MODDIR); fd >= 0) { write_int(fd, id); int dfd = recv_fd(fd); close(fd); return dfd; } return -1; } void ZygiskModule::setOption(zygisk::Option opt) { if (g_ctx == nullptr) return; switch (opt) { case zygisk::FORCE_DENYLIST_UNMOUNT: g_ctx->flags |= DO_REVERT_UNMOUNT; break; case zygisk::DLCLOSE_MODULE_LIBRARY: unload = true; break; } } uint32_t ZygiskModule::getFlags() { return g_ctx ? (g_ctx->info_flags & ~PRIVATE_MASK) : 0; } void ZygiskModule::tryUnload() const { if (unload) dlclose(handle); } // ----------------------------------------------------------------- #define call_app(method) \ switch (*mod.api_version) { \ case 1: \ case 2: { \ AppSpecializeArgs_v1 a(args); \ mod.v1->method(mod.v1->impl, &a); \ break; \ } \ case 3: \ case 4: \ case 5: \ mod.v1->method(mod.v1->impl, args);\ break; \ } void ZygiskModule::preAppSpecialize(AppSpecializeArgs_v5 *args) const { call_app(preAppSpecialize) } void ZygiskModule::postAppSpecialize(const AppSpecializeArgs_v5 *args) const { call_app(postAppSpecialize) } void ZygiskModule::preServerSpecialize(ServerSpecializeArgs_v1 *args) const { mod.v1->preServerSpecialize(mod.v1->impl, args); } void ZygiskModule::postServerSpecialize(const ServerSpecializeArgs_v1 *args) const { mod.v1->postServerSpecialize(mod.v1->impl, args); } // ----------------------------------------------------------------- void ZygiskContext::plt_hook_register(const char *regex, const char *symbol, void *fn, void **backup) { if (regex == nullptr || symbol == nullptr || fn == nullptr) return; regex_t re; if (regcomp(&re, regex, REG_NOSUB) != 0) return; mutex_guard lock(hook_info_lock); register_info.emplace_back(RegisterInfo{re, symbol, fn, backup}); } void ZygiskContext::plt_hook_exclude(const char *regex, const char *symbol) { if (!regex) return; regex_t re; if (regcomp(&re, regex, REG_NOSUB) != 0) return; mutex_guard lock(hook_info_lock); ignore_info.emplace_back(IgnoreInfo{re, symbol ?: ""}); } void ZygiskContext::plt_hook_process_regex() { if (register_info.empty()) return; for (auto &map : lsplt::MapInfo::Scan()) { if (map.offset != 0 || !map.is_private || !(map.perms & PROT_READ)) continue; for (auto &reg: register_info) { if (regexec(&reg.regex, map.path.data(), 0, nullptr, 0) != 0) continue; bool ignored = false; for (auto &ign: ignore_info) { if (regexec(&ign.regex, map.path.data(), 0, nullptr, 0) != 0) continue; if (ign.symbol.empty() || ign.symbol == reg.symbol) { ignored = true; break; } } if (!ignored) { lsplt::RegisterHook(map.dev, map.inode, reg.symbol, reg.callback, reg.backup); } } } } bool ZygiskContext::plt_hook_commit() { { mutex_guard lock(hook_info_lock); plt_hook_process_regex(); register_info.clear(); ignore_info.clear(); } return lsplt::CommitHook(); } // ----------------------------------------------------------------- void ZygiskContext::sanitize_fds() { zygisk_close_logd(); if (!is_child()) { return; } if (can_exempt_fd() && !exempted_fds.empty()) { auto update_fd_array = [&](int old_len) -> jintArray { jintArray array = env->NewIntArray(static_cast<int>(old_len + exempted_fds.size())); if (array == nullptr) return nullptr; env->SetIntArrayRegion( array, old_len, static_cast<int>(exempted_fds.size()), exempted_fds.data()); for (int fd : exempted_fds) { if (fd >= 0 && fd < MAX_FD_SIZE) { allowed_fds[fd] = true; } } *args.app->fds_to_ignore = array; return array; }; if (jintArray fdsToIgnore = *args.app->fds_to_ignore) { int *arr = env->GetIntArrayElements(fdsToIgnore, nullptr); int len = env->GetArrayLength(fdsToIgnore); for (int i = 0; i < len; ++i) { int fd = arr[i]; if (fd >= 0 && fd < MAX_FD_SIZE) { allowed_fds[fd] = true; } } if (jintArray newFdList = update_fd_array(len)) { env->SetIntArrayRegion(newFdList, 0, len, arr); } env->ReleaseIntArrayElements(fdsToIgnore, arr, JNI_ABORT); } else { update_fd_array(0); } } // Close all forbidden fds to prevent crashing auto dir = xopen_dir("/proc/self/fd"); int dfd = dirfd(dir.get()); for (dirent *entry; (entry = xreaddir(dir.get()));) { int fd = parse_int(entry->d_name); if ((fd < 0 || fd >= MAX_FD_SIZE || !allowed_fds[fd]) && fd != dfd) { close(fd); } } } bool ZygiskContext::exempt_fd(int fd) { if ((flags & POST_SPECIALIZE) || (flags & SKIP_CLOSE_LOG_PIPE)) return true; if (!can_exempt_fd()) return false; exempted_fds.push_back(fd); return true; } bool ZygiskContext::can_exempt_fd() const { return (flags & APP_FORK_AND_SPECIALIZE) && args.app->fds_to_ignore; } static int sigmask(int how, int signum) { sigset_t set; sigemptyset(&set); sigaddset(&set, signum); return sigprocmask(how, &set, nullptr); } void ZygiskContext::fork_pre() { // Do our own fork before loading any 3rd party code // First block SIGCHLD, unblock after original fork is done sigmask(SIG_BLOCK, SIGCHLD); pid = old_fork(); if (!is_child()) return; // Record all open fds auto dir = xopen_dir("/proc/self/fd"); for (dirent *entry; (entry = xreaddir(dir.get()));) { int fd = parse_int(entry->d_name); if (fd < 0 || fd >= MAX_FD_SIZE) { close(fd); continue; } allowed_fds[fd] = true; } // The dirfd will be closed once out of scope allowed_fds[dirfd(dir.get())] = false; // logd_fd should be handled separately if (int fd = zygisk_get_logd(); fd >= 0) { allowed_fds[fd] = false; } } void ZygiskContext::fork_post() { // Unblock SIGCHLD in case the original method didn't sigmask(SIG_UNBLOCK, SIGCHLD); } void ZygiskContext::run_modules_pre(const vector<int> &fds) { for (int i = 0; i < fds.size(); ++i) { struct stat s{}; if (fstat(fds[i], &s) != 0 || !S_ISREG(s.st_mode)) { close(fds[i]); continue; } android_dlextinfo info { .flags = ANDROID_DLEXT_USE_LIBRARY_FD, .library_fd = fds[i], }; if (void *h = android_dlopen_ext("/jit-cache", RTLD_LAZY, &info)) { if (void *e = dlsym(h, "zygisk_module_entry")) { modules.emplace_back(i, h, e); } } else if (flags & SERVER_FORK_AND_SPECIALIZE) { ZLOGW("Failed to dlopen zygisk module: %s\n", dlerror()); } close(fds[i]); } for (auto it = modules.begin(); it != modules.end();) { it->onLoad(env); if (it->valid()) { ++it; } else { it = modules.erase(it); } } for (auto &m : modules) { if (flags & APP_SPECIALIZE) { m.preAppSpecialize(args.app); } else if (flags & SERVER_FORK_AND_SPECIALIZE) { m.preServerSpecialize(args.server); } } } void ZygiskContext::run_modules_post() { flags |= POST_SPECIALIZE; for (const auto &m : modules) { if (flags & APP_SPECIALIZE) { m.postAppSpecialize(args.app); } else if (flags & SERVER_FORK_AND_SPECIALIZE) { m.postServerSpecialize(args.server); } m.tryUnload(); } } void ZygiskContext::app_specialize_pre() { flags |= APP_SPECIALIZE; vector<int> module_fds; int fd = remote_get_info(args.app->uid, process, &info_flags, module_fds); if ((info_flags & UNMOUNT_MASK) == UNMOUNT_MASK) { ZLOGI("[%s] is on the denylist\n", process); flags |= DO_REVERT_UNMOUNT; } else if (fd >= 0) { run_modules_pre(module_fds); } close(fd); } void ZygiskContext::app_specialize_post() { run_modules_post(); if (info_flags & PROCESS_IS_MAGISK_APP) { setenv("ZYGISK_ENABLED", "1", 1); } // Cleanups env->ReleaseStringUTFChars(args.app->nice_name, process); } void ZygiskContext::server_specialize_pre() { vector<int> module_fds; int fd = remote_get_info(1000, "system_server", &info_flags, module_fds); if (fd >= 0) { if (module_fds.empty()) { write_int(fd, 0); } else { run_modules_pre(module_fds); // Send the bitset of module status back to magiskd from system_server dynamic_bitset bits; for (const auto &m : modules) bits[m.getId()] = true; write_int(fd, static_cast<int>(bits.slots())); for (int i = 0; i < bits.slots(); ++i) { auto l = bits.get_slot(i); xwrite(fd, &l, sizeof(l)); } } close(fd); } } void ZygiskContext::server_specialize_post() { run_modules_post(); } // ----------------------------------------------------------------- void ZygiskContext::nativeSpecializeAppProcess_pre() { process = env->GetStringUTFChars(args.app->nice_name, nullptr); ZLOGV("pre specialize [%s]\n", process); // App specialize does not check FD flags |= SKIP_CLOSE_LOG_PIPE; app_specialize_pre(); } void ZygiskContext::nativeSpecializeAppProcess_post() { ZLOGV("post specialize [%s]\n", process); app_specialize_post(); } void ZygiskContext::nativeForkSystemServer_pre() { ZLOGV("pre forkSystemServer\n"); flags |= SERVER_FORK_AND_SPECIALIZE; fork_pre(); if (is_child()) { server_specialize_pre(); } sanitize_fds(); } void ZygiskContext::nativeForkSystemServer_post() { if (is_child()) { ZLOGV("post forkSystemServer\n"); server_specialize_post(); } fork_post(); } void ZygiskContext::nativeForkAndSpecialize_pre() { process = env->GetStringUTFChars(args.app->nice_name, nullptr); ZLOGV("pre forkAndSpecialize [%s]\n", process); flags |= APP_FORK_AND_SPECIALIZE; fork_pre(); if (is_child()) { app_specialize_pre(); } sanitize_fds(); } void ZygiskContext::nativeForkAndSpecialize_post() { if (is_child()) { ZLOGV("post forkAndSpecialize [%s]\n", process); app_specialize_post(); } fork_post(); }
14,035
C++
.cpp
406
27.5
107
0.55653
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
24
bootimg.cpp
topjohnwu_Magisk/native/src/boot/bootimg.cpp
#include <bit> #include <functional> #include <memory> #include <span> #include <base.hpp> #include "boot-rs.hpp" #include "bootimg.hpp" #include "magiskboot.hpp" #include "compress.hpp" using namespace std; #define PADDING 15 #define SHA256_DIGEST_SIZE 32 #define SHA_DIGEST_SIZE 20 static void decompress(format_t type, int fd, const void *in, size_t size) { auto ptr = get_decoder(type, make_unique<fd_stream>(fd)); ptr->write(in, size); } static off_t compress(format_t type, int fd, const void *in, size_t size) { auto prev = lseek(fd, 0, SEEK_CUR); { auto strm = get_encoder(type, make_unique<fd_stream>(fd)); strm->write(in, size); } auto now = lseek(fd, 0, SEEK_CUR); return now - prev; } static void dump(const void *buf, size_t size, const char *filename) { if (size == 0) return; int fd = creat(filename, 0644); xwrite(fd, buf, size); close(fd); } static size_t restore(int fd, const char *filename) { int ifd = xopen(filename, O_RDONLY); size_t size = lseek(ifd, 0, SEEK_END); lseek(ifd, 0, SEEK_SET); xsendfile(fd, ifd, nullptr, size); close(ifd); return size; } void dyn_img_hdr::print() const { uint32_t ver = header_version(); fprintf(stderr, "%-*s [%u]\n", PADDING, "HEADER_VER", ver); if (!is_vendor()) fprintf(stderr, "%-*s [%u]\n", PADDING, "KERNEL_SZ", kernel_size()); fprintf(stderr, "%-*s [%u]\n", PADDING, "RAMDISK_SZ", ramdisk_size()); if (ver < 3) fprintf(stderr, "%-*s [%u]\n", PADDING, "SECOND_SZ", second_size()); if (ver == 0) fprintf(stderr, "%-*s [%u]\n", PADDING, "EXTRA_SZ", extra_size()); if (ver == 1 || ver == 2) fprintf(stderr, "%-*s [%u]\n", PADDING, "RECOV_DTBO_SZ", recovery_dtbo_size()); if (ver == 2 || is_vendor()) fprintf(stderr, "%-*s [%u]\n", PADDING, "DTB_SZ", dtb_size()); if (ver == 4 && is_vendor()) fprintf(stderr, "%-*s [%u]\n", PADDING, "BOOTCONFIG_SZ", bootconfig_size()); if (uint32_t os_ver = os_version()) { int a,b,c,y,m = 0; int version = os_ver >> 11; int patch_level = os_ver & 0x7ff; a = (version >> 14) & 0x7f; b = (version >> 7) & 0x7f; c = version & 0x7f; fprintf(stderr, "%-*s [%d.%d.%d]\n", PADDING, "OS_VERSION", a, b, c); y = (patch_level >> 4) + 2000; m = patch_level & 0xf; fprintf(stderr, "%-*s [%d-%02d]\n", PADDING, "OS_PATCH_LEVEL", y, m); } fprintf(stderr, "%-*s [%u]\n", PADDING, "PAGESIZE", page_size()); if (const char *n = name()) { fprintf(stderr, "%-*s [%s]\n", PADDING, "NAME", n); } fprintf(stderr, "%-*s [%.*s%.*s]\n", PADDING, "CMDLINE", BOOT_ARGS_SIZE, cmdline(), BOOT_EXTRA_ARGS_SIZE, extra_cmdline()); if (const char *checksum = id()) { fprintf(stderr, "%-*s [", PADDING, "CHECKSUM"); for (int i = 0; i < SHA256_DIGEST_SIZE; ++i) fprintf(stderr, "%02hhx", checksum[i]); fprintf(stderr, "]\n"); } } void dyn_img_hdr::dump_hdr_file() const { FILE *fp = xfopen(HEADER_FILE, "w"); if (name()) fprintf(fp, "name=%s\n", name()); fprintf(fp, "cmdline=%.*s%.*s\n", BOOT_ARGS_SIZE, cmdline(), BOOT_EXTRA_ARGS_SIZE, extra_cmdline()); uint32_t ver = os_version(); if (ver) { int a, b, c, y, m; int version, patch_level; version = ver >> 11; patch_level = ver & 0x7ff; a = (version >> 14) & 0x7f; b = (version >> 7) & 0x7f; c = version & 0x7f; fprintf(fp, "os_version=%d.%d.%d\n", a, b, c); y = (patch_level >> 4) + 2000; m = patch_level & 0xf; fprintf(fp, "os_patch_level=%d-%02d\n", y, m); } fclose(fp); } void dyn_img_hdr::load_hdr_file() { parse_prop_file(HEADER_FILE, [=, this](string_view key, string_view value) -> bool { if (key == "name" && name()) { memset(name(), 0, 16); memcpy(name(), value.data(), value.length() > 15 ? 15 : value.length()); } else if (key == "cmdline") { memset(cmdline(), 0, BOOT_ARGS_SIZE); memset(extra_cmdline(), 0, BOOT_EXTRA_ARGS_SIZE); if (value.length() > BOOT_ARGS_SIZE) { memcpy(cmdline(), value.data(), BOOT_ARGS_SIZE); auto len = std::min(value.length() - BOOT_ARGS_SIZE, (size_t) BOOT_EXTRA_ARGS_SIZE); memcpy(extra_cmdline(), &value[BOOT_ARGS_SIZE], len); } else { memcpy(cmdline(), value.data(), value.length()); } } else if (key == "os_version") { int patch_level = os_version() & 0x7ff; int a, b, c; sscanf(value.data(), "%d.%d.%d", &a, &b, &c); os_version() = (((a << 14) | (b << 7) | c) << 11) | patch_level; } else if (key == "os_patch_level") { int os_ver = os_version() >> 11; int y, m; sscanf(value.data(), "%d-%d", &y, &m); y -= 2000; os_version() = (os_ver << 11) | (y << 4) | m; } return true; }); } boot_img::boot_img(const char *image) : map(image) { fprintf(stderr, "Parsing boot image: [%s]\n", image); for (const uint8_t *addr = map.buf(); addr < map.buf() + map.sz(); ++addr) { format_t fmt = check_fmt(addr, map.sz()); switch (fmt) { case CHROMEOS: // chromeos require external signing flags[CHROMEOS_FLAG] = true; addr += 65535; break; case DHTB: flags[DHTB_FLAG] = true; flags[SEANDROID_FLAG] = true; fprintf(stderr, "DHTB_HDR\n"); addr += sizeof(dhtb_hdr) - 1; break; case BLOB: flags[BLOB_FLAG] = true; fprintf(stderr, "TEGRA_BLOB\n"); addr += sizeof(blob_hdr) - 1; break; case AOSP: case AOSP_VENDOR: if (parse_image(addr, fmt)) return; // fallthrough default: break; } } exit(1); } boot_img::~boot_img() { delete hdr; } struct [[gnu::packed]] fdt_header { struct fdt32_t { uint32_t byte0: 8; uint32_t byte1: 8; uint32_t byte2: 8; uint32_t byte3: 8; constexpr operator uint32_t() const { return bit_cast<uint32_t>(fdt32_t { .byte0 = byte3, .byte1 = byte2, .byte2 = byte1, .byte3 = byte0 }); } }; struct node_header { fdt32_t tag; char name[0]; }; fdt32_t magic; /* magic word FDT_MAGIC */ fdt32_t totalsize; /* total size of DT block */ fdt32_t off_dt_struct; /* offset to structure */ fdt32_t off_dt_strings; /* offset to strings */ fdt32_t off_mem_rsvmap; /* offset to memory reserve map */ fdt32_t version; /* format version */ fdt32_t last_comp_version; /* last compatible version */ /* version 2 fields below */ fdt32_t boot_cpuid_phys; /* Which physical CPU id we're booting on */ /* version 3 fields below */ fdt32_t size_dt_strings; /* size of the strings block */ /* version 17 fields below */ fdt32_t size_dt_struct; /* size of the structure block */ }; static int find_dtb_offset(const uint8_t *buf, unsigned sz) { const uint8_t * const end = buf + sz; for (auto curr = buf; curr < end; curr += sizeof(fdt_header)) { curr = static_cast<uint8_t*>(memmem(curr, end - curr, DTB_MAGIC, sizeof(fdt_header::fdt32_t))); if (curr == nullptr) return -1; auto fdt_hdr = reinterpret_cast<const fdt_header *>(curr); // Check that fdt_header.totalsize does not overflow kernel image size uint32_t totalsize = fdt_hdr->totalsize; if (totalsize > end - curr) continue; // Check that fdt_header.off_dt_struct does not overflow kernel image size uint32_t off_dt_struct = fdt_hdr->off_dt_struct; if (off_dt_struct > end - curr) continue; // Check that fdt_node_header.tag of first node is FDT_BEGIN_NODE auto fdt_node_hdr = reinterpret_cast<const fdt_header::node_header *>(curr + off_dt_struct); if (fdt_node_hdr->tag != 0x1u) continue; return curr - buf; } return -1; } static format_t check_fmt_lg(const uint8_t *buf, unsigned sz) { format_t fmt = check_fmt(buf, sz); if (fmt == LZ4_LEGACY) { // We need to check if it is LZ4_LG uint32_t off = 4; uint32_t block_sz; while (off + sizeof(block_sz) <= sz) { memcpy(&block_sz, buf + off, sizeof(block_sz)); off += sizeof(block_sz); if (off + block_sz > sz) return LZ4_LG; off += block_sz; } } return fmt; } #define CMD_MATCH(s) BUFFER_MATCH(h->cmdline, s) pair<const uint8_t *, dyn_img_hdr *> boot_img::create_hdr(const uint8_t *addr, format_t type) { if (type == AOSP_VENDOR) { fprintf(stderr, "VENDOR_BOOT_HDR\n"); auto h = reinterpret_cast<const boot_img_hdr_vnd_v3*>(addr); switch (h->header_version) { case 4: return make_pair(addr, new dyn_img_vnd_v4(addr)); default: return make_pair(addr, new dyn_img_vnd_v3(addr)); } } auto h = reinterpret_cast<const boot_img_hdr_v0*>(addr); if (h->page_size >= 0x02000000) { fprintf(stderr, "PXA_BOOT_HDR\n"); return make_pair(addr, new dyn_img_pxa(addr)); } auto make_hdr = [](const uint8_t *ptr) -> dyn_img_hdr * { auto h = reinterpret_cast<const boot_img_hdr_v0*>(ptr); if (memcmp(h->magic, BOOT_MAGIC, BOOT_MAGIC_SIZE) != 0) return nullptr; switch (h->header_version) { case 1: return new dyn_img_v1(ptr); case 2: return new dyn_img_v2(ptr); case 3: return new dyn_img_v3(ptr); case 4: return new dyn_img_v4(ptr); default: return new dyn_img_v0(ptr); } }; // For NOOKHD and ACCLAIM, the entire boot image is shifted by a fixed offset. // For AMONET, only the header is internally shifted by a fixed offset. if (BUFFER_CONTAIN(addr, AMONET_MICROLOADER_SZ, AMONET_MICROLOADER_MAGIC) && BUFFER_MATCH(addr + AMONET_MICROLOADER_SZ, BOOT_MAGIC)) { flags[AMONET_FLAG] = true; fprintf(stderr, "AMONET_MICROLOADER\n"); // The real header is shifted, copy to temporary buffer h = reinterpret_cast<const boot_img_hdr_v0*>(addr + AMONET_MICROLOADER_SZ); if (memcmp(h->magic, BOOT_MAGIC, BOOT_MAGIC_SIZE) != 0) return make_pair(addr, nullptr); auto real_hdr_sz = h->page_size - AMONET_MICROLOADER_SZ; heap_data copy(h->page_size); memcpy(copy.buf(), h, real_hdr_sz); return make_pair(addr, make_hdr(copy.buf())); } if (CMD_MATCH(NOOKHD_RL_MAGIC) || CMD_MATCH(NOOKHD_GL_MAGIC) || CMD_MATCH(NOOKHD_GR_MAGIC) || CMD_MATCH(NOOKHD_EB_MAGIC) || CMD_MATCH(NOOKHD_ER_MAGIC)) { flags[NOOKHD_FLAG] = true; fprintf(stderr, "NOOKHD_LOADER\n"); addr += NOOKHD_PRE_HEADER_SZ; } else if (BUFFER_MATCH(h->name, ACCLAIM_MAGIC)) { flags[ACCLAIM_FLAG] = true; fprintf(stderr, "ACCLAIM_LOADER\n"); addr += ACCLAIM_PRE_HEADER_SZ; } return make_pair(addr, make_hdr(addr)); } static const char *vendor_ramdisk_type(int type) { switch (type) { case VENDOR_RAMDISK_TYPE_PLATFORM: return "platform"; case VENDOR_RAMDISK_TYPE_RECOVERY: return "recovery"; case VENDOR_RAMDISK_TYPE_DLKM: return "dlkm"; case VENDOR_RAMDISK_TYPE_NONE: default: return "none"; } } #define assert_off() \ if ((base_addr + off) > (map.buf() + map_end)) { \ fprintf(stderr, "Corrupted boot image!\n"); \ return false; \ } #define get_block(name) \ name = base_addr + off; \ off += hdr->name##_size(); \ off = align_to(off, hdr->page_size()); \ assert_off(); bool boot_img::parse_image(const uint8_t *p, format_t type) { auto [base_addr, hdr] = create_hdr(p, type); if (hdr == nullptr) { fprintf(stderr, "Invalid boot image header!\n"); return false; } if (const char *id = hdr->id()) { for (int i = SHA_DIGEST_SIZE + 4; i < SHA256_DIGEST_SIZE; ++i) { if (id[i]) { flags[SHA256_FLAG] = true; break; } } } hdr->print(); size_t map_end = align_to(map.sz(), getpagesize()); size_t off = hdr->hdr_space(); get_block(kernel); get_block(ramdisk); get_block(second); get_block(extra); get_block(recovery_dtbo); get_block(dtb); get_block(signature); get_block(vendor_ramdisk_table); get_block(bootconfig); payload = byte_view(base_addr, off); auto tail_addr = base_addr + off; tail = byte_view(tail_addr, map.buf() + map_end - tail_addr); if (auto size = hdr->kernel_size()) { if (int dtb_off = find_dtb_offset(kernel, size); dtb_off > 0) { kernel_dtb = byte_view(kernel + dtb_off, size - dtb_off); hdr->kernel_size() = dtb_off; fprintf(stderr, "%-*s [%zu]\n", PADDING, "KERNEL_DTB_SZ", kernel_dtb.sz()); } k_fmt = check_fmt_lg(kernel, hdr->kernel_size()); if (k_fmt == MTK) { fprintf(stderr, "MTK_KERNEL_HDR\n"); flags[MTK_KERNEL] = true; k_hdr = reinterpret_cast<const mtk_hdr *>(kernel); fprintf(stderr, "%-*s [%u]\n", PADDING, "SIZE", k_hdr->size); fprintf(stderr, "%-*s [%s]\n", PADDING, "NAME", k_hdr->name); kernel += sizeof(mtk_hdr); hdr->kernel_size() -= sizeof(mtk_hdr); k_fmt = check_fmt_lg(kernel, hdr->kernel_size()); } if (k_fmt == ZIMAGE) { z_hdr = reinterpret_cast<const zimage_hdr *>(kernel); if (const void *gzip = memmem(kernel, hdr->kernel_size(), GZIP1_MAGIC "\x08\x00", 4)) { fprintf(stderr, "ZIMAGE_KERNEL\n"); z_info.hdr_sz = (const uint8_t *) gzip - kernel; // Find end of piggy uint32_t zImage_size = z_hdr->end - z_hdr->start; uint32_t piggy_end = zImage_size; uint32_t offsets[16]; memcpy(offsets, kernel + zImage_size - sizeof(offsets), sizeof(offsets)); for (int i = 15; i >= 0; --i) { if (offsets[i] > (zImage_size - 0xFF) && offsets[i] < zImage_size) { piggy_end = offsets[i]; break; } } if (piggy_end == zImage_size) { fprintf(stderr, "! Could not find end of zImage piggy, keeping raw kernel\n"); } else { flags[ZIMAGE_KERNEL] = true; z_info.tail = byte_view(kernel + piggy_end, hdr->kernel_size() - piggy_end); kernel += z_info.hdr_sz; hdr->kernel_size() = piggy_end - z_info.hdr_sz; k_fmt = check_fmt_lg(kernel, hdr->kernel_size()); } } else { fprintf(stderr, "! Could not find zImage gzip piggy, keeping raw kernel\n"); } } fprintf(stderr, "%-*s [%s]\n", PADDING, "KERNEL_FMT", fmt2name[k_fmt]); } if (auto size = hdr->ramdisk_size()) { if (hdr->vendor_ramdisk_table_size()) { // v4 vendor boot contains multiple ramdisks using table_entry = const vendor_ramdisk_table_entry_v4; if (hdr->vendor_ramdisk_table_entry_size() != sizeof(table_entry)) { fprintf(stderr, "! Invalid vendor image: vendor_ramdisk_table_entry_size != %zu\n", sizeof(table_entry)); exit(1); } span<table_entry> table( reinterpret_cast<table_entry *>(vendor_ramdisk_table), hdr->vendor_ramdisk_table_entry_num()); for (auto &it : table) { format_t fmt = check_fmt_lg(ramdisk + it.ramdisk_offset, it.ramdisk_size); fprintf(stderr, "%-*s name=[%s] type=[%s] size=[%u] fmt=[%s]\n", PADDING, "VND_RAMDISK", it.ramdisk_name, vendor_ramdisk_type(it.ramdisk_type), it.ramdisk_size, fmt2name[fmt]); } } else { r_fmt = check_fmt_lg(ramdisk, size); if (r_fmt == MTK) { fprintf(stderr, "MTK_RAMDISK_HDR\n"); flags[MTK_RAMDISK] = true; r_hdr = reinterpret_cast<const mtk_hdr *>(ramdisk); fprintf(stderr, "%-*s [%u]\n", PADDING, "SIZE", r_hdr->size); fprintf(stderr, "%-*s [%s]\n", PADDING, "NAME", r_hdr->name); ramdisk += sizeof(mtk_hdr); hdr->ramdisk_size() -= sizeof(mtk_hdr); r_fmt = check_fmt_lg(ramdisk, hdr->ramdisk_size()); } fprintf(stderr, "%-*s [%s]\n", PADDING, "RAMDISK_FMT", fmt2name[r_fmt]); } } if (auto size = hdr->extra_size()) { e_fmt = check_fmt_lg(extra, size); fprintf(stderr, "%-*s [%s]\n", PADDING, "EXTRA_FMT", fmt2name[e_fmt]); } if (tail.sz()) { // Check special flags if (tail.sz() >= 16 && BUFFER_MATCH(tail.buf(), SEANDROID_MAGIC)) { fprintf(stderr, "SAMSUNG_SEANDROID\n"); flags[SEANDROID_FLAG] = true; } else if (tail.sz() >= 16 && BUFFER_MATCH(tail.buf(), LG_BUMP_MAGIC)) { fprintf(stderr, "LG_BUMP_IMAGE\n"); flags[LG_BUMP_FLAG] = true; } // Check if the image is signed if (verify()) { fprintf(stderr, "AVB1_SIGNED\n"); flags[AVB1_SIGNED_FLAG] = true; } // Find AVB footer const void *footer = tail.buf() + tail.sz() - sizeof(AvbFooter); if (BUFFER_MATCH(footer, AVB_FOOTER_MAGIC)) { avb_footer = reinterpret_cast<const AvbFooter*>(footer); // Double check if meta header exists const void *meta = base_addr + __builtin_bswap64(avb_footer->vbmeta_offset); if (BUFFER_MATCH(meta, AVB_MAGIC)) { fprintf(stderr, "VBMETA\n"); flags[AVB_FLAG] = true; vbmeta = reinterpret_cast<const AvbVBMetaImageHeader*>(meta); } } } this->hdr = hdr; return true; } bool boot_img::verify(const char *cert) const { return rust::verify_boot_image(*this, cert); } int split_image_dtb(const char *filename, bool skip_decomp) { mmap_data img(filename); if (int off = find_dtb_offset(img.buf(), img.sz()); off > 0) { format_t fmt = check_fmt_lg(img.buf(), img.sz()); if (!skip_decomp && COMPRESSED(fmt)) { int fd = creat(KERNEL_FILE, 0644); decompress(fmt, fd, img.buf(), off); close(fd); } else { dump(img.buf(), off, KERNEL_FILE); } dump(img.buf() + off, img.sz() - off, KER_DTB_FILE); return 0; } else { fprintf(stderr, "Cannot find DTB in %s\n", filename); return 1; } } int unpack(const char *image, bool skip_decomp, bool hdr) { const boot_img boot(image); if (hdr) boot.hdr->dump_hdr_file(); // Dump kernel if (!skip_decomp && COMPRESSED(boot.k_fmt)) { if (boot.hdr->kernel_size() != 0) { int fd = creat(KERNEL_FILE, 0644); decompress(boot.k_fmt, fd, boot.kernel, boot.hdr->kernel_size()); close(fd); } } else { dump(boot.kernel, boot.hdr->kernel_size(), KERNEL_FILE); } // Dump kernel_dtb dump(boot.kernel_dtb.buf(), boot.kernel_dtb.sz(), KER_DTB_FILE); // Dump ramdisk if (boot.hdr->vendor_ramdisk_table_size()) { using table_entry = const vendor_ramdisk_table_entry_v4; span<table_entry> table( reinterpret_cast<table_entry *>(boot.vendor_ramdisk_table), boot.hdr->vendor_ramdisk_table_entry_num()); xmkdir(VND_RAMDISK_DIR, 0755); owned_fd dirfd = xopen(VND_RAMDISK_DIR, O_RDONLY | O_CLOEXEC); for (auto &it : table) { char file_name[40]; if (it.ramdisk_name[0] == '\0') { strscpy(file_name, RAMDISK_FILE, sizeof(file_name)); } else { ssprintf(file_name, sizeof(file_name), "%s.cpio", it.ramdisk_name); } owned_fd fd = xopenat(dirfd, file_name, O_CREAT | O_TRUNC | O_WRONLY | O_CLOEXEC, 0644); format_t fmt = check_fmt_lg(boot.ramdisk + it.ramdisk_offset, it.ramdisk_size); if (!skip_decomp && COMPRESSED(fmt)) { decompress(fmt, fd, boot.ramdisk + it.ramdisk_offset, it.ramdisk_size); } else { xwrite(fd, boot.ramdisk + it.ramdisk_offset, it.ramdisk_size); } } } else if (!skip_decomp && COMPRESSED(boot.r_fmt)) { if (boot.hdr->ramdisk_size() != 0) { int fd = creat(RAMDISK_FILE, 0644); decompress(boot.r_fmt, fd, boot.ramdisk, boot.hdr->ramdisk_size()); close(fd); } } else { dump(boot.ramdisk, boot.hdr->ramdisk_size(), RAMDISK_FILE); } // Dump second dump(boot.second, boot.hdr->second_size(), SECOND_FILE); // Dump extra if (!skip_decomp && COMPRESSED(boot.e_fmt)) { if (boot.hdr->extra_size() != 0) { int fd = creat(EXTRA_FILE, 0644); decompress(boot.e_fmt, fd, boot.extra, boot.hdr->extra_size()); close(fd); } } else { dump(boot.extra, boot.hdr->extra_size(), EXTRA_FILE); } // Dump recovery_dtbo dump(boot.recovery_dtbo, boot.hdr->recovery_dtbo_size(), RECV_DTBO_FILE); // Dump dtb dump(boot.dtb, boot.hdr->dtb_size(), DTB_FILE); // Dump bootconfig dump(boot.bootconfig, boot.hdr->bootconfig_size(), BOOTCONFIG_FILE); return boot.flags[CHROMEOS_FLAG] ? 2 : 0; } #define file_align_with(page_size) \ write_zero(fd, align_padding(lseek(fd, 0, SEEK_CUR) - off.header, page_size)) #define file_align() file_align_with(boot.hdr->page_size()) void repack(const char *src_img, const char *out_img, bool skip_comp) { const boot_img boot(src_img); fprintf(stderr, "Repack to boot image: [%s]\n", out_img); struct { uint32_t header; uint32_t kernel; uint32_t ramdisk; uint32_t second; uint32_t extra; uint32_t dtb; uint32_t total; uint32_t vbmeta; } off{}; // Create a new boot header and reset sizes auto hdr = boot.hdr->clone(); hdr->kernel_size() = 0; hdr->ramdisk_size() = 0; hdr->second_size() = 0; hdr->dtb_size() = 0; hdr->bootconfig_size() = 0; if (access(HEADER_FILE, R_OK) == 0) hdr->load_hdr_file(); /*************** * Write blocks ***************/ // Create new image int fd = creat(out_img, 0644); if (boot.flags[DHTB_FLAG]) { // Skip DHTB header write_zero(fd, sizeof(dhtb_hdr)); } else if (boot.flags[BLOB_FLAG]) { xwrite(fd, boot.map.buf(), sizeof(blob_hdr)); } else if (boot.flags[NOOKHD_FLAG]) { xwrite(fd, boot.map.buf(), NOOKHD_PRE_HEADER_SZ); } else if (boot.flags[ACCLAIM_FLAG]) { xwrite(fd, boot.map.buf(), ACCLAIM_PRE_HEADER_SZ); } // Copy raw header off.header = lseek(fd, 0, SEEK_CUR); xwrite(fd, boot.payload.buf(), hdr->hdr_space()); // kernel off.kernel = lseek(fd, 0, SEEK_CUR); if (boot.flags[MTK_KERNEL]) { // Copy MTK headers xwrite(fd, boot.k_hdr, sizeof(mtk_hdr)); } if (boot.flags[ZIMAGE_KERNEL]) { // Copy zImage headers xwrite(fd, boot.z_hdr, boot.z_info.hdr_sz); } if (access(KERNEL_FILE, R_OK) == 0) { mmap_data m(KERNEL_FILE); if (!skip_comp && !COMPRESSED_ANY(check_fmt(m.buf(), m.sz())) && COMPRESSED(boot.k_fmt)) { // Always use zopfli for zImage compression auto fmt = (boot.flags[ZIMAGE_KERNEL] && boot.k_fmt == GZIP) ? ZOPFLI : boot.k_fmt; hdr->kernel_size() = compress(fmt, fd, m.buf(), m.sz()); } else { hdr->kernel_size() = xwrite(fd, m.buf(), m.sz()); } if (boot.flags[ZIMAGE_KERNEL]) { if (hdr->kernel_size() > boot.hdr->kernel_size()) { fprintf(stderr, "! Recompressed kernel is too large, using original kernel\n"); ftruncate64(fd, lseek64(fd, - (off64_t) hdr->kernel_size(), SEEK_CUR)); xwrite(fd, boot.kernel, boot.hdr->kernel_size()); } else if (!skip_comp) { // Pad zeros to make sure the zImage file size does not change // Also ensure the last 4 bytes are the uncompressed vmlinux size uint32_t sz = m.sz(); write_zero(fd, boot.hdr->kernel_size() - hdr->kernel_size() - sizeof(sz)); xwrite(fd, &sz, sizeof(sz)); } // zImage size shall remain the same hdr->kernel_size() = boot.hdr->kernel_size(); } } else if (boot.hdr->kernel_size() != 0) { xwrite(fd, boot.kernel, boot.hdr->kernel_size()); hdr->kernel_size() = boot.hdr->kernel_size(); } if (boot.flags[ZIMAGE_KERNEL]) { // Copy zImage tail and adjust size accordingly hdr->kernel_size() += boot.z_info.hdr_sz; hdr->kernel_size() += xwrite(fd, boot.z_info.tail.buf(), boot.z_info.tail.sz()); } // kernel dtb if (access(KER_DTB_FILE, R_OK) == 0) hdr->kernel_size() += restore(fd, KER_DTB_FILE); file_align(); // ramdisk off.ramdisk = lseek(fd, 0, SEEK_CUR); if (boot.flags[MTK_RAMDISK]) { // Copy MTK headers xwrite(fd, boot.r_hdr, sizeof(mtk_hdr)); } using table_entry = vendor_ramdisk_table_entry_v4; vector<table_entry> ramdisk_table; if (boot.hdr->vendor_ramdisk_table_size()) { // Create a copy so we can modify it auto entry_start = reinterpret_cast<const table_entry *>(boot.vendor_ramdisk_table); ramdisk_table.insert( ramdisk_table.begin(), entry_start, entry_start + boot.hdr->vendor_ramdisk_table_entry_num()); owned_fd dirfd = xopen(VND_RAMDISK_DIR, O_RDONLY | O_CLOEXEC); uint32_t ramdisk_offset = 0; for (auto &it : ramdisk_table) { char file_name[64]; if (it.ramdisk_name[0] == '\0') { strscpy(file_name, RAMDISK_FILE, sizeof(file_name)); } else { ssprintf(file_name, sizeof(file_name), "%s.cpio", it.ramdisk_name); } mmap_data m(dirfd, file_name); format_t fmt = check_fmt_lg(boot.ramdisk + it.ramdisk_offset, it.ramdisk_size); it.ramdisk_offset = ramdisk_offset; if (!skip_comp && !COMPRESSED_ANY(check_fmt(m.buf(), m.sz())) && COMPRESSED(fmt)) { it.ramdisk_size = compress(fmt, fd, m.buf(), m.sz()); } else { it.ramdisk_size = xwrite(fd, m.buf(), m.sz()); } ramdisk_offset += it.ramdisk_size; } hdr->ramdisk_size() = ramdisk_offset; file_align(); } else if (access(RAMDISK_FILE, R_OK) == 0) { mmap_data m(RAMDISK_FILE); auto r_fmt = boot.r_fmt; if (!skip_comp && !hdr->is_vendor() && hdr->header_version() == 4 && r_fmt != LZ4_LEGACY) { // A v4 boot image ramdisk will have to be merged with other vendor ramdisks, // and they have to use the exact same compression method. v4 GKIs are required to // use lz4 (legacy), so hardcode the format here. fprintf(stderr, "RAMDISK_FMT: [%s] -> [%s]\n", fmt2name[r_fmt], fmt2name[LZ4_LEGACY]); r_fmt = LZ4_LEGACY; } if (!skip_comp && !COMPRESSED_ANY(check_fmt(m.buf(), m.sz())) && COMPRESSED(r_fmt)) { hdr->ramdisk_size() = compress(r_fmt, fd, m.buf(), m.sz()); } else { hdr->ramdisk_size() = xwrite(fd, m.buf(), m.sz()); } file_align(); } // second off.second = lseek(fd, 0, SEEK_CUR); if (access(SECOND_FILE, R_OK) == 0) { hdr->second_size() = restore(fd, SECOND_FILE); file_align(); } // extra off.extra = lseek(fd, 0, SEEK_CUR); if (access(EXTRA_FILE, R_OK) == 0) { mmap_data m(EXTRA_FILE); if (!skip_comp && !COMPRESSED_ANY(check_fmt(m.buf(), m.sz())) && COMPRESSED(boot.e_fmt)) { hdr->extra_size() = compress(boot.e_fmt, fd, m.buf(), m.sz()); } else { hdr->extra_size() = xwrite(fd, m.buf(), m.sz()); } file_align(); } // recovery_dtbo if (access(RECV_DTBO_FILE, R_OK) == 0) { hdr->recovery_dtbo_offset() = lseek(fd, 0, SEEK_CUR); hdr->recovery_dtbo_size() = restore(fd, RECV_DTBO_FILE); file_align(); } // dtb off.dtb = lseek(fd, 0, SEEK_CUR); if (access(DTB_FILE, R_OK) == 0) { hdr->dtb_size() = restore(fd, DTB_FILE); file_align(); } // Copy boot signature if (boot.hdr->signature_size()) { xwrite(fd, boot.signature, boot.hdr->signature_size()); file_align(); } // vendor ramdisk table if (!ramdisk_table.empty()) { xwrite(fd, ramdisk_table.data(), sizeof(table_entry) * ramdisk_table.size()); file_align(); } // bootconfig if (access(BOOTCONFIG_FILE, R_OK) == 0) { hdr->bootconfig_size() = restore(fd, BOOTCONFIG_FILE); file_align(); } // Proprietary stuffs if (boot.flags[SEANDROID_FLAG]) { xwrite(fd, SEANDROID_MAGIC, 16); if (boot.flags[DHTB_FLAG]) { xwrite(fd, "\xFF\xFF\xFF\xFF", 4); } } else if (boot.flags[LG_BUMP_FLAG]) { xwrite(fd, LG_BUMP_MAGIC, 16); } off.total = lseek(fd, 0, SEEK_CUR); file_align(); // vbmeta if (boot.flags[AVB_FLAG]) { // According to avbtool.py, if the input is not an Android sparse image // (which boot images are not), the default block size is 4096 file_align_with(4096); off.vbmeta = lseek(fd, 0, SEEK_CUR); uint64_t vbmeta_size = __builtin_bswap64(boot.avb_footer->vbmeta_size); xwrite(fd, boot.vbmeta, vbmeta_size); } // Pad image to original size if not chromeos (as it requires post processing) if (!boot.flags[CHROMEOS_FLAG]) { off_t current = lseek(fd, 0, SEEK_CUR); if (current < boot.map.sz()) { write_zero(fd, boot.map.sz() - current); } } /****************** * Patch the image ******************/ // Map output image as rw mmap_data out(out_img, true); // MTK headers if (boot.flags[MTK_KERNEL]) { auto m_hdr = reinterpret_cast<mtk_hdr *>(out.buf() + off.kernel); m_hdr->size = hdr->kernel_size(); hdr->kernel_size() += sizeof(mtk_hdr); } if (boot.flags[MTK_RAMDISK]) { auto m_hdr = reinterpret_cast<mtk_hdr *>(out.buf() + off.ramdisk); m_hdr->size = hdr->ramdisk_size(); hdr->ramdisk_size() += sizeof(mtk_hdr); } // Make sure header size matches hdr->header_size() = hdr->hdr_size(); // Update checksum if (char *id = hdr->id()) { auto ctx = get_sha(!boot.flags[SHA256_FLAG]); uint32_t size = hdr->kernel_size(); ctx->update(byte_view(out.buf() + off.kernel, size)); ctx->update(byte_view(&size, sizeof(size))); size = hdr->ramdisk_size(); ctx->update(byte_view(out.buf() + off.ramdisk, size)); ctx->update(byte_view(&size, sizeof(size))); size = hdr->second_size(); ctx->update(byte_view(out.buf() + off.second, size)); ctx->update(byte_view(&size, sizeof(size))); size = hdr->extra_size(); if (size) { ctx->update(byte_view(out.buf() + off.extra, size)); ctx->update(byte_view(&size, sizeof(size))); } uint32_t ver = hdr->header_version(); if (ver == 1 || ver == 2) { size = hdr->recovery_dtbo_size(); ctx->update(byte_view(out.buf() + hdr->recovery_dtbo_offset(), size)); ctx->update(byte_view(&size, sizeof(size))); } if (ver == 2) { size = hdr->dtb_size(); ctx->update(byte_view(out.buf() + off.dtb, size)); ctx->update(byte_view(&size, sizeof(size))); } memset(id, 0, BOOT_ID_SIZE); ctx->finalize_into(byte_data(id, ctx->output_size())); } // Print new header info hdr->print(); // Copy main header if (boot.flags[AMONET_FLAG]) { auto real_hdr_sz = std::min(hdr->hdr_space() - AMONET_MICROLOADER_SZ, hdr->hdr_size()); memcpy(out.buf() + off.header + AMONET_MICROLOADER_SZ, hdr->raw_hdr(), real_hdr_sz); } else { memcpy(out.buf() + off.header, hdr->raw_hdr(), hdr->hdr_size()); } if (boot.flags[AVB_FLAG]) { // Copy and patch AVB structures auto footer = reinterpret_cast<AvbFooter*>(out.buf() + out.sz() - sizeof(AvbFooter)); memcpy(footer, boot.avb_footer, sizeof(AvbFooter)); footer->original_image_size = __builtin_bswap64(off.total); footer->vbmeta_offset = __builtin_bswap64(off.vbmeta); if (check_env("PATCHVBMETAFLAG")) { auto vbmeta = reinterpret_cast<AvbVBMetaImageHeader*>(out.buf() + off.vbmeta); vbmeta->flags = __builtin_bswap32(3); } } if (boot.flags[DHTB_FLAG]) { // DHTB header auto d_hdr = reinterpret_cast<dhtb_hdr *>(out.buf()); memcpy(d_hdr, DHTB_MAGIC, 8); d_hdr->size = off.total - sizeof(dhtb_hdr); sha256_hash(byte_view(out.buf() + sizeof(dhtb_hdr), d_hdr->size), byte_data(d_hdr->checksum, 32)); } else if (boot.flags[BLOB_FLAG]) { // Blob header auto b_hdr = reinterpret_cast<blob_hdr *>(out.buf()); b_hdr->size = off.total - sizeof(blob_hdr); } // Sign the image after we finish patching the boot image if (boot.flags[AVB1_SIGNED_FLAG]) { byte_view payload(out.buf() + off.header, off.total - off.header); auto sig = rust::sign_boot_image(payload, "/boot", nullptr, nullptr); if (!sig.empty()) { lseek(fd, off.total, SEEK_SET); xwrite(fd, sig.data(), sig.size()); } } close(fd); } int verify(const char *image, const char *cert) { const boot_img boot(image); if (cert == nullptr) { // Boot image parsing already checks if the image is signed return boot.flags[AVB1_SIGNED_FLAG] ? 0 : 1; } else { // Provide a custom certificate and re-verify return boot.verify(cert) ? 0 : 1; } } int sign(const char *image, const char *name, const char *cert, const char *key) { const boot_img boot(image); auto sig = rust::sign_boot_image(boot.payload, name, cert, key); if (sig.empty()) return 1; auto eof = boot.tail.buf() - boot.map.buf(); int fd = xopen(image, O_WRONLY | O_CLOEXEC); if (lseek(fd, eof, SEEK_SET) != eof || xwrite(fd, sig.data(), sig.size()) != sig.size()) { close(fd); return 1; } if (auto off = lseek(fd, 0, SEEK_CUR); off < boot.map.sz()) { // Wipe out rest of tail write_zero(fd, boot.map.sz() - off); } close(fd); return 0; }
36,011
C++
.cpp
896
31.418527
104
0.548525
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25
main.cpp
topjohnwu_Magisk/native/src/boot/main.cpp
#include <base.hpp> #include "boot-rs.hpp" #include "magiskboot.hpp" #include "compress.hpp" using namespace std; #ifdef USE_CRT0 __BEGIN_DECLS int musl_vfprintf(FILE *stream, const char *format, va_list arg); int vfprintf(FILE *stream, const char *format, va_list arg) { return musl_vfprintf(stream, format, arg); } __END_DECLS #endif static void print_formats() { for (int fmt = GZIP; fmt < LZOP; ++fmt) { fprintf(stderr, "%s ", fmt2name[(format_t) fmt]); } } static void usage(char *arg0) { fprintf(stderr, R"EOF(MagiskBoot - Boot Image Modification Tool Usage: %s <action> [args...] Supported actions: unpack [-n] [-h] <bootimg> Unpack <bootimg> to its individual components, each component to a file with its corresponding file name in the current directory. Supported components: kernel, kernel_dtb, ramdisk.cpio, second, dtb, extra, and recovery_dtbo. By default, each component will be decompressed on-the-fly. If '-n' is provided, all decompression operations will be skipped; each component will remain untouched, dumped in its original format. If '-h' is provided, the boot image header information will be dumped to the file 'header', which can be used to modify header configurations during repacking. Return values: 0:valid 1:error 2:chromeos repack [-n] <origbootimg> [outbootimg] Repack boot image components using files from the current directory to [outbootimg], or 'new-boot.img' if not specified. Current directory should only contain required files for [outbootimg], or incorrect [outbootimg] may be produced. <origbootimg> is the original boot image used to unpack the components. By default, each component will be automatically compressed using its corresponding format detected in <origbootimg>. If a component file in the current directory is already compressed, then no addition compression will be performed for that specific component. If '-n' is provided, all compression operations will be skipped. If env variable PATCHVBMETAFLAG is set to true, all disable flags in the boot image's vbmeta header will be set. verify <bootimg> [x509.pem] Check whether the boot image is signed with AVB 1.0 signature. Optionally provide a certificate to verify whether the image is signed by the public key certificate. Return value: 0:valid 1:error sign <bootimg> [name] [x509.pem pk8] Sign <bootimg> with AVB 1.0 signature. Optionally provide the name of the image (default: '/boot'). Optionally provide the certificate/private key pair for signing. If the certificate/private key pair is not provided, the AOSP verity key bundled in the executable will be used. extract <payload.bin> [partition] [outfile] Extract [partition] from <payload.bin> to [outfile]. If [outfile] is not specified, then output to '[partition].img'. If [partition] is not specified, then attempt to extract either 'init_boot' or 'boot'. Which partition was chosen can be determined by whichever 'init_boot.img' or 'boot.img' exists. <payload.bin> can be '-' to be STDIN. hexpatch <file> <hexpattern1> <hexpattern2> Search <hexpattern1> in <file>, and replace it with <hexpattern2> cpio <incpio> [commands...] Do cpio commands to <incpio> (modifications are done in-place). Each command is a single argument; add quotes for each command. See "cpio --help" for supported commands. dtb <file> <action> [args...] Do dtb related actions to <file>. See "dtb --help" for supported actions. split [-n] <file> Split image.*-dtb into kernel + kernel_dtb. If '-n' is provided, decompression operations will be skipped; the kernel will remain untouched, split in its original format. sha1 <file> Print the SHA1 checksum for <file> cleanup Cleanup the current working directory compress[=format] <infile> [outfile] Compress <infile> with [format] to [outfile]. <infile>/[outfile] can be '-' to be STDIN/STDOUT. If [format] is not specified, then gzip will be used. If [outfile] is not specified, then <infile> will be replaced with another file suffixed with a matching file extension. Supported formats: )EOF", arg0); print_formats(); fprintf(stderr, R"EOF( decompress <infile> [outfile] Detect format and decompress <infile> to [outfile]. <infile>/[outfile] can be '-' to be STDIN/STDOUT. If [outfile] is not specified, then <infile> will be replaced with another file removing its archive format file extension. Supported formats: )EOF"); print_formats(); fprintf(stderr, "\n\n"); exit(1); } int main(int argc, char *argv[]) { cmdline_logging(); umask(0); if (argc < 2) usage(argv[0]); // Skip '--' for backwards compatibility string_view action(argv[1]); if (str_starts(action, "--")) action = argv[1] + 2; if (action == "cleanup") { fprintf(stderr, "Cleaning up...\n"); unlink(HEADER_FILE); unlink(KERNEL_FILE); unlink(RAMDISK_FILE); unlink(SECOND_FILE); unlink(KER_DTB_FILE); unlink(EXTRA_FILE); unlink(RECV_DTBO_FILE); unlink(DTB_FILE); unlink(BOOTCONFIG_FILE); rm_rf(VND_RAMDISK_DIR); } else if (argc > 2 && action == "sha1") { uint8_t sha1[20]; { mmap_data m(argv[2]); sha1_hash(m, byte_data(sha1, sizeof(sha1))); } for (uint8_t i : sha1) printf("%02x", i); printf("\n"); } else if (argc > 2 && action == "split") { if (argv[2] == "-n"sv) { if (argc == 3) usage(argv[0]); return split_image_dtb(argv[3], true); } else { return split_image_dtb(argv[2]); } } else if (argc > 2 && action == "unpack") { int idx = 2; bool nodecomp = false; bool hdr = false; for (;;) { if (idx >= argc) usage(argv[0]); if (argv[idx][0] != '-') break; for (char *flag = &argv[idx][1]; *flag; ++flag) { if (*flag == 'n') nodecomp = true; else if (*flag == 'h') hdr = true; else usage(argv[0]); } ++idx; } return unpack(argv[idx], nodecomp, hdr); } else if (argc > 2 && action == "repack") { if (argv[2] == "-n"sv) { if (argc == 3) usage(argv[0]); repack(argv[3], argv[4] ? argv[4] : NEW_BOOT, true); } else { repack(argv[2], argv[3] ? argv[3] : NEW_BOOT); } } else if (argc > 2 && action == "verify") { return verify(argv[2], argv[3]); } else if (argc > 2 && action == "sign") { if (argc == 5) usage(argv[0]); return sign( argv[2], argc > 3 ? argv[3] : "/boot", argc > 5 ? argv[4] : nullptr, argc > 5 ? argv[5] : nullptr); } else if (argc > 2 && action == "decompress") { decompress(argv[2], argv[3]); } else if (argc > 2 && str_starts(action, "compress")) { compress(action[8] == '=' ? &action[9] : "gzip", argv[2], argv[3]); } else if (argc > 4 && action == "hexpatch") { return hexpatch(byte_view(argv[2]), byte_view(argv[3]), byte_view(argv[4])) ? 0 : 1; } else if (argc > 2 && action == "cpio") { return rust::cpio_commands(argc - 2, argv + 2) ? 0 : 1; } else if (argc > 2 && action == "dtb") { return rust::dtb_commands(argc - 2, argv + 2) ? 0 : 1; } else if (argc > 2 && action == "extract") { return rust::extract_boot_from_payload( argv[2], argc > 3 ? argv[3] : nullptr, argc > 4 ? argv[4] : nullptr ) ? 0 : 1; } else { usage(argv[0]); } return 0; }
8,056
C++
.cpp
200
33.17
92
0.610245
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
27
format.cpp
topjohnwu_Magisk/native/src/boot/format.cpp
#include "format.hpp" Name2Fmt name2fmt; Fmt2Name fmt2name; Fmt2Ext fmt2ext; #define CHECKED_MATCH(s) (len >= (sizeof(s) - 1) && BUFFER_MATCH(buf, s)) format_t check_fmt(const void *buf, size_t len) { if (CHECKED_MATCH(CHROMEOS_MAGIC)) { return CHROMEOS; } else if (CHECKED_MATCH(BOOT_MAGIC)) { return AOSP; } else if (CHECKED_MATCH(VENDOR_BOOT_MAGIC)) { return AOSP_VENDOR; } else if (CHECKED_MATCH(GZIP1_MAGIC) || CHECKED_MATCH(GZIP2_MAGIC)) { return GZIP; } else if (CHECKED_MATCH(LZOP_MAGIC)) { return LZOP; } else if (CHECKED_MATCH(XZ_MAGIC)) { return XZ; } else if (len >= 13 && memcmp(buf, "\x5d\x00\x00", 3) == 0 && (((char *)buf)[12] == '\xff' || ((char *)buf)[12] == '\x00')) { return LZMA; } else if (CHECKED_MATCH(BZIP_MAGIC)) { return BZIP2; } else if (CHECKED_MATCH(LZ41_MAGIC) || CHECKED_MATCH(LZ42_MAGIC)) { return LZ4; } else if (CHECKED_MATCH(LZ4_LEG_MAGIC)) { return LZ4_LEGACY; } else if (CHECKED_MATCH(MTK_MAGIC)) { return MTK; } else if (CHECKED_MATCH(DTB_MAGIC)) { return DTB; } else if (CHECKED_MATCH(DHTB_MAGIC)) { return DHTB; } else if (CHECKED_MATCH(TEGRABLOB_MAGIC)) { return BLOB; } else if (len >= 0x28 && memcmp(&((char *)buf)[0x24], ZIMAGE_MAGIC, 4) == 0) { return ZIMAGE; } else { return UNKNOWN; } } const char *Fmt2Name::operator[](format_t fmt) { switch (fmt) { case GZIP: return "gzip"; case ZOPFLI: return "zopfli"; case LZOP: return "lzop"; case XZ: return "xz"; case LZMA: return "lzma"; case BZIP2: return "bzip2"; case LZ4: return "lz4"; case LZ4_LEGACY: return "lz4_legacy"; case LZ4_LG: return "lz4_lg"; case DTB: return "dtb"; case ZIMAGE: return "zimage"; default: return "raw"; } } const char *Fmt2Ext::operator[](format_t fmt) { switch (fmt) { case GZIP: case ZOPFLI: return ".gz"; case LZOP: return ".lzo"; case XZ: return ".xz"; case LZMA: return ".lzma"; case BZIP2: return ".bz2"; case LZ4: case LZ4_LEGACY: case LZ4_LG: return ".lz4"; default: return ""; } } #define CHECK(s, f) else if (name == s) return f; format_t Name2Fmt::operator[](std::string_view name) { if (0) {} CHECK("gzip", GZIP) CHECK("zopfli", ZOPFLI) CHECK("xz", XZ) CHECK("lzma", LZMA) CHECK("bzip2", BZIP2) CHECK("lz4", LZ4) CHECK("lz4_legacy", LZ4_LEGACY) CHECK("lz4_lg", LZ4_LG) else return UNKNOWN; }
2,902
C++
.cpp
103
20.621359
83
0.533668
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
28
twostage.cpp
topjohnwu_Magisk/native/src/init/twostage.cpp
#include <sys/mount.h> #include <consts.hpp> #include <base.hpp> #include <sys/vfs.h> #include "init.hpp" using namespace std; void FirstStageInit::prepare() { prepare_data(); if (struct stat st{}; fstatat(-1, "/sdcard", &st, AT_SYMLINK_NOFOLLOW) != 0 && fstatat(-1, "/first_stage_ramdisk/sdcard", &st, AT_SYMLINK_NOFOLLOW) != 0) { if (config->force_normal_boot) { xmkdirs("/first_stage_ramdisk/storage/self", 0755); xsymlink("/system/system/bin/init", "/first_stage_ramdisk/storage/self/primary"); LOGD("Symlink /first_stage_ramdisk/storage/self/primary -> /system/system/bin/init\n"); close(xopen("/first_stage_ramdisk/sdcard", O_RDONLY | O_CREAT | O_CLOEXEC, 0)); } else { xmkdirs("/storage/self", 0755); xsymlink("/system/system/bin/init", "/storage/self/primary"); LOGD("Symlink /storage/self/primary -> /system/system/bin/init\n"); } xrename("/init", "/sdcard"); // Try to keep magiskinit in rootfs for samsung RKP if (mount("/sdcard", "/sdcard", nullptr, MS_BIND, nullptr) == 0) { LOGD("Bind mount /sdcard -> /sdcard\n"); } else { // rootfs before 3.12 xmount("/data/magiskinit", "/sdcard", nullptr, MS_BIND, nullptr); LOGD("Bind mount /sdcard -> /data/magiskinit\n"); } restore_ramdisk_init(); } else { restore_ramdisk_init(); // fallback to hexpatch if /sdcard exists auto init = mmap_data("/init", true); // Redirect original init to magiskinit for (size_t off : init.patch(INIT_PATH, REDIR_PATH)) { LOGD("Patch @ %08zX [" INIT_PATH "] -> [" REDIR_PATH "]\n", off); } } } void LegacySARInit::first_stage_prep() { // Patch init binary int src = xopen("/init", O_RDONLY); int dest = xopen("/data/init", O_CREAT | O_WRONLY, 0); { mmap_data init("/init"); for (size_t off : init.patch(INIT_PATH, REDIR_PATH)) { LOGD("Patch @ %08zX [" INIT_PATH "] -> [" REDIR_PATH "]\n", off); } write(dest, init.buf(), init.sz()); fclone_attr(src, dest); close(dest); close(src); } xmount("/data/init", "/init", nullptr, MS_BIND, nullptr); } bool SecondStageInit::prepare() { umount2("/init", MNT_DETACH); umount2(INIT_PATH, MNT_DETACH); // just in case unlink("/data/init"); // Make sure init dmesg logs won't get messed up argv[0] = (char *) INIT_PATH; // Some weird devices like meizu, uses 2SI but still have legacy rootfs struct statfs sfs{}; statfs("/", &sfs); if (sfs.f_type == RAMFS_MAGIC || sfs.f_type == TMPFS_MAGIC) { // We are still on rootfs, so make sure we will execute the init of the 2nd stage unlink("/init"); xsymlink(INIT_PATH, "/init"); return true; } return false; }
2,944
C++
.cpp
73
32.958904
99
0.584207
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29
selinux.cpp
topjohnwu_Magisk/native/src/init/selinux.cpp
#include <sys/mount.h> #include <consts.hpp> #include <sepolicy.hpp> #include "init.hpp" using namespace std; void MagiskInit::patch_sepolicy(const char *in, const char *out) { LOGD("Patching monolithic policy\n"); auto sepol = unique_ptr<sepolicy>(sepolicy::from_file(in)); sepol->magisk_rules(); // Custom rules auto rule = "/data/" PREINITMIRR "/sepolicy.rule"; if (xaccess(rule, R_OK) == 0) { LOGD("Loading custom sepolicy patch: [%s]\n", rule); sepol->load_rule_file(rule); } LOGD("Dumping sepolicy to: [%s]\n", out); sepol->to_file(out); // Remove OnePlus stupid debug sepolicy and use our own if (access("/sepolicy_debug", F_OK) == 0) { unlink("/sepolicy_debug"); link("/sepolicy", "/sepolicy_debug"); } } #define MOCK_COMPAT SELINUXMOCK "/compatible" #define MOCK_LOAD SELINUXMOCK "/load" #define MOCK_ENFORCE SELINUXMOCK "/enforce" bool MagiskInit::hijack_sepolicy() { xmkdir(SELINUXMOCK, 0); if (access("/system/bin/init", F_OK) == 0) { // On 2SI devices, the 2nd stage init file is always a dynamic executable. // This meant that instead of going through convoluted methods trying to alter // and block init's control flow, we can just LD_PRELOAD and replace the // security_load_policy function with our own implementation. cp_afc("init-ld", "/dev/preload.so"); setenv("LD_PRELOAD", "/dev/preload.so", 1); } // Hijack the "load" and "enforce" node in selinuxfs to manipulate // the actual sepolicy being loaded into the kernel auto hijack = [&] { LOGD("Hijack [" SELINUX_LOAD "]\n"); close(xopen(MOCK_LOAD, O_CREAT | O_RDONLY, 0600)); xmount(MOCK_LOAD, SELINUX_LOAD, nullptr, MS_BIND, nullptr); LOGD("Hijack [" SELINUX_ENFORCE "]\n"); mkfifo(MOCK_ENFORCE, 0644); xmount(MOCK_ENFORCE, SELINUX_ENFORCE, nullptr, MS_BIND, nullptr); }; string dt_compat; if (access(SELINUX_ENFORCE, F_OK) != 0) { // selinuxfs not mounted yet. Hijack the dt fstab nodes first // and let the original init mount selinuxfs for us. // This only happens on Android 8.0 - 9.0 char buf[4096]; ssprintf(buf, sizeof(buf), "%s/fstab/compatible", config->dt_dir); dt_compat = full_read(buf); if (dt_compat.empty()) { // Device does not do early mount and uses monolithic policy return false; } // Remount procfs with proper options xmount(nullptr, "/proc", nullptr, MS_REMOUNT, "hidepid=2,gid=3009"); LOGD("Hijack [%s]\n", buf); // Preserve sysfs and procfs for hijacking mount_list.erase(std::remove_if( mount_list.begin(), mount_list.end(), [](const string &s) { return s == "/proc" || s == "/sys"; }), mount_list.end()); mkfifo(MOCK_COMPAT, 0444); xmount(MOCK_COMPAT, buf, nullptr, MS_BIND, nullptr); } else { hijack(); } // Read all custom rules into memory string rules; auto rule = "/data/" PREINITMIRR "/sepolicy.rule"; if (xaccess(rule, R_OK) == 0) { LOGD("Loading custom sepolicy patch: [%s]\n", rule); rules = full_read(rule); } // Create a new process waiting for init operations if (xfork()) { // In parent, return and continue boot process return true; } if (!dt_compat.empty()) { // This open will block until init calls DoFirstStageMount // The only purpose here is actually to wait for init to mount selinuxfs for us int fd = xopen(MOCK_COMPAT, O_WRONLY); char buf[4096]; ssprintf(buf, sizeof(buf), "%s/fstab/compatible", config->dt_dir); xumount2(buf, MNT_DETACH); hijack(); xwrite(fd, dt_compat.data(), dt_compat.size()); close(fd); } // This open will block until init calls security_getenforce int fd = xopen(MOCK_ENFORCE, O_WRONLY); // Cleanup the hijacks umount2("/init", MNT_DETACH); xumount2(SELINUX_LOAD, MNT_DETACH); xumount2(SELINUX_ENFORCE, MNT_DETACH); // Load and patch policy auto sepol = unique_ptr<sepolicy>(sepolicy::from_file(MOCK_LOAD)); sepol->magisk_rules(); sepol->load_rules(rules); // Load patched policy into kernel sepol->to_file(SELINUX_LOAD); // Write to the enforce node ONLY after sepolicy is loaded. We need to make sure // the actual init process is blocked until sepolicy is loaded, or else // restorecon will fail and re-exec won't change context, causing boot failure. // We (ab)use the fact that init reads the enforce node, and because // it has been replaced with our FIFO file, init will block until we // write something into the pipe, effectively hijacking its control flow. string enforce = full_read(SELINUX_ENFORCE); xwrite(fd, enforce.data(), enforce.length()); close(fd); // At this point, the init process will be unblocked // and continue on with restorecon + re-exec. // Terminate process exit(0); }
5,135
C++
.cpp
119
36.445378
96
0.638516
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
30
init.cpp
topjohnwu_Magisk/native/src/init/init.cpp
#include <sys/stat.h> #include <sys/types.h> #include <libgen.h> #include <vector> #include <xz.h> #include <base.hpp> #include "init.hpp" using namespace std; #ifdef USE_CRT0 __BEGIN_DECLS int tiny_vfprintf(FILE *stream, const char *format, va_list arg); int vfprintf(FILE *stream, const char *format, va_list arg) { return tiny_vfprintf(stream, format, arg); } __END_DECLS #endif bool unxz(out_stream &strm, rust::Slice<const uint8_t> bytes) { uint8_t out[8192]; xz_crc32_init(); size_t size = bytes.size(); struct xz_dec *dec = xz_dec_init(XZ_DYNALLOC, 1 << 26); run_finally finally([&] { xz_dec_end(dec); }); struct xz_buf b = { .in = bytes.data(), .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 false; strm.write(out, b.out_pos); b.out_pos = 0; } while (b.in_pos != size); return true; } void restore_ramdisk_init() { unlink("/init"); const char *orig_init = backup_init(); if (access(orig_init, F_OK) == 0) { xrename(orig_init, "/init"); } else { // If the backup init is missing, this means that the boot ramdisk // was created from scratch, and the real init is in a separate CPIO, // which is guaranteed to be placed at /system/bin/init. xsymlink(INIT_PATH, "/init"); } } class RecoveryInit : public BaseInit { public: using BaseInit::BaseInit; void start() override { LOGD("Ramdisk is recovery, abort\n"); restore_ramdisk_init(); rm_rf("/.backup"); exec_init(); } }; int main(int argc, char *argv[]) { umask(0); auto name = basename(argv[0]); if (name == "magisk"sv) return magisk_proxy_main(argc, argv); if (getpid() != 1) return 1; BaseInit *init; BootConfig config{}; if (argc > 1 && argv[1] == "selinux_setup"sv) { rust::setup_klog(); init = new SecondStageInit(argv); } else { // This will also mount /sys and /proc load_kernel_info(&config); bool recovery = access("/sbin/recovery", F_OK) == 0 || access("/system/bin/recovery", F_OK) == 0; if (config.force_normal_boot) init = new FirstStageInit(argv, &config); else if (!recovery && check_two_stage()) init = new FirstStageInit(argv, &config); else if (config.skip_initramfs) init = new LegacySARInit(argv, &config); else if (recovery) init = new RecoveryInit(argv, &config); else init = new RootFSInit(argv, &config); } // Run the main routine init->start(); exit(1); }
2,861
C++
.cpp
94
24.234043
77
0.581818
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
31
mount.cpp
topjohnwu_Magisk/native/src/init/mount.cpp
#include <set> #include <sys/mount.h> #include <sys/sysmacros.h> #include <libgen.h> #include <base.hpp> #include <flags.h> #include <consts.hpp> #include "init.hpp" using namespace std; struct devinfo { int major; int minor; char devname[32]; char partname[32]; char dmname[32]; char devpath[PATH_MAX]; }; static vector<devinfo> dev_list; // When this boolean is set, this means we are currently // running magiskinit on legacy SAR AVD emulator bool avd_hack = false; static void parse_device(devinfo *dev, const char *uevent) { dev->partname[0] = '\0'; dev->devpath[0] = '\0'; dev->dmname[0] = '\0'; dev->devname[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") strscpy(dev->devname, value.data(), sizeof(dev->devname)); else if (key == "PARTNAME") strscpy(dev->partname, value.data(), sizeof(dev->devname)); return true; }); } static void collect_devices(const auto &partition_map) { char path[PATH_MAX]; 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)); strscpy(dev.dmname, name.data(), sizeof(dev.dmname)); } if (auto it = std::ranges::find_if(partition_map, [&](const auto &i) { return i.first == dev.devname; }); dev.partname[0] == '\0' && it != partition_map.end()) { // use androidboot.partition_map as partname fallback. strscpy(dev.partname, it->second.data(), sizeof(dev.partname)); } sprintf(path, "/sys/dev/block/%s", entry->d_name); xrealpath(path, dev.devpath, sizeof(dev.devpath)); dev_list.push_back(dev); } } } static struct { char partname[32]; char block_dev[64]; } blk_info; static dev_t setup_block() { static const auto partition_map = load_partition_map(); if (dev_list.empty()) collect_devices(partition_map); 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 if (strcasecmp(dev.devname, blk_info.partname) == 0) LOGD("Setup %s: [%s] (%d, %d)\n", dev.devname, dev.devname, dev.major, dev.minor); else if (std::string_view(dev.devpath).ends_with("/"s + blk_info.partname)) LOGD("Setup %s: [%s] (%d, %d)\n", dev.devpath, dev.devname, dev.major, dev.minor); else continue; dev_t rdev = makedev(dev.major, dev.minor); xmknod(blk_info.block_dev, S_IFBLK | 0600, rdev); return rdev; } // Wait 10ms and try again usleep(10000); dev_list.clear(); collect_devices(partition_map); } // The requested partname does not exist return 0; } static void mount_preinit_dir(string preinit_dev) { if (preinit_dev.empty()) return; strcpy(blk_info.partname, preinit_dev.data()); strcpy(blk_info.block_dev, PREINITDEV); auto dev = setup_block(); if (dev == 0) { LOGE("Cannot find preinit %s, abort!\n", preinit_dev.data()); return; } xmkdir(MIRRDIR, 0); bool mounted = false; // First, find if it is already mounted std::string mnt_point; if (rust::is_device_mounted(dev, mnt_point)) { // Already mounted, just bind mount xmount(mnt_point.data(), MIRRDIR, nullptr, MS_BIND, nullptr); mounted = true; } // Since we are mounting the block device directly, make sure to ONLY mount the partitions // as read-only, or else the kernel might crash due to crappy drivers. // After the device boots up, magiskd will properly bind mount the correct partition // on to PREINITMIRR as writable. For more details, check bootstages.cpp if (mounted || mount(PREINITDEV, MIRRDIR, "ext4", MS_RDONLY, nullptr) == 0 || mount(PREINITDEV, MIRRDIR, "f2fs", MS_RDONLY, nullptr) == 0) { string preinit_dir = resolve_preinit_dir(MIRRDIR); // 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); } xumount2(MIRRDIR, MNT_DETACH); } else { PLOGE("Failed to mount preinit %s\n", preinit_dev.data()); unlink(PREINITDEV); } } bool LegacySARInit::mount_system_root() { LOGD("Mounting system_root\n"); // 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"); auto dev = setup_block(); if (dev > 0) goto mount_root; // Try NVIDIA naming scheme strcpy(blk_info.partname, "APP"); dev = setup_block(); if (dev > 0) goto mount_root; sprintf(blk_info.partname, "system%s", config->slot); dev = setup_block(); if (dev > 0) goto mount_root; // Poll forever if rootwait was given in cmdline } 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); 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); } } rust::switch_root("/system_root"); // Make dev writable xmount("tmpfs", "/dev", "tmpfs", 0, "mode=755"); mount_list.emplace_back("/dev"); bool is_two_stage = access("/system/bin/init", F_OK) == 0; LOGD("is_two_stage: [%d]\n", is_two_stage); // For API 28 AVD, it uses legacy SAR setup that requires // special hacks in magiskinit to work properly. if (!is_two_stage && config->emulator) { avd_hack = true; // 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); } return is_two_stage; } void BaseInit::exec_init() { // Unmount in reverse order for (auto &p : reversed(mount_list)) { if (xumount2(p.data(), MNT_DETACH) == 0) LOGD("Unmount [%s]\n", p.data()); } execve("/init", argv, environ); exit(1); } void BaseInit::prepare_data() { LOGD("Setup data tmp\n"); xmkdir("/data", 0755); xmount("magisk", "/data", "tmpfs", 0, "mode=755"); cp_afc("/init", "/data/magiskinit"); cp_afc("/.backup", "/data/.backup"); cp_afc("/overlay.d", "/data/overlay.d"); } void MagiskInit::setup_tmp(const char *path) { LOGD("Setup Magisk tmp at %s\n", path); chdir("/data"); xmkdir(INTLROOT, 0711); xmkdir(DEVICEDIR, 0711); xmkdir(WORKERDIR, 0); mount_preinit_dir(preinit_dev); cp_afc(".backup/.magisk", MAIN_CONFIG); rm_rf(".backup"); // Create applet symlinks for (int i = 0; applet_names[i]; ++i) xsymlink("./magisk", applet_names[i]); xsymlink("./magiskpolicy", "supolicy"); xmount(".", path, nullptr, MS_BIND, nullptr); chdir(path); // Prepare worker xmount(WORKERDIR, WORKERDIR, nullptr, MS_BIND, nullptr); // Use isolated devpts if kernel support if (access("/dev/pts/ptmx", F_OK) == 0) { xmkdirs(SHELLPTS, 0755); xmount("devpts", SHELLPTS, "devpts", MS_NOSUID | MS_NOEXEC, "newinstance"); xmount(nullptr, SHELLPTS, nullptr, MS_PRIVATE, nullptr); if (access(SHELLPTS "/ptmx", F_OK)) { umount2(SHELLPTS, MNT_DETACH); rmdir(SHELLPTS); } } chdir("/"); }
9,033
C++
.cpp
234
31.226496
99
0.585722
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
32
rootdir.cpp
topjohnwu_Magisk/native/src/init/rootdir.cpp
#include <sys/mount.h> #include <libgen.h> #include <sys/sysmacros.h> #include <sepolicy.hpp> #include <consts.hpp> #include <base.hpp> #include <flags.h> #include "init.hpp" using namespace std; static vector<string> rc_list; static string magic_mount_list; #define NEW_INITRC_DIR "/system/etc/init/hw" #define INIT_RC "init.rc" static void magic_mount(const string &sdir, const string &ddir = "") { auto dir = xopen_dir(sdir.data()); if (!dir) return; for (dirent *entry; (entry = xreaddir(dir.get()));) { string src = sdir + "/" + entry->d_name; string dest = ddir + "/" + entry->d_name; if (access(dest.data(), F_OK) == 0) { if (entry->d_type == DT_DIR) { // Recursive magic_mount(src, dest); } else { LOGD("Mount [%s] -> [%s]\n", src.data(), dest.data()); xmount(src.data(), dest.data(), nullptr, MS_BIND, nullptr); magic_mount_list += dest; magic_mount_list += '\n'; } } } } static void patch_rc_scripts(const char *src_path, const char *tmp_path, bool writable) { auto src_dir = xopen_dir(src_path); if (!src_dir) return; int src_fd = dirfd(src_dir.get()); // If writable, directly modify the file in src_path, or else add to rootfs overlay auto dest_dir = writable ? [&] { return xopen_dir(src_path); }() : [&] { char buf[PATH_MAX] = {}; ssprintf(buf, sizeof(buf), ROOTOVL "%s", src_path); xmkdirs(buf, 0755); return xopen_dir(buf); }(); if (!dest_dir) return; int dest_fd = dirfd(dest_dir.get()); // First patch init.rc { auto src = xopen_file(xopenat(src_fd, INIT_RC, O_RDONLY | O_CLOEXEC, 0), "re"); if (!src) return; if (writable) unlinkat(src_fd, INIT_RC, 0); auto dest = xopen_file( xopenat(dest_fd, INIT_RC, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0), "we"); if (!dest) return; LOGD("Patching " INIT_RC " in %s\n", src_path); file_readline(false, src.get(), [&dest](string_view line) -> bool { // Do not start vaultkeeper if (str_contains(line, "start vaultkeeper")) { LOGD("Remove vaultkeeper\n"); return true; } // Do not run flash_recovery if (line.starts_with("service flash_recovery")) { LOGD("Remove flash_recovery\n"); fprintf(dest.get(), "service flash_recovery /system/bin/true\n"); return true; } // Samsung's persist.sys.zygote.early will cause Zygote to start before post-fs-data if (line.starts_with("on property:persist.sys.zygote.early=")) { LOGD("Invalidate persist.sys.zygote.early\n"); fprintf(dest.get(), "on property:persist.sys.zygote.early.xxxxx=true\n"); return true; } // Else just write the line fprintf(dest.get(), "%s", line.data()); return true; }); fprintf(dest.get(), "\n"); // Inject custom rc scripts for (auto &script : rc_list) { // Replace template arguments of rc scripts with dynamic paths replace_all(script, "${MAGISKTMP}", tmp_path); fprintf(dest.get(), "\n%s\n", script.data()); } rc_list.clear(); // Inject Magisk rc scripts rust::inject_magisk_rc(fileno(dest.get()), tmp_path); fclone_attr(fileno(src.get()), fileno(dest.get())); } // Then patch init.zygote*.rc for (dirent *entry; (entry = readdir(src_dir.get()));) { auto name = std::string_view(entry->d_name); if (!name.starts_with("init.zygote") || !name.ends_with(".rc")) continue; auto src = xopen_file(xopenat(src_fd, name.data(), O_RDONLY | O_CLOEXEC, 0), "re"); if (!src) continue; if (writable) unlinkat(src_fd, name.data(), 0); auto dest = xopen_file( xopenat(dest_fd, name.data(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0), "we"); if (!dest) continue; LOGD("Patching %s in %s\n", name.data(), src_path); file_readline(false, src.get(), [&dest, &tmp_path](string_view line) -> bool { if (line.starts_with("service zygote ")) { LOGD("Inject zygote restart\n"); fprintf(dest.get(), "%s", line.data()); fprintf(dest.get(), " onrestart exec " MAGISK_PROC_CON " 0 0 -- %s/magisk --zygote-restart\n", tmp_path); return true; } fprintf(dest.get(), "%s", line.data()); return true; }); fclone_attr(fileno(src.get()), fileno(dest.get())); } if (faccessat(src_fd, "init.fission_host.rc", F_OK, 0) == 0) { { LOGD("Patching fissiond\n"); mmap_data fissiond("/system/bin/fissiond", false); for (size_t off : fissiond.patch("ro.build.system.fission_single_os", "ro.build.system.xxxxxxxxxxxxxxxxx")) { LOGD("Patch @ %08zX [ro.build.system.fission_single_os] -> [ro.build.system.xxxxxxxxxxxxxxxxx]\n", off); } mkdirs(ROOTOVL "/system/bin", 0755); if (auto target_fissiond = xopen_file(ROOTOVL "/system/bin/fissiond", "we")) { fwrite(fissiond.buf(), 1, fissiond.sz(), target_fissiond.get()); clone_attr("/system/bin/fissiond", ROOTOVL "/system/bin/fissiond"); } } LOGD("hijack isolated\n"); auto hijack = xopen_file("/sys/devices/system/cpu/isolated", "re"); mkfifo(INTLROOT "/isolated", 0777); xmount(INTLROOT "/isolated", "/sys/devices/system/cpu/isolated", nullptr, MS_BIND, nullptr); if (!xfork()) { auto dest = xopen_file(INTLROOT "/isolated", "we"); LOGD("hijacked isolated\n"); xumount2("/sys/devices/system/cpu/isolated", MNT_DETACH); unlink(INTLROOT "/isolated"); string content; full_read(fileno(hijack.get()), content); { string target = "/dev/cells/cell2"s + tmp_path; xmkdirs(target.data(), 0); xmount(tmp_path, target.data(), nullptr, MS_BIND | MS_REC,nullptr); magic_mount(ROOTOVL, "/dev/cells/cell2"); auto mount = xopen_file(ROOTMNT, "w"); fwrite(magic_mount_list.data(), 1, magic_mount_list.length(), mount.get()); } fprintf(dest.get(), "%s", content.data()); exit(0); } } } static void load_overlay_rc(const char *overlay) { auto dir = open_dir(overlay); if (!dir) return; int dfd = dirfd(dir.get()); // Do not allow overwrite init.rc unlinkat(dfd, INIT_RC, 0); // '/' + name + '\0' char buf[NAME_MAX + 2]; buf[0] = '/'; for (dirent *entry; (entry = xreaddir(dir.get()));) { if (!str_ends(entry->d_name, ".rc")) { continue; } strscpy(buf + 1, entry->d_name, sizeof(buf) - 1); if (access(buf, F_OK) == 0) { LOGD("Replace rc script [%s]\n", entry->d_name); } else { LOGD("Found rc script [%s]\n", entry->d_name); int rc = xopenat(dfd, entry->d_name, O_RDONLY | O_CLOEXEC); rc_list.push_back(full_read(rc)); close(rc); unlinkat(dfd, entry->d_name, 0); } } } static void recreate_sbin(const char *mirror, bool use_bind_mount) { auto dp = xopen_dir(mirror); int src = dirfd(dp.get()); char buf[4096]; for (dirent *entry; (entry = xreaddir(dp.get()));) { string sbin_path = "/sbin/"s + entry->d_name; struct stat st; fstatat(src, entry->d_name, &st, AT_SYMLINK_NOFOLLOW); if (S_ISLNK(st.st_mode)) { xreadlinkat(src, entry->d_name, buf, sizeof(buf)); xsymlink(buf, sbin_path.data()); } else { sprintf(buf, "%s/%s", mirror, entry->d_name); if (use_bind_mount) { auto mode = st.st_mode & 0777; // Create dummy if (S_ISDIR(st.st_mode)) xmkdir(sbin_path.data(), mode); else close(xopen(sbin_path.data(), O_CREAT | O_WRONLY | O_CLOEXEC, mode)); xmount(buf, sbin_path.data(), nullptr, MS_BIND, nullptr); } else { xsymlink(buf, sbin_path.data()); } } } } static void extract_files(bool sbin) { const char *magisk_xz = sbin ? "/sbin/magisk.xz" : "magisk.xz"; const char *stub_xz = sbin ? "/sbin/stub.xz" : "stub.xz"; const char *init_ld_xz = sbin ? "/sbin/init-ld.xz" : "init-ld.xz"; if (access(magisk_xz, F_OK) == 0) { mmap_data magisk(magisk_xz); unlink(magisk_xz); int fd = xopen("magisk", O_WRONLY | O_CREAT, 0755); fd_stream ch(fd); unxz(ch, magisk); close(fd); } if (access(stub_xz, F_OK) == 0) { mmap_data stub(stub_xz); unlink(stub_xz); int fd = xopen("stub.apk", O_WRONLY | O_CREAT, 0); fd_stream ch(fd); unxz(ch, stub); close(fd); } if (access(init_ld_xz, F_OK) == 0) { mmap_data init_ld(init_ld_xz); unlink(init_ld_xz); int fd = xopen("init-ld", O_WRONLY | O_CREAT, 0); fd_stream ch(fd); unxz(ch, init_ld); close(fd); } } void MagiskInit::parse_config_file() { parse_prop_file("/data/.backup/.magisk", [&](auto key, auto value) -> bool { if (key == "PREINITDEVICE") { preinit_dev = value; return false; } return true; }); } void MagiskInit::patch_ro_root() { mount_list.emplace_back("/data"); parse_config_file(); string tmp_dir; if (access("/sbin", F_OK) == 0) { tmp_dir = "/sbin"; } else { tmp_dir = "/debug_ramdisk"; xmkdir("/data/debug_ramdisk", 0); xmount("/debug_ramdisk", "/data/debug_ramdisk", nullptr, MS_MOVE, nullptr); } setup_tmp(tmp_dir.data()); chdir(tmp_dir.data()); if (tmp_dir == "/sbin") { // Recreate original sbin structure xmkdir(MIRRDIR, 0755); xmount("/", MIRRDIR, nullptr, MS_BIND, nullptr); recreate_sbin(MIRRDIR "/sbin", true); xumount2(MIRRDIR, MNT_DETACH); } else { // Restore debug_ramdisk xmount("/data/debug_ramdisk", "/debug_ramdisk", nullptr, MS_MOVE, nullptr); rmdir("/data/debug_ramdisk"); } xrename("overlay.d", ROOTOVL); extern bool avd_hack; // Handle avd hack if (avd_hack) { int src = xopen("/init", O_RDONLY | O_CLOEXEC); mmap_data init("/init"); // Force disable early mount on original init for (size_t off : init.patch("android,fstab", "xxx")) { LOGD("Patch @ %08zX [android,fstab] -> [xxx]\n", off); } int dest = xopen(ROOTOVL "/init", O_CREAT | O_WRONLY | O_CLOEXEC, 0); xwrite(dest, init.buf(), init.sz()); fclone_attr(src, dest); close(src); close(dest); } load_overlay_rc(ROOTOVL); if (access(ROOTOVL "/sbin", F_OK) == 0) { // Move files in overlay.d/sbin into tmp_dir mv_path(ROOTOVL "/sbin", "."); } // Patch init.rc if (access(NEW_INITRC_DIR "/" INIT_RC, F_OK) == 0) { // Android 11's new init.rc patch_rc_scripts(NEW_INITRC_DIR, tmp_dir.data(), false); } else { patch_rc_scripts("/", tmp_dir.data(), false); } // Extract overlay archives extract_files(false); // Oculus Go will use a special sepolicy if unlocked if (access("/sepolicy.unlocked", F_OK) == 0) { patch_sepolicy("/sepolicy.unlocked", ROOTOVL "/sepolicy.unlocked"); } else { bool patch = access(SPLIT_PLAT_CIL, F_OK) != 0 && access("/sepolicy", F_OK) == 0; if (patch || !hijack_sepolicy()) { patch_sepolicy("/sepolicy", ROOTOVL "/sepolicy"); } } unlink("init-ld"); // Mount rootdir magic_mount(ROOTOVL); int dest = xopen(ROOTMNT, O_WRONLY | O_CREAT, 0); write(dest, magic_mount_list.data(), magic_mount_list.length()); close(dest); chdir("/"); } void RootFSInit::prepare() { prepare_data(); LOGD("Restoring /init\n"); rename(backup_init(), "/init"); } #define PRE_TMPSRC "/magisk" #define PRE_TMPDIR PRE_TMPSRC "/tmp" void MagiskInit::patch_rw_root() { mount_list.emplace_back("/data"); parse_config_file(); // Create hardlink mirror of /sbin to /root mkdir("/root", 0777); clone_attr("/sbin", "/root"); link_path("/sbin", "/root"); // Handle overlays load_overlay_rc("/overlay.d"); mv_path("/overlay.d", "/"); rm_rf("/data/overlay.d"); rm_rf("/.backup"); // Patch init.rc patch_rc_scripts("/", "/sbin", true); bool treble; { auto init = mmap_data("/init"); treble = init.contains(SPLIT_PLAT_CIL); } xmkdir(PRE_TMPSRC, 0); xmount("tmpfs", PRE_TMPSRC, "tmpfs", 0, "mode=755"); xmkdir(PRE_TMPDIR, 0); setup_tmp(PRE_TMPDIR); chdir(PRE_TMPDIR); // Extract overlay archives extract_files(true); bool patch = !treble && access("/sepolicy", F_OK) == 0; if (patch || !hijack_sepolicy()) { patch_sepolicy("/sepolicy", "/sepolicy"); } unlink("init-ld"); chdir("/"); // Dump magiskinit as magisk cp_afc(REDIR_PATH, "/sbin/magisk"); } int magisk_proxy_main(int argc, char *argv[]) { rust::setup_klog(); LOGD("%s\n", __FUNCTION__); // Mount rootfs as rw to do post-init rootfs patches xmount(nullptr, "/", nullptr, MS_REMOUNT, nullptr); unlink("/sbin/magisk"); // Move tmpfs to /sbin // make parent private before MS_MOVE xmount(nullptr, PRE_TMPSRC, nullptr, MS_PRIVATE, nullptr); xmount(PRE_TMPDIR, "/sbin", nullptr, MS_MOVE, nullptr); xumount2(PRE_TMPSRC, MNT_DETACH); rmdir(PRE_TMPDIR); rmdir(PRE_TMPSRC); // Create symlinks pointing back to /root recreate_sbin("/root", false); // Tell magiskd to remount rootfs setenv("REMOUNT_ROOT", "1", 1); execve("/sbin/magisk", argv, environ); return 1; }
14,410
C++
.cpp
374
30.112299
121
0.553211
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
33
getinfo.cpp
topjohnwu_Magisk/native/src/init/getinfo.cpp
#include <sys/sysmacros.h> #include <sys/types.h> #include <sys/stat.h> #include <linux/input.h> #include <fcntl.h> #include <vector> #include <base.hpp> #include "init.hpp" using namespace std; vector<string> mount_list; template<char... cs> using chars = integer_sequence<char, cs...>; // If quoted, parsing ends when we find char in [breaks] // If not quoted, parsing ends when we find char in [breaks] + [escapes] template<char... escapes, char... breaks> static string extract_quoted_str_until(chars<escapes...>, chars<breaks...>, string_view str, size_t &pos, bool &quoted) { string result; char match_array[] = {escapes..., breaks..., '"'}; string_view match(match_array, std::size(match_array)); for (size_t cur = pos;; ++cur) { cur = str.find_first_of(match, cur); if (cur == string_view::npos || ((str[cur] == breaks) || ...) || (!quoted && ((str[cur] == escapes) || ...))) { result.append(str.substr(pos, cur - pos)); pos = cur; return result; } if (str[cur] == '"') { quoted = !quoted; result.append(str.substr(pos, cur - pos)); pos = cur + 1; } } } // Parse string into key value pairs. // The string format: [delim][key][padding][eq][padding][value][delim] template<char delim, char eq, char... padding> static kv_pairs parse_impl(chars<padding...>, string_view str) { kv_pairs kv; char skip_array[] = {eq, padding...}; string_view skip(skip_array, std::size(skip_array)); bool quoted = false; for (size_t pos = 0u; pos < str.size(); pos = str.find_first_not_of(delim, pos)) { auto key = extract_quoted_str_until( chars<padding..., delim>{}, chars<eq>{}, str, pos, quoted); pos = str.find_first_not_of(skip, pos); if (pos == string_view::npos || str[pos] == delim) { kv.emplace_back(key, ""); continue; } auto value = extract_quoted_str_until(chars<delim>{}, chars<>{}, str, pos, quoted); kv.emplace_back(key, value); } return kv; } static kv_pairs parse_cmdline(string_view str) { return parse_impl<' ', '='>(chars<>{}, str); } static kv_pairs parse_bootconfig(string_view str) { return parse_impl<'\n', '='>(chars<' '>{}, str); } static kv_pairs parse_partition_map(std::string_view str) { return parse_impl<';', ','>(chars<>{}, str); } #define test_bit(bit, array) (array[bit / 8] & (1 << (bit % 8))) static bool check_key_combo() { LOGD("Running in recovery mode, waiting for key...\n"); uint8_t bitmask[(KEY_MAX + 1) / 8]; vector<int> events; constexpr const char *name = "/event"; for (int minor = 64; minor < 96; ++minor) { if (xmknod(name, S_IFCHR | 0444, makedev(13, minor))) continue; int fd = open(name, O_RDONLY | O_CLOEXEC); unlink(name); if (fd < 0) continue; memset(bitmask, 0, sizeof(bitmask)); ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(bitmask)), bitmask); if (test_bit(KEY_VOLUMEUP, bitmask)) events.push_back(fd); else close(fd); } if (events.empty()) return false; run_finally fin([&] { for_each(events.begin(), events.end(), close); }); // Return true if volume up key is held for more than 3 seconds int count = 0; for (int i = 0; i < 500; ++i) { for (const int &fd : events) { memset(bitmask, 0, sizeof(bitmask)); ioctl(fd, EVIOCGKEY(sizeof(bitmask)), bitmask); if (test_bit(KEY_VOLUMEUP, bitmask)) { count++; break; } } if (count >= 300) { LOGD("KEY_VOLUMEUP detected: disable system-as-root\n"); return true; } // Check every 10ms usleep(10000); } return false; } void BootConfig::set(const kv_pairs &kv) { for (const auto &[key, value] : kv) { if (key == "androidboot.slot_suffix") { // Many Amlogic devices are A-only but have slot_suffix... if (value == "normal") { LOGW("Skip invalid androidboot.slot_suffix=[normal]\n"); continue; } strscpy(slot, value.data(), sizeof(slot)); } else if (key == "androidboot.slot") { slot[0] = '_'; strscpy(slot + 1, value.data(), sizeof(slot) - 1); } else if (key == "skip_initramfs") { skip_initramfs = true; } else if (key == "androidboot.force_normal_boot") { force_normal_boot = !value.empty() && value[0] == '1'; } else if (key == "rootwait") { rootwait = true; } else if (key == "androidboot.android_dt_dir") { strscpy(dt_dir, value.data(), sizeof(dt_dir)); } else if (key == "androidboot.hardware") { strscpy(hardware, value.data(), sizeof(hardware)); } else if (key == "androidboot.hardware.platform") { strscpy(hardware_plat, value.data(), sizeof(hardware_plat)); } else if (key == "androidboot.fstab_suffix") { strscpy(fstab_suffix, value.data(), sizeof(fstab_suffix)); } else if (key == "qemu") { emulator = true; } } } void BootConfig::print() { LOGD("skip_initramfs=[%d]\n", skip_initramfs); LOGD("force_normal_boot=[%d]\n", force_normal_boot); LOGD("rootwait=[%d]\n", rootwait); LOGD("slot=[%s]\n", slot); LOGD("dt_dir=[%s]\n", dt_dir); LOGD("fstab_suffix=[%s]\n", fstab_suffix); LOGD("hardware=[%s]\n", hardware); LOGD("hardware.platform=[%s]\n", hardware_plat); LOGD("emulator=[%d]\n", emulator); } #define read_dt(name, key) \ ssprintf(file_name, sizeof(file_name), "%s/" name, config->dt_dir); \ if (access(file_name, R_OK) == 0) { \ string data = full_read(file_name); \ if (!data.empty()) { \ data.pop_back(); \ strscpy(config->key, data.data(), sizeof(config->key)); \ } \ } void load_kernel_info(BootConfig *config) { // Get kernel data using procfs and sysfs xmkdir("/proc", 0755); xmount("proc", "/proc", "proc", 0, nullptr); xmkdir("/sys", 0755); xmount("sysfs", "/sys", "sysfs", 0, nullptr); mount_list.emplace_back("/proc"); mount_list.emplace_back("/sys"); // Log to kernel rust::setup_klog(); config->set(parse_cmdline(full_read("/proc/cmdline"))); config->set(parse_bootconfig(full_read("/proc/bootconfig"))); parse_prop_file("/.backup/.magisk", [=](auto key, auto value) -> bool { if (key == "RECOVERYMODE" && value == "true") { config->skip_initramfs = config->emulator || !check_key_combo(); return false; } return true; }); if (config->dt_dir[0] == '\0') strscpy(config->dt_dir, DEFAULT_DT_DIR, sizeof(config->dt_dir)); char file_name[128]; read_dt("fstab_suffix", fstab_suffix) read_dt("hardware", hardware) read_dt("hardware.platform", hardware_plat) LOGD("Device config:\n"); config->print(); } // `androidboot.partition_map` allows associating a partition name for a raw block device // through a comma separated and semicolon deliminated list. For example, // `androidboot.partition_map=vdb,metadata;vdc,userdata` maps `vdb` to `metadata` and `vdc` to // `userdata`. // https://android.googlesource.com/platform/system/core/+/refs/heads/android13-release/init/devices.cpp#191 kv_pairs load_partition_map() { const string_view kPartitionMapKey = "androidboot.partition_map"; for (const auto &[key, value] : parse_cmdline(full_read("/proc/cmdline"))) { if (key == kPartitionMapKey) return parse_partition_map(value); } for (const auto &[key, value] : parse_bootconfig(full_read("/proc/bootconfig"))) { if (key == kPartitionMapKey) return parse_partition_map(value); } return {}; } bool check_two_stage() { if (access("/first_stage_ramdisk", F_OK) == 0) return true; if (access("/second_stage_resources", F_OK) == 0) return true; if (access("/system/bin/init", F_OK) == 0) return true; // If we still have no indication, parse the original init and see what's up mmap_data init(backup_init()); return init.contains("selinux_setup"); } void unxz_init(const char *init_xz, const char *init) { LOGD("unxz %s -> %s\n", init_xz, init); int fd = xopen(init, O_WRONLY | O_CREAT, 0777); fd_stream ch(fd); unxz(ch, mmap_data{init_xz}); close(fd); clone_attr(init_xz, init); unlink(init_xz); } const char *backup_init() { if (access("/.backup/init.xz", F_OK) == 0) unxz_init("/.backup/init.xz", "/.backup/init"); return "/.backup/init"; }
9,085
C++
.cpp
229
33.008734
108
0.568823
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
34
logging.cpp
topjohnwu_Magisk/native/src/base/logging.cpp
#include <cstdio> #include <cstdlib> #include <android/log.h> #include <flags.h> #include <base.hpp> using namespace std; #ifndef __call_bypassing_fortify #define __call_bypassing_fortify(fn) (&fn) #endif #undef vsnprintf static int fmt_and_log_with_rs(LogLevel level, const char *fmt, va_list ap) { constexpr int sz = 4096; char buf[sz]; buf[0] = '\0'; // Fortify logs when a fatal error occurs. Do not run through fortify again int len = std::min(__call_bypassing_fortify(vsnprintf)(buf, sz, fmt, ap), sz - 1); log_with_rs(level, rust::Utf8CStr(buf, len + 1)); return len; } // Used to override external C library logging extern "C" int magisk_log_print(int prio, const char *tag, const char *fmt, ...) { LogLevel level; switch (prio) { case ANDROID_LOG_DEBUG: level = LogLevel::Debug; break; case ANDROID_LOG_INFO: level = LogLevel::Info; break; case ANDROID_LOG_WARN: level = LogLevel::Warn; break; case ANDROID_LOG_ERROR: level = LogLevel::ErrorCxx; break; default: return 0; } char fmt_buf[4096]; auto len = strscpy(fmt_buf, tag, sizeof(fmt_buf) - 1); // Prevent format specifications in the tag std::replace(fmt_buf, fmt_buf + len, '%', '_'); len = ssprintf(fmt_buf + len, sizeof(fmt_buf) - len - 1, ": %s", fmt) + len; // Ensure the fmt string always ends with newline if (fmt_buf[len - 1] != '\n') { fmt_buf[len] = '\n'; fmt_buf[len + 1] = '\0'; } va_list argv; va_start(argv, fmt); int ret = fmt_and_log_with_rs(level, fmt_buf, argv); va_end(argv); return ret; } #define LOG_BODY(level) \ va_list argv; \ va_start(argv, fmt); \ fmt_and_log_with_rs(LogLevel::level, fmt, argv); \ va_end(argv); \ // LTO will optimize out the NOP function #if MAGISK_DEBUG void LOGD(const char *fmt, ...) { LOG_BODY(Debug) } #else void LOGD(const char *fmt, ...) {} #endif void LOGI(const char *fmt, ...) { LOG_BODY(Info) } void LOGW(const char *fmt, ...) { LOG_BODY(Warn) } void LOGE(const char *fmt, ...) { LOG_BODY(ErrorCxx) } // Export raw symbol to fortify compat extern "C" void __vloge(const char* fmt, va_list ap) { fmt_and_log_with_rs(LogLevel::ErrorCxx, fmt, ap); }
2,316
C++
.cpp
72
27.972222
86
0.626231
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35
stream.cpp
topjohnwu_Magisk/native/src/base/stream.cpp
#include <unistd.h> #include <cstddef> #include <base.hpp> #include <stream.hpp> using namespace std; static int strm_read(void *v, char *buf, int len) { auto strm = static_cast<stream *>(v); return strm->read(buf, len); } static int strm_write(void *v, const char *buf, int len) { auto strm = static_cast<stream *>(v); if (!strm->write(buf, len)) return -1; return len; } static int strm_close(void *v) { auto strm = static_cast<stream *>(v); delete strm; return 0; } sFILE make_stream_fp(stream_ptr &&strm) { auto fp = make_file(funopen(strm.release(), strm_read, strm_write, nullptr, strm_close)); setbuf(fp.get(), nullptr); return fp; } ssize_t in_stream::readFully(void *buf, size_t len) { size_t read_sz = 0; ssize_t ret; do { ret = read((byte *) buf + read_sz, len - read_sz); if (ret < 0) { if (errno == EINTR) continue; return ret; } read_sz += ret; } while (read_sz != len && ret != 0); return read_sz; } bool filter_out_stream::write(const void *buf, size_t len) { return base->write(buf, len); } bool chunk_out_stream::write(const void *_in, size_t len) { auto in = static_cast<const uint8_t *>(_in); while (len) { if (buf_off + len >= chunk_sz) { // Enough input for a chunk const uint8_t *src; if (buf_off) { src = data.buf(); auto copy = chunk_sz - buf_off; memcpy(data.buf() + buf_off, in, copy); in += copy; len -= copy; buf_off = 0; } else { src = in; in += chunk_sz; len -= chunk_sz; } if (!write_chunk(src, chunk_sz, false)) return false; } else { // Buffer internally memcpy(data.buf() + buf_off, in, len); buf_off += len; break; } } return true; } bool chunk_out_stream::write_chunk(const void *buf, size_t len, bool) { return base->write(buf, len); } void chunk_out_stream::finalize() { if (buf_off) { if (!write_chunk(data.buf(), buf_off, true)) { LOGE("Error in finalize, file truncated\n"); } buf_off = 0; } } ssize_t byte_stream::read(void *buf, size_t len) { len = std::min((size_t) len, _data._sz- _pos); memcpy(buf, _data.buf() + _pos, len); _pos += len; return len; } bool byte_stream::write(const void *buf, size_t len) { resize(_pos + len); memcpy(_data.buf() + _pos, buf, len); _pos += len; _data._sz= std::max(_data.sz(), _pos); return true; } void byte_stream::resize(size_t new_sz, bool zero) { bool resize = false; size_t old_cap = _cap; while (new_sz > _cap) { _cap = _cap ? (_cap << 1) - (_cap >> 1) : 1 << 12; resize = true; } if (resize) { _data._buf = static_cast<uint8_t *>(::realloc(_data._buf, _cap)); if (zero) memset(_data.buf() + old_cap, 0, _cap - old_cap); } } ssize_t rust_vec_stream::read(void *buf, size_t len) { len = std::min<size_t>(len, _data.size() - _pos); memcpy(buf, _data.data() + _pos, len); _pos += len; return len; } bool rust_vec_stream::write(const void *buf, size_t len) { ensure_size(_pos + len); memcpy(_data.data() + _pos, buf, len); _pos += len; return true; } void rust_vec_stream::ensure_size(size_t sz, bool zero) { size_t old_sz = _data.size(); if (sz > old_sz) { resize_vec(_data, sz); if (zero) memset(_data.data() + old_sz, 0, sz - old_sz); } } ssize_t fd_stream::read(void *buf, size_t len) { return ::read(fd, buf, len); } ssize_t fd_stream::do_write(const void *buf, size_t len) { return ::write(fd, buf, len); } bool file_stream::write(const void *buf, size_t len) { size_t write_sz = 0; ssize_t ret; do { ret = do_write((byte *) buf + write_sz, len - write_sz); if (ret < 0) { if (errno == EINTR) continue; return false; } write_sz += ret; } while (write_sz != len && ret != 0); return true; } #if ENABLE_IOV ssize_t in_stream::readv(const iovec *iov, int iovcnt) { size_t read_sz = 0; for (int i = 0; i < iovcnt; ++i) { auto ret = readFully(iov[i].iov_base, iov[i].iov_len); if (ret < 0) return ret; read_sz += ret; } return read_sz; } ssize_t out_stream::writev(const iovec *iov, int iovcnt) { size_t write_sz = 0; for (int i = 0; i < iovcnt; ++i) { if (!write(iov[i].iov_base, iov[i].iov_len)) return write_sz; write_sz += iov[i].iov_len; } return write_sz; } ssize_t fd_stream::readv(const iovec *iov, int iovcnt) { return ::readv(fd, iov, iovcnt); } ssize_t fd_stream::writev(const iovec *iov, int iovcnt) { return ::writev(fd, iov, iovcnt); } #endif // ENABLE_IOV
5,077
C++
.cpp
175
22.742857
93
0.539787
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
36
new.cpp
topjohnwu_Magisk/native/src/base/new.cpp
#include <new> #include <cstdlib> /* Override libc++ new implementation * to optimize final build size */ void* operator new(std::size_t s) { return std::malloc(s); } void* operator new[](std::size_t s) { return std::malloc(s); } void operator delete(void *p) { std::free(p); } void operator delete[](void *p) { std::free(p); } void* operator new(std::size_t s, const std::nothrow_t&) noexcept { return std::malloc(s); } void* operator new[](std::size_t s, const std::nothrow_t&) noexcept { return std::malloc(s); } void operator delete(void *p, const std::nothrow_t&) noexcept { std::free(p); } void operator delete[](void *p, const std::nothrow_t&) noexcept { std::free(p); }
685
C++
.cpp
12
55.833333
94
0.681073
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
37
files.cpp
topjohnwu_Magisk/native/src/base/files.cpp
#include <sys/mman.h> #include <sys/sendfile.h> #include <sys/sysmacros.h> #include <linux/fs.h> #include <fcntl.h> #include <unistd.h> #include <libgen.h> #include <base.hpp> using namespace std; int fd_pathat(int dirfd, const char *name, char *path, size_t size) { if (fd_path(dirfd, byte_data(path, size)) < 0) return -1; auto len = strlen(path); path[len] = '/'; strscpy(path + len + 1, name, size - len - 1); return 0; } void full_read(int fd, string &str) { char buf[4096]; for (ssize_t len; (len = xread(fd, buf, sizeof(buf))) > 0;) str.insert(str.end(), buf, buf + len); } void full_read(const char *filename, string &str) { if (int fd = xopen(filename, O_RDONLY | O_CLOEXEC); fd >= 0) { full_read(fd, str); close(fd); } } string full_read(int fd) { string str; full_read(fd, str); return str; } string full_read(const char *filename) { string str; full_read(filename, str); return str; } void write_zero(int fd, size_t size) { char buf[4096] = {0}; size_t len; while (size > 0) { len = sizeof(buf) > size ? size : sizeof(buf); write(fd, buf, len); size -= len; } } void file_readline(bool trim, FILE *fp, const function<bool(string_view)> &fn) { size_t len = 1024; char *buf = (char *) malloc(len); char *start; ssize_t read; while ((read = getline(&buf, &len, fp)) >= 0) { start = buf; if (trim) { while (read && "\n\r "sv.find(buf[read - 1]) != string::npos) --read; buf[read] = '\0'; while (*start == ' ') ++start; } if (!fn(start)) break; } free(buf); } void file_readline(bool trim, const char *file, const function<bool(string_view)> &fn) { if (auto fp = open_file(file, "re")) file_readline(trim, fp.get(), fn); } void file_readline(const char *file, const function<bool(string_view)> &fn) { file_readline(false, file, fn); } void parse_prop_file(FILE *fp, const function<bool(string_view, string_view)> &fn) { file_readline(true, fp, [&](string_view line_view) -> bool { char *line = (char *) line_view.data(); if (line[0] == '#') return true; char *eql = strchr(line, '='); if (eql == nullptr || eql == line) return true; *eql = '\0'; return fn(line, eql + 1); }); } void parse_prop_file(const char *file, const function<bool(string_view, string_view)> &fn) { if (auto fp = open_file(file, "re")) parse_prop_file(fp.get(), fn); } sDIR make_dir(DIR *dp) { return sDIR(dp, [](DIR *dp){ return dp ? closedir(dp) : 1; }); } sFILE make_file(FILE *fp) { return sFILE(fp, [](FILE *fp){ return fp ? fclose(fp) : 1; }); } mmap_data::mmap_data(const char *name, bool rw) { auto slice = rust::map_file(name, rw); if (!slice.empty()) { _buf = slice.data(); _sz = slice.size(); } } mmap_data::mmap_data(int dirfd, const char *name, bool rw) { auto slice = rust::map_file_at(dirfd, name, rw); if (!slice.empty()) { _buf = slice.data(); _sz = slice.size(); } } mmap_data::mmap_data(int fd, size_t sz, bool rw) { auto slice = rust::map_fd(fd, sz, rw); if (!slice.empty()) { _buf = slice.data(); _sz = slice.size(); } } mmap_data::~mmap_data() { if (_buf) munmap(_buf, _sz); } string resolve_preinit_dir(const char *base_dir) { string dir = base_dir; if (access((dir + "/unencrypted").data(), F_OK) == 0) { dir += "/unencrypted/magisk"; } else if (access((dir + "/adb").data(), F_OK) == 0) { dir += "/adb/modules"; } else { dir += "/magisk"; } return dir; }
3,811
C++
.cpp
131
23.877863
92
0.560109
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
38
misc.cpp
topjohnwu_Magisk/native/src/base/misc.cpp
#include <sys/types.h> #include <sys/wait.h> #include <sys/prctl.h> #include <sys/sysmacros.h> #include <fcntl.h> #include <pwd.h> #include <unistd.h> #include <syscall.h> #include <random> #include <string> #include <base.hpp> using namespace std; bool byte_view::contains(byte_view pattern) const { return _buf != nullptr && memmem(_buf, _sz, pattern._buf, pattern._sz) != nullptr; } bool byte_view::equals(byte_view o) const { return _sz == o._sz && memcmp(_buf, o._buf, _sz) == 0; } heap_data byte_view::clone() const { heap_data copy(_sz); memcpy(copy._buf, _buf, _sz); return copy; } void byte_data::swap(byte_data &o) { std::swap(_buf, o._buf); std::swap(_sz, o._sz); } rust::Vec<size_t> byte_data::patch(byte_view from, byte_view to) { rust::Vec<size_t> v; if (_buf == nullptr) return v; auto p = _buf; auto eof = _buf + _sz; while (p < eof) { p = static_cast<uint8_t *>(memmem(p, eof - p, from.buf(), from.sz())); if (p == nullptr) return v; memset(p, 0, from.sz()); memcpy(p, to.buf(), to.sz()); v.push_back(p - _buf); p += from.sz(); } return v; } rust::Vec<size_t> mut_u8_patch( rust::Slice<uint8_t> buf, rust::Slice<const uint8_t> from, rust::Slice<const uint8_t> to) { byte_data data(buf); return data.patch(from, to); } int fork_dont_care() { if (int pid = xfork()) { waitpid(pid, nullptr, 0); return pid; } else if (xfork()) { exit(0); } return 0; } int fork_no_orphan() { int pid = xfork(); if (pid) return pid; prctl(PR_SET_PDEATHSIG, SIGKILL); if (getppid() == 1) exit(1); return 0; } int exec_command(exec_t &exec) { auto pipefd = array<int, 2>{-1, -1}; int outfd = -1; if (exec.fd == -1) { if (xpipe2(pipefd, O_CLOEXEC) == -1) return -1; outfd = pipefd[1]; } else if (exec.fd >= 0) { outfd = exec.fd; } int pid = exec.fork(); if (pid < 0) { close(pipefd[0]); close(pipefd[1]); return -1; } else if (pid) { if (exec.fd == -1) { exec.fd = pipefd[0]; close(pipefd[1]); } return pid; } // Unblock all signals sigset_t set; sigfillset(&set); pthread_sigmask(SIG_UNBLOCK, &set, nullptr); if (outfd >= 0) { xdup2(outfd, STDOUT_FILENO); if (exec.err) xdup2(outfd, STDERR_FILENO); close(outfd); } // Call the pre-exec callback if (exec.pre_exec) exec.pre_exec(); execve(exec.argv[0], (char **) exec.argv, environ); PLOGE("execve %s", exec.argv[0]); exit(-1); } int exec_command_sync(exec_t &exec) { int pid = exec_command(exec); if (pid < 0) return -1; int status; waitpid(pid, &status, 0); return WEXITSTATUS(status); } int new_daemon_thread(thread_entry entry, void *arg) { pthread_t thread; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); errno = pthread_create(&thread, &attr, entry, arg); if (errno) { PLOGE("pthread_create"); } return errno; } static char *argv0; static size_t name_len; void init_argv0(int argc, char **argv) { argv0 = argv[0]; name_len = (argv[argc - 1] - argv[0]) + strlen(argv[argc - 1]) + 1; } void set_nice_name(const char *name) { memset(argv0, 0, name_len); strscpy(argv0, name, name_len); prctl(PR_SET_NAME, name); } template<typename T, int base> static T parse_num(string_view s) { T val = 0; for (char c : s) { if (isdigit(c)) { c -= '0'; } else if (base > 10 && isalpha(c)) { c -= isupper(c) ? 'A' - 10 : 'a' - 10; } else { return -1; } if (c >= base) { return -1; } val *= base; val += c; } return val; } /* * Bionic's atoi runs through strtol(). * Use our own implementation for faster conversion. */ int parse_int(string_view s) { return parse_num<int, 10>(s); } uint64_t parse_uint64_hex(string_view s) { return parse_num<uint64_t, 16>(s); } uint32_t binary_gcd(uint32_t u, uint32_t v) { if (u == 0) return v; if (v == 0) return u; auto shift = __builtin_ctz(u | v); u >>= __builtin_ctz(u); do { v >>= __builtin_ctz(v); if (u > v) { auto t = v; v = u; u = t; } v -= u; } while (v != 0); return u << shift; } int switch_mnt_ns(int pid) { int ret = -1; int fd = syscall(__NR_pidfd_open, pid, 0); if (fd > 0) { ret = setns(fd, CLONE_NEWNS); close(fd); } if (ret < 0) { char mnt[32]; ssprintf(mnt, sizeof(mnt), "/proc/%d/ns/mnt", pid); fd = open(mnt, O_RDONLY); if (fd < 0) return 1; // Maybe process died.. // Switch to its namespace ret = xsetns(fd, 0); close(fd); } return ret; } string &replace_all(string &str, string_view from, string_view to) { size_t pos = 0; while((pos = str.find(from, pos)) != string::npos) { str.replace(pos, from.length(), to); pos += to.length(); } return str; } template <typename T> static auto split_impl(string_view s, string_view delims) { vector<T> result; size_t base = 0; size_t found; while (true) { found = s.find_first_of(delims, base); result.emplace_back(s.substr(base, found - base)); if (found == string::npos) break; base = found + 1; } return result; } vector<string> split(string_view s, string_view delims) { return split_impl<string>(s, delims); } vector<string_view> split_view(string_view s, string_view delims) { return split_impl<string_view>(s, delims); } #undef vsnprintf int vssprintf(char *dest, size_t size, const char *fmt, va_list ap) { if (size > 0) { *dest = 0; return std::min(vsnprintf(dest, size, fmt, ap), (int) size - 1); } return -1; } int ssprintf(char *dest, size_t size, const char *fmt, ...) { va_list va; va_start(va, fmt); int r = vssprintf(dest, size, fmt, va); va_end(va); return r; } #undef strlcpy size_t strscpy(char *dest, const char *src, size_t size) { return std::min(strlcpy(dest, src, size), size - 1); } extern "C" void cxx$utf8str$new(rust::Utf8CStr *self, const void *s, size_t len); extern "C" const char *cxx$utf8str$ptr(const rust::Utf8CStr *self); extern "C" size_t cxx$utf8str$len(const rust::Utf8CStr *self); rust::Utf8CStr::Utf8CStr(const char *s, size_t len) { cxx$utf8str$new(this, s, len); } const char *rust::Utf8CStr::data() const { return cxx$utf8str$ptr(this); } size_t rust::Utf8CStr::length() const { return cxx$utf8str$len(this); }
6,944
C++
.cpp
260
21.488462
86
0.568763
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
39
sepolicy.cpp
topjohnwu_Magisk/native/src/sepolicy/sepolicy.cpp
#include <base.hpp> #include "policy.hpp" using namespace std; // Invert is adding rules for auditdeny; in other cases, invert is removing rules #define strip_av(effect, invert) ((effect == AVTAB_AUDITDENY) == !invert) // libsepol internal APIs __BEGIN_DECLS int policydb_index_decls(sepol_handle_t * handle, policydb_t * p); int avtab_hash(struct avtab_key *keyp, uint32_t mask); int type_set_expand(type_set_t * set, ebitmap_t * t, policydb_t * p, unsigned char alwaysexpand); int context_from_string( sepol_handle_t * handle, const policydb_t * policydb, context_struct_t ** cptr, const char *con_str, size_t con_str_len); int context_to_string( sepol_handle_t * handle, const policydb_t * policydb, const context_struct_t * context, char **result, size_t * result_len); __END_DECLS template <typename T> struct auto_cast_wrapper { auto_cast_wrapper(T *ptr) : ptr(ptr) {} template <typename U> operator U*() const { return static_cast<U*>(ptr); } private: T *ptr; }; template <typename T> static auto_cast_wrapper<T> auto_cast(T *p) { return auto_cast_wrapper<T>(p); } static auto hashtab_find(hashtab_t h, const_hashtab_key_t key) { return auto_cast(hashtab_search(h, key)); } template <class Node, class Func> static void list_for_each(Node *node_ptr, const Func &fn) { auto cur = node_ptr; while (cur) { auto next = cur->next; fn(cur); cur = next; } } template <class Node, class Func> static Node *list_find(Node *node_ptr, const Func &fn) { for (auto cur = node_ptr; cur; cur = cur->next) { if (fn(cur)) { return cur; } } return nullptr; } template <class Node, class Func> static void hash_for_each(Node **node_ptr, int n_slot, const Func &fn) { for (int i = 0; i < n_slot; ++i) { list_for_each(node_ptr[i], fn); } } template <class Func> static void hashtab_for_each(hashtab_t htab, const Func &fn) { hash_for_each(htab->htable, htab->size, fn); } template <class Func> static void avtab_for_each(avtab_t *avtab, const Func &fn) { hash_for_each(avtab->htable, avtab->nslot, fn); } template <class Func> static void for_each_attr(hashtab_t htab, const Func &fn) { hashtab_for_each(htab, [&](hashtab_ptr_t node) { auto type = static_cast<type_datum_t *>(node->datum); if (type->flavor == TYPE_ATTRIB) fn(type); }); } static int avtab_remove_node(avtab_t *h, avtab_ptr_t node) { if (!h || !h->htable) return SEPOL_ENOMEM; int hvalue = avtab_hash(&node->key, h->mask); avtab_ptr_t prev = nullptr; avtab_ptr_t cur = h->htable[hvalue]; while (cur) { if (cur == node) break; prev = cur; cur = cur->next; } if (cur == nullptr) return SEPOL_ENOENT; // Detach from link list if (prev) prev->next = node->next; else h->htable[hvalue] = node->next; h->nel--; // Free memory free(node->datum.xperms); free(node); return 0; } static bool is_redundant(avtab_ptr_t node) { switch (node->key.specified) { case AVTAB_AUDITDENY: return node->datum.data == ~0U; case AVTAB_XPERMS: return node->datum.xperms == nullptr; default: return node->datum.data == 0U; } } avtab_ptr_t sepol_impl::find_avtab_node(avtab_key_t *key, avtab_extended_perms_t *xperms) { avtab_ptr_t node; // AVTAB_XPERMS entries are not necessarily unique if (key->specified & AVTAB_XPERMS) { if (xperms == nullptr) return nullptr; node = avtab_search_node(&db->te_avtab, key); while (node) { if ((node->datum.xperms->specified == xperms->specified) && (node->datum.xperms->driver == xperms->driver)) { node = nullptr; break; } node = avtab_search_node_next(node, key->specified); } } else { node = avtab_search_node(&db->te_avtab, key); } return node; } avtab_ptr_t sepol_impl::insert_avtab_node(avtab_key_t *key) { avtab_datum_t avdatum{}; // AUDITDENY, aka DONTAUDIT, are &= assigned, versus |= for others. // Initialize the data accordingly. avdatum.data = key->specified == AVTAB_AUDITDENY ? ~0U : 0U; return avtab_insert_nonunique(&db->te_avtab, key, &avdatum); } avtab_ptr_t sepol_impl::get_avtab_node(avtab_key_t *key, avtab_extended_perms_t *xperms) { avtab_ptr_t node = find_avtab_node(key, xperms); if (!node) { node = insert_avtab_node(key); } return node; } void sepol_impl::add_rule(type_datum_t *src, type_datum_t *tgt, class_datum_t *cls, perm_datum_t *perm, int effect, bool invert) { if (src == nullptr) { if (strip_av(effect, invert)) { // Stripping av, have to go through all types for correct results hashtab_for_each(db->p_types.table, [&](hashtab_ptr_t node) { add_rule(auto_cast(node->datum), tgt, cls, perm, effect, invert); }); } else { // If we are not stripping av, go through all attributes instead of types for optimization for_each_attr(db->p_types.table, [&](type_datum_t *type) { add_rule(type, tgt, cls, perm, effect, invert); }); } } else if (tgt == nullptr) { if (strip_av(effect, invert)) { hashtab_for_each(db->p_types.table, [&](hashtab_ptr_t node) { add_rule(src, auto_cast(node->datum), cls, perm, effect, invert); }); } else { for_each_attr(db->p_types.table, [&](type_datum_t *type) { add_rule(src, type, cls, perm, effect, invert); }); } } else if (cls == nullptr) { hashtab_for_each(db->p_classes.table, [&](hashtab_ptr_t node) { add_rule(src, tgt, auto_cast(node->datum), perm, effect, invert); }); } else { avtab_key_t key; key.source_type = src->s.value; key.target_type = tgt->s.value; key.target_class = cls->s.value; key.specified = effect; avtab_ptr_t node = get_avtab_node(&key, nullptr); if (invert) { if (perm) node->datum.data &= ~(1U << (perm->s.value - 1)); else node->datum.data = 0U; } else { if (perm) node->datum.data |= 1U << (perm->s.value - 1); else node->datum.data = ~0U; } if (is_redundant(node)) avtab_remove_node(&db->te_avtab, node); } } bool sepol_impl::add_rule(const char *s, const char *t, const char *c, const char *p, int effect, bool invert) { type_datum_t *src = nullptr, *tgt = nullptr; class_datum_t *cls = nullptr; perm_datum_t *perm = nullptr; if (s) { src = hashtab_find(db->p_types.table, s); if (src == nullptr) { LOGW("source type %s does not exist\n", s); return false; } } if (t) { tgt = hashtab_find(db->p_types.table, t); if (tgt == nullptr) { LOGW("target type %s does not exist\n", t); return false; } } if (c) { cls = hashtab_find(db->p_classes.table, c); if (cls == nullptr) { LOGW("class %s does not exist\n", c); return false; } } if (p) { if (c == nullptr) { LOGW("No class is specified, cannot add perm [%s] \n", p); return false; } perm = hashtab_find(cls->permissions.table, p); if (perm == nullptr && cls->comdatum != nullptr) { perm = hashtab_find(cls->comdatum->permissions.table, p); } if (perm == nullptr) { LOGW("perm %s does not exist in class %s\n", p, c); return false; } } add_rule(src, tgt, cls, perm, effect, invert); return true; } #define ioctl_driver(x) (x>>8 & 0xFF) #define ioctl_func(x) (x & 0xFF) void sepol_impl::add_xperm_rule(type_datum_t *src, type_datum_t *tgt, class_datum_t *cls, const Xperm &p, int effect) { if (db->policyvers < POLICYDB_VERSION_XPERMS_IOCTL) { LOGW("policy version %u does not support ioctl extended permissions rules\n", db->policyvers); return; } if (src == nullptr) { for_each_attr(db->p_types.table, [&](type_datum_t *type) { add_xperm_rule(type, tgt, cls, p, effect); }); } else if (tgt == nullptr) { for_each_attr(db->p_types.table, [&](type_datum_t *type) { add_xperm_rule(src, type, cls, p, effect); }); } else if (cls == nullptr) { hashtab_for_each(db->p_classes.table, [&](hashtab_ptr_t node) { add_xperm_rule(src, tgt, auto_cast(node->datum), p, effect); }); } else { avtab_key_t key; key.source_type = src->s.value; key.target_type = tgt->s.value; key.target_class = cls->s.value; key.specified = effect; // Each key may contain 1 driver node and 256 function nodes avtab_ptr_t node_list[257] = { nullptr }; #define driver_node (node_list[256]) // Find all rules with key for (avtab_ptr_t node = avtab_search_node(&db->te_avtab, &key); node;) { if (node->datum.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) { driver_node = node; } else if (node->datum.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) { node_list[node->datum.xperms->driver] = node; } node = avtab_search_node_next(node, key.specified); } if (p.reset) { for (int i = 0; i <= 0xFF; ++i) { if (node_list[i]) { avtab_remove_node(&db->te_avtab, node_list[i]); node_list[i] = nullptr; } } if (driver_node) { memset(driver_node->datum.xperms->perms, 0, sizeof(avtab_extended_perms_t::perms)); } } auto new_driver_node = [&]() -> avtab_ptr_t { auto node = insert_avtab_node(&key); node->datum.xperms = auto_cast(calloc(1, sizeof(avtab_extended_perms_t))); node->datum.xperms->specified = AVTAB_XPERMS_IOCTLDRIVER; node->datum.xperms->driver = 0; return node; }; auto new_func_node = [&](uint8_t driver) -> avtab_ptr_t { auto node = insert_avtab_node(&key); node->datum.xperms = auto_cast(calloc(1, sizeof(avtab_extended_perms_t))); node->datum.xperms->specified = AVTAB_XPERMS_IOCTLFUNCTION; node->datum.xperms->driver = driver; return node; }; if (!p.reset) { if (ioctl_driver(p.low) != ioctl_driver(p.high)) { if (driver_node == nullptr) { driver_node = new_driver_node(); } for (int i = ioctl_driver(p.low); i <= ioctl_driver(p.high); ++i) { xperm_set(i, driver_node->datum.xperms->perms); } } else { uint8_t driver = ioctl_driver(p.low); auto node = node_list[driver]; if (node == nullptr) { node = new_func_node(driver); node_list[driver] = node; } for (int i = ioctl_func(p.low); i <= ioctl_func(p.high); ++i) { xperm_set(i, node->datum.xperms->perms); } } } else { if (driver_node == nullptr) { driver_node = new_driver_node(); } // Fill the driver perms memset(driver_node->datum.xperms->perms, ~0, sizeof(avtab_extended_perms_t::perms)); if (ioctl_driver(p.low) != ioctl_driver(p.high)) { for (int i = ioctl_driver(p.low); i <= ioctl_driver(p.high); ++i) { xperm_clear(i, driver_node->datum.xperms->perms); } } else { uint8_t driver = ioctl_driver(p.low); auto node = node_list[driver]; if (node == nullptr) { node = new_func_node(driver); // Fill the func perms memset(node->datum.xperms->perms, ~0, sizeof(avtab_extended_perms_t::perms)); node_list[driver] = node; } xperm_clear(driver, driver_node->datum.xperms->perms); for (int i = ioctl_func(p.low); i <= ioctl_func(p.high); ++i) { xperm_clear(i, node->datum.xperms->perms); } } } } } bool sepol_impl::add_xperm_rule(const char *s, const char *t, const char *c, const Xperm &p, int effect) { type_datum_t *src = nullptr, *tgt = nullptr; class_datum_t *cls = nullptr; if (s) { src = hashtab_find(db->p_types.table, s); if (src == nullptr) { LOGW("source type %s does not exist\n", s); return false; } } if (t) { tgt = hashtab_find(db->p_types.table, t); if (tgt == nullptr) { LOGW("target type %s does not exist\n", t); return false; } } if (c) { cls = hashtab_find(db->p_classes.table, c); if (cls == nullptr) { LOGW("class %s does not exist\n", c); return false; } } add_xperm_rule(src, tgt, cls, p, effect); return true; } bool sepol_impl::add_type_rule(const char *s, const char *t, const char *c, const char *d, int effect) { type_datum_t *src, *tgt, *def; class_datum_t *cls; src = hashtab_find(db->p_types.table, s); if (src == nullptr) { LOGW("source type %s does not exist\n", s); return false; } tgt = hashtab_find(db->p_types.table, t); if (tgt == nullptr) { LOGW("target type %s does not exist\n", t); return false; } cls = hashtab_find(db->p_classes.table, c); if (cls == nullptr) { LOGW("class %s does not exist\n", c); return false; } def = hashtab_find(db->p_types.table, d); if (def == nullptr) { LOGW("default type %s does not exist\n", d); return false; } avtab_key_t key; key.source_type = src->s.value; key.target_type = tgt->s.value; key.target_class = cls->s.value; key.specified = effect; avtab_ptr_t node = get_avtab_node(&key, nullptr); node->datum.data = def->s.value; return true; } bool sepol_impl::add_filename_trans(const char *s, const char *t, const char *c, const char *d, const char *o) { type_datum_t *src, *tgt, *def; class_datum_t *cls; src = hashtab_find(db->p_types.table, s); if (src == nullptr) { LOGW("source type %s does not exist\n", s); return false; } tgt = hashtab_find(db->p_types.table, t); if (tgt == nullptr) { LOGW("target type %s does not exist\n", t); return false; } cls = hashtab_find(db->p_classes.table, c); if (cls == nullptr) { LOGW("class %s does not exist\n", c); return false; } def = hashtab_find(db->p_types.table, d); if (def == nullptr) { LOGW("default type %s does not exist\n", d); return false; } filename_trans_key_t key; key.ttype = tgt->s.value; key.tclass = cls->s.value; key.name = (char *) o; filename_trans_datum_t *trans = hashtab_find(db->filename_trans, (hashtab_key_t) &key); filename_trans_datum_t *last = nullptr; while (trans) { if (ebitmap_get_bit(&trans->stypes, src->s.value - 1)) { // Duplicate, overwrite existing data and return trans->otype = def->s.value; return true; } if (trans->otype == def->s.value) break; last = trans; trans = trans->next; } if (trans == nullptr) { trans = auto_cast(calloc(sizeof(*trans), 1)); ebitmap_init(&trans->stypes); trans->otype = def->s.value; } if (last) { last->next = trans; } else { filename_trans_key_t *new_key = auto_cast(malloc(sizeof(*new_key))); memcpy(new_key, &key, sizeof(key)); new_key->name = strdup(key.name); hashtab_insert(db->filename_trans, (hashtab_key_t) new_key, trans); } db->filename_trans_count++; return ebitmap_set_bit(&trans->stypes, src->s.value - 1, 1) == 0; } bool sepol_impl::add_genfscon(const char *fs_name, const char *path, const char *context) { // First try to create context context_struct_t *ctx; if (context_from_string(nullptr, db, &ctx, context, strlen(context))) { LOGW("Failed to create context from string [%s]\n", context); return false; } // Find genfs node genfs_t *fs = list_find(db->genfs, [&](genfs_t *n) { return strcmp(n->fstype, fs_name) == 0; }); if (fs == nullptr) { fs = auto_cast(calloc(sizeof(*fs), 1)); fs->fstype = strdup(fs_name); fs->next = db->genfs; db->genfs = fs; } // Find context node ocontext_t *o_ctx = list_find(fs->head, [&](ocontext_t *n) { return strcmp(n->u.name, path) == 0; }); if (o_ctx == nullptr) { o_ctx = auto_cast(calloc(sizeof(*o_ctx), 1)); o_ctx->u.name = strdup(path); o_ctx->next = fs->head; fs->head = o_ctx; } memset(o_ctx->context, 0, sizeof(o_ctx->context)); memcpy(&o_ctx->context[0], ctx, sizeof(*ctx)); free(ctx); return true; } bool sepol_impl::add_type(const char *type_name, uint32_t flavor) { type_datum_t *type = hashtab_find(db->p_types.table, type_name); if (type) { LOGW("Type %s already exists\n", type_name); return true; } type = auto_cast(malloc(sizeof(type_datum_t))); type_datum_init(type); type->primary = 1; type->flavor = flavor; uint32_t value = 0; if (symtab_insert(db, SYM_TYPES, strdup(type_name), type, SCOPE_DECL, 1, &value)) return false; type->s.value = value; ebitmap_set_bit(&db->global->branch_list->declared.p_types_scope, value - 1, 1); auto new_size = sizeof(ebitmap_t) * db->p_types.nprim; db->type_attr_map = auto_cast(realloc(db->type_attr_map, new_size)); db->attr_type_map = auto_cast(realloc(db->attr_type_map, new_size)); ebitmap_init(&db->type_attr_map[value - 1]); ebitmap_init(&db->attr_type_map[value - 1]); ebitmap_set_bit(&db->type_attr_map[value - 1], value - 1, 1); // Re-index stuffs if (policydb_index_decls(nullptr, db) || policydb_index_classes(db) || policydb_index_others(nullptr, db, 0)) return false; // Add the type to all roles for (int i = 0; i < db->p_roles.nprim; ++i) { // Not sure all those three calls are needed ebitmap_set_bit(&db->role_val_to_struct[i]->types.negset, value - 1, 0); ebitmap_set_bit(&db->role_val_to_struct[i]->types.types, value - 1, 1); type_set_expand(&db->role_val_to_struct[i]->types, &db->role_val_to_struct[i]->cache, db, 0); } return true; } bool sepol_impl::set_type_state(const char *type_name, bool permissive) { type_datum_t *type; if (type_name == nullptr) { hashtab_for_each(db->p_types.table, [&](hashtab_ptr_t node) { type = auto_cast(node->datum); if (ebitmap_set_bit(&db->permissive_map, type->s.value, permissive)) LOGW("Could not set bit in permissive map\n"); }); } else { type = hashtab_find(db->p_types.table, type_name); if (type == nullptr) { LOGW("type %s does not exist\n", type_name); return false; } if (ebitmap_set_bit(&db->permissive_map, type->s.value, permissive)) { LOGW("Could not set bit in permissive map\n"); return false; } } return true; } void sepol_impl::add_typeattribute(type_datum_t *type, type_datum_t *attr) { ebitmap_set_bit(&db->type_attr_map[type->s.value - 1], attr->s.value - 1, 1); ebitmap_set_bit(&db->attr_type_map[attr->s.value - 1], type->s.value - 1, 1); hashtab_for_each(db->p_classes.table, [&](hashtab_ptr_t node){ auto cls = static_cast<class_datum_t *>(node->datum); list_for_each(cls->constraints, [&](constraint_node_t *n) { list_for_each(n->expr, [&](constraint_expr_t *e) { if (e->expr_type == CEXPR_NAMES && ebitmap_get_bit(&e->type_names->types, attr->s.value - 1)) { ebitmap_set_bit(&e->names, type->s.value - 1, 1); } }); }); }); } bool sepol_impl::add_typeattribute(const char *type, const char *attr) { type_datum_t *type_d = hashtab_find(db->p_types.table, type); if (type_d == nullptr) { LOGW("type %s does not exist\n", type); return false; } else if (type_d->flavor == TYPE_ATTRIB) { LOGW("type %s is an attribute\n", attr); return false; } type_datum *attr_d = hashtab_find(db->p_types.table, attr); if (attr_d == nullptr) { LOGW("attribute %s does not exist\n", type); return false; } else if (attr_d->flavor != TYPE_ATTRIB) { LOGW("type %s is not an attribute \n", attr); return false; } add_typeattribute(type_d, attr_d); return true; } void sepolicy::strip_dontaudit() { avtab_for_each(&impl->db->te_avtab, [=, this](avtab_ptr_t node) { if (node->key.specified == AVTAB_AUDITDENY || node->key.specified == AVTAB_XPERMS_DONTAUDIT) avtab_remove_node(&impl->db->te_avtab, node); }); } void sepolicy::print_rules() { hashtab_for_each(impl->db->p_types.table, [&](hashtab_ptr_t node) { type_datum_t *type = auto_cast(node->datum); if (type->flavor == TYPE_ATTRIB) { impl->print_type(stdout, type); } }); hashtab_for_each(impl->db->p_types.table, [&](hashtab_ptr_t node) { type_datum_t *type = auto_cast(node->datum); if (type->flavor == TYPE_TYPE) { impl->print_type(stdout, type); } }); avtab_for_each(&impl->db->te_avtab, [&](avtab_ptr_t node) { impl->print_avtab(stdout, node); }); hashtab_for_each(impl->db->filename_trans, [&](hashtab_ptr_t node) { impl->print_filename_trans(stdout, node); }); list_for_each(impl->db->genfs, [&](genfs_t *genfs) { list_for_each(genfs->head, [&](ocontext *context) { char *ctx = nullptr; size_t len = 0; if (context_to_string(nullptr, impl->db, &context->context[0], &ctx, &len) == 0) { fprintf(stdout, "genfscon %s %s %s\n", genfs->fstype, context->u.name, ctx); free(ctx); } }); }); } void sepol_impl::print_type(FILE *fp, type_datum_t *type) { const char *name = db->p_type_val_to_name[type->s.value - 1]; if (name == nullptr) return; if (type->flavor == TYPE_ATTRIB) { fprintf(fp, "attribute %s\n", name); } else if (type->flavor == TYPE_TYPE) { bool first = true; ebitmap_t *bitmap = &db->type_attr_map[type->s.value - 1]; for (uint32_t i = 0; i <= bitmap->highbit; ++i) { if (ebitmap_get_bit(bitmap, i)) { auto attr_type = db->type_val_to_struct[i]; if (attr_type->flavor == TYPE_ATTRIB) { if (const char *attr = db->p_type_val_to_name[i]) { if (first) { fprintf(fp, "type %s {", name); first = false; } fprintf(fp, " %s", attr); } } } } if (!first) { fprintf(fp, " }\n"); } } if (ebitmap_get_bit(&db->permissive_map, type->s.value)) { fprintf(fp, "permissive %s\n", name); } } void sepol_impl::print_avtab(FILE *fp, avtab_ptr_t node) { const char *src = db->p_type_val_to_name[node->key.source_type - 1]; const char *tgt = db->p_type_val_to_name[node->key.target_type - 1]; const char *cls = db->p_class_val_to_name[node->key.target_class - 1]; if (src == nullptr || tgt == nullptr || cls == nullptr) return; if (node->key.specified & AVTAB_AV) { uint32_t data = node->datum.data; const char *name; switch (node->key.specified) { case AVTAB_ALLOWED: name = "allow"; break; case AVTAB_AUDITALLOW: name = "auditallow"; break; case AVTAB_AUDITDENY: name = "dontaudit"; // Invert the rules for dontaudit data = ~data; break; default: return; } class_datum_t *clz = db->class_val_to_struct[node->key.target_class - 1]; if (clz == nullptr) return; auto it = class_perm_names.find(cls); if (it == class_perm_names.end()) { it = class_perm_names.try_emplace(cls).first; // Find all permission names and cache the value hashtab_for_each(clz->permissions.table, [&](hashtab_ptr_t node) { perm_datum_t *perm = auto_cast(node->datum); it->second[perm->s.value - 1] = node->key; }); if (clz->comdatum) { hashtab_for_each(clz->comdatum->permissions.table, [&](hashtab_ptr_t node) { perm_datum_t *perm = auto_cast(node->datum); it->second[perm->s.value - 1] = node->key; }); } } bool first = true; for (int i = 0; i < 32; ++i) { if (data & (1u << i)) { if (const char *perm = it->second[i]) { if (first) { fprintf(fp, "%s %s %s %s {", name, src, tgt, cls); first = false; } fprintf(fp, " %s", perm); } } } if (!first) { fprintf(fp, " }\n"); } } else if (node->key.specified & AVTAB_TYPE) { const char *name; switch (node->key.specified) { case AVTAB_TRANSITION: name = "type_transition"; break; case AVTAB_MEMBER: name = "type_member"; break; case AVTAB_CHANGE: name = "type_change"; break; default: return; } if (const char *def = db->p_type_val_to_name[node->datum.data - 1]) { fprintf(fp, "%s %s %s %s %s\n", name, src, tgt, cls, def); } } else if (node->key.specified & AVTAB_XPERMS) { const char *name; switch (node->key.specified) { case AVTAB_XPERMS_ALLOWED: name = "allowxperm"; break; case AVTAB_XPERMS_AUDITALLOW: name = "auditallowxperm"; break; case AVTAB_XPERMS_DONTAUDIT: name = "dontauditxperm"; break; default: return; } avtab_extended_perms_t *xperms = node->datum.xperms; if (xperms == nullptr) return; vector<pair<uint8_t, uint8_t>> ranges; { int low = -1; for (int i = 0; i < 256; ++i) { if (xperm_test(i, xperms->perms)) { if (low < 0) { low = i; } if (i == 255) { ranges.emplace_back(low, 255); } } else if (low >= 0) { ranges.emplace_back(low, i - 1); low = -1; } } } auto to_value = [&](uint8_t val) -> uint16_t { if (xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) { return (((uint16_t) xperms->driver) << 8) | val; } else { return ((uint16_t) val) << 8; } }; if (!ranges.empty()) { fprintf(fp, "%s %s %s %s ioctl {", name, src, tgt, cls); for (auto [l, h] : ranges) { uint16_t low = to_value(l); uint16_t high = to_value(h); if (low == high) { fprintf(fp, " 0x%04X", low); } else { fprintf(fp, " 0x%04X-0x%04X", low, high); } } fprintf(fp, " }\n"); } } } void sepol_impl::print_filename_trans(FILE *fp, hashtab_ptr_t node) { auto key = reinterpret_cast<filename_trans_key_t *>(node->key); filename_trans_datum_t *trans = auto_cast(node->datum); const char *tgt = db->p_type_val_to_name[key->ttype - 1]; const char *cls = db->p_class_val_to_name[key->tclass - 1]; const char *def = db->p_type_val_to_name[trans->otype - 1]; if (tgt == nullptr || cls == nullptr || def == nullptr || key->name == nullptr) return; for (uint32_t i = 0; i <= trans->stypes.highbit; ++i) { if (ebitmap_get_bit(&trans->stypes, i)) { if (const char *src = db->p_type_val_to_name[i]) { fprintf(fp, "type_transition %s %s %s %s %s\n", src, tgt, cls, def, key->name); } } } }
29,766
C++
.cpp
797
28.144291
130
0.533601
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
40
main.cpp
topjohnwu_Magisk/native/src/sepolicy/main.cpp
#include <base.hpp> #include <vector> #include "policy.hpp" using namespace std; [[noreturn]] static void usage(char *arg0) { fprintf(stderr, R"EOF(MagiskPolicy - SELinux Policy Patch Tool Usage: %s [--options...] [policy statements...] Options: --help show help message for policy statements --load FILE load monolithic sepolicy from FILE --load-split load from precompiled sepolicy or compile split cil policies --compile-split compile split cil policies --save FILE dump monolithic sepolicy to FILE --live immediately load sepolicy into the kernel --magisk apply built-in Magisk sepolicy rules --apply FILE apply rules from FILE, read and parsed line by line as policy statements (multiple --apply are allowed) --print-rules print all rules in the loaded sepolicy If neither --load, --load-split, nor --compile-split is specified, it will load from current live policies (/sys/fs/selinux/policy) )EOF", arg0); exit(1); } int main(int argc, char *argv[]) { cmdline_logging(); const char *out_file = nullptr; vector<string_view> rule_files; sepolicy *sepol = nullptr; bool magisk = false; bool live = false; bool print = false; if (argc < 2) usage(argv[0]); int i = 1; for (; i < argc; ++i) { // Parse options if (argv[i][0] == '-' && argv[i][1] == '-') { auto option = argv[i] + 2; if (option == "live"sv) live = true; else if (option == "magisk"sv) magisk = true; else if (option == "print-rules"sv) print = true; else if (option == "load"sv) { if (argv[i + 1] == nullptr) usage(argv[0]); sepol = sepolicy::from_file(argv[i + 1]); if (!sepol) { fprintf(stderr, "Cannot load policy from %s\n", argv[i + 1]); return 1; } ++i; } else if (option == "load-split"sv) { sepol = sepolicy::from_split(); if (!sepol) { fprintf(stderr, "Cannot load split cil\n"); return 1; } } else if (option == "compile-split"sv) { sepol = sepolicy::compile_split(); if (!sepol) { fprintf(stderr, "Cannot compile split cil\n"); return 1; } } else if (option == "save"sv) { if (argv[i + 1] == nullptr) usage(argv[0]); out_file = argv[i + 1]; ++i; } else if (option == "apply"sv) { if (argv[i + 1] == nullptr) usage(argv[0]); rule_files.emplace_back(argv[i + 1]); ++i; } else if (option == "help"sv) { rust::print_statement_help(); exit(0); } else { usage(argv[0]); } } else { break; } } // Use current policy if nothing is loaded if (sepol == nullptr && !(sepol = sepolicy::from_file(SELINUX_POLICY))) { fprintf(stderr, "Cannot load policy from " SELINUX_POLICY "\n"); return 1; } if (print) { sepol->print_rules(); return 0; } if (magisk) sepol->magisk_rules(); if (!rule_files.empty()) for (const auto &rule_file : rule_files) sepol->load_rule_file(rule_file.data()); for (; i < argc; ++i) sepol->parse_statement(argv[i]); if (live && !sepol->to_file(SELINUX_LOAD)) { fprintf(stderr, "Cannot apply policy\n"); return 1; } if (out_file && !sepol->to_file(out_file)) { fprintf(stderr, "Cannot dump policy to %s\n", out_file); return 1; } delete sepol; return 0; }
4,051
C++
.cpp
114
25.315789
81
0.504337
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
41
api.cpp
topjohnwu_Magisk/native/src/sepolicy/api.cpp
#include <base.hpp> #include "policy.hpp" using Str = rust::Str; #if 0 template<typename Arg> std::string as_str(const Arg &arg) { if constexpr (std::is_same_v<Arg, const char *> || std::is_same_v<Arg, char *>) { return arg == nullptr ? "*" : arg; } else if constexpr (std::is_same_v<Arg, Xperm>) { return std::string(rust::xperm_to_string(arg)); } else { return std::to_string(arg); } } // Print out all rules going through public API for debugging template<typename ...Args> static void print_rule(const char *action, Args ...args) { std::string s; s = (... + (" " + as_str(args))); LOGD("%s%s\n", action, s.data()); } #else #define print_rule(...) ((void) 0) #endif bool sepolicy::exists(const char *type) { return hashtab_search(impl->db->p_types.table, type) != nullptr; } void sepolicy::load_rule_file(const char *file) { rust::load_rule_file(*this, file); } void sepolicy::parse_statement(const char *data) { rust::parse_statement(*this, data); } void sepolicy::magisk_rules() { rust::magisk_rules(*this); } void sepolicy::load_rules(const std::string &rules) { rust::load_rules(*this, byte_view(rules, false)); } template<typename F, typename ...T> requires(std::invocable<F, T...>) static inline void expand(F &&f, T &&...args) { f(std::forward<T>(args)...); } template<typename ...T> static inline void expand(const Str &s, T &&...args) { if (s.empty()) { expand(std::forward<T>(args)..., (char *) nullptr); } else { expand(std::forward<T>(args)..., std::string(s).data()); } } template<typename ...T> static inline void expand(const StrVec &vec, T &&...args) { if (vec.empty()) { expand(std::forward<T>(args)..., (char *) nullptr); } else { for (auto &s : vec) { expand(s, std::forward<T>(args)...); } } } template<typename ...T> static inline void expand(const Xperms &vec, T &&...args) { for (auto &p : vec) { expand(std::forward<T>(args)..., p); } } void sepolicy::allow(StrVec src, StrVec tgt, StrVec cls, StrVec perm) { expand(src, tgt, cls, perm, [this](auto ...args) { print_rule("allow", args...); impl->add_rule(args..., AVTAB_ALLOWED, false); }); } void sepolicy::deny(StrVec src, StrVec tgt, StrVec cls, StrVec perm) { expand(src, tgt, cls, perm, [this](auto ...args) { print_rule("deny", args...); impl->add_rule(args..., AVTAB_ALLOWED, true); }); } void sepolicy::auditallow(StrVec src, StrVec tgt, StrVec cls, StrVec perm) { expand(src, tgt, cls, perm, [this](auto ...args) { print_rule("auditallow", args...); impl->add_rule(args..., AVTAB_AUDITALLOW, false); }); } void sepolicy::dontaudit(StrVec src, StrVec tgt, StrVec cls, StrVec perm) { expand(src, tgt, cls, perm, [this](auto ...args) { print_rule("dontaudit", args...); impl->add_rule(args..., AVTAB_AUDITDENY, true); }); } void sepolicy::permissive(StrVec types) { expand(types, [this](auto ...args) { print_rule("permissive", args...); impl->set_type_state(args..., true); }); } void sepolicy::enforce(StrVec types) { expand(types, [this](auto ...args) { print_rule("enforce", args...); impl->set_type_state(args..., false); }); } void sepolicy::typeattribute(StrVec types, StrVec attrs) { expand(types, attrs, [this](auto ...args) { print_rule("typeattribute", args...); impl->add_typeattribute(args...); }); } void sepolicy::type(Str type, StrVec attrs) { expand(type, attrs, [this](auto name, auto attr) { print_rule("type", name, attr); impl->add_type(name, TYPE_TYPE) && impl->add_typeattribute(name, attr); }); } void sepolicy::attribute(Str name) { expand(name, [this](auto ...args) { print_rule("attribute", args...); impl->add_type(args..., TYPE_ATTRIB); }); } void sepolicy::type_transition(Str src, Str tgt, Str cls, Str def, Str obj) { expand(src, tgt, cls, def, obj, [this](auto s, auto t, auto c, auto d, auto o) { if (o) { print_rule("type_transition", s, t, c, d, o); impl->add_filename_trans(s, t, c, d, o); } else { print_rule("type_transition", s, t, c, d); impl->add_type_rule(s, t, c, d, AVTAB_TRANSITION); } }); } void sepolicy::type_change(Str src, Str tgt, Str cls, Str def) { expand(src, tgt, cls, def, [this](auto ...args) { print_rule("type_change", args...); impl->add_type_rule(args..., AVTAB_CHANGE); }); } void sepolicy::type_member(Str src, Str tgt, Str cls, Str def) { expand(src, tgt, cls, def, [this](auto ...args) { print_rule("type_member", args...); impl->add_type_rule(args..., AVTAB_MEMBER); }); } void sepolicy::genfscon(Str fs_name, Str path, Str ctx) { expand(fs_name, path, ctx, [this](auto ...args) { print_rule("genfscon", args...); impl->add_genfscon(args...); }); } void sepolicy::allowxperm(StrVec src, StrVec tgt, StrVec cls, Xperms xperm) { expand(src, tgt, cls, xperm, [this](auto ...args) { print_rule("allowxperm", args...); impl->add_xperm_rule(args..., AVTAB_XPERMS_ALLOWED); }); } void sepolicy::auditallowxperm(StrVec src, StrVec tgt, StrVec cls, Xperms xperm) { expand(src, tgt, cls, xperm, [this](auto ...args) { print_rule("auditallowxperm", args...); impl->add_xperm_rule(args..., AVTAB_XPERMS_AUDITALLOW); }); } void sepolicy::dontauditxperm(StrVec src, StrVec tgt, StrVec cls, Xperms xperm) { expand(src, tgt, cls, xperm, [this](auto ...args) { print_rule("dontauditxperm", args...); impl->add_xperm_rule(args..., AVTAB_XPERMS_DONTAUDIT); }); }
5,831
C++
.cpp
169
29.733728
85
0.605006
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
42
policydb.cpp
topjohnwu_Magisk/native/src/sepolicy/policydb.cpp
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <cil/cil.h> #include <base.hpp> #include <stream.hpp> #include "policy.hpp" #define SHALEN 64 static bool cmp_sha256(const char *a, const char *b) { char id_a[SHALEN] = {0}; char id_b[SHALEN] = {0}; if (int fd = xopen(a, O_RDONLY | O_CLOEXEC); fd >= 0) { xread(fd, id_a, SHALEN); close(fd); } else { return false; } if (int fd = xopen(b, O_RDONLY | O_CLOEXEC); fd >= 0) { xread(fd, id_b, SHALEN); close(fd); } else { return false; } LOGD("%s=[%.*s]\n", a, SHALEN, id_a); LOGD("%s=[%.*s]\n", b, SHALEN, id_b); return memcmp(id_a, id_b, SHALEN) == 0; } static bool check_precompiled(const char *precompiled) { bool ok = false; const char *actual_sha; char compiled_sha[128]; actual_sha = PLAT_POLICY_DIR "plat_and_mapping_sepolicy.cil.sha256"; if (access(actual_sha, R_OK) == 0) { ok = true; sprintf(compiled_sha, "%s.plat_and_mapping.sha256", precompiled); if (!cmp_sha256(actual_sha, compiled_sha)) return false; } actual_sha = PLAT_POLICY_DIR "plat_sepolicy_and_mapping.sha256"; if (access(actual_sha, R_OK) == 0) { ok = true; sprintf(compiled_sha, "%s.plat_sepolicy_and_mapping.sha256", precompiled); if (!cmp_sha256(actual_sha, compiled_sha)) return false; } actual_sha = PROD_POLICY_DIR "product_sepolicy_and_mapping.sha256"; if (access(actual_sha, R_OK) == 0) { ok = true; sprintf(compiled_sha, "%s.product_sepolicy_and_mapping.sha256", precompiled); if (!cmp_sha256(actual_sha, compiled_sha) != 0) return false; } actual_sha = SYSEXT_POLICY_DIR "system_ext_sepolicy_and_mapping.sha256"; if (access(actual_sha, R_OK) == 0) { ok = true; sprintf(compiled_sha, "%s.system_ext_sepolicy_and_mapping.sha256", precompiled); if (!cmp_sha256(actual_sha, compiled_sha) != 0) return false; } return ok; } static void load_cil(struct cil_db *db, const char *file) { mmap_data d(file); cil_add_file(db, file, (const char *) d.buf(), d.sz()); LOGD("cil_add [%s]\n", file); } sepolicy *sepolicy::from_data(char *data, size_t len) { LOGD("Load policy from data\n"); policy_file_t pf; policy_file_init(&pf); pf.data = data; pf.len = len; pf.type = PF_USE_MEMORY; auto db = static_cast<policydb_t *>(malloc(sizeof(policydb_t))); if (policydb_init(db) || policydb_read(db, &pf, 0)) { LOGE("Fail to load policy from data\n"); free(db); return nullptr; } auto sepol = new sepol_impl(db); return sepol; } sepolicy *sepolicy::from_file(const char *file) { LOGD("Load policy from: %s\n", file); policy_file_t pf; policy_file_init(&pf); auto fp = xopen_file(file, "re"); pf.fp = fp.get(); pf.type = PF_USE_STDIO; auto db = static_cast<policydb_t *>(malloc(sizeof(policydb_t))); if (policydb_init(db) || policydb_read(db, &pf, 0)) { LOGE("Fail to load policy from %s\n", file); free(db); return nullptr; } auto sepol = new sepol_impl(db); return sepol; } sepolicy *sepolicy::compile_split() { char path[128], plat_ver[10]; cil_db_t *db = nullptr; sepol_policydb_t *pdb = nullptr; FILE *f; int policy_ver; const char *cil_file; #if MAGISK_DEBUG cil_set_log_level(CIL_INFO); #endif cil_set_log_handler(+[](int lvl, const char *msg) { if (lvl == CIL_ERR) { LOGE("cil: %s", msg); } else if (lvl == CIL_WARN) { LOGW("cil: %s", msg); } else if (lvl == CIL_INFO) { LOGI("cil: %s", msg); } else { LOGD("cil: %s", msg); } }); cil_db_init(&db); run_finally fin([db_ptr = &db]{ cil_db_destroy(db_ptr); }); cil_set_mls(db, 1); cil_set_multiple_decls(db, 1); cil_set_disable_neverallow(db, 1); cil_set_target_platform(db, SEPOL_TARGET_SELINUX); cil_set_attrs_expand_generated(db, 1); f = xfopen(SELINUX_VERSION, "re"); fscanf(f, "%d", &policy_ver); fclose(f); cil_set_policy_version(db, policy_ver); // Get mapping version f = xfopen(VEND_POLICY_DIR "plat_sepolicy_vers.txt", "re"); fscanf(f, "%s", plat_ver); fclose(f); // plat load_cil(db, SPLIT_PLAT_CIL); sprintf(path, PLAT_POLICY_DIR "mapping/%s.cil", plat_ver); load_cil(db, path); sprintf(path, PLAT_POLICY_DIR "mapping/%s.compat.cil", plat_ver); if (access(path, R_OK) == 0) load_cil(db, path); // system_ext sprintf(path, SYSEXT_POLICY_DIR "mapping/%s.cil", plat_ver); if (access(path, R_OK) == 0) load_cil(db, path); sprintf(path, SYSEXT_POLICY_DIR "mapping/%s.compat.cil", plat_ver); if (access(path, R_OK) == 0) load_cil(db, path); cil_file = SYSEXT_POLICY_DIR "system_ext_sepolicy.cil"; if (access(cil_file, R_OK) == 0) load_cil(db, cil_file); // product sprintf(path, PROD_POLICY_DIR "mapping/%s.cil", plat_ver); if (access(path, R_OK) == 0) load_cil(db, path); cil_file = PROD_POLICY_DIR "product_sepolicy.cil"; if (access(cil_file, R_OK) == 0) load_cil(db, cil_file); // vendor cil_file = VEND_POLICY_DIR "nonplat_sepolicy.cil"; if (access(cil_file, R_OK) == 0) load_cil(db, cil_file); cil_file = VEND_POLICY_DIR "plat_pub_versioned.cil"; if (access(cil_file, R_OK) == 0) load_cil(db, cil_file); cil_file = VEND_POLICY_DIR "vendor_sepolicy.cil"; if (access(cil_file, R_OK) == 0) load_cil(db, cil_file); // odm cil_file = ODM_POLICY_DIR "odm_sepolicy.cil"; if (access(cil_file, R_OK) == 0) load_cil(db, cil_file); if (cil_compile(db)) return nullptr; if (cil_build_policydb(db, &pdb)) return nullptr; auto sepol = new sepol_impl(&pdb->p); return sepol; } sepolicy *sepolicy::from_split() { const char *odm_pre = ODM_POLICY_DIR "precompiled_sepolicy"; const char *vend_pre = VEND_POLICY_DIR "precompiled_sepolicy"; if (access(odm_pre, R_OK) == 0 && check_precompiled(odm_pre)) return sepolicy::from_file(odm_pre); else if (access(vend_pre, R_OK) == 0 && check_precompiled(vend_pre)) return sepolicy::from_file(vend_pre); else return sepolicy::compile_split(); } sepol_impl::~sepol_impl() { policydb_destroy(db); free(db); } bool sepolicy::to_file(const char *file) { // No partial writes are allowed to /sys/fs/selinux/load, thus the reason why we // first dump everything into memory, then directly call write system call heap_data data; auto fp = make_stream_fp<byte_stream>(data); policy_file_t pf; policy_file_init(&pf); pf.type = PF_USE_STDIO; pf.fp = fp.get(); if (policydb_write(impl->db, &pf)) { LOGE("Fail to create policy image\n"); return false; } int fd = xopen(file, O_WRONLY | O_CREAT | O_CLOEXEC, 0644); if (fd < 0) return false; if (struct stat st{}; xfstat(fd, &st) == 0 && st.st_size > 0) { ftruncate(fd, 0); } xwrite(fd, data.buf(), data.sz()); close(fd); return true; }
7,365
C++
.cpp
217
28.092166
88
0.598677
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
43
node.hpp
topjohnwu_Magisk/native/src/core/node.hpp
#pragma once #include <sys/mount.h> #include <map> using namespace std; #define TYPE_INTER (1 << 0) /* intermediate node */ #define TYPE_TMPFS (1 << 1) /* replace with tmpfs */ #define TYPE_MODULE (1 << 2) /* mount from module */ #define TYPE_ROOT (1 << 3) /* partition root */ #define TYPE_CUSTOM (1 << 4) /* custom node type overrides all */ #define TYPE_DIR (TYPE_INTER|TYPE_TMPFS|TYPE_ROOT) class node_entry; class dir_node; class inter_node; class tmpfs_node; class module_node; class root_node; // Poor man's dynamic cast without RTTI template<class T> static bool isa(node_entry *node); template<class T> static T *dyn_cast(node_entry *node); template<class T> uint8_t type_id() { return TYPE_CUSTOM; } template<> uint8_t type_id<dir_node>() { return TYPE_DIR; } template<> uint8_t type_id<inter_node>() { return TYPE_INTER; } template<> uint8_t type_id<tmpfs_node>() { return TYPE_TMPFS; } template<> uint8_t type_id<module_node>() { return TYPE_MODULE; } template<> uint8_t type_id<root_node>() { return TYPE_ROOT; } class node_entry { public: virtual ~node_entry() = default; // Node info bool is_dir() const { return file_type() == DT_DIR; } bool is_lnk() const { return file_type() == DT_LNK; } bool is_reg() const { return file_type() == DT_REG; } const string &name() const { return _name; } dir_node *parent() const { return _parent; } // Don't call the following two functions before prepare const string &node_path(); const string worker_path(); virtual void mount() = 0; inline static string module_mnt; protected: template<class T> node_entry(const char *name, uint8_t file_type, T*) : _name(name), _file_type(file_type & 15), _node_type(type_id<T>()) {} template<class T> explicit node_entry(T*) : _file_type(0), _node_type(type_id<T>()) {} virtual void consume(node_entry *other) { _name.swap(other->_name); _file_type = other->_file_type; _parent = other->_parent; delete other; } void create_and_mount(const char *reason, const string &src, bool ro=false); // Use bit 7 of _file_type for exist status bool exist() const { return static_cast<bool>(_file_type & (1 << 7)); } void set_exist(bool b) { if (b) _file_type |= (1 << 7); else _file_type &= ~(1 << 7); } private: friend class dir_node; template<class T> friend bool isa(node_entry *node); uint8_t file_type() const { return static_cast<uint8_t>(_file_type & 15); } // Node properties string _name; dir_node *_parent = nullptr; // Cache, it should only be used within prepare string _node_path; uint8_t _file_type; const uint8_t _node_type; }; class dir_node : public node_entry { public: using map_type = map<string_view, node_entry *>; using iterator = map_type::iterator; ~dir_node() override { for (auto &it : children) delete it.second; children.clear(); } /************** * Entrypoints **************/ // Traverse through module directories to generate a tree of module files void collect_module_files(const char *module, int dfd); // Traverse through the real filesystem and prepare the tree for magic mount. // Return true to indicate that this node needs to be upgraded to tmpfs_node. bool prepare(); // Default directory mount logic void mount() override { for (auto &pair : children) pair.second->mount(); } /*************** * Tree Methods ***************/ bool is_empty() { return children.empty(); } template<class T> T *get_child(string_view name) { return iterator_to_node<T>(children.find(name)); } root_node *root() { if (!_root) _root = _parent->root(); return _root; } // Return child with name or nullptr node_entry *extract(string_view name) { auto it = children.find(name); if (it != children.end()) { auto ret = it->second; children.erase(it); return ret; } return nullptr; } // Return false if rejected bool insert(node_entry *node) { auto fn = [=](auto) { return node; }; return node && iterator_to_node(insert(node->_name, node->_node_type, fn)); } // Return inserted node or null if rejected template<class T, class ...Args> T *emplace(string_view name, Args &&...args) { auto fn = [&](auto) { return new T(std::forward<Args>(args)...); }; return iterator_to_node<T>(insert(name, type_id<T>(), fn)); } // Return upgraded node or null if rejected template<class T, class ...Args> T *upgrade(string_view name, Args &...args) { return iterator_to_node<T>(upgrade<T>(children.find(name), args...)); } protected: template<class T> dir_node(const char *name, T *self) : node_entry(name, DT_DIR, self) { if constexpr (std::is_same_v<T, root_node>) _root = self; } template<class T> dir_node(dirent *entry, T *self) : node_entry(entry->d_name, entry->d_type, self) { if constexpr (std::is_same_v<T, root_node>) _root = self; } template<class T> dir_node(node_entry *node, T *self) : node_entry(self) { if constexpr (std::is_same_v<T, root_node>) _root = self; dir_node::consume(node); } void consume(node_entry *other) override { if (auto o = dyn_cast<dir_node>(other)) { children.merge(o->children); for (auto &pair : children) pair.second->_parent = this; } node_entry::consume(other); } // Use bit 6 of _file_type // Skip binding mirror for this directory bool replace() const { return static_cast<bool>(_file_type & (1 << 6)); } void set_replace(bool b) { if (b) _file_type |= (1 << 6); else _file_type &= ~(1 << 6); } template<class T = node_entry> T *iterator_to_node(iterator it) { return static_cast<T*>(it == children.end() ? nullptr : it->second); } template<typename Builder> iterator insert(string_view name, uint8_t type, const Builder &builder) { return insert_at(children.find(name), type, builder); } // Emplace insert a new node, or upgrade if the requested type has a higher rank. // Return iterator to the new/upgraded node, or end() if insertion is rejected. // fn is the node builder function. Signature: (node_entry *&) -> node_entry * // fn gets a reference to the existing node pointer and returns a new node object. // Input is null when there is no existing node. If returns null, the insertion is rejected. // If fn consumes the input, it should set the reference to null. template<typename Builder> iterator insert_at(iterator it, uint8_t type, const Builder &builder) { node_entry *node = nullptr; if (it != children.end()) { // Upgrade existing node only if higher rank if (it->second->_node_type < type) { node = builder(it->second); if (!node) return children.end(); if (it->second) node->consume(it->second); it = children.erase(it); // Minor optimization to make insert O(1) by using hint if (it == children.begin()) it = children.emplace(node->_name, node).first; else it = children.emplace_hint(--it, node->_name, node); } else { return children.end(); } } else { node = builder(node); if (!node) return children.end(); node->_parent = this; it = children.emplace(node->_name, node).first; } return it; } template<class T, class ...Args> iterator upgrade(iterator it, Args &&...args) { return insert_at(it, type_id<T>(), [&](node_entry *&ex) -> node_entry * { if (!ex) return nullptr; auto node = new T(ex, std::forward<Args>(args)...); ex = nullptr; return node; }); } // dir nodes host children map_type children; private: // Root node lookup cache root_node *_root = nullptr; }; class root_node : public dir_node { public: explicit root_node(const char *name) : dir_node(name, this), prefix("") { set_exist(true); } explicit root_node(node_entry *node) : dir_node(node, this), prefix("/system") { set_exist(true); } const char * const prefix; }; class inter_node : public dir_node { public: inter_node(const char *name) : dir_node(name, this) {} inter_node(dirent *entry) : dir_node(entry, this) {} }; class module_node : public node_entry { public: module_node(const char *module, dirent *entry) : node_entry(entry->d_name, entry->d_type, this), module(module) {} module_node(node_entry *node, const char *module) : node_entry(this), module(module) { node_entry::consume(node); } void mount() override; private: const char *module; }; // Don't create tmpfs_node before prepare class tmpfs_node : public dir_node { public: explicit tmpfs_node(node_entry *node); void mount() override; }; template<class T> static bool isa(node_entry *node) { return node && (node->_node_type & type_id<T>()); } template<class T> static T *dyn_cast(node_entry *node) { return isa<T>(node) ? static_cast<T*>(node) : nullptr; } const string &node_entry::node_path() { if (_parent && _node_path.empty()) _node_path = _parent->node_path() + '/' + _name; return _node_path; } const string node_entry::worker_path() { return get_magisk_tmp() + "/"s WORKERDIR + node_path(); }
9,908
C++
.h
262
31.507634
96
0.605151
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
44
pts.hpp
topjohnwu_Magisk/native/src/core/su/pts.hpp
/* * Copyright 2013, Tan Chee Eng (@tan-ce) */ /* * pts.hpp * * Manages the pseudo-terminal driver on Linux/Android and provides some * helper functions to handle raw input mode and terminal window resizing */ #ifndef _PTS_H_ #define _PTS_H_ #include <sys/types.h> /** * pts_open * * Opens a pts device and returns the name of the slave tty device. * * Arguments * slave_name the name of the slave device * slave_name_size the size of the buffer passed via slave_name * * Return Values * on failure either -2 or -1 (errno set) is returned. * on success, the file descriptor of the master device is returned. */ int pts_open(char *slave_name, size_t slave_name_size); int get_pty_num(int fd); /** * set_stdin_raw * * Changes stdin to raw unbuffered mode, disables echo, * auto carriage return, etc. * * Return Value * on failure -1, and errno is set * on success 0 */ int set_stdin_raw(void); /** * restore_stdin * * Restore termios on stdin to the state it was before * set_stdin_raw() was called. If set_stdin_raw() was * never called, does nothing and doesn't return an error. * * This function is async-safe. * * Return Value * on failure, -1 and errno is set * on success, 0 */ int restore_stdin(void); /** * watch_sigwinch_async * * After calling this function, if the application receives * SIGWINCH, the terminal window size will be read from * "input" and set on "output". * * NOTE: This function blocks SIGWINCH and spawns a thread. * * Arguments * master A file descriptor of the TTY window size to follow * slave A file descriptor of the TTY window size which is * to be set on SIGWINCH * * Return Value * on failure, -1 and errno will be set. In this case, no * thread has been spawned and SIGWINCH will not be * blocked. * on success, 0 */ int watch_sigwinch_async(int master, int slave); /** * pump_stdin_async * * Forward data from STDIN to the given FD * in a separate thread */ void pump_stdin_async(int outfd); /** * pump_stdout_blocking * * Forward data from the FD to STDOUT. * Returns when the remote end of the FD closes. * * Before returning, restores stdin settings. */ void pump_stdout_blocking(int infd); #endif
2,253
C++
.h
90
23.1
73
0.712227
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
45
su.hpp
topjohnwu_Magisk/native/src/core/su/su.hpp
#pragma once #include <sys/types.h> #include <sys/stat.h> #include <memory> #include <db.hpp> #include <core.hpp> #define DEFAULT_SHELL "/system/bin/sh" // Constants for atty #define ATTY_IN (1 << 0) #define ATTY_OUT (1 << 1) #define ATTY_ERR (1 << 2) class su_info { public: // Unique key const int uid; // These should be guarded with internal lock int eval_uid; // The effective UID, taking multiuser settings into consideration db_settings cfg; su_access access; std::string mgr_pkg; int mgr_uid; void check_db(); // These should be guarded with global cache lock bool is_fresh(); void refresh(); su_info(int uid); ~su_info(); mutex_guard lock(); private: long timestamp; // Internal lock pthread_mutex_t _lock; }; struct su_req_base { uid_t uid = AID_ROOT; bool login = false; bool keepenv = false; pid_t target = -1; } __attribute__((packed)); struct su_request : public su_req_base { std::string shell = DEFAULT_SHELL; std::string command; std::string context; std::vector<gid_t> gids; }; struct su_context { std::shared_ptr<su_info> info; su_request req; int pid; }; void app_log(const su_context &ctx); void app_notify(const su_context &ctx); int app_request(const su_context &ctx);
1,329
C++
.h
53
21.641509
85
0.667458
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
46
deny.hpp
topjohnwu_Magisk/native/src/core/deny/deny.hpp
#pragma once #include <pthread.h> #include <string_view> #include <functional> #include <map> #include <atomic> #include <core.hpp> #define ISOLATED_MAGIC "isolated" namespace DenyRequest { enum : int { ENFORCE, DISABLE, ADD, REMOVE, LIST, STATUS, END }; } namespace DenyResponse { enum : int { OK, ENFORCED, NOT_ENFORCED, ITEM_EXIST, ITEM_NOT_EXIST, INVALID_PKG, NO_NS, ERROR, END }; } // CLI entries int enable_deny(); int disable_deny(); int add_list(int client); int rm_list(int client); void ls_list(int client); bool proc_context_match(int pid, std::string_view context); void *logcat(void *arg); extern bool logcat_exit;
701
C++
.h
41
14.317073
59
0.697389
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
47
db.hpp
topjohnwu_Magisk/native/src/core/include/db.hpp
#pragma once #include <sys/stat.h> #include <map> #include <string> #include <string_view> #include <functional> template <class T, size_t N> class db_dict { public: T& operator [](std::string_view key) { return data[get_idx(key)]; } const T& operator [](std::string_view key) const { return data[get_idx(key)]; } T& operator [](int key) { return data[key]; } const T& operator [](int key) const { return data[key]; } protected: T data[N + 1]; virtual int get_idx(std::string_view key) const = 0; }; /*************** * DB Settings * ***************/ constexpr const char *DB_SETTING_KEYS[] = { "root_access", "multiuser_mode", "mnt_ns", "denylist", "zygisk", "bootloop", }; // Settings key indices enum { ROOT_ACCESS = 0, SU_MULTIUSER_MODE, SU_MNT_NS, DENYLIST_CONFIG, ZYGISK_CONFIG, BOOTLOOP_COUNT, }; // Values for root_access enum { ROOT_ACCESS_DISABLED = 0, ROOT_ACCESS_APPS_ONLY, ROOT_ACCESS_ADB_ONLY, ROOT_ACCESS_APPS_AND_ADB }; // Values for multiuser_mode enum { MULTIUSER_MODE_OWNER_ONLY = 0, MULTIUSER_MODE_OWNER_MANAGED, MULTIUSER_MODE_USER }; // Values for mnt_ns enum { NAMESPACE_MODE_GLOBAL = 0, NAMESPACE_MODE_REQUESTER, NAMESPACE_MODE_ISOLATE }; class db_settings : public db_dict<int, std::size(DB_SETTING_KEYS)> { public: db_settings(); protected: int get_idx(std::string_view key) const override; }; /************** * DB Strings * **************/ constexpr const char *DB_STRING_KEYS[] = { "requester" }; // Strings keys indices enum { SU_MANAGER = 0 }; class db_strings : public db_dict<std::string, std::size(DB_STRING_KEYS)> { protected: int get_idx(std::string_view key) const override; }; /************* * SU Access * *************/ typedef enum { QUERY = 0, DENY = 1, ALLOW = 2, } policy_t; struct su_access { policy_t policy; int log; int notify; }; #define DEFAULT_SU_ACCESS { QUERY, 1, 1 } #define SILENT_SU_ACCESS { ALLOW, 0, 0 } #define NO_SU_ACCESS { DENY, 0, 0 } /******************** * Public Functions * ********************/ using db_row = std::map<std::string_view, std::string_view>; using db_row_cb = std::function<bool(db_row&)>; struct owned_fd; struct db_result { db_result() = default; db_result(const char *s) : err(s) {} bool check_err(); operator bool() { return err.empty(); } private: std::string err; }; int get_db_settings(db_settings &cfg, int key = -1); int set_db_settings(int key, int value); int get_db_strings(db_strings &str, int key = -1); void rm_db_strings(int key); void exec_sql(owned_fd client); db_result db_exec(const char *sql); db_result db_exec(const char *sql, const db_row_cb &fn);
2,811
C++
.h
119
20.495798
75
0.625047
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
48
daemon.hpp
topjohnwu_Magisk/native/src/core/include/daemon.hpp
#pragma once #include <base.hpp> namespace rust { struct MagiskD; } struct MagiskD { // Make sure only references can exist ~MagiskD() = delete; // Binding to Rust static const MagiskD &get(); // C++ implementation void reboot() const; bool post_fs_data() const; void late_start() const; void boot_complete() const; const rust::MagiskD *operator->() const; private: const rust::MagiskD &as_rust() const; }; const char *get_magisk_tmp(); // Rust bindings static inline rust::Utf8CStr get_magisk_tmp_rs() { return get_magisk_tmp(); } static inline rust::String resolve_preinit_dir_rs(rust::Utf8CStr base_dir) { return resolve_preinit_dir(base_dir.c_str()); }
714
C++
.h
25
25.28
77
0.697059
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
49
selinux.hpp
topjohnwu_Magisk/native/src/core/include/selinux.hpp
#pragma once #include <base.hpp> int setcon(const char *con); int getfilecon(const char *path, byte_data con); int lgetfilecon(const char *path, byte_data con); int fgetfilecon(int fd, byte_data con); int setfilecon(const char *path, const char *con); int lsetfilecon(const char *path, const char *con); int fsetfilecon(int fd, const char *con); int getfilecon_at(int dirfd, const char *name, byte_data con); void setfilecon_at(int dirfd, const char *name, const char *con); void restorecon(); void restore_tmpcon();
520
C++
.h
13
38.769231
65
0.763889
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
50
resetprop.hpp
topjohnwu_Magisk/native/src/core/include/resetprop.hpp
#pragma once #include <string> #include <map> #include <cxx.h> struct prop_cb { virtual void exec(const char *name, const char *value, uint32_t serial) = 0; }; using prop_list = std::map<std::string, std::string>; struct prop_collector : prop_cb { explicit prop_collector(prop_list &list) : list(list) {} void exec(const char *name, const char *value, uint32_t) override { list.insert({name, value}); } private: prop_list &list; }; // System properties rust::String get_prop_rs(const char *name, bool persist); std::string get_prop(const char *name, bool persist = false); int delete_prop(const char *name, bool persist = false); int set_prop(const char *name, const char *value, bool skip_svc = false); void load_prop_file(const char *filename, bool skip_svc = false); static inline void prop_cb_exec(prop_cb &cb, const char *name, const char *value, uint32_t serial) { cb.exec(name, value, serial); }
941
C++
.h
25
35.12
100
0.70989
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
51
core.hpp
topjohnwu_Magisk/native/src/core/include/core.hpp
#pragma once #include <pthread.h> #include <poll.h> #include <string> #include <limits> #include <atomic> #include <functional> #include "socket.hpp" #include "../core-rs.hpp" #define AID_ROOT 0 #define AID_SHELL 2000 #define AID_APP_START 10000 #define AID_APP_END 19999 #define AID_USER_OFFSET 100000 #define to_app_id(uid) (uid % AID_USER_OFFSET) #define to_user_id(uid) (uid / AID_USER_OFFSET) // Return codes for daemon enum class RespondCode : int { ERROR = -1, OK = 0, ROOT_REQUIRED, ACCESS_DENIED, END }; struct module_info { std::string name; int z32 = -1; #if defined(__LP64__) int z64 = -1; #endif }; extern bool zygisk_enabled; extern std::vector<module_info> *module_list; extern std::string native_bridge; void reset_zygisk(bool restore); int connect_daemon(int req, bool create = false); void unlock_blocks(); // Poll control using poll_callback = void(*)(pollfd*); void register_poll(const pollfd *pfd, poll_callback callback); void unregister_poll(int fd, bool auto_close); void clear_poll(); // Thread pool void init_thread_pool(); void exec_task(std::function<void()> &&task); // Daemon handlers void boot_stage_handler(int client, int code); void denylist_handler(int client, const sock_cred *cred); void su_daemon_handler(int client, const sock_cred *cred); void zygisk_handler(int client, const sock_cred *cred); // Package void preserve_stub_apk(); std::vector<bool> get_app_no_list(); int get_manager(int user, std::string *pkg = nullptr, bool install = false); void prune_su_access(); // Module stuffs void handle_modules(); void load_modules(); void disable_modules(); void remove_modules(); void exec_module_scripts(const char *stage); // Scripting void exec_script(const char *script); void exec_common_scripts(const char *stage); void exec_module_scripts(const char *stage, const std::vector<std::string_view> &modules); void install_apk(const char *apk); void uninstall_pkg(const char *pkg); void clear_pkg(const char *pkg, int user_id); [[noreturn]] void install_module(const char *file); // Denylist extern std::atomic<bool> denylist_enforced; int denylist_cli(int argc, char **argv); void initialize_denylist(); void scan_deny_apps(); bool is_deny_target(int uid, std::string_view process); void revert_unmount(int pid = -1) noexcept;
2,319
C++
.h
76
28.894737
90
0.745063
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
52
socket.hpp
topjohnwu_Magisk/native/src/core/include/socket.hpp
#pragma once #include <sys/un.h> #include <sys/socket.h> #include <string_view> #include <string> #include <vector> struct sock_cred : public ucred { std::string context; }; bool get_client_cred(int fd, sock_cred *cred); std::vector<int> recv_fds(int sockfd); int recv_fd(int sockfd); int send_fds(int sockfd, const int *fds, int cnt); int send_fd(int sockfd, int fd); int read_int(int fd); int read_int_be(int fd); void write_int(int fd, int val); void write_int_be(int fd, int val); std::string read_string(int fd); bool read_string(int fd, std::string &str); void write_string(int fd, std::string_view str); template<typename T> requires(std::is_trivially_copyable_v<T>) void write_vector(int fd, const std::vector<T> &vec) { write_int(fd, static_cast<int>(vec.size())); xwrite(fd, vec.data(), vec.size() * sizeof(T)); } template<typename T> requires(std::is_trivially_copyable_v<T>) bool read_vector(int fd, std::vector<T> &vec) { int size = read_int(fd); if (size == -1) return false; vec.resize(size); return xread(fd, vec.data(), size * sizeof(T)) == size * sizeof(T); }
1,111
C++
.h
33
31.666667
71
0.698975
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
53
module.hpp
topjohnwu_Magisk/native/src/core/zygisk/module.hpp
#pragma once #include <regex.h> #include <bitset> #include <list> #include "api.hpp" struct ZygiskContext; struct ZygiskModule; struct AppSpecializeArgs_v1; using AppSpecializeArgs_v2 = AppSpecializeArgs_v1; struct AppSpecializeArgs_v3; using AppSpecializeArgs_v4 = AppSpecializeArgs_v3; struct AppSpecializeArgs_v5; struct module_abi_v1; using module_abi_v2 = module_abi_v1; using module_abi_v3 = module_abi_v1; using module_abi_v4 = module_abi_v1; using module_abi_v5 = module_abi_v1; struct api_abi_v1; struct api_abi_v2; using api_abi_v3 = api_abi_v2; struct api_abi_v4; using api_abi_v5 = api_abi_v4; union ApiTable; struct AppSpecializeArgs_v3 { jint &uid; jint &gid; jintArray &gids; jint &runtime_flags; jobjectArray &rlimits; jint &mount_external; jstring &se_info; jstring &nice_name; jstring &instruction_set; jstring &app_data_dir; jintArray *fds_to_ignore = nullptr; jboolean *is_child_zygote = nullptr; jboolean *is_top_app = nullptr; jobjectArray *pkg_data_info_list = nullptr; jobjectArray *whitelisted_data_info_list = nullptr; jboolean *mount_data_dirs = nullptr; jboolean *mount_storage_dirs = nullptr; AppSpecializeArgs_v3( jint &uid, jint &gid, jintArray &gids, jint &runtime_flags, jobjectArray &rlimits, jint &mount_external, jstring &se_info, jstring &nice_name, jstring &instruction_set, jstring &app_data_dir) : uid(uid), gid(gid), gids(gids), runtime_flags(runtime_flags), rlimits(rlimits), mount_external(mount_external), se_info(se_info), nice_name(nice_name), instruction_set(instruction_set), app_data_dir(app_data_dir) {} }; struct AppSpecializeArgs_v5 : public AppSpecializeArgs_v3 { jboolean *mount_sysprop_overrides = nullptr; AppSpecializeArgs_v5( jint &uid, jint &gid, jintArray &gids, jint &runtime_flags, jobjectArray &rlimits, jint &mount_external, jstring &se_info, jstring &nice_name, jstring &instruction_set, jstring &app_data_dir) : AppSpecializeArgs_v3( uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir) {} }; struct AppSpecializeArgs_v1 { jint &uid; jint &gid; jintArray &gids; jint &runtime_flags; jint &mount_external; jstring &se_info; jstring &nice_name; jstring &instruction_set; jstring &app_data_dir; jboolean *const is_child_zygote; jboolean *const is_top_app; jobjectArray *const pkg_data_info_list; jobjectArray *const whitelisted_data_info_list; jboolean *const mount_data_dirs; jboolean *const mount_storage_dirs; AppSpecializeArgs_v1(const AppSpecializeArgs_v5 *a) : uid(a->uid), gid(a->gid), gids(a->gids), runtime_flags(a->runtime_flags), mount_external(a->mount_external), se_info(a->se_info), nice_name(a->nice_name), instruction_set(a->instruction_set), app_data_dir(a->app_data_dir), is_child_zygote(a->is_child_zygote), is_top_app(a->is_top_app), pkg_data_info_list(a->pkg_data_info_list), whitelisted_data_info_list(a->whitelisted_data_info_list), mount_data_dirs(a->mount_data_dirs), mount_storage_dirs(a->mount_storage_dirs) {} }; struct ServerSpecializeArgs_v1 { jint &uid; jint &gid; jintArray &gids; jint &runtime_flags; jlong &permitted_capabilities; jlong &effective_capabilities; ServerSpecializeArgs_v1( jint &uid, jint &gid, jintArray &gids, jint &runtime_flags, jlong &permitted_capabilities, jlong &effective_capabilities) : uid(uid), gid(gid), gids(gids), runtime_flags(runtime_flags), permitted_capabilities(permitted_capabilities), effective_capabilities(effective_capabilities) {} }; struct module_abi_v1 { long api_version; void *impl; void (*preAppSpecialize)(void *, void *); void (*postAppSpecialize)(void *, const void *); void (*preServerSpecialize)(void *, void *); void (*postServerSpecialize)(void *, const void *); }; enum : uint32_t { PROCESS_GRANTED_ROOT = zygisk::StateFlag::PROCESS_GRANTED_ROOT, PROCESS_ON_DENYLIST = zygisk::StateFlag::PROCESS_ON_DENYLIST, DENYLIST_ENFORCING = (1u << 30), PROCESS_IS_MAGISK_APP = (1u << 31), UNMOUNT_MASK = (PROCESS_ON_DENYLIST | DENYLIST_ENFORCING), PRIVATE_MASK = (DENYLIST_ENFORCING | PROCESS_IS_MAGISK_APP) }; struct api_abi_base { ZygiskModule *impl; bool (*registerModule)(ApiTable *, long *); }; struct api_abi_v1 : public api_abi_base { /* 0 */ void (*hookJniNativeMethods)(JNIEnv *, const char *, JNINativeMethod *, int); /* 1 */ void (*pltHookRegister)(const char *, const char *, void *, void **); /* 2 */ void (*pltHookExclude)(const char *, const char *); /* 3 */ bool (*pltHookCommit)(); /* 4 */ int (*connectCompanion)(ZygiskModule *); /* 5 */ void (*setOption)(ZygiskModule *, zygisk::Option); }; struct api_abi_v2 : public api_abi_v1 { /* 6 */ int (*getModuleDir)(ZygiskModule *); /* 7 */ uint32_t (*getFlags)(ZygiskModule *); }; struct api_abi_v4 : public api_abi_base { /* 0 */ void (*hookJniNativeMethods)(JNIEnv *, const char *, JNINativeMethod *, int); /* 1 */ void (*pltHookRegister)(dev_t, ino_t, const char *, void *, void **); /* 2 */ bool (*exemptFd)(int); /* 3 */ bool (*pltHookCommit)(); /* 4 */ int (*connectCompanion)(ZygiskModule *); /* 5 */ void (*setOption)(ZygiskModule *, zygisk::Option); /* 6 */ int (*getModuleDir)(ZygiskModule *); /* 7 */ uint32_t (*getFlags)(ZygiskModule *); }; union ApiTable { api_abi_base base; api_abi_v1 v1; api_abi_v2 v2; api_abi_v4 v4; }; struct ZygiskModule { void onLoad(void *env) { entry.fn(&api, env); } void preAppSpecialize(AppSpecializeArgs_v5 *args) const; void postAppSpecialize(const AppSpecializeArgs_v5 *args) const; void preServerSpecialize(ServerSpecializeArgs_v1 *args) const; void postServerSpecialize(const ServerSpecializeArgs_v1 *args) const; bool valid() const; int connectCompanion() const; int getModuleDir() const; void setOption(zygisk::Option opt); static uint32_t getFlags(); void tryUnload() const; void clearApi() { memset(&api, 0, sizeof(api)); } int getId() const { return id; } ZygiskModule(int id, void *handle, void *entry); static bool RegisterModuleImpl(ApiTable *api, long *module); private: const int id; bool unload = false; void * const handle; union { void * const ptr; void (* const fn)(void *, void *); } entry; ApiTable api; union { long *api_version; module_abi_v1 *v1; } mod; }; extern ZygiskContext *g_ctx; extern int (*old_fork)(void); enum : uint32_t { POST_SPECIALIZE = (1u << 0), APP_FORK_AND_SPECIALIZE = (1u << 1), APP_SPECIALIZE = (1u << 2), SERVER_FORK_AND_SPECIALIZE = (1u << 3), DO_REVERT_UNMOUNT = (1u << 4), SKIP_CLOSE_LOG_PIPE = (1u << 5), }; #define MAX_FD_SIZE 1024 #define DCL_PRE_POST(name) \ void name##_pre(); \ void name##_post(); struct ZygiskContext { JNIEnv *env; union { void *ptr; AppSpecializeArgs_v5 *app; ServerSpecializeArgs_v1 *server; } args; const char *process; std::list<ZygiskModule> modules; int pid; uint32_t flags; uint32_t info_flags; std::bitset<MAX_FD_SIZE> allowed_fds; std::vector<int> exempted_fds; struct RegisterInfo { regex_t regex; std::string symbol; void *callback; void **backup; }; struct IgnoreInfo { regex_t regex; std::string symbol; }; pthread_mutex_t hook_info_lock; std::vector<RegisterInfo> register_info; std::vector<IgnoreInfo> ignore_info; ZygiskContext(JNIEnv *env, void *args); ~ZygiskContext(); void run_modules_pre(const std::vector<int> &fds); void run_modules_post(); DCL_PRE_POST(fork) DCL_PRE_POST(app_specialize) DCL_PRE_POST(server_specialize) DCL_PRE_POST(nativeForkAndSpecialize) DCL_PRE_POST(nativeSpecializeAppProcess) DCL_PRE_POST(nativeForkSystemServer) void sanitize_fds(); bool exempt_fd(int fd); bool can_exempt_fd() const; bool is_child() const { return pid <= 0; } // Compatibility shim void plt_hook_register(const char *regex, const char *symbol, void *fn, void **backup); void plt_hook_exclude(const char *regex, const char *symbol); void plt_hook_process_regex(); bool plt_hook_commit(); }; #undef DCL_PRE_POST
8,743
C++
.h
239
31.280335
94
0.664103
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
54
zygisk.hpp
topjohnwu_Magisk/native/src/core/zygisk/zygisk.hpp
#pragma once #include <sys/mman.h> #include <stdint.h> #include <jni.h> #include <vector> #include <core.hpp> namespace ZygiskRequest { enum : int { GET_INFO, CONNECT_COMPANION, GET_MODDIR, END }; } #if defined(__LP64__) #define ZLOGD(...) LOGD("zygisk64: " __VA_ARGS__) #define ZLOGE(...) LOGE("zygisk64: " __VA_ARGS__) #define ZLOGI(...) LOGI("zygisk64: " __VA_ARGS__) #define ZLOGW(...) LOGW("zygisk64: " __VA_ARGS__) #else #define ZLOGD(...) LOGD("zygisk32: " __VA_ARGS__) #define ZLOGE(...) LOGE("zygisk32: " __VA_ARGS__) #define ZLOGI(...) LOGI("zygisk32: " __VA_ARGS__) #define ZLOGW(...) LOGW("zygisk32: " __VA_ARGS__) #endif // Extreme verbose logging #define ZLOGV(...) ZLOGD(__VA_ARGS__) //#define ZLOGV(...) (void*)0 void hook_entry(); void hookJniNativeMethods(JNIEnv *env, const char *clz, JNINativeMethod *methods, int numMethods); int remote_get_info(int uid, const char *process, uint32_t *flags, std::vector<int> &fds); inline int zygisk_request(int req) { int fd = connect_daemon(+RequestCode::ZYGISK); if (fd < 0) return fd; write_int(fd, req); return fd; } // The reference of the following structs // https://cs.android.com/android/platform/superproject/main/+/main:art/libnativebridge/include/nativebridge/native_bridge.h struct NativeBridgeRuntimeCallbacks { const char* (*getMethodShorty)(JNIEnv* env, jmethodID mid); uint32_t (*getNativeMethodCount)(JNIEnv* env, jclass clazz); uint32_t (*getNativeMethods)(JNIEnv* env, jclass clazz, JNINativeMethod* methods, uint32_t method_count); }; struct NativeBridgeCallbacks { uint32_t version; void *padding[5]; bool (*isCompatibleWith)(uint32_t); };
1,718
C++
.h
50
31.38
124
0.683353
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
56
jni_hooks.hpp
topjohnwu_Magisk/native/src/core/zygisk/jni_hooks.hpp
// Generated by gen_jni_hooks.py std::array<JNINativeMethod, 17> zygote_methods = {{ { "nativeForkAndSpecialize", "(II[II[[IILjava/lang/String;Ljava/lang/String;[ILjava/lang/String;Ljava/lang/String;)I", (void *) +[] [[clang::no_stack_protector]] (JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jintArray fds_to_close, jstring instruction_set, jstring app_data_dir) static -> jint { AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); ZygiskContext ctx(env, &args); ctx.nativeForkAndSpecialize_pre(); reinterpret_cast<jint(*)(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jintArray fds_to_close, jstring instruction_set, jstring app_data_dir)>(g_hook->zygote_methods[0].fnPtr)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, fds_to_close, instruction_set, app_data_dir ); ctx.nativeForkAndSpecialize_post(); return ctx.pid; } }, { "nativeForkAndSpecialize", "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[ILjava/lang/String;Ljava/lang/String;)I", (void *) +[] [[clang::no_stack_protector]] (JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jintArray fds_to_close, jintArray fds_to_ignore, jstring instruction_set, jstring app_data_dir) static -> jint { AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); args.fds_to_ignore = &fds_to_ignore; ZygiskContext ctx(env, &args); ctx.nativeForkAndSpecialize_pre(); reinterpret_cast<jint(*)(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jintArray fds_to_close, jintArray fds_to_ignore, jstring instruction_set, jstring app_data_dir)>(g_hook->zygote_methods[1].fnPtr)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, fds_to_close, fds_to_ignore, instruction_set, app_data_dir ); ctx.nativeForkAndSpecialize_post(); return ctx.pid; } }, { "nativeForkAndSpecialize", "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;)I", (void *) +[] [[clang::no_stack_protector]] (JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jintArray fds_to_close, jintArray fds_to_ignore, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir) static -> jint { AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); args.fds_to_ignore = &fds_to_ignore; args.is_child_zygote = &is_child_zygote; ZygiskContext ctx(env, &args); ctx.nativeForkAndSpecialize_pre(); reinterpret_cast<jint(*)(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jintArray fds_to_close, jintArray fds_to_ignore, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir)>(g_hook->zygote_methods[2].fnPtr)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, fds_to_close, fds_to_ignore, is_child_zygote, instruction_set, app_data_dir ); ctx.nativeForkAndSpecialize_post(); return ctx.pid; } }, { "nativeForkAndSpecialize", "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;Z)I", (void *) +[] [[clang::no_stack_protector]] (JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jintArray fds_to_close, jintArray fds_to_ignore, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app) static -> jint { AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); args.fds_to_ignore = &fds_to_ignore; args.is_child_zygote = &is_child_zygote; args.is_top_app = &is_top_app; ZygiskContext ctx(env, &args); ctx.nativeForkAndSpecialize_pre(); reinterpret_cast<jint(*)(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jintArray fds_to_close, jintArray fds_to_ignore, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app)>(g_hook->zygote_methods[3].fnPtr)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, fds_to_close, fds_to_ignore, is_child_zygote, instruction_set, app_data_dir, is_top_app ); ctx.nativeForkAndSpecialize_post(); return ctx.pid; } }, { "nativeForkAndSpecialize", "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;Z[Ljava/lang/String;[Ljava/lang/String;ZZ)I", (void *) +[] [[clang::no_stack_protector]] (JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jintArray fds_to_close, jintArray fds_to_ignore, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app, jobjectArray pkg_data_info_list, jobjectArray whitelisted_data_info_list, jboolean mount_data_dirs, jboolean mount_storage_dirs) static -> jint { AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); args.fds_to_ignore = &fds_to_ignore; args.is_child_zygote = &is_child_zygote; args.is_top_app = &is_top_app; args.pkg_data_info_list = &pkg_data_info_list; args.whitelisted_data_info_list = &whitelisted_data_info_list; args.mount_data_dirs = &mount_data_dirs; args.mount_storage_dirs = &mount_storage_dirs; ZygiskContext ctx(env, &args); ctx.nativeForkAndSpecialize_pre(); reinterpret_cast<jint(*)(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jintArray fds_to_close, jintArray fds_to_ignore, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app, jobjectArray pkg_data_info_list, jobjectArray whitelisted_data_info_list, jboolean mount_data_dirs, jboolean mount_storage_dirs)>(g_hook->zygote_methods[4].fnPtr)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, fds_to_close, fds_to_ignore, is_child_zygote, instruction_set, app_data_dir, is_top_app, pkg_data_info_list, whitelisted_data_info_list, mount_data_dirs, mount_storage_dirs ); ctx.nativeForkAndSpecialize_post(); return ctx.pid; } }, { "nativeForkAndSpecialize", "(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;Z[Ljava/lang/String;[Ljava/lang/String;ZZZ)I", (void *) +[] [[clang::no_stack_protector]] (JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jintArray fds_to_close, jintArray fds_to_ignore, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app, jobjectArray pkg_data_info_list, jobjectArray whitelisted_data_info_list, jboolean mount_data_dirs, jboolean mount_storage_dirs, jboolean mount_sysprop_overrides) static -> jint { AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); args.fds_to_ignore = &fds_to_ignore; args.is_child_zygote = &is_child_zygote; args.is_top_app = &is_top_app; args.pkg_data_info_list = &pkg_data_info_list; args.whitelisted_data_info_list = &whitelisted_data_info_list; args.mount_data_dirs = &mount_data_dirs; args.mount_storage_dirs = &mount_storage_dirs; args.mount_sysprop_overrides = &mount_sysprop_overrides; ZygiskContext ctx(env, &args); ctx.nativeForkAndSpecialize_pre(); reinterpret_cast<jint(*)(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jintArray fds_to_close, jintArray fds_to_ignore, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app, jobjectArray pkg_data_info_list, jobjectArray whitelisted_data_info_list, jboolean mount_data_dirs, jboolean mount_storage_dirs, jboolean mount_sysprop_overrides)>(g_hook->zygote_methods[5].fnPtr)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, fds_to_close, fds_to_ignore, is_child_zygote, instruction_set, app_data_dir, is_top_app, pkg_data_info_list, whitelisted_data_info_list, mount_data_dirs, mount_storage_dirs, mount_sysprop_overrides ); ctx.nativeForkAndSpecialize_post(); return ctx.pid; } }, { "nativeForkAndSpecialize", "(II[II[[IILjava/lang/String;IILjava/lang/String;[ILjava/lang/String;Ljava/lang/String;)I", (void *) +[] [[clang::no_stack_protector]] (JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jint _0, jint _1, jstring nice_name, jintArray fds_to_close, jstring instruction_set, jstring app_data_dir) static -> jint { AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); ZygiskContext ctx(env, &args); ctx.nativeForkAndSpecialize_pre(); reinterpret_cast<jint(*)(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jint _0, jint _1, jstring nice_name, jintArray fds_to_close, jstring instruction_set, jstring app_data_dir)>(g_hook->zygote_methods[6].fnPtr)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, _0, _1, nice_name, fds_to_close, instruction_set, app_data_dir ); ctx.nativeForkAndSpecialize_post(); return ctx.pid; } }, { "nativeForkAndSpecialize", "(II[II[[IILjava/lang/String;IILjava/lang/String;[ILjava/lang/String;Ljava/lang/String;I)I", (void *) +[] [[clang::no_stack_protector]] (JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jint _2, jint _3, jstring nice_name, jintArray fds_to_close, jstring instruction_set, jstring app_data_dir, jint _4) static -> jint { AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); ZygiskContext ctx(env, &args); ctx.nativeForkAndSpecialize_pre(); reinterpret_cast<jint(*)(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jint _2, jint _3, jstring nice_name, jintArray fds_to_close, jstring instruction_set, jstring app_data_dir, jint _4)>(g_hook->zygote_methods[7].fnPtr)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, _2, _3, nice_name, fds_to_close, instruction_set, app_data_dir, _4 ); ctx.nativeForkAndSpecialize_post(); return ctx.pid; } }, { "nativeForkAndSpecialize", "(II[II[[IILjava/lang/String;IILjava/lang/String;[I[ILjava/lang/String;Ljava/lang/String;)I", (void *) +[] [[clang::no_stack_protector]] (JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jint _5, jint _6, jstring nice_name, jintArray fds_to_close, jintArray fds_to_ignore, jstring instruction_set, jstring app_data_dir) static -> jint { AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); args.fds_to_ignore = &fds_to_ignore; ZygiskContext ctx(env, &args); ctx.nativeForkAndSpecialize_pre(); reinterpret_cast<jint(*)(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jint _5, jint _6, jstring nice_name, jintArray fds_to_close, jintArray fds_to_ignore, jstring instruction_set, jstring app_data_dir)>(g_hook->zygote_methods[8].fnPtr)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, _5, _6, nice_name, fds_to_close, fds_to_ignore, instruction_set, app_data_dir ); ctx.nativeForkAndSpecialize_post(); return ctx.pid; } }, { "nativeForkAndSpecialize", "(II[II[[IILjava/lang/String;IILjava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;)I", (void *) +[] [[clang::no_stack_protector]] (JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jint _7, jint _8, jstring nice_name, jintArray fds_to_close, jintArray fds_to_ignore, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir) static -> jint { AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); args.fds_to_ignore = &fds_to_ignore; args.is_child_zygote = &is_child_zygote; ZygiskContext ctx(env, &args); ctx.nativeForkAndSpecialize_pre(); reinterpret_cast<jint(*)(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jint _7, jint _8, jstring nice_name, jintArray fds_to_close, jintArray fds_to_ignore, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir)>(g_hook->zygote_methods[9].fnPtr)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, _7, _8, nice_name, fds_to_close, fds_to_ignore, is_child_zygote, instruction_set, app_data_dir ); ctx.nativeForkAndSpecialize_post(); return ctx.pid; } }, { "nativeSpecializeAppProcess", "(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;)V", (void *) +[] [[clang::no_stack_protector]] (JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir) static -> void { AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); args.is_child_zygote = &is_child_zygote; ZygiskContext ctx(env, &args); ctx.nativeSpecializeAppProcess_pre(); reinterpret_cast<void(*)(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir)>(g_hook->zygote_methods[10].fnPtr)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, is_child_zygote, instruction_set, app_data_dir ); ctx.nativeSpecializeAppProcess_post(); } }, { "nativeSpecializeAppProcess", "(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;Z)V", (void *) +[] [[clang::no_stack_protector]] (JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app) static -> void { AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); args.is_child_zygote = &is_child_zygote; args.is_top_app = &is_top_app; ZygiskContext ctx(env, &args); ctx.nativeSpecializeAppProcess_pre(); reinterpret_cast<void(*)(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app)>(g_hook->zygote_methods[11].fnPtr)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, is_child_zygote, instruction_set, app_data_dir, is_top_app ); ctx.nativeSpecializeAppProcess_post(); } }, { "nativeSpecializeAppProcess", "(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;Z[Ljava/lang/String;[Ljava/lang/String;ZZ)V", (void *) +[] [[clang::no_stack_protector]] (JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app, jobjectArray pkg_data_info_list, jobjectArray whitelisted_data_info_list, jboolean mount_data_dirs, jboolean mount_storage_dirs) static -> void { AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); args.is_child_zygote = &is_child_zygote; args.is_top_app = &is_top_app; args.pkg_data_info_list = &pkg_data_info_list; args.whitelisted_data_info_list = &whitelisted_data_info_list; args.mount_data_dirs = &mount_data_dirs; args.mount_storage_dirs = &mount_storage_dirs; ZygiskContext ctx(env, &args); ctx.nativeSpecializeAppProcess_pre(); reinterpret_cast<void(*)(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app, jobjectArray pkg_data_info_list, jobjectArray whitelisted_data_info_list, jboolean mount_data_dirs, jboolean mount_storage_dirs)>(g_hook->zygote_methods[12].fnPtr)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, is_child_zygote, instruction_set, app_data_dir, is_top_app, pkg_data_info_list, whitelisted_data_info_list, mount_data_dirs, mount_storage_dirs ); ctx.nativeSpecializeAppProcess_post(); } }, { "nativeSpecializeAppProcess", "(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;Z[Ljava/lang/String;[Ljava/lang/String;ZZZ)V", (void *) +[] [[clang::no_stack_protector]] (JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app, jobjectArray pkg_data_info_list, jobjectArray whitelisted_data_info_list, jboolean mount_data_dirs, jboolean mount_storage_dirs, jboolean mount_sysprop_overrides) static -> void { AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); args.is_child_zygote = &is_child_zygote; args.is_top_app = &is_top_app; args.pkg_data_info_list = &pkg_data_info_list; args.whitelisted_data_info_list = &whitelisted_data_info_list; args.mount_data_dirs = &mount_data_dirs; args.mount_storage_dirs = &mount_storage_dirs; args.mount_sysprop_overrides = &mount_sysprop_overrides; ZygiskContext ctx(env, &args); ctx.nativeSpecializeAppProcess_pre(); reinterpret_cast<void(*)(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app, jobjectArray pkg_data_info_list, jobjectArray whitelisted_data_info_list, jboolean mount_data_dirs, jboolean mount_storage_dirs, jboolean mount_sysprop_overrides)>(g_hook->zygote_methods[13].fnPtr)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, is_child_zygote, instruction_set, app_data_dir, is_top_app, pkg_data_info_list, whitelisted_data_info_list, mount_data_dirs, mount_storage_dirs, mount_sysprop_overrides ); ctx.nativeSpecializeAppProcess_post(); } }, { "nativeSpecializeAppProcess", "(II[II[[IILjava/lang/String;IILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;)V", (void *) +[] [[clang::no_stack_protector]] (JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jint _9, jint _10, jstring nice_name, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir) static -> void { AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir); args.is_child_zygote = &is_child_zygote; ZygiskContext ctx(env, &args); ctx.nativeSpecializeAppProcess_pre(); reinterpret_cast<void(*)(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jint _9, jint _10, jstring nice_name, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir)>(g_hook->zygote_methods[14].fnPtr)( env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, _9, _10, nice_name, is_child_zygote, instruction_set, app_data_dir ); ctx.nativeSpecializeAppProcess_post(); } }, { "nativeForkSystemServer", "(II[II[[IJJ)I", (void *) +[] [[clang::no_stack_protector]] (JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities, jlong effective_capabilities) static -> jint { ServerSpecializeArgs_v1 args(uid, gid, gids, runtime_flags, permitted_capabilities, effective_capabilities); ZygiskContext ctx(env, &args); ctx.nativeForkSystemServer_pre(); reinterpret_cast<jint(*)(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities, jlong effective_capabilities)>(g_hook->zygote_methods[15].fnPtr)( env, clazz, uid, gid, gids, runtime_flags, rlimits, permitted_capabilities, effective_capabilities ); ctx.nativeForkSystemServer_post(); return ctx.pid; } }, { "nativeForkSystemServer", "(II[IIII[[IJJ)I", (void *) +[] [[clang::no_stack_protector]] (JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jint _11, jint _12, jobjectArray rlimits, jlong permitted_capabilities, jlong effective_capabilities) static -> jint { ServerSpecializeArgs_v1 args(uid, gid, gids, runtime_flags, permitted_capabilities, effective_capabilities); ZygiskContext ctx(env, &args); ctx.nativeForkSystemServer_pre(); reinterpret_cast<jint(*)(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jint _11, jint _12, jobjectArray rlimits, jlong permitted_capabilities, jlong effective_capabilities)>(g_hook->zygote_methods[16].fnPtr)( env, clazz, uid, gid, gids, runtime_flags, _11, _12, rlimits, permitted_capabilities, effective_capabilities ); ctx.nativeForkSystemServer_post(); return ctx.pid; } }, }};
25,969
C++
.h
277
82.592058
539
0.685247
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
57
consts.hpp
topjohnwu_Magisk/native/src/include/consts.hpp
#pragma once #define JAVA_PACKAGE_NAME "com.topjohnwu.magisk" #define ZYGISKLDR "libzygisk.so" #define NBPROP "ro.dalvik.vm.native.bridge" #define SECURE_DIR "/data/adb" #define MODULEROOT SECURE_DIR "/modules" #define MODULEUPGRADE SECURE_DIR "/modules_update" #define DATABIN SECURE_DIR "/magisk" #define MAGISKDB SECURE_DIR "/magisk.db" // tmpfs paths #define INTLROOT ".magisk" #define MIRRDIR INTLROOT "/mirror" #define PREINITMIRR INTLROOT "/preinit" #define DEVICEDIR INTLROOT "/device" #define PREINITDEV DEVICEDIR "/preinit" #define WORKERDIR INTLROOT "/worker" #define MODULEMNT INTLROOT "/modules" #define BBPATH INTLROOT "/busybox" #define ROOTOVL INTLROOT "/rootdir" #define SHELLPTS INTLROOT "/pts" #define ROOTMNT ROOTOVL "/.mount_list" #define SELINUXMOCK INTLROOT "/selinux" #define MAIN_CONFIG INTLROOT "/config" #define MAIN_SOCKET DEVICEDIR "/socket" #define LOG_PIPE DEVICEDIR "/log" constexpr const char *applet_names[] = { "su", "resetprop", nullptr }; #define POST_FS_DATA_WAIT_TIME 40 #define POST_FS_DATA_SCRIPT_MAX_TIME 35 // Unconstrained domain the daemon and root processes run in #define SEPOL_PROC_DOMAIN "magisk" #define MAGISK_PROC_CON "u:r:" SEPOL_PROC_DOMAIN ":s0" // Unconstrained file type that anyone can access #define SEPOL_FILE_TYPE "magisk_file" #define MAGISK_FILE_CON "u:object_r:" SEPOL_FILE_TYPE ":s0" // Log pipe that only root and zygote can open #define SEPOL_LOG_TYPE "magisk_log_file" #define MAGISK_LOG_CON "u:object_r:" SEPOL_LOG_TYPE ":s0" extern int SDK_INT; #define APP_DATA_DIR (SDK_INT >= 24 ? "/data/user_de" : "/data/user") // Multi-call entrypoints int magisk_main(int argc, char *argv[]); int su_client_main(int argc, char *argv[]); int resetprop_main(int argc, char *argv[]); int zygisk_main(int argc, char *argv[]);
1,924
C++
.h
44
42.568182
70
0.709023
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
58
magiskboot.hpp
topjohnwu_Magisk/native/src/boot/magiskboot.hpp
#pragma once #include <sys/types.h> #include <base.hpp> #define HEADER_FILE "header" #define KERNEL_FILE "kernel" #define RAMDISK_FILE "ramdisk.cpio" #define VND_RAMDISK_DIR "vendor_ramdisk" #define SECOND_FILE "second" #define EXTRA_FILE "extra" #define KER_DTB_FILE "kernel_dtb" #define RECV_DTBO_FILE "recovery_dtbo" #define DTB_FILE "dtb" #define BOOTCONFIG_FILE "bootconfig" #define NEW_BOOT "new-boot.img" int unpack(const char *image, bool skip_decomp = false, bool hdr = false); void repack(const char *src_img, const char *out_img, bool skip_comp = false); int verify(const char *image, const char *cert); int sign(const char *image, const char *name, const char *cert, const char *key); int split_image_dtb(const char *filename, bool skip_decomp = false); int dtb_commands(int argc, char *argv[]); static inline bool check_env(const char *name) { using namespace std::string_view_literals; const char *val = getenv(name); return val != nullptr && val == "true"sv; }
1,031
C++
.h
25
39.56
81
0.715285
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
59
format.hpp
topjohnwu_Magisk/native/src/boot/format.hpp
#pragma once #include <string_view> typedef enum { UNKNOWN, /* Boot formats */ CHROMEOS, AOSP, AOSP_VENDOR, DHTB, BLOB, /* Compression formats */ GZIP, ZOPFLI, XZ, LZMA, BZIP2, LZ4, LZ4_LEGACY, LZ4_LG, /* Unsupported compression */ LZOP, /* Misc */ MTK, DTB, ZIMAGE, } format_t; #define COMPRESSED(fmt) ((fmt) >= GZIP && (fmt) < LZOP) #define COMPRESSED_ANY(fmt) ((fmt) >= GZIP && (fmt) <= LZOP) #define BUFFER_MATCH(buf, s) (memcmp(buf, s, sizeof(s) - 1) == 0) #define BUFFER_CONTAIN(buf, sz, s) (memmem(buf, sz, s, sizeof(s) - 1) != nullptr) #define BOOT_MAGIC "ANDROID!" #define VENDOR_BOOT_MAGIC "VNDRBOOT" #define CHROMEOS_MAGIC "CHROMEOS" #define GZIP1_MAGIC "\x1f\x8b" #define GZIP2_MAGIC "\x1f\x9e" #define LZOP_MAGIC "\x89""LZO" #define XZ_MAGIC "\xfd""7zXZ" #define BZIP_MAGIC "BZh" #define LZ4_LEG_MAGIC "\x02\x21\x4c\x18" #define LZ41_MAGIC "\x03\x21\x4c\x18" #define LZ42_MAGIC "\x04\x22\x4d\x18" #define MTK_MAGIC "\x88\x16\x88\x58" #define DTB_MAGIC "\xd0\x0d\xfe\xed" #define LG_BUMP_MAGIC "\x41\xa9\xe4\x67\x74\x4d\x1d\x1b\xa4\x29\xf2\xec\xea\x65\x52\x79" #define DHTB_MAGIC "\x44\x48\x54\x42\x01\x00\x00\x00" #define SEANDROID_MAGIC "SEANDROIDENFORCE" #define TEGRABLOB_MAGIC "-SIGNED-BY-SIGNBLOB-" #define NOOKHD_RL_MAGIC "Red Loader" #define NOOKHD_GL_MAGIC "Green Loader" #define NOOKHD_GR_MAGIC "Green Recovery" #define NOOKHD_EB_MAGIC "eMMC boot.img+secondloader" #define NOOKHD_ER_MAGIC "eMMC recovery.img+secondloader" #define NOOKHD_PRE_HEADER_SZ 1048576 #define ACCLAIM_MAGIC "BauwksBoot" #define ACCLAIM_PRE_HEADER_SZ 262144 #define AMONET_MICROLOADER_MAGIC "microloader" #define AMONET_MICROLOADER_SZ 1024 #define AVB_FOOTER_MAGIC "AVBf" #define AVB_MAGIC "AVB0" #define ZIMAGE_MAGIC "\x18\x28\x6f\x01" class Fmt2Name { public: const char *operator[](format_t fmt); }; class Fmt2Ext { public: const char *operator[](format_t fmt); }; class Name2Fmt { public: format_t operator[](std::string_view name); }; format_t check_fmt(const void *buf, size_t len); extern Name2Fmt name2fmt; extern Fmt2Name fmt2name; extern Fmt2Ext fmt2ext;
2,224
C++
.h
76
27.026316
90
0.696913
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
60
bootimg.hpp
topjohnwu_Magisk/native/src/boot/bootimg.hpp
#pragma once #include <cstdint> #include <utility> #include <bitset> #include <cxx.h> #include "format.hpp" /****************** * Special Headers *****************/ struct mtk_hdr { uint32_t magic; /* MTK magic */ uint32_t size; /* Size of the content */ char name[32]; /* The type of the header */ char padding[472]; /* Padding to 512 bytes */ } __attribute__((packed)); struct dhtb_hdr { char magic[8]; /* DHTB magic */ uint8_t checksum[40]; /* Payload SHA256, whole image + SEANDROIDENFORCE + 0xFFFFFFFF */ uint32_t size; /* Payload size, whole image + SEANDROIDENFORCE + 0xFFFFFFFF */ char padding[460]; /* Padding to 512 bytes */ } __attribute__((packed)); struct blob_hdr { char secure_magic[20]; /* "-SIGNED-BY-SIGNBLOB-" */ uint32_t datalen; /* 0x00000000 */ uint32_t signature; /* 0x00000000 */ char magic[16]; /* "MSM-RADIO-UPDATE" */ uint32_t hdr_version; /* 0x00010000 */ uint32_t hdr_size; /* Size of header */ uint32_t part_offset; /* Same as size */ uint32_t num_parts; /* Number of partitions */ uint32_t unknown[7]; /* All 0x00000000 */ char name[4]; /* Name of partition */ uint32_t offset; /* offset in blob where this partition starts */ uint32_t size; /* Size of data */ uint32_t version; /* 0x00000001 */ } __attribute__((packed)); struct zimage_hdr { uint32_t code[9]; uint32_t magic; /* zImage magic */ uint32_t start; /* absolute load/run zImage address */ uint32_t end; /* zImage end address */ uint32_t endian; /* endianness flag */ // There could be more fields, but we don't care } __attribute__((packed)); /************** * AVB Headers **************/ #define AVB_FOOTER_MAGIC_LEN 4 #define AVB_MAGIC_LEN 4 #define AVB_RELEASE_STRING_SIZE 48 // https://android.googlesource.com/platform/external/avb/+/refs/heads/android11-release/libavb/avb_footer.h struct AvbFooter { uint8_t magic[AVB_FOOTER_MAGIC_LEN]; uint32_t version_major; uint32_t version_minor; uint64_t original_image_size; uint64_t vbmeta_offset; uint64_t vbmeta_size; uint8_t reserved[28]; } __attribute__((packed)); // https://android.googlesource.com/platform/external/avb/+/refs/heads/android11-release/libavb/avb_vbmeta_image.h struct AvbVBMetaImageHeader { uint8_t magic[AVB_MAGIC_LEN]; uint32_t required_libavb_version_major; uint32_t required_libavb_version_minor; uint64_t authentication_data_block_size; uint64_t auxiliary_data_block_size; uint32_t algorithm_type; uint64_t hash_offset; uint64_t hash_size; uint64_t signature_offset; uint64_t signature_size; uint64_t public_key_offset; uint64_t public_key_size; uint64_t public_key_metadata_offset; uint64_t public_key_metadata_size; uint64_t descriptors_offset; uint64_t descriptors_size; uint64_t rollback_index; uint32_t flags; uint32_t rollback_index_location; uint8_t release_string[AVB_RELEASE_STRING_SIZE]; uint8_t reserved[80]; } __attribute__((packed)); /********************* * Boot Image Headers *********************/ // https://android.googlesource.com/platform/system/tools/mkbootimg/+/refs/heads/android12-release/include/bootimg/bootimg.h #define BOOT_MAGIC_SIZE 8 #define BOOT_NAME_SIZE 16 #define BOOT_ID_SIZE 32 #define BOOT_ARGS_SIZE 512 #define BOOT_EXTRA_ARGS_SIZE 1024 #define VENDOR_BOOT_ARGS_SIZE 2048 #define VENDOR_RAMDISK_NAME_SIZE 32 #define VENDOR_RAMDISK_TABLE_ENTRY_BOARD_ID_SIZE 16 #define VENDOR_RAMDISK_TYPE_NONE 0 #define VENDOR_RAMDISK_TYPE_PLATFORM 1 #define VENDOR_RAMDISK_TYPE_RECOVERY 2 #define VENDOR_RAMDISK_TYPE_DLKM 3 /* * When the boot image header has a version of 0 - 2, the structure of the boot * image is as follows: * * +-----------------+ * | boot header | 1 page * +-----------------+ * | kernel | m pages * +-----------------+ * | ramdisk | n pages * +-----------------+ * | second stage | o pages * +-----------------+ * | extra blob | x pages (non standard) * +-----------------+ * | recovery dtbo | p pages * +-----------------+ * | dtb | q pages * +-----------------+ * * m = (kernel_size + page_size - 1) / page_size * n = (ramdisk_size + page_size - 1) / page_size * o = (second_size + page_size - 1) / page_size * p = (recovery_dtbo_size + page_size - 1) / page_size * q = (dtb_size + page_size - 1) / page_size * x = (extra_size + page_size - 1) / page_size */ struct boot_img_hdr_v0_common { char magic[BOOT_MAGIC_SIZE]; uint32_t kernel_size; /* size in bytes */ uint32_t kernel_addr; /* physical load addr */ uint32_t ramdisk_size; /* size in bytes */ uint32_t ramdisk_addr; /* physical load addr */ uint32_t second_size; /* size in bytes */ uint32_t second_addr; /* physical load addr */ } __attribute__((packed)); struct boot_img_hdr_v0 : public boot_img_hdr_v0_common { uint32_t tags_addr; /* physical addr for kernel tags */ // In AOSP headers, this field is used for page size. // For Samsung PXA headers, the use of this field is unknown; // however, its value is something unrealistic to be treated as page size. // We use this fact to determine whether this is an AOSP or PXA header. union { uint32_t unknown; uint32_t page_size; /* flash page size we assume */ }; // In header v1, this field is used for header version // However, on some devices like Samsung, this field is used to store DTB // We treat this field differently based on its value union { uint32_t header_version; /* the version of the header */ uint32_t extra_size; /* extra blob size in bytes */ }; // Operating system version and security patch level. // For version "A.B.C" and patch level "Y-M-D": // (7 bits for each of A, B, C; 7 bits for (Y-2000), 4 bits for M) // os_version = A[31:25] B[24:18] C[17:11] (Y-2000)[10:4] M[3:0] uint32_t os_version; char name[BOOT_NAME_SIZE]; /* asciiz product name */ char cmdline[BOOT_ARGS_SIZE]; char id[BOOT_ID_SIZE]; /* timestamp / checksum / sha1 / etc */ // Supplemental command line data; kept here to maintain // binary compatibility with older versions of mkbootimg. char extra_cmdline[BOOT_EXTRA_ARGS_SIZE]; } __attribute__((packed)); struct boot_img_hdr_v1 : public boot_img_hdr_v0 { uint32_t recovery_dtbo_size; /* size in bytes for recovery DTBO/ACPIO image */ uint64_t recovery_dtbo_offset; /* offset to recovery dtbo/acpio in boot image */ uint32_t header_size; } __attribute__((packed)); struct boot_img_hdr_v2 : public boot_img_hdr_v1 { uint32_t dtb_size; /* size in bytes for DTB image */ uint64_t dtb_addr; /* physical load address for DTB image */ } __attribute__((packed)); // Special Samsung header struct boot_img_hdr_pxa : public boot_img_hdr_v0_common { uint32_t extra_size; /* extra blob size in bytes */ uint32_t unknown; uint32_t tags_addr; /* physical addr for kernel tags */ uint32_t page_size; /* flash page size we assume */ char name[24]; /* asciiz product name */ char cmdline[BOOT_ARGS_SIZE]; char id[BOOT_ID_SIZE]; /* timestamp / checksum / sha1 / etc */ char extra_cmdline[BOOT_EXTRA_ARGS_SIZE]; } __attribute__((packed)); /* * When the boot image header has a version of 3 - 4, the structure of the boot * image is as follows: * * +---------------------+ * | boot header | 4096 bytes * +---------------------+ * | kernel | m pages * +---------------------+ * | ramdisk | n pages * +---------------------+ * | boot signature | g pages * +---------------------+ * * m = (kernel_size + 4096 - 1) / 4096 * n = (ramdisk_size + 4096 - 1) / 4096 * g = (signature_size + 4096 - 1) / 4096 * * Page size is fixed at 4096 bytes. * * The structure of the vendor boot image is as follows: * * +------------------------+ * | vendor boot header | o pages * +------------------------+ * | vendor ramdisk section | p pages * +------------------------+ * | dtb | q pages * +------------------------+ * | vendor ramdisk table | r pages * +------------------------+ * | bootconfig | s pages * +------------------------+ * * o = (2128 + page_size - 1) / page_size * p = (vendor_ramdisk_size + page_size - 1) / page_size * q = (dtb_size + page_size - 1) / page_size * r = (vendor_ramdisk_table_size + page_size - 1) / page_size * s = (vendor_bootconfig_size + page_size - 1) / page_size * * Note that in version 4 of the vendor boot image, multiple vendor ramdisks can * be included in the vendor boot image. The bootloader can select a subset of * ramdisks to load at runtime. To help the bootloader select the ramdisks, each * ramdisk is tagged with a type tag and a set of hardware identifiers * describing the board, soc or platform that this ramdisk is intended for. * * The vendor ramdisk section is consist of multiple ramdisk images concatenated * one after another, and vendor_ramdisk_size is the size of the section, which * is the total size of all the ramdisks included in the vendor boot image. * * The vendor ramdisk table holds the size, offset, type, name and hardware * identifiers of each ramdisk. The type field denotes the type of its content. * The vendor ramdisk names are unique. The hardware identifiers are specified * in the board_id field in each table entry. The board_id field is consist of a * vector of unsigned integer words, and the encoding scheme is defined by the * hardware vendor. * * For the different type of ramdisks, there are: * - VENDOR_RAMDISK_TYPE_NONE indicates the value is unspecified. * - VENDOR_RAMDISK_TYPE_PLATFORM ramdisks contain platform specific bits, so * the bootloader should always load these into memory. * - VENDOR_RAMDISK_TYPE_RECOVERY ramdisks contain recovery resources, so * the bootloader should load these when booting into recovery. * - VENDOR_RAMDISK_TYPE_DLKM ramdisks contain dynamic loadable kernel * modules. * * Version 4 of the vendor boot image also adds a bootconfig section to the end * of the image. This section contains Boot Configuration parameters known at * build time. The bootloader is responsible for placing this section directly * after the generic ramdisk, followed by the bootconfig trailer, before * entering the kernel. */ struct boot_img_hdr_v3 { uint8_t magic[BOOT_MAGIC_SIZE]; uint32_t kernel_size; /* size in bytes */ uint32_t ramdisk_size; /* size in bytes */ uint32_t os_version; uint32_t header_size; uint32_t reserved[4]; uint32_t header_version; char cmdline[BOOT_ARGS_SIZE + BOOT_EXTRA_ARGS_SIZE]; } __attribute__((packed)); struct boot_img_hdr_vnd_v3 { // Must be VENDOR_BOOT_MAGIC. uint8_t magic[BOOT_MAGIC_SIZE]; // Version of the vendor boot image header. uint32_t header_version; uint32_t page_size; /* flash page size we assume */ uint32_t kernel_addr; /* physical load addr */ uint32_t ramdisk_addr; /* physical load addr */ uint32_t ramdisk_size; /* size in bytes */ char cmdline[VENDOR_BOOT_ARGS_SIZE]; uint32_t tags_addr; /* physical addr for kernel tags (if required) */ char name[BOOT_NAME_SIZE]; /* asciiz product name */ uint32_t header_size; uint32_t dtb_size; /* size in bytes for DTB image */ uint64_t dtb_addr; /* physical load address for DTB image */ } __attribute__((packed)); struct boot_img_hdr_v4 : public boot_img_hdr_v3 { uint32_t signature_size; /* size in bytes */ } __attribute__((packed)); struct boot_img_hdr_vnd_v4 : public boot_img_hdr_vnd_v3 { uint32_t vendor_ramdisk_table_size; /* size in bytes for the vendor ramdisk table */ uint32_t vendor_ramdisk_table_entry_num; /* number of entries in the vendor ramdisk table */ uint32_t vendor_ramdisk_table_entry_size; /* size in bytes for a vendor ramdisk table entry */ uint32_t bootconfig_size; /* size in bytes for the bootconfig section */ } __attribute__((packed)); struct vendor_ramdisk_table_entry_v4 { uint32_t ramdisk_size; /* size in bytes for the ramdisk image */ uint32_t ramdisk_offset; /* offset to the ramdisk image in vendor ramdisk section */ uint32_t ramdisk_type; /* type of the ramdisk */ char ramdisk_name[VENDOR_RAMDISK_NAME_SIZE]; /* asciiz ramdisk name */ // Hardware identifiers describing the board, soc or platform which this // ramdisk is intended to be loaded on. uint32_t board_id[VENDOR_RAMDISK_TABLE_ENTRY_BOARD_ID_SIZE]; } __attribute__((packed)); /******************************* * Polymorphic Universal Header *******************************/ #define decl_val(name, len) \ virtual uint##len##_t name() const { return 0; } #define decl_var(name, len) \ virtual uint##len##_t &name() { return j##len(); } \ decl_val(name, len) #define decl_str(name) \ virtual char *name() { return nullptr; } \ virtual const char *name() const { return nullptr; } struct dyn_img_hdr { virtual bool is_vendor() const = 0; // Standard entries decl_var(kernel_size, 32) decl_var(ramdisk_size, 32) decl_var(second_size, 32) decl_val(page_size, 32) decl_val(header_version, 32) decl_var(extra_size, 32) decl_var(os_version, 32) decl_str(name) decl_str(cmdline) decl_str(id) decl_str(extra_cmdline) // v1/v2 specific decl_var(recovery_dtbo_size, 32) decl_var(recovery_dtbo_offset, 64) decl_var(header_size, 32) decl_var(dtb_size, 32) // v4 specific decl_val(signature_size, 32) // v4 vendor specific decl_val(vendor_ramdisk_table_size, 32) decl_val(vendor_ramdisk_table_entry_num, 32) decl_val(vendor_ramdisk_table_entry_size, 32) decl_var(bootconfig_size, 32) virtual ~dyn_img_hdr() { free(raw); } virtual size_t hdr_size() const = 0; virtual size_t hdr_space() const { return page_size(); } virtual dyn_img_hdr *clone() const = 0; const void *raw_hdr() const { return raw; } void print() const; void dump_hdr_file() const; void load_hdr_file(); protected: union { boot_img_hdr_v2 *v2_hdr; /* AOSP v2 header */ boot_img_hdr_v4 *v4_hdr; /* AOSP v4 header */ boot_img_hdr_vnd_v4 *v4_vnd; /* AOSP vendor v4 header */ boot_img_hdr_pxa *hdr_pxa; /* Samsung PXA header */ void *raw; /* Raw pointer */ }; static uint32_t &j32() { _j32 = 0; return _j32; } static uint64_t &j64() { _j64 = 0; return _j64; } private: // Junk for references inline static uint32_t _j32 = 0; inline static uint64_t _j64 = 0; }; #undef decl_var #undef decl_val #undef decl_str #define __impl_cls(name, hdr) \ protected: name() = default; \ public: \ name(const void *ptr) { \ raw = malloc(sizeof(hdr)); \ memcpy(raw, ptr, sizeof(hdr)); \ } \ size_t hdr_size() const override { \ return sizeof(hdr); \ } \ dyn_img_hdr *clone() const override { \ auto p = new name(raw); \ return p; \ }; #define __impl_val(name, hdr_name) \ decltype(std::declval<const dyn_img_hdr>().name()) name() const override { return hdr_name->name; } #define __impl_var(name, hdr_name) \ decltype(std::declval<dyn_img_hdr>().name()) name() override { return hdr_name->name; } \ __impl_val(name, hdr_name) #define impl_cls(ver) __impl_cls(dyn_img_##ver, boot_img_hdr_##ver) #define impl_val(name) __impl_val(name, v2_hdr) #define impl_var(name) __impl_var(name, v2_hdr) struct dyn_img_hdr_boot : public dyn_img_hdr { bool is_vendor() const final { return false; } }; struct dyn_img_common : public dyn_img_hdr_boot { impl_var(kernel_size) impl_var(ramdisk_size) impl_var(second_size) }; struct dyn_img_v0 : public dyn_img_common { impl_cls(v0) impl_val(page_size) impl_var(extra_size) impl_var(os_version) impl_var(name) impl_var(cmdline) impl_var(id) impl_var(extra_cmdline) }; struct dyn_img_v1 : public dyn_img_v0 { impl_cls(v1) impl_val(header_version) impl_var(recovery_dtbo_size) impl_var(recovery_dtbo_offset) impl_var(header_size) uint32_t &extra_size() override { return j32(); } uint32_t extra_size() const override { return 0; } }; struct dyn_img_v2 : public dyn_img_v1 { impl_cls(v2) impl_var(dtb_size) }; #undef impl_val #undef impl_var #define impl_val(name) __impl_val(name, hdr_pxa) #define impl_var(name) __impl_var(name, hdr_pxa) struct dyn_img_pxa : public dyn_img_common { impl_cls(pxa) impl_var(extra_size) impl_val(page_size) impl_var(name) impl_var(cmdline) impl_var(id) impl_var(extra_cmdline) }; #undef impl_val #undef impl_var #define impl_val(name) __impl_val(name, v4_hdr) #define impl_var(name) __impl_var(name, v4_hdr) struct dyn_img_v3 : public dyn_img_hdr_boot { impl_cls(v3) impl_var(kernel_size) impl_var(ramdisk_size) impl_var(os_version) impl_var(header_size) impl_val(header_version) impl_var(cmdline) // Make API compatible uint32_t page_size() const override { return 4096; } char *extra_cmdline() override { return &v4_hdr->cmdline[BOOT_ARGS_SIZE]; } const char *extra_cmdline() const override { return &v4_hdr->cmdline[BOOT_ARGS_SIZE]; } }; struct dyn_img_v4 : public dyn_img_v3 { impl_cls(v4) impl_val(signature_size) }; struct dyn_img_hdr_vendor : public dyn_img_hdr { bool is_vendor() const final { return true; } }; #undef impl_val #undef impl_var #define impl_val(name) __impl_val(name, v4_vnd) #define impl_var(name) __impl_var(name, v4_vnd) struct dyn_img_vnd_v3 : public dyn_img_hdr_vendor { impl_cls(vnd_v3) impl_val(header_version) impl_val(page_size) impl_var(ramdisk_size) impl_var(cmdline) impl_var(name) impl_var(header_size) impl_var(dtb_size) size_t hdr_space() const override { return align_to(hdr_size(), page_size()); } // Make API compatible char *extra_cmdline() override { return &v4_vnd->cmdline[BOOT_ARGS_SIZE]; } const char *extra_cmdline() const override { return &v4_vnd->cmdline[BOOT_ARGS_SIZE]; } }; struct dyn_img_vnd_v4 : public dyn_img_vnd_v3 { impl_cls(vnd_v4) impl_val(vendor_ramdisk_table_size) impl_val(vendor_ramdisk_table_entry_num) impl_val(vendor_ramdisk_table_entry_size) impl_var(bootconfig_size) }; #undef __impl_cls #undef __impl_val #undef __impl_var #undef impl_cls #undef impl_val #undef impl_var /****************** * Full Boot Image ******************/ enum { MTK_KERNEL, MTK_RAMDISK, CHROMEOS_FLAG, DHTB_FLAG, SEANDROID_FLAG, LG_BUMP_FLAG, SHA256_FLAG, BLOB_FLAG, NOOKHD_FLAG, ACCLAIM_FLAG, AMONET_FLAG, AVB1_SIGNED_FLAG, AVB_FLAG, ZIMAGE_KERNEL, BOOT_FLAGS_MAX }; struct boot_img { // Memory map of the whole image const mmap_data map; // Android image header const dyn_img_hdr *hdr = nullptr; // Flags to indicate the state of current boot image std::bitset<BOOT_FLAGS_MAX> flags; // The format of kernel, ramdisk and extra format_t k_fmt = UNKNOWN; format_t r_fmt = UNKNOWN; format_t e_fmt = UNKNOWN; /************************************************************* * Following pointers points within the read-only mmap region *************************************************************/ // Layout of the memory mapped region // +---------+ // | head | Vendor specific. Should not exist for standard AOSP boot images. // +---------+ // | payload | The actual entire AOSP boot image, including the boot image header. // +---------+ // | tail | Data after payload. Usually contains signature/AVB information. // +---------+ byte_view payload; byte_view tail; // MTK headers const mtk_hdr *k_hdr = nullptr; const mtk_hdr *r_hdr = nullptr; // The pointers/values after parse_image // +---------------+ // | z_hdr | z_info.hdr_sz // +---------------+ // | kernel | hdr->kernel_size() // +---------------+ // | z_info.tail | z_info.tail.sz() // +---------------+ const zimage_hdr *z_hdr = nullptr; struct { uint32_t hdr_sz; byte_view tail; } z_info; // AVB structs const AvbFooter *avb_footer = nullptr; const AvbVBMetaImageHeader *vbmeta = nullptr; // Pointers to blocks defined in header const uint8_t *kernel = nullptr; const uint8_t *ramdisk = nullptr; const uint8_t *second = nullptr; const uint8_t *extra = nullptr; const uint8_t *recovery_dtbo = nullptr; const uint8_t *dtb = nullptr; const uint8_t *signature = nullptr; const uint8_t *vendor_ramdisk_table = nullptr; const uint8_t *bootconfig = nullptr; // dtb embedded in kernel byte_view kernel_dtb; // Blocks defined in header but we do not care byte_view ignore; boot_img(const char *); ~boot_img(); bool parse_image(const uint8_t *addr, format_t type); std::pair<const uint8_t *, dyn_img_hdr *> create_hdr(const uint8_t *addr, format_t type); // Rust FFI rust::Slice<const uint8_t> get_payload() const { return payload; } rust::Slice<const uint8_t> get_tail() const { return tail; } bool verify(const char *cert = nullptr) const; };
21,885
C++
.h
573
34.453752
124
0.63175
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
61
compress.hpp
topjohnwu_Magisk/native/src/boot/compress.hpp
#pragma once #include <cxx.h> #include <stream.hpp> #include "format.hpp" out_strm_ptr get_encoder(format_t type, out_strm_ptr &&base); out_strm_ptr get_decoder(format_t type, out_strm_ptr &&base); void compress(const char *method, const char *infile, const char *outfile); void decompress(char *infile, const char *outfile); bool decompress(rust::Slice<const uint8_t> buf, int fd); bool xz(rust::Slice<const uint8_t> buf, rust::Vec<uint8_t> &out); bool unxz(rust::Slice<const uint8_t> buf, rust::Vec<uint8_t> &out);
520
C++
.h
11
46
75
0.741107
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
62
init.hpp
topjohnwu_Magisk/native/src/init/init.hpp
#include <base.hpp> #include <stream.hpp> #include "init-rs.hpp" using kv_pairs = std::vector<std::pair<std::string, std::string>>; struct BootConfig { bool skip_initramfs; bool force_normal_boot; bool rootwait; bool emulator; char slot[3]; char dt_dir[64]; char fstab_suffix[32]; char hardware[32]; char hardware_plat[32]; void set(const kv_pairs &); void print(); }; #define DEFAULT_DT_DIR "/proc/device-tree/firmware/android" #define INIT_PATH "/system/bin/init" #define REDIR_PATH "/data/magiskinit" extern std::vector<std::string> mount_list; int magisk_proxy_main(int argc, char *argv[]); bool unxz(out_stream &strm, rust::Slice<const uint8_t> bytes); void load_kernel_info(BootConfig *config); kv_pairs load_partition_map(); bool check_two_stage(); const char *backup_init(); void restore_ramdisk_init(); /*************** * Base classes ***************/ class BaseInit { protected: BootConfig *config = nullptr; char **argv = nullptr; [[noreturn]] void exec_init(); void prepare_data(); public: BaseInit(char *argv[], BootConfig *config = nullptr) : config(config), argv(argv) {} virtual ~BaseInit() = default; virtual void start() = 0; }; class MagiskInit : public BaseInit { private: std::string preinit_dev; void parse_config_file(); void patch_sepolicy(const char *in, const char *out); bool hijack_sepolicy(); void setup_tmp(const char *path); protected: void patch_rw_root(); void patch_ro_root(); public: using BaseInit::BaseInit; }; /*************** * 2 Stage Init ***************/ class FirstStageInit : public BaseInit { private: void prepare(); public: FirstStageInit(char *argv[], BootConfig *config) : BaseInit(argv, config) { LOGD("%s\n", __FUNCTION__); }; void start() override { prepare(); exec_init(); } }; class SecondStageInit : public MagiskInit { private: bool prepare(); public: SecondStageInit(char *argv[]) : MagiskInit(argv) { LOGD("%s\n", __FUNCTION__); }; void start() override { bool is_rootfs = prepare(); if (is_rootfs) patch_rw_root(); else patch_ro_root(); exec_init(); } }; /************* * Legacy SAR *************/ class LegacySARInit : public MagiskInit { private: bool mount_system_root(); void first_stage_prep(); public: LegacySARInit(char *argv[], BootConfig *config) : MagiskInit(argv, config) { LOGD("%s\n", __FUNCTION__); }; void start() override { prepare_data(); bool is_two_stage = mount_system_root(); if (is_two_stage) first_stage_prep(); else patch_ro_root(); exec_init(); } }; /************ * Initramfs ************/ class RootFSInit : public MagiskInit { private: void prepare(); public: RootFSInit(char *argv[], BootConfig *config) : MagiskInit(argv, config) { LOGD("%s\n", __FUNCTION__); } void start() override { prepare(); patch_rw_root(); exec_init(); } };
3,129
C++
.h
123
21.121951
88
0.613865
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
63
config.h
topjohnwu_Magisk/native/src/external/xz_config/config.h
/* config.h. Generated from config.h.in by configure. */ /* config.h.in. Generated from configure.ac by autoheader. */ /* Define if building universal (internal helper macro) */ /* #undef AC_APPLE_UNIVERSAL_BUILD */ /* How many MiB of RAM to assume if the real amount cannot be determined. */ #define ASSUME_RAM 128 /* Define to 1 if translation of program messages to the user's native language is requested. */ /* #undef ENABLE_NLS */ /* Define to 1 if bswap_16 is available. */ #define HAVE_BSWAP_16 1 /* Define to 1 if bswap_32 is available. */ #define HAVE_BSWAP_32 1 /* Define to 1 if bswap_64 is available. */ #define HAVE_BSWAP_64 1 /* Define to 1 if you have the <byteswap.h> header file. */ #define HAVE_BYTESWAP_H 1 /* Define to 1 if Capsicum is available. */ /* #undef HAVE_CAPSICUM */ /* Define to 1 if the system has the type `CC_SHA256_CTX'. */ /* #undef HAVE_CC_SHA256_CTX */ /* Define to 1 if you have the `CC_SHA256_Init' function. */ /* #undef HAVE_CC_SHA256_INIT */ /* Define to 1 if you have the MacOS X function CFLocaleCopyCurrent in the CoreFoundation framework. */ /* #undef HAVE_CFLOCALECOPYCURRENT */ /* Define to 1 if you have the MacOS X function CFPreferencesCopyAppValue in the CoreFoundation framework. */ /* #undef HAVE_CFPREFERENCESCOPYAPPVALUE */ /* Define to 1 if crc32 integrity check is enabled. */ #define HAVE_CHECK_CRC32 1 /* Define to 1 if crc64 integrity check is enabled. */ #define HAVE_CHECK_CRC64 1 /* Define to 1 if sha256 integrity check is enabled. */ #define HAVE_CHECK_SHA256 1 /* Define to 1 if you have the `clock_gettime' function. */ #define HAVE_CLOCK_GETTIME 1 /* Define to 1 if you have the <CommonCrypto/CommonDigest.h> header file. */ /* #undef HAVE_COMMONCRYPTO_COMMONDIGEST_H */ /* Define if the GNU dcgettext() function is already present or preinstalled. */ /* #undef HAVE_DCGETTEXT */ /* Define to 1 if you have the declaration of `CLOCK_MONOTONIC', and to 0 if you don't. */ #define HAVE_DECL_CLOCK_MONOTONIC 1 /* Define to 1 if you have the declaration of `program_invocation_name', and to 0 if you don't. */ #define HAVE_DECL_PROGRAM_INVOCATION_NAME 0 /* Define to 1 if any of HAVE_DECODER_foo have been defined. */ #define HAVE_DECODERS 1 /* Define to 1 if arm decoder is enabled. */ #define HAVE_DECODER_ARM 1 /* Define to 1 if armthumb decoder is enabled. */ #define HAVE_DECODER_ARMTHUMB 1 /* Define to 1 if delta decoder is enabled. */ #define HAVE_DECODER_DELTA 1 /* Define to 1 if ia64 decoder is enabled. */ #define HAVE_DECODER_IA64 1 /* Define to 1 if lzma1 decoder is enabled. */ #define HAVE_DECODER_LZMA1 1 /* Define to 1 if lzma2 decoder is enabled. */ #define HAVE_DECODER_LZMA2 1 /* Define to 1 if powerpc decoder is enabled. */ #define HAVE_DECODER_POWERPC 1 /* Define to 1 if sparc decoder is enabled. */ #define HAVE_DECODER_SPARC 1 /* Define to 1 if x86 decoder is enabled. */ #define HAVE_DECODER_X86 1 /* Define to 1 if you have the <dlfcn.h> header file. */ #define HAVE_DLFCN_H 1 /* Define to 1 if any of HAVE_ENCODER_foo have been defined. */ #define HAVE_ENCODERS 1 /* Define to 1 if arm encoder is enabled. */ #define HAVE_ENCODER_ARM 1 /* Define to 1 if armthumb encoder is enabled. */ #define HAVE_ENCODER_ARMTHUMB 1 /* Define to 1 if delta encoder is enabled. */ #define HAVE_ENCODER_DELTA 1 /* Define to 1 if ia64 encoder is enabled. */ #define HAVE_ENCODER_IA64 1 /* Define to 1 if lzma1 encoder is enabled. */ #define HAVE_ENCODER_LZMA1 1 /* Define to 1 if lzma2 encoder is enabled. */ #define HAVE_ENCODER_LZMA2 1 /* Define to 1 if powerpc encoder is enabled. */ #define HAVE_ENCODER_POWERPC 1 /* Define to 1 if sparc encoder is enabled. */ #define HAVE_ENCODER_SPARC 1 /* Define to 1 if x86 encoder is enabled. */ #define HAVE_ENCODER_X86 1 /* Define to 1 if you have the <fcntl.h> header file. */ #define HAVE_FCNTL_H 1 /* Define to 1 if you have the `futimens' function. */ #define HAVE_FUTIMENS 1 /* Define to 1 if you have the `futimes' function. */ /* #undef HAVE_FUTIMES */ /* Define to 1 if you have the `futimesat' function. */ /* #undef HAVE_FUTIMESAT */ /* Define to 1 if you have the <getopt.h> header file. */ #define HAVE_GETOPT_H 1 /* Define to 1 if you have the `getopt_long' function. */ #define HAVE_GETOPT_LONG 1 /* Define if the GNU gettext() function is already present or preinstalled. */ /* #undef HAVE_GETTEXT */ /* Define if you have the iconv() function and it works. */ /* #undef HAVE_ICONV */ /* Define to 1 if you have the <immintrin.h> header file. */ /* #undef HAVE_IMMINTRIN_H */ /* Define to 1 if you have the <inttypes.h> header file. */ #define HAVE_INTTYPES_H 1 /* Define to 1 if you have the <limits.h> header file. */ #define HAVE_LIMITS_H 1 /* Define to 1 if mbrtowc and mbstate_t are properly declared. */ #define HAVE_MBRTOWC 1 /* Define to 1 if you have the <memory.h> header file. */ #define HAVE_MEMORY_H 1 /* Define to 1 to enable bt2 match finder. */ #define HAVE_MF_BT2 1 /* Define to 1 to enable bt3 match finder. */ #define HAVE_MF_BT3 1 /* Define to 1 to enable bt4 match finder. */ #define HAVE_MF_BT4 1 /* Define to 1 to enable hc3 match finder. */ #define HAVE_MF_HC3 1 /* Define to 1 to enable hc4 match finder. */ #define HAVE_MF_HC4 1 /* Define to 1 if you have the <minix/sha2.h> header file. */ /* #undef HAVE_MINIX_SHA2_H */ /* Define to 1 if getopt.h declares extern int optreset. */ #define HAVE_OPTRESET 1 /* Define to 1 if you have the `posix_fadvise' function. */ #define HAVE_POSIX_FADVISE 1 /* Define to 1 if you have the `pthread_condattr_setclock' function. */ #define HAVE_PTHREAD_CONDATTR_SETCLOCK 1 /* Have PTHREAD_PRIO_INHERIT. */ /* #undef HAVE_PTHREAD_PRIO_INHERIT */ /* Define to 1 if you have the `SHA256Init' function. */ /* #undef HAVE_SHA256INIT */ /* Define to 1 if the system has the type `SHA256_CTX'. */ /* #undef HAVE_SHA256_CTX */ /* Define to 1 if you have the <sha256.h> header file. */ /* #undef HAVE_SHA256_H */ /* Define to 1 if you have the `SHA256_Init' function. */ /* #undef HAVE_SHA256_INIT */ /* Define to 1 if the system has the type `SHA2_CTX'. */ /* #undef HAVE_SHA2_CTX */ /* Define to 1 if you have the <sha2.h> header file. */ /* #undef HAVE_SHA2_H */ /* Define to 1 if optimizing for size. */ /* #undef HAVE_SMALL */ /* Define to 1 if stdbool.h conforms to C99. */ #define HAVE_STDBOOL_H 1 /* Define to 1 if you have the <stdint.h> header file. */ #define HAVE_STDINT_H 1 /* Define to 1 if you have the <stdlib.h> header file. */ #define HAVE_STDLIB_H 1 /* Define to 1 if you have the <strings.h> header file. */ #define HAVE_STRINGS_H 1 /* Define to 1 if you have the <string.h> header file. */ #define HAVE_STRING_H 1 /* Define to 1 if `st_atimensec' is a member of `struct stat'. */ #define HAVE_STRUCT_STAT_ST_ATIMENSEC 1 /* Define to 1 if `st_atimespec.tv_nsec' is a member of `struct stat'. */ /* #undef HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC */ /* Define to 1 if `st_atim.st__tim.tv_nsec' is a member of `struct stat'. */ /* #undef HAVE_STRUCT_STAT_ST_ATIM_ST__TIM_TV_NSEC */ /* Define to 1 if `st_atim.tv_nsec' is a member of `struct stat'. */ /* #undef HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC */ /* Define to 1 if `st_uatime' is a member of `struct stat'. */ /* #undef HAVE_STRUCT_STAT_ST_UATIME */ /* Define to 1 if you have the <sys/byteorder.h> header file. */ /* #undef HAVE_SYS_BYTEORDER_H */ /* Define to 1 if you have the <sys/capsicum.h> header file. */ /* #undef HAVE_SYS_CAPSICUM_H */ /* Define to 1 if you have the <sys/endian.h> header file. */ /* #undef HAVE_SYS_ENDIAN_H */ /* Define to 1 if you have the <sys/param.h> header file. */ #define HAVE_SYS_PARAM_H 1 /* Define to 1 if you have the <sys/stat.h> header file. */ #define HAVE_SYS_STAT_H 1 /* Define to 1 if you have the <sys/time.h> header file. */ #define HAVE_SYS_TIME_H 1 /* Define to 1 if you have the <sys/types.h> header file. */ #define HAVE_SYS_TYPES_H 1 /* Define to 1 if the system has the type `uintptr_t'. */ #define HAVE_UINTPTR_T 1 /* Define to 1 if you have the <unistd.h> header file. */ #define HAVE_UNISTD_H 1 /* Define to 1 if you have the `utime' function. */ /* #undef HAVE_UTIME */ /* Define to 1 if you have the `utimes' function. */ /* #undef HAVE_UTIMES */ /* Define to 1 or 0, depending whether the compiler supports simple visibility declarations. */ #define HAVE_VISIBILITY 1 /* Define to 1 if you have the `wcwidth' function. */ #define HAVE_WCWIDTH 1 /* Define to 1 if the system has the type `_Bool'. */ #define HAVE__BOOL 1 /* Define to 1 if _mm_movemask_epi8 is available. */ /* #undef HAVE__MM_MOVEMASK_EPI8 */ /* Define to the sub-directory where libtool stores uninstalled libraries. */ #define LT_OBJDIR ".libs/" /* Define to 1 when using POSIX threads (pthreads). */ #define MYTHREAD_POSIX 1 /* Define to 1 when using Windows Vista compatible threads. This uses features that are not available on Windows XP. */ /* #undef MYTHREAD_VISTA */ /* Define to 1 when using Windows 95 (and thus XP) compatible threads. This avoids use of features that were added in Windows Vista. */ /* #undef MYTHREAD_WIN95 */ /* Define to 1 to disable debugging code. */ #define NDEBUG 1 /* Name of package */ #define PACKAGE "xz" /* Define to the address where bug reports for this package should be sent. */ #define PACKAGE_BUGREPORT "lasse.collin@tukaani.org" /* Define to the full name of this package. */ #define PACKAGE_NAME "XZ Utils" /* Define to the full name and version of this package. */ #define PACKAGE_STRING "XZ Utils 5.3.0alpha" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "xz" /* Define to the home page for this package. */ #define PACKAGE_URL "http://tukaani.org/xz/" /* Define to the version of this package. */ #define PACKAGE_VERSION "5.3.0alpha" /* Define to necessary symbol if this constant uses a non-standard name on your system. */ /* #undef PTHREAD_CREATE_JOINABLE */ /* The size of `size_t', as computed by sizeof. */ #define SIZEOF_SIZE_T 4 /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1 /* Define to 1 if the number of available CPU cores can be detected with cpuset(2). */ /* #undef TUKLIB_CPUCORES_CPUSET */ /* Define to 1 if the number of available CPU cores can be detected with pstat_getdynamic(). */ /* #undef TUKLIB_CPUCORES_PSTAT_GETDYNAMIC */ /* Define to 1 if the number of available CPU cores can be detected with sysconf(_SC_NPROCESSORS_ONLN) or sysconf(_SC_NPROC_ONLN). */ #define TUKLIB_CPUCORES_SYSCONF 1 /* Define to 1 if the number of available CPU cores can be detected with sysctl(). */ /* #undef TUKLIB_CPUCORES_SYSCTL */ /* Define to 1 if the system supports fast unaligned access to 16-bit and 32-bit integers. */ /* #undef TUKLIB_FAST_UNALIGNED_ACCESS */ /* Define to 1 if the amount of physical memory can be detected with _system_configuration.physmem. */ /* #undef TUKLIB_PHYSMEM_AIX */ /* Define to 1 if the amount of physical memory can be detected with getinvent_r(). */ /* #undef TUKLIB_PHYSMEM_GETINVENT_R */ /* Define to 1 if the amount of physical memory can be detected with getsysinfo(). */ /* #undef TUKLIB_PHYSMEM_GETSYSINFO */ /* Define to 1 if the amount of physical memory can be detected with pstat_getstatic(). */ /* #undef TUKLIB_PHYSMEM_PSTAT_GETSTATIC */ /* Define to 1 if the amount of physical memory can be detected with sysconf(_SC_PAGESIZE) and sysconf(_SC_PHYS_PAGES). */ #define TUKLIB_PHYSMEM_SYSCONF 1 /* Define to 1 if the amount of physical memory can be detected with sysctl(). */ /* #undef TUKLIB_PHYSMEM_SYSCTL */ /* Define to 1 if the amount of physical memory can be detected with Linux sysinfo(). */ /* #undef TUKLIB_PHYSMEM_SYSINFO */ /* Enable extensions on AIX 3, Interix. */ #ifndef _ALL_SOURCE # define _ALL_SOURCE 1 #endif /* Enable GNU extensions on systems that have them. */ #ifndef _GNU_SOURCE # define _GNU_SOURCE 1 #endif /* Enable threading extensions on Solaris. */ #ifndef _POSIX_PTHREAD_SEMANTICS # define _POSIX_PTHREAD_SEMANTICS 1 #endif /* Enable extensions on HP NonStop. */ #ifndef _TANDEM_SOURCE # define _TANDEM_SOURCE 1 #endif /* Enable general extensions on Solaris. */ #ifndef __EXTENSIONS__ # define __EXTENSIONS__ 1 #endif /* Version number of package */ #define VERSION "5.3.0alpha" /* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most significant byte first (like Motorola and SPARC, unlike Intel). */ #if defined AC_APPLE_UNIVERSAL_BUILD # if defined __BIG_ENDIAN__ # define WORDS_BIGENDIAN 1 # endif #else # ifndef WORDS_BIGENDIAN /* # undef WORDS_BIGENDIAN */ # endif #endif /* Enable large inode numbers on Mac OS X 10.5. */ #ifndef _DARWIN_USE_64_BIT_INODE # define _DARWIN_USE_64_BIT_INODE 1 #endif /* Number of bits in a file offset, on hosts where this is settable. */ /* #undef _FILE_OFFSET_BITS */ /* Define for large files, on AIX-style hosts. */ /* #undef _LARGE_FILES */ /* Define to 1 if on MINIX. */ /* #undef _MINIX */ /* Define to 2 if the system does not provide POSIX.1 features except with this defined. */ /* #undef _POSIX_1_SOURCE */ /* Define to 1 if you need to in order for `stat' and other things to work. */ /* #undef _POSIX_SOURCE */ /* Define for Solaris 2.5.1 so the uint32_t typedef from <sys/synch.h>, <pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the #define below would cause a syntax error. */ /* #undef _UINT32_T */ /* Define for Solaris 2.5.1 so the uint64_t typedef from <sys/synch.h>, <pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the #define below would cause a syntax error. */ /* #undef _UINT64_T */ /* Define for Solaris 2.5.1 so the uint8_t typedef from <sys/synch.h>, <pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the #define below would cause a syntax error. */ /* #undef _UINT8_T */ /* Define to rpl_ if the getopt replacement functions and variables should be used. */ /* #undef __GETOPT_PREFIX */ /* Define to the type of a signed integer type of width exactly 32 bits if such a type exists and the standard includes do not define it. */ /* #undef int32_t */ /* Define to the type of a signed integer type of width exactly 64 bits if such a type exists and the standard includes do not define it. */ /* #undef int64_t */ /* Define to the type of an unsigned integer type of width exactly 16 bits if such a type exists and the standard includes do not define it. */ /* #undef uint16_t */ /* Define to the type of an unsigned integer type of width exactly 32 bits if such a type exists and the standard includes do not define it. */ /* #undef uint32_t */ /* Define to the type of an unsigned integer type of width exactly 64 bits if such a type exists and the standard includes do not define it. */ /* #undef uint64_t */ /* Define to the type of an unsigned integer type of width exactly 8 bits if such a type exists and the standard includes do not define it. */ /* #undef uint8_t */ /* Define to the type of an unsigned integer type wide enough to hold a pointer, if such a type exists, and if the system does not define it. */ /* #undef uintptr_t */
15,262
C++
.h
354
41.384181
78
0.719453
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
64
xz_lzma2.h
topjohnwu_Magisk/native/src/external/xz-embedded/xz_lzma2.h
/* * LZMA2 definitions * * Authors: Lasse Collin <lasse.collin@tukaani.org> * Igor Pavlov <http://7-zip.org/> * * This file has been put into the public domain. * You can do whatever you want with this file. */ #ifndef XZ_LZMA2_H #define XZ_LZMA2_H /* Range coder constants */ #define RC_SHIFT_BITS 8 #define RC_TOP_BITS 24 #define RC_TOP_VALUE (1 << RC_TOP_BITS) #define RC_BIT_MODEL_TOTAL_BITS 11 #define RC_BIT_MODEL_TOTAL (1 << RC_BIT_MODEL_TOTAL_BITS) #define RC_MOVE_BITS 5 /* * Maximum number of position states. A position state is the lowest pb * number of bits of the current uncompressed offset. In some places there * are different sets of probabilities for different position states. */ #define POS_STATES_MAX (1 << 4) /* * This enum is used to track which LZMA symbols have occurred most recently * and in which order. This information is used to predict the next symbol. * * Symbols: * - Literal: One 8-bit byte * - Match: Repeat a chunk of data at some distance * - Long repeat: Multi-byte match at a recently seen distance * - Short repeat: One-byte repeat at a recently seen distance * * The symbol names are in from STATE_oldest_older_previous. REP means * either short or long repeated match, and NONLIT means any non-literal. */ enum lzma_state { STATE_LIT_LIT, STATE_MATCH_LIT_LIT, STATE_REP_LIT_LIT, STATE_SHORTREP_LIT_LIT, STATE_MATCH_LIT, STATE_REP_LIT, STATE_SHORTREP_LIT, STATE_LIT_MATCH, STATE_LIT_LONGREP, STATE_LIT_SHORTREP, STATE_NONLIT_MATCH, STATE_NONLIT_REP }; /* Total number of states */ #define STATES 12 /* The lowest 7 states indicate that the previous state was a literal. */ #define LIT_STATES 7 /* Indicate that the latest symbol was a literal. */ static inline void lzma_state_literal(enum lzma_state *state) { if (*state <= STATE_SHORTREP_LIT_LIT) *state = STATE_LIT_LIT; else if (*state <= STATE_LIT_SHORTREP) *state -= 3; else *state -= 6; } /* Indicate that the latest symbol was a match. */ static inline void lzma_state_match(enum lzma_state *state) { *state = *state < LIT_STATES ? STATE_LIT_MATCH : STATE_NONLIT_MATCH; } /* Indicate that the latest state was a long repeated match. */ static inline void lzma_state_long_rep(enum lzma_state *state) { *state = *state < LIT_STATES ? STATE_LIT_LONGREP : STATE_NONLIT_REP; } /* Indicate that the latest symbol was a short match. */ static inline void lzma_state_short_rep(enum lzma_state *state) { *state = *state < LIT_STATES ? STATE_LIT_SHORTREP : STATE_NONLIT_REP; } /* Test if the previous symbol was a literal. */ static inline bool lzma_state_is_literal(enum lzma_state state) { return state < LIT_STATES; } /* Each literal coder is divided in three sections: * - 0x001-0x0FF: Without match byte * - 0x101-0x1FF: With match byte; match bit is 0 * - 0x201-0x2FF: With match byte; match bit is 1 * * Match byte is used when the previous LZMA symbol was something else than * a literal (that is, it was some kind of match). */ #define LITERAL_CODER_SIZE 0x300 /* Maximum number of literal coders */ #define LITERAL_CODERS_MAX (1 << 4) /* Minimum length of a match is two bytes. */ #define MATCH_LEN_MIN 2 /* Match length is encoded with 4, 5, or 10 bits. * * Length Bits * 2-9 4 = Choice=0 + 3 bits * 10-17 5 = Choice=1 + Choice2=0 + 3 bits * 18-273 10 = Choice=1 + Choice2=1 + 8 bits */ #define LEN_LOW_BITS 3 #define LEN_LOW_SYMBOLS (1 << LEN_LOW_BITS) #define LEN_MID_BITS 3 #define LEN_MID_SYMBOLS (1 << LEN_MID_BITS) #define LEN_HIGH_BITS 8 #define LEN_HIGH_SYMBOLS (1 << LEN_HIGH_BITS) #define LEN_SYMBOLS (LEN_LOW_SYMBOLS + LEN_MID_SYMBOLS + LEN_HIGH_SYMBOLS) /* * Maximum length of a match is 273 which is a result of the encoding * described above. */ #define MATCH_LEN_MAX (MATCH_LEN_MIN + LEN_SYMBOLS - 1) /* * Different sets of probabilities are used for match distances that have * very short match length: Lengths of 2, 3, and 4 bytes have a separate * set of probabilities for each length. The matches with longer length * use a shared set of probabilities. */ #define DIST_STATES 4 /* * Get the index of the appropriate probability array for decoding * the distance slot. */ static inline uint32_t lzma_get_dist_state(uint32_t len) { return len < DIST_STATES + MATCH_LEN_MIN ? len - MATCH_LEN_MIN : DIST_STATES - 1; } /* * The highest two bits of a 32-bit match distance are encoded using six bits. * This six-bit value is called a distance slot. This way encoding a 32-bit * value takes 6-36 bits, larger values taking more bits. */ #define DIST_SLOT_BITS 6 #define DIST_SLOTS (1 << DIST_SLOT_BITS) /* Match distances up to 127 are fully encoded using probabilities. Since * the highest two bits (distance slot) are always encoded using six bits, * the distances 0-3 don't need any additional bits to encode, since the * distance slot itself is the same as the actual distance. DIST_MODEL_START * indicates the first distance slot where at least one additional bit is * needed. */ #define DIST_MODEL_START 4 /* * Match distances greater than 127 are encoded in three pieces: * - distance slot: the highest two bits * - direct bits: 2-26 bits below the highest two bits * - alignment bits: four lowest bits * * Direct bits don't use any probabilities. * * The distance slot value of 14 is for distances 128-191. */ #define DIST_MODEL_END 14 /* Distance slots that indicate a distance <= 127. */ #define FULL_DISTANCES_BITS (DIST_MODEL_END / 2) #define FULL_DISTANCES (1 << FULL_DISTANCES_BITS) /* * For match distances greater than 127, only the highest two bits and the * lowest four bits (alignment) is encoded using probabilities. */ #define ALIGN_BITS 4 #define ALIGN_SIZE (1 << ALIGN_BITS) #define ALIGN_MASK (ALIGN_SIZE - 1) /* Total number of all probability variables */ #define PROBS_TOTAL (1846 + LITERAL_CODERS_MAX * LITERAL_CODER_SIZE) /* * LZMA remembers the four most recent match distances. Reusing these * distances tends to take less space than re-encoding the actual * distance value. */ #define REPS 4 #endif
6,199
C++
.h
178
32.61236
78
0.724103
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
65
xz_private.h
topjohnwu_Magisk/native/src/external/xz-embedded/xz_private.h
/* * Private includes and definitions * * Author: Lasse Collin <lasse.collin@tukaani.org> * * This file has been put into the public domain. * You can do whatever you want with this file. */ #ifndef XZ_PRIVATE_H #define XZ_PRIVATE_H #ifdef __KERNEL__ # include <linux/xz.h> # include <linux/kernel.h> # include <asm/unaligned.h> /* XZ_PREBOOT may be defined only via decompress_unxz.c. */ # ifndef XZ_PREBOOT # include <linux/slab.h> # include <linux/vmalloc.h> # include <linux/string.h> # ifdef CONFIG_XZ_DEC_X86 # define XZ_DEC_X86 # endif # ifdef CONFIG_XZ_DEC_POWERPC # define XZ_DEC_POWERPC # endif # ifdef CONFIG_XZ_DEC_IA64 # define XZ_DEC_IA64 # endif # ifdef CONFIG_XZ_DEC_ARM # define XZ_DEC_ARM # endif # ifdef CONFIG_XZ_DEC_ARMTHUMB # define XZ_DEC_ARMTHUMB # endif # ifdef CONFIG_XZ_DEC_SPARC # define XZ_DEC_SPARC # endif # define memeq(a, b, size) (memcmp(a, b, size) == 0) # define memzero(buf, size) memset(buf, 0, size) # endif # define get_le32(p) le32_to_cpup((const uint32_t *)(p)) #else /* * For userspace builds, use a separate header to define the required * macros and functions. This makes it easier to adapt the code into * different environments and avoids clutter in the Linux kernel tree. */ # include "xz_config.h" #endif /* If no specific decoding mode is requested, enable support for all modes. */ #if !defined(XZ_DEC_SINGLE) && !defined(XZ_DEC_PREALLOC) \ && !defined(XZ_DEC_DYNALLOC) # define XZ_DEC_SINGLE # define XZ_DEC_PREALLOC # define XZ_DEC_DYNALLOC #endif /* * The DEC_IS_foo(mode) macros are used in "if" statements. If only some * of the supported modes are enabled, these macros will evaluate to true or * false at compile time and thus allow the compiler to omit unneeded code. */ #ifdef XZ_DEC_SINGLE # define DEC_IS_SINGLE(mode) ((mode) == XZ_SINGLE) #else # define DEC_IS_SINGLE(mode) (false) #endif #ifdef XZ_DEC_PREALLOC # define DEC_IS_PREALLOC(mode) ((mode) == XZ_PREALLOC) #else # define DEC_IS_PREALLOC(mode) (false) #endif #ifdef XZ_DEC_DYNALLOC # define DEC_IS_DYNALLOC(mode) ((mode) == XZ_DYNALLOC) #else # define DEC_IS_DYNALLOC(mode) (false) #endif #if !defined(XZ_DEC_SINGLE) # define DEC_IS_MULTI(mode) (true) #elif defined(XZ_DEC_PREALLOC) || defined(XZ_DEC_DYNALLOC) # define DEC_IS_MULTI(mode) ((mode) != XZ_SINGLE) #else # define DEC_IS_MULTI(mode) (false) #endif /* * If any of the BCJ filter decoders are wanted, define XZ_DEC_BCJ. * XZ_DEC_BCJ is used to enable generic support for BCJ decoders. */ #ifndef XZ_DEC_BCJ # if defined(XZ_DEC_X86) || defined(XZ_DEC_POWERPC) \ || defined(XZ_DEC_IA64) || defined(XZ_DEC_ARM) \ || defined(XZ_DEC_ARM) || defined(XZ_DEC_ARMTHUMB) \ || defined(XZ_DEC_SPARC) # define XZ_DEC_BCJ # endif #endif /* * Allocate memory for LZMA2 decoder. xz_dec_lzma2_reset() must be used * before calling xz_dec_lzma2_run(). */ XZ_EXTERN struct xz_dec_lzma2 *xz_dec_lzma2_create(enum xz_mode mode, uint32_t dict_max); /* * Decode the LZMA2 properties (one byte) and reset the decoder. Return * XZ_OK on success, XZ_MEMLIMIT_ERROR if the preallocated dictionary is not * big enough, and XZ_OPTIONS_ERROR if props indicates something that this * decoder doesn't support. */ XZ_EXTERN enum xz_ret xz_dec_lzma2_reset(struct xz_dec_lzma2 *s, uint8_t props); /* Decode raw LZMA2 stream from b->in to b->out. */ XZ_EXTERN enum xz_ret xz_dec_lzma2_run(struct xz_dec_lzma2 *s, struct xz_buf *b); /* Free the memory allocated for the LZMA2 decoder. */ XZ_EXTERN void xz_dec_lzma2_end(struct xz_dec_lzma2 *s); #ifdef XZ_DEC_BCJ /* * Allocate memory for BCJ decoders. xz_dec_bcj_reset() must be used before * calling xz_dec_bcj_run(). */ XZ_EXTERN struct xz_dec_bcj *xz_dec_bcj_create(bool single_call); /* * Decode the Filter ID of a BCJ filter. This implementation doesn't * support custom start offsets, so no decoding of Filter Properties * is needed. Returns XZ_OK if the given Filter ID is supported. * Otherwise XZ_OPTIONS_ERROR is returned. */ XZ_EXTERN enum xz_ret xz_dec_bcj_reset(struct xz_dec_bcj *s, uint8_t id); /* * Decode raw BCJ + LZMA2 stream. This must be used only if there actually is * a BCJ filter in the chain. If the chain has only LZMA2, xz_dec_lzma2_run() * must be called directly. */ XZ_EXTERN enum xz_ret xz_dec_bcj_run(struct xz_dec_bcj *s, struct xz_dec_lzma2 *lzma2, struct xz_buf *b); /* Free the memory allocated for the BCJ filters. */ #define xz_dec_bcj_end(s) kfree(s) #endif #endif
4,667
C++
.h
139
30.877698
78
0.701397
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
66
xz.h
topjohnwu_Magisk/native/src/external/xz-embedded/xz.h
/* * XZ decompressor * * Authors: Lasse Collin <lasse.collin@tukaani.org> * Igor Pavlov <http://7-zip.org/> * * This file has been put into the public domain. * You can do whatever you want with this file. */ #ifndef XZ_H #define XZ_H #ifdef __KERNEL__ # include <linux/stddef.h> # include <linux/types.h> #else # include <stddef.h> # include <stdint.h> #endif #ifdef __cplusplus extern "C" { #endif /* In Linux, this is used to make extern functions static when needed. */ #ifndef XZ_EXTERN # define XZ_EXTERN extern #endif /** * enum xz_mode - Operation mode * * @XZ_SINGLE: Single-call mode. This uses less RAM than * than multi-call modes, because the LZMA2 * dictionary doesn't need to be allocated as * part of the decoder state. All required data * structures are allocated at initialization, * so xz_dec_run() cannot return XZ_MEM_ERROR. * @XZ_PREALLOC: Multi-call mode with preallocated LZMA2 * dictionary buffer. All data structures are * allocated at initialization, so xz_dec_run() * cannot return XZ_MEM_ERROR. * @XZ_DYNALLOC: Multi-call mode. The LZMA2 dictionary is * allocated once the required size has been * parsed from the stream headers. If the * allocation fails, xz_dec_run() will return * XZ_MEM_ERROR. * * It is possible to enable support only for a subset of the above * modes at compile time by defining XZ_DEC_SINGLE, XZ_DEC_PREALLOC, * or XZ_DEC_DYNALLOC. The xz_dec kernel module is always compiled * with support for all operation modes, but the preboot code may * be built with fewer features to minimize code size. */ enum xz_mode { XZ_SINGLE, XZ_PREALLOC, XZ_DYNALLOC }; /** * enum xz_ret - Return codes * @XZ_OK: Everything is OK so far. More input or more * output space is required to continue. This * return code is possible only in multi-call mode * (XZ_PREALLOC or XZ_DYNALLOC). * @XZ_STREAM_END: Operation finished successfully. * @XZ_UNSUPPORTED_CHECK: Integrity check type is not supported. Decoding * is still possible in multi-call mode by simply * calling xz_dec_run() again. * Note that this return value is used only if * XZ_DEC_ANY_CHECK was defined at build time, * which is not used in the kernel. Unsupported * check types return XZ_OPTIONS_ERROR if * XZ_DEC_ANY_CHECK was not defined at build time. * @XZ_MEM_ERROR: Allocating memory failed. This return code is * possible only if the decoder was initialized * with XZ_DYNALLOC. The amount of memory that was * tried to be allocated was no more than the * dict_max argument given to xz_dec_init(). * @XZ_MEMLIMIT_ERROR: A bigger LZMA2 dictionary would be needed than * allowed by the dict_max argument given to * xz_dec_init(). This return value is possible * only in multi-call mode (XZ_PREALLOC or * XZ_DYNALLOC); the single-call mode (XZ_SINGLE) * ignores the dict_max argument. * @XZ_FORMAT_ERROR: File format was not recognized (wrong magic * bytes). * @XZ_OPTIONS_ERROR: This implementation doesn't support the requested * compression options. In the decoder this means * that the header CRC32 matches, but the header * itself specifies something that we don't support. * @XZ_DATA_ERROR: Compressed data is corrupt. * @XZ_BUF_ERROR: Cannot make any progress. Details are slightly * different between multi-call and single-call * mode; more information below. * * In multi-call mode, XZ_BUF_ERROR is returned when two consecutive calls * to XZ code cannot consume any input and cannot produce any new output. * This happens when there is no new input available, or the output buffer * is full while at least one output byte is still pending. Assuming your * code is not buggy, you can get this error only when decoding a compressed * stream that is truncated or otherwise corrupt. * * In single-call mode, XZ_BUF_ERROR is returned only when the output buffer * is too small or the compressed input is corrupt in a way that makes the * decoder produce more output than the caller expected. When it is * (relatively) clear that the compressed input is truncated, XZ_DATA_ERROR * is used instead of XZ_BUF_ERROR. */ enum xz_ret { XZ_OK, XZ_STREAM_END, XZ_UNSUPPORTED_CHECK, XZ_MEM_ERROR, XZ_MEMLIMIT_ERROR, XZ_FORMAT_ERROR, XZ_OPTIONS_ERROR, XZ_DATA_ERROR, XZ_BUF_ERROR }; /** * struct xz_buf - Passing input and output buffers to XZ code * @in: Beginning of the input buffer. This may be NULL if and only * if in_pos is equal to in_size. * @in_pos: Current position in the input buffer. This must not exceed * in_size. * @in_size: Size of the input buffer * @out: Beginning of the output buffer. This may be NULL if and only * if out_pos is equal to out_size. * @out_pos: Current position in the output buffer. This must not exceed * out_size. * @out_size: Size of the output buffer * * Only the contents of the output buffer from out[out_pos] onward, and * the variables in_pos and out_pos are modified by the XZ code. */ struct xz_buf { const uint8_t *in; size_t in_pos; size_t in_size; uint8_t *out; size_t out_pos; size_t out_size; }; /** * struct xz_dec - Opaque type to hold the XZ decoder state */ struct xz_dec; /** * xz_dec_init() - Allocate and initialize a XZ decoder state * @mode: Operation mode * @dict_max: Maximum size of the LZMA2 dictionary (history buffer) for * multi-call decoding. This is ignored in single-call mode * (mode == XZ_SINGLE). LZMA2 dictionary is always 2^n bytes * or 2^n + 2^(n-1) bytes (the latter sizes are less common * in practice), so other values for dict_max don't make sense. * In the kernel, dictionary sizes of 64 KiB, 128 KiB, 256 KiB, * 512 KiB, and 1 MiB are probably the only reasonable values, * except for kernel and initramfs images where a bigger * dictionary can be fine and useful. * * Single-call mode (XZ_SINGLE): xz_dec_run() decodes the whole stream at * once. The caller must provide enough output space or the decoding will * fail. The output space is used as the dictionary buffer, which is why * there is no need to allocate the dictionary as part of the decoder's * internal state. * * Because the output buffer is used as the workspace, streams encoded using * a big dictionary are not a problem in single-call mode. It is enough that * the output buffer is big enough to hold the actual uncompressed data; it * can be smaller than the dictionary size stored in the stream headers. * * Multi-call mode with preallocated dictionary (XZ_PREALLOC): dict_max bytes * of memory is preallocated for the LZMA2 dictionary. This way there is no * risk that xz_dec_run() could run out of memory, since xz_dec_run() will * never allocate any memory. Instead, if the preallocated dictionary is too * small for decoding the given input stream, xz_dec_run() will return * XZ_MEMLIMIT_ERROR. Thus, it is important to know what kind of data will be * decoded to avoid allocating excessive amount of memory for the dictionary. * * Multi-call mode with dynamically allocated dictionary (XZ_DYNALLOC): * dict_max specifies the maximum allowed dictionary size that xz_dec_run() * may allocate once it has parsed the dictionary size from the stream * headers. This way excessive allocations can be avoided while still * limiting the maximum memory usage to a sane value to prevent running the * system out of memory when decompressing streams from untrusted sources. * * On success, xz_dec_init() returns a pointer to struct xz_dec, which is * ready to be used with xz_dec_run(). If memory allocation fails, * xz_dec_init() returns NULL. */ XZ_EXTERN struct xz_dec *xz_dec_init(enum xz_mode mode, uint32_t dict_max); /** * xz_dec_run() - Run the XZ decoder * @s: Decoder state allocated using xz_dec_init() * @b: Input and output buffers * * The possible return values depend on build options and operation mode. * See enum xz_ret for details. * * Note that if an error occurs in single-call mode (return value is not * XZ_STREAM_END), b->in_pos and b->out_pos are not modified and the * contents of the output buffer from b->out[b->out_pos] onward are * undefined. This is true even after XZ_BUF_ERROR, because with some filter * chains, there may be a second pass over the output buffer, and this pass * cannot be properly done if the output buffer is truncated. Thus, you * cannot give the single-call decoder a too small buffer and then expect to * get that amount valid data from the beginning of the stream. You must use * the multi-call decoder if you don't want to uncompress the whole stream. */ XZ_EXTERN enum xz_ret xz_dec_run(struct xz_dec *s, struct xz_buf *b); /** * xz_dec_reset() - Reset an already allocated decoder state * @s: Decoder state allocated using xz_dec_init() * * This function can be used to reset the multi-call decoder state without * freeing and reallocating memory with xz_dec_end() and xz_dec_init(). * * In single-call mode, xz_dec_reset() is always called in the beginning of * xz_dec_run(). Thus, explicit call to xz_dec_reset() is useful only in * multi-call mode. */ XZ_EXTERN void xz_dec_reset(struct xz_dec *s); /** * xz_dec_end() - Free the memory allocated for the decoder state * @s: Decoder state allocated using xz_dec_init(). If s is NULL, * this function does nothing. */ XZ_EXTERN void xz_dec_end(struct xz_dec *s); /* * Standalone build (userspace build or in-kernel build for boot time use) * needs a CRC32 implementation. For normal in-kernel use, kernel's own * CRC32 module is used instead, and users of this module don't need to * care about the functions below. */ #ifndef XZ_INTERNAL_CRC32 # ifdef __KERNEL__ # define XZ_INTERNAL_CRC32 0 # else # define XZ_INTERNAL_CRC32 1 # endif #endif /* * If CRC64 support has been enabled with XZ_USE_CRC64, a CRC64 * implementation is needed too. */ #ifndef XZ_USE_CRC64 # undef XZ_INTERNAL_CRC64 # define XZ_INTERNAL_CRC64 0 #endif #ifndef XZ_INTERNAL_CRC64 # ifdef __KERNEL__ # error Using CRC64 in the kernel has not been implemented. # else # define XZ_INTERNAL_CRC64 1 # endif #endif #if XZ_INTERNAL_CRC32 /* * This must be called before any other xz_* function to initialize * the CRC32 lookup table. */ XZ_EXTERN void xz_crc32_init(void); /* * Update CRC32 value using the polynomial from IEEE-802.3. To start a new * calculation, the third argument must be zero. To continue the calculation, * the previously returned value is passed as the third argument. */ XZ_EXTERN uint32_t xz_crc32(const uint8_t *buf, size_t size, uint32_t crc); #endif #if XZ_INTERNAL_CRC64 /* * This must be called before any other xz_* function (except xz_crc32_init()) * to initialize the CRC64 lookup table. */ XZ_EXTERN void xz_crc64_init(void); /* * Update CRC64 value using the polynomial from ECMA-182. To start a new * calculation, the third argument must be zero. To continue the calculation, * the previously returned value is passed as the third argument. */ XZ_EXTERN uint64_t xz_crc64(const uint8_t *buf, size_t size, uint64_t crc); #endif #ifdef __cplusplus } #endif #endif
12,395
C++
.h
283
41.787986
78
0.666612
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
67
xz_config.h
topjohnwu_Magisk/native/src/external/xz-embedded/xz_config.h
/* * Private includes and definitions for userspace use of XZ Embedded * * Author: Lasse Collin <lasse.collin@tukaani.org> * * This file has been put into the public domain. * You can do whatever you want with this file. */ #ifndef XZ_CONFIG_H #define XZ_CONFIG_H /* Uncomment to enable CRC64 support. */ /* #define XZ_USE_CRC64 */ /* Uncomment as needed to enable BCJ filter decoders. */ /* #define XZ_DEC_X86 */ /* #define XZ_DEC_POWERPC */ /* #define XZ_DEC_IA64 */ /* #define XZ_DEC_ARM */ /* #define XZ_DEC_ARMTHUMB */ /* #define XZ_DEC_SPARC */ /* * MSVC doesn't support modern C but XZ Embedded is mostly C89 * so these are enough. */ #ifdef _MSC_VER typedef unsigned char bool; # define true 1 # define false 0 # define inline __inline #else # include <stdbool.h> #endif #include <stdlib.h> #include <string.h> #include "xz.h" #define kmalloc(size, flags) malloc(size) #define kfree(ptr) free(ptr) #define vmalloc(size) malloc(size) #define vfree(ptr) free(ptr) #define memeq(a, b, size) (memcmp(a, b, size) == 0) #define memzero(buf, size) memset(buf, 0, size) #ifndef min # define min(x, y) ((x) < (y) ? (x) : (y)) #endif #define min_t(type, x, y) min(x, y) /* * Some functions have been marked with __always_inline to keep the * performance reasonable even when the compiler is optimizing for * small code size. You may be able to save a few bytes by #defining * __always_inline to plain inline, but don't complain if the code * becomes slow. * * NOTE: System headers on GNU/Linux may #define this macro already, * so if you want to change it, you need to #undef it first. */ #ifndef __always_inline # ifdef __GNUC__ # define __always_inline \ inline __attribute__((__always_inline__)) # else # define __always_inline inline # endif #endif /* Inline functions to access unaligned unsigned 32-bit integers */ #ifndef get_unaligned_le32 static inline uint32_t get_unaligned_le32(const uint8_t *buf) { return (uint32_t)buf[0] | ((uint32_t)buf[1] << 8) | ((uint32_t)buf[2] << 16) | ((uint32_t)buf[3] << 24); } #endif #ifndef get_unaligned_be32 static inline uint32_t get_unaligned_be32(const uint8_t *buf) { return (uint32_t)(buf[0] << 24) | ((uint32_t)buf[1] << 16) | ((uint32_t)buf[2] << 8) | (uint32_t)buf[3]; } #endif #ifndef put_unaligned_le32 static inline void put_unaligned_le32(uint32_t val, uint8_t *buf) { buf[0] = (uint8_t)val; buf[1] = (uint8_t)(val >> 8); buf[2] = (uint8_t)(val >> 16); buf[3] = (uint8_t)(val >> 24); } #endif #ifndef put_unaligned_be32 static inline void put_unaligned_be32(uint32_t val, uint8_t *buf) { buf[0] = (uint8_t)(val >> 24); buf[1] = (uint8_t)(val >> 16); buf[2] = (uint8_t)(val >> 8); buf[3] = (uint8_t)val; } #endif /* * Use get_unaligned_le32() also for aligned access for simplicity. On * little endian systems, #define get_le32(ptr) (*(const uint32_t *)(ptr)) * could save a few bytes in code size. */ #ifndef get_le32 # define get_le32 get_unaligned_le32 #endif #endif
3,089
C++
.h
108
26.092593
74
0.669477
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
68
xz_stream.h
topjohnwu_Magisk/native/src/external/xz-embedded/xz_stream.h
/* * Definitions for handling the .xz file format * * Author: Lasse Collin <lasse.collin@tukaani.org> * * This file has been put into the public domain. * You can do whatever you want with this file. */ #ifndef XZ_STREAM_H #define XZ_STREAM_H #if defined(__KERNEL__) && !XZ_INTERNAL_CRC32 # include <linux/crc32.h> # undef crc32 # define xz_crc32(buf, size, crc) \ (~crc32_le(~(uint32_t)(crc), buf, size)) #endif /* * See the .xz file format specification at * http://tukaani.org/xz/xz-file-format.txt * to understand the container format. */ #define STREAM_HEADER_SIZE 12 #define HEADER_MAGIC "\3757zXZ" #define HEADER_MAGIC_SIZE 6 #define FOOTER_MAGIC "YZ" #define FOOTER_MAGIC_SIZE 2 /* * Variable-length integer can hold a 63-bit unsigned integer or a special * value indicating that the value is unknown. * * Experimental: vli_type can be defined to uint32_t to save a few bytes * in code size (no effect on speed). Doing so limits the uncompressed and * compressed size of the file to less than 256 MiB and may also weaken * error detection slightly. */ typedef uint64_t vli_type; #define VLI_MAX ((vli_type)-1 / 2) #define VLI_UNKNOWN ((vli_type)-1) /* Maximum encoded size of a VLI */ #define VLI_BYTES_MAX (sizeof(vli_type) * 8 / 7) /* Integrity Check types */ enum xz_check { XZ_CHECK_NONE = 0, XZ_CHECK_CRC32 = 1, XZ_CHECK_CRC64 = 4, XZ_CHECK_SHA256 = 10 }; /* Maximum possible Check ID */ #define XZ_CHECK_MAX 15 #endif
1,487
C++
.h
50
27.64
74
0.719298
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
69
files.hpp
topjohnwu_Magisk/native/src/base/files.hpp
#pragma once #include <sys/stat.h> #include <functional> #include <string_view> #include <string> #include <vector> #include <linux/fs.h> #include "misc.hpp" template <typename T> static inline T align_to(T v, int a) { static_assert(std::is_integral<T>::value); return (v + a - 1) / a * a; } template <typename T> static inline T align_padding(T v, int a) { return align_to(v, a) - v; } struct mmap_data : public byte_data { static_assert((sizeof(void *) == 8 && BLKGETSIZE64 == 0x80081272) || (sizeof(void *) == 4 && BLKGETSIZE64 == 0x80041272)); ALLOW_MOVE_ONLY(mmap_data) explicit mmap_data(const char *name, bool rw = false); mmap_data(int dirfd, const char *name, bool rw = false); mmap_data(int fd, size_t sz, bool rw = false); ~mmap_data(); }; extern "C" { int mkdirs(const char *path, mode_t mode); ssize_t canonical_path(const char * __restrict__ path, char * __restrict__ buf, size_t bufsiz); bool rm_rf(const char *path); bool frm_rf(int dirfd); bool cp_afc(const char *src, const char *dest); bool mv_path(const char *src, const char *dest); bool link_path(const char *src, const char *dest); bool clone_attr(const char *src, const char *dest); bool fclone_attr(int src, int dest); } // extern "C" int fd_pathat(int dirfd, const char *name, char *path, size_t size); static inline ssize_t realpath( const char * __restrict__ path, char * __restrict__ buf, size_t bufsiz) { return canonical_path(path, buf, bufsiz); } void full_read(int fd, std::string &str); void full_read(const char *filename, std::string &str); std::string full_read(int fd); std::string full_read(const char *filename); void write_zero(int fd, size_t size); void file_readline(bool trim, FILE *fp, const std::function<bool(std::string_view)> &fn); void file_readline(bool trim, const char *file, const std::function<bool(std::string_view)> &fn); void file_readline(const char *file, const std::function<bool(std::string_view)> &fn); void parse_prop_file(FILE *fp, const std::function<bool(std::string_view, std::string_view)> &fn); void parse_prop_file(const char *file, const std::function<bool(std::string_view, std::string_view)> &fn); std::string resolve_preinit_dir(const char *base_dir); using sFILE = std::unique_ptr<FILE, decltype(&fclose)>; using sDIR = std::unique_ptr<DIR, decltype(&closedir)>; sDIR make_dir(DIR *dp); sFILE make_file(FILE *fp); static inline sDIR open_dir(const char *path) { return make_dir(opendir(path)); } static inline sDIR xopen_dir(const char *path) { return make_dir(xopendir(path)); } static inline sDIR xopen_dir(int dirfd) { return make_dir(xfdopendir(dirfd)); } static inline sFILE open_file(const char *path, const char *mode) { return make_file(fopen(path, mode)); } static inline sFILE xopen_file(const char *path, const char *mode) { return make_file(xfopen(path, mode)); } static inline sFILE xopen_file(int fd, const char *mode) { return make_file(xfdopen(fd, mode)); }
3,015
C++
.h
76
37.157895
98
0.702943
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
70
xwrap.hpp
topjohnwu_Magisk/native/src/base/xwrap.hpp
#pragma once #include <unistd.h> #include <dirent.h> #include <stdio.h> #include <poll.h> #include <fcntl.h> extern "C" { FILE *xfopen(const char *pathname, const char *mode); FILE *xfdopen(int fd, const char *mode); int xopen(const char *pathname, int flags, mode_t mode = 0); int xopenat(int dirfd, const char *pathname, int flags, mode_t mode = 0); ssize_t xwrite(int fd, const void *buf, size_t count); ssize_t xread(int fd, void *buf, size_t count); ssize_t xxread(int fd, void *buf, size_t count); off64_t xlseek64(int fd, off64_t offset, int whence); int xsetns(int fd, int nstype); int xunshare(int flags); DIR *xopendir(const char *name); DIR *xfdopendir(int fd); dirent *xreaddir(DIR *dirp); pid_t xsetsid(); int xsocket(int domain, int type, int protocol); int xbind(int sockfd, const struct sockaddr *addr, socklen_t addrlen); int xlisten(int sockfd, int backlog); int xaccept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags); ssize_t xsendmsg(int sockfd, const struct msghdr *msg, int flags); ssize_t xrecvmsg(int sockfd, struct msghdr *msg, int flags); int xaccess(const char *path, int mode); int xfaccessat(int dirfd, const char *pathname, int mode, int flags); int xstat(const char *pathname, struct stat *buf); int xlstat(const char *pathname, struct stat *buf); int xfstat(int fd, struct stat *buf); int xfstatat(int dirfd, const char *pathname, struct stat *buf, int flags); int xdup(int fd); int xdup2(int oldfd, int newfd); int xdup3(int oldfd, int newfd, int flags); ssize_t xreadlink(const char * __restrict__ pathname, char * __restrict__ buf, size_t bufsiz); ssize_t xreadlinkat( int dirfd, const char * __restrict__ pathname, char * __restrict__ buf, size_t bufsiz); int xsymlink(const char *target, const char *linkpath); int xsymlinkat(const char *target, int newdirfd, const char *linkpath); int xlinkat(int olddirfd, const char *oldpath, int newdirfd, const char *newpath, int flags); int xmount(const char *source, const char *target, const char *filesystemtype, unsigned long mountflags, const void *data); int xumount(const char *target); int xumount2(const char *target, int flags); int xrename(const char *oldpath, const char *newpath); int xmkdir(const char *pathname, mode_t mode); int xmkdirs(const char *pathname, mode_t mode); int xmkdirat(int dirfd, const char *pathname, mode_t mode); void *xmmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset); ssize_t xsendfile(int out_fd, int in_fd, off_t *offset, size_t count); pid_t xfork(); int xpoll(pollfd *fds, nfds_t nfds, int timeout); ssize_t xrealpath(const char * __restrict__ path, char * __restrict__ buf, size_t bufsiz); int xmknod(const char * pathname, mode_t mode, dev_t dev); } // extern "C"
2,765
C++
.h
58
46.086207
95
0.736959
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
71
logging.hpp
topjohnwu_Magisk/native/src/base/logging.hpp
#pragma once #include <cerrno> #include <cstdarg> void LOGD(const char *fmt, ...) __printflike(1, 2); void LOGI(const char *fmt, ...) __printflike(1, 2); void LOGW(const char *fmt, ...) __printflike(1, 2); void LOGE(const char *fmt, ...) __printflike(1, 2); #define PLOGE(fmt, args...) LOGE(fmt " failed with %d: %s\n", ##args, errno, std::strerror(errno))
359
C++
.h
8
43.625
98
0.653295
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
72
misc.hpp
topjohnwu_Magisk/native/src/base/misc.hpp
#pragma once #include <pthread.h> #include <string> #include <functional> #include <string_view> #include <bitset> #include <random> #include <cxx.h> #include "xwrap.hpp" #define DISALLOW_COPY_AND_MOVE(clazz) \ clazz(const clazz&) = delete; \ clazz(clazz &&) = delete; #define ALLOW_MOVE_ONLY(clazz) \ clazz(const clazz&) = delete; \ clazz(clazz &&o) { swap(o); } \ clazz& operator=(clazz &&o) { swap(o); return *this; } class mutex_guard { DISALLOW_COPY_AND_MOVE(mutex_guard) public: explicit mutex_guard(pthread_mutex_t &m): mutex(&m) { pthread_mutex_lock(mutex); } void unlock() { pthread_mutex_unlock(mutex); mutex = nullptr; } ~mutex_guard() { if (mutex) pthread_mutex_unlock(mutex); } private: pthread_mutex_t *mutex; }; template <class Func> class run_finally { DISALLOW_COPY_AND_MOVE(run_finally) public: explicit run_finally(Func &&fn) : fn(std::move(fn)) {} ~run_finally() { fn(); } private: Func fn; }; template <typename T> class reversed_container { public: reversed_container(T &base) : base(base) {} decltype(std::declval<T>().rbegin()) begin() { return base.rbegin(); } decltype(std::declval<T>().crbegin()) begin() const { return base.crbegin(); } decltype(std::declval<T>().crbegin()) cbegin() const { return base.crbegin(); } decltype(std::declval<T>().rend()) end() { return base.rend(); } decltype(std::declval<T>().crend()) end() const { return base.crend(); } decltype(std::declval<T>().crend()) cend() const { return base.crend(); } private: T &base; }; template <typename T> reversed_container<T> reversed(T &base) { return reversed_container<T>(base); } template<class T> static inline void default_new(T *&p) { p = new T(); } template<class T> static inline void default_new(std::unique_ptr<T> &p) { p.reset(new T()); } template<typename T, typename Impl> class stateless_allocator { public: using value_type = T; T *allocate(size_t num) { return static_cast<T*>(Impl::allocate(sizeof(T) * num)); } void deallocate(T *ptr, size_t num) { Impl::deallocate(ptr, sizeof(T) * num); } stateless_allocator() = default; stateless_allocator(const stateless_allocator&) = default; stateless_allocator(stateless_allocator&&) = default; template <typename U> stateless_allocator(const stateless_allocator<U, Impl>&) {} bool operator==(const stateless_allocator&) { return true; } bool operator!=(const stateless_allocator&) { return false; } }; class dynamic_bitset_impl { public: using slot_type = unsigned long; constexpr static int slot_size = sizeof(slot_type) * 8; using slot_bits = std::bitset<slot_size>; size_t slots() const { return slot_list.size(); } slot_type get_slot(size_t slot) const { return slot_list.size() > slot ? slot_list[slot].to_ulong() : 0ul; } void emplace_back(slot_type l) { slot_list.emplace_back(l); } protected: slot_bits::reference get(size_t pos) { size_t slot = pos / slot_size; size_t index = pos % slot_size; if (slot_list.size() <= slot) { slot_list.resize(slot + 1); } return slot_list[slot][index]; } bool get(size_t pos) const { size_t slot = pos / slot_size; size_t index = pos % slot_size; return slot_list.size() > slot && slot_list[slot][index]; } private: std::vector<slot_bits> slot_list; }; struct dynamic_bitset : public dynamic_bitset_impl { slot_bits::reference operator[] (size_t pos) { return get(pos); } bool operator[] (size_t pos) const { return get(pos); } }; struct StringCmp { using is_transparent = void; bool operator()(std::string_view a, std::string_view b) const { return a < b; } }; struct heap_data; // Interchangeable as `&[u8]` in Rust struct byte_view { byte_view() : _buf(nullptr), _sz(0) {} byte_view(const void *buf, size_t sz) : _buf((uint8_t *) buf), _sz(sz) {} // byte_view, or any of its subclass, can be copied as byte_view byte_view(const byte_view &o) : _buf(o._buf), _sz(o._sz) {} // Bridging to Rust slice byte_view(rust::Slice<const uint8_t> o) : byte_view(o.data(), o.size()) {} operator rust::Slice<const uint8_t>() const { return rust::Slice<const uint8_t>(_buf, _sz); } // String as bytes byte_view(const char *s, bool with_nul = true) : byte_view(std::string_view(s), with_nul, false) {} byte_view(const std::string &s, bool with_nul = true) : byte_view(std::string_view(s), with_nul, false) {} byte_view(std::string_view s, bool with_nul = true) : byte_view(s, with_nul, true /* string_view is not guaranteed to null terminate */ ) {} // Vector as bytes byte_view(const std::vector<uint8_t> &v) : byte_view(v.data(), v.size()) {} const uint8_t *buf() const { return _buf; } size_t sz() const { return _sz; } bool contains(byte_view pattern) const; bool equals(byte_view o) const; heap_data clone() const; protected: uint8_t *_buf; size_t _sz; private: byte_view(std::string_view s, bool with_nul, bool check_nul) : byte_view(static_cast<const void *>(s.data()), s.length()) { if (with_nul) { if (check_nul && s[s.length()] != '\0') return; ++_sz; } } }; // Interchangeable as `&mut [u8]` in Rust struct byte_data : public byte_view { byte_data() = default; byte_data(void *buf, size_t sz) : byte_view(buf, sz) {} // byte_data, or any of its subclass, can be copied as byte_data byte_data(const byte_data &o) : byte_data(o._buf, o._sz) {} // Transparent conversion from common C++ types to mutable byte references byte_data(std::string &s, bool with_nul = true) : byte_data(s.data(), with_nul ? s.length() + 1 : s.length()) {} byte_data(std::vector<uint8_t> &v) : byte_data(v.data(), v.size()) {} // Bridging to Rust slice byte_data(rust::Slice<uint8_t> o) : byte_data(o.data(), o.size()) {} operator rust::Slice<uint8_t>() { return rust::Slice<uint8_t>(_buf, _sz); } using byte_view::buf; uint8_t *buf() { return _buf; } void swap(byte_data &o); rust::Vec<size_t> patch(byte_view from, byte_view to); }; template<size_t N> struct byte_array : public byte_data { byte_array() : byte_data(arr, N), arr{0} {} private: uint8_t arr[N]; }; class byte_stream; struct heap_data : public byte_data { ALLOW_MOVE_ONLY(heap_data) heap_data() = default; explicit heap_data(size_t sz) : byte_data(calloc(sz, 1), sz) {} ~heap_data() { free(_buf); } // byte_stream needs to reallocate the internal buffer friend byte_stream; }; struct owned_fd { ALLOW_MOVE_ONLY(owned_fd) owned_fd() : fd(-1) {} owned_fd(int fd) : fd(fd) {} ~owned_fd() { close(fd); fd = -1; } operator int() { return fd; } int release() { int f = fd; fd = -1; return f; } void swap(owned_fd &owned) { std::swap(fd, owned.fd); } private: int fd; }; rust::Vec<size_t> mut_u8_patch( rust::Slice<uint8_t> buf, rust::Slice<const uint8_t> from, rust::Slice<const uint8_t> to); uint64_t parse_uint64_hex(std::string_view s); int parse_int(std::string_view s); using thread_entry = void *(*)(void *); extern "C" int new_daemon_thread(thread_entry entry, void *arg = nullptr); static inline bool str_contains(std::string_view s, std::string_view ss) { return s.find(ss) != std::string::npos; } static inline bool str_starts(std::string_view s, std::string_view ss) { return s.size() >= ss.size() && s.compare(0, ss.size(), ss) == 0; } static inline bool str_ends(std::string_view s, std::string_view ss) { return s.size() >= ss.size() && s.compare(s.size() - ss.size(), std::string::npos, ss) == 0; } static inline std::string ltrim(std::string &&s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) { return !std::isspace(ch); })); return std::move(s); } static inline std::string rtrim(std::string &&s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) { return !std::isspace(ch) && ch != '\0'; }).base(), s.end()); return std::move(s); } int fork_dont_care(); int fork_no_orphan(); void init_argv0(int argc, char **argv); void set_nice_name(const char *name); uint32_t binary_gcd(uint32_t u, uint32_t v); int switch_mnt_ns(int pid); std::string &replace_all(std::string &str, std::string_view from, std::string_view to); std::vector<std::string> split(std::string_view s, std::string_view delims); std::vector<std::string_view> split_view(std::string_view, std::string_view delims); // Similar to vsnprintf, but the return value is the written number of bytes __printflike(3, 0) int vssprintf(char *dest, size_t size, const char *fmt, va_list ap); // Similar to snprintf, but the return value is the written number of bytes __printflike(3, 4) int ssprintf(char *dest, size_t size, const char *fmt, ...); // This is not actually the strscpy from the Linux kernel. // Silently truncates, and returns the number of bytes written. extern "C" size_t strscpy(char *dest, const char *src, size_t size); // Ban usage of unsafe cstring functions #define vsnprintf __use_vssprintf_instead__ #define snprintf __use_ssprintf_instead__ #define strlcpy __use_strscpy_instead__ struct exec_t { bool err = false; int fd = -2; void (*pre_exec)() = nullptr; int (*fork)() = xfork; const char **argv = nullptr; }; int exec_command(exec_t &exec); template <class ...Args> int exec_command(exec_t &exec, Args &&...args) { const char *argv[] = {args..., nullptr}; exec.argv = argv; return exec_command(exec); } int exec_command_sync(exec_t &exec); template <class ...Args> int exec_command_sync(exec_t &exec, Args &&...args) { const char *argv[] = {args..., nullptr}; exec.argv = argv; return exec_command_sync(exec); } template <class ...Args> int exec_command_sync(Args &&...args) { exec_t exec; return exec_command_sync(exec, args...); } template <class ...Args> void exec_command_async(Args &&...args) { const char *argv[] = {args..., nullptr}; exec_t exec { .fork = fork_dont_care, .argv = argv, }; exec_command(exec); } template <typename T> constexpr auto operator+(T e) noexcept -> std::enable_if_t<std::is_enum<T>::value, std::underlying_type_t<T>> { return static_cast<std::underlying_type_t<T>>(e); } namespace rust { struct Utf8CStr { const char *data() const; size_t length() const; Utf8CStr(const char *s, size_t len); Utf8CStr() : Utf8CStr("", 1) {}; Utf8CStr(const Utf8CStr &o) = default; Utf8CStr(Utf8CStr &&o) = default; Utf8CStr(const char *s) : Utf8CStr(s, strlen(s) + 1) {}; Utf8CStr(std::string_view s) : Utf8CStr(s.data(), s.length() + 1) {}; Utf8CStr(std::string s) : Utf8CStr(s.data(), s.length() + 1) {}; const char *c_str() const { return this->data(); } size_t size() const { return this->length(); } bool empty() const { return this->length() == 0 ; } operator std::string_view() { return {data(), length()}; } private: #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-private-field" std::array<std::uintptr_t, 2> repr; #pragma clang diagnostic pop }; } // namespace rust
11,417
C++
.h
305
33.55082
97
0.642127
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
73
stream.hpp
topjohnwu_Magisk/native/src/base/include/stream.hpp
#pragma once #include <sys/uio.h> #include <cstdio> #include <memory> #include "../files.hpp" #define ENABLE_IOV 0 struct out_stream { virtual bool write(const void *buf, size_t len) = 0; #if ENABLE_IOV virtual ssize_t writev(const iovec *iov, int iovcnt); #endif virtual ~out_stream() = default; }; using out_strm_ptr = std::unique_ptr<out_stream>; // Delegates all operations to base stream class filter_out_stream : public out_stream { public: filter_out_stream(out_strm_ptr &&base) : base(std::move(base)) {} bool write(const void *buf, size_t len) override; protected: out_strm_ptr base; }; // Buffered output stream, writing in chunks class chunk_out_stream : public filter_out_stream { public: chunk_out_stream(out_strm_ptr &&base, size_t buf_sz, size_t chunk_sz) : filter_out_stream(std::move(base)), chunk_sz(chunk_sz), data(buf_sz) {} chunk_out_stream(out_strm_ptr &&base, size_t buf_sz = 4096) : chunk_out_stream(std::move(base), buf_sz, buf_sz) {} bool write(const void *buf, size_t len) final; protected: // Classes inheriting this class has to call finalize() in its destructor void finalize(); virtual bool write_chunk(const void *buf, size_t len, bool final); size_t chunk_sz; private: size_t buf_off = 0; heap_data data; }; struct in_stream { virtual ssize_t read(void *buf, size_t len) = 0; ssize_t readFully(void *buf, size_t len); #if ENABLE_IOV virtual ssize_t readv(const iovec *iov, int iovcnt); #endif virtual ~in_stream() = default; }; // A stream is something that is writable and readable struct stream : public out_stream, public in_stream {}; using stream_ptr = std::unique_ptr<stream>; // Byte stream that dynamically allocates memory class byte_stream : public stream { public: byte_stream(heap_data &data) : _data(data) {} ssize_t read(void *buf, size_t len) override; bool write(const void *buf, size_t len) override; private: heap_data &_data; size_t _pos = 0; size_t _cap = 0; void resize(size_t new_sz, bool zero = false); }; class rust_vec_stream : public stream { public: rust_vec_stream(rust::Vec<uint8_t> &data) : _data(data) {} ssize_t read(void *buf, size_t len) override; bool write(const void *buf, size_t len) override; private: rust::Vec<uint8_t> &_data; size_t _pos = 0; void ensure_size(size_t sz, bool zero = false); }; class file_stream : public stream { public: bool write(const void *buf, size_t len) final; protected: virtual ssize_t do_write(const void *buf, size_t len) = 0; }; // File stream but does not close the file descriptor at any time class fd_stream : public file_stream { public: fd_stream(int fd) : fd(fd) {} ssize_t read(void *buf, size_t len) override; #if ENABLE_IOV ssize_t readv(const iovec *iov, int iovcnt) override; ssize_t writev(const iovec *iov, int iovcnt) override; #endif protected: ssize_t do_write(const void *buf, size_t len) override; private: int fd; }; /* **************************************** * Bridge between stream class and C stdio * ****************************************/ // stream_ptr -> sFILE sFILE make_stream_fp(stream_ptr &&strm); template <class T, class... Args> sFILE make_stream_fp(Args &&... args) { return make_stream_fp(stream_ptr(new T(std::forward<Args>(args)...))); }
3,383
C++
.h
101
30.49505
77
0.67732
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
74
base.hpp
topjohnwu_Magisk/native/src/base/include/base.hpp
#pragma once #include "../xwrap.hpp" #include "../files.hpp" #include "../misc.hpp" #include "../logging.hpp" #include "../base-rs.hpp" using rust::xpipe2; using rust::fd_path;
178
C++
.h
8
21.125
25
0.692308
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
75
policy.hpp
topjohnwu_Magisk/native/src/sepolicy/policy.hpp
#pragma once // Internal APIs, do not use directly #include <map> #include <string_view> #include <sepol/policydb/policydb.h> #include <sepolicy.hpp> #include "policy-rs.hpp" struct sepol_impl : public sepolicy { avtab_ptr_t find_avtab_node(avtab_key_t *key, avtab_extended_perms_t *xperms); avtab_ptr_t insert_avtab_node(avtab_key_t *key); avtab_ptr_t get_avtab_node(avtab_key_t *key, avtab_extended_perms_t *xperms); void print_type(FILE *fp, type_datum_t *type); void print_avtab(FILE *fp, avtab_ptr_t node); void print_filename_trans(FILE *fp, hashtab_ptr_t node); bool add_rule(const char *s, const char *t, const char *c, const char *p, int effect, bool invert); void add_rule(type_datum_t *src, type_datum_t *tgt, class_datum_t *cls, perm_datum_t *perm, int effect, bool invert); void add_xperm_rule(type_datum_t *src, type_datum_t *tgt, class_datum_t *cls, const Xperm &p, int effect); bool add_xperm_rule(const char *s, const char *t, const char *c, const Xperm &p, int effect); bool add_type_rule(const char *s, const char *t, const char *c, const char *d, int effect); bool add_filename_trans(const char *s, const char *t, const char *c, const char *d, const char *o); bool add_genfscon(const char *fs_name, const char *path, const char *context); bool add_type(const char *type_name, uint32_t flavor); bool set_type_state(const char *type_name, bool permissive); void add_typeattribute(type_datum_t *type, type_datum_t *attr); bool add_typeattribute(const char *type, const char *attr); sepol_impl(policydb *db) : db(db) {} ~sepol_impl(); policydb *db; private: std::map<std::string_view, std::array<const char *, 32>> class_perm_names; }; #define impl reinterpret_cast<sepol_impl *>(this)
1,796
C++
.h
32
52.1875
121
0.701824
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
76
sepolicy.hpp
topjohnwu_Magisk/native/src/sepolicy/include/sepolicy.hpp
#pragma once #include <stdlib.h> #include <string> #include <base.hpp> // sepolicy paths #define PLAT_POLICY_DIR "/system/etc/selinux/" #define VEND_POLICY_DIR "/vendor/etc/selinux/" #define PROD_POLICY_DIR "/product/etc/selinux/" #define ODM_POLICY_DIR "/odm/etc/selinux/" #define SYSEXT_POLICY_DIR "/system_ext/etc/selinux/" #define SPLIT_PLAT_CIL PLAT_POLICY_DIR "plat_sepolicy.cil" // selinuxfs paths #define SELINUX_MNT "/sys/fs/selinux" #define SELINUX_ENFORCE SELINUX_MNT "/enforce" #define SELINUX_POLICY SELINUX_MNT "/policy" #define SELINUX_LOAD SELINUX_MNT "/load" #define SELINUX_VERSION SELINUX_MNT "/policyvers" struct Xperm; using StrVec = rust::Vec<rust::Str>; using Xperms = rust::Vec<Xperm>; struct sepolicy { using c_str = const char *; using Str = rust::Str; // Public static factory functions static sepolicy *from_data(char *data, size_t len); static sepolicy *from_file(c_str file); static sepolicy *from_split(); static sepolicy *compile_split(); // External APIs bool to_file(c_str file); void load_rules(const std::string &rules); void load_rule_file(c_str file); void print_rules(); void parse_statement(c_str statement); // Operation on types void type(Str type, StrVec attrs); void attribute(Str names); void permissive(StrVec types); void enforce(StrVec types); void typeattribute(StrVec types, StrVec attrs); bool exists(c_str type); // Access vector rules void allow(StrVec src, StrVec tgt, StrVec cls, StrVec perm); void deny(StrVec src, StrVec tgt, StrVec cls, StrVec perm); void auditallow(StrVec src, StrVec tgt, StrVec cls, StrVec perm); void dontaudit(StrVec src, StrVec tgt, StrVec cls, StrVec perm); // Extended permissions access vector rules void allowxperm(StrVec src, StrVec tgt, StrVec cls, Xperms xperm); void auditallowxperm(StrVec src, StrVec tgt, StrVec cls, Xperms xperm); void dontauditxperm(StrVec src, StrVec tgt, StrVec cls, Xperms xperm); // Type rules void type_transition(Str src, Str tgt, Str cls, Str def, Str obj); void type_change(Str src, Str tgt, Str cls, Str def); void type_member(Str src, Str tgt, Str cls, Str def); // File system labeling void genfscon(Str fs_name, Str path, Str ctx); // Magisk void magisk_rules(); void strip_dontaudit(); protected: // Prevent anyone from accidentally creating an instance sepolicy() = default; };
2,531
C++
.h
63
36.365079
75
0.704202
topjohnwu/Magisk
47,255
11,960
25
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
77
node.cpp
WerWolv_ImHex/lib/libimhex/source/data_processor/node.cpp
#include <hex/data_processor/node.hpp> #include <hex/helpers/fmt.hpp> #include <hex/api/localization_manager.hpp> #include <hex/providers/provider.hpp> namespace hex::dp { int Node::s_idCounter = 1; static std::atomic_bool s_interrupted; Node::Node(UnlocalizedString unlocalizedTitle, std::vector<Attribute> attributes) : m_id(s_idCounter++), m_unlocalizedTitle(std::move(unlocalizedTitle)), m_attributes(std::move(attributes)) { for (auto &attr : m_attributes) attr.setParentNode(this); } void Node::draw() { this->drawNode(); } const std::vector<u8>& Node::getBufferOnInput(u32 index) { auto attribute = this->getConnectedInputAttribute(index); if (attribute == nullptr) throwNodeError(hex::format("Nothing connected to input '{0}'", Lang(m_attributes[index].getUnlocalizedName()))); if (attribute->getType() != Attribute::Type::Buffer) throwNodeError("Tried to read buffer from non-buffer attribute"); markInputProcessed(index); attribute->getParentNode()->process(); unmarkInputProcessed(index); auto &outputData = attribute->getOutputData(); if (outputData.empty()) throwNodeError("No data available at connected attribute"); return outputData; } const i128& Node::getIntegerOnInput(u32 index) { auto attribute = this->getConnectedInputAttribute(index); auto &outputData = [&] -> std::vector<u8>& { if (attribute != nullptr) { if (attribute->getType() != Attribute::Type::Integer) throwNodeError("Tried to read integer from non-integer attribute"); markInputProcessed(index); attribute->getParentNode()->process(); unmarkInputProcessed(index); return attribute->getOutputData(); } else { return this->getAttribute(index).getOutputData(); } }(); if (outputData.empty()) throwNodeError("No data available at connected attribute"); if (outputData.size() < sizeof(i128)) throwNodeError("Not enough data provided for integer"); return *reinterpret_cast<i128 *>(outputData.data()); } const double& Node::getFloatOnInput(u32 index) { auto attribute = this->getConnectedInputAttribute(index); auto &outputData = [&] -> std::vector<u8>& { if (attribute != nullptr) { if (attribute->getType() != Attribute::Type::Float) throwNodeError("Tried to read integer from non-float attribute"); markInputProcessed(index); attribute->getParentNode()->process(); unmarkInputProcessed(index); return attribute->getOutputData(); } else { return this->getAttribute(index).getOutputData(); } }(); if (outputData.empty()) throwNodeError("No data available at connected attribute"); if (outputData.size() < sizeof(double)) throwNodeError("Not enough data provided for float"); return *reinterpret_cast<double *>(outputData.data()); } void Node::setBufferOnOutput(u32 index, std::span<const u8> data) { if (index >= this->getAttributes().size()) throwNodeError("Attribute index out of bounds!"); auto &attribute = this->getAttributes()[index]; if (attribute.getIOType() != Attribute::IOType::Out) throwNodeError("Tried to set output data of an input attribute!"); if (attribute.getType() != Attribute::Type::Buffer) throwNodeError("Tried to set buffer on non-buffer attribute!"); attribute.getOutputData() = { data.begin(), data.end() }; } void Node::setIntegerOnOutput(u32 index, i128 integer) { if (index >= this->getAttributes().size()) throwNodeError("Attribute index out of bounds!"); auto &attribute = this->getAttributes()[index]; if (attribute.getIOType() != Attribute::IOType::Out) throwNodeError("Tried to set output data of an input attribute!"); if (attribute.getType() != Attribute::Type::Integer) throwNodeError("Tried to set integer on non-integer attribute!"); std::vector<u8> buffer(sizeof(integer), 0); std::memcpy(buffer.data(), &integer, sizeof(integer)); attribute.getOutputData() = buffer; } void Node::setFloatOnOutput(u32 index, double floatingPoint) { if (index >= this->getAttributes().size()) throwNodeError("Attribute index out of bounds!"); auto &attribute = this->getAttributes()[index]; if (attribute.getIOType() != Attribute::IOType::Out) throwNodeError("Tried to set output data of an input attribute!"); if (attribute.getType() != Attribute::Type::Float) throwNodeError("Tried to set float on non-float attribute!"); std::vector<u8> buffer(sizeof(floatingPoint), 0); std::memcpy(buffer.data(), &floatingPoint, sizeof(floatingPoint)); attribute.getOutputData() = buffer; } void Node::setOverlayData(u64 address, const std::vector<u8> &data) { if (m_overlay == nullptr) throwNodeError("Tried setting overlay data on a node that's not the end of a chain!"); m_overlay->setAddress(address); m_overlay->getData() = data; } [[noreturn]] void Node::throwNodeError(const std::string &message) { throw NodeError { this, message }; } void Node::setAttributes(std::vector<Attribute> attributes) { m_attributes = std::move(attributes); for (auto &attr : m_attributes) attr.setParentNode(this); } void Node::setIdCounter(int id) { if (id > s_idCounter) s_idCounter = id; } Attribute& Node::getAttribute(u32 index) { if (index >= this->getAttributes().size()) throw std::runtime_error("Attribute index out of bounds!"); return this->getAttributes()[index]; } Attribute *Node::getConnectedInputAttribute(u32 index) { const auto &connectedAttribute = this->getAttribute(index).getConnectedAttributes(); if (connectedAttribute.empty()) return nullptr; return connectedAttribute.begin()->second; } void Node::markInputProcessed(u32 index) { const auto &[iter, inserted] = m_processedInputs.insert(index); if (!inserted) throwNodeError("Recursion detected!"); if (s_interrupted) { s_interrupted = false; throwNodeError("Execution interrupted!"); } } void Node::unmarkInputProcessed(u32 index) { m_processedInputs.erase(index); } void Node::interrupt() { s_interrupted = true; } }
6,961
C++
.cpp
147
37.585034
195
0.627721
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
78
attribute.cpp
WerWolv_ImHex/lib/libimhex/source/data_processor/attribute.cpp
#include <hex/data_processor/attribute.hpp> namespace hex::dp { int Attribute::s_idCounter = 1; Attribute::Attribute(IOType ioType, Type type, UnlocalizedString unlocalizedName) : m_id(s_idCounter++), m_ioType(ioType), m_type(type), m_unlocalizedName(std::move(unlocalizedName)) { } Attribute::~Attribute() { for (auto &[linkId, attr] : this->getConnectedAttributes()) attr->removeConnectedAttribute(linkId); } void Attribute::setIdCounter(int id) { if (id > s_idCounter) s_idCounter = id; } }
569
C++
.cpp
14
34.285714
188
0.667883
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
79
link.cpp
WerWolv_ImHex/lib/libimhex/source/data_processor/link.cpp
#include <hex/data_processor/link.hpp> namespace hex::dp { int Link::s_idCounter = 1; Link::Link(int from, int to) : m_id(s_idCounter++), m_from(from), m_to(to) { } void Link::setIdCounter(int id) { if (id > s_idCounter) s_idCounter = id; } }
283
C++
.cpp
9
26
82
0.592593
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
80
tests.cpp
WerWolv_ImHex/lib/libimhex/source/test/tests.cpp
#include <hex/test/tests.hpp> namespace hex::test { std::map<std::string, Test> Tests::s_tests; bool initPluginImpl(std::string name) { if (name != "Built-in") { if(!initPluginImpl("Built-in")) return false; } hex::Plugin *plugin = hex::PluginManager::getPlugin(name); if (plugin == nullptr) { hex::log::fatal("Plugin '{}' was not found !", name); return false; }else if (!plugin->initializePlugin()) { hex::log::fatal("Failed to initialize plugin '{}' !", name); return false; } hex::log::info("Initialized plugin '{}' successfully", name); return true; } }
698
C++
.cpp
19
28.421053
72
0.560651
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
81
memory_provider.cpp
WerWolv_ImHex/lib/libimhex/source/providers/memory_provider.cpp
#include <hex/providers/memory_provider.hpp> #include <cstring> namespace hex::prv { bool MemoryProvider::open() { if (m_data.empty()) { m_data.resize(1); } return true; } void MemoryProvider::readRaw(u64 offset, void *buffer, size_t size) { auto actualSize = this->getActualSize(); if (actualSize == 0 || (offset + size) > actualSize || buffer == nullptr || size == 0) return; std::memcpy(buffer, &m_data.front() + offset, size); } void MemoryProvider::writeRaw(u64 offset, const void *buffer, size_t size) { if ((offset + size) > this->getActualSize() || buffer == nullptr || size == 0) return; std::memcpy(&m_data.front() + offset, buffer, size); } void MemoryProvider::resizeRaw(u64 newSize) { m_data.resize(newSize); } }
876
C++
.cpp
24
29.25
94
0.592637
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
82
provider.cpp
WerWolv_ImHex/lib/libimhex/source/providers/provider.cpp
#include <hex/providers/provider.hpp> #include <hex.hpp> #include <hex/api/event_manager.hpp> #include <cmath> #include <cstring> #include <optional> #include <hex/helpers/magic.hpp> #include <wolv/io/file.hpp> #include <wolv/literals.hpp> #include <nlohmann/json.hpp> namespace hex::prv { using namespace wolv::literals; namespace { u32 s_idCounter = 0; } Provider::Provider() : m_undoRedoStack(this), m_id(s_idCounter++) { } Provider::~Provider() { m_overlays.clear(); if (auto selection = ImHexApi::HexEditor::getSelection(); selection.has_value() && selection->provider == this) EventRegionSelected::post(ImHexApi::HexEditor::ProviderRegion { { 0x00, 0x00 }, nullptr }); } void Provider::read(u64 offset, void *buffer, size_t size, bool overlays) { this->readRaw(offset - this->getBaseAddress(), buffer, size); if (overlays) this->applyOverlays(offset, buffer, size); } void Provider::write(u64 offset, const void *buffer, size_t size) { if (!this->isWritable()) return; EventProviderDataModified::post(this, offset, size, static_cast<const u8*>(buffer)); this->markDirty(); } void Provider::save() { if (!this->isWritable()) return; EventProviderSaved::post(this); } void Provider::saveAs(const std::fs::path &path) { wolv::io::File file(path, wolv::io::File::Mode::Create); if (file.isValid()) { std::vector<u8> buffer(std::min<size_t>(2_MiB, this->getActualSize()), 0x00); size_t bufferSize = 0; for (u64 offset = 0; offset < this->getActualSize(); offset += bufferSize) { bufferSize = std::min<size_t>(buffer.size(), this->getActualSize() - offset); this->read(this->getBaseAddress() + offset, buffer.data(), bufferSize, true); file.writeBuffer(buffer.data(), bufferSize); } EventProviderSaved::post(this); } } bool Provider::resize(u64 newSize) { if (newSize >> 63) { log::error("new provider size is very large ({}). Is it a negative number ?", newSize); return false; } i64 difference = newSize - this->getActualSize(); if (difference > 0) EventProviderDataInserted::post(this, this->getActualSize(), difference); else if (difference < 0) EventProviderDataRemoved::post(this, this->getActualSize() + difference, -difference); this->markDirty(); return true; } void Provider::insert(u64 offset, u64 size) { EventProviderDataInserted::post(this, offset, size); this->markDirty(); } void Provider::remove(u64 offset, u64 size) { EventProviderDataRemoved::post(this, offset, size); this->markDirty(); } void Provider::insertRaw(u64 offset, u64 size) { auto oldSize = this->getActualSize(); this->resizeRaw(oldSize + size); std::vector<u8> buffer(0x1000); const std::vector<u8> zeroBuffer(0x1000); auto position = oldSize; while (position > offset) { const auto readSize = std::min<size_t>(position - offset, buffer.size()); position -= readSize; this->readRaw(position, buffer.data(), readSize); this->writeRaw(position, zeroBuffer.data(), readSize); this->writeRaw(position + size, buffer.data(), readSize); } } void Provider::removeRaw(u64 offset, u64 size) { if (offset > this->getActualSize() || size == 0) return; if ((offset + size) > this->getActualSize()) size = this->getActualSize() - offset; auto oldSize = this->getActualSize(); std::vector<u8> buffer(0x1000); const auto newSize = oldSize - size; auto position = offset; while (position < newSize) { const auto readSize = std::min<size_t>(newSize - position, buffer.size()); this->readRaw(position + size, buffer.data(), readSize); this->writeRaw(position, buffer.data(), readSize); position += readSize; } this->resizeRaw(newSize); } void Provider::applyOverlays(u64 offset, void *buffer, size_t size) const { for (auto &overlay : m_overlays) { auto overlayOffset = overlay->getAddress(); auto overlaySize = overlay->getSize(); i128 overlapMin = std::max(offset, overlayOffset); i128 overlapMax = std::min(offset + size, overlayOffset + overlaySize); if (overlapMax > overlapMin) std::memcpy(static_cast<u8 *>(buffer) + std::max<i128>(0, overlapMin - offset), overlay->getData().data() + std::max<i128>(0, overlapMin - overlayOffset), overlapMax - overlapMin); } } Overlay *Provider::newOverlay() { return m_overlays.emplace_back(std::make_unique<Overlay>()).get(); } void Provider::deleteOverlay(Overlay *overlay) { m_overlays.remove_if([overlay](const auto &item) { return item.get() == overlay; }); } const std::list<std::unique_ptr<Overlay>> &Provider::getOverlays() const { return m_overlays; } u64 Provider::getPageSize() const { return m_pageSize; } void Provider::setPageSize(u64 pageSize) { if (pageSize > MaxPageSize) pageSize = MaxPageSize; if (pageSize == 0) return; m_pageSize = pageSize; } u32 Provider::getPageCount() const { return (this->getActualSize() / this->getPageSize()) + (this->getActualSize() % this->getPageSize() != 0 ? 1 : 0); } u32 Provider::getCurrentPage() const { return m_currPage; } void Provider::setCurrentPage(u32 page) { if (page < getPageCount()) m_currPage = page; } void Provider::setBaseAddress(u64 address) { m_baseAddress = address; this->markDirty(); } u64 Provider::getBaseAddress() const { return m_baseAddress; } u64 Provider::getCurrentPageAddress() const { return this->getPageSize() * this->getCurrentPage(); } u64 Provider::getSize() const { return std::min<u64>(this->getActualSize() - this->getPageSize() * m_currPage, this->getPageSize()); } std::optional<u32> Provider::getPageOfAddress(u64 address) const { u32 page = std::floor((address - this->getBaseAddress()) / double(this->getPageSize())); if (page >= this->getPageCount()) return std::nullopt; return page; } std::vector<Provider::Description> Provider::getDataDescription() const { return { }; } void Provider::undo() { m_undoRedoStack.undo(); } void Provider::redo() { m_undoRedoStack.redo(); } bool Provider::canUndo() const { return m_undoRedoStack.canUndo(); } bool Provider::canRedo() const { return m_undoRedoStack.canRedo(); } bool Provider::hasFilePicker() const { return false; } bool Provider::handleFilePicker() { return false; } bool Provider::hasLoadInterface() const { return false; } bool Provider::hasInterface() const { return false; } bool Provider::drawLoadInterface() { return true; } void Provider::drawInterface() { } nlohmann::json Provider::storeSettings(nlohmann::json settings) const { settings["displayName"] = this->getName(); settings["type"] = this->getTypeName(); settings["baseAddress"] = m_baseAddress; settings["currPage"] = m_currPage; return settings; } void Provider::loadSettings(const nlohmann::json &settings) { m_baseAddress = settings["baseAddress"]; m_currPage = settings["currPage"]; } std::pair<Region, bool> Provider::getRegionValidity(u64 address) const { u64 absoluteAddress = address - this->getBaseAddress(); if (absoluteAddress < this->getActualSize()) return { Region { this->getBaseAddress() + absoluteAddress, this->getActualSize() - absoluteAddress }, true }; bool insideValidRegion = false; std::optional<u64> nextRegionAddress; for (const auto &overlay : m_overlays) { Region overlayRegion = { overlay->getAddress(), overlay->getSize() }; if (!nextRegionAddress.has_value() || overlay->getAddress() < nextRegionAddress) { nextRegionAddress = overlayRegion.getStartAddress(); } if (Region { address, 1 }.overlaps(overlayRegion)) { insideValidRegion = true; } } if (!nextRegionAddress.has_value()) return { Region::Invalid(), false }; else return { Region { address, *nextRegionAddress - address }, insideValidRegion }; } u32 Provider::getID() const { return m_id; } void Provider::setID(u32 id) { m_id = id; if (id > s_idCounter) s_idCounter = id + 1; } [[nodiscard]] std::variant<std::string, i128> Provider::queryInformation(const std::string &category, const std::string &) { if (category == "mime") return magic::getMIMEType(this); else if (category == "description") return magic::getDescription(this); else if (category == "provider_type") return this->getTypeName(); else return 0; } [[nodiscard]] bool Provider::isDumpable() const { return true; } }
9,787
C++
.cpp
248
30.919355
196
0.605341
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
83
stack.cpp
WerWolv_ImHex/lib/libimhex/source/providers/undo/stack.cpp
#include <hex/providers/undo_redo/stack.hpp> #include <hex/providers/undo_redo/operations/operation_group.hpp> #include <hex/providers/provider.hpp> #include <wolv/utils/guards.hpp> #include <atomic> namespace hex::prv::undo { namespace { std::atomic<bool> s_locked; std::mutex s_mutex; } Stack::Stack(Provider *provider) : m_provider(provider) { } void Stack::undo(u32 count) { std::scoped_lock lock(s_mutex); s_locked = true; ON_SCOPE_EXIT { s_locked = false; }; // If there are no operations, we can't undo anything. if (m_undoStack.empty()) return; for (u32 i = 0; i < count; i += 1) { // If we reached the start of the list, we can't undo anymore. if (!this->canUndo()) { return; } // Move last element from the undo stack to the redo stack m_redoStack.emplace_back(std::move(m_undoStack.back())); m_redoStack.back()->undo(m_provider); m_undoStack.pop_back(); } } void Stack::redo(u32 count) { std::scoped_lock lock(s_mutex); s_locked = true; ON_SCOPE_EXIT { s_locked = false; }; // If there are no operations, we can't redo anything. if (m_redoStack.empty()) return; for (u32 i = 0; i < count; i += 1) { // If we reached the end of the list, we can't redo anymore. if (!this->canRedo()) { return; } // Move last element from the undo stack to the redo stack m_undoStack.emplace_back(std::move(m_redoStack.back())); m_undoStack.back()->redo(m_provider); m_redoStack.pop_back(); } } void Stack::groupOperations(u32 count, const UnlocalizedString &unlocalizedName) { if (count <= 1) return; auto operation = std::make_unique<OperationGroup>(unlocalizedName); i64 startIndex = std::max<i64>(0, m_undoStack.size() - count); // Move operations from our stack to the group in the same order they were added for (u32 i = 0; i < count; i += 1) { i64 index = startIndex + i; m_undoStack[index]->undo(m_provider); operation->addOperation(std::move(m_undoStack[index])); } // Remove the empty operations from the stack m_undoStack.resize(startIndex); this->add(std::move(operation)); } void Stack::apply(const Stack &otherStack) { for (const auto &operation : otherStack.m_undoStack) { this->add(operation->clone()); } } void Stack::reapply() { for (const auto &operation : m_undoStack) { operation->redo(m_provider); } } bool Stack::add(std::unique_ptr<Operation> &&operation) { // If we're already inside of an undo/redo operation, ignore new operations being added if (s_locked) return false; s_locked = true; ON_SCOPE_EXIT { s_locked = false; }; std::scoped_lock lock(s_mutex); // Clear the redo stack m_redoStack.clear(); // Insert the new operation at the end of the list m_undoStack.emplace_back(std::move(operation)); // Do the operation this->getLastOperation()->redo(m_provider); return true; } bool Stack::canUndo() const { return !m_undoStack.empty(); } bool Stack::canRedo() const { return !m_redoStack.empty(); } }
3,599
C++
.cpp
95
28.715789
95
0.577746
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
84
toast.cpp
WerWolv_ImHex/lib/libimhex/source/ui/toast.cpp
#include <hex/ui/toast.hpp> #include <hex/helpers/auto_reset.hpp> namespace hex::impl { [[nodiscard]] std::list<std::unique_ptr<ToastBase>> &ToastBase::getQueuedToasts() { static AutoReset<std::list<std::unique_ptr<ToastBase>>> queuedToasts; return queuedToasts; } std::mutex& ToastBase::getMutex() { static std::mutex mutex; return mutex; } }
397
C++
.cpp
12
27.666667
87
0.668421
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
85
imgui_imhex_extensions.cpp
WerWolv_ImHex/lib/libimhex/source/ui/imgui_imhex_extensions.cpp
#include <hex/ui/imgui_imhex_extensions.h> #include <imgui.h> #include <imgui_internal.h> #include <implot.h> #include <implot_internal.h> #include <cimgui.h> #include <opengl_support.h> #undef IMGUI_DEFINE_MATH_OPERATORS #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> #include <lunasvg.h> #include <set> #include <string> #include <algorithm> #include <hex/api/imhex_api.hpp> #include <hex/api/task_manager.hpp> #include <hex/api/theme_manager.hpp> #include <hex/helpers/logger.hpp> namespace ImGuiExt { using namespace ImGui; namespace { bool isOpenGLExtensionSupported(const char *name) { static std::set<std::string> extensions; if (extensions.empty()) { GLint extensionCount = 0; glGetIntegerv(GL_NUM_EXTENSIONS, &extensionCount); for (GLint i = 0; i < extensionCount; i++) { std::string extension = reinterpret_cast<const char*>(glGetStringi(GL_EXTENSIONS, i)); extensions.emplace(std::move(extension)); } } return extensions.contains(name); } bool isOpenGLVersionAtLeast(u8 major, u8 minor) { static GLint actualMajor = 0, actualMinor = 0; if (actualMajor == 0 || actualMinor == 0) { glGetIntegerv(GL_MAJOR_VERSION, &actualMajor); glGetIntegerv(GL_MINOR_VERSION, &actualMinor); } return actualMajor > major || (actualMajor == major && actualMinor >= minor); } constexpr auto getGLFilter(Texture::Filter filter) { switch (filter) { using enum Texture::Filter; case Nearest: return GL_NEAREST; case Linear: return GL_LINEAR; } return GL_NEAREST; } [[maybe_unused]] GLint getMaxSamples(GLenum target, GLenum format) { GLint maxSamples; glGetInternalformativ(target, format, GL_SAMPLES, 1, &maxSamples); return maxSamples; } GLuint createTextureFromRGBA8Array(const ImU8 *buffer, int width, int height, Texture::Filter filter) { GLuint texture; // Generate texture glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, getGLFilter(filter)); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, getGLFilter(filter)); #if defined(GL_UNPACK_ROW_LENGTH) glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); #endif // Allocate storage for the texture glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); return texture; } GLuint createMultisampleTextureFromRGBA8Array(const ImU8 *buffer, int width, int height, Texture::Filter filter) { // Create a regular texture from the RGBA8 array GLuint texture = createTextureFromRGBA8Array(buffer, width, height, filter); if (filter == Texture::Filter::Nearest) { return texture; } if (!isOpenGLVersionAtLeast(3,2)) { return texture; } if (!isOpenGLExtensionSupported("GL_ARB_texture_multisample")) { return texture; } #if defined(GL_TEXTURE_2D_MULTISAMPLE) static const auto sampleCount = std::min(static_cast<GLint>(8), getMaxSamples(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8)); // Generate renderbuffer GLuint renderbuffer; glGenRenderbuffers(1, &renderbuffer); glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer); glRenderbufferStorageMultisample(GL_RENDERBUFFER, sampleCount, GL_DEPTH24_STENCIL8, width, height); // Generate framebuffer GLuint framebuffer; glGenFramebuffers(1, &framebuffer); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); // Unbind framebuffer on exit ON_SCOPE_EXIT { glBindFramebuffer(GL_FRAMEBUFFER, 0); }; // Attach texture to color attachment 0 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, texture, 0); // Attach renderbuffer to depth-stencil attachment glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, renderbuffer); // Check framebuffer status if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { hex::log::error("Driver claims to support texture multisampling but it's not working"); return texture; } #endif return texture; } } Texture Texture::fromImage(const ImU8 *buffer, int size, Filter filter) { if (size == 0) return {}; unsigned char *imageData = nullptr; Texture result; imageData = stbi_load_from_memory(buffer, size, &result.m_width, &result.m_height, nullptr, 4); if (imageData == nullptr) return {}; GLuint texture = createMultisampleTextureFromRGBA8Array(imageData, result.m_width, result.m_height, filter); STBI_FREE(imageData); result.m_textureId = reinterpret_cast<ImTextureID>(static_cast<intptr_t>(texture)); return result; } Texture Texture::fromImage(std::span<const std::byte> buffer, Filter filter) { return Texture::fromImage(reinterpret_cast<const ImU8*>(buffer.data()), buffer.size(), filter); } Texture Texture::fromImage(const std::fs::path &path, Filter filter) { return Texture::fromImage(wolv::util::toUTF8String(path).c_str(), filter); } Texture Texture::fromImage(const char *path, Filter filter) { Texture result; unsigned char *imageData = stbi_load(path, &result.m_width, &result.m_height, nullptr, 4); if (imageData == nullptr) return {}; GLuint texture = createMultisampleTextureFromRGBA8Array(imageData, result.m_width, result.m_height, filter); STBI_FREE(imageData); result.m_textureId = reinterpret_cast<ImTextureID>(static_cast<intptr_t>(texture)); return result; } Texture Texture::fromGLTexture(unsigned int glTexture, int width, int height) { Texture texture; texture.m_textureId = reinterpret_cast<ImTextureID>(static_cast<intptr_t>(glTexture)); texture.m_width = width; texture.m_height = height; return texture; } Texture Texture::fromBitmap(std::span<const std::byte> buffer, int width, int height, Filter filter) { return Texture::fromBitmap(reinterpret_cast<const ImU8*>(buffer.data()), buffer.size(), width, height, filter); } Texture Texture::fromBitmap(const ImU8 *buffer, int size, int width, int height, Filter filter) { if (width * height * 4 > size) return {}; GLuint texture = createMultisampleTextureFromRGBA8Array(buffer, width, height, filter); Texture result; result.m_width = width; result.m_height = height; result.m_textureId = reinterpret_cast<ImTextureID>(static_cast<intptr_t>(texture)); return result; } Texture Texture::fromSVG(const char *path, int width, int height, Filter filter) { auto document = lunasvg::Document::loadFromFile(path); auto bitmap = document->renderToBitmap(width, height); auto texture = createMultisampleTextureFromRGBA8Array(bitmap.data(), bitmap.width(), bitmap.height(), filter); Texture result; result.m_width = bitmap.width(); result.m_height = bitmap.height(); result.m_textureId = reinterpret_cast<ImTextureID>(static_cast<intptr_t>(texture)); return result; } Texture Texture::fromSVG(const std::fs::path &path, int width, int height, Filter filter) { return Texture::fromSVG(wolv::util::toUTF8String(path).c_str(), width, height, filter); } Texture Texture::fromSVG(std::span<const std::byte> buffer, int width, int height, Filter filter) { auto document = lunasvg::Document::loadFromData(reinterpret_cast<const char*>(buffer.data()), buffer.size()); auto bitmap = document->renderToBitmap(width, height); bitmap.convertToRGBA(); auto texture = createMultisampleTextureFromRGBA8Array(bitmap.data(), bitmap.width(), bitmap.height(), filter); Texture result; result.m_width = bitmap.width(); result.m_height = bitmap.height(); result.m_textureId = reinterpret_cast<ImTextureID>(static_cast<intptr_t>(texture)); return result; } Texture::Texture(Texture&& other) noexcept { if (m_textureId != nullptr) glDeleteTextures(1, reinterpret_cast<GLuint*>(&m_textureId)); m_textureId = other.m_textureId; m_width = other.m_width; m_height = other.m_height; other.m_textureId = nullptr; } Texture& Texture::operator=(Texture&& other) noexcept { if (m_textureId != nullptr) glDeleteTextures(1, reinterpret_cast<GLuint*>(&m_textureId)); m_textureId = other.m_textureId; m_width = other.m_width; m_height = other.m_height; other.m_textureId = nullptr; return *this; } Texture::~Texture() { if (m_textureId == nullptr) return; glDeleteTextures(1, reinterpret_cast<GLuint*>(&m_textureId)); } float GetTextWrapPos() { return GImGui->CurrentWindow->DC.TextWrapPos; } int UpdateStringSizeCallback(ImGuiInputTextCallbackData *data) { if (data->EventFlag == ImGuiInputTextFlags_CallbackResize) { auto &string = *static_cast<std::string *>(data->UserData); string.resize(data->BufTextLen); data->Buf = string.data(); } return 0; } bool IconHyperlink(const char *icon, const char *label, const ImVec2 &size_arg, ImGuiButtonFlags flags) { ImGuiWindow *window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext &g = *GImGui; const ImGuiID id = window->GetID(label); ImVec2 label_size = CalcTextSize(icon, nullptr, false); label_size.x += CalcTextSize(" ", nullptr, false).x + CalcTextSize(label, nullptr, false).x; ImVec2 pos = window->DC.CursorPos; ImVec2 size = CalcItemSize(size_arg, label_size.x, label_size.y); const ImRect bb(pos, pos + size); if (!ItemAdd(bb, id)) return false; if (g.LastItemData.InFlags & ImGuiItemFlags_ButtonRepeat) flags |= ImGuiButtonFlags_Repeat; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); // Render const ImU32 col = hovered ? GetColorU32(ImGuiCol_ButtonHovered) : GetColorU32(ImGuiCol_ButtonActive); PushStyleColor(ImGuiCol_Text, ImU32(col)); Text("%s %s", icon, label); if (hovered) GetWindowDrawList()->AddLine(ImVec2(pos.x, pos.y + size.y), pos + size, ImU32(col)); PopStyleColor(); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); return pressed; } bool Hyperlink(const char *label, const ImVec2 &size_arg, ImGuiButtonFlags flags) { ImGuiWindow *window = GetCurrentWindow(); ImGuiContext &g = *GImGui; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, nullptr, true); ImVec2 pos = window->DC.CursorPos; ImVec2 size = CalcItemSize(size_arg, label_size.x, label_size.y); const ImRect bb(pos, pos + size); ItemAdd(bb, id); if (g.LastItemData.InFlags & ImGuiItemFlags_ButtonRepeat) flags |= ImGuiButtonFlags_Repeat; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); // Render const ImU32 col = hovered ? GetColorU32(ImGuiCol_ButtonHovered) : GetColorU32(ImGuiCol_ButtonActive); PushStyleColor(ImGuiCol_Text, ImU32(col)); TextEx(label, nullptr, ImGuiTextFlags_NoWidthForLargeClippedText); // Skip formatting if (hovered) GetWindowDrawList()->AddLine(ImVec2(pos.x, pos.y + size.y), pos + size, ImU32(col)); PopStyleColor(); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); return pressed; } bool BulletHyperlink(const char *label, const ImVec2 &size_arg, ImGuiButtonFlags flags) { ImGuiWindow *window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext &g = *GImGui; const ImGuiStyle &style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, nullptr, true); ImVec2 pos = window->DC.CursorPos; ImVec2 size = CalcItemSize(size_arg, label_size.x, label_size.y) + ImVec2(g.FontSize + style.FramePadding.x * 2, 0.0F); const ImRect bb(pos, pos + size); ItemSize(size, 0); if (!ItemAdd(bb, id)) return false; if (g.LastItemData.InFlags & ImGuiItemFlags_ButtonRepeat) flags |= ImGuiButtonFlags_Repeat; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); // Render const ImU32 col = hovered ? GetColorU32(ImGuiCol_ButtonHovered) : GetColorU32(ImGuiCol_ButtonActive); PushStyleColor(ImGuiCol_Text, ImU32(col)); RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x, g.FontSize * 0.5F), col); RenderText(bb.Min + ImVec2(g.FontSize * 0.5 + style.FramePadding.x, 0.0F), label, nullptr, false); GetWindowDrawList()->AddLine(bb.Min + ImVec2(g.FontSize * 0.5 + style.FramePadding.x, size.y), pos + size - ImVec2(g.FontSize * 0.5 + style.FramePadding.x, 0), ImU32(col)); PopStyleColor(); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); return pressed; } bool DescriptionButton(const char *label, const char *description, const ImVec2 &size_arg, ImGuiButtonFlags flags) { ImGuiWindow *window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext &g = *GImGui; const ImGuiStyle &style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 text_size = CalcTextSize((std::string(label) + "\n " + std::string(description)).c_str(), nullptr, true); const ImVec2 label_size = CalcTextSize(label, nullptr, true); ImVec2 pos = window->DC.CursorPos; if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag) pos.y += window->DC.CurrLineTextBaseOffset - style.FramePadding.y; ImVec2 size = CalcItemSize(size_arg, text_size.x + style.FramePadding.x * 4.0F, text_size.y + style.FramePadding.y * 4.0F); const ImRect bb(pos, pos + size); ItemSize(size, style.FramePadding.y); if (!ItemAdd(bb, id)) return false; if (g.LastItemData.InFlags & ImGuiItemFlags_ButtonRepeat) flags |= ImGuiButtonFlags_Repeat; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); PushStyleVar(ImGuiStyleVar_ButtonTextAlign, ImVec2(0.0, 0.5)); PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1); // Render const ImU32 col = GetCustomColorU32((held && hovered) ? ImGuiCustomCol_DescButtonActive : hovered ? ImGuiCustomCol_DescButtonHovered : ImGuiCustomCol_DescButton); RenderNavHighlight(bb, id); RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); PushStyleColor(ImGuiCol_Text, GetColorU32(ImGuiCol_ButtonActive)); RenderTextClipped(bb.Min + style.FramePadding * 2, bb.Max - style.FramePadding, label, nullptr, nullptr); PopStyleColor(); PushStyleColor(ImGuiCol_Text, GetColorU32(ImGuiCol_Text)); auto clipBb = bb; clipBb.Max.x -= style.FramePadding.x; RenderTextClipped(bb.Min + style.FramePadding * 2 + ImVec2(style.FramePadding.x * 2, label_size.y), bb.Max - style.FramePadding, description, nullptr, &text_size, style.ButtonTextAlign, &clipBb); PopStyleColor(); PopStyleVar(2); // Automatically close popups // if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) // CloseCurrentPopup(); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); return pressed; } bool DescriptionButtonProgress(const char *label, const char *description, float fraction, const ImVec2 &size_arg, ImGuiButtonFlags flags) { ImGuiWindow *window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext &g = *GImGui; const ImGuiStyle &style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 text_size = CalcTextSize((std::string(label) + "\n " + std::string(description)).c_str(), nullptr, true); const ImVec2 label_size = CalcTextSize(label, nullptr, true); ImVec2 pos = window->DC.CursorPos; if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag) pos.y += window->DC.CurrLineTextBaseOffset - style.FramePadding.y; ImVec2 size = CalcItemSize(size_arg, text_size.x + style.FramePadding.x * 4.0F, text_size.y + style.FramePadding.y * 6.0F); const ImRect bb(pos, pos + size); ItemSize(size, style.FramePadding.y); if (!ItemAdd(bb, id)) return false; if (g.LastItemData.InFlags & ImGuiItemFlags_ButtonRepeat) flags |= ImGuiButtonFlags_Repeat; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); PushStyleVar(ImGuiStyleVar_ButtonTextAlign, ImVec2(0.0, 0.5)); PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1); // Render const ImU32 col = GetCustomColorU32((held && hovered) ? ImGuiCustomCol_DescButtonActive : hovered ? ImGuiCustomCol_DescButtonHovered : ImGuiCustomCol_DescButton); RenderNavHighlight(bb, id); RenderFrame(bb.Min, bb.Max, col, false, style.FrameRounding); PushStyleColor(ImGuiCol_Text, GetColorU32(ImGuiCol_ButtonActive)); RenderTextClipped(bb.Min + style.FramePadding * 2, bb.Max - style.FramePadding, label, nullptr, nullptr); PopStyleColor(); PushStyleColor(ImGuiCol_Text, GetColorU32(ImGuiCol_Text)); auto clipBb = bb; clipBb.Max.x -= style.FramePadding.x; RenderTextClipped(bb.Min + style.FramePadding * 2 + ImVec2(style.FramePadding.x * 2, label_size.y), bb.Max - style.FramePadding, description, nullptr, &text_size, style.ButtonTextAlign, &clipBb); PopStyleColor(); RenderFrame(ImVec2(bb.Min.x, bb.Max.y - 5 * hex::ImHexApi::System::getGlobalScale()), bb.Max, GetColorU32(ImGuiCol_ScrollbarBg), false, style.FrameRounding); RenderFrame(ImVec2(bb.Min.x, bb.Max.y - 5 * hex::ImHexApi::System::getGlobalScale()), ImVec2(bb.Min.x + fraction * bb.GetSize().x, bb.Max.y), GetColorU32(ImGuiCol_Button), false, style.FrameRounding); RenderFrame(bb.Min, bb.Max, 0x00, true, style.FrameRounding); PopStyleVar(2); // Automatically close popups // if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) // CloseCurrentPopup(); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); return pressed; } void HelpHover(const char *text, const char *icon, ImU32 iconColor) { PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0, 0, 0, 0)); PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0, 0, 0, 0)); PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0F); PushStyleColor(ImGuiCol_Text, iconColor); Button(icon); PopStyleColor(); if (IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) { SetNextWindowSizeConstraints(ImVec2(GetTextLineHeight() * 25, 0), ImVec2(GetTextLineHeight() * 35, FLT_MAX)); BeginTooltip(); TextFormattedWrapped("{}", text); EndTooltip(); } PopStyleVar(2); PopStyleColor(3); } void UnderlinedText(const char *label, ImColor color, const ImVec2 &size_arg) { ImGuiWindow *window = GetCurrentWindow(); const ImVec2 label_size = CalcTextSize(label, nullptr, true); ImVec2 pos = window->DC.CursorPos; ImVec2 size = CalcItemSize(size_arg, label_size.x, label_size.y); PushStyleColor(ImGuiCol_Text, ImU32(color)); TextEx(label, nullptr, ImGuiTextFlags_NoWidthForLargeClippedText); // Skip formatting GetWindowDrawList()->AddLine(ImVec2(pos.x, pos.y + size.y), pos + size, ImU32(color)); PopStyleColor(); } void UnderwavedText(const char *label, ImColor textColor, ImColor lineColor, const ImVec2 &size_arg) { ImGuiWindow *window = GetCurrentWindow(); std::string labelStr(label); for (char letter : labelStr) { std::string letterStr(1, letter); const ImVec2 label_size = CalcTextSize(letterStr.c_str(), nullptr, true); ImVec2 size = CalcItemSize(size_arg, label_size.x, label_size.y); ImVec2 pos = window->DC.CursorPos; float lineWidth = size.x / 3.0f; float halfLineW = lineWidth / 2.0f; float lineY = pos.y + size.y; ImVec2 initial = ImVec2(pos.x, lineY); ImVec2 pos1 = ImVec2(pos.x + lineWidth, lineY - 2.0f); ImVec2 pos2 = ImVec2(pos.x + lineWidth + halfLineW, lineY); ImVec2 pos3 = ImVec2(pos.x + lineWidth * 2 + halfLineW, lineY - 2.0f); ImVec2 pos4 = ImVec2(pos.x + lineWidth * 3, lineY - 1.0f); PushStyleColor(ImGuiCol_Text, ImU32(textColor)); TextEx(letterStr.c_str(), nullptr, ImGuiTextFlags_NoWidthForLargeClippedText); // Skip formatting GetWindowDrawList()->AddLine(initial, pos1, ImU32(lineColor),0.4f); GetWindowDrawList()->AddLine(pos1, pos2, ImU32(lineColor),0.3f); GetWindowDrawList()->AddLine(pos2, pos3, ImU32(lineColor),0.4f); GetWindowDrawList()->AddLine(pos3, pos4, ImU32(lineColor),0.3f); PopStyleColor(); window->DC.CursorPos = ImVec2(pos.x + size.x, pos.y); } } void TextSpinner(const char *label) { Text("[%c] %s", "|/-\\"[ImU32(GetTime() * 20) % 4], label); } void Header(const char *label, bool firstEntry) { if (!firstEntry) NewLine(); SeparatorText(label); } void HeaderColored(const char *label, ImColor color, bool firstEntry) { if (!firstEntry) NewLine(); TextFormattedColored(color, "{}", label); Separator(); } bool InfoTooltip(const char *text, bool isSeparator) { static double lastMoveTime; static ImGuiID lastHoveredID; double currTime = GetTime(); ImGuiID hoveredID = GetHoveredID(); bool result = false; if (IsItemHovered(ImGuiHoveredFlags_DelayNormal) && (currTime - lastMoveTime) >= 0.5 && hoveredID == lastHoveredID) { if (!std::string_view(text).empty()) { const auto textWidth = CalcTextSize(text).x; const auto maxWidth = 300 * hex::ImHexApi::System::getGlobalScale(); const bool wrapping = textWidth > maxWidth; if (wrapping) ImGui::SetNextWindowSizeConstraints(ImVec2(maxWidth, 0), ImVec2(maxWidth, FLT_MAX)); else ImGui::SetNextWindowSize(ImVec2(textWidth + GetStyle().WindowPadding.x * 2, 0)); if (BeginTooltip()) { if (isSeparator) SeparatorText(text); else { if (wrapping) TextFormattedWrapped("{}", text); else TextFormatted("{}", text); } EndTooltip(); } } result = true; } if (hoveredID != lastHoveredID) { lastMoveTime = currTime; } lastHoveredID = hoveredID; return result; } ImU32 GetCustomColorU32(ImGuiCustomCol idx, float alpha_mul) { auto &customData = *static_cast<ImHexCustomData *>(GImGui->IO.UserData); ImVec4 c = customData.Colors[idx]; c.w *= GImGui->Style.Alpha * alpha_mul; return ColorConvertFloat4ToU32(c); } ImVec4 GetCustomColorVec4(ImGuiCustomCol idx, float alpha_mul) { auto &customData = *static_cast<ImHexCustomData *>(GImGui->IO.UserData); ImVec4 c = customData.Colors[idx]; c.w *= GImGui->Style.Alpha * alpha_mul; return c; } float GetCustomStyleFloat(ImGuiCustomStyle idx) { auto &customData = *static_cast<ImHexCustomData *>(GImGui->IO.UserData); switch (idx) { case ImGuiCustomStyle_WindowBlur: return customData.styles.WindowBlur; default: return 0.0F; } } ImVec2 GetCustomStyleVec2(ImGuiCustomStyle idx) { switch (idx) { default: return { }; } } void StyleCustomColorsDark() { auto &colors = static_cast<ImHexCustomData *>(GImGui->IO.UserData)->Colors; colors[ImGuiCustomCol_DescButton] = ImColor(20, 20, 20); colors[ImGuiCustomCol_DescButtonHovered] = ImColor(40, 40, 40); colors[ImGuiCustomCol_DescButtonActive] = ImColor(60, 60, 60); colors[ImGuiCustomCol_ToolbarGray] = ImColor(230, 230, 230); colors[ImGuiCustomCol_ToolbarRed] = ImColor(231, 76, 60); colors[ImGuiCustomCol_ToolbarYellow] = ImColor(241, 196, 15); colors[ImGuiCustomCol_ToolbarGreen] = ImColor(56, 139, 66); colors[ImGuiCustomCol_ToolbarBlue] = ImColor(6, 83, 155); colors[ImGuiCustomCol_ToolbarPurple] = ImColor(103, 42, 120); colors[ImGuiCustomCol_ToolbarBrown] = ImColor(219, 179, 119); colors[ImGuiCustomCol_Highlight] = ImColor(77, 198, 155); colors[ImGuiCustomCol_IEEEToolSign] = ImColor(93, 93, 127); colors[ImGuiCustomCol_IEEEToolExp] = ImColor(93, 127, 93); colors[ImGuiCustomCol_IEEEToolMantissa] = ImColor(127, 93, 93); } void StyleCustomColorsLight() { auto &colors = static_cast<ImHexCustomData *>(GImGui->IO.UserData)->Colors; colors[ImGuiCustomCol_DescButton] = ImColor(230, 230, 230); colors[ImGuiCustomCol_DescButtonHovered] = ImColor(210, 210, 210); colors[ImGuiCustomCol_DescButtonActive] = ImColor(190, 190, 190); colors[ImGuiCustomCol_ToolbarGray] = ImColor(25, 25, 25); colors[ImGuiCustomCol_ToolbarRed] = ImColor(231, 76, 60); colors[ImGuiCustomCol_ToolbarYellow] = ImColor(241, 196, 15); colors[ImGuiCustomCol_ToolbarGreen] = ImColor(56, 139, 66); colors[ImGuiCustomCol_ToolbarBlue] = ImColor(6, 83, 155); colors[ImGuiCustomCol_ToolbarPurple] = ImColor(103, 42, 120); colors[ImGuiCustomCol_ToolbarBrown] = ImColor(219, 179, 119); colors[ImGuiCustomCol_Highlight] = ImColor(41, 151, 112); colors[ImGuiCustomCol_IEEEToolSign] = ImColor(187, 187, 255); colors[ImGuiCustomCol_IEEEToolExp] = ImColor(187, 255, 187); colors[ImGuiCustomCol_IEEEToolMantissa] = ImColor(255, 187,187); } void StyleCustomColorsClassic() { auto &colors = static_cast<ImHexCustomData *>(GImGui->IO.UserData)->Colors; colors[ImGuiCustomCol_DescButton] = ImColor(40, 40, 80); colors[ImGuiCustomCol_DescButtonHovered] = ImColor(60, 60, 100); colors[ImGuiCustomCol_DescButtonActive] = ImColor(80, 80, 120); colors[ImGuiCustomCol_ToolbarGray] = ImColor(230, 230, 230); colors[ImGuiCustomCol_ToolbarRed] = ImColor(231, 76, 60); colors[ImGuiCustomCol_ToolbarYellow] = ImColor(241, 196, 15); colors[ImGuiCustomCol_ToolbarGreen] = ImColor(56, 139, 66); colors[ImGuiCustomCol_ToolbarBlue] = ImColor(6, 83, 155); colors[ImGuiCustomCol_ToolbarPurple] = ImColor(103, 42, 120); colors[ImGuiCustomCol_ToolbarBrown] = ImColor(219, 179, 119); colors[ImGuiCustomCol_Highlight] = ImColor(77, 198, 155); colors[ImGuiCustomCol_IEEEToolSign] = ImColor(93, 93, 127); colors[ImGuiCustomCol_IEEEToolExp] = ImColor(93, 127, 93); colors[ImGuiCustomCol_IEEEToolMantissa] = ImColor(127, 93, 93); } void OpenPopupInWindow(const char *window_name, const char *popup_name) { if (Begin(window_name)) { OpenPopup(popup_name); } End(); } bool TitleBarButton(const char *label, ImVec2 size_arg) { ImGuiWindow *window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext &g = *GImGui; const ImGuiStyle &style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, nullptr, true); ImVec2 pos = window->DC.CursorPos; ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0F, label_size.y + style.FramePadding.y * 2.0F); const ImRect bb(pos, pos + size); ItemSize(size, style.FramePadding.y); if (!ItemAdd(bb, id)) return false; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held); // Render const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); RenderNavHighlight(bb, id); RenderFrame(bb.Min, bb.Max, col, false, style.FrameRounding); RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, nullptr, &label_size, style.ButtonTextAlign, &bb); // Automatically close popups // if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) // CloseCurrentPopup(); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); return pressed; } bool ToolBarButton(const char *symbol, ImVec4 color) { ImGuiWindow *window = GetCurrentWindow(); if (window->SkipItems) return false; color.w = 1.0F; ImGuiContext &g = *GImGui; const ImGuiStyle &style = g.Style; const ImGuiID id = window->GetID(symbol); const ImVec2 label_size = CalcTextSize(symbol, nullptr, true); ImVec2 pos = window->DC.CursorPos; ImVec2 size = CalcItemSize(ImVec2(1, 1) * GetCurrentWindow()->MenuBarHeight, label_size.x + style.FramePadding.x * 2.0F, label_size.y + style.FramePadding.y * 2.0F); ImVec2 padding = (size - label_size) / 2; const ImRect bb(pos, pos + size); ItemSize(size, style.FramePadding.y); if (!ItemAdd(bb, id)) return false; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held); PushStyleColor(ImGuiCol_Text, color); // Render const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_MenuBarBg); RenderNavHighlight(bb, id); RenderFrame(bb.Min, bb.Max, col, false, style.FrameRounding); RenderTextClipped(bb.Min + padding, bb.Max - padding, symbol, nullptr, &size, style.ButtonTextAlign, &bb); PopStyleColor(); // Automatically close popups // if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) // CloseCurrentPopup(); IMGUI_TEST_ENGINE_ITEM_INFO(id, symbol, g.LastItemData.StatusFlags); return pressed; } bool IconButton(const char *symbol, ImVec4 color, ImVec2 size_arg) { ImGuiWindow *window = GetCurrentWindow(); if (window->SkipItems) return false; color.w = 1.0F; ImGuiContext &g = *GImGui; const ImGuiStyle &style = g.Style; const ImGuiID id = window->GetID(symbol); const ImVec2 label_size = CalcTextSize(symbol, nullptr, true); ImVec2 pos = window->DC.CursorPos; ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0F, label_size.y + style.FramePadding.y * 2.0F); const ImRect bb(pos, pos + size); ItemSize(size, style.FramePadding.y); if (!ItemAdd(bb, id)) return false; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held); PushStyleColor(ImGuiCol_Text, color); // Render const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); RenderNavHighlight(bb, id); RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); RenderTextClipped(bb.Min + style.FramePadding * ImVec2(1.3, 1), bb.Max - style.FramePadding, symbol, nullptr, &label_size, style.ButtonTextAlign, &bb); PopStyleColor(); // Automatically close popups // if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) // CloseCurrentPopup(); IMGUI_TEST_ENGINE_ITEM_INFO(id, symbol, g.LastItemData.StatusFlags); return pressed; } bool InputIntegerPrefix(const char *label, const char *prefix, void *value, ImGuiDataType type, const char *format, ImGuiInputTextFlags flags) { auto window = GetCurrentWindow(); const ImGuiID id = window->GetID(label); const ImGuiStyle &style = GImGui->Style; const ImVec2 label_size = CalcTextSize(label, nullptr, true); const ImVec2 frame_size = CalcItemSize(ImVec2(0, 0), CalcTextSize(prefix).x, label_size.y + style.FramePadding.y * 2.0F); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(CalcItemWidth(), frame_size.y)); SetCursorPosX(GetCursorPosX() + frame_size.x); char buf[64]; DataTypeFormatString(buf, IM_ARRAYSIZE(buf), type, value, format); RenderNavHighlight(frame_bb, id); RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); PushStyleVar(ImGuiStyleVar_Alpha, 0.6F); RenderText(ImVec2(frame_bb.Min.x + style.FramePadding.x, frame_bb.Min.y + style.FramePadding.y), prefix); PopStyleVar(); bool value_changed = false; PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0); PushStyleColor(ImGuiCol_FrameBg, 0x00000000); PushStyleColor(ImGuiCol_FrameBgHovered, 0x00000000); PushStyleColor(ImGuiCol_FrameBgActive, 0x00000000); if (InputTextEx(label, nullptr, buf, IM_ARRAYSIZE(buf), ImVec2(CalcItemWidth() - frame_size.x, label_size.y + style.FramePadding.y * 2.0F), flags)) value_changed = DataTypeApplyFromText(buf, type, value, format); PopStyleColor(3); PopStyleVar(); if (value_changed) MarkItemEdited(GImGui->LastItemData.ID); return value_changed; } bool InputHexadecimal(const char *label, u32 *value, ImGuiInputTextFlags flags) { return InputIntegerPrefix(label, "0x", value, ImGuiDataType_U32, "%lX", flags | ImGuiInputTextFlags_CharsHexadecimal); } bool InputHexadecimal(const char *label, u64 *value, ImGuiInputTextFlags flags) { return InputIntegerPrefix(label, "0x", value, ImGuiDataType_U64, "%llX", flags | ImGuiInputTextFlags_CharsHexadecimal); } bool SliderBytes(const char *label, u64 *value, u64 min, u64 max, ImGuiSliderFlags flags) { std::string format; if (*value < 1024) { format = hex::format("{} Bytes", *value); } else if (*value < 1024 * 1024) { format = hex::format("{:.2f} KB", *value / 1024.0); } else if (*value < 1024 * 1024 * 1024) { format = hex::format("{:.2f} MB", *value / (1024.0 * 1024.0)); } else { format = hex::format("{:.2f} GB", *value / (1024.0 * 1024.0 * 1024.0)); } return ImGui::SliderScalar(label, ImGuiDataType_U64, value, &min, &max, format.c_str(), flags | ImGuiSliderFlags_Logarithmic); } void SmallProgressBar(float fraction, float yOffset) { ImGuiWindow *window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext &g = *GImGui; const ImGuiStyle &style = g.Style; ImVec2 pos = window->DC.CursorPos + ImVec2(0, yOffset); ImVec2 size = CalcItemSize(ImVec2(100, 5) * hex::ImHexApi::System::getGlobalScale(), 100, g.FontSize + style.FramePadding.y * 2.0F); ImRect bb(pos, pos + size); ItemSize(size, 0); if (!ItemAdd(bb, 0)) return; // Render bool no_progress = fraction < 0; fraction = ImSaturate(fraction); RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); bb.Expand(ImVec2(-style.FrameBorderSize, -style.FrameBorderSize)); if (no_progress) { auto time = (fmod(ImGui::GetTime() * 2, 1.8) - 0.4); RenderRectFilledRangeH(window->DrawList, bb, GetColorU32(ImGuiCol_PlotHistogram), ImSaturate(time), ImSaturate(time + 0.2), style.FrameRounding); } else { RenderRectFilledRangeH(window->DrawList, bb, GetColorU32(ImGuiCol_PlotHistogram), 0.0F, fraction, style.FrameRounding); } } void TextUnformattedCentered(const char *text) { auto availableSpace = ImGui::GetContentRegionAvail(); std::string drawString; auto textEnd = text + strlen(text); for (auto wrapPos = text; wrapPos != textEnd;) { wrapPos = ImGui::GetFont()->CalcWordWrapPositionA(1, wrapPos, textEnd, availableSpace.x * 0.8F); drawString += std::string(text, wrapPos) + "\n"; text = wrapPos; } drawString.pop_back(); auto textSize = ImGui::CalcTextSize(drawString.c_str()); ImPlot::AddTextCentered(ImGui::GetWindowDrawList(), ImGui::GetCursorScreenPos() + availableSpace / 2 - ImVec2(0, textSize.y / 2), ImGui::GetColorU32(ImGuiCol_Text), drawString.c_str()); } bool InputTextIcon(const char *label, const char *icon, std::string &buffer, ImGuiInputTextFlags flags) { auto window = GetCurrentWindow(); const ImGuiID id = window->GetID(label); const ImGuiStyle &style = GImGui->Style; const ImVec2 label_size = CalcTextSize(label, nullptr, true); const ImVec2 icon_frame_size = CalcTextSize(icon) + style.FramePadding * 2.0F; const ImVec2 frame_size = CalcItemSize(ImVec2(0, 0), icon_frame_size.x, label_size.y + style.FramePadding.y * 2.0F); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); SetCursorPosX(GetCursorPosX() + frame_size.x); bool value_changed = InputTextEx(label, nullptr, buffer.data(), buffer.size() + 1, ImVec2(CalcItemWidth(), label_size.y + style.FramePadding.y * 2.0F), ImGuiInputTextFlags_CallbackResize | flags, UpdateStringSizeCallback, &buffer); if (value_changed) MarkItemEdited(GImGui->LastItemData.ID); RenderNavHighlight(frame_bb, id); RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); RenderFrame(frame_bb.Min, frame_bb.Min + icon_frame_size, GetColorU32(ImGuiCol_TableBorderStrong), true, style.FrameRounding); RenderText(ImVec2(frame_bb.Min.x + style.FramePadding.x, frame_bb.Min.y + style.FramePadding.y), icon); return value_changed; } bool InputScalarCallback(const char* label, ImGuiDataType data_type, void* p_data, const char* format, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; if (format == nullptr) format = DataTypeGetInfo(data_type)->PrintFmt; char buf[64]; DataTypeFormatString(buf, IM_ARRAYSIZE(buf), data_type, p_data, format); bool value_changed = false; if ((flags & (ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsScientific)) == 0) flags |= ImGuiInputTextFlags_CharsDecimal; flags |= ImGuiInputTextFlags_AutoSelectAll; flags |= ImGuiInputTextFlags_NoMarkEdited; // We call MarkItemEdited() ourselves by comparing the actual data rather than the string. if (ImGui::InputText(label, buf, IM_ARRAYSIZE(buf), flags, callback, user_data)) value_changed = DataTypeApplyFromText(buf, data_type, p_data, format); if (value_changed) MarkItemEdited(g.LastItemData.ID); return value_changed; } void HideTooltip() { char window_name[16]; ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", GImGui->TooltipOverrideCount); if (ImGuiWindow* window = FindWindowByName(window_name); window != nullptr) { if (window->Active) window->Hidden = true; } } bool BitCheckbox(const char* label, bool* v) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, nullptr, true); const ImVec2 size = ImVec2(CalcTextSize("0").x + style.FramePadding.x * 2, GetFrameHeight()); const ImVec2 pos = window->DC.CursorPos; const ImRect total_bb(pos, pos + size); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, id)) { IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0)); return false; } bool hovered, held; bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); if (pressed) { *v = !(*v); MarkItemEdited(id); } const ImRect check_bb(pos, pos + size); RenderNavHighlight(total_bb, id); RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding); RenderText(check_bb.Min + style.FramePadding, *v ? "1" : "0"); ImVec2 label_pos = ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y); if (label_size.x > 0.0F) RenderText(label_pos, label); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0)); return pressed; } bool DimmedButton(const char* label, ImVec2 size){ PushStyleColor(ImGuiCol_ButtonHovered, GetCustomColorU32(ImGuiCustomCol_DescButtonHovered)); PushStyleColor(ImGuiCol_Button, GetCustomColorU32(ImGuiCustomCol_DescButton)); PushStyleColor(ImGuiCol_Text, GetColorU32(ImGuiCol_ButtonActive)); PushStyleColor(ImGuiCol_ButtonActive, GetCustomColorU32(ImGuiCustomCol_DescButtonActive)); PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1); bool res = Button(label, size); PopStyleColor(4); PopStyleVar(1); return res; } bool DimmedIconButton(const char *symbol, ImVec4 color, ImVec2 size){ PushStyleColor(ImGuiCol_ButtonHovered, GetCustomColorU32(ImGuiCustomCol_DescButtonHovered)); PushStyleColor(ImGuiCol_Button, GetCustomColorU32(ImGuiCustomCol_DescButton)); PushStyleColor(ImGuiCol_Text, GetColorU32(ImGuiCol_ButtonActive)); PushStyleColor(ImGuiCol_ButtonActive, GetCustomColorU32(ImGuiCustomCol_DescButtonActive)); PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1); bool res = IconButton(symbol, color, size); PopStyleColor(4); PopStyleVar(1); return res; } bool DimmedButtonToggle(const char *icon, bool *v, ImVec2 size) { bool pushed = false; bool toggled = false; if (*v) { PushStyleColor(ImGuiCol_Border, GetStyleColorVec4(ImGuiCol_ButtonActive)); pushed = true; } if (DimmedIconButton(icon, GetStyleColorVec4(ImGuiCol_Text), size)) { *v = !*v; toggled = true; } if (pushed) PopStyleColor(); return toggled; } bool DimmedIconToggle(const char *icon, bool *v) { bool pushed = false; bool toggled = false; if (*v) { PushStyleColor(ImGuiCol_Border, GetStyleColorVec4(ImGuiCol_ButtonActive)); pushed = true; } if (DimmedIconButton(icon, GetStyleColorVec4(ImGuiCol_Text))) { *v = !*v; toggled = true; } if (pushed) PopStyleColor(); return toggled; } bool DimmedIconToggle(const char *iconOn, const char *iconOff, bool *v) { bool pushed = false; bool toggled = false; if (*v) { PushStyleColor(ImGuiCol_Border, GetStyleColorVec4(ImGuiCol_ButtonActive)); pushed = true; } if (DimmedIconButton(*v ? iconOn : iconOff, GetStyleColorVec4(ImGuiCol_Text))) { *v = !*v; toggled = true; } if (pushed) PopStyleColor(); return toggled; } void TextOverlay(const char *text, ImVec2 pos) { const auto textSize = CalcTextSize(text); const auto textPos = pos - textSize / 2; const auto margin = GetStyle().FramePadding * 2; const auto textRect = ImRect(textPos - margin, textPos + textSize + margin); auto drawList = GetForegroundDrawList(); drawList->AddRectFilled(textRect.Min, textRect.Max, GetColorU32(ImGuiCol_WindowBg) | 0xFF000000); drawList->AddRect(textRect.Min, textRect.Max, GetColorU32(ImGuiCol_Border)); drawList->AddText(textPos, GetColorU32(ImGuiCol_Text), text); } bool BeginBox() { PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2(5, 5)); auto result = BeginTable("##box", 1, ImGuiTableFlags_BordersOuter | ImGuiTableFlags_SizingStretchSame); TableNextRow(); TableNextColumn(); return result; } void EndBox() { EndTable(); PopStyleVar(); } bool BeginSubWindow(const char *label, bool *collapsed, ImVec2 size, ImGuiChildFlags flags) { const bool hasMenuBar = !std::string_view(label).empty(); bool result = false; ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0F); if (ImGui::BeginChild(hex::format("{}##SubWindow", label).c_str(), size, ImGuiChildFlags_Border | ImGuiChildFlags_AutoResizeY | flags, hasMenuBar ? ImGuiWindowFlags_MenuBar : ImGuiWindowFlags_None)) { result = true; if (hasMenuBar && ImGui::BeginMenuBar()) { if (collapsed == nullptr) ImGui::TextUnformatted(label); else { ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, ImGui::GetStyle().FramePadding.y)); ImGui::PushStyleColor(ImGuiCol_Button, 0x00); if (ImGui::Button(label)) *collapsed = !*collapsed; ImGui::PopStyleColor(); ImGui::PopStyleVar(); } ImGui::EndMenuBar(); } if (collapsed != nullptr && *collapsed) { ImGui::SetCursorPosY(ImGui::GetCursorPosY() - (ImGui::GetStyle().FramePadding.y * 2)); ImGuiExt::TextFormattedDisabled("..."); result = false; } } ImGui::PopStyleVar(); return result; } void EndSubWindow() { ImGui::EndChild(); } bool VSliderAngle(const char* label, const ImVec2& size, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format, ImGuiSliderFlags flags) { if (format == nullptr) format = "%.0f deg"; float v_deg = (*v_rad) * 360.0F / (2 * IM_PI); bool value_changed = ImGui::VSliderFloat(label, size, &v_deg, v_degrees_min, v_degrees_max, format, flags); *v_rad = v_deg * (2 * IM_PI) / 360.0F; return value_changed; } bool InputFilePicker(const char *label, std::fs::path &path, const std::vector<hex::fs::ItemFilter> &validExtensions) { bool picked = false; ImGui::PushID(label); const auto buttonSize = ImGui::CalcTextSize("...") + ImGui::GetStyle().FramePadding * 2; ImGui::PushItemWidth(ImGui::CalcItemWidth() - buttonSize.x - ImGui::GetStyle().FramePadding.x); std::string string = wolv::util::toUTF8String(path); if (ImGui::InputText("##pathInput", string, ImGuiInputTextFlags_AutoSelectAll)) { path = std::u8string(string.begin(), string.end()); picked = true; } ImGui::PopItemWidth(); ImGui::SameLine(); if (ImGui::Button("...", buttonSize)) { hex::fs::openFileBrowser(hex::fs::DialogMode::Open, validExtensions, [&](const std::fs::path &pickedPath) { path = pickedPath; picked = true; }); } ImGui::SameLine(); ImGui::TextUnformatted(label); ImGui::PopID(); return picked; } bool ToggleSwitch(const char *label, bool *v) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, nullptr, true); const ImVec2 size = ImVec2(GetFrameHeight() * 2.0F, GetFrameHeight()); const ImVec2 pos = window->DC.CursorPos; const ImRect total_bb(pos, pos + ImVec2(size.x + (label_size.x > 0.0F ? style.ItemInnerSpacing.x + label_size.x : 0.0F), label_size.y + style.FramePadding.y * 2.0F)); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, id)) { IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0)); return false; } bool hovered, held; bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); if (pressed) { *v = !(*v); MarkItemEdited(id); } const ImRect knob_bb(pos, pos + size); window->DrawList->AddRectFilled(knob_bb.Min, knob_bb.Max, GetColorU32(held ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : *v ? ImGuiCol_ButtonActive : ImGuiCol_Button), size.y / 2); if (*v) window->DrawList->AddCircleFilled(knob_bb.Max - ImVec2(size.y / 2, size.y / 2), (size.y - style.ItemInnerSpacing.y) / 2, GetColorU32(ImGuiCol_ScrollbarGrabActive), 16); else window->DrawList->AddCircleFilled(knob_bb.Min + ImVec2(size.y / 2, size.y / 2), (size.y - style.ItemInnerSpacing.y) / 2, GetColorU32(ImGuiCol_ScrollbarGrabActive), 16); ImVec2 label_pos = ImVec2(knob_bb.Max.x + style.ItemInnerSpacing.x, knob_bb.Min.y + style.FramePadding.y); if (g.LogEnabled) LogRenderedText(&label_pos, *v ? "((*) )" : "( (*))"); if (label_size.x > 0.0F) RenderText(label_pos, label); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0)); return pressed; } bool ToggleSwitch(const char *label, bool v) { return ToggleSwitch(label, &v); } bool PopupTitleBarButton(const char* label, bool p_enabled) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const ImGuiID id = window->GetID(label); const ImRect title_rect = window->TitleBarRect(); const ImVec2 size(g.FontSize, g.FontSize); // Button size matches font size for aesthetic consistency. const ImVec2 pos = window->DC.CursorPos; const ImVec2 max_pos = pos + size; const ImRect bb(pos.x, title_rect.Min.y, max_pos.x, title_rect.Max.y); ImGui::PushClipRect(title_rect.Min, title_rect.Max, false); // Check for item addition (similar to how clipping is handled in the original button functions). bool is_clipped = !ItemAdd(bb, id); bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_None); if (is_clipped) { ImGui::PopClipRect(); return pressed; } // const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); // window->DrawList->AddCircleFilled(bb.GetCenter(), ImMax(2.0f, g.FontSize * 0.5f + 1.0f), bg_col); // Draw the label in the center ImU32 text_col = GetColorU32(p_enabled || hovered ? ImGuiCol_Text : ImGuiCol_TextDisabled); window->DrawList->AddText(bb.GetCenter() - ImVec2(g.FontSize * 0.45F, g.FontSize * 0.5F), text_col, label); // Return the button press state ImGui::PopClipRect(); return pressed; } void PopupTitleBarText(const char* text) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const ImRect title_rect = window->TitleBarRect(); const ImVec2 size(g.FontSize, g.FontSize); // Button size matches font size for aesthetic consistency. const ImVec2 pos = window->DC.CursorPos; const ImVec2 max_pos = pos + size; const ImRect bb(pos.x, title_rect.Min.y, max_pos.x, title_rect.Max.y); ImGui::PushClipRect(title_rect.Min, title_rect.Max, false); // Draw the label in the center ImU32 text_col = GetColorU32(ImGuiCol_Text); window->DrawList->AddText(bb.GetCenter() - ImVec2(g.FontSize * 0.45F, g.FontSize * 0.5F), text_col, text); // Return the button press state ImGui::PopClipRect(); } } namespace ImGui { bool InputText(const char *label, std::u8string &buffer, ImGuiInputTextFlags flags) { return ImGui::InputText(label, reinterpret_cast<char *>(buffer.data()), buffer.size() + 1, ImGuiInputTextFlags_CallbackResize | flags, ImGuiExt::UpdateStringSizeCallback, &buffer); } bool InputText(const char *label, std::string &buffer, ImGuiInputTextFlags flags) { return ImGui::InputText(label, buffer.data(), buffer.size() + 1, ImGuiInputTextFlags_CallbackResize | flags, ImGuiExt::UpdateStringSizeCallback, &buffer); } bool InputTextMultiline(const char *label, std::string &buffer, const ImVec2 &size, ImGuiInputTextFlags flags) { return ImGui::InputTextMultiline(label, buffer.data(), buffer.size() + 1, size, ImGuiInputTextFlags_CallbackResize | flags, ImGuiExt::UpdateStringSizeCallback, &buffer); } bool InputTextWithHint(const char *label, const char *hint, std::string &buffer, ImGuiInputTextFlags flags) { return ImGui::InputTextWithHint(label, hint, buffer.data(), buffer.size() + 1, ImGuiInputTextFlags_CallbackResize | flags, ImGuiExt::UpdateStringSizeCallback, &buffer); } }
57,714
C++
.cpp
1,075
43.309767
260
0.634098
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
86
view.cpp
WerWolv_ImHex/lib/libimhex/source/ui/view.cpp
#include <hex/ui/view.hpp> #include <imgui.h> #include <string> namespace hex { View::View(UnlocalizedString unlocalizedName, const char *icon) : m_unlocalizedViewName(std::move(unlocalizedName)), m_icon(icon) { } bool View::shouldDraw() const { return ImHexApi::Provider::isValid() && ImHexApi::Provider::get()->isAvailable(); } bool View::shouldProcess() const { return this->shouldDraw() && this->getWindowOpenState(); } bool View::hasViewMenuItemEntry() const { return true; } ImVec2 View::getMinSize() const { return scaled({ 300, 400 }); } ImVec2 View::getMaxSize() const { return { FLT_MAX, FLT_MAX }; } ImGuiWindowFlags View::getWindowFlags() const { return ImGuiWindowFlags_None; } bool &View::getWindowOpenState() { return m_windowOpen; } const bool &View::getWindowOpenState() const { return m_windowOpen; } const UnlocalizedString &View::getUnlocalizedName() const { return m_unlocalizedViewName; } std::string View::getName() const { return View::toWindowName(m_unlocalizedViewName); } bool View::didWindowJustOpen() { return std::exchange(m_windowJustOpened, false); } void View::setWindowJustOpened(bool state) { m_windowJustOpened = state; } void View::trackViewOpenState() { if (m_windowOpen && !m_prevWindowOpen) this->setWindowJustOpened(true); m_prevWindowOpen = m_windowOpen; } void View::discardNavigationRequests() { if (ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows)) ImGui::GetIO().ConfigFlags &= ~ImGuiConfigFlags_NavEnableKeyboard; } std::string View::toWindowName(const UnlocalizedString &unlocalizedName) { return fmt::format("{}###{}", Lang(unlocalizedName), unlocalizedName.get()); } }
1,923
C++
.cpp
54
29.092593
137
0.662696
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
87
popup.cpp
WerWolv_ImHex/lib/libimhex/source/ui/popup.cpp
#include <hex/ui/popup.hpp> #include <hex/helpers/auto_reset.hpp> namespace hex::impl { [[nodiscard]] std::vector<std::unique_ptr<PopupBase>> &PopupBase::getOpenPopups() { static AutoReset<std::vector<std::unique_ptr<PopupBase>>> openPopups; return openPopups; } std::mutex& PopupBase::getMutex() { static std::mutex mutex; return mutex; } }
398
C++
.cpp
12
27.5
87
0.666667
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
88
http_requests_emscripten.cpp
WerWolv_ImHex/lib/libimhex/source/helpers/http_requests_emscripten.cpp
#if defined(OS_WEB) #include <hex/helpers/http_requests.hpp> namespace hex { HttpRequest::HttpRequest(std::string method, std::string url) : m_method(std::move(method)), m_url(std::move(url)) { emscripten_fetch_attr_init(&m_attr); } HttpRequest::HttpRequest(HttpRequest &&other) noexcept { m_attr = other.m_attr; m_method = std::move(other.m_method); m_url = std::move(other.m_url); m_headers = std::move(other.m_headers); m_body = std::move(other.m_body); } HttpRequest& HttpRequest::operator=(HttpRequest &&other) noexcept { m_attr = other.m_attr; m_method = std::move(other.m_method); m_url = std::move(other.m_url); m_headers = std::move(other.m_headers); m_body = std::move(other.m_body); return *this; } HttpRequest::~HttpRequest() { } void HttpRequest::setDefaultConfig() { } std::future<HttpRequest::Result<std::vector<u8>>> HttpRequest::downloadFile() { return std::async(std::launch::async, [this] { std::vector<u8> response; return this->executeImpl<std::vector<u8>>(response); }); } void HttpRequest::setProxyUrl(std::string proxy) { hex::unused(proxy); } void HttpRequest::setProxyState(bool state) { hex::unused(state); } void HttpRequest::checkProxyErrors() { } int HttpRequest::progressCallback(void *contents, curl_off_t dlTotal, curl_off_t dlNow, curl_off_t ulTotal, curl_off_t ulNow) { hex::unused(contents, dlTotal, dlNow, ulTotal, ulNow); return -1; } } #endif
1,634
C++
.cpp
42
31.904762
131
0.629442
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
89
utils_linux.cpp
WerWolv_ImHex/lib/libimhex/source/helpers/utils_linux.cpp
#if defined(OS_LINUX) #include <hex/helpers/logger.hpp> #include <vector> #include <string> #include <unistd.h> namespace hex { void executeCmd(const std::vector<std::string> &argsVector) { std::vector<char*> cArgsVector; for (const auto &str : argsVector) { cArgsVector.push_back(const_cast<char*>(str.c_str())); } cArgsVector.push_back(nullptr); if (fork() == 0) { execvp(cArgsVector[0], &cArgsVector[0]); log::error("execvp() failed: {}", strerror(errno)); exit(EXIT_FAILURE); } } } #endif
612
C++
.cpp
20
23.65
66
0.59792
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
90
logger.cpp
WerWolv_ImHex/lib/libimhex/source/helpers/logger.cpp
#include <hex/helpers/logger.hpp> #include <hex/api/task_manager.hpp> #include <hex/api/event_manager.hpp> #include <hex/helpers/fs.hpp> #include <hex/helpers/fmt.hpp> #include <hex/helpers/default_paths.hpp> #include <wolv/io/file.hpp> #include <mutex> #include <chrono> #include <fmt/chrono.h> #if defined(OS_WINDOWS) #include <Windows.h> #endif namespace hex::log { namespace { wolv::io::File s_loggerFile; bool s_colorOutputEnabled = false; std::recursive_mutex s_loggerMutex; bool s_loggingSuspended = false; bool s_debugLoggingEnabled = false; } void suspendLogging() { s_loggingSuspended = true; } void resumeLogging() { s_loggingSuspended = false; } void enableDebugLogging() { s_debugLoggingEnabled = true; } namespace impl { void lockLoggerMutex() { s_loggerMutex.lock(); } void unlockLoggerMutex() { s_loggerMutex.unlock(); } bool isLoggingSuspended() { return s_loggingSuspended; } bool isDebugLoggingEnabled() { #if defined(DEBUG) return true; #else return s_debugLoggingEnabled; #endif } FILE *getDestination() { if (s_loggerFile.isValid()) return s_loggerFile.getHandle(); else return stdout; } wolv::io::File& getFile() { return s_loggerFile; } bool isRedirected() { return s_loggerFile.isValid(); } void redirectToFile() { if (s_loggerFile.isValid()) return; for (const auto &path : paths::Logs.all()) { wolv::io::fs::createDirectories(path); s_loggerFile = wolv::io::File(path / hex::format("{0:%Y%m%d_%H%M%S}.log", fmt::localtime(std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()))), wolv::io::File::Mode::Create); s_loggerFile.disableBuffering(); if (s_loggerFile.isValid()) { s_colorOutputEnabled = false; break; } } } void enableColorPrinting() { s_colorOutputEnabled = true; #if defined(OS_WINDOWS) auto hConsole = ::GetStdHandle(STD_OUTPUT_HANDLE); if (hConsole != INVALID_HANDLE_VALUE) { DWORD mode = 0; if (::GetConsoleMode(hConsole, &mode) == TRUE) { mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING | ENABLE_PROCESSED_OUTPUT; ::SetConsoleMode(hConsole, mode); } } #endif } std::vector<LogEntry>& getLogEntries() { static std::vector<LogEntry> logEntries; return logEntries; } void addLogEntry(std::string_view project, std::string_view level, std::string_view message) { getLogEntries().emplace_back(project.data(), level.data(), message.data()); } void printPrefix(FILE *dest, const fmt::text_style &ts, const std::string &level, const char *projectName) { const auto now = fmt::localtime(std::chrono::system_clock::to_time_t(std::chrono::system_clock::now())); fmt::print(dest, "[{0:%H:%M:%S}] ", now); if (s_colorOutputEnabled) fmt::print(dest, ts, "{0} ", level); else fmt::print(dest, "{0} ", level); std::string projectThreadTag = projectName; if (auto threadName = TaskManager::getCurrentThreadName(); !threadName.empty()) projectThreadTag += fmt::format(" | {0}", threadName); constexpr static auto MaxTagLength = 25; if (projectThreadTag.length() > MaxTagLength) projectThreadTag.resize(MaxTagLength); fmt::print(dest, "[{0}] ", projectThreadTag); const auto projectNameLength = projectThreadTag.length(); fmt::print(dest, "{0}", std::string(projectNameLength > MaxTagLength ? 0 : MaxTagLength - projectNameLength, ' ')); } void assertionHandler(const char* exprString, const char* file, int line) { log::error("Assertion failed: {} at {}:{}", exprString, file, line); #if defined (DEBUG) std::abort(); #endif } namespace color { fmt::color debug() { return fmt::color::medium_sea_green; } fmt::color info() { return fmt::color::steel_blue; } fmt::color warn() { return fmt::color::orange; } fmt::color error() { return fmt::color::indian_red; } fmt::color fatal() { return fmt::color::medium_purple; } } } }
4,913
C++
.cpp
123
28.772358
209
0.555509
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
91
http_requests.cpp
WerWolv_ImHex/lib/libimhex/source/helpers/http_requests.cpp
#include <hex/helpers/http_requests.hpp> #include <hex/helpers/crypto.hpp> #include <hex/helpers/fmt.hpp> namespace hex { size_t HttpRequest::writeToVector(void *contents, size_t size, size_t nmemb, void *userdata) { auto &response = *static_cast<std::vector<u8>*>(userdata); auto startSize = response.size(); response.resize(startSize + size * nmemb); std::memcpy(response.data() + startSize, contents, size * nmemb); return size * nmemb; } size_t HttpRequest::writeToFile(void *contents, size_t size, size_t nmemb, void *userdata) { auto &file = *static_cast<wolv::io::File*>(userdata); file.writeBuffer(static_cast<const u8*>(contents), size * nmemb); return size * nmemb; } std::string HttpRequest::urlEncode(const std::string &input) { std::string result; for (char c : input){ if (std::isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') result += c; else result += hex::format("%02X", c); } return result; } std::string HttpRequest::urlDecode(const std::string &input) { std::string result; for (u32 i = 0; i < input.size(); i++){ if (input[i] != '%'){ if (input[i] == '+') result += ' '; else result += input[i]; } else { const auto hex = crypt::decode16(input.substr(i + 1, 2)); if (hex.empty()) return ""; result += char(hex[0]); i += 2; } } return result; } }
1,699
C++
.cpp
45
27.422222
98
0.509744
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
92
tar.cpp
WerWolv_ImHex/lib/libimhex/source/helpers/tar.cpp
#include <hex/helpers/tar.hpp> #include <hex/helpers/literals.hpp> #include <hex/helpers/logger.hpp> #include <hex/helpers/fmt.hpp> #include <wolv/io/file.hpp> #include <microtar.h> namespace hex { using namespace hex::literals; Tar::Tar(const std::fs::path &path, Mode mode) { int tarError = MTAR_ESUCCESS; // Explicitly create file so a short path gets generated if (mode == Mode::Create) { wolv::io::File file(path, wolv::io::File::Mode::Create); file.flush(); } m_ctx = std::make_unique<mtar_t>(); auto shortPath = wolv::io::fs::toShortPath(path); if (mode == Tar::Mode::Read) tarError = mtar_open(m_ctx.get(), shortPath.string().c_str(), "r"); else if (mode == Tar::Mode::Write) tarError = mtar_open(m_ctx.get(), shortPath.string().c_str(), "a"); else if (mode == Tar::Mode::Create) tarError = mtar_open(m_ctx.get(), shortPath.string().c_str(), "w"); else tarError = MTAR_EFAILURE; m_path = path; m_valid = (tarError == MTAR_ESUCCESS); if (!m_valid) { m_tarOpenErrno = tarError; // Hopefully this errno corresponds to the file open call in mtar_open m_fileOpenErrno = errno; } } Tar::~Tar() { this->close(); } Tar::Tar(hex::Tar &&other) noexcept { m_ctx = std::move(other.m_ctx); m_path = other.m_path; m_valid = other.m_valid; m_tarOpenErrno = other.m_tarOpenErrno; m_fileOpenErrno = other.m_fileOpenErrno; other.m_ctx = { }; other.m_valid = false; } Tar &Tar::operator=(Tar &&other) noexcept { m_ctx = std::move(other.m_ctx); m_path = std::move(other.m_path); m_valid = other.m_valid; other.m_valid = false; m_tarOpenErrno = other.m_tarOpenErrno; m_fileOpenErrno = other.m_fileOpenErrno; return *this; } std::vector<std::fs::path> Tar::listEntries(const std::fs::path &basePath) const { std::vector<std::fs::path> result; const std::string PaxHeaderName = "@PaxHeader"; mtar_header_t header; while (mtar_read_header(m_ctx.get(), &header) != MTAR_ENULLRECORD) { std::fs::path path = header.name; if (header.name != PaxHeaderName && wolv::io::fs::isSubPath(basePath, path)) { result.emplace_back(header.name); } mtar_next(m_ctx.get()); } return result; } bool Tar::contains(const std::fs::path &path) const { mtar_header_t header; const auto fixedPath = wolv::io::fs::toNormalizedPathString(path); return mtar_find(m_ctx.get(), fixedPath.c_str(), &header) == MTAR_ESUCCESS; } std::string Tar::getOpenErrorString() const { return hex::format("{}: {}", mtar_strerror(m_tarOpenErrno), std::strerror(m_fileOpenErrno)); } void Tar::close() { if (m_valid) { mtar_finalize(m_ctx.get()); mtar_close(m_ctx.get()); } m_ctx.reset(); m_valid = false; } std::vector<u8> Tar::readVector(const std::fs::path &path) const { mtar_header_t header; const auto fixedPath = wolv::io::fs::toNormalizedPathString(path); int ret = mtar_find(m_ctx.get(), fixedPath.c_str(), &header); if (ret != MTAR_ESUCCESS){ log::debug("Failed to read vector from path {} in tarred file {}: {}", path.string(), m_path.string(), mtar_strerror(ret)); return {}; } std::vector<u8> result(header.size, 0x00); mtar_read_data(m_ctx.get(), result.data(), result.size()); return result; } std::string Tar::readString(const std::fs::path &path) const { auto result = this->readVector(path); return { result.begin(), result.end() }; } void Tar::writeVector(const std::fs::path &path, const std::vector<u8> &data) const { if (path.has_parent_path()) { std::fs::path pathPart; for (const auto &part : path.parent_path()) { pathPart /= part; auto fixedPath = wolv::io::fs::toNormalizedPathString(pathPart); mtar_write_dir_header(m_ctx.get(), fixedPath.c_str()); } } const auto fixedPath = wolv::io::fs::toNormalizedPathString(path); mtar_write_file_header(m_ctx.get(), fixedPath.c_str(), data.size()); mtar_write_data(m_ctx.get(), data.data(), data.size()); } void Tar::writeString(const std::fs::path &path, const std::string &data) const { this->writeVector(path, { data.begin(), data.end() }); } static void writeFile(mtar_t *ctx, const mtar_header_t *header, const std::fs::path &path) { constexpr static u64 BufferSize = 1_MiB; wolv::io::File outputFile(path, wolv::io::File::Mode::Create); std::vector<u8> buffer; for (u64 offset = 0; offset < header->size; offset += BufferSize) { buffer.resize(std::min<u64>(BufferSize, header->size - offset)); mtar_read_data(ctx, buffer.data(), buffer.size()); outputFile.writeVector(buffer); } } void Tar::extract(const std::fs::path &path, const std::fs::path &outputPath) const { mtar_header_t header; mtar_find(m_ctx.get(), path.string().c_str(), &header); writeFile(m_ctx.get(), &header, outputPath); } void Tar::extractAll(const std::fs::path &outputPath) const { mtar_header_t header; while (mtar_read_header(m_ctx.get(), &header) != MTAR_ENULLRECORD) { const auto filePath = std::fs::absolute(outputPath / std::fs::path(header.name)); if (filePath.filename() != "@PaxHeader") { std::fs::create_directories(filePath.parent_path()); writeFile(m_ctx.get(), &header, filePath); } mtar_next(m_ctx.get()); } } }
6,097
C++
.cpp
143
33.342657
100
0.576596
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
93
encoding_file.cpp
WerWolv_ImHex/lib/libimhex/source/helpers/encoding_file.cpp
#include <hex/helpers/encoding_file.hpp> #include <hex/helpers/utils.hpp> #include <wolv/io/file.hpp> #include <wolv/utils/string.hpp> namespace hex { EncodingFile::EncodingFile() : m_mapping(std::make_unique<std::map<size_t, std::map<std::vector<u8>, std::string>>>()) { } EncodingFile::EncodingFile(const hex::EncodingFile &other) { m_mapping = std::make_unique<std::map<size_t, std::map<std::vector<u8>, std::string>>>(*other.m_mapping); m_tableContent = other.m_tableContent; m_longestSequence = other.m_longestSequence; m_shortestSequence = other.m_shortestSequence; m_valid = other.m_valid; m_name = other.m_name; } EncodingFile::EncodingFile(EncodingFile &&other) noexcept { m_mapping = std::move(other.m_mapping); m_tableContent = std::move(other.m_tableContent); m_longestSequence = other.m_longestSequence; m_shortestSequence = other.m_shortestSequence; m_valid = other.m_valid; m_name = std::move(other.m_name); } EncodingFile::EncodingFile(Type type, const std::fs::path &path) : EncodingFile() { auto file = wolv::io::File(path, wolv::io::File::Mode::Read); switch (type) { case Type::Thingy: parse(file.readString()); break; default: return; } { m_name = path.stem().string(); m_name = wolv::util::replaceStrings(m_name, "_", " "); if (!m_name.empty()) m_name[0] = std::toupper(m_name[0]); } m_valid = true; } EncodingFile::EncodingFile(Type type, const std::string &content) : EncodingFile() { switch (type) { case Type::Thingy: parse(content); break; default: return; } m_name = "Unknown"; m_valid = true; } EncodingFile &EncodingFile::operator=(const hex::EncodingFile &other) { m_mapping = std::make_unique<std::map<size_t, std::map<std::vector<u8>, std::string>>>(*other.m_mapping); m_tableContent = other.m_tableContent; m_longestSequence = other.m_longestSequence; m_shortestSequence = other.m_shortestSequence; m_valid = other.m_valid; m_name = other.m_name; return *this; } EncodingFile &EncodingFile::operator=(EncodingFile &&other) noexcept { m_mapping = std::move(other.m_mapping); m_tableContent = std::move(other.m_tableContent); m_longestSequence = other.m_longestSequence; m_shortestSequence = other.m_shortestSequence; m_valid = other.m_valid; m_name = std::move(other.m_name); return *this; } std::pair<std::string_view, size_t> EncodingFile::getEncodingFor(std::span<u8> buffer) const { for (auto riter = m_mapping->crbegin(); riter != m_mapping->crend(); ++riter) { const auto &[size, mapping] = *riter; if (size > buffer.size()) continue; std::vector key(buffer.begin(), buffer.begin() + size); if (mapping.contains(key)) return { mapping.at(key), size }; } return { ".", 1 }; } u64 EncodingFile::getEncodingLengthFor(std::span<u8> buffer) const { for (auto riter = m_mapping->crbegin(); riter != m_mapping->crend(); ++riter) { const auto &[size, mapping] = *riter; if (size > buffer.size()) continue; std::vector key(buffer.begin(), buffer.begin() + size); if (mapping.contains(key)) return size; } return 1; } void EncodingFile::parse(const std::string &content) { m_tableContent = content; for (const auto &line : splitString(m_tableContent, "\n")) { std::string from, to; { auto delimiterPos = line.find('='); if (delimiterPos >= line.length()) continue; from = line.substr(0, delimiterPos); to = line.substr(delimiterPos + 1); if (from.empty()) continue; } auto fromBytes = hex::parseByteString(from); if (fromBytes.empty()) continue; if (to.length() > 1) to = wolv::util::trim(to); if (to.empty()) to = " "; if (!m_mapping->contains(fromBytes.size())) m_mapping->insert({ fromBytes.size(), {} }); u64 keySize = fromBytes.size(); (*m_mapping)[keySize].insert({ std::move(fromBytes), to }); m_longestSequence = std::max(m_longestSequence, keySize); m_shortestSequence = std::min(m_shortestSequence, keySize); } } }
4,850
C++
.cpp
116
31.37931
124
0.564097
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
94
opengl.cpp
WerWolv_ImHex/lib/libimhex/source/helpers/opengl.cpp
#include <hex/helpers/opengl.hpp> #include <opengl_support.h> #include <hex/helpers/utils.hpp> #include <hex/helpers/logger.hpp> #include <wolv/utils/guards.hpp> #include <numbers> namespace hex::gl { Matrix<float,4,4> GetOrthographicMatrix( float viewWidth, float viewHeight, float nearVal,float farVal, bool actionType) { int sign =1; if (actionType) sign=-1; //float left = leftRight.x; //float right = leftRight.y; //float down = upDown.x; //float up = upDown.y; Matrix<float,4,4> result(0); //result.updateElement(0,0,sign /(right-left)) result.updateElement(0,0,sign / viewWidth); //result.updateElement(0,3,sign * (right + left)/(right - left)); //result.updateElement(1,1, sign /(up-down)); result.updateElement(1,1, sign / viewHeight); //result.updateElement(1,3, sign * (up + down)/(up - down)); result.updateElement(2,2,-sign * 2/(farVal - nearVal)); result.updateElement(3,2,-sign * (farVal + nearVal)/(farVal - nearVal)); result.updateElement(3,3,sign); return result; } Matrix<float,4,4> GetPerspectiveMatrix( float viewWidth, float viewHeight, float nearVal,float farVal, bool actionType) { int sign =1; if (actionType) sign=-1; //float left = leftRight.x; //float right = leftRight.y; //float down = upDown.x; //float up = upDown.y; //T aspect=(right-left)/(top-bottom); //T f = nearVal/top; Matrix<float,4,4> result(0); // T f = 1.0 / tan(fovy / 2.0); tan(fovy / 2.0) = top / near; fovy = 2 * atan2(top,near) //result.updateElement(0,0,sign * nearVal/(right-left)); //result.updateElement(1,1, sign * nearVal/(up-down)); result.updateElement(0,0,sign * nearVal/viewWidth); result.updateElement(1,1, sign * nearVal/viewHeight); result.updateElement(2,2,-sign * (farVal + nearVal)/(farVal - nearVal)); result.updateElement(3,2,-sign * 2*farVal*nearVal/(farVal - nearVal)); result.updateElement(2,3,-sign); return result; } Shader::Shader(std::string_view vertexSource, std::string_view fragmentSource) { auto vertexShader = glCreateShader(GL_VERTEX_SHADER); this->compile(vertexShader, vertexSource); auto fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); this->compile(fragmentShader, fragmentSource); ON_SCOPE_EXIT { glDeleteShader(vertexShader); glDeleteShader(fragmentShader); }; m_program = glCreateProgram(); glAttachShader(m_program, vertexShader); glAttachShader(m_program, fragmentShader); glLinkProgram(m_program); int result = false; glGetProgramiv(m_program, GL_LINK_STATUS, &result); if (!result) { std::vector<char> log(512); glGetShaderInfoLog(m_program, log.size(), nullptr, log.data()); log::error("Failed to link shader: {}", log.data()); } } Shader::~Shader() { if (m_program != 0) glDeleteProgram(m_program); } Shader::Shader(Shader &&other) noexcept { m_program = other.m_program; other.m_program = 0; } Shader& Shader::operator=(Shader &&other) noexcept { m_program = other.m_program; other.m_program = 0; return *this; } void Shader::bind() const { glUseProgram(m_program); } void Shader::unbind() const { glUseProgram(0); } void Shader::setUniform(std::string_view name, const int &value) { glUniform1i(getUniformLocation(name), value); } void Shader::setUniform(std::string_view name, const float &value) { glUniform1f(getUniformLocation(name), value); } GLint Shader::getUniformLocation(std::string_view name) { auto uniform = m_uniforms.find(name.data()); if (uniform == m_uniforms.end()) { auto location = glGetUniformLocation(m_program, name.data()); if (location == -1) { log::warn("Uniform '{}' not found in shader", name); return -1; } m_uniforms[name.data()] = location; uniform = m_uniforms.find(name.data()); } return uniform->second; } void Shader::compile(GLuint shader, std::string_view source) const { auto sourcePtr = source.data(); glShaderSource(shader, 1, &sourcePtr, nullptr); glCompileShader(shader); int result = false; glGetShaderiv(shader, GL_COMPILE_STATUS, &result); if (!result) { std::vector<char> log(512); glGetShaderInfoLog(shader, log.size(), nullptr, log.data()); log::error("Failed to compile shader: {}", log.data()); } } template<typename T> Buffer<T>::Buffer(BufferType type, std::span<const T> data) : m_size(data.size()), m_type(GLuint(type)) { glGenBuffers(1, &m_buffer); glBindBuffer(m_type, m_buffer); glBufferData(m_type, data.size_bytes(), data.data(), GL_STATIC_DRAW); glBindBuffer(m_type, 0); } template<typename T> Buffer<T>::~Buffer() { glDeleteBuffers(1, &m_buffer); } template<typename T> Buffer<T>::Buffer(Buffer &&other) noexcept { m_buffer = other.m_buffer; m_size = other.m_size; m_type = other.m_type; other.m_buffer = -1; } template<typename T> Buffer<T>& Buffer<T>::operator=(Buffer &&other) noexcept { m_buffer = other.m_buffer; m_size = other.m_size; m_type = other.m_type; other.m_buffer = -1; return *this; } template<typename T> void Buffer<T>::bind() const { glBindBuffer(m_type, m_buffer); } template<typename T> void Buffer<T>::unbind() const { glBindBuffer(m_type, 0); } template<typename T> size_t Buffer<T>::getSize() const { return m_size; } template<typename T> void Buffer<T>::draw(unsigned primitive) const { switch (m_type) { case GL_ARRAY_BUFFER: glDrawArrays(primitive, 0, m_size); break; case GL_ELEMENT_ARRAY_BUFFER: glDrawElements(primitive, m_size, impl::getType<T>(), nullptr); break; } } template<typename T> void Buffer<T>::update(std::span<const T> data) { glBindBuffer(m_type, m_buffer); glBufferSubData(m_type, 0, data.size_bytes(), data.data()); glBindBuffer(m_type, 0); } template class Buffer<float>; template class Buffer<u32>; template class Buffer<u16>; template class Buffer<u8>; VertexArray::VertexArray() { glGenVertexArrays(1, &m_array); } VertexArray::~VertexArray() { glDeleteVertexArrays(1, &m_array); } VertexArray::VertexArray(VertexArray &&other) noexcept { m_array = other.m_array; other.m_array = -1; } VertexArray& VertexArray::operator=(VertexArray &&other) noexcept { m_array = other.m_array; other.m_array = -1; return *this; } void VertexArray::bind() const { glBindVertexArray(m_array); } void VertexArray::unbind() const { glBindVertexArray(0); } Texture::Texture(u32 width, u32 height) : m_texture(0), m_width(width), m_height(height) { glGenTextures(1, &m_texture); glBindTexture(GL_TEXTURE_2D, m_texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, 0); } Texture::~Texture() { if (m_texture != 0) glDeleteTextures(1, &m_texture); } Texture::Texture(Texture &&other) noexcept { m_texture = other.m_texture; other.m_texture = -1; m_width = other.m_width; m_height = other.m_height; } Texture& Texture::operator=(Texture &&other) noexcept { m_texture = other.m_texture; other.m_texture = -1; return *this; } void Texture::bind() const { glBindTexture(GL_TEXTURE_2D, m_texture); } void Texture::unbind() const { glBindTexture(GL_TEXTURE_2D, 0); } GLuint Texture::getTexture() const { return m_texture; } u32 Texture::getWidth() const { return m_width; } u32 Texture::getHeight() const { return m_height; } GLuint Texture::release() { auto copy = m_texture; m_texture = -1; return copy; } FrameBuffer::FrameBuffer(u32 width, u32 height) { glGenFramebuffers(1, &m_frameBuffer); glBindFramebuffer(GL_FRAMEBUFFER, m_frameBuffer); glGenRenderbuffers(1, &m_renderBuffer); glBindRenderbuffer(GL_RENDERBUFFER, m_renderBuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, m_renderBuffer); glBindRenderbuffer(GL_RENDERBUFFER, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); } FrameBuffer::~FrameBuffer() { glDeleteFramebuffers(1, &m_frameBuffer); glDeleteRenderbuffers(1, &m_renderBuffer); } FrameBuffer::FrameBuffer(FrameBuffer &&other) noexcept { m_frameBuffer = other.m_frameBuffer; other.m_frameBuffer = -1; m_renderBuffer = other.m_renderBuffer; other.m_renderBuffer = -1; } FrameBuffer& FrameBuffer::operator=(FrameBuffer &&other) noexcept { m_frameBuffer = other.m_frameBuffer; other.m_frameBuffer = -1; m_renderBuffer = other.m_renderBuffer; other.m_renderBuffer = -1; return *this; } void FrameBuffer::bind() const { glBindFramebuffer(GL_FRAMEBUFFER, m_frameBuffer); } void FrameBuffer::unbind() const { glBindFramebuffer(GL_FRAMEBUFFER, 0); } void FrameBuffer::attachTexture(const Texture &texture) const { glBindFramebuffer(GL_FRAMEBUFFER, m_frameBuffer); texture.bind(); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture.getTexture(), 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); } AxesVectors::AxesVectors() { m_vertices.resize(36); m_colors.resize(48); m_indices.resize(18); // Vertices are x,y,z. Colors are RGBA. Indices are for the ends of each segment // Entries with value zero are unneeded but kept to help keep track of location // x-axis //vertices[0]=0.0F; vertices[1]= 0.0F vertices[2] = 0.0F; // shaft base m_vertices[3] = 1.0F;//vertices[4]= 0.0F vertices[5] = 0.0F; // shaft tip m_vertices[6] = 0.9F; m_vertices[8] = 0.05F; // arrow base m_vertices[9] = 0.9F; m_vertices[11]=-0.05F; // arrow base // y-axis //vertices[12]=0.0F; vertices[13] = 0.0F; vertices[14]=0.0F;// shaft base m_vertices[16] = 1.0F;//vertices[17]=0.0F;// shaft tip m_vertices[18] = 0.05F; m_vertices[19] = 0.9F;//vertices[20]=0.0F;// arrow base m_vertices[21] =-0.05F; m_vertices[22] = 0.9F;//vertices[23]=0.0F;// arrow base // z-axis //vertices[24]=0.0F; vertices[25]=0.0F vertices[26] = 0.0F; // shaft base m_vertices[29] = 1.0F; // shaft tip m_vertices[30] = 0.05F; m_vertices[32] = 0.9F; // arrow base m_vertices[33] =-0.05F; m_vertices[35] = 0.9F; // arrow base // x-axis colors m_colors[0] = 0.7F; m_colors[3] = 1.0F; m_colors[4] = 0.7F; m_colors[7] = 1.0F; m_colors[8] = 0.7F; m_colors[11] = 1.0F; m_colors[12] = 0.7F; m_colors[15] = 1.0F; // y-axis colors m_colors[17] = 0.7F; m_colors[19] = 1.0F; m_colors[21] = 0.7F; m_colors[23] = 1.0F; m_colors[25] = 0.7F; m_colors[27] = 1.0F; m_colors[29] = 0.7F; m_colors[31] = 1.0F; // z-axis colors m_colors[34] = 0.7F; m_colors[35] = 1.0F; m_colors[38] = 0.7F; m_colors[39] = 1.0F; m_colors[42] = 0.7F; m_colors[43] = 1.0F; m_colors[46] = 0.7F; m_colors[47] = 1.0F; // indices for x m_indices[0] = 0; m_indices[1] = 1; m_indices[2] = 2; m_indices[3] = 1; m_indices[4] = 3; m_indices[5] = 1; // indices for y m_indices[6] = 4; m_indices[7] = 5; m_indices[8] = 6; m_indices[9] = 5; m_indices[10] = 7; m_indices[11] = 5; // indices for z m_indices[12] = 8; m_indices[13] = 9; m_indices[14] = 10; m_indices[15] = 9; m_indices[16] = 11; m_indices[17] = 9; } AxesBuffers::AxesBuffers(const VertexArray& axesVertexArray, const AxesVectors &axesVectors) { m_vertices = {}; m_colors = {}; m_indices = {}; axesVertexArray.bind(); m_vertices = gl::Buffer<float>(gl::BufferType::Vertex, axesVectors.getVertices()); m_colors = gl::Buffer<float>(gl::BufferType::Vertex, axesVectors.getColors()); m_indices = gl::Buffer<u8>(gl::BufferType::Index, axesVectors.getIndices()); axesVertexArray.addBuffer(0, m_vertices); axesVertexArray.addBuffer(1, m_colors, 4); m_vertices.unbind(); m_colors.unbind(); m_indices.unbind(); axesVertexArray.unbind(); } GridVectors::GridVectors(int sliceCount) { m_slices = sliceCount; m_vertices.resize((m_slices + 1) * (m_slices + 1) * 3); m_colors.resize((m_slices + 1) * (m_slices + 1) * 4); m_indices.resize(m_slices * m_slices * 6 + m_slices * 2); int k = 0; int l = 0; for (u32 j = 0; j <= m_slices; ++j) { float z = 2.0F * float(j) / float(m_slices) - 1.0F; for (u32 i = 0; i <= m_slices; ++i) { m_vertices[k ] = 2.0F * float(i) / float(m_slices) - 1.0F; m_vertices[k + 1] = 0.0F; m_vertices[k + 2] = z; k += 3; m_colors[l ] = 0.5F; m_colors[l + 1] = 0.5F; m_colors[l + 2] = 0.5F; m_colors[l + 3] = 0.3F; l += 4; } } k = 0; for (u32 j = 0; j < m_slices; ++j) { int row1 = j * (m_slices + 1); int row2 = (j + 1) * (m_slices + 1); for (u32 i = 0; i < m_slices; ++i) { m_indices[k ] = row1 + i; m_indices[k + 1] = row1 + i + 1; m_indices[k + 2] = row1 + i + 1; m_indices[k + 3] = row2 + i + 1; m_indices[k + 4] = row2 + i + 1; m_indices[k + 5] = row2 + i; k += 6; if (i == 0) { m_indices[k ] = row2 + i; m_indices[k + 1] = row1 + i; k += 2; } } } } GridBuffers::GridBuffers(const VertexArray& gridVertexArray, const GridVectors &gridVectors) { m_vertices = {}; m_colors = {}; m_indices = {}; gridVertexArray.bind(); m_vertices = gl::Buffer<float>(gl::BufferType::Vertex, gridVectors.getVertices()); m_indices = gl::Buffer<u8>(gl::BufferType::Index, gridVectors.getIndices()); m_colors = gl::Buffer<float>(gl::BufferType::Vertex, gridVectors.getColors()); gridVertexArray.addBuffer(0, m_vertices); gridVertexArray.addBuffer(1, m_colors,4); m_vertices.unbind(); m_colors.unbind(); m_indices.unbind(); gridVertexArray.unbind(); } hex::gl::LightSourceVectors::LightSourceVectors(int res) { m_resolution = res; auto res_sq = m_resolution * m_resolution; m_radius = 0.05f; m_vertices.resize((res_sq + 2) * 3); m_normals.resize((res_sq + 2) * 3); m_colors.resize((res_sq + 2) * 4); m_indices.resize(res_sq * 6); constexpr auto TwoPi = std::numbers::pi_v<float> * 2.0F; constexpr auto HalfPi = std::numbers::pi_v<float> / 2.0F; const auto dv = TwoPi / m_resolution; const auto du = std::numbers::pi_v<float> / (m_resolution + 1); m_normals[0] = 0; m_normals[1] = 0; m_normals[2] = 1; m_vertices[0] = 0; m_vertices[1] = 0; m_vertices[2] = m_radius; m_colors[0] = 1.0; m_colors[1] = 1.0; m_colors[2] = 1.0; m_colors[3] = 1.0; // Vertical: pi/2 to -pi/2 for (int i = 0; i < m_resolution; i += 1) { float u = HalfPi - (i + 1) * du; float z = std::sin(u); float xy = std::cos(u); // Horizontal: 0 to 2pi for (int j = 0; j < m_resolution; j += 1) { float v = j * dv; float x = xy * std::cos(v); float y = xy * std::sin(v); i32 n = (i * m_resolution + j + 1) * 3; m_normals[n] = x; m_normals[n + 1] = y; m_normals[n + 2] = z; m_vertices[n] = m_radius * x; m_vertices[n + 1] = m_radius * y; m_vertices[n + 2] = m_radius * z; n = (i * m_resolution + j + 1) * 4; m_colors[n] = 1.0F; m_colors[n + 1] = 1.0F; m_colors[n + 2] = 1.0F; m_colors[n + 3] = 1.0F; } } i32 n = ((res_sq + 1) * 3); m_normals[n ] = 0; m_normals[n + 1] = 0; m_normals[n + 2] = -1; m_vertices[n ] = 0; m_vertices[n + 1] = 0; m_vertices[n + 2] = -m_radius; n = ((res_sq + 1) * 4); m_colors[n ] = 1.0; m_colors[n + 1] = 1.0; m_colors[n + 2] = 1.0; m_colors[n + 3] = 1.0; // that was the easy part, indices are a bit more complicated // and may need some explaining. The RxR grid slices the globe // into longitudes which are the vertical slices and latitudes // which are the horizontal slices. The latitudes are all full // circles except for the poles, so we don't count them as part // of the grid. That means that there are R+2 latitudes and R // longitudes.Between consecutive latitudes we have 2*R triangles. // Since we have R true latitudes there are R-1 spaces between them so // between the top and the bottom we have 2*R*(R-1) triangles. // the top and bottom have R triangles each, so we have a total of // 2*R*(R-1) + 2*R = 2*R*R triangles. Each triangle has 3 vertices, // so we have 6*R*R indices. // The North Pole is index 0 and the South Pole is index 6*res*res -1 // The first row of vertices is 1 to res, the second row is res+1 to 2*res etc. // First, the North Pole for (int i = 0; i < m_resolution; i += 1) { m_indices[i * 3] = 0; m_indices[i * 3 + 1] = i + 1; if (i == m_resolution - 1) m_indices[i * 3 + 2] = 1; else m_indices[i * 3 + 2] = (i + 2); } // Now the spaces between true latitudes for (int i = 0; i < m_resolution - 1; i += 1) { // k is the index of the first vertex of the i-th latitude i32 k = i * m_resolution + 1; // When we go a full circle we need to connect the last vertex to the first, so // we do R-1 first because their indices can be computed easily for (int j = 0; j < m_resolution - 1; j += 1) { // We store the indices of the array where the vertices were store // in the triplets that make the triangles. These triplets are stored in // an array that has indices itself which can be confusing. // l keeps track of the indices of the array that stores the triplets // each i brings 6R and each j 6. 3R from the North Pole. i32 l = (i * m_resolution + j) * 6 + 3 * m_resolution; m_indices[l ] = k + j; m_indices[l + 1] = k + j + m_resolution + 1; m_indices[l + 2] = k + j + 1; m_indices[l + 3] = k + j; m_indices[l + 4] = k + j + m_resolution; m_indices[l + 5] = k + j + m_resolution + 1; } // Now the last vertex of the i-th latitude is connected to the first i32 l = (( i + 1) * m_resolution - 1) * 6 + 3 * m_resolution; m_indices[l ] = k + m_resolution - 1; m_indices[l + 1] = k + m_resolution; m_indices[l + 2] = k; m_indices[l + 3] = k + m_resolution - 1; m_indices[l + 4] = k + 2 * m_resolution - 1; m_indices[l + 5] = k + m_resolution; } // Now the South Pole i32 k = (m_resolution-1) * m_resolution + 1; i32 l = 3 * m_resolution * ( 2 * m_resolution - 1); for (int i = 0; i < m_resolution; i += 1) { if (i == m_resolution -1) m_indices[l + i * 3] = k; else m_indices[l + i * 3] = k + i + 1; m_indices[l + i * 3 + 1] = k + i; m_indices[l + i * 3 + 2] = k + m_resolution; } } void LightSourceVectors::moveTo(const Vector<float, 3> &position) { auto vertexCount = m_vertices.size(); for (unsigned k = 0; k < vertexCount; k += 3) { m_vertices[k ] = m_radius * m_normals[k ] + position[0]; m_vertices[k + 1] = m_radius * m_normals[k + 1] + position[1]; m_vertices[k + 2] = m_radius * m_normals[k + 2] + position[2]; } } LightSourceBuffers::LightSourceBuffers(const VertexArray &sourceVertexArray, const LightSourceVectors &sourceVectors) { sourceVertexArray.bind(); m_vertices = gl::Buffer<float>(gl::BufferType::Vertex, sourceVectors.getVertices()); m_indices = gl::Buffer<u16>(gl::BufferType::Index, sourceVectors.getIndices()); m_normals = gl::Buffer<float>(gl::BufferType::Vertex, sourceVectors.getNormals()); m_colors = gl::Buffer<float>(gl::BufferType::Vertex, sourceVectors.getColors()); sourceVertexArray.addBuffer(0, m_vertices); sourceVertexArray.addBuffer(1, m_normals); sourceVertexArray.addBuffer(2, m_colors, 4); m_vertices.unbind(); m_normals.unbind(); m_colors.unbind(); m_indices.unbind(); sourceVertexArray.unbind(); } void LightSourceBuffers::moveVertices(const VertexArray& sourceVertexArray, const LightSourceVectors& sourceVectors) { sourceVertexArray.bind(); m_vertices.update(sourceVectors.getVertices()); sourceVertexArray.addBuffer(0, m_vertices); sourceVertexArray.unbind(); } void LightSourceBuffers::updateColors(const VertexArray& sourceVertexArray, const LightSourceVectors& sourceVectors) { sourceVertexArray.bind(); m_colors.update(sourceVectors.getColors()); sourceVertexArray.addBuffer(2, m_colors, 4); sourceVertexArray.unbind(); } }
23,710
C++
.cpp
558
32.876344
124
0.556641
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
95
default_paths.cpp
WerWolv_ImHex/lib/libimhex/source/helpers/default_paths.cpp
#include <hex/helpers/default_paths.hpp> #include <hex/api/imhex_api.hpp> #include <hex/api/project_file_manager.hpp> #if defined(OS_WINDOWS) #include <windows.h> #include <shlobj.h> #elif defined(OS_LINUX) || defined(OS_WEB) #include <xdg.hpp> # endif namespace hex::paths { std::vector<std::fs::path> getDataPaths(bool includeSystemFolders) { std::vector<std::fs::path> paths; #if defined(OS_WINDOWS) // In the portable Windows version, we just use the executable directory // Prevent the use of the AppData folder here if (!ImHexApi::System::isPortableVersion()) { PWSTR wAppDataPath = nullptr; if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_LocalAppData, KF_FLAG_CREATE, nullptr, &wAppDataPath))) { paths.emplace_back(wAppDataPath); CoTaskMemFree(wAppDataPath); } } #elif defined(OS_MACOS) paths.push_back(wolv::io::fs::getApplicationSupportDirectoryPath() / "imhex"); #elif defined(OS_LINUX) || defined(OS_WEB) paths.push_back(xdg::DataHomeDir()); auto dataDirs = xdg::DataDirs(); std::copy(dataDirs.begin(), dataDirs.end(), std::back_inserter(paths)); #endif #if defined(OS_MACOS) if (includeSystemFolders) { if (auto executablePath = wolv::io::fs::getExecutablePath(); executablePath.has_value()) { paths.push_back(*executablePath); } } #else for (auto &path : paths) path = path / "imhex"; if (ImHexApi::System::isPortableVersion() || includeSystemFolders) { if (auto executablePath = wolv::io::fs::getExecutablePath(); executablePath.has_value()) paths.push_back(executablePath->parent_path()); } #endif // Add additional data directories to the path auto additionalDirs = ImHexApi::System::getAdditionalFolderPaths(); std::ranges::copy(additionalDirs, std::back_inserter(paths)); // Add the project file directory to the path, if one is loaded if (ProjectFile::hasPath()) { paths.push_back(ProjectFile::getPath().parent_path()); } return paths; } std::vector<std::fs::path> getConfigPaths(bool includeSystemFolders) { #if defined(OS_WINDOWS) return getDataPaths(includeSystemFolders); #elif defined(OS_MACOS) return getDataPaths(includeSystemFolders); #elif defined(OS_LINUX) || defined(OS_WEB) hex::unused(includeSystemFolders); return {xdg::ConfigHomeDir() / "imhex"}; #endif } static std::vector<std::fs::path> appendPath(std::vector<std::fs::path> paths, std::fs::path folder) { folder.make_preferred(); for (auto &path : paths) path = path / folder; return paths; } static std::vector<std::fs::path> getPluginPaths() { std::vector<std::fs::path> paths = getDataPaths(true); // Add the system plugin directory to the path if one was provided at compile time #if defined(OS_LINUX) && defined(SYSTEM_PLUGINS_LOCATION) paths.push_back(SYSTEM_PLUGINS_LOCATION); #endif return paths; } namespace impl { std::vector<std::fs::path> DefaultPath::read() const { auto result = this->all(); std::erase_if(result, [](const auto &entryPath) { return !wolv::io::fs::isDirectory(entryPath); }); return result; } std::vector<std::fs::path> DefaultPath::write() const { auto result = this->read(); std::erase_if(result, [](const auto &entryPath) { return !hex::fs::isPathWritable(entryPath); }); return result; } std::vector<std::fs::path> ConfigPath::all() const { return appendPath(getConfigPaths(false), m_postfix); } std::vector<std::fs::path> DataPath::all() const { return appendPath(getDataPaths(true), m_postfix); } std::vector<std::fs::path> DataPath::write() const { auto result = appendPath(getDataPaths(false), m_postfix); std::erase_if(result, [](const auto &entryPath) { return !hex::fs::isPathWritable(entryPath); }); return result; } std::vector<std::fs::path> PluginPath::all() const { return appendPath(getPluginPaths(), m_postfix); } } }
4,726
C++
.cpp
109
32.495413
117
0.587604
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
96
debugging.cpp
WerWolv_ImHex/lib/libimhex/source/helpers/debugging.cpp
#include <hex/helpers/debugging.hpp> namespace hex::dbg { namespace impl { bool &getDebugWindowState() { static bool state = false; return state; } } }
205
C++
.cpp
9
15.888889
38
0.581152
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
97
fs.cpp
WerWolv_ImHex/lib/libimhex/source/helpers/fs.cpp
#include <hex/helpers/fs.hpp> #include <hex/api/imhex_api.hpp> #include <hex/api/project_file_manager.hpp> #include <hex/helpers/logger.hpp> #include <hex/helpers/fmt.hpp> #include <hex/helpers/utils_linux.hpp> #include <hex/helpers/auto_reset.hpp> #if defined(OS_WINDOWS) #include <windows.h> #include <shlobj.h> #include <shellapi.h> #elif defined(OS_LINUX) || defined(OS_WEB) #include <xdg.hpp> # if defined(OS_FREEBSD) #include <sys/syslimits.h> # else #include <limits.h> # endif #endif #if defined(OS_WEB) #include <emscripten.h> #else #include <GLFW/glfw3.h> #include <nfd.hpp> #endif #include <filesystem> #include <wolv/io/file.hpp> #include <wolv/io/fs.hpp> #include <wolv/utils/string.hpp> #include <fmt/format.h> #include <fmt/xchar.h> namespace hex::fs { static AutoReset<std::function<void(const std::string&)>> s_fileBrowserErrorCallback; void setFileBrowserErrorCallback(const std::function<void(const std::string&)> &callback) { s_fileBrowserErrorCallback = callback; } // With help from https://github.com/owncloud/client/blob/cba22aa34b3677406e0499aadd126ce1d94637a2/src/gui/openfilemanager.cpp void openFileExternal(const std::fs::path &filePath) { // Make sure the file exists before trying to open it if (!wolv::io::fs::exists(filePath)) { return; } #if defined(OS_WINDOWS) hex::unused( ShellExecuteW(nullptr, L"open", filePath.c_str(), nullptr, nullptr, SW_SHOWNORMAL) ); #elif defined(OS_MACOS) hex::unused(system( hex::format("open {}", wolv::util::toUTF8String(filePath)).c_str() )); #elif defined(OS_LINUX) executeCmd({"xdg-open", wolv::util::toUTF8String(filePath)}); #endif } void openFolderExternal(const std::fs::path &dirPath) { // Make sure the folder exists before trying to open it if (!wolv::io::fs::exists(dirPath)) { return; } #if defined(OS_WINDOWS) auto args = fmt::format(L"\"{}\"", dirPath.c_str()); ShellExecuteW(nullptr, L"open", L"explorer.exe", args.c_str(), nullptr, SW_SHOWNORMAL); #elif defined(OS_MACOS) hex::unused(system( hex::format("open {}", wolv::util::toUTF8String(dirPath)).c_str() )); #elif defined(OS_LINUX) executeCmd({"xdg-open", wolv::util::toUTF8String(dirPath)}); #endif } void openFolderWithSelectionExternal(const std::fs::path &selectedFilePath) { // Make sure the file exists before trying to open it if (!wolv::io::fs::exists(selectedFilePath)) { return; } #if defined(OS_WINDOWS) auto args = fmt::format(L"/select,\"{}\"", selectedFilePath.c_str()); ShellExecuteW(nullptr, L"open", L"explorer.exe", args.c_str(), nullptr, SW_SHOWNORMAL); #elif defined(OS_MACOS) hex::unused(system( hex::format( R"(osascript -e 'tell application "Finder" to reveal POSIX file "{}"')", wolv::util::toUTF8String(selectedFilePath) ).c_str() )); system(R"(osascript -e 'tell application "Finder" to activate')"); #elif defined(OS_LINUX) // Fallback to only opening the folder for now // TODO actually select the file executeCmd({"xdg-open", wolv::util::toUTF8String(selectedFilePath.parent_path())}); #endif } #if defined(OS_WEB) std::function<void(std::fs::path)> currentCallback; EMSCRIPTEN_KEEPALIVE extern "C" void fileBrowserCallback(char* path) { currentCallback(path); } EM_JS(int, callJs_saveFile, (const char *rawFilename), { let filename = UTF8ToString(rawFilename) || "file.bin"; FS.createPath("/", "savedFiles"); if (FS.analyzePath(filename).exists) { FS.unlink(filename); } // Call callback that will write the file Module._fileBrowserCallback(stringToNewUTF8("/savedFiles/" + filename)); let data = FS.readFile("/savedFiles/" + filename); const reader = Object.assign(new FileReader(), { onload: () => { // Show popup to user to download let saver = document.createElement('a'); saver.href = reader.result; saver.download = filename; saver.style = "display: none"; saver.click(); }, onerror: () => { throw new Error(reader.error); }, }); reader.readAsDataURL(new File([data], "", { type: "application/octet-stream" })); }); EM_JS(int, callJs_openFile, (bool multiple), { let selector = document.createElement("input"); selector.type = "file"; selector.style = "display: none"; if (multiple) { selector.multiple = true; } selector.onchange = () => { if (selector.files.length == 0) return; FS.createPath("/", "openedFiles"); for (let file of selector.files) { const fr = new FileReader(); fr.onload = () => { let folder = "/openedFiles/"+Math.random().toString(36).substring(2)+"/"; FS.createPath("/", folder); if (FS.analyzePath(folder+file.name).exists) { console.log(`Error: ${folder+file.name} already exist`); } else { FS.createDataFile(folder, file.name, fr.result, true, true); Module._fileBrowserCallback(stringToNewUTF8(folder+file.name)); } }; fr.readAsBinaryString(file); } }; selector.click(); }); bool openFileBrowser(DialogMode mode, const std::vector<ItemFilter> &validExtensions, const std::function<void(std::fs::path)> &callback, const std::string &defaultPath, bool multiple) { switch (mode) { case DialogMode::Open: { currentCallback = callback; callJs_openFile(multiple); break; } case DialogMode::Save: { currentCallback = callback; std::fs::path path; if (!defaultPath.empty()) path = std::fs::path(defaultPath).filename(); else if (!validExtensions.empty()) path = "file." + validExtensions[0].spec; callJs_saveFile(path.filename().string().c_str()); break; } case DialogMode::Folder: { throw std::logic_error("Selecting a folder is not implemented"); return false; } default: std::unreachable(); } return true; } #else bool openFileBrowser(DialogMode mode, const std::vector<ItemFilter> &validExtensions, const std::function<void(std::fs::path)> &callback, const std::string &defaultPath, bool multiple) { // Turn the content of the ItemFilter objects into something NFD understands std::vector<nfdfilteritem_t> validExtensionsNfd; validExtensionsNfd.reserve(validExtensions.size()); for (const auto &extension : validExtensions) { validExtensionsNfd.emplace_back(nfdfilteritem_t{ extension.name.c_str(), extension.spec.c_str() }); } // Clear errors from previous runs NFD::ClearError(); // Try to initialize NFD if (NFD::Init() != NFD_OKAY) { // Handle errors if initialization failed log::error("NFD init returned an error: {}", NFD::GetError()); if (*s_fileBrowserErrorCallback != nullptr) { const auto error = NFD::GetError(); (*s_fileBrowserErrorCallback)(error != nullptr ? error : "No details"); } return false; } NFD::UniquePathU8 outPath; NFD::UniquePathSet outPaths; nfdresult_t result = NFD_ERROR; // Open the correct file dialog based on the mode switch (mode) { case DialogMode::Open: if (multiple) result = NFD::OpenDialogMultiple(outPaths, validExtensionsNfd.data(), validExtensionsNfd.size(), defaultPath.empty() ? nullptr : defaultPath.c_str()); else result = NFD::OpenDialog(outPath, validExtensionsNfd.data(), validExtensionsNfd.size(), defaultPath.empty() ? nullptr : defaultPath.c_str()); break; case DialogMode::Save: result = NFD::SaveDialog(outPath, validExtensionsNfd.data(), validExtensionsNfd.size(), defaultPath.empty() ? nullptr : defaultPath.c_str()); break; case DialogMode::Folder: result = NFD::PickFolder(outPath, defaultPath.empty() ? nullptr : defaultPath.c_str()); break; } if (result == NFD_OKAY){ // Handle the path if the dialog was opened in single mode if (outPath != nullptr) { // Call the provided callback with the path callback(outPath.get()); } // Handle multiple paths if the dialog was opened in multiple mode if (outPaths != nullptr) { nfdpathsetsize_t numPaths = 0; if (NFD::PathSet::Count(outPaths, numPaths) == NFD_OKAY) { // Loop over all returned paths and call the callback with each of them for (size_t i = 0; i < numPaths; i++) { NFD::UniquePathSetPath path; if (NFD::PathSet::GetPath(outPaths, i, path) == NFD_OKAY) callback(path.get()); } } } } else if (result == NFD_ERROR) { // Handle errors that occurred during the file dialog call log::error("Requested file dialog returned an error: {}", NFD::GetError()); if (*s_fileBrowserErrorCallback != nullptr) { const auto error = NFD::GetError(); (*s_fileBrowserErrorCallback)(error != nullptr ? error : "No details"); } } NFD::Quit(); return result == NFD_OKAY; } #endif bool isPathWritable(const std::fs::path &path) { constexpr static auto TestFileName = "__imhex__tmp__"; // Try to open the __imhex__tmp__ file in the given path // If one does exist already, try to delete it { wolv::io::File file(path / TestFileName, wolv::io::File::Mode::Read); if (file.isValid()) { if (!file.remove()) return false; } } // Try to create a new file in the given path // If that fails, or the file cannot be deleted anymore afterward; the path is not writable wolv::io::File file(path / TestFileName, wolv::io::File::Mode::Create); const bool result = file.isValid(); if (!file.remove()) return false; return result; } std::fs::path toShortPath(const std::fs::path &path) { #if defined(OS_WINDOWS) // Get the size of the short path size_t size = GetShortPathNameW(path.c_str(), nullptr, 0); if (size == 0) return path; // Get the short path std::wstring newPath(size, 0x00); GetShortPathNameW(path.c_str(), newPath.data(), newPath.size()); newPath.pop_back(); return newPath; #else // Other supported platforms don't have short paths return path; #endif } }
12,610
C++
.cpp
279
31.770609
194
0.538693
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
98
patches.cpp
WerWolv_ImHex/lib/libimhex/source/helpers/patches.cpp
#include <hex/helpers/patches.hpp> #include <hex/helpers/utils.hpp> #include <hex/providers/provider.hpp> #include <cstring> #include <string_view> namespace hex { namespace { class PatchesGenerator : public hex::prv::Provider { public: explicit PatchesGenerator() = default; ~PatchesGenerator() override = default; [[nodiscard]] bool isAvailable() const override { return true; } [[nodiscard]] bool isReadable() const override { return true; } [[nodiscard]] bool isWritable() const override { return true; } [[nodiscard]] bool isResizable() const override { return true; } [[nodiscard]] bool isSavable() const override { return false; } [[nodiscard]] bool isSavableAsRecent() const override { return false; } [[nodiscard]] bool open() override { return true; } void close() override { } void readRaw(u64 offset, void *buffer, size_t size) override { hex::unused(offset, buffer, size); } void writeRaw(u64 offset, const void *buffer, size_t size) override { for (u64 i = 0; i < size; i += 1) m_patches[offset] = static_cast<const u8*>(buffer)[i]; } [[nodiscard]] u64 getActualSize() const override { if (m_patches.empty()) return 0; else return m_patches.rbegin()->first; } void resizeRaw(u64 newSize) override { hex::unused(newSize); } void insertRaw(u64 offset, u64 size) override { std::vector<std::pair<u64, u8>> patchesToMove; for (auto &[address, value] : m_patches) { if (address > offset) patchesToMove.emplace_back(address, value); } for (const auto &[address, value] : patchesToMove) m_patches.erase(address); for (const auto &[address, value] : patchesToMove) m_patches.insert({ address + size, value }); } void removeRaw(u64 offset, u64 size) override { std::vector<std::pair<u64, u8>> patchesToMove; for (auto &[address, value] : m_patches) { if (address > offset) patchesToMove.emplace_back(address, value); } for (const auto &[address, value] : patchesToMove) m_patches.erase(address); for (const auto &[address, value] : patchesToMove) m_patches.insert({ address - size, value }); } [[nodiscard]] std::string getName() const override { return ""; } [[nodiscard]] std::string getTypeName() const override { return ""; } const std::map<u64, u8>& getPatches() const { return m_patches; } private: std::map<u64, u8> m_patches; }; void pushStringBack(std::vector<u8> &buffer, const std::string &string) { std::copy(string.begin(), string.end(), std::back_inserter(buffer)); } template<typename T> void pushBytesBack(std::vector<u8> &buffer, T bytes) { buffer.resize(buffer.size() + sizeof(T)); std::memcpy((&buffer.back() - sizeof(T)) + 1, &bytes, sizeof(T)); } } wolv::util::Expected<std::vector<u8>, IPSError> Patches::toIPSPatch() const { std::vector<u8> result; pushStringBack(result, "PATCH"); std::vector<u64> addresses; std::vector<u8> values; for (const auto &[address, value] : m_patches) { addresses.push_back(address); values.push_back(value); } std::optional<u64> startAddress; std::vector<u8> bytes; for (u32 i = 0; i < addresses.size(); i++) { if (!startAddress.has_value()) startAddress = addresses[i]; if (i != addresses.size() - 1 && addresses[i] == (addresses[i + 1] - 1)) { bytes.push_back(values[i]); } else { bytes.push_back(values[i]); if (bytes.size() > 0xFFFF) return wolv::util::Unexpected(IPSError::PatchTooLarge); if (startAddress > 0xFFFF'FFFF) return wolv::util::Unexpected(IPSError::AddressOutOfRange); u32 address = startAddress.value(); auto addressBytes = reinterpret_cast<u8 *>(&address); result.push_back(addressBytes[2]); result.push_back(addressBytes[1]); result.push_back(addressBytes[0]); pushBytesBack<u16>(result, changeEndianness<u16>(bytes.size(), std::endian::big)); for (auto byte : bytes) result.push_back(byte); bytes.clear(); startAddress = {}; } } pushStringBack(result, "EOF"); return result; } wolv::util::Expected<std::vector<u8>, IPSError> Patches::toIPS32Patch() const { std::vector<u8> result; pushStringBack(result, "IPS32"); std::vector<u64> addresses; std::vector<u8> values; for (const auto &[address, value] : m_patches) { addresses.push_back(address); values.push_back(value); } std::optional<u64> startAddress; std::vector<u8> bytes; for (u32 i = 0; i < addresses.size(); i++) { if (!startAddress.has_value()) startAddress = addresses[i]; if (i != addresses.size() - 1 && addresses[i] == (addresses[i + 1] - 1)) { bytes.push_back(values[i]); } else { bytes.push_back(values[i]); if (bytes.size() > 0xFFFF) return wolv::util::Unexpected(IPSError::PatchTooLarge); if (startAddress > 0xFFFF'FFFF) return wolv::util::Unexpected(IPSError::AddressOutOfRange); u32 address = startAddress.value(); auto addressBytes = reinterpret_cast<u8 *>(&address); result.push_back(addressBytes[3]); result.push_back(addressBytes[2]); result.push_back(addressBytes[1]); result.push_back(addressBytes[0]); pushBytesBack<u16>(result, changeEndianness<u16>(bytes.size(), std::endian::big)); for (auto byte : bytes) result.push_back(byte); bytes.clear(); startAddress = {}; } } pushStringBack(result, "EEOF"); return result; } wolv::util::Expected<Patches, IPSError> Patches::fromProvider(hex::prv::Provider* provider) { PatchesGenerator generator; generator.getUndoStack().apply(provider->getUndoStack()); if (generator.getActualSize() > 0xFFFF'FFFF) return wolv::util::Unexpected(IPSError::PatchTooLarge); auto patches = generator.getPatches(); return Patches(std::move(patches)); } wolv::util::Expected<Patches, IPSError> Patches::fromIPSPatch(const std::vector<u8> &ipsPatch) { if (ipsPatch.size() < (5 + 3)) return wolv::util::Unexpected(IPSError::InvalidPatchHeader); const char *header = "PATCH"; if (std::memcmp(ipsPatch.data(), header, 5) != 0) return wolv::util::Unexpected(IPSError::InvalidPatchHeader); Patches result; bool foundEOF = false; u32 ipsOffset = 5; while (ipsOffset < ipsPatch.size() - (5 + 3)) { u32 offset = ipsPatch[ipsOffset + 2] | (ipsPatch[ipsOffset + 1] << 8) | (ipsPatch[ipsOffset + 0] << 16); u16 size = ipsPatch[ipsOffset + 4] | (ipsPatch[ipsOffset + 3] << 8); ipsOffset += 5; // Handle normal record if (size > 0x0000) { if (ipsOffset + size > ipsPatch.size() - 3) return wolv::util::Unexpected(IPSError::InvalidPatchFormat); for (u16 i = 0; i < size; i++) result.get()[offset + i] = ipsPatch[ipsOffset + i]; ipsOffset += size; } // Handle RLE record else { if (ipsOffset + 3 > ipsPatch.size() - 3) return wolv::util::Unexpected(IPSError::InvalidPatchFormat); u16 rleSize = ipsPatch[ipsOffset + 0] | (ipsPatch[ipsOffset + 1] << 8); ipsOffset += 2; for (u16 i = 0; i < rleSize; i++) result.get()[offset + i] = ipsPatch[ipsOffset + 0]; ipsOffset += 1; } const char *footer = "EOF"; if (std::memcmp(ipsPatch.data() + ipsOffset, footer, 3) == 0) foundEOF = true; } if (foundEOF) return result; else return wolv::util::Unexpected(IPSError::MissingEOF); } wolv::util::Expected<Patches, IPSError> Patches::fromIPS32Patch(const std::vector<u8> &ipsPatch) { if (ipsPatch.size() < (5 + 4)) return wolv::util::Unexpected(IPSError::InvalidPatchHeader); const char *header = "IPS32"; if (std::memcmp(ipsPatch.data(), header, 5) != 0) return wolv::util::Unexpected(IPSError::InvalidPatchHeader); Patches result; bool foundEEOF = false; u32 ipsOffset = 5; while (ipsOffset < ipsPatch.size() - (5 + 4)) { u32 offset = ipsPatch[ipsOffset + 3] | (ipsPatch[ipsOffset + 2] << 8) | (ipsPatch[ipsOffset + 1] << 16) | (ipsPatch[ipsOffset + 0] << 24); u16 size = ipsPatch[ipsOffset + 5] | (ipsPatch[ipsOffset + 4] << 8); ipsOffset += 6; // Handle normal record if (size > 0x0000) { if (ipsOffset + size > ipsPatch.size() - 3) return wolv::util::Unexpected(IPSError::InvalidPatchFormat); for (u16 i = 0; i < size; i++) result.get()[offset + i] = ipsPatch[ipsOffset + i]; ipsOffset += size; } // Handle RLE record else { if (ipsOffset + 3 > ipsPatch.size() - 3) return wolv::util::Unexpected(IPSError::InvalidPatchFormat); u16 rleSize = ipsPatch[ipsOffset + 0] | (ipsPatch[ipsOffset + 1] << 8); ipsOffset += 2; for (u16 i = 0; i < rleSize; i++) result.get()[offset + i] = ipsPatch[ipsOffset + 0]; ipsOffset += 1; } const char *footer = "EEOF"; if (std::memcmp(ipsPatch.data() + ipsOffset, footer, 4) == 0) foundEEOF = true; } if (foundEEOF) return result; else return wolv::util::Unexpected(IPSError::MissingEOF); } }
11,213
C++
.cpp
240
33.145833
150
0.528061
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
99
http_requests_native.cpp
WerWolv_ImHex/lib/libimhex/source/helpers/http_requests_native.cpp
#if !defined(OS_WEB) #include <hex/helpers/http_requests.hpp> namespace hex { namespace { std::string s_proxyUrl; bool s_proxyState; } HttpRequest::HttpRequest(std::string method, std::string url) : m_method(std::move(method)), m_url(std::move(url)) { AT_FIRST_TIME { curl_global_init(CURL_GLOBAL_ALL); }; AT_FINAL_CLEANUP { curl_global_cleanup(); }; m_curl = curl_easy_init(); } HttpRequest::~HttpRequest() { curl_easy_cleanup(m_curl); } HttpRequest::HttpRequest(HttpRequest &&other) noexcept { m_curl = other.m_curl; other.m_curl = nullptr; m_method = std::move(other.m_method); m_url = std::move(other.m_url); m_headers = std::move(other.m_headers); m_body = std::move(other.m_body); } HttpRequest& HttpRequest::operator=(HttpRequest &&other) noexcept { m_curl = other.m_curl; other.m_curl = nullptr; m_method = std::move(other.m_method); m_url = std::move(other.m_url); m_headers = std::move(other.m_headers); m_body = std::move(other.m_body); return *this; } void HttpRequest::setDefaultConfig() { curl_easy_setopt(m_curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS); curl_easy_setopt(m_curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); curl_easy_setopt(m_curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(m_curl, CURLOPT_USERAGENT, "ImHex/1.0"); curl_easy_setopt(m_curl, CURLOPT_DEFAULT_PROTOCOL, "https"); curl_easy_setopt(m_curl, CURLOPT_SSL_VERIFYPEER, 1L); curl_easy_setopt(m_curl, CURLOPT_SSL_VERIFYHOST, 2L); curl_easy_setopt(m_curl, CURLOPT_TIMEOUT_MS, 0L); curl_easy_setopt(m_curl, CURLOPT_CONNECTTIMEOUT_MS, m_timeout); curl_easy_setopt(m_curl, CURLOPT_NOSIGNAL, 1L); curl_easy_setopt(m_curl, CURLOPT_NOPROGRESS, 0L); curl_easy_setopt(m_curl, CURLOPT_XFERINFODATA, this); curl_easy_setopt(m_curl, CURLOPT_XFERINFOFUNCTION, progressCallback); if (s_proxyState) curl_easy_setopt(m_curl, CURLOPT_PROXY, s_proxyUrl.c_str()); } std::future<HttpRequest::Result<std::vector<u8>>> HttpRequest::downloadFile() { return std::async(std::launch::async, [this] { std::vector<u8> response; curl_easy_setopt(m_curl, CURLOPT_WRITEFUNCTION, writeToVector); curl_easy_setopt(m_curl, CURLOPT_WRITEDATA, &response); return this->executeImpl<std::vector<u8>>(response); }); } void HttpRequest::setProxyUrl(std::string proxy) { s_proxyUrl = std::move(proxy); } void HttpRequest::setProxyState(bool enabled) { s_proxyState = enabled; } void HttpRequest::checkProxyErrors() { if (s_proxyState && !s_proxyUrl.empty()){ log::info("A custom proxy '{0}' is in use. Is it working correctly?", s_proxyUrl); } } int HttpRequest::progressCallback(void *contents, curl_off_t dlTotal, curl_off_t dlNow, curl_off_t ulTotal, curl_off_t ulNow) { auto &request = *static_cast<HttpRequest *>(contents); if (dlTotal > 0) request.m_progress = float(dlNow) / dlTotal; else if (ulTotal > 0) request.m_progress = float(ulNow) / ulTotal; else request.m_progress = 0.0F; return request.m_canceled ? CURLE_ABORTED_BY_CALLBACK : CURLE_OK; } } #endif
3,540
C++
.cpp
84
33.797619
131
0.622994
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
100
magic.cpp
WerWolv_ImHex/lib/libimhex/source/helpers/magic.cpp
#include <hex/helpers/magic.hpp> #include <hex/helpers/utils.hpp> #include <hex/helpers/fs.hpp> #include <hex/helpers/logger.hpp> #include <hex/helpers/default_paths.hpp> #include <wolv/utils/guards.hpp> #include <wolv/utils/string.hpp> #include <hex/providers/provider.hpp> #include <filesystem> #include <optional> #include <string> #include <magic.h> #include <unistd.h> #if defined(OS_WINDOWS) #define MAGIC_PATH_SEPARATOR ";" #else #define MAGIC_PATH_SEPARATOR ":" #endif namespace hex::magic { static std::optional<std::string> getMagicFiles(bool sourceFiles = false) { std::string magicFiles; std::error_code error; for (const auto &dir : paths::Magic.read()) { for (const auto &entry : std::fs::directory_iterator(dir, error)) { auto path = std::fs::absolute(entry.path()); if (sourceFiles) { if (path.extension().empty() || entry.is_directory()) magicFiles += wolv::util::toUTF8String(path) + MAGIC_PATH_SEPARATOR; } else { if (path.extension() == ".mgc") magicFiles += wolv::util::toUTF8String(path) + MAGIC_PATH_SEPARATOR; } } } if (!magicFiles.empty()) magicFiles.pop_back(); if (error) return std::nullopt; else return magicFiles; } bool compile() { magic_t ctx = magic_open(MAGIC_CHECK); ON_SCOPE_EXIT { magic_close(ctx); }; auto magicFiles = getMagicFiles(true); if (!magicFiles.has_value()) return false; if (magicFiles->empty()) return true; std::array<char, 1024> cwd = { }; if (getcwd(cwd.data(), cwd.size()) == nullptr) return false; std::optional<std::fs::path> magicFolder; for (const auto &dir : paths::Magic.write()) { if (std::fs::exists(dir) && fs::isPathWritable(dir)) { magicFolder = dir; break; } } if (!magicFolder.has_value()) { log::error("Could not find a writable magic folder"); return false; } if (chdir(wolv::util::toUTF8String(*magicFolder).c_str()) != 0) return false; auto result = magic_compile(ctx, magicFiles->c_str()) == 0; if (!result) { log::error("Failed to compile magic files \"{}\": {}", *magicFiles, magic_error(ctx)); } if (chdir(cwd.data()) != 0) return false; return result; } std::string getDescription(const std::vector<u8> &data, bool firstEntryOnly) { if (data.empty()) return ""; auto magicFiles = getMagicFiles(); if (magicFiles.has_value()) { magic_t ctx = magic_open(firstEntryOnly ? MAGIC_NONE : MAGIC_CONTINUE); ON_SCOPE_EXIT { magic_close(ctx); }; if (magic_load(ctx, magicFiles->c_str()) == 0) { if (auto description = magic_buffer(ctx, data.data(), data.size()); description != nullptr) { auto result = wolv::util::replaceStrings(description, "\\012-", "\n-"); if (result.ends_with("- data")) result = result.substr(0, result.size() - 6); return result; } } } return ""; } std::string getDescription(prv::Provider *provider, u64 address, size_t size, bool firstEntryOnly) { std::vector<u8> buffer(std::min<u64>(provider->getSize(), size), 0x00); provider->read(address, buffer.data(), buffer.size()); return getDescription(buffer, firstEntryOnly); } std::string getMIMEType(const std::vector<u8> &data, bool firstEntryOnly) { if (data.empty()) return ""; auto magicFiles = getMagicFiles(); if (magicFiles.has_value()) { magic_t ctx = magic_open(MAGIC_MIME_TYPE | (firstEntryOnly ? MAGIC_NONE : MAGIC_CONTINUE)); ON_SCOPE_EXIT { magic_close(ctx); }; if (magic_load(ctx, magicFiles->c_str()) == 0) { if (auto mimeType = magic_buffer(ctx, data.data(), data.size()); mimeType != nullptr) { auto result = wolv::util::replaceStrings(mimeType, "\\012-", "\n-"); if (result.ends_with("- application/octet-stream")) result = result.substr(0, result.size() - 26); return result; } } } return ""; } std::string getMIMEType(prv::Provider *provider, u64 address, size_t size, bool firstEntryOnly) { std::vector<u8> buffer(std::min<u64>(provider->getSize(), size), 0x00); provider->read(address, buffer.data(), buffer.size()); return getMIMEType(buffer, firstEntryOnly); } std::string getExtensions(prv::Provider *provider, u64 address, size_t size, bool firstEntryOnly) { std::vector<u8> buffer(std::min<u64>(provider->getSize(), size), 0x00); provider->read(address, buffer.data(), buffer.size()); return getExtensions(buffer, firstEntryOnly); } std::string getExtensions(const std::vector<u8> &data, bool firstEntryOnly) { if (data.empty()) return ""; auto magicFiles = getMagicFiles(); if (magicFiles.has_value()) { magic_t ctx = magic_open(MAGIC_EXTENSION | (firstEntryOnly ? MAGIC_NONE : MAGIC_CONTINUE)); ON_SCOPE_EXIT { magic_close(ctx); }; if (magic_load(ctx, magicFiles->c_str()) == 0) { if (auto extension = magic_buffer(ctx, data.data(), data.size()); extension != nullptr) { auto result = wolv::util::replaceStrings(extension, "\\012-", "\n-"); if (result.ends_with("- ???")) result = result.substr(0, result.size() - 5); return result; } } } return ""; } std::string getAppleCreatorType(prv::Provider *provider, u64 address, size_t size, bool firstEntryOnly) { std::vector<u8> buffer(std::min<u64>(provider->getSize(), size), 0x00); provider->read(address, buffer.data(), buffer.size()); return getAppleCreatorType(buffer, firstEntryOnly); } std::string getAppleCreatorType(const std::vector<u8> &data, bool firstEntryOnly) { if (data.empty()) return ""; auto magicFiles = getMagicFiles(); if (magicFiles.has_value()) { magic_t ctx = magic_open(MAGIC_APPLE | (firstEntryOnly ? MAGIC_NONE : MAGIC_CONTINUE)); ON_SCOPE_EXIT { magic_close(ctx); }; if (magic_load(ctx, magicFiles->c_str()) == 0) { if (auto result = magic_buffer(ctx, data.data(), data.size()); result != nullptr) return wolv::util::replaceStrings(result, "\\012-", "\n-"); } } return {}; } bool isValidMIMEType(const std::string &mimeType) { // MIME types always contain a slash if (!mimeType.contains("/")) return false; // The MIME type "application/octet-stream" is a fallback type for arbitrary binary data. // Specifying this in a pattern would make it get suggested for every single unknown binary that's being loaded. // We don't want that, so we ignore it here if (mimeType == "application/octet-stream") return false; return true; } }
7,604
C++
.cpp
169
34.349112
120
0.56893
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
101
crypto.cpp
WerWolv_ImHex/lib/libimhex/source/helpers/crypto.cpp
#include <hex/helpers/crypto.hpp> #include <hex/providers/provider.hpp> #include <wolv/utils/guards.hpp> #include <mbedtls/version.h> #include <mbedtls/base64.h> #include <mbedtls/bignum.h> #include <mbedtls/md5.h> #include <mbedtls/sha1.h> #include <mbedtls/sha256.h> #include <mbedtls/sha512.h> #include <mbedtls/cipher.h> #include <array> #include <functional> #include <cstddef> #include <cstdint> #include <bit> #if MBEDTLS_VERSION_MAJOR <= 2 #define mbedtls_md5_starts mbedtls_md5_starts_ret #define mbedtls_md5_update mbedtls_md5_update_ret #define mbedtls_md5_finish mbedtls_md5_finish_ret #define mbedtls_sha1_starts mbedtls_sha1_starts_ret #define mbedtls_sha1_update mbedtls_sha1_update_ret #define mbedtls_sha1_finish mbedtls_sha1_finish_ret #define mbedtls_sha256_starts mbedtls_sha256_starts_ret #define mbedtls_sha256_update mbedtls_sha256_update_ret #define mbedtls_sha256_finish mbedtls_sha256_finish_ret #define mbedtls_sha512_starts mbedtls_sha512_starts_ret #define mbedtls_sha512_update mbedtls_sha512_update_ret #define mbedtls_sha512_finish mbedtls_sha512_finish_ret #endif namespace hex::crypt { using namespace std::placeholders; template<std::invocable<unsigned char *, size_t> Func> void processDataByChunks(prv::Provider *data, u64 offset, size_t size, Func func) { std::array<u8, 512> buffer = { 0 }; for (size_t bufferOffset = 0; bufferOffset < size; bufferOffset += buffer.size()) { const auto readSize = std::min(buffer.size(), size - bufferOffset); data->read(offset + bufferOffset, buffer.data(), readSize); func(buffer.data(), readSize); } } template<typename T> T reflect(T in, std::size_t bits) { T out {}; for (std::size_t i = 0; i < bits; i++) { out <<= 1; if (in & 0b1) out |= 1; in >>= 1; } return out; } template<typename T> T reflect(T in) { if constexpr (sizeof(T) == 1) { T out { in }; out = ((out & 0xf0u) >> 4) | ((out & 0x0fu) << 4); out = ((out & 0xccu) >> 2) | ((out & 0x33u) << 2); out = ((out & 0xaau) >> 1) | ((out & 0x55u) << 1); return out; } else { return reflect(in, sizeof(T) * 8); } } template<size_t NumBits> requires (std::has_single_bit(NumBits)) class Crc { // Use reflected algorithm, so we reflect only if refin / refout is FALSE // mask values, 0b1 << 64 is UB, so use 0b10 << 63 public: constexpr Crc(u64 polynomial, u64 init, u64 xorOut, bool reflectInput, bool reflectOutput) : m_value(0x00), m_init(init & ((0b10ull << (NumBits - 1)) - 1)), m_xorOut(xorOut & ((0b10ull << (NumBits - 1)) - 1)), m_reflectInput(reflectInput), m_reflectOutput(reflectOutput), m_table([polynomial] { auto reflectedPoly = reflect(polynomial & ((0b10ull << (NumBits - 1)) - 1), NumBits); std::array<uint64_t, 256> table = { 0 }; for (uint32_t i = 0; i < 256; i++) { uint64_t c = i; for (std::size_t j = 0; j < 8; j++) { if (c & 0b1) c = reflectedPoly ^ (c >> 1); else c >>= 1; } table[i] = c; } return table; }()) { reset(); } constexpr void reset() { m_value = reflect(m_init, NumBits); } constexpr void processBytes(const unsigned char *data, std::size_t size) { for (std::size_t i = 0; i < size; i++) { u8 byte; if (m_reflectInput) byte = data[i]; else byte = reflect(data[i]); m_value = m_table[(m_value ^ byte) & 0xFFL] ^ (m_value >> 8); } } [[nodiscard]] constexpr u64 checksum() const { if (m_reflectOutput) return m_value ^ m_xorOut; else return reflect(m_value, NumBits) ^ m_xorOut; } private: u64 m_value; u64 m_init; u64 m_xorOut; bool m_reflectInput; bool m_reflectOutput; std::array<uint64_t, 256> m_table; }; template<size_t NumBits> auto calcCrc(prv::Provider *data, u64 offset, std::size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut) { using Crc = Crc<NumBits>; Crc crc(polynomial, init, xorout, reflectIn, reflectOut); processDataByChunks(data, offset, size, std::bind(&Crc::processBytes, &crc, _1, _2)); return crc.checksum(); } u8 crc8(prv::Provider *&data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorOut, bool reflectIn, bool reflectOut) { return calcCrc<8>(data, offset, size, polynomial, init, xorOut, reflectIn, reflectOut); } u16 crc16(prv::Provider *&data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorOut, bool reflectIn, bool reflectOut) { return calcCrc<16>(data, offset, size, polynomial, init, xorOut, reflectIn, reflectOut); } u32 crc32(prv::Provider *&data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorOut, bool reflectIn, bool reflectOut) { return calcCrc<32>(data, offset, size, polynomial, init, xorOut, reflectIn, reflectOut); } std::array<u8, 16> md5(prv::Provider *&data, u64 offset, size_t size) { std::array<u8, 16> result = { 0 }; mbedtls_md5_context ctx; mbedtls_md5_init(&ctx); mbedtls_md5_starts(&ctx); processDataByChunks(data, offset, size, std::bind(mbedtls_md5_update, &ctx, _1, _2)); mbedtls_md5_finish(&ctx, result.data()); mbedtls_md5_free(&ctx); return result; } std::array<u8, 16> md5(const std::vector<u8> &data) { std::array<u8, 16> result = { 0 }; mbedtls_md5_context ctx; mbedtls_md5_init(&ctx); mbedtls_md5_starts(&ctx); mbedtls_md5_update(&ctx, data.data(), data.size()); mbedtls_md5_finish(&ctx, result.data()); mbedtls_md5_free(&ctx); return result; } std::array<u8, 20> sha1(prv::Provider *&data, u64 offset, size_t size) { std::array<u8, 20> result = { 0 }; mbedtls_sha1_context ctx; mbedtls_sha1_init(&ctx); mbedtls_sha1_starts(&ctx); processDataByChunks(data, offset, size, std::bind(mbedtls_sha1_update, &ctx, _1, _2)); mbedtls_sha1_finish(&ctx, result.data()); mbedtls_sha1_free(&ctx); return result; } std::array<u8, 20> sha1(const std::vector<u8> &data) { std::array<u8, 20> result = { 0 }; mbedtls_sha1_context ctx; mbedtls_sha1_init(&ctx); mbedtls_sha1_starts(&ctx); mbedtls_sha1_update(&ctx, data.data(), data.size()); mbedtls_sha1_finish(&ctx, result.data()); mbedtls_sha1_free(&ctx); return result; } std::array<u8, 28> sha224(prv::Provider *&data, u64 offset, size_t size) { std::array<u8, 28> result = { 0 }; mbedtls_sha256_context ctx; mbedtls_sha256_init(&ctx); mbedtls_sha256_starts(&ctx, true); processDataByChunks(data, offset, size, std::bind(mbedtls_sha256_update, &ctx, _1, _2)); mbedtls_sha256_finish(&ctx, result.data()); mbedtls_sha256_free(&ctx); return result; } std::array<u8, 28> sha224(const std::vector<u8> &data) { std::array<u8, 28> result = { 0 }; mbedtls_sha256_context ctx; mbedtls_sha256_init(&ctx); mbedtls_sha256_starts(&ctx, true); mbedtls_sha256_update(&ctx, data.data(), data.size()); mbedtls_sha256_finish(&ctx, result.data()); mbedtls_sha256_free(&ctx); return result; } std::array<u8, 32> sha256(prv::Provider *&data, u64 offset, size_t size) { std::array<u8, 32> result = { 0 }; mbedtls_sha256_context ctx; mbedtls_sha256_init(&ctx); mbedtls_sha256_starts(&ctx, false); processDataByChunks(data, offset, size, std::bind(mbedtls_sha256_update, &ctx, _1, _2)); mbedtls_sha256_finish(&ctx, result.data()); mbedtls_sha256_free(&ctx); return result; } std::array<u8, 32> sha256(const std::vector<u8> &data) { std::array<u8, 32> result = { 0 }; mbedtls_sha256_context ctx; mbedtls_sha256_init(&ctx); mbedtls_sha256_starts(&ctx, false); mbedtls_sha256_update(&ctx, data.data(), data.size()); mbedtls_sha256_finish(&ctx, result.data()); mbedtls_sha256_free(&ctx); return result; } std::array<u8, 48> sha384(prv::Provider *&data, u64 offset, size_t size) { std::array<u8, 48> result = { 0 }; mbedtls_sha512_context ctx; mbedtls_sha512_init(&ctx); mbedtls_sha512_starts(&ctx, true); processDataByChunks(data, offset, size, std::bind(mbedtls_sha512_update, &ctx, _1, _2)); mbedtls_sha512_finish(&ctx, result.data()); mbedtls_sha512_free(&ctx); return result; } std::array<u8, 48> sha384(const std::vector<u8> &data) { std::array<u8, 48> result = { 0 }; mbedtls_sha512_context ctx; mbedtls_sha512_init(&ctx); mbedtls_sha512_starts(&ctx, true); mbedtls_sha512_update(&ctx, data.data(), data.size()); mbedtls_sha512_finish(&ctx, result.data()); mbedtls_sha512_free(&ctx); return result; } std::array<u8, 64> sha512(prv::Provider *&data, u64 offset, size_t size) { std::array<u8, 64> result = { 0 }; mbedtls_sha512_context ctx; mbedtls_sha512_init(&ctx); mbedtls_sha512_starts(&ctx, false); processDataByChunks(data, offset, size, std::bind(mbedtls_sha512_update, &ctx, _1, _2)); mbedtls_sha512_finish(&ctx, result.data()); mbedtls_sha512_free(&ctx); return result; } std::array<u8, 64> sha512(const std::vector<u8> &data) { std::array<u8, 64> result = { 0 }; mbedtls_sha512_context ctx; mbedtls_sha512_init(&ctx); mbedtls_sha512_starts(&ctx, false); mbedtls_sha512_update(&ctx, data.data(), data.size()); mbedtls_sha512_finish(&ctx, result.data()); mbedtls_sha512_free(&ctx); return result; } std::vector<u8> decode64(const std::vector<u8> &input) { size_t written = 0; mbedtls_base64_decode(nullptr, 0, &written, input.data(), input.size()); std::vector<u8> output(written, 0x00); if (mbedtls_base64_decode(output.data(), output.size(), &written, input.data(), input.size())) return {}; output.resize(written); return output; } std::vector<u8> encode64(const std::vector<u8> &input) { size_t written = 0; mbedtls_base64_encode(nullptr, 0, &written, input.data(), input.size()); std::vector<u8> output(written, 0x00); if (mbedtls_base64_encode(output.data(), output.size(), &written, input.data(), input.size())) return {}; output.resize(written); return output; } std::vector<u8> decode16(const std::string &input) { std::vector<u8> output(input.length() / 2, 0x00); mbedtls_mpi ctx; mbedtls_mpi_init(&ctx); ON_SCOPE_EXIT { mbedtls_mpi_free(&ctx); }; // Read buffered constexpr static auto BufferSize = 0x100; for (size_t offset = 0; offset < input.size(); offset += BufferSize) { std::string inputPart = input.substr(offset, std::min<size_t>(BufferSize, input.size() - offset)); if (mbedtls_mpi_read_string(&ctx, 16, inputPart.c_str())) return {}; if (mbedtls_mpi_write_binary(&ctx, output.data() + offset / 2, inputPart.size() / 2)) return {}; } return output; } std::string encode16(const std::vector<u8> &input) { if (input.empty()) return {}; std::string output(input.size() * 2, '\0'); for (size_t i = 0; i < input.size(); i++) { output[2 * i + 0] = "0123456789ABCDEF"[input[i] / 16]; output[2 * i + 1] = "0123456789ABCDEF"[input[i] % 16]; } return output; } template<typename T> static T safeLeftShift(T t, u32 shift) { if (shift >= sizeof(t) * 8) { return 0; } else { return t << shift; } } template<typename T> static T decodeLeb128(const std::vector<u8> &bytes) { T value = 0; u32 shift = 0; u8 b = 0; for (u8 byte : bytes) { b = byte; value |= safeLeftShift(static_cast<T>(byte & 0x7F), shift); shift += 7; if ((byte & 0x80) == 0) { break; } } if constexpr(std::signed_integral<T>) { if ((b & 0x40) != 0) { value |= safeLeftShift(~static_cast<T>(0), shift); } } return value; } u128 decodeUleb128(const std::vector<u8> &bytes) { return decodeLeb128<u128>(bytes); } i128 decodeSleb128(const std::vector<u8> &bytes) { return decodeLeb128<i128>(bytes); } template<typename T> static std::vector<u8> encodeLeb128(T value) { std::vector<u8> bytes; u8 byte; while (true) { byte = value & 0x7F; value >>= 7; if constexpr(std::signed_integral<T>) { if (value == 0 && (byte & 0x40) == 0) { break; } if (value == -1 && (byte & 0x40) != 0) { break; } } else { if (value == 0) { break; } } bytes.push_back(byte | 0x80); } bytes.push_back(byte); return bytes; } std::vector<u8> encodeUleb128(u128 value) { return encodeLeb128<u128>(value); } std::vector<u8> encodeSleb128(i128 value) { return encodeLeb128<i128>(value); } static std::vector<u8> aes(mbedtls_cipher_type_t type, mbedtls_operation_t operation, const std::vector<u8> &key, std::array<u8, 8> nonce, std::array<u8, 8> iv, const std::vector<u8> &input) { std::vector<u8> output; if (input.empty()) return {}; if (key.size() > 256) return {}; mbedtls_cipher_context_t ctx; auto cipherInfo = mbedtls_cipher_info_from_type(type); mbedtls_cipher_setup(&ctx, cipherInfo); mbedtls_cipher_setkey(&ctx, key.data(), key.size() * 8, operation); std::array<u8, 16> nonceCounter = { 0 }; std::copy(nonce.begin(), nonce.end(), nonceCounter.begin()); std::copy(iv.begin(), iv.end(), nonceCounter.begin() + 8); size_t outputSize = input.size() + mbedtls_cipher_get_block_size(&ctx); output.resize(outputSize, 0x00); mbedtls_cipher_crypt(&ctx, nonceCounter.data(), nonceCounter.size(), input.data(), input.size(), output.data(), &outputSize); mbedtls_cipher_free(&ctx); output.resize(input.size()); return output; } std::vector<u8> aesDecrypt(AESMode mode, KeyLength keyLength, const std::vector<u8> &key, std::array<u8, 8> nonce, std::array<u8, 8> iv, const std::vector<u8> &input) { switch (keyLength) { case KeyLength::Key128Bits: if (key.size() != 128 / 8) return {}; break; case KeyLength::Key192Bits: if (key.size() != 192 / 8) return {}; break; case KeyLength::Key256Bits: if (key.size() != 256 / 8) return {}; break; default: return {}; } mbedtls_cipher_type_t type; switch (mode) { case AESMode::ECB: type = MBEDTLS_CIPHER_AES_128_ECB; break; case AESMode::CBC: type = MBEDTLS_CIPHER_AES_128_CBC; break; case AESMode::CFB128: type = MBEDTLS_CIPHER_AES_128_CFB128; break; case AESMode::CTR: type = MBEDTLS_CIPHER_AES_128_CTR; break; case AESMode::GCM: type = MBEDTLS_CIPHER_AES_128_GCM; break; case AESMode::CCM: type = MBEDTLS_CIPHER_AES_128_CCM; break; case AESMode::OFB: type = MBEDTLS_CIPHER_AES_128_OFB; break; case AESMode::XTS: type = MBEDTLS_CIPHER_AES_128_XTS; break; default: return {}; } type = mbedtls_cipher_type_t(type + u8(keyLength)); return aes(type, MBEDTLS_DECRYPT, key, nonce, iv, input); } }
17,328
C++
.cpp
428
30.495327
196
0.55878
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
102
imgui_hooks.cpp
WerWolv_ImHex/lib/libimhex/source/helpers/imgui_hooks.cpp
#include <hex/api/event_manager.hpp> #include <imgui.h> #include <imgui_internal.h> #include <array> void ImGuiTestEngineHook_ItemAdd(ImGuiContext*, ImGuiID id, const ImRect& bb, const ImGuiLastItemData*) { std::array<float, 4> boundingBox = { bb.Min.x, bb.Min.y, bb.Max.x, bb.Max.y }; hex::EventImGuiElementRendered::post(id, boundingBox); } void ImGuiTestEngineHook_ItemInfo(ImGuiContext*, ImGuiID, const char*, ImGuiItemStatusFlags) {} void ImGuiTestEngineHook_Log(ImGuiContext*, const char*, ...) {} const char* ImGuiTestEngine_FindItemDebugLabel(ImGuiContext*, ImGuiID) { return nullptr; }
606
C++
.cpp
11
53.090909
105
0.766892
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false