From 22dbfe6c2eb4ee0ea87fe8c8fbc66d97f780f7fa Mon Sep 17 00:00:00 2001 From: Perfare Date: Tue, 10 Aug 2021 15:30:47 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8D=87=E7=BA=A7=20Riru=20v26?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitattributes | 6 +- LICENSE | 21 +++ build.gradle | 16 +- gradle.properties | 3 +- gradle/wrapper/gradle-wrapper.properties | 4 +- module.gradle | 53 +++--- module/build.gradle | 176 +++++++++--------- module/src/main/cpp/CMakeLists.txt | 24 ++- module/src/main/cpp/include/config.h | 8 + module/src/main/cpp/main.cpp | 166 +++++++---------- module/src/main/cpp/template/config.cpp | 8 + settings.gradle | 4 + .../META-INF/com/google/android/update-binary | 154 +-------------- template/magisk_module/customize.sh | 73 ++++---- template/magisk_module/module.prop | 6 + template/magisk_module/post-fs-data.sh | 10 - template/magisk_module/riru.sh | 70 ++++--- template/magisk_module/uninstall.sh | 4 - template/magisk_module/verify.sh | 2 +- 19 files changed, 345 insertions(+), 463 deletions(-) create mode 100644 LICENSE create mode 100644 module/src/main/cpp/include/config.h create mode 100644 module/src/main/cpp/template/config.cpp create mode 100644 template/magisk_module/module.prop delete mode 100644 template/magisk_module/post-fs-data.sh diff --git a/.gitattributes b/.gitattributes index 1341b049..27fc7c29 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,4 @@ -*.prop text eol=lf -*.sh text eol=lf \ No newline at end of file +* text=auto eol=lf + +*.bat text eol=crlf +*.jar binary \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..39817e71 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Rikka + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/build.gradle b/build.gradle index 890dbfcb..479bce87 100644 --- a/build.gradle +++ b/build.gradle @@ -8,26 +8,28 @@ idea.module { buildscript { repositories { + mavenCentral() google() - jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:4.1.1' + classpath 'com.android.tools.build:gradle:4.2.2' } } allprojects { repositories { + mavenCentral() google() - jcenter() } } -task clean(type: Delete) { - delete rootProject.buildDir -} - ext { minSdkVersion = 23 targetSdkVersion = 30 + + outDir = file("$rootDir/out") +} + +task clean(type: Delete) { + delete rootProject.buildDir, outDir } diff --git a/gradle.properties b/gradle.properties index 8bcc7a1e..73229782 100644 --- a/gradle.properties +++ b/gradle.properties @@ -18,4 +18,5 @@ android.useAndroidX=true # Automatically convert third-party libraries to use AndroidX android.enableJetifier=true # https://github.com/google/prefab/issues/122 -android.prefabVersion=1.1.2 \ No newline at end of file +# Remove this until AGP update prefab version +android.prefabVersion=1.1.3 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 57e0a438..de39001a 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Fri Oct 09 23:12:33 CST 2020 +#Mon Jul 12 21:05:17 CST 2021 distributionBase=GRADLE_USER_HOME -distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.1.1-all.zip distributionPath=wrapper/dists zipStorePath=wrapper/dists zipStoreBase=GRADLE_USER_HOME diff --git a/module.gradle b/module.gradle index a01cb670..693c142b 100644 --- a/module.gradle +++ b/module.gradle @@ -1,31 +1,30 @@ ext { - // FIXME replace with yours - moduleId = "il2cppdumper" - moduleName = "Il2CppDumper" - moduleAuthor = "Perfare" - moduleDescription = "Il2CppDumper Riru version." - moduleVersion = "v1.1" - moduleVersionCode = 1 + /* + This name will be used in the name of the so file ("lib${moduleLibraryName}.so"). + */ + moduleLibraryName = "il2cppdumper" + + /* Minimal supported Riru API version, used in the version check of riru.sh */ + moduleMinRiruApiVersion = 24 + + /* The version name of minimal supported Riru, used in the version check of riru.sh */ + moduleMinRiruVersionName = "v24.0.0" - moduleMinRiruApiVersion = 9 - moduleMinRiruVersionName = "v22.0" - moduleRiruApiVersion = 10 + /* Maximum supported Riru API version, used in the version check of riru.sh */ + moduleRiruApiVersion = 26 - moduleProp = [ - name : moduleName, - version : moduleVersion, - versionCode: moduleVersionCode.toString(), - author : moduleAuthor, - description: moduleDescription, - minApi : moduleMinRiruApiVersion - ] + /* + Magisk module ID + Since Magisk use it to distinguish different modules, you should never change it. - magiskModuleProp = [ - id : "riru-${moduleId.replace('_', '-')}", - name : "Riru - ${moduleProp['name']}", - version : moduleProp['version'], - versionCode: moduleProp['versionCode'], - author : moduleProp['author'], - description: moduleProp['description'] - ] -} \ No newline at end of file + Note, the older version of the template uses '-' instead of '_', if your are upgrading from + the older version, please pay attention. + */ + magiskModuleId = "riru_il2cppdumper" + + moduleName = "Il2CppDumper" + moduleAuthor = "Perfare" + moduleDescription = "Il2CppDumper Riru version." + moduleVersion = "v26.0.0" + moduleVersionCode = 26 +} diff --git a/module/build.gradle b/module/build.gradle index 4bc37175..89588c6c 100644 --- a/module/build.gradle +++ b/module/build.gradle @@ -1,3 +1,8 @@ +import org.apache.tools.ant.filters.FixCrLfFilter +import org.apache.tools.ant.filters.ReplaceTokens + +import java.security.MessageDigest + apply plugin: 'com.android.library' apply from: file(rootProject.file('module.gradle')) @@ -8,11 +13,11 @@ android { targetSdkVersion rootProject.ext.targetSdkVersion externalNativeBuild { cmake { - arguments "-DMODULE_NAME:STRING=riru_$moduleId", + arguments "-DMODULE_NAME:STRING=$moduleLibraryName", "-DRIRU_MODULE_API_VERSION=$moduleRiruApiVersion", "-DRIRU_MODULE_VERSION=$moduleVersionCode", - "-DRIRU_MODULE_VERSION_NAME:STRING=\"$moduleVersion\"" - + "-DRIRU_MODULE_VERSION_NAME:STRING=$moduleVersion", + "-DRIRU_MODULE_MIN_API_VERSION=$moduleMinRiruApiVersion" } } } @@ -29,8 +34,6 @@ android { repositories { mavenLocal() - jcenter() - maven { url 'https://dl.bintray.com/rikkaw/Libraries' } } dependencies { @@ -39,104 +42,95 @@ dependencies { // you can copy this file from https://github.com/RikkaApps/Riru/blob/master/riru/src/main/cpp/include_riru/riru.h // The default version of prefab in AGP has problem to process header only package, - // you may have to add android.prefabVersion=1.1.2 in your gradle.properties. + // you may have to add "android.prefabVersion" in your gradle.properties. // See https://github.com/google/prefab/issues/122 - implementation 'rikka.ndk:riru:10' + implementation 'dev.rikka.ndk:riru:26.0.0' } -def outDir = file("$rootDir/out") -def magiskDir = file("$outDir/magisk_module") -def zipName = "${magiskModuleProp['id'].replace('_', '-')}-${magiskModuleProp['version']}.zip" -def riruDir = "$magiskDir/riru" +afterEvaluate { + android.libraryVariants.forEach { variant -> + def variantCapped = variant.name.capitalize() + def variantLowered = variant.name.toLowerCase() -import org.apache.tools.ant.filters.FixCrLfFilter + def zipName = "${magiskModuleId.replace('_', '-')}-${moduleVersion}-${variantLowered}.zip" + def magiskDir = file("$outDir/magisk_module_$variantLowered") -import java.nio.file.Files -import java.security.MessageDigest + task("prepareMagiskFiles${variantCapped}", type: Sync) { + dependsOn("assemble$variantCapped") -static def calcSha256(file) { - def md = MessageDigest.getInstance("SHA-256") - file.eachByte 4096, { bytes, size -> - md.update(bytes, 0, size); - } - return md.digest().encodeHex() -} + def templatePath = "$rootDir/template/magisk_module" -static def renameOrFail(File from, File to) { - if (!from.renameTo(to)) { - throw new IOException("Unable reanme file $from to $to") - } -} + into magiskDir + from(templatePath) { + exclude 'riru.sh', 'module.prop' + } + from(templatePath) { + include 'riru.sh' + filter(ReplaceTokens.class, tokens: [ + "RIRU_MODULE_LIB_NAME" : moduleLibraryName, + "RIRU_MODULE_API_VERSION" : moduleRiruApiVersion.toString(), + "RIRU_MODULE_MIN_API_VERSION" : moduleMinRiruApiVersion.toString(), + "RIRU_MODULE_MIN_RIRU_VERSION_NAME": moduleMinRiruVersionName, + ]) + filter(FixCrLfFilter.class, + eol: FixCrLfFilter.CrLf.newInstance("lf")) + } + from(templatePath) { + include 'module.prop' + expand([ + id : magiskModuleId, + name : moduleName, + version : moduleVersion, + versionCode: moduleVersionCode.toString(), + author : moduleAuthor, + description: moduleDescription, + ]) + filter(FixCrLfFilter.class, + eol: FixCrLfFilter.CrLf.newInstance("lf")) + } + from("$buildDir/intermediates/stripped_native_libs/$variantLowered/out/lib") { + into 'lib' + } + doLast { + fileTree("$magiskDir").visit { f -> + if (f.directory) return + if (f.file.name == '.gitattributes') return + + def md = MessageDigest.getInstance("SHA-256") + f.file.eachByte 4096, { bytes, size -> + md.update(bytes, 0, size) + } + file(f.file.path + ".sha256sum").text = md.digest().encodeHex() + } + } + } -android.libraryVariants.all { variant -> - def task = variant.assembleProvider.get() - task.doLast { - // clear - delete { delete magiskDir } - - // copy from template - copy { - from "$rootDir/template/magisk_module" - into magiskDir.path - exclude 'riru.sh' + task("zip${variantCapped}", type: Zip) { + dependsOn("prepareMagiskFiles${variantCapped}") + from magiskDir + archiveName zipName + destinationDir outDir } - // copy riru.sh - copy { - from "$rootDir/template/magisk_module" - into magiskDir.path - include 'riru.sh' - filter { line -> - line.replaceAll('%%%RIRU_MODULE_ID%%%', moduleId) - .replaceAll('%%%RIRU_MODULE_API_VERSION%%%', moduleRiruApiVersion.toString()) - .replaceAll('%%%RIRU_MODULE_MIN_API_VERSION%%%', moduleMinRiruApiVersion.toString()) - .replaceAll('%%%RIRU_MODULE_MIN_RIRU_VERSION_NAME%%%', moduleMinRiruVersionName) - } - filter(FixCrLfFilter.class, - eol: FixCrLfFilter.CrLf.newInstance("lf")) + + task("push${variantCapped}", type: Exec) { + dependsOn("zip${variantCapped}") + workingDir outDir + commandLine android.adbExecutable, "push", zipName, "/data/local/tmp/" + } + + task("flash${variantCapped}", type: Exec) { + dependsOn("push${variantCapped}") + commandLine android.adbExecutable, "shell", "su", "-c", + "magisk --install-module /data/local/tmp/${zipName}" } - // copy .git files manually since gradle exclude it by default - Files.copy(file("$rootDir/template/magisk_module/.gitattributes").toPath(), file("${magiskDir.path}/.gitattributes").toPath()) - - // generate module.prop - def modulePropText = "" - magiskModuleProp.each { k, v -> modulePropText += "$k=$v\n" } - modulePropText = modulePropText.trim() - file("$magiskDir/module.prop").text = modulePropText - - // generate module.prop for Riru - def riruModulePropText = "" - moduleProp.each { k, v -> riruModulePropText += "$k=$v\n" } - riruModulePropText = riruModulePropText.trim() - file(riruDir).mkdirs() - - // module.prop.new will be renamed to module.prop in post-fs-data.sh - file("$riruDir/module.prop.new").text = riruModulePropText - - // copy native files - def nativeOutDir = file("build/intermediates/cmake/$variant.name/obj") - - file("$magiskDir/system").mkdirs() - file("$magiskDir/system_x86").mkdirs() - renameOrFail(file("$nativeOutDir/arm64-v8a"), file("$magiskDir/system/lib64")) - renameOrFail(file("$nativeOutDir/armeabi-v7a"), file("$magiskDir/system/lib")) - renameOrFail(file("$nativeOutDir/x86_64"), file("$magiskDir/system_x86/lib64")) - renameOrFail(file("$nativeOutDir/x86"), file("$magiskDir/system_x86/lib")) - - // generate sha1sum - fileTree("$magiskDir").matching { - exclude "README.md", "META-INF" - }.visit { f -> - if (f.directory) return - file(f.file.path + ".sha256sum").text = calcSha256(f.file) + + task("flashAndReboot${variantCapped}", type: Exec) { + dependsOn("flash${variantCapped}") + commandLine android.adbExecutable, "shell", "reboot" } + + variant.assembleProvider.get().finalizedBy("zip${variantCapped}") } - task.finalizedBy zipMagiskMoudle } - -task zipMagiskMoudle(type: Zip) { - from magiskDir - archiveName zipName - destinationDir outDir -} \ No newline at end of file diff --git a/module/src/main/cpp/CMakeLists.txt b/module/src/main/cpp/CMakeLists.txt index 01b64084..8866be17 100644 --- a/module/src/main/cpp/CMakeLists.txt +++ b/module/src/main/cpp/CMakeLists.txt @@ -2,6 +2,8 @@ cmake_minimum_required(VERSION 3.4.1) if (NOT DEFINED MODULE_NAME) message(FATAL_ERROR "MODULE_NAME is not set") +else () + project(${MODULE_NAME}) endif () set(DobbyHome Dobby) @@ -15,9 +17,8 @@ SET_OPTION(DOBBY_GENERATE_SHARED OFF) add_subdirectory(${DobbyHome} dobby) add_definitions(-DRIRU_MODULE) -add_definitions(-DRIRU_MODULE_API_VERSION=${RIRU_MODULE_API_VERSION}) -add_definitions(-DRIRU_MODULE_VERSION=${RIRU_MODULE_VERSION}) -add_definitions(-DRIRU_MODULE_VERSION_NAME=${RIRU_MODULE_VERSION_NAME}) + +configure_file(template/config.cpp config.cpp) message("Build type: ${CMAKE_BUILD_TYPE}") @@ -25,22 +26,29 @@ set(CMAKE_CXX_STANDARD 11) set(LINKER_FLAGS "-ffixed-x18 -Wl,--hash-style=both") set(C_FLAGS "-Werror=format -fdata-sections -ffunction-sections") +set(CXX_FLAGS "${CXX_FLAGS} -fno-exceptions -fno-rtti") -if (CMAKE_BUILD_TYPE STREQUAL "Release") +if (NOT CMAKE_BUILD_TYPE STREQUAL "Debug") set(C_FLAGS "${C_FLAGS} -O2 -fvisibility=hidden -fvisibility-inlines-hidden") - set(LINKER_FLAGS "${LINKER_FLAGS} -Wl,-exclude-libs,ALL -Wl,--gc-sections") + set(LINKER_FLAGS "${LINKER_FLAGS} -Wl,-exclude-libs,ALL -Wl,--gc-sections -Wl,--strip-all") else () set(C_FLAGS "${C_FLAGS} -O0") endif () set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${C_FLAGS}") -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${C_FLAGS}") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${C_FLAGS} ${CXX_FLAGS}") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${LINKER_FLAGS}") set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${LINKER_FLAGS}") find_package(riru REQUIRED CONFIG) -add_library(${MODULE_NAME} SHARED main.cpp hook.cpp il2cpp_dump.cpp) +include_directories(include) + +add_library(${MODULE_NAME} SHARED main.cpp ${CMAKE_CURRENT_BINARY_DIR}/config.cpp hook.cpp il2cpp_dump.cpp) target_link_libraries(${MODULE_NAME} log riru::riru dobby) -set_target_properties(${MODULE_NAME} PROPERTIES LINK_FLAGS_RELEASE -s) + +if (NOT CMAKE_BUILD_TYPE STREQUAL "Debug") + add_custom_command(TARGET ${MODULE_NAME} POST_BUILD + COMMAND ${CMAKE_STRIP} --strip-all --remove-section=.comment "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/lib${MODULE_NAME}.so") +endif () diff --git a/module/src/main/cpp/include/config.h b/module/src/main/cpp/include/config.h new file mode 100644 index 00000000..6203e3d8 --- /dev/null +++ b/module/src/main/cpp/include/config.h @@ -0,0 +1,8 @@ +#pragma once + +namespace riru { + extern const int moduleVersionCode; + extern const char* const moduleVersionName; + extern const int moduleApiVersion; + extern const int moduleMinApiVersion; +} diff --git a/module/src/main/cpp/main.cpp b/module/src/main/cpp/main.cpp index e3e9998e..4aac3278 100644 --- a/module/src/main/cpp/main.cpp +++ b/module/src/main/cpp/main.cpp @@ -3,23 +3,28 @@ #include #include #include +#include #include #include "hook.h" static void forkAndSpecializePre( - JNIEnv *env, jclass clazz, jint *_uid, jint *gid, jintArray *gids, jint *runtimeFlags, + JNIEnv *env, jclass clazz, jint *uid, jint *gid, jintArray *gids, jint *runtimeFlags, jobjectArray *rlimits, jint *mountExternal, jstring *seInfo, jstring *niceName, jintArray *fdsToClose, jintArray *fdsToIgnore, jboolean *is_child_zygote, - jstring *instructionSet, jstring *appDataDir, jboolean *isTopApp, - jobjectArray *pkgDataInfoList, - jobjectArray *whitelistedDataInfoList, jboolean *bindMountAppDataDirs, - jboolean *bindMountAppStorageDirs) { - enable_hack = isGame(env, *appDataDir); + jstring *instructionSet, jstring *appDataDir, jboolean *isTopApp, jobjectArray *pkgDataInfoList, + jobjectArray *whitelistedDataInfoList, jboolean *bindMountAppDataDirs, jboolean *bindMountAppStorageDirs) { + // Called "before" com_android_internal_os_Zygote_nativeForkAndSpecialize in frameworks/base/core/jni/com_android_internal_os_Zygote.cpp + // Parameters are pointers, you can change the value of them if you want + // Some parameters are not exist is older Android versions, in this case, they are null or 0 + enable_hack = isGame(env, *appDataDir); } static void forkAndSpecializePost(JNIEnv *env, jclass clazz, jint res) { + // Called "after" com_android_internal_os_Zygote_nativeForkAndSpecialize in frameworks/base/core/jni/com_android_internal_os_Zygote.cpp + // "res" is the return value of com_android_internal_os_Zygote_nativeForkAndSpecialize + if (res == 0) { - // in app process + // In app process if (enable_hack) { int ret; pthread_t ntid; @@ -27,130 +32,93 @@ static void forkAndSpecializePost(JNIEnv *env, jclass clazz, jint res) { LOGE("can't create thread: %s\n", strerror(ret)); } } + // When unload allowed is true, the module will be unloaded (dlclose) by Riru + // If this modules has hooks installed, DONOT set it to true, or there will be SIGSEGV + // This value will be automatically reset to false before the "pre" function is called + riru_set_unload_allowed(false); } else { - // in zygote process, res is child pid - // don't print log here, see https://github.com/RikkaApps/Riru/blob/77adfd6a4a6a81bfd20569c910bc4854f2f84f5e/riru-core/jni/main/jni_native_method.cpp#L55-L66 + // In zygote process } } static void specializeAppProcessPre( - JNIEnv *env, jclass clazz, jint *_uid, jint *gid, jintArray *gids, jint *runtimeFlags, + JNIEnv *env, jclass clazz, jint *uid, jint *gid, jintArray *gids, jint *runtimeFlags, jobjectArray *rlimits, jint *mountExternal, jstring *seInfo, jstring *niceName, jboolean *startChildZygote, jstring *instructionSet, jstring *appDataDir, jboolean *isTopApp, jobjectArray *pkgDataInfoList, jobjectArray *whitelistedDataInfoList, jboolean *bindMountAppDataDirs, jboolean *bindMountAppStorageDirs) { - // added from Android 10, but disabled at least in Google Pixel devices + // Called "before" com_android_internal_os_Zygote_nativeSpecializeAppProcess in frameworks/base/core/jni/com_android_internal_os_Zygote.cpp + // Parameters are pointers, you can change the value of them if you want + // Some parameters are not exist is older Android versions, in this case, they are null or 0 } static void specializeAppProcessPost( JNIEnv *env, jclass clazz) { - // added from Android 10, but disabled at least in Google Pixel devices + // Called "after" com_android_internal_os_Zygote_nativeSpecializeAppProcess in frameworks/base/core/jni/com_android_internal_os_Zygote.cpp + + // When unload allowed is true, the module will be unloaded (dlclose) by Riru + // If this modules has hooks installed, DONOT set it to true, or there will be SIGSEGV + // This value will be automatically reset to false before the "pre" function is called + riru_set_unload_allowed(true); } static void forkSystemServerPre( JNIEnv *env, jclass clazz, uid_t *uid, gid_t *gid, jintArray *gids, jint *runtimeFlags, jobjectArray *rlimits, jlong *permittedCapabilities, jlong *effectiveCapabilities) { - + // Called "before" com_android_internal_os_Zygote_forkSystemServer in frameworks/base/core/jni/com_android_internal_os_Zygote.cpp + // Parameters are pointers, you can change the value of them if you want + // Some parameters are not exist is older Android versions, in this case, they are null or 0 } static void forkSystemServerPost(JNIEnv *env, jclass clazz, jint res) { + // Called "after" com_android_internal_os_Zygote_forkSystemServer in frameworks/base/core/jni/com_android_internal_os_Zygote.cpp + if (res == 0) { - // in system server process + // In system server process } else { - // in zygote process, res is child pid - // don't print log here, see https://github.com/RikkaApps/Riru/blob/77adfd6a4a6a81bfd20569c910bc4854f2f84f5e/riru-core/jni/main/jni_native_method.cpp#L55-L66 + // In zygote process } } -static int shouldSkipUid(int uid) { - // by default, Riru only call module functions in "normal app processes" (10000 <= uid % 100000 <= 19999) - // false = don't skip - return false; -} - static void onModuleLoaded() { - // called when the shared library of Riru core is loaded + // Called when this library is loaded and "hidden" by Riru (see Riru's hide.cpp) + + // If you want to use threads, start them here rather than the constructors + // __attribute__((constructor)) or constructors of static variables, + // or the "hide" will cause SIGSEGV } extern "C" { int riru_api_version; -RiruApiV9 *riru_api_v9; - -/* - * Init will be called three times. - * - * The first time: - * Returns the highest version number supported by both Riru and the module. - * - * arg: (int *) Riru's API version - * returns: (int *) the highest possible API version - * - * The second time: - * Returns the RiruModuleX struct created by the module. - * (X is the return of the first call) - * - * arg: (RiruApiVX *) RiruApi strcut, this pointer can be saved for further use - * returns: (RiruModuleX *) RiruModule strcut - * - * The second time: - * Let the module to cleanup (such as RiruModuleX struct created before). - * - * arg: null - * returns: (ignored) - * - */ -void *init(void *arg) { - static int step = 0; - step += 1; - - static void *_module; - - switch (step) { - case 1: { - auto core_max_api_version = *(int *) arg; - riru_api_version = - core_max_api_version <= RIRU_MODULE_API_VERSION ? core_max_api_version - : RIRU_MODULE_API_VERSION; - return &riru_api_version; - } - case 2: { - switch (riru_api_version) { - // RiruApiV10 and RiruModuleInfoV10 are equal to V9 - case 10: - case 9: { - riru_api_v9 = (RiruApiV9 *) arg; - - auto module = (RiruModuleInfoV9 *) malloc(sizeof(RiruModuleInfoV9)); - memset(module, 0, sizeof(RiruModuleInfoV9)); - _module = module; - - module->supportHide = true; - - module->version = RIRU_MODULE_VERSION; - module->versionName = RIRU_MODULE_VERSION_NAME; - module->onModuleLoaded = onModuleLoaded; - module->shouldSkipUid = shouldSkipUid; - module->forkAndSpecializePre = forkAndSpecializePre; - module->forkAndSpecializePost = forkAndSpecializePost; - module->specializeAppProcessPre = specializeAppProcessPre; - module->specializeAppProcessPost = specializeAppProcessPost; - module->forkSystemServerPre = forkSystemServerPre; - module->forkSystemServerPost = forkSystemServerPost; - return module; - } - default: { - return nullptr; - } - } - } - case 3: { - free(_module); - return nullptr; - } - default: { - return nullptr; +const char *riru_magisk_module_path = nullptr; +int *riru_allow_unload = nullptr; + +static auto module = RiruVersionedModuleInfo{ + .moduleApiVersion = riru::moduleApiVersion, + .moduleInfo= RiruModuleInfo{ + .supportHide = true, + .version = riru::moduleVersionCode, + .versionName = riru::moduleVersionName, + .onModuleLoaded = onModuleLoaded, + .forkAndSpecializePre = forkAndSpecializePre, + .forkAndSpecializePost = forkAndSpecializePost, + .forkSystemServerPre = forkSystemServerPre, + .forkSystemServerPost = forkSystemServerPost, + .specializeAppProcessPre = specializeAppProcessPre, + .specializeAppProcessPost = specializeAppProcessPost } +}; + +RiruVersionedModuleInfo *init(Riru *riru) { + auto core_max_api_version = riru->riruApiVersion; + riru_api_version = core_max_api_version <= riru::moduleApiVersion ? core_max_api_version : riru::moduleApiVersion; + module.moduleApiVersion = riru_api_version; + + riru_magisk_module_path = strdup(riru->magiskModulePath); + if (riru_api_version >= 25) { + riru_allow_unload = riru->allowUnload; } + return &module; +} } -} \ No newline at end of file diff --git a/module/src/main/cpp/template/config.cpp b/module/src/main/cpp/template/config.cpp new file mode 100644 index 00000000..36e2f460 --- /dev/null +++ b/module/src/main/cpp/template/config.cpp @@ -0,0 +1,8 @@ +#include "config.h" + +namespace riru { + const int moduleVersionCode = ${RIRU_MODULE_VERSION}; + const char* const moduleVersionName = "${RIRU_MODULE_VERSION_NAME}"; + const int moduleApiVersion = ${RIRU_MODULE_API_VERSION}; + const int moduleMinApiVersion = ${RIRU_MODULE_MIN_API_VERSION}; +} diff --git a/settings.gradle b/settings.gradle index 1d0cab1b..a8433394 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1 +1,5 @@ include ':module' + +import org.apache.tools.ant.DirectoryScanner + +DirectoryScanner.removeDefaultExclude('**/.gitattributes') diff --git a/template/magisk_module/META-INF/com/google/android/update-binary b/template/magisk_module/META-INF/com/google/android/update-binary index d19eeb55..28b48e58 100644 --- a/template/magisk_module/META-INF/com/google/android/update-binary +++ b/template/magisk_module/META-INF/com/google/android/update-binary @@ -6,168 +6,28 @@ umask 022 -# Global vars -TMPDIR=/dev/tmp -PERSISTDIR=/sbin/.magisk/mirror/persist - -rm -rf $TMPDIR 2>/dev/null -mkdir -p $TMPDIR - # echo before loading util_functions ui_print() { echo "$1"; } require_new_magisk() { ui_print "*******************************" - ui_print " Please install Magisk v19.0+! " + ui_print " Please install Magisk v20.4+! " ui_print "*******************************" exit 1 } -is_legacy_script() { - unzip -l "$ZIPFILE" install.sh | grep -q install.sh - return $? -} - -print_modname() { - local len - len=`echo -n $MODNAME | wc -c` - len=$((len + 2)) - local pounds=`printf "%${len}s" | tr ' ' '*'` - ui_print "$pounds" - ui_print " $MODNAME " - ui_print "$pounds" - ui_print "*******************" - ui_print " Powered by Magisk " - ui_print "*******************" -} - -############## -# Environment -############## +######################### +# Load util_functions.sh +######################### OUTFD=$2 ZIPFILE=$3 mount /data 2>/dev/null -# Load utility functions [ -f /data/adb/magisk/util_functions.sh ] || require_new_magisk . /data/adb/magisk/util_functions.sh -[ $MAGISK_VER_CODE -gt 18100 ] || require_new_magisk - -# Preperation for flashable zips -setup_flashable - -# Mount partitions -mount_partitions - -# Detect version and architecture -api_level_arch_detect - -# Setup busybox and binaries -$BOOTMODE && boot_actions || recovery_actions - -############## -# Preparation -############## - -# Extract prop file -unzip -o "$ZIPFILE" module.prop -d $TMPDIR >&2 -[ ! -f $TMPDIR/module.prop ] && abort "! Unable to extract zip file!" - -$BOOTMODE && MODDIRNAME=modules_update || MODDIRNAME=modules -MODULEROOT=$NVBASE/$MODDIRNAME -MODID=`grep_prop id $TMPDIR/module.prop` -MODPATH=$MODULEROOT/$MODID -MODNAME=`grep_prop name $TMPDIR/module.prop` - -# Create mod paths -rm -rf $MODPATH 2>/dev/null -mkdir -p $MODPATH - -########## -# Install -########## - -if is_legacy_script; then - unzip -oj "$ZIPFILE" module.prop install.sh uninstall.sh 'common/*' -d $TMPDIR >&2 - - # Load install script - . $TMPDIR/install.sh - - # Callbacks - print_modname - on_install - - # Custom uninstaller - [ -f $TMPDIR/uninstall.sh ] && cp -af $TMPDIR/uninstall.sh $MODPATH/uninstall.sh - - # Skip mount - $SKIPMOUNT && touch $MODPATH/skip_mount - - # prop file - $PROPFILE && cp -af $TMPDIR/system.prop $MODPATH/system.prop - - # Module info - cp -af $TMPDIR/module.prop $MODPATH/module.prop - - # post-fs-data scripts - $POSTFSDATA && cp -af $TMPDIR/post-fs-data.sh $MODPATH/post-fs-data.sh - - # service scripts - $LATESTARTSERVICE && cp -af $TMPDIR/service.sh $MODPATH/service.sh - - ui_print "- Setting permissions" - set_permissions -else - print_modname - - unzip -o "$ZIPFILE" customize.sh -d $MODPATH >&2 - - if ! grep -q '^SKIPUNZIP=1$' $MODPATH/customize.sh 2>/dev/null; then - ui_print "- Extracting module files" - unzip -o "$ZIPFILE" -x 'META-INF/*' -d $MODPATH >&2 - - # Default permissions - set_perm_recursive $MODPATH 0 0 0755 0644 - fi - - # Load customization script - [ -f $MODPATH/customize.sh ] && . $MODPATH/customize.sh -fi - -# Handle replace folders -for TARGET in $REPLACE; do - ui_print "- Replace target: $TARGET" - mktouch $MODPATH$TARGET/.replace -done - -if $BOOTMODE; then - # Update info for Magisk Manager - mktouch $NVBASE/modules/$MODID/update - cp -af $MODPATH/module.prop $NVBASE/modules/$MODID/module.prop -fi - -# Copy over custom sepolicy rules -if [ -f $MODPATH/sepolicy.rule -a -e $PERSISTDIR ]; then - ui_print "- Installing custom sepolicy patch" - PERSISTMOD=$PERSISTDIR/magisk/$MODID - mkdir -p $PERSISTMOD - cp -af $MODPATH/sepolicy.rule $PERSISTMOD/sepolicy.rule -fi - -# Remove stuffs that don't belong to modules -rm -rf \ -$MODPATH/system/placeholder $MODPATH/customize.sh \ -$MODPATH/README.md $MODPATH/.git* 2>/dev/null - -############## -# Finalizing -############## - -cd / -$BOOTMODE || recovery_cleanup -rm -rf $TMPDIR +[ $MAGISK_VER_CODE -lt 20400 ] && require_new_magisk -ui_print "- Done" -exit 0 \ No newline at end of file +install_module +exit 0 diff --git a/template/magisk_module/customize.sh b/template/magisk_module/customize.sh index f484ebcd..11f86b9c 100644 --- a/template/magisk_module/customize.sh +++ b/template/magisk_module/customize.sh @@ -1,13 +1,6 @@ SKIPUNZIP=1 -# check_architecture -if [ "$ARCH" != "arm" ] && [ "$ARCH" != "arm64" ] && [ "$ARCH" != "x86" ] && [ "$ARCH" != "x64" ]; then - abort "! Unsupported platform: $ARCH" -else - ui_print "- Device platform: $ARCH" -fi - -# extract verify.sh +# Extract verify.sh ui_print "- Extracting verify.sh" unzip -o "$ZIPFILE" 'verify.sh' -d "$TMPDIR" >&2 if [ ! -f "$TMPDIR/verify.sh" ]; then @@ -18,46 +11,60 @@ if [ ! -f "$TMPDIR/verify.sh" ]; then fi . $TMPDIR/verify.sh -# extract riru.sh -extract "$ZIPFILE" 'riru.sh' "$MODPATH" -. $MODPATH/riru.sh +# Extract riru.sh + +# Variables provided by riru.sh: +# +# RIRU_API: API version of installed Riru, 0 if not installed +# RIRU_MIN_COMPATIBLE_API: minimal supported API version by installed Riru, 0 if not installed or version < v23.2 +# RIRU_VERSION_CODE: version code of installed Riru, 0 if not installed or version < v23.2 +# RIRU_VERSION_NAME: version name of installed Riru, "" if not installed or version < v23.2 + +extract "$ZIPFILE" 'riru.sh' "$TMPDIR" +. $TMPDIR/riru.sh +# Functions from util_functions.sh (it will be loaded by riru.sh) check_riru_version +enforce_install_from_magisk_app -# extract libs +# Check architecture +if [ "$ARCH" != "arm" ] && [ "$ARCH" != "arm64" ] && [ "$ARCH" != "x86" ] && [ "$ARCH" != "x64" ]; then + abort "! Unsupported platform: $ARCH" +else + ui_print "- Device platform: $ARCH" +fi + +# Extract libs ui_print "- Extracting module files" extract "$ZIPFILE" 'module.prop' "$MODPATH" -extract "$ZIPFILE" 'post-fs-data.sh' "$MODPATH" extract "$ZIPFILE" 'uninstall.sh' "$MODPATH" -#extract "$ZIPFILE" 'sepolicy.rule' "$MODPATH" -if [ "$ARCH" = "x86" ] || [ "$ARCH" = "x64" ]; then - ui_print "- Extracting x86 libraries" - extract "$ZIPFILE" "system_x86/lib/libriru_$RIRU_MODULE_ID.so" "$MODPATH" - mv "$MODPATH/system_x86" "$MODPATH/system" +# Riru v24+ load files from the "riru" folder in the Magisk module folder +# This "riru" folder is also used to determine if a Magisk module is a Riru module - if [ "$IS64BIT" = true ]; then - ui_print "- Extracting x64 libraries" - extract "$ZIPFILE" "system_x86/lib64/libriru_$RIRU_MODULE_ID.so" "$MODPATH" - mv "$MODPATH/system_x86/lib64" "$MODPATH/system/lib64" - fi -else +mkdir "$MODPATH/riru" +mkdir "$MODPATH/riru/lib" +mkdir "$MODPATH/riru/lib64" + +if [ "$ARCH" = "arm" ] || [ "$ARCH" = "arm64" ]; then ui_print "- Extracting arm libraries" - extract "$ZIPFILE" "system/lib/libriru_$RIRU_MODULE_ID.so" "$MODPATH" + extract "$ZIPFILE" "lib/armeabi-v7a/lib$RIRU_MODULE_LIB_NAME.so" "$MODPATH/riru/lib" true if [ "$IS64BIT" = true ]; then ui_print "- Extracting arm64 libraries" - extract "$ZIPFILE" "system/lib64/libriru_$RIRU_MODULE_ID.so" "$MODPATH" + extract "$ZIPFILE" "lib/arm64-v8a/lib$RIRU_MODULE_LIB_NAME.so" "$MODPATH/riru/lib64" true fi fi -set_perm_recursive "$MODPATH" 0 0 0755 0644 +if [ "$ARCH" = "x86" ] || [ "$ARCH" = "x64" ]; then + ui_print "- Extracting x86 libraries" + extract "$ZIPFILE" "lib/x86/lib$RIRU_MODULE_LIB_NAME.so" "$MODPATH/riru/lib" true -# extract Riru files -ui_print "- Extracting extra files" -[ -d "$RIRU_MODULE_PATH" ] || mkdir -p "$RIRU_MODULE_PATH" || abort "! Can't create $RIRU_MODULE_PATH" + if [ "$IS64BIT" = true ]; then + ui_print "- Extracting x64 libraries" + extract "$ZIPFILE" "lib/x86_64/lib$RIRU_MODULE_LIB_NAME.so" "$MODPATH/riru/lib64" true + fi +fi -rm -f "$RIRU_MODULE_PATH/module.prop.new" -extract "$ZIPFILE" 'riru/module.prop.new' "$RIRU_MODULE_PATH" true -set_perm "$RIRU_MODULE_PATH/module.prop.new" 0 0 0600 $RIRU_SECONTEXT \ No newline at end of file +set_perm_recursive "$MODPATH" 0 0 0755 0644 diff --git a/template/magisk_module/module.prop b/template/magisk_module/module.prop new file mode 100644 index 00000000..236bd20a --- /dev/null +++ b/template/magisk_module/module.prop @@ -0,0 +1,6 @@ +id=${id} +name=${name} +version=${version} +versionCode=${versionCode} +author=${author} +description=${description} diff --git a/template/magisk_module/post-fs-data.sh b/template/magisk_module/post-fs-data.sh deleted file mode 100644 index 664f6c1a..00000000 --- a/template/magisk_module/post-fs-data.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/system/bin/sh -MODDIR=${0%/*} -[ ! -f "$MODDIR/riru.sh" ] && exit 1 -. $MODDIR/riru.sh - -# Rename module.prop.new -if [ -f "$RIRU_MODULE_PATH/module.prop.new" ]; then - rm "$RIRU_MODULE_PATH/module.prop" - mv "$RIRU_MODULE_PATH/module.prop.new" "$RIRU_MODULE_PATH/module.prop" -fi \ No newline at end of file diff --git a/template/magisk_module/riru.sh b/template/magisk_module/riru.sh index 15b6613c..c3152c5b 100644 --- a/template/magisk_module/riru.sh +++ b/template/magisk_module/riru.sh @@ -1,36 +1,44 @@ #!/sbin/sh -RIRU_PATH="/data/adb/riru" -RIRU_MODULE_ID="%%%RIRU_MODULE_ID%%%" -RIRU_MODULE_PATH="$RIRU_PATH/modules/$RIRU_MODULE_ID" -RIRU_SECONTEXT="u:object_r:magisk_file:s0" +RIRU_MODULE_LIB_NAME="@RIRU_MODULE_LIB_NAME@" -# used by /data/adb/riru/util_functions.sh -RIRU_MODULE_API_VERSION=%%%RIRU_MODULE_API_VERSION%%% -RIRU_MODULE_MIN_API_VERSION=%%%RIRU_MODULE_MIN_API_VERSION%%% -RIRU_MODULE_MIN_RIRU_VERSION_NAME="%%%RIRU_MODULE_MIN_RIRU_VERSION_NAME%%%" +# Variables for customize.sh +RIRU_API=0 +RIRU_MIN_COMPATIBLE_API=0 +RIRU_VERSION_CODE=0 +RIRU_VERSION_NAME="" -# this function will be used when /data/adb/riru/util_functions.sh not exits -check_riru_version() { - if [ ! -f "$RIRU_PATH/api_version" ] && [ ! -f "$RIRU_PATH/api_version.new" ]; then - ui_print "*********************************************************" - ui_print "! Riru $RIRU_MIN_VERSION_NAME or above is required" - ui_print "! Please install Riru from Magisk Manager or https://github.com/RikkaApps/Riru/releases" - abort "*********************************************************" - fi - local_api_version=$(cat "$RIRU_PATH/api_version.new") || local_api_version=$(cat "$RIRU_PATH/api_version") || local_api_version=0 - [ "$local_api_version" -eq "$local_api_version" ] || local_api_version=0 - ui_print "- Riru API version: $local_api_version" - if [ "$local_api_version" -lt $RIRU_MODULE_MIN_API_VERSION ]; then - ui_print "*********************************************************" - ui_print "! Riru $RIRU_MIN_VERSION_NAME or above is required" - ui_print "! Please upgrade Riru from Magisk Manager or https://github.com/RikkaApps/Riru/releases" - abort "*********************************************************" - fi -} +# Used by util_functions.sh +RIRU_MODULE_API_VERSION=@RIRU_MODULE_API_VERSION@ +RIRU_MODULE_MIN_API_VERSION=@RIRU_MODULE_MIN_API_VERSION@ +RIRU_MODULE_MIN_RIRU_VERSION_NAME="@RIRU_MODULE_MIN_RIRU_VERSION_NAME@" -if [ -f /data/adb/riru/util_functions.sh ]; then - ui_print "- Load /data/adb/riru/util_functions.sh" - . /data/adb/riru/util_functions.sh +if [ "$MAGISK_VER_CODE" -ge 21000 ]; then + MAGISK_CURRENT_RIRU_MODULE_PATH=$(magisk --path)/.magisk/modules/riru-core else - ui_print "- Can't find /data/adb/riru/util_functions.sh" -fi \ No newline at end of file + MAGISK_CURRENT_RIRU_MODULE_PATH=/sbin/.magisk/modules/riru-core +fi + +if [ ! -d $MAGISK_CURRENT_RIRU_MODULE_PATH ]; then + ui_print "*********************************************************" + ui_print "! Riru is not installed" + ui_print "! Please install Riru from Magisk Manager or https://github.com/RikkaApps/Riru/releases" + abort "*********************************************************" +fi + +if [ -f "$MAGISK_CURRENT_RIRU_MODULE_PATH/disable" ] || [ -f "$MAGISK_CURRENT_RIRU_MODULE_PATH/remove" ]; then + ui_print "*********************************************************" + ui_print "! Riru is not enabled or will be removed" + ui_print "! Please enable Riru in Magisk first" + abort "*********************************************************" +fi + +if [ -f $MAGISK_CURRENT_RIRU_MODULE_PATH/util_functions.sh ]; then + ui_print "- Load $MAGISK_CURRENT_RIRU_MODULE_PATH/util_functions.sh" + # shellcheck disable=SC1090 + . $MAGISK_CURRENT_RIRU_MODULE_PATH/util_functions.sh +else + ui_print "*********************************************************" + ui_print "! Riru $RIRU_MODULE_MIN_RIRU_VERSION_NAME or above is required" + ui_print "! Please upgrade Riru from Magisk Manager or https://github.com/RikkaApps/Riru/releases" + abort "*********************************************************" +fi diff --git a/template/magisk_module/uninstall.sh b/template/magisk_module/uninstall.sh index 3c83e2be..3c86bf32 100644 --- a/template/magisk_module/uninstall.sh +++ b/template/magisk_module/uninstall.sh @@ -1,6 +1,2 @@ #!/sbin/sh MODDIR=${0%/*} -[ ! -f "$MODDIR/riru.sh" ] && exit 1 -. $MODDIR/riru.sh - -rm -rf "$RIRU_MODULE_PATH" \ No newline at end of file diff --git a/template/magisk_module/verify.sh b/template/magisk_module/verify.sh index b04a9ea3..fc706b6f 100644 --- a/template/magisk_module/verify.sh +++ b/template/magisk_module/verify.sh @@ -36,4 +36,4 @@ extract() { (echo "$(cat "$hash_path") $file_path" | sha256sum -c -s -) || abort_verify "Failed to verify $file" ui_print "- Verified $file" >&1 -} \ No newline at end of file +}