### Minimal ZN module Source: https://github.com/hsskyboy/nyazygisk This example demonstrates the minimal structure of a Zygisk Next module. It shows how to define a module with the required target_api_version and onModuleLoaded callback, and how to use the API to hook a function in a library. ```APIDOC ## Minimal ZN module ### Description This example demonstrates the minimal structure of a Zygisk Next module. It shows how to define a module with the required target_api_version and onModuleLoaded callback, and how to use the API to hook a function in a library. ### Code Example ```c #include static void (*orig_read)(int, void *, size_t); static void on_module_loaded(void *self, const struct ZygiskNextAPI *api) { // PLT hook read() in libc.so of this process void *base = api->getBaseAddress(api->newSymbolResolver("libc.so", 0)); if (base && api->pltHook(base, "read", (void *) my_read, (void **) &orig_read)) { // hooked } } struct ZygiskNextModule zn_module = { .target_api_version = ZYGISK_NEXT_API_VERSION, .onModuleLoaded = on_module_loaded, }; ``` ``` -------------------------------- ### Lifecycle wiring conceptual flow from module.cpp Source: https://github.com/hsskyboy/nyazygisk Conceptual comment block from module.cpp showing the injected library entry flow: hook_entry installs 25 JNI hooks, then on app fork the nativeForkAndSpecialize wrapper runs pre/post hooks via ZygiskContext, calling run_modules_pre/post and each ZygiskModule's preAppSpecialize/postAppSpecialize. For exact ordering, see ZygiskContext::fork_pre/post, app_specialize_pre/post, server_specialize_pre/post in loader/src/injector/module.cpp. ```cpp // Injected library entry (entry.cpp) calls hook_entry(addr, size); // that installs the 25 JNI hooks into Zygote. When an app forks: // nativeForkAndSpecialize wrapper // -> ZygiskContext ctx(env, &args) // -> ctx.nativeForkAndSpecialize_pre(); // -> ctx.run_modules_pre(); // fork_pre -> app_specialize_pre // each ZygiskModule::preAppSpecialize(args) // -> original method (the real fork) // -> ctx.nativeForkAndSpecialize_post(); // -> run_modules_post(); // app_specialize_post -> fork_post // each ZygiskModule::postAppSpecialize(args) ``` -------------------------------- ### Injected entry on boot in SPAWN mode Source: https://github.com/hsskyboy/nyazygisk Shows the core actions inside entry() when mode == TraceMode::SPAWN (default for monitord zygote). It installs 25 Zygote JNI hooks, sends a seccomp event if needed, and loads ZN modules matching "zygote". After this, app forks run nativeForkAndSpecialize wrappers from jni_hooks.hpp. ```cpp // inside entry(): mode == TraceMode::SPAWN (default for monitord zygote) hook_entry(addr, size); // install 25 Zygote JNI hooks send_seccomp_event_if_needed(); zn::loadAllModules(); // load ZN modules matching "zygote" // app forks now run nativeForkAndSpecialize wrappers from jni_hooks.hpp ``` -------------------------------- ### HyperOS runtime registration with error handling Source: https://github.com/hsskyboy/nyazygisk This example shows how to register a module for the HyperOS runtime. It demonstrates checking the runtime type, setting up the module structure, and handling registration errors. ```APIDOC ## HyperOS runtime registration with error handling ### Description This example shows how to register a module for the HyperOS runtime. It demonstrates checking the runtime type, setting up the module structure, and handling registration errors. ### Code Example ```c #include static void on_app_specialized(const struct ZnHyosAppSpecializeArgs *args) { // runs per app forked by hyos_spawner: process_name, package_name, se_info } static void on_module_loaded(void *self, const struct ZygiskNextAPI *api) { const struct ZygiskNextRuntime *rt = api->getRuntime(); if (!rt) return; if (rt->type != ZN_RUNTIME_HYOS) return; struct ZygiskNextHyosModule mod = { .target_api_version = ZYGISK_NEXT_HYOS_API_VERSION, .onAppSpecialized = on_app_specialized, }; int rc = rt->registerModule(&mod); // ZN_SUCCESS (0) or ZN_FAILED (1) if (rc != ZN_SUCCESS) { /* too many modules, bad version, or absent callback */ } } struct ZygiskNextModule zn_module = { .target_api_version = ZYGISK_NEXT_API_VERSION, .onModuleLoaded = on_module_loaded, }; ``` ``` -------------------------------- ### GetProcessFlags (1) Source: https://github.com/hsskyboy/nyazygisk Retrieves per-UID root/denylist/exclusion state for specializing processes. Only root can call it; non-root peers get 0. ```APIDOC ## GetProcessFlags (1) ### Description Per-UID root/denylist/exclusion state for specializing processes. ### Auth **root only**. ### Request `[2][u32 uid]` ### Reply `[u32 flags]` — bitmask of `ProcessFlags` (`PROCESS_GRANTED_ROOT = 1<<0`, `PROCESS_ON_DENYLIST = 1<<1`, `PROCESS_EXCLUDED = 1<<26`, `PROCESS_IS_MANAGER = 1<<27`, `PROCESS_ROOT_IS_APATCH = 1<<28`, `PROCESS_ROOT_IS_KSU = 1<<29`, `PROCESS_ROOT_IS_MAGISK = 1<<30`). Cached in shared memory; non-root peers get `0`. ``` -------------------------------- ### enum Command (loader/src/ptracer/main.hpp) Source: https://github.com/hsskyboy/nyazygisk Defines commands sent between the monitor and daemon. START, STOP, EXIT, ZYGOTE_INJECTED, DAEMON_SET_INFO, DAEMON_SET_ERROR_INFO, SYSTEM_SERVER_STARTED, and REARM are used to control tracing and refresh module snapshots. ```cpp enum Command { START = 1, // start tracing STOP = 2, // stop tracing EXIT = 3, // monitor exits ZYGOTE_INJECTED = 4, // sent from daemon DAEMON_SET_INFO = 5, // sent from daemon DAEMON_SET_ERROR_INFO = 6, SYSTEM_SERVER_STARTED = 7, REARM = 8, // refresh module snapshot + live-attach running zygote/system_server }; ``` -------------------------------- ### Get ZN plan and report module load Source: https://github.com/hsskyboy/nyazygisk Retrieves the ZygiskNext plan for a given process and reports whether each module library was loaded. Requires root or AID_SYSTEM for GetZnPlan and ReportZnModule. ```cpp auto plan = zygiskd::GetZnPlan("zygote", "/system/bin/app_process64"); // vector for (auto &entry : plan) { // entry.lib_path, entry.companion, entry.lib_fd.get() bool loaded = dlopen_fd(entry.lib_fd.get()); zygiskd::ReportZnModule(entry.lib_path, loaded); } ``` -------------------------------- ### enum TracingState, struct Status, struct StartCounter (loader/src/ptracer/types.hpp) Source: https://github.com/hsskyboy/nyazygisk Defines tracing state (TRACING, STOPPING, STOPPED, EXITING), status fields for daemon and zygote injection, and a start counter with last start time and count. ```cpp enum TracingState { TRACING = 1, STOPPING, STOPPED, EXITING }; struct Status { bool supported = false; bool zygote_injected = false; bool daemon_running = false; pid_t daemon_pid = -1; std::string daemon_info; std::string daemon_error_info; }; struct StartCounter { struct timespec last_start_time{.tv_sec = 0, .tv_nsec = 0}; int count = 0; }; ``` -------------------------------- ### ZygoteAbiManager class declaration (zygote_abi.hpp) Source: https://github.com/hsskyboy/nyazygisk Declares the per-architecture ZygoteAbiManager. Crash loop policy: if Zygote crashes more than 5 times within 60 seconds, the monitor stops arming, writes the reason into the status file, and waits. rearm() starts the daemon if gone, rebuilds the module snapshot, and forks detached children running 'tracer trace ' against an already-running zygote and system_server; a failed attach resumes the target uninjected. ```cpp class ZygoteAbiManager { public: static constexpr int CRASH_LOOP_RETRY_COUNT = 5; static constexpr int CRASH_LOOP_WINDOW_SECONDS = 60; ZygoteAbiManager(AppMonitor& monitor, bool is_64bit); bool handle_daemon_exit_if_match(int pid, int process_status); const char* check_and_prepare_injection(); const char* prepare_aux_injection(); // non-Zygote targets (hyos_spawner) bool rearm(); // live-attach running zygote + system_server const Status& get_status() const; void notify_injected(); void notify_system_server_started(); void set_daemon_info(std::string_view info); void set_daemon_crashed(std::string_view error); const char* const abi_name_; const std::string program_path_; private: bool is_in_crash_loop(); bool ensure_daemon_created(bool* started = nullptr); void attach_running(pid_t pid, const char* mode_flag, const char* what); Status status_; StartCounter counter; std::string tracer_path_; std::string daemon_path_; AppMonitor& monitor_; }; ``` -------------------------------- ### void SystemServerStarted() Source: https://github.com/hsskyboy/nyazygisk Writes `SystemServerStarted`; daemon forwards `SYSTEM_SERVER_STARTED` (7) to the monitor. ```APIDOC ## void SystemServerStarted() ### Description Writes `SystemServerStarted`; daemon forwards `SYSTEM_SERVER_STARTED` (7) to the monitor. ``` -------------------------------- ### void Init(const char* path) Source: https://github.com/hsskyboy/nyazygisk Initializes the client-side TMP_PATH so sockets resolve to `$TMP/.sock`. Call before any other function. ```APIDOC ## void Init(const char* path) ### Description Initializes the client-side TMP_PATH so sockets resolve to `$TMP/.sock`. Call before any other function. ### Parameters - **path** (const char*) - Required - The path to initialize TMP_PATH. ``` -------------------------------- ### CLI usage: monitor | trace | ctl | version Source: https://github.com/hsskyboy/nyazygisk Shows the command-line syntax for the ptracer binary. Use 'monitor' to run the init monitor, 'trace ' for one-shot injection with optional mode flags, 'ctl' to send datagram commands to the control socket, and 'version' to print the version string. ```text usage: monitor | trace [--spawn | --standalone | --system_server] | ctl | version ``` -------------------------------- ### zygiskd::Init Source: https://github.com/hsskyboy/nyazygisk Initializes the zygiskd client library. Must be called before using other functions. ```APIDOC ## zygiskd::Init ### Description Initializes the zygiskd client library. Must be called before using other functions. ### Method Function call ### Signature `zygiskd::Init("/data/system_de/nyazygisk")` ### Parameters - **path** (string) - Required - Path to the daemon's data directory. ### Example ```cpp zygiskd::Init("/data/system_de/nyazygisk"); ``` ``` -------------------------------- ### ZygiskModule struct definition Source: https://github.com/hsskyboy/nyazygisk Defines the ZygiskModule struct used for each loaded module. The constructor takes the module index (id), dlopen handle, and resolved zygisk_module_entry function. RegisterModuleImpl adapts the module's api_version to the correct ApiTable view and installs dispatch stubs. ```cpp 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(); bool tryUnload() const; bool loadedBySystem() const; // true when the system linker (fallback) loaded this module 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; }; ``` -------------------------------- ### ReadModules (4) Source: https://github.com/hsskyboy/nyazygisk Fetches the module libraries to dlopen. Returns a snapshot of modules with sealed/read-only memfds. ```APIDOC ## ReadModules (4) ### Description The injected process fetches the module libraries to `dlopen`. ### Auth uid 0 or 1000. ### Request `[5]` ### Reply `[usize count]` then per module `[string name][fd memfd]`. One snapshot per reply; memfds are sealed/read-only. ``` -------------------------------- ### zygisk::Option enum definition Source: https://github.com/hsskyboy/nyazygisk Defines the Option enum with two values. FORCE_DENYLIST_UNMOUNT forces Magisk's DenyList unmount routines and is only meaningful in preAppSpecialize. DLCLOSE_MODULE_LIBRARY dlcloses the module library after post[XXX]Specialize; never enable after hooking functions because all module code gets unmapped. ```cpp enum Option : int { FORCE_DENYLIST_UNMOUNT = 0, DLCLOSE_MODULE_LIBRARY = 1, }; ``` -------------------------------- ### GetZnPlan (11) Source: https://github.com/hsskyboy/nyazygisk Retrieves the list of ZN modules to inject into the current process. The request includes the process name and path, and the reply contains the module entries. ```APIDOC ## GetZnPlan (11) ### Description Retrieves the list of ZN modules to inject into the current process, based on the process name and path. ### Method Unknown (custom protocol) ### Endpoint GetZnPlan (11) ### Parameters #### Request Body - `process_name` (string) - Required - The name of the current process. - `process_path` (string) - Required - The path of the current process. ### Response #### Success Response - `count` (usize) - Number of module entries. - Per entry: - `lib_path` (string) - Path to the library. - `companion` (u8) - Companion flag. - `lib_fd` (fd) - File descriptor for the library. ### Auth - uid 0 or 1000. ``` -------------------------------- ### zn::loadAllModules Source: https://github.com/hsskyboy/nyazygisk Loads all ZN modules. It scans /data/adb/modules/*/zn_modules.txt, asks the daemon for the ZN plan (GetZnPlan), loads matching libraries via modloader::Dlopen, runs onModuleLoaded, and reports success via ReportZnModule. ```APIDOC ## loadAllModules ### Description Loads all ZN modules. It scans /data/adb/modules/*/zn_modules.txt, asks the daemon for the ZN plan (GetZnPlan), loads matching libraries via modloader::Dlopen, runs onModuleLoaded, and reports success via ReportZnModule. ### Method loadAllModules ### Parameters #### Parameters - **connect_retry** (unsigned char) - Optional - Number of connection retries. Default is 1. ### Response No return value. ``` -------------------------------- ### Entry point and __cxa_atexit declarations Source: https://github.com/hsskyboy/nyazygisk Declares the injected-library entry function and the intercepted exit-handler registration. entry() initializes the daemon and hook engine, then dispatches by TraceMode; __cxa_atexit always returns 0 to block exit handlers. ```cpp extern "C" [[gnu::visibility("default")]] void entry(void* addr, size_t size, const char* path, TraceMode mode); extern "C" int __cxa_atexit(void (*func)(void*), void* arg, void* dso); ``` -------------------------------- ### zn::initHookEngine Source: https://github.com/hsskyboy/nyazygisk Initializes the hook engine by calling zn::hook::initPltEngineFromConfig(). ```APIDOC ## initHookEngine ### Description Initializes the hook engine by calling zn::hook::initPltEngineFromConfig(). ### Method initHookEngine ### Parameters None. ### Response No return value. ``` -------------------------------- ### zn::hook::prepareFork Source: https://github.com/hsskyboy/nyazygisk Prepares for a fork() operation when YukiPLT is initialized in the parent. Returns true if the caller must call afterForkParent or afterForkChild after forking. ```APIDOC ## prepareFork ### Description Prepares for a fork() operation when YukiPLT is initialized in the parent. Returns true if the caller must call afterForkParent or afterForkChild after forking. ### Method prepareFork ### Parameters None. ### Response #### Success Response - **bool** - True if the caller must call afterForkParent or afterForkChild. ``` -------------------------------- ### zn::hook::getPltEngine Source: https://github.com/hsskyboy/nyazygisk Returns the currently active PLT engine. ```APIDOC ## getPltEngine ### Description Returns the currently active PLT engine. ### Method getPltEngine ### Parameters None. ### Response #### Success Response - **PltEngine** - The active PLT engine. ``` -------------------------------- ### Build NyaZygisk with Gradle Source: https://github.com/hsskyboy/nyazygisk/blob/master/README.md Builds the module zips using Gradle. Requires JDK 21, Android SDK with NDK 27.2.12479018, and Rust with cargo-ndk. Output zips are written to module/build/outputs/release/. ```sh ./gradlew zipRelease zipDebug ``` -------------------------------- ### connectCompanion Source: https://github.com/hsskyboy/nyazygisk Connects to the root companion process and returns a Unix domain socket file descriptor. Only works in pre[XXX]Specialize (SELinux). Returns -1 on failure. ```APIDOC ## connectCompanion ### Description Connects to the root companion process and returns a Unix domain socket fd. Only works in `pre[XXX]Specialize` (SELinux). The companion process is ABI-aware (32-bit callers reach a 32-bit companion). Returns `-1` on failure. ### Method `int connectCompanion()` ### Parameters None ### Response #### Success Response - Returns a Unix domain socket fd (int) #### Error Response - Returns `-1` on failure ``` -------------------------------- ### UpdateMountNamespace (3) Source: https://github.com/hsskyboy/nyazygisk Hands the cached clean/root namespace fd to the mid-specialize process for setns. Only root can call it. ```APIDOC ## UpdateMountNamespace (3) ### Description Hands the cached clean/root namespace fd to the mid-specialize process for `setns`. ### Auth **root only** (setns requires CAP_SYS_ADMIN anyway). ### Request `[4][u8 type]` (0 = Clean, 1 = Root) ### Reply `[u8 ok]` then, when ok, an fd via `SCM_RIGHTS`. `1` = fd follows; `0` = namespace not cached. ``` -------------------------------- ### PingHeartbeat (0) Source: https://github.com/hsskyboy/nyazygisk Liveness probe for the daemon. The injector aborts when this fails. ```APIDOC ## PingHeartbeat (0) ### Description Liveness probe; the injector aborts when it fails. ### Auth uid 0 or 1000. ### Request `[1]` (code only). ### Reply None on this socket. On success the daemon sends datagram `ZYGOTE_INJECTED` (4, `u32 LE`) to `$TMP/init_monitor`. ``` -------------------------------- ### Read modules and connect a companion Source: https://github.com/hsskyboy/nyazygisk Initializes the zygiskd client, checks the daemon heartbeat, reads the module list, connects to a companion socket, and refreshes modules. Requires root or AID_SYSTEM for ReadModules and RefreshModules; ConnectCompanion is root-only. ```cpp #include "daemon.hpp" zygiskd::Init("/data/system_de/nyazygisk"); if (!zygiskd::PingHeartbeat()) { // daemon is not running — nothing to load return; } auto modules = zygiskd::ReadModules(); // vector for (const auto &m : modules) { // m.name, m.memfd.get() — the sealed library memfd } int sock = zygiskd::ConnectCompanion(0); // index into the snapshot if (sock < 0) { // companion unavailable or failed to load } else { // use sock, then close(sock) } bool refreshed = zygiskd::RefreshModules(); // rearm path ``` -------------------------------- ### CacheMountNamespace (2) Source: https://github.com/hsskyboy/nyazygisk Tells the daemon to cache the pid's Clean and Root mount namespaces. Untrusted peers are rejected with a warning and no caching. ```APIDOC ## CacheMountNamespace (2) ### Description Tells the daemon to cache the pid's `Clean` and `Root` mount namespaces (`save_mount_namespace(pid, Clean)` then `(pid, Root)`). Untrusted peers are rejected with a warning and no caching. ### Auth uid 0 or 1000. ### Request `[3][u32 pid]` ### Reply None. ``` -------------------------------- ### bool RefreshModules() Source: https://github.com/hsskyboy/nyazygisk Writes `RefreshModules` (root only); daemon rebuilds the module snapshot from disk and replies 1 (ok) / 0 (kept previous snapshot). Synchronous by design: the rearm path must not inject against a stale snapshot. ```APIDOC ## bool RefreshModules() ### Description Writes `RefreshModules` (root only); daemon rebuilds the module snapshot from disk and replies 1 (ok) / 0 (kept previous snapshot). Synchronous by design: the rearm path must not inject against a stale snapshot. ### Returns - **bool** - True if the module snapshot was refreshed, false if the previous snapshot was kept. ``` -------------------------------- ### zn::initHyosRuntime Source: https://github.com/hsskyboy/nyazygisk Enables the HYOS runtime and records the spawner pid via raw getpid syscall. Internally it hooks selinux_android_setcontext and pthread_setname_np on the spawner, delivers onAppSpecialized via hyosDeliverAppSpecialized, registers up to kMaxHyosModules = 16 modules, and uses pthread_atfork coordination. ```APIDOC ## initHyosRuntime ### Description Enables the HYOS runtime and records the spawner pid via raw getpid syscall. Internally it hooks selinux_android_setcontext and pthread_setname_np on the spawner, delivers onAppSpecialized via hyosDeliverAppSpecialized, registers up to kMaxHyosModules = 16 modules, and uses pthread_atfork coordination. ### Method initHyosRuntime ### Parameters None. ### Response No return value. ``` -------------------------------- ### zn::hook::initPltEngineFromConfig Source: https://github.com/hsskyboy/nyazygisk Initializes the PLT engine based on the configuration. It reads the 'plt_engine=' option from config.prop to select the engine. ```APIDOC ## initPltEngineFromConfig ### Description Initializes the PLT engine based on the configuration. It reads the 'plt_engine=' option from config.prop to select the engine. ### Method initPltEngineFromConfig ### Parameters None. ### Response No return value. ``` -------------------------------- ### RegisterZnCompanionBroker (14) Source: https://github.com/hsskyboy/nyazygisk Registers a SOCK_DGRAM broker for ZN companion streams. The broker must be a declared ZN companion and the socket must be SOCK_DGRAM. ```APIDOC ## RegisterZnCompanionBroker (14) ### Description Registers a SOCK_DGRAM broker for ZN companion streams. The broker must be a declared ZN companion and the socket must be SOCK_DGRAM. ### Method Unknown (custom protocol) ### Endpoint RegisterZnCompanionBroker (14) ### Parameters #### Request Body - `lib_path` (string) - Required - Path to the library. - `broker_fd` (fd) - Required - File descriptor for the broker socket. ### Preconditions - `broker_fd` must be `SO_TYPE == SOCK_DGRAM` (checked via `getsockopt`). - The lib must be a declared ZN companion. ### Response #### Success Response - `ok` (u8) - 1 = broker thread registered (supplants any previous one), 0 = rejected. ### Auth - root only. ``` -------------------------------- ### zygiskd::ConnectCompanion Source: https://github.com/hsskyboy/nyazygisk Connects to a companion process for a given module index. Returns a socket file descriptor. ```APIDOC ## zygiskd::ConnectCompanion ### Description Connects to a companion process for a given module index. Returns a socket file descriptor. ### Method Function call ### Signature `int zygiskd::ConnectCompanion(int index)` ### Parameters - **index** (int) - Required - Index into the module snapshot. ### Return Value - **int** - Socket file descriptor, or negative if companion unavailable. ### Example ```cpp int sock = zygiskd::ConnectCompanion(0); if (sock < 0) { // companion unavailable or failed to load } else { // use sock, then close(sock) } ``` ``` -------------------------------- ### files.hpp: file_readline overloads, sFILE/sDIR RAII handles, open_dir/open_file Source: https://github.com/hsskyboy/nyazygisk Declarations from loader/src/include/files.hpp. file_readline reads lines with an early-stop callback; overloads accept FILE*, path, or path with default trim. sFILE/sDIR are RAII unique_ptr wrappers for FILE and DIR. make_dir/make_file wrap raw pointers; open_dir/open_file open by path (x variants take path/int dirfd or path/fd). The x variants abort on failure; plain variants return an empty handle. ```cpp void file_readline(bool trim, FILE *fp, const std::function &fn); void file_readline(bool trim, const char *file, const std::function &fn); void file_readline(const char *file, const std::function &fn); using sFILE = std::unique_ptr; using sDIR = std::unique_ptr; sDIR make_dir(DIR *dp); sFILE make_file(FILE *fp); sDIR open_dir(const char *path); // xopen_dir variants for path/int dirfd sFILE open_file(const char *path, const char *mode); // xopen_file variants for path/fd ``` -------------------------------- ### zygisk::ModuleBase::preAppSpecialize Source: https://github.com/hsskyboy/nyazygisk Called before app specialization; process runs with Zygote's privilege and no sandbox. Args may be read and overwritten. ```APIDOC ## preAppSpecialize ### Description Called before app specialization; process runs with Zygote's privilege and no sandbox. Args may be read and overwritten. ### Method preAppSpecialize ### Parameters - `AppSpecializeArgs *args` - The arguments for app specialization. ### Response No return value. ``` -------------------------------- ### int ConnectCompanion(size_t index) Source: https://github.com/hsskyboy/nyazygisk Writes `RequestCompanionSocket` + usize module index; the daemon spawns/validates the companion and passes the client's fd through. Returns the companion socket fd or `-1` (a `0` byte on failure). ```APIDOC ## int ConnectCompanion(size_t index) ### Description Writes `RequestCompanionSocket` + usize module index; the daemon spawns/validates the companion and passes the client's fd through. Returns the companion socket fd or `-1` (a `0` byte on failure). ### Parameters - **index** (size_t) - Required - The module index. ### Returns - **int** - The companion socket file descriptor, or `-1` on failure. ``` -------------------------------- ### std::string GetTmpPath() Source: https://github.com/hsskyboy/nyazygisk Returns the initialized work directory. ```APIDOC ## std::string GetTmpPath() ### Description Returns the initialized work directory. ### Returns - **std::string** - The initialized work directory. ``` -------------------------------- ### void ReportZnModule(const std::string& lib_path, bool injected) Source: https://github.com/hsskyboy/nyazygisk Writes `ReportZnModule` + lib path + u8 success flag. Tracks injected/failed counts in `zn_states` and rewrites `zn_modules_state`. ```APIDOC ## void ReportZnModule(const std::string& lib_path, bool injected) ### Description Writes `ReportZnModule` + lib path + u8 success flag. Tracks injected/failed counts in `zn_states` and rewrites `zn_modules_state`. ### Parameters - **lib_path** (const std::string&) - Required - The library path. - **injected** (bool) - Required - Whether the module was injected successfully. ``` -------------------------------- ### namespace zn API Source: https://github.com/hsskyboy/nyazygisk Declares the injector API in zn_api.hpp and zn_loader.hpp. getApiForVersion returns kApiV4 for >=4, kApiFull for >=2, else kApiNoSymbolResolver. initHookEngine calls zn::hook::initPltEngineFromConfig(). HYOS runtime hooks selinux_android_setcontext and pthread_setname_np on the spawner, delivers onAppSpecialized, registers up to kMaxHyosModules=16 modules, and uses pthread_atfork. loadAllModules scans /data/adb/modules/*/zn_modules.txt, asks for GetZnPlan, loads via modloader::Dlopen, runs onModuleLoaded, and reports via ReportZnModule. hasResidentState is true when ZN module or ByteHook trampoline state requires libzygisk.so to stay mapped. ```cpp namespace zn { struct ZnModuleHandle { std::string lib_path; bool companion = false; int target_api_version = 0; int companion_broker_fd = -1; }; const ZygiskNextAPI* getApiForVersion(int target_api_version); void initHookEngine(); bool isHyosSpawner(); void initHyosRuntime(); bool isHyosRuntime(); void loadAllModules(unsigned char connect_retry = 1); bool hasResidentState(); } ``` -------------------------------- ### void CacheMountNamespace(pid_t pid) Source: https://github.com/hsskyboy/nyazygisk Writes `CacheMountNamespace` + u32 pid; tells the daemon to cache the pid's Clean and Root mount namespaces. ```APIDOC ## void CacheMountNamespace(pid_t pid) ### Description Writes `CacheMountNamespace` + u32 pid; tells the daemon to cache the pid's Clean and Root mount namespaces. ### Parameters - **pid** (pid_t) - Required - The process ID whose mount namespaces should be cached. ``` -------------------------------- ### connectCompanion Source: https://github.com/hsskyboy/nyazygisk Connects a Unix stream socket to the module's declared companion process. Returns the socket file descriptor on success, or -1 on failure. ```APIDOC ## connectCompanion ### Description Connects a Unix stream socket to the module's declared companion process. `handle` is the `self_handle` received in `onModuleLoaded`. Returns the socket fd on success, `-1` on failure. Close the fd yourself. On the HyperOS spawner path this is routed through the SOCK_DGRAM companion broker when available. ### Signature `int (*connectCompanion)(void *handle)` ### Parameters - **handle** (void*) - Required - The `self_handle` from `onModuleLoaded`. ### Return Value - **int** - Socket file descriptor on success, `-1` on failure. ``` -------------------------------- ### struct ZnHyosAppSpecializeArgs Source: https://github.com/hsskyboy/nyazygisk Provides read-only process specialization information for apps forked by the HyperOS spawner. The callback runs after uid, gid, supplementary groups, and SELinux app context are applied. ```APIDOC ## struct ZnHyosAppSpecializeArgs ### Description Provides read-only process specialization information for apps forked by the HyperOS spawner. The callback runs after uid, gid, supplementary groups, and SELinux app context are applied. ### Fields - **process_name** (const char*) - Required - Process name. - **package_name** (const char*) - Required - Package name. - **se_info** (const char*) - Required - SELinux info. ### Notes String pointers are non-null and valid only for the duration of the callback. ### Example ```c struct ZnHyosAppSpecializeArgs { const char *process_name; const char *package_name; const char *se_info; }; ``` ``` -------------------------------- ### zygisk::ModuleBase::onLoad Source: https://github.com/hsskyboy/nyazygisk Called as soon as the module is loaded into the target process. Store the handles for later use. ```APIDOC ## onLoad ### Description Called as soon as the module is loaded into the target process. Store the handles for later use. ### Method onLoad ### Parameters - `Api *api` - The API handle for the module. - `JNIEnv *env` - The JNI environment pointer. ### Response No return value. ``` -------------------------------- ### struct ZnHyosAppSpecializeArgs definition Source: https://github.com/hsskyboy/nyazygisk Read-only process specialization info for apps forked by `/system_ext/bin/hyos_spawner`. The callback runs after uid, gid, supplementary groups, and SELinux app context are applied. String pointers are non-null and valid only for the duration of the callback. ```c struct ZnHyosAppSpecializeArgs { const char *process_name; const char *package_name; const char *se_info; }; ``` -------------------------------- ### struct ZygiskNextModule definition Source: https://github.com/hsskyboy/nyazygisk Defines the module entry point. `target_api_version` should be set to `ZYGISK_NEXT_API_VERSION`. `onModuleLoaded` is called after all needed libraries of the main executable are loaded, before the executable's entry (`main`) is called. ```c struct ZygiskNextModule { int target_api_version; void (*onModuleLoaded)(void *self_handle, const struct ZygiskNextAPI *api); }; ``` -------------------------------- ### zygisk::ModuleBase::postServerSpecialize Source: https://github.com/hsskyboy/nyazygisk Called after system_server specialization; runs with system_server privilege. ```APIDOC ## postServerSpecialize ### Description Called after system_server specialization; runs with system_server privilege. ### Method postServerSpecialize ### Parameters - `const ServerSpecializeArgs *args` - The arguments for server specialization. ### Response No return value. ``` -------------------------------- ### bool RegisterZnCompanionBroker(const std::string& lib_path, int broker_fd) Source: https://github.com/hsskyboy/nyazygisk Writes `RegisterZnCompanionBroker` + string lib path and sends `broker_fd` (must be `SOCK_DGRAM`); `true` when the daemon's broker thread is registered. ```APIDOC ## bool RegisterZnCompanionBroker(const std::string& lib_path, int broker_fd) ### Description Writes `RegisterZnCompanionBroker` + string lib path and sends `broker_fd` (must be `SOCK_DGRAM`); `true` when the daemon's broker thread is registered. ### Parameters - **lib_path** (const std::string&) - Required - The library path. - **broker_fd** (int) - Required - The broker file descriptor (must be SOCK_DGRAM). ### Returns - **bool** - True if the broker thread is registered, false otherwise. ``` -------------------------------- ### Companion daemon with error handling Source: https://github.com/hsskyboy/nyazygisk Registers a companion handler and connects from the module, checking for failures. connectCompanion returns -1 on failure, getModuleDir returns -1 on error. Use when the module needs a root companion process. ```cpp static void handler(int socket) { // Runs inside the root companion daemon, one thread per request. int fd = socket; // read requests from the app over `fd`, reply over `fd` } REGISTER_ZYGISK_COMPANION(handler) class ExampleModule : public zygisk::ModuleBase { public: void preAppSpecialize(zygisk::AppSpecializeArgs *args) override { int sock = api->connectCompanion(); // -1 on failure if (sock < 0) return; // companion unavailable int moddir = api->getModuleDir(); // -1 on error // ... send fd over sock (sendmsg/SCM_RIGHTS), close sock } // ... }; ``` -------------------------------- ### Load module via modloader::Dlopen and resolve entry Source: https://github.com/hsskyboy/nyazygisk Use modloader::Dlopen to load a module from a memfd, with a flag indicating whether the system linker was used. If the handle is null, both loaders failed and the module should be abandoned. The via_system flag tells whether the module is visible in solist; then resolve the entry with modloader::Dlsym and close with modloader::Dlclose. ```cpp #include "module_loader.hpp" bool via_system = false; void *handle = modloader::Dlopen(memfd_fd, "my_module", &via_system); if (!handle) { // both loaders failed — give up on this module return; } // via_system == true -> module is visible in solist; scrub its trace // via_system == false -> custom linker; hidden from solist void *entry = modloader::Dlsym(handle, "zygisk_module_entry"); // ... resolve and run module entry ... modloader::Dlclose(handle); ``` -------------------------------- ### zn::hook::afterForkParent Source: https://github.com/hsskyboy/nyazygisk Called in the parent process after a fork() to restore YukiPLT's process-owner guard. ```APIDOC ## afterForkParent ### Description Called in the parent process after a fork() to restore YukiPLT's process-owner guard. ### Method afterForkParent ### Parameters None. ### Response No return value. ``` -------------------------------- ### Atexit namespace declaration (atexit.hpp) Source: https://github.com/hsskyboy/nyazygisk Declares utilities to scrub libc's __cxa_atexit array. scrubFingerprint() best-effort compacts the array under libc's lock and re-protects it read-only; every obstacle leaves libc unchanged and is reported via ScrubStatus. ```cpp namespace Atexit { inline size_t page_size(); // getauxval(AT_PAGESZ) constexpr size_t max_android_page_size(); inline uintptr_t page_start(uintptr_t x); inline uintptr_t page_offset(uintptr_t x); inline uintptr_t page_end(uintptr_t x); enum class ScrubStatus { kDone, kNothingToScrub, kNoArray, kNoLock, kLockBusy, kNotWritable, kLeftWritable, }; const char* describe(ScrubStatus status); struct AtexitEntry { void (*fn)(void*); void* arg; void* dso; }; class AtexitArray { public: AtexitArray(AtexitEntry* existing_array, size_t current_size, size_t current_capacity, size_t initial_extracted_count, uint64_t initial_total_appends); std::string format_state_string() const; size_t size() const; uint64_t total_appends() const; const AtexitEntry& operator[](size_t idx) const; ScrubStatus recompact(int& protect_errno); private: // ... }; ScrubStatus scrubFingerprint(); } ``` -------------------------------- ### forEachSymbols Source: https://github.com/hsskyboy/nyazygisk Walks the library symbol table, invoking a callback for each symbol. The walk stops if the callback returns false. ```APIDOC ## forEachSymbols ### Description Walks the library symbol table; the callback receives name, address, and size per symbol. Returning `false` from the callback stops the walk. ### Signature `void (*forEachSymbols)(struct ZnSymbolResolver *resolver, bool (*callback)(const char *name, void *addr, size_t size, void *data), void *data)` ### Parameters - **resolver** (struct ZnSymbolResolver*) - Required - Resolver to use. - **callback** (function pointer) - Required - Callback invoked for each symbol. - **data** (void*) - Optional - User data passed to callback. ``` -------------------------------- ### zn::hook::afterForkChild Source: https://github.com/hsskyboy/nyazygisk Called in the child process after a fork() to restore YukiPLT's process-owner guard. ```APIDOC ## afterForkChild ### Description Called in the child process after a fork() to restore YukiPLT's process-owner guard. ### Method afterForkChild ### Parameters None. ### Response No return value. ``` -------------------------------- ### zygiskd::GetZnPlan Source: https://github.com/hsskyboy/nyazygisk Retrieves the Zygisk Next plan for a given process. Returns a vector of ZnPlanEntry objects. ```APIDOC ## zygiskd::GetZnPlan ### Description Retrieves the Zygisk Next plan for a given process. Returns a vector of ZnPlanEntry objects. ### Method Function call ### Signature `std::vector zygiskd::GetZnPlan(const std::string& process, const std::string& path)` ### Parameters - **process** (string) - Required - Process name (e.g., "zygote"). - **path** (string) - Required - Path to the executable (e.g., "/system/bin/app_process64"). ### Return Value - **vector** - List of plan entries, each with `lib_path`, `companion`, and `lib_fd`. ### Example ```cpp auto plan = zygiskd::GetZnPlan("zygote", "/system/bin/app_process64"); for (auto &entry : plan) { // entry.lib_path, entry.companion, entry.lib_fd.get() } ``` ``` -------------------------------- ### int ConnectZnCompanion(const std::string& lib_path) Source: https://github.com/hsskyboy/nyazygisk Writes `RequestZnCompanionSocket` + string canonical lib path; the daemon validates it with `is_allowed_zn_companion` and forwards the connection to the ZN companion. Returns the fd, or `-1` after a `0` reply. ```APIDOC ## int ConnectZnCompanion(const std::string& lib_path) ### Description Writes `RequestZnCompanionSocket` + string canonical lib path; the daemon validates it with `is_allowed_zn_companion` and forwards the connection to the ZN companion. Returns the fd, or `-1` after a `0` reply. ### Parameters - **lib_path** (const std::string&) - Required - The canonical library path. ### Returns - **int** - The file descriptor of the ZN companion socket, or `-1` on failure. ``` -------------------------------- ### freeSymbolResolver Source: https://github.com/hsskyboy/nyazygisk Releases a symbol resolver created by newSymbolResolver. ```APIDOC ## freeSymbolResolver ### Description Releases a resolver created by `newSymbolResolver`. ### Signature `void (*freeSymbolResolver)(struct ZnSymbolResolver *resolver)` ### Parameters - **resolver** (struct ZnSymbolResolver*) - Required - Resolver to release. ``` -------------------------------- ### std::vector GetZnPlan(const std::string& process_name, const std::string& process_path, uint8_t retry = 1) Source: https://github.com/hsskyboy/nyazygisk Writes `GetZnPlan` + process name + process path; the daemon replies with the count then per entry: string `lib_path`, u8 companion flag, and the library fd. ```APIDOC ## std::vector GetZnPlan(const std::string& process_name, const std::string& process_path, uint8_t retry = 1) ### Description Writes `GetZnPlan` + process name + process path; the daemon replies with the count then per entry: string `lib_path`, u8 companion flag, and the library fd. ### Parameters - **process_name** (const std::string&) - Required - The process name. - **process_path** (const std::string&) - Required - The process path. - **retry** (uint8_t) - Optional - Number of retry attempts (default 1). ### Returns - **std::vector** - A vector of ZnPlanEntry objects. ``` -------------------------------- ### RefreshModules (13) Source: https://github.com/hsskyboy/nyazygisk Synchronously refreshes the module set from disk. Returns whether the refresh was successful. ```APIDOC ## RefreshModules (13) ### Description Synchronously refreshes the module set from disk. Returns 1 if rebuilt, 0 if kept previous snapshot. ### Method Unknown (custom protocol) ### Endpoint RefreshModules (13) ### Parameters #### Request Body - None ### Response #### Success Response - `ok` (u8) - 1 = rebuilt from disk, 0 = kept previous snapshot (failures also reply 0). ### Auth - root only. ```