├── module
├── template
│ ├── post-fs-data.sh
│ ├── sepolicy.rule
│ ├── zn_modules.txt
│ ├── META-INF
│ │ └── com
│ │ │ └── google
│ │ │ └── android
│ │ │ ├── updater-script
│ │ │ └── update-binary
│ ├── module.prop
│ ├── service.sh
│ ├── verify.sh
│ └── customize.sh
├── .gitignore
├── src
│ └── main
│ │ ├── AndroidManifest.xml
│ │ └── cpp
│ │ ├── CMakeLists.txt
│ │ ├── hook.cpp
│ │ └── zygisk_next_api.h
└── build.gradle.kts
├── README.md
├── gradle
├── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
└── libs.versions.toml
├── .gitignore
├── settings.gradle.kts
├── gradle.properties
├── gradlew.bat
└── gradlew
/module/template/post-fs-data.sh:
--------------------------------------------------------------------------------
1 | MODDIR=${0%/*}
2 |
--------------------------------------------------------------------------------
/module/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 | /libs
3 | /obj
4 | /release
5 |
--------------------------------------------------------------------------------
/module/template/sepolicy.rule:
--------------------------------------------------------------------------------
1 | allow logd logd process execmem
2 |
--------------------------------------------------------------------------------
/module/template/zn_modules.txt:
--------------------------------------------------------------------------------
1 | name=logd lib/lib${moduleId}.so
2 |
--------------------------------------------------------------------------------
/module/template/META-INF/com/google/android/updater-script:
--------------------------------------------------------------------------------
1 | #MAGISK
2 |
--------------------------------------------------------------------------------
/module/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Check https://android-review.googlesource.com/c/platform/system/logging/+/3725346 for details.
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aviraxp/ZN-AuditPatch/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea
5 | .DS_Store
6 | /build
7 | /captures
8 | .externalNativeBuild
9 | .cxx
10 | local.properties
11 |
--------------------------------------------------------------------------------
/module/template/module.prop:
--------------------------------------------------------------------------------
1 | id=${moduleId}
2 | name=${moduleName}
3 | version=${versionName}
4 | versionCode=${versionCode}
5 | author=aviraxp
6 | description=Replace sensitive context in audit log.
7 | #updateJson=
8 |
--------------------------------------------------------------------------------
/module/template/service.sh:
--------------------------------------------------------------------------------
1 | # FIXME: logd starts very early in boot process, and ZN can only handle services which is started after post-fs-data for now
2 | resetprop -w sys.boot_completed 0
3 | setprop ctl.restart logd
4 |
--------------------------------------------------------------------------------
/gradle/libs.versions.toml:
--------------------------------------------------------------------------------
1 | [versions]
2 | agp = "8.6.1"
3 |
4 | [plugins]
5 | agp-app = { id = "com.android.application", version.ref = "agp" }
6 |
7 | [libraries]
8 | cxx = { module = "org.lsposed.libcxx:libcxx", version = "27.0.12077973" }
9 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sun Dec 31 12:28:57 CST 2023
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.1-bin.zip
5 | zipStoreBase=GRADLE_USER_HOME
6 | zipStorePath=wrapper/dists
7 |
--------------------------------------------------------------------------------
/module/src/main/cpp/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 3.22.1)
2 | project(auditpatch)
3 |
4 | set(CXX_FLAGS "${CXX_FLAGS} -fno-exceptions -fno-rtti -fvisibility=hidden -fvisibility-inlines-hidden")
5 |
6 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CXX_FLAGS}")
7 |
8 | find_package(cxx REQUIRED CONFIG)
9 | link_libraries(cxx::cxx)
10 |
11 | add_library(${MODULE_NAME} SHARED hook.cpp)
12 | target_link_libraries(${MODULE_NAME} log)
13 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | google()
4 | mavenCentral()
5 | gradlePluginPortal()
6 | }
7 | }
8 |
9 | dependencyResolutionManagement {
10 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
11 | repositories {
12 | google()
13 | mavenCentral()
14 | }
15 | }
16 |
17 | rootProject.name = "auditpatch"
18 | include(
19 | ":module"
20 | )
21 |
--------------------------------------------------------------------------------
/module/template/META-INF/com/google/android/update-binary:
--------------------------------------------------------------------------------
1 | #!/sbin/sh
2 |
3 | #################
4 | # Initialization
5 | #################
6 |
7 | umask 022
8 |
9 | # echo before loading util_functions
10 | ui_print() { echo "$1"; }
11 |
12 | require_new_magisk() {
13 | ui_print "*******************************"
14 | ui_print " Please install Magisk v20.4+! "
15 | ui_print "*******************************"
16 | exit 1
17 | }
18 |
19 | #########################
20 | # Load util_functions.sh
21 | #########################
22 |
23 | OUTFD=$2
24 | ZIPFILE=$3
25 |
26 | mount /data 2>/dev/null
27 |
28 | [ -f /data/adb/magisk/util_functions.sh ] || require_new_magisk
29 | . /data/adb/magisk/util_functions.sh
30 | [ $MAGISK_VER_CODE -lt 20400 ] && require_new_magisk
31 |
32 | install_module
33 | exit 0
34 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 |
--------------------------------------------------------------------------------
/module/template/verify.sh:
--------------------------------------------------------------------------------
1 | TMPDIR_FOR_VERIFY="$TMPDIR/.vunzip"
2 | mkdir "$TMPDIR_FOR_VERIFY"
3 |
4 | abort_verify() {
5 | ui_print "*********************************************************"
6 | ui_print "! $1"
7 | ui_print "! This zip may be corrupted, please try downloading again"
8 | abort "*********************************************************"
9 | }
10 |
11 | # extract
12 | extract() {
13 | zip=$1
14 | file=$2
15 | dir=$3
16 | junk_paths=$4
17 | [ -z "$junk_paths" ] && junk_paths=false
18 | opts="-o"
19 | [ $junk_paths = true ] && opts="-oj"
20 |
21 | file_path=""
22 | hash_path=""
23 | if [ $junk_paths = true ]; then
24 | file_path="$dir/$(basename "$file")"
25 | hash_path="$TMPDIR_FOR_VERIFY/$(basename "$file").sha256"
26 | else
27 | file_path="$dir/$file"
28 | hash_path="$TMPDIR_FOR_VERIFY/$file.sha256"
29 | fi
30 |
31 | unzip $opts "$zip" "$file" -d "$dir" >&2
32 | [ -f "$file_path" ] || abort_verify "$file not exists"
33 |
34 | unzip $opts "$zip" "$file.sha256" -d "$TMPDIR_FOR_VERIFY" >&2
35 | [ -f "$hash_path" ] || abort_verify "$file.sha256 not exists"
36 |
37 | (echo "$(cat "$hash_path") $file_path" | sha256sum -c -s -) || abort_verify "Failed to verify $file"
38 | ui_print "- Verified $file" >&1
39 | }
40 |
41 | file="META-INF/com/google/android/update-binary"
42 | file_path="$TMPDIR_FOR_VERIFY/$file"
43 | hash_path="$file_path.sha256"
44 | unzip -o "$ZIPFILE" "META-INF/com/google/android/*" -d "$TMPDIR_FOR_VERIFY" >&2
45 | [ -f "$file_path" ] || abort_verify "$file not exists"
46 | if [ -f "$hash_path" ]; then
47 | (echo "$(cat "$hash_path") $file_path" | sha256sum -c -s -) || abort_verify "Failed to verify $file"
48 | ui_print "- Verified $file" >&1
49 | else
50 | ui_print "- Download from Magisk app"
51 | fi
52 |
--------------------------------------------------------------------------------
/module/template/customize.sh:
--------------------------------------------------------------------------------
1 | # shellcheck disable=SC2034
2 | SKIPUNZIP=1
3 |
4 | DEBUG=@DEBUG@
5 | SONAME=@SONAME@
6 | SUPPORTED_ABIS="@SUPPORTED_ABIS@"
7 |
8 | if [ "$BOOTMODE" ] && [ "$KSU" ]; then
9 | ui_print "- Installing from KernelSU app"
10 | ui_print "- KernelSU version: $KSU_KERNEL_VER_CODE (kernel) + $KSU_VER_CODE (ksud)"
11 | if [ "$(which magisk)" ]; then
12 | ui_print "*********************************************************"
13 | ui_print "! Multiple root implementation is NOT supported!"
14 | ui_print "! Please uninstall Magisk before installing $SONAME"
15 | abort "*********************************************************"
16 | fi
17 | elif [ "$BOOTMODE" ] && [ "$MAGISK_VER_CODE" ]; then
18 | ui_print "- Installing from Magisk app"
19 | else
20 | ui_print "*********************************************************"
21 | ui_print "! Install from recovery is not supported"
22 | ui_print "! Please install from KernelSU or Magisk app"
23 | abort "*********************************************************"
24 | fi
25 |
26 | VERSION=$(grep_prop version "${TMPDIR}/module.prop")
27 | ui_print "- Installing $SONAME $VERSION"
28 |
29 | # check architecture
30 | support=false
31 | for abi in $SUPPORTED_ABIS
32 | do
33 | if [ "$ARCH" == "$abi" ]; then
34 | support=true
35 | fi
36 | done
37 | if [ "$support" == "false" ]; then
38 | abort "! Unsupported platform: $ARCH"
39 | else
40 | ui_print "- Device platform: $ARCH"
41 | fi
42 |
43 | ui_print "- Extracting verify.sh"
44 | unzip -o "$ZIPFILE" 'verify.sh' -d "$TMPDIR" >&2
45 | if [ ! -f "$TMPDIR/verify.sh" ]; then
46 | ui_print "*********************************************************"
47 | ui_print "! Unable to extract verify.sh!"
48 | ui_print "! This zip may be corrupted, please try downloading again"
49 | abort "*********************************************************"
50 | fi
51 | . "$TMPDIR/verify.sh"
52 | extract "$ZIPFILE" 'customize.sh' "$TMPDIR/.vunzip"
53 | extract "$ZIPFILE" 'verify.sh' "$TMPDIR/.vunzip"
54 | extract "$ZIPFILE" 'sepolicy.rule' "$TMPDIR"
55 |
56 | ui_print "- Extracting module files"
57 | extract "$ZIPFILE" 'module.prop' "$MODPATH"
58 | extract "$ZIPFILE" 'post-fs-data.sh' "$MODPATH"
59 | extract "$ZIPFILE" 'service.sh' "$MODPATH"
60 | extract "$ZIPFILE" 'zn_modules.txt' "$MODPATH"
61 | mv "$TMPDIR/sepolicy.rule" "$MODPATH"
62 |
63 | mkdir "$MODPATH/lib"
64 |
65 | ui_print "- Extracting $ARCH libraries"
66 | extract "$ZIPFILE" "lib/$ARCH/lib$SONAME.so" "$MODPATH/lib" true
67 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/module/src/main/cpp/hook.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include "zygisk_next_api.h"
7 |
8 | #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, "zn-auditpatch", __VA_ARGS__)
9 | #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, "zn-auditpatch", __VA_ARGS__)
10 |
11 | static ZygiskNextAPI api_table;
12 | void *handle;
13 |
14 | static int (*old_vasprintf)(char **strp, const char *fmt, va_list ap) = nullptr;
15 |
16 | static bool has_quote_after(const char *pos, size_t match_len) {
17 | const char *end = pos + match_len;
18 | while (*end != '\0') {
19 | if (*end == '"') {
20 | return true;
21 | }
22 | end++;
23 | }
24 | return false;
25 | }
26 |
27 | static int my_vasprintf(char **strp, const char *fmt, va_list ap) {
28 | // https://cs.android.com/android/platform/superproject/main/+/main:system/logging/logd/LogAudit.cpp;l=210
29 | auto result = old_vasprintf(strp, fmt, ap);
30 |
31 | if (result > 0 && *strp) {
32 | // https://cs.android.com/android/platform/superproject/main/+/main:external/selinux/libselinux/src/android/android_seapp.c;l=694
33 | constexpr std::string_view target_context = "tcontext=u:r:priv_app:s0:c512,c768";
34 | constexpr std::string_view source_contexts[] = {
35 | "tcontext=u:r:su:s0",
36 | "tcontext=u:r:magisk:s0"
37 | };
38 |
39 | for (const auto &source: source_contexts) {
40 | char *pos = strstr(*strp, source.data());
41 |
42 | if (pos && !has_quote_after(pos, source.size())) {
43 | size_t extra_space = (target_context.size() > source.size()) ?
44 | (target_context.size() - source.size()) : 0;
45 |
46 | // Reverse double space in case
47 | char *new_str = static_cast(malloc(result + 2 * extra_space + 1));
48 |
49 | strcpy(new_str, *strp);
50 | pos = new_str + (pos - *strp);
51 |
52 | if (source.size() != target_context.size()) {
53 | memmove(pos + target_context.size(), pos + source.size(),
54 | strlen(pos + source.size()) + 1);
55 | }
56 | memcpy(pos, target_context.data(), target_context.size());
57 |
58 | free(*strp);
59 | *strp = new_str;
60 | return static_cast(strlen(new_str));
61 | }
62 | }
63 | }
64 |
65 | return result;
66 | }
67 |
68 | void onModuleLoaded(void *self_handle, const struct ZygiskNextAPI *api) {
69 | memcpy(&api_table, api, sizeof(ZygiskNextAPI));
70 |
71 | auto resolver = api_table.newSymbolResolver("libc.so", nullptr);
72 | if (!resolver) return;
73 |
74 | size_t sz;
75 | auto addr = api_table.symbolLookup(resolver, "vasprintf", false, &sz);
76 | api_table.freeSymbolResolver(resolver);
77 |
78 | if (addr &&
79 | api_table.inlineHook(addr, (void *) my_vasprintf, (void **) &old_vasprintf) == ZN_SUCCESS) {
80 | LOGI("logd hook success");
81 | } else {
82 | LOGE("logd hook failure");
83 | }
84 | }
85 |
86 | __attribute__((visibility("default")))
87 | struct ZygiskNextModule zn_module = {
88 | .target_api_version = ZYGISK_NEXT_API_VERSION_1,
89 | .onModuleLoaded = onModuleLoaded,
90 | };
91 |
--------------------------------------------------------------------------------
/module/src/main/cpp/zygisk_next_api.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 |
5 | #ifdef __cplusplus
6 | extern "C" {
7 | #endif
8 |
9 | #define ZYGISK_NEXT_API_VERSION_1 3
10 |
11 | #define ZN_SUCCESS 0
12 | #define ZN_FAILED 1
13 |
14 | struct ZnSymbolResolver;
15 |
16 | struct ZygiskNextAPI {
17 | // Hook API
18 |
19 | // Do plt hook at symbol specified by the param `symbol` of library specified by the param `base_addr`
20 | // The plt address of `symbol` in the library will be replaced with hook_handler, and
21 | // its original value will be put to the address specified by `origianl` (can be null).
22 | // You can use this api to do caller-oriented hook
23 | // If you want to unhook, please call this function with hook_handler = original
24 | // If hook succeed, returns ZN_SUCCESS, otherwise ZN_FAILED
25 | int (*pltHook)(void* base_addr, const char* symbol, void* hook_handler, void** original);
26 |
27 | // Do inline hook at the address specified by `target`, replace it with a new function specified
28 | // by `addr`, and the param `original` receives the address of original function.
29 | // You can use this api to achieve a global hook in current process.
30 | // In the current implementation , an address can only hook once, so the module can't hook an
31 | // address which is already hooked by an another module, except that the module unhooked it.
32 | // If hooking succeed, returns ZN_SUCCESS, otherwise ZN_FAILED
33 | int (*inlineHook)(void* target, void* addr, void** original);
34 |
35 | // Unhook the address which is formerly hooked.
36 | // If hook succeed, returns ZN_SUCCESS, otherwise ZN_FAILED
37 | int (*inlineUnhook)(void* target);
38 |
39 | // Symbol Resolver API
40 |
41 | // Obtain a new ZnSymbolResolver object
42 | // `path` is required, which specifies the path of library to resolve. It can be an absolute path
43 | // or just the file name of library, e.g. /system/lib64/libc.so or libc.so .
44 | // If `base_addr` is non-zero, it will be used as the base address of the library.
45 | // Otherwise, Zygisk Next will try to find out the base address of the specified library in this process.
46 | // If succeed, it returns a valid pointer to the symbol resolver, otherwise nullptr is returned.
47 | struct ZnSymbolResolver* (*newSymbolResolver)(const char* path, void* base_addr);
48 |
49 | // Release the ZnSymbolResolver object pointed by `resolver`.
50 | void (*freeSymbolResolver)(struct ZnSymbolResolver* resolver);
51 |
52 | // Retrieve the base address of the library of the resolver image in the process.
53 | void* (*getBaseAddress)(struct ZnSymbolResolver* resolver);
54 |
55 | // Lookup the address of symbol by name or prefix (if `prefix` is true)
56 | // If the symbol exists, the function returns its address, otherwise returns nullptr.
57 | // If `size` is not nullptr, the size of the symbol will be put to *size .
58 | // In the current implementation, gnu_debugdata resolution is supported.
59 | void* (*symbolLookup)(struct ZnSymbolResolver* resolver, const char* name, bool prefix, size_t* size);
60 |
61 | // Walk through the symbol table of the library, the callback will receive the name, the address,
62 | // and the size of each symbol. Returning false in the callback means stop the walking.
63 | void (*forEachSymbols)(struct ZnSymbolResolver* resolver,
64 | bool (*callback)(const char* name, void* addr, size_t size, void* data),
65 | void* data);
66 |
67 | // Companion API
68 |
69 | // Create a unix sock stream connection to your declared companion process.
70 | // The value of `handle` is the `self_handle` which you've received from onModuleLoaded.
71 | // On success, it returns the file descriptor refer to the socket, otherwise -1 is returned.
72 | // Please close this file descriptor by yourself.
73 | int (*connectCompanion)(void* handle);
74 | };
75 |
76 | // Callbacks of an injected library
77 | struct ZygiskNextModule {
78 | // Please fill this with the target version of your module, e.g. ZYGISK_NEXT_API_VERSION_1
79 | int target_api_version;
80 |
81 | // This callback will be called after all needed library of the main executable are loaded,
82 | // and before the entry (i.e. `main`) of the main executable is called.
83 | void (*onModuleLoaded)(void* self_handle, const struct ZygiskNextAPI* api);
84 | };
85 |
86 | // Callbacks of a companion library
87 | struct ZygiskNextCompanionModule {
88 | int target_api_version;
89 |
90 | void (*onCompanionLoaded)();
91 |
92 | // This callback will be called when your Zygisk Next module is trying to establish a connection
93 | // with your companion module, i.e. `connectCompanion` is called.
94 | // The `fd` param will be a unix sock stream file descriptor.
95 | // Please close this file descriptor after use by yourself.
96 | void (*onModuleConnected)(int fd);
97 | };
98 |
99 | // Please define your `zn_module` in your source file.
100 | extern __attribute__((visibility("default"), unused)) struct ZygiskNextModule zn_module;
101 | extern __attribute__((visibility("default"), unused)) struct ZygiskNextCompanionModule zn_companion_module;
102 |
103 | #ifdef __cplusplus
104 | }
105 | #endif
106 |
--------------------------------------------------------------------------------
/module/build.gradle.kts:
--------------------------------------------------------------------------------
1 | import android.databinding.tool.ext.capitalizeUS
2 | import org.apache.tools.ant.filters.FixCrLfFilter
3 | import org.apache.tools.ant.filters.ReplaceTokens
4 | import java.security.MessageDigest
5 |
6 | plugins {
7 | alias(libs.plugins.agp.app)
8 | }
9 |
10 | val moduleId: String by rootProject.extra
11 | val moduleName: String by rootProject.extra
12 | val verCode: Int by rootProject.extra
13 | val verName: String by rootProject.extra
14 | val commitHash: String by rootProject.extra
15 | val abiList: List by rootProject.extra
16 |
17 | android {
18 | buildFeatures {
19 | prefab = true
20 | }
21 | defaultConfig {
22 | ndk {
23 | abiFilters.addAll(abiList)
24 | }
25 | externalNativeBuild {
26 | cmake {
27 | cppFlags("-std=c++20")
28 | arguments(
29 | "-DANDROID_STL=none",
30 | "-DMODULE_NAME=$moduleId"
31 | )
32 | }
33 | }
34 | }
35 | externalNativeBuild {
36 | /*
37 | ndkBuild {
38 | path("src/main/cpp/Android.mk")
39 | }
40 | */
41 | cmake {
42 | path("src/main/cpp/CMakeLists.txt")
43 | }
44 | }
45 | }
46 |
47 | val abiMap = mapOf(
48 | "arm64-v8a" to "arm64",
49 | "armeabi-v7a" to "arm",
50 | "x86" to "x86",
51 | "x86_64" to "x64"
52 | )
53 |
54 | androidComponents.onVariants { variant ->
55 | afterEvaluate {
56 | val variantLowered = variant.name.lowercase()
57 | val variantCapped = variant.name.capitalizeUS()
58 | val buildTypeLowered = variant.buildType?.lowercase()
59 | val supportedAbis = abiList.map {
60 | abiMap[it] ?: error("unsupported abi $it")
61 | }.joinToString(" ")
62 |
63 | val moduleDir = layout.buildDirectory.file("outputs/module/$variantLowered")
64 | val zipFileName =
65 | "$moduleName-$verName-$verCode-$commitHash-$buildTypeLowered.zip".replace(' ', '-')
66 |
67 | val prepareModuleFilesTask = task("prepareModuleFiles$variantCapped") {
68 | group = "module"
69 | dependsOn("assemble$variantCapped")
70 | into(moduleDir)
71 | from(rootProject.layout.projectDirectory.file("README.md"))
72 | from(layout.projectDirectory.file("template")) {
73 | exclude("module.prop", "customize.sh", "post-fs-data.sh", "service.sh", "zn_modules.txt")
74 | filter("eol" to FixCrLfFilter.CrLf.newInstance("lf"))
75 | }
76 | from(layout.projectDirectory.file("template")) {
77 | include("module.prop", "zn_modules.txt")
78 | expand(
79 | "moduleId" to moduleId,
80 | "moduleName" to moduleName,
81 | "versionName" to "$verName ($verCode-$commitHash-$variantLowered)",
82 | "versionCode" to verCode
83 | )
84 | }
85 | from(layout.projectDirectory.file("template")) {
86 | include("customize.sh", "post-fs-data.sh", "service.sh")
87 | val tokens = mapOf(
88 | "DEBUG" to if (buildTypeLowered == "debug") "true" else "false",
89 | "SONAME" to moduleId,
90 | "SUPPORTED_ABIS" to supportedAbis
91 | )
92 | filter("tokens" to tokens)
93 | filter("eol" to FixCrLfFilter.CrLf.newInstance("lf"))
94 | }
95 | abiList.forEach { abi ->
96 | val arch = abiMap[abi]
97 | from(layout.buildDirectory.file("intermediates/stripped_native_libs/$variantLowered/strip${variantCapped}DebugSymbols/out/lib/$abi")) {
98 | into("lib/$arch")
99 | }
100 | }
101 |
102 | doLast {
103 | fileTree(moduleDir).visit {
104 | if (isDirectory) return@visit
105 | val md = MessageDigest.getInstance("SHA-256")
106 | file.forEachBlock(4096) { bytes, size ->
107 | md.update(bytes, 0, size)
108 | }
109 | file(file.path + ".sha256").writeText(
110 | org.apache.commons.codec.binary.Hex.encodeHexString(
111 | md.digest()
112 | )
113 | )
114 | }
115 | }
116 | }
117 |
118 | val zipTask = task("zip$variantCapped") {
119 | group = "module"
120 | dependsOn(prepareModuleFilesTask)
121 | archiveFileName.set(zipFileName)
122 | destinationDirectory.set(layout.projectDirectory.file("release").asFile)
123 | from(moduleDir)
124 | }
125 |
126 | val pushTask = task("push$variantCapped") {
127 | group = "module"
128 | dependsOn(zipTask)
129 | commandLine("adb", "push", zipTask.outputs.files.singleFile.path, "/data/local/tmp")
130 | }
131 |
132 | val installKsuTask = task("installKsu$variantCapped") {
133 | group = "module"
134 | dependsOn(pushTask)
135 | commandLine(
136 | "adb", "shell", "su", "-c",
137 | "/data/adb/ksud module install /data/local/tmp/$zipFileName"
138 | )
139 | }
140 |
141 | val installMagiskTask = task("installMagisk$variantCapped") {
142 | group = "module"
143 | dependsOn(pushTask)
144 | commandLine(
145 | "adb",
146 | "shell",
147 | "su",
148 | "-M",
149 | "-c",
150 | "magisk --install-module /data/local/tmp/$zipFileName"
151 | )
152 | }
153 |
154 | task("installKsuAndReboot$variantCapped") {
155 | group = "module"
156 | dependsOn(installKsuTask)
157 | commandLine("adb", "reboot")
158 | }
159 |
160 | task("installMagiskAndReboot$variantCapped") {
161 | group = "module"
162 | dependsOn(installMagiskTask)
163 | commandLine("adb", "reboot")
164 | }
165 | }
166 | }
167 |
168 | dependencies {
169 | implementation(libs.cxx)
170 | }
171 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------