diff --git a/riru/.gitattributes b/riru/.gitattributes new file mode 100644 index 0000000..27fc7c2 --- /dev/null +++ b/riru/.gitattributes @@ -0,0 +1,4 @@ +* text=auto eol=lf + +*.bat text eol=crlf +*.jar binary \ No newline at end of file diff --git a/riru/.gitignore b/riru/.gitignore new file mode 100644 index 0000000..302e5c0 --- /dev/null +++ b/riru/.gitignore @@ -0,0 +1,15 @@ +*.iml +.gradle +/local.properties +.idea +/.idea/caches/build_file_checksums.ser +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +.DS_Store +/build +/captures +/out +.externalNativeBuild +.cxx +module.gradle \ No newline at end of file diff --git a/riru/LICENSE b/riru/LICENSE new file mode 100644 index 0000000..39817e7 --- /dev/null +++ b/riru/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/riru/README.md b/riru/README.md new file mode 100644 index 0000000..aaf8519 --- /dev/null +++ b/riru/README.md @@ -0,0 +1,141 @@ +# Riru - Template + +[Riru](https://github.com/RikkaApps/Riru) module template. + +## Build + +1. Rename `module.example.gradle` to `module.gradle` +2. Replace module info in `module.gradle` (all lines end with "replace with yours") +3. Write your codes +4. Run gradle task `:module:assembleRelease` task from Android Studio or command line, zip will be saved in `out`. + +## File structure + +A Riru module is a Magisk module, please read [Magisk module document](https://topjohnwu.github.io/Magisk/guides.html#magisk-modules) first. + +If the folder `$MODPATH/riru` exists, the module is considered as a Riru module. All files in `$MODPATH/riru/lib(64)` will be loaded by Riru. + +## API changes + +### API 26 (Riru v26) + +- Remove the support of pre-24 modules +- `/data/adb/dev_random` is planned to be moved to another place in the next major version +- Libraries in `/dev` do not have stacktrace, developers have to put so file into `/system`, Riru v26 makes this simpler + + Create an empty file, `libxxx` (no `.so` suffix), at `$MODPATH/riru/lib(64)`, Riru will try to load `/system/lib(64)/libxxx.so` + +### API 25 (Riru v25) + +- Modules can be unloaded (see `main.cpp`) +- `shouldSkipUid` is removed for API 25 modules + +### API 24 (Riru v24) + +- The Riru API version is unified with Riru version, now the API version is 24 +- The `/data/adb/riru/modules/` folder is deprecated, modules only need to place library files in `$MODPATH/riru/lib(64)` (see `customize.sh` `post-fs-data.sh`) +- The `init` function is called only once (see `main.cpp`) +- It's recommended to place modules files in the Magisk module folder, zygote has permission read this folder directly (the path is passed through `init` function, see `main.cpp`) + +### API 10 (Riru v23) + +
+ Background of rirud: + + Riru v22.0 move config files to `/data/adb`, this makes patch SELinux rules a must. However Magisk's `sepolicy.rule` actually not work for maybe lots of devices. As the release of Riru v22.0, these people "suddenly" appears. + + `sepolicy.rule` support was added from Magisk v20.2, a long time ago, no one report to Magisk 😒. + + To workaround this "problem", "rirud" is introduced. It will be started by `post-fs-data.sh` and run a socket runs under `u:r:zygote:s0` context. All file operations can be done through this socket. +
+ + +From Riru v23, "read file" and "read dir" function are added for "rirud". Modules can use this to read files that zygote itself has not permission to access. Note, for hide purpose, "rirud" socket is only available before system_server is started. + +In order to give the module enough freedom (like how to allocate memory), there is no "API". The module needs to implement socket codes by itself. + +
+ + Pseudocode of read file: + +``` +socket(PF_UNIX, SOCK_STREAM) +setup_sockaddr("rirud") + +write(ACTION_READ_FILE /* 4 */, sizeof(uint32)) +write(path_size, sizeof(uint32)) +write(path, path_size) + +errno = read(sizeof(int32_t)) // errno of "open" in "rirud" +if (errno != 0) return + +bytes_count = read(sizeof(int32_t)) + +if (bytes_count > 0) { + // file has size + // read total "bytes_count" bytes +} else if (bytes_count == 0) { + // file has no size, read until 0 + // read until 0 +} +``` + +
+ +
+ + Pseudocode of read dir: + +``` +socket(PF_UNIX, SOCK_STREAM) +setup_sockaddr("rirud") + +write(ACTION_READ_DIR /* 5 */, sizeof(uint32)) +write(path_size, sizeof(uint32)) +write(path, path_size) + +errno = read(sizeof(int32_t)) // errno of "opendir" in "rirud" +if (errno != 0) return + +while (true) { + write(1 /* continue */, sizeof(uint8)) + + reply = read(sizeof(int32)) + if (reply == -1) break // end + if (reply != 0) continue // reply is errno of "readdir" in "rirud" + + d_type = read(sizeof(uchar)) + d_name = read(256) +} +``` + +
+ +Example implementation: + +### API 9 (Riru v22) + +#### API + +Functions like `nativeForkAnd...` do not need to be exported directly. The only function to export is `void *init(void *)`. See the comment of `init` and template's implementation for more. + +This has these advantages: + +* Module can support different Riru versions +* Riru itself will not relay on ".prop" file (unreliable) to get module information + +#### Riru + +Starting v22.0, Riru has switched to "native bridge" (`ro.dalvik.vm.native.bridge`) to inject zygote, this will lead Riru and modules be loaded later ([`LoadNativeBridge`](https://cs.android.com/android/platform/superproject/+/android-11.0.0_r1:art/libnativebridge/native_bridge.cc;l=227) vs `__attribute__((constructor))`). + +For most modules, this should have no problem, but modules like Xposed frameworks may have to make changes. + +> Magisk may provider Riru-like features in the far future, and of course, it will have more strict restrictions, module codes will not be run in zygote. Maybe Xposed framework modules should prepare for this? + +Riru v22 also provides hide function to make the memory of the module to anonymous memory ([see the implementation](https://github.com/RikkaApps/Riru/blob/master/core/src/main/cpp/hide.cpp)). This is an opt-in behavior (`module->supportHide`) and Riru itself also has a global toggle (`/data/adb/riru/enable_hide`). + +#### Module installer + +`RIRU_PATH` has been changed to `/data/adb/riru` for hide purpose. If you have other files in `/data/misc/riru`, move them here (or anywhere else if you want). + +Note `/data/adb/riru` have the same SELinux like other Magisk files (set by Riru in post-fs-data), `u:object_r:magisk_file:s0`. DO NOT reset the context to something else. diff --git a/riru/build.gradle b/riru/build.gradle new file mode 100644 index 0000000..479bce8 --- /dev/null +++ b/riru/build.gradle @@ -0,0 +1,35 @@ +apply plugin: 'idea' + +idea.module { + excludeDirs += file('out') + resourceDirs += file('template') + resourceDirs += file('scripts') +} + +buildscript { + repositories { + mavenCentral() + google() + } + dependencies { + classpath 'com.android.tools.build:gradle:4.2.2' + } +} + +allprojects { + repositories { + mavenCentral() + google() + } +} + +ext { + minSdkVersion = 23 + targetSdkVersion = 30 + + outDir = file("$rootDir/out") +} + +task clean(type: Delete) { + delete rootProject.buildDir, outDir +} diff --git a/riru/gradle.properties b/riru/gradle.properties new file mode 100644 index 0000000..7322978 --- /dev/null +++ b/riru/gradle.properties @@ -0,0 +1,22 @@ +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx1536m +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app's APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true +# Automatically convert third-party libraries to use AndroidX +android.enableJetifier=true +# https://github.com/google/prefab/issues/122 +# Remove this until AGP update prefab version +android.prefabVersion=1.1.3 diff --git a/riru/gradle/wrapper/gradle-wrapper.jar b/riru/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..f6b961f Binary files /dev/null and b/riru/gradle/wrapper/gradle-wrapper.jar differ diff --git a/riru/gradle/wrapper/gradle-wrapper.properties b/riru/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..de39001 --- /dev/null +++ b/riru/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon Jul 12 21:05:17 CST 2021 +distributionBase=GRADLE_USER_HOME +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/riru/gradlew b/riru/gradlew new file mode 100755 index 0000000..cccdd3d --- /dev/null +++ b/riru/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/riru/gradlew.bat b/riru/gradlew.bat new file mode 100644 index 0000000..f955316 --- /dev/null +++ b/riru/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/riru/module.example.gradle b/riru/module.example.gradle new file mode 100644 index 0000000..6c06e3b --- /dev/null +++ b/riru/module.example.gradle @@ -0,0 +1,30 @@ +ext { + /* + This name will be used in the name of the so file ("lib${moduleLibraryName}.so"). + */ + moduleLibraryName = "template" + + /* 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" + + /* Maximum supported Riru API version, used in the version check of riru.sh */ + moduleRiruApiVersion = 26 + + /* + Magisk module ID + Since Magisk use it to distinguish different modules, you should never change it. + + Note, the older version of the template uses '-' instead of '_', if your are upgrading from + the older version, please pay attention. + */ + magiskModuleId = "riru_template" + + moduleName = "Template" + moduleAuthor = "Template" + moduleDescription = "Riru module template. Requires Riru $moduleMinRiruVersionName or above." + moduleVersion = "v26.0.0" + moduleVersionCode = 26 +} diff --git a/riru/module/.gitignore b/riru/module/.gitignore new file mode 100644 index 0000000..9833d4b --- /dev/null +++ b/riru/module/.gitignore @@ -0,0 +1,3 @@ +/.externalNativeBuild +/build +/release \ No newline at end of file diff --git a/riru/module/build.gradle b/riru/module/build.gradle new file mode 100644 index 0000000..89588c6 --- /dev/null +++ b/riru/module/build.gradle @@ -0,0 +1,136 @@ +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')) + +android { + compileSdkVersion rootProject.ext.targetSdkVersion + defaultConfig { + minSdkVersion rootProject.ext.minSdkVersion + targetSdkVersion rootProject.ext.targetSdkVersion + externalNativeBuild { + cmake { + arguments "-DMODULE_NAME:STRING=$moduleLibraryName", + "-DRIRU_MODULE_API_VERSION=$moduleRiruApiVersion", + "-DRIRU_MODULE_VERSION=$moduleVersionCode", + "-DRIRU_MODULE_VERSION_NAME:STRING=$moduleVersion", + "-DRIRU_MODULE_MIN_API_VERSION=$moduleMinRiruApiVersion" + } + } + } + buildFeatures { + prefab true + } + externalNativeBuild { + cmake { + path "src/main/cpp/CMakeLists.txt" + version "3.10.2" + } + } +} + +repositories { + mavenLocal() +} + +dependencies { + // This is prefab aar which contains "riru.h" + // If you want to use older versions of AGP, + // 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" in your gradle.properties. + // See https://github.com/google/prefab/issues/122 + + implementation 'dev.rikka.ndk:riru:26.0.0' +} + + +afterEvaluate { + android.libraryVariants.forEach { variant -> + def variantCapped = variant.name.capitalize() + def variantLowered = variant.name.toLowerCase() + + def zipName = "${magiskModuleId.replace('_', '-')}-${moduleVersion}-${variantLowered}.zip" + def magiskDir = file("$outDir/magisk_module_$variantLowered") + + task("prepareMagiskFiles${variantCapped}", type: Sync) { + dependsOn("assemble$variantCapped") + + def templatePath = "$rootDir/template/magisk_module" + + 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() + } + } + } + + task("zip${variantCapped}", type: Zip) { + dependsOn("prepareMagiskFiles${variantCapped}") + from magiskDir + archiveName zipName + destinationDir outDir + } + + 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}" + } + + task("flashAndReboot${variantCapped}", type: Exec) { + dependsOn("flash${variantCapped}") + commandLine android.adbExecutable, "shell", "reboot" + } + + variant.assembleProvider.get().finalizedBy("zip${variantCapped}") + } +} diff --git a/riru/module/src/main/AndroidManifest.xml b/riru/module/src/main/AndroidManifest.xml new file mode 100644 index 0000000..235c657 --- /dev/null +++ b/riru/module/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/riru/module/src/main/cpp/CMakeLists.txt b/riru/module/src/main/cpp/CMakeLists.txt new file mode 100644 index 0000000..4606e89 --- /dev/null +++ b/riru/module/src/main/cpp/CMakeLists.txt @@ -0,0 +1,44 @@ +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 () + +add_definitions(-DRIRU_MODULE) + +configure_file(template/config.cpp config.cpp) + +message("Build type: ${CMAKE_BUILD_TYPE}") + +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 (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 -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} ${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) + +include_directories(include) + +add_library(${MODULE_NAME} SHARED main.cpp ${CMAKE_CURRENT_BINARY_DIR}/config.cpp) +target_link_libraries(${MODULE_NAME} log riru::riru) + +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/riru/module/src/main/cpp/include/config.h b/riru/module/src/main/cpp/include/config.h new file mode 100644 index 0000000..6203e3d --- /dev/null +++ b/riru/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/riru/module/src/main/cpp/main.cpp b/riru/module/src/main/cpp/main.cpp new file mode 100644 index 0000000..1368034 --- /dev/null +++ b/riru/module/src/main/cpp/main.cpp @@ -0,0 +1,115 @@ +#include +#include +#include +#include +#include +#include + +static void forkAndSpecializePre( + 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) { + // 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 +} + +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 + + // 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); + } else { + // In zygote process + } +} + +static void specializeAppProcessPre( + 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) { + // 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) { + // 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 + } else { + // In zygote process + } +} + +static void onModuleLoaded() { + // 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; +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; +} +} diff --git a/riru/module/src/main/cpp/template/config.cpp b/riru/module/src/main/cpp/template/config.cpp new file mode 100644 index 0000000..36e2f46 --- /dev/null +++ b/riru/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/riru/settings.gradle b/riru/settings.gradle new file mode 100644 index 0000000..a843339 --- /dev/null +++ b/riru/settings.gradle @@ -0,0 +1,5 @@ +include ':module' + +import org.apache.tools.ant.DirectoryScanner + +DirectoryScanner.removeDefaultExclude('**/.gitattributes') diff --git a/riru/template/magisk_module/.gitattributes b/riru/template/magisk_module/.gitattributes new file mode 100644 index 0000000..11e33e9 --- /dev/null +++ b/riru/template/magisk_module/.gitattributes @@ -0,0 +1,10 @@ +# Declare files that will always have LF line endings on checkout. +META-INF/** text eol=lf +*.prop text eol=lf +*.sh text eol=lf +*.md text eol=lf +sepolicy.rule text eol=lf + +# Denote all files that are truly binary and should not be modified. +system/** binary +system_x86/** binary \ No newline at end of file diff --git a/riru/template/magisk_module/META-INF/com/google/android/update-binary b/riru/template/magisk_module/META-INF/com/google/android/update-binary new file mode 100644 index 0000000..28b48e5 --- /dev/null +++ b/riru/template/magisk_module/META-INF/com/google/android/update-binary @@ -0,0 +1,33 @@ +#!/sbin/sh + +################# +# Initialization +################# + +umask 022 + +# echo before loading util_functions +ui_print() { echo "$1"; } + +require_new_magisk() { + ui_print "*******************************" + ui_print " Please install Magisk v20.4+! " + ui_print "*******************************" + exit 1 +} + +######################### +# Load util_functions.sh +######################### + +OUTFD=$2 +ZIPFILE=$3 + +mount /data 2>/dev/null + +[ -f /data/adb/magisk/util_functions.sh ] || require_new_magisk +. /data/adb/magisk/util_functions.sh +[ $MAGISK_VER_CODE -lt 20400 ] && require_new_magisk + +install_module +exit 0 diff --git a/riru/template/magisk_module/META-INF/com/google/android/updater-script b/riru/template/magisk_module/META-INF/com/google/android/updater-script new file mode 100644 index 0000000..11d5c96 --- /dev/null +++ b/riru/template/magisk_module/META-INF/com/google/android/updater-script @@ -0,0 +1 @@ +#MAGISK diff --git a/riru/template/magisk_module/README.md b/riru/template/magisk_module/README.md new file mode 100644 index 0000000..c316e8b --- /dev/null +++ b/riru/template/magisk_module/README.md @@ -0,0 +1 @@ +# Riru - Template \ No newline at end of file diff --git a/riru/template/magisk_module/customize.sh b/riru/template/magisk_module/customize.sh new file mode 100644 index 0000000..11f86b9 --- /dev/null +++ b/riru/template/magisk_module/customize.sh @@ -0,0 +1,70 @@ +SKIPUNZIP=1 + +# Extract verify.sh +ui_print "- Extracting verify.sh" +unzip -o "$ZIPFILE" 'verify.sh' -d "$TMPDIR" >&2 +if [ ! -f "$TMPDIR/verify.sh" ]; then + ui_print "*********************************************************" + ui_print "! Unable to extract verify.sh!" + ui_print "! This zip may be corrupted, please try downloading again" + abort "*********************************************************" +fi +. $TMPDIR/verify.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 + +# 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" 'uninstall.sh' "$MODPATH" + +# 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 + +mkdir "$MODPATH/riru" +mkdir "$MODPATH/riru/lib" +mkdir "$MODPATH/riru/lib64" + +if [ "$ARCH" = "arm" ] || [ "$ARCH" = "arm64" ]; then + ui_print "- Extracting arm libraries" + 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" "lib/arm64-v8a/lib$RIRU_MODULE_LIB_NAME.so" "$MODPATH/riru/lib64" true + fi +fi + +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 + + 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 + +set_perm_recursive "$MODPATH" 0 0 0755 0644 diff --git a/riru/template/magisk_module/module.prop b/riru/template/magisk_module/module.prop new file mode 100644 index 0000000..236bd20 --- /dev/null +++ b/riru/template/magisk_module/module.prop @@ -0,0 +1,6 @@ +id=${id} +name=${name} +version=${version} +versionCode=${versionCode} +author=${author} +description=${description} diff --git a/riru/template/magisk_module/riru.sh b/riru/template/magisk_module/riru.sh new file mode 100644 index 0000000..c3152c5 --- /dev/null +++ b/riru/template/magisk_module/riru.sh @@ -0,0 +1,44 @@ +#!/sbin/sh +RIRU_MODULE_LIB_NAME="@RIRU_MODULE_LIB_NAME@" + +# Variables for customize.sh +RIRU_API=0 +RIRU_MIN_COMPATIBLE_API=0 +RIRU_VERSION_CODE=0 +RIRU_VERSION_NAME="" + +# 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 [ "$MAGISK_VER_CODE" -ge 21000 ]; then + MAGISK_CURRENT_RIRU_MODULE_PATH=$(magisk --path)/.magisk/modules/riru-core +else + 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/riru/template/magisk_module/uninstall.sh b/riru/template/magisk_module/uninstall.sh new file mode 100644 index 0000000..3c86bf3 --- /dev/null +++ b/riru/template/magisk_module/uninstall.sh @@ -0,0 +1,2 @@ +#!/sbin/sh +MODDIR=${0%/*} diff --git a/riru/template/magisk_module/verify.sh b/riru/template/magisk_module/verify.sh new file mode 100644 index 0000000..fc706b6 --- /dev/null +++ b/riru/template/magisk_module/verify.sh @@ -0,0 +1,39 @@ +TMPDIR_FOR_VERIFY="$TMPDIR/.vunzip" +mkdir "$TMPDIR_FOR_VERIFY" + +abort_verify() { + ui_print "*********************************************************" + ui_print "! $1" + ui_print "! This zip may be corrupted, please try downloading again" + abort "*********************************************************" +} + +# extract +extract() { + zip=$1 + file=$2 + dir=$3 + junk_paths=$4 + [ -z "$junk_paths" ] && junk_paths=false + opts="-o" + [ $junk_paths = true ] && opts="-oj" + + file_path="" + hash_path="" + if [ $junk_paths = true ]; then + file_path="$dir/$(basename "$file")" + hash_path="$TMPDIR_FOR_VERIFY/$(basename "$file").sha256sum" + else + file_path="$dir/$file" + hash_path="$TMPDIR_FOR_VERIFY/$file.sha256sum" + fi + + unzip $opts "$zip" "$file" -d "$dir" >&2 + [ -f "$file_path" ] || abort_verify "$file not exists" + + unzip $opts "$zip" "$file.sha256sum" -d "$TMPDIR_FOR_VERIFY" >&2 + [ -f "$hash_path" ] || abort_verify "$file.sha256sum not exists" + + (echo "$(cat "$hash_path") $file_path" | sha256sum -c -s -) || abort_verify "Failed to verify $file" + ui_print "- Verified $file" >&1 +}