├── demo
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ └── themes.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── values-night
│ │ │ │ └── themes.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ ├── layout
│ │ │ │ └── activity_main.xml
│ │ │ └── drawable
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── me
│ │ │ └── fycz
│ │ │ └── demo
│ │ │ └── MainActivity.kt
│ ├── test
│ │ └── java
│ │ │ └── me
│ │ │ └── fycz
│ │ │ └── maple
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── me
│ │ └── fycz
│ │ └── maple
│ │ └── ExampleInstrumentedTest.java
├── proguard-rules.pro
└── build.gradle
├── maple
├── .gitignore
├── consumer-rules.pro
├── src
│ ├── main
│ │ ├── AndroidManifest.xml
│ │ ├── jni
│ │ │ ├── CMakeLists.txt
│ │ │ ├── logging.h
│ │ │ ├── maple.cpp
│ │ │ ├── elf_util.h
│ │ │ └── elf_util.cpp
│ │ └── java
│ │ │ ├── org
│ │ │ └── apache
│ │ │ │ └── commons
│ │ │ │ └── lang3
│ │ │ │ └── reflect
│ │ │ │ └── MemberUtilsX.java
│ │ │ └── me
│ │ │ └── fycz
│ │ │ └── maple
│ │ │ ├── MethodHook.java
│ │ │ ├── MethodReplacement.java
│ │ │ ├── MapleBridge.java
│ │ │ └── MapleUtils.java
│ ├── test
│ │ └── java
│ │ │ └── me
│ │ │ └── fycz
│ │ │ └── maple
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── me
│ │ └── fycz
│ │ └── maple
│ │ └── ExampleInstrumentedTest.java
├── proguard-rules.pro
└── build.gradle
├── .idea
├── .gitignore
├── compiler.xml
├── vcs.xml
├── misc.xml
└── gradle.xml
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── settings.gradle
├── gradle.properties
├── README.md
├── gradlew.bat
├── gradlew
└── LICENSE
/demo/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/maple/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/maple/consumer-rules.pro:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/demo/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Maple
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fengyuecanzhu/Maple/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fengyuecanzhu/Maple/HEAD/demo/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fengyuecanzhu/Maple/HEAD/demo/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fengyuecanzhu/Maple/HEAD/demo/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fengyuecanzhu/Maple/HEAD/demo/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fengyuecanzhu/Maple/HEAD/demo/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fengyuecanzhu/Maple/HEAD/demo/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fengyuecanzhu/Maple/HEAD/demo/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fengyuecanzhu/Maple/HEAD/demo/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fengyuecanzhu/Maple/HEAD/demo/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fengyuecanzhu/Maple/HEAD/demo/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/maple/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Mar 28 12:43:35 CST 2022
2 | distributionBase=GRADLE_USER_HOME
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
4 | distributionPath=wrapper/dists
5 | zipStorePath=wrapper/dists
6 | zipStoreBase=GRADLE_USER_HOME
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 | local.properties
16 | /demo/release/
17 |
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/maple/src/main/jni/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 3.18.1)
2 | project("Maple")
3 |
4 | set(CMAKE_CXX_STANDARD 20)
5 | set(CMAKE_CXX_STANDARD_REQUIRED ON)
6 |
7 | add_library(maple SHARED maple.cpp elf_util.cpp)
8 | find_package(dobby REQUIRED CONFIG)
9 | find_package(lsplant REQUIRED CONFIG)
10 | target_link_libraries(maple log dobby::dobby lsplant::lsplant)
11 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | gradlePluginPortal()
4 | google()
5 | mavenCentral()
6 | }
7 | }
8 | dependencyResolutionManagement {
9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
10 | repositories {
11 | google()
12 | mavenCentral()
13 | }
14 | }
15 | rootProject.name = "Maple"
16 | include ':demo'
17 | include ':maple'
18 |
--------------------------------------------------------------------------------
/demo/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
--------------------------------------------------------------------------------
/demo/src/test/java/me/fycz/maple/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package me.fycz.maple;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/maple/src/test/java/me/fycz/maple/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package me.fycz.maple;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/maple/src/main/java/org/apache/commons/lang3/reflect/MemberUtilsX.java:
--------------------------------------------------------------------------------
1 | package org.apache.commons.lang3.reflect;
2 |
3 | import java.lang.reflect.Constructor;
4 | import java.lang.reflect.Method;
5 |
6 | /**
7 | * @author fengyue
8 | * @date 2022/3/28 16:16
9 | */
10 | public class MemberUtilsX {
11 | public static int compareConstructorFit(final Constructor> left, final Constructor> right, final Class>[] actual) {
12 | return MemberUtils.compareConstructorFit(left, right, actual);
13 | }
14 |
15 | public static int compareMethodFit(final Method left, final Method right, final Class>[] actual) {
16 | return MemberUtils.compareMethodFit(left, right, actual);
17 | }
18 | }
--------------------------------------------------------------------------------
/demo/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/maple/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
20 |
21 |
--------------------------------------------------------------------------------
/demo/src/androidTest/java/me/fycz/maple/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package me.fycz.maple;
2 |
3 | import android.content.Context;
4 |
5 | import androidx.test.platform.app.InstrumentationRegistry;
6 | import androidx.test.ext.junit.runners.AndroidJUnit4;
7 |
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 |
11 | import static org.junit.Assert.*;
12 |
13 | /**
14 | * Instrumented test, which will execute on an Android device.
15 | *
16 | * @see Testing documentation
17 | */
18 | @RunWith(AndroidJUnit4.class)
19 | public class ExampleInstrumentedTest {
20 | @Test
21 | public void useAppContext() {
22 | // Context of the app under test.
23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
24 | assertEquals("me.fycz.maple", appContext.getPackageName());
25 | }
26 | }
--------------------------------------------------------------------------------
/demo/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
--------------------------------------------------------------------------------
/maple/src/androidTest/java/me/fycz/maple/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package me.fycz.maple;
2 |
3 | import android.content.Context;
4 |
5 | import androidx.test.platform.app.InstrumentationRegistry;
6 | import androidx.test.ext.junit.runners.AndroidJUnit4;
7 |
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 |
11 | import static org.junit.Assert.*;
12 |
13 | /**
14 | * Instrumented test, which will execute on an Android device.
15 | *
16 | * @see Testing documentation
17 | */
18 | @RunWith(AndroidJUnit4.class)
19 | public class ExampleInstrumentedTest {
20 | @Test
21 | public void useAppContext() {
22 | // Context of the app under test.
23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
24 | assertEquals("me.fycz.maple.test", appContext.getPackageName());
25 | }
26 | }
--------------------------------------------------------------------------------
/demo/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
13 |
14 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/demo/src/main/res/values-night/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
--------------------------------------------------------------------------------
/maple/src/main/jni/logging.h:
--------------------------------------------------------------------------------
1 | #ifndef _LOGGING_H
2 | #define _LOGGING_H
3 |
4 | #include
5 |
6 | #ifndef LOG_TAG
7 | #define LOG_TAG "Maple"
8 | #endif
9 |
10 | #ifdef LOG_DISABLED
11 | #define LOGD(...)
12 | #define LOGV(...)
13 | #define LOGI(...)
14 | #define LOGW(...)
15 | #define LOGE(...)
16 | #else
17 | #ifndef NDEBUG
18 | #define LOGD(fmt, ...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, "%s:%d#%s" ": " fmt, __FILE_NAME__, __LINE__, __PRETTY_FUNCTION__ __VA_OPT__(,) __VA_ARGS__)
19 | #define LOGV(fmt, ...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, "%s:%d#%s" ": " fmt, __FILE_NAME__, __LINE__, __PRETTY_FUNCTION__ __VA_OPT__(,) __VA_ARGS__)
20 | #else
21 | #define LOGD(...)
22 | #define LOGV(...)
23 | #endif
24 | #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
25 | #define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
26 | #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
27 | #define LOGF(...) __android_log_print(ANDROID_LOG_FATAL, LOG_TAG, __VA_ARGS__)
28 | #define PLOGE(fmt, args...) LOGE(fmt " failed with %d: %s", ##args, errno, strerror(errno))
29 | #endif
30 |
31 | #endif // _LOGGING_H
32 |
--------------------------------------------------------------------------------
/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 | # Enables namespacing of each library's R class so that its R class includes only the
19 | # resources declared in the library itself and none from the library's dependencies,
20 | # thereby reducing the size of the R class for that library
21 | android.nonTransitiveRClass=true
--------------------------------------------------------------------------------
/maple/src/main/java/me/fycz/maple/MethodHook.java:
--------------------------------------------------------------------------------
1 | package me.fycz.maple;
2 |
3 |
4 | /**
5 | * @author fengyue
6 | * @date 2022/3/28 15:08
7 | */
8 | public abstract class MethodHook {
9 | /**
10 | * Called before the invocation of the method.
11 | *
12 | *
You can use {@link MapleBridge.MethodHookParam#setResult} and {@link MapleBridge.MethodHookParam#setThrowable}
13 | * to prevent the original method from being called.
14 | *
15 | *
Note that implementations shouldn't call {@code super(param)}, it's not necessary.
16 | *
17 | * @param param Information about the method call.
18 | * @throws Throwable Everything the callback throws is caught and logged.
19 | */
20 | protected void beforeHookedMethod(MapleBridge.MethodHookParam param) throws Throwable {
21 | }
22 |
23 | /**
24 | * Called after the invocation of the method.
25 | *
26 | *
You can use {@link MapleBridge.MethodHookParam#setResult} and {@link MapleBridge.MethodHookParam#setThrowable}
27 | * to modify the return value of the original method.
28 | *
29 | *
Note that implementations shouldn't call {@code super(param)}, it's not necessary.
30 | *
31 | * @param param Information about the method call.
32 | * @throws Throwable Everything the callback throws is caught and logged.
33 | */
34 | protected void afterHookedMethod(MapleBridge.MethodHookParam param) throws Throwable {
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/demo/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | id 'kotlin-android'
4 | }
5 |
6 | android {
7 | compileSdk 32
8 |
9 | defaultConfig {
10 | applicationId "me.fycz.maple"
11 | minSdk 21
12 | targetSdk 32
13 | versionCode 1
14 | versionName "1.0"
15 |
16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
17 | multiDexEnabled true
18 |
19 | ndk {
20 | abiFilters 'x86', 'x86_64','armeabi-v7a','arm64-v8a'
21 | }
22 | }
23 |
24 | buildFeatures {
25 | viewBinding true
26 | }
27 |
28 | buildTypes {
29 | release {
30 | minifyEnabled false
31 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
32 | }
33 | }
34 | compileOptions {
35 | sourceCompatibility JavaVersion.VERSION_11
36 | targetCompatibility JavaVersion.VERSION_11
37 | }
38 | }
39 |
40 | dependencies {
41 | implementation 'androidx.appcompat:appcompat:1.4.1'
42 | implementation 'com.google.android.material:material:1.5.0'
43 | testImplementation 'junit:junit:4.13.2'
44 | androidTestImplementation 'androidx.test.ext:junit:1.1.3'
45 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
46 | implementation "androidx.core:core-ktx:+"
47 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
48 | implementation(project(":maple"))
49 | }
--------------------------------------------------------------------------------
/demo/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Maple
2 |
3 | A Java hook framwork (Xposed style) for Android Runtime (ART) implemented by [LSPlant](https://github.com/LSPosed/LSPlant).
4 |
5 | ## Features
6 |
7 | * Support Android 5.0 - 13 (API level 21 - 33)
8 | * Support armeabi-v7a, arm64-v8a, x86, x86-64
9 | * Xposed style hook api
10 |
11 | ## Usage
12 |
13 | #### 1、Before usage
14 |
15 | Import method:
16 |
17 | Add the maven repository in your build.gradle(Project) (new version Android Studio please in settings.gradle):
18 |
19 | ```groovy
20 | allprojects {
21 | repositories {
22 | mavenCentral()
23 | }
24 | }
25 | ```
26 |
27 | Then import the framework in your build.gradle(app):
28 |
29 | ```groovy
30 | dependencies {
31 | implementation "me.fycz.maple:maple:2.1"
32 | }
33 | ```
34 |
35 | #### 2、Usage in codes
36 |
37 | All APIs are xposed style, you can use as simple as using xposed.
38 |
39 | kotlin:
40 |
41 | ```kotlin
42 | MapleUtils.findAndHookMethod(
43 | Activity::class.java,
44 | "onCreate",
45 | Bundle::class.java,
46 | object : MethodHook() {
47 | override fun beforeHookedMethod(param: MapleBridge.MethodHookParam) {
48 | //TODO: Hook before the method onCreate in the Activity is called.
49 | }
50 | }
51 | )
52 | ```
53 |
54 | java:
55 |
56 | ```java
57 | MapleUtils.findAndHookMethod(
58 | Activity.class,
59 | "onCreate",
60 | Bundle.class,
61 | new MethodHook() {
62 | @Override
63 | public void afterHookedMethod(MapleBridge.MethodHookParam param) throws Throwable {
64 | //TODO: Hook after the method onCreate in the Activity is called.
65 | }
66 | }
67 | );
68 | ```
69 |
70 | ## Credits
71 |
72 | Inspired by the following frameworks:
73 |
74 | - [LSPlant](https://github.com/LSPosed/LSPlant)
75 | - [Dobby](https://github.com/LSPosed/Dobby)
76 | - [Pine](https://github.com/canyie/Pine)
77 | - [XposedBridge](https://github.com/rovo89/XposedBridge)
78 |
79 |
--------------------------------------------------------------------------------
/demo/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
11 |
12 |
17 |
18 |
24 |
25 |
31 |
32 |
38 |
39 |
45 |
46 |
52 |
53 |
54 |
--------------------------------------------------------------------------------
/maple/src/main/java/me/fycz/maple/MethodReplacement.java:
--------------------------------------------------------------------------------
1 | package me.fycz.maple;
2 |
3 |
4 | /**
5 | * A special case of {@link MethodHook} which completely replaces the original method.
6 | */
7 | public abstract class MethodReplacement extends MethodHook {
8 |
9 | /**
10 | * @hide
11 | */
12 | @Override
13 | protected final void beforeHookedMethod(MapleBridge.MethodHookParam param) throws Throwable {
14 | try {
15 | Object result = replaceHookedMethod(param);
16 | param.setResult(result);
17 | } catch (Throwable t) {
18 | MapleUtils.log(t);
19 | param.setThrowable(t);
20 | }
21 | }
22 |
23 | /**
24 | * @hide
25 | */
26 | @Override
27 | @SuppressWarnings("EmptyMethod")
28 | protected final void afterHookedMethod(MapleBridge.MethodHookParam param) throws Throwable {
29 | }
30 |
31 | /**
32 | * Shortcut for replacing a method completely. Whatever is returned/thrown here is taken
33 | * instead of the result of the original method (which will not be called).
34 | *
35 | *
Note that implementations shouldn't call {@code super(param)}, it's not necessary.
36 | *
37 | * @param param Information about the method call.
38 | * @throws Throwable Anything that is thrown by the callback will be passed on to the original caller.
39 | */
40 | @SuppressWarnings("UnusedParameters")
41 | protected abstract Object replaceHookedMethod(MapleBridge.MethodHookParam param) throws Throwable;
42 |
43 | /**
44 | * Predefined callback that skips the method without replacements.
45 | */
46 | public static final MethodReplacement DO_NOTHING = new MethodReplacement() {
47 | @Override
48 | protected Object replaceHookedMethod(MapleBridge.MethodHookParam param) throws Throwable {
49 | return null;
50 | }
51 | };
52 |
53 | /**
54 | * Creates a callback which always returns a specific value.
55 | *
56 | * @param result The value that should be returned to callers of the hooked method.
57 | */
58 | public static MethodReplacement returnConstant(final Object result) {
59 | return new MethodReplacement() {
60 | @Override
61 | protected Object replaceHookedMethod(MapleBridge.MethodHookParam param) throws Throwable {
62 | return result;
63 | }
64 | };
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/maple/src/main/jni/maple.cpp:
--------------------------------------------------------------------------------
1 | //
2 | // Created by fengyue on 2022/3/28.
3 | //
4 |
5 | #include
6 | #include
7 | #include
8 | #include "elf_util.h"
9 | #include "logging.h"
10 |
11 | #define _uintval(p) reinterpret_cast(p)
12 | #define _ptr(p) reinterpret_cast(p)
13 | #define _align_up(x, n) (((x) + ((n) - 1)) & ~((n) - 1))
14 | #define _align_down(x, n) ((x) & -(n))
15 | #define _page_size 4096
16 | #define _page_align(n) _align_up(static_cast(n), _page_size)
17 | #define _ptr_align(x) _ptr(_align_down(reinterpret_cast(x), _page_size))
18 | #define _make_rwx(p, n) ::mprotect(_ptr_align(p), \
19 | _page_align(_uintval(p) + n) != _page_align(_uintval(p)) ? _page_align(n) + _page_size : _page_align(n), \
20 | PROT_READ | PROT_WRITE | PROT_EXEC)
21 |
22 | bool init_result;
23 |
24 | void *InlineHooker(void *target, void *hooker) {
25 | _make_rwx(target, _page_size);
26 | void *origin_call;
27 | if (DobbyHook(target, hooker, &origin_call) == RS_SUCCESS) {
28 | return origin_call;
29 | } else {
30 | return nullptr;
31 | }
32 | }
33 |
34 | bool InlineUnhooker(void *func) {
35 | return DobbyDestroy(func) == RT_SUCCESS;
36 | }
37 |
38 | extern "C"
39 | JNIEXPORT jboolean JNICALL
40 | Java_me_fycz_maple_MapleBridge_hasInitHook(JNIEnv *, jclass) {
41 | return init_result;
42 | }
43 |
44 | extern "C"
45 | JNIEXPORT jobject JNICALL
46 | Java_me_fycz_maple_MapleBridge_doHook(JNIEnv *env, jobject thiz, jobject original,
47 | jobject callback) {
48 | return lsplant::Hook(env, original, thiz, callback);
49 | }
50 |
51 | extern "C"
52 | JNIEXPORT jboolean JNICALL
53 | Java_me_fycz_maple_MapleBridge_doUnhook(JNIEnv *env, jclass, jobject target) {
54 | return lsplant::UnHook(env, target);
55 | }
56 |
57 | extern "C"
58 | JNIEXPORT jboolean JNICALL
59 | Java_me_fycz_maple_MapleBridge_isHooked(JNIEnv *env, jclass, jobject method) {
60 | return lsplant::IsHooked(env, method);
61 | }
62 |
63 | extern "C"
64 | JNIEXPORT jboolean JNICALL
65 | Java_me_fycz_maple_MapleBridge_makeClassInheritable(JNIEnv *env, jclass, jclass clazz) {
66 | return lsplant::MakeClassInheritable(env, clazz);
67 | }
68 |
69 | JNIEXPORT jint JNICALL
70 | JNI_OnLoad(JavaVM *vm, void *reserved) {
71 | JNIEnv *env;
72 | if (vm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) {
73 | return JNI_ERR;
74 | }
75 | SandHook::ElfImg art("libart.so");
76 | lsplant::InitInfo initInfo{
77 | .inline_hooker = InlineHooker,
78 | .inline_unhooker = InlineUnhooker,
79 | .art_symbol_resolver = [&art](std::string_view symbol) -> void * {
80 | auto *out = reinterpret_cast(art.getSymbAddress(symbol));
81 | return out;
82 | }
83 | };
84 | init_result = lsplant::Init(env, initInfo);
85 | return JNI_VERSION_1_6;
86 | }
87 |
--------------------------------------------------------------------------------
/maple/src/main/jni/elf_util.h:
--------------------------------------------------------------------------------
1 | #ifndef SANDHOOK_ELF_UTIL_H
2 | #define SANDHOOK_ELF_UTIL_H
3 |
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 | #include
10 |
11 | #define SHT_GNU_HASH 0x6ffffff6
12 |
13 | namespace SandHook {
14 | class ElfImg {
15 | public:
16 |
17 | ElfImg(std::string_view elf);
18 |
19 | constexpr ElfW(Addr) getSymbOffset(std::string_view name) const {
20 | return getSymbOffset(name, GnuHash(name), ElfHash(name));
21 | }
22 |
23 | constexpr ElfW(Addr) getSymbAddress(std::string_view name) const {
24 | ElfW(Addr) offset = getSymbOffset(name);
25 | if (offset > 0 && base != nullptr) {
26 | return static_cast((uintptr_t) base + offset - bias);
27 | } else {
28 | return 0;
29 | }
30 | }
31 |
32 | template
33 | requires(std::is_pointer_v)
34 | constexpr T getSymbAddress(std::string_view name) const {
35 | return reinterpret_cast(getSymbAddress(name));
36 | }
37 |
38 | bool isValid() const {
39 | return base != nullptr;
40 | }
41 |
42 | const std::string name() const {
43 | return elf;
44 | }
45 |
46 | ~ElfImg();
47 |
48 | private:
49 | ElfW(Addr) getSymbOffset(std::string_view name, uint32_t gnu_hash, uint32_t elf_hash) const;
50 |
51 | ElfW(Addr) ElfLookup(std::string_view name, uint32_t hash) const;
52 |
53 | ElfW(Addr) GnuLookup(std::string_view name, uint32_t hash) const;
54 |
55 | ElfW(Addr) LinearLookup(std::string_view name) const;
56 |
57 | constexpr static uint32_t ElfHash(std::string_view name);
58 |
59 | constexpr static uint32_t GnuHash(std::string_view name);
60 |
61 | bool findModuleBase();
62 |
63 | std::string elf;
64 | void *base = nullptr;
65 | char *buffer = nullptr;
66 | off_t size = 0;
67 | off_t bias = -4396;
68 | ElfW(Ehdr) *header = nullptr;
69 | ElfW(Shdr) *section_header = nullptr;
70 | ElfW(Shdr) *symtab = nullptr;
71 | ElfW(Shdr) *strtab = nullptr;
72 | ElfW(Shdr) *dynsym = nullptr;
73 | ElfW(Sym) *symtab_start = nullptr;
74 | ElfW(Sym) *dynsym_start = nullptr;
75 | ElfW(Sym) *strtab_start = nullptr;
76 | ElfW(Off) symtab_count = 0;
77 | ElfW(Off) symstr_offset = 0;
78 | ElfW(Off) symstr_offset_for_symtab = 0;
79 | ElfW(Off) symtab_offset = 0;
80 | ElfW(Off) dynsym_offset = 0;
81 | ElfW(Off) symtab_size = 0;
82 |
83 | uint32_t nbucket_{};
84 | uint32_t *bucket_ = nullptr;
85 | uint32_t *chain_ = nullptr;
86 |
87 | uint32_t gnu_nbucket_{};
88 | uint32_t gnu_symndx_{};
89 | uint32_t gnu_bloom_size_;
90 | uint32_t gnu_shift2_;
91 | uintptr_t *gnu_bloom_filter_;
92 | uint32_t *gnu_bucket_;
93 | uint32_t *gnu_chain_;
94 |
95 | mutable std::unordered_map symtabs_;
96 | };
97 |
98 | constexpr uint32_t ElfImg::ElfHash(std::string_view name) {
99 | uint32_t h = 0, g = 0;
100 | for (unsigned char p: name) {
101 | h = (h << 4) + p;
102 | g = h & 0xf0000000;
103 | h ^= g;
104 | h ^= g >> 24;
105 | }
106 | return h;
107 | }
108 |
109 | constexpr uint32_t ElfImg::GnuHash(std::string_view name) {
110 | uint32_t h = 5381;
111 | for (unsigned char p: name) {
112 | h += (h << 5) + p;
113 | }
114 | return h;
115 | }
116 | }
117 |
118 | #endif //SANDHOOK_ELF_UTIL_H
119 |
--------------------------------------------------------------------------------
/maple/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id("com.android.library")
3 | id("maven-publish")
4 | id("signing")
5 | }
6 |
7 | android {
8 | compileSdk 32
9 | ndkVersion "23.1.7779620"
10 |
11 | defaultConfig {
12 | minSdk 21
13 | targetSdk 32
14 |
15 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
16 | consumerProguardFiles "consumer-rules.pro"
17 |
18 | ndk {
19 | abiFilters 'x86', 'x86_64','armeabi-v7a','arm64-v8a'
20 | }
21 | externalNativeBuild {
22 | cmake {
23 | arguments += "-DANDROID_STL=c++_shared"
24 | }
25 | }
26 | }
27 | externalNativeBuild {
28 | cmake {
29 | path = file("src/main/jni/CMakeLists.txt")
30 | version "3.18.1"
31 | }
32 | }
33 |
34 | buildFeatures {
35 | prefab true
36 | }
37 |
38 | buildTypes {
39 | release {
40 | minifyEnabled false
41 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
42 | }
43 | }
44 | compileOptions {
45 | sourceCompatibility JavaVersion.VERSION_11
46 | targetCompatibility JavaVersion.VERSION_11
47 | }
48 |
49 | publishing {
50 | singleVariant("release") {
51 | withSourcesJar()
52 | withJavadocJar()
53 | }
54 | }
55 | }
56 |
57 | task sourcesJar(type: Jar) {
58 | from android.sourceSets.main.java.srcDirs
59 | classifier = 'sources'
60 | }
61 |
62 |
63 | publishing {
64 | publications {
65 | maven(MavenPublication) {
66 | group = "me.fycz.maple"
67 | artifactId = "maple"
68 | version = "2.1"
69 | afterEvaluate {
70 | artifact bundleReleaseAar
71 | artifact sourcesJar
72 | }
73 | pom {
74 | name = "Maple"
75 | description = "A hook framework for Android Runtime (ART)"
76 | url = "https://github.com/fengyuecanzhu/Maple"
77 | licenses {
78 | license {
79 | name = "GNU Lesser General Public License v3.0"
80 | url = "https://github.com/fengyuecanzhu/Maple/blob/master/LICENSE"
81 | }
82 | }
83 | developers {
84 | developer {
85 | name = "fengyuecanzhu"
86 | url = "https://github.com/fengyuecanzhu"
87 | }
88 | }
89 | scm {
90 | connection = "scm:git:https://github.com/fengyuecanzhu/Maple.git"
91 | url = "https://github.com/fengyuecanzhu/Maple"
92 | }
93 | }
94 | }
95 | }
96 | repositories {
97 | maven {
98 | name = "OSSRH"
99 | if (project.version.toString().endsWith("-SNAPSHOT")) {
100 | url = "https://s01.oss.sonatype.org/content/repositories/snapshots"
101 | } else {
102 | url = "https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/"
103 | }
104 | credentials {
105 | username = findProperty("ossrhUsername") ?: System.getenv("OSSRH_USERNAME")
106 | password = findProperty("ossrhPassword") ?: System.getenv("OSSRH_PASSWORD")
107 | }
108 | }
109 | }
110 | }
111 |
112 | signing {
113 | def signingKey = findProperty("signingKey")
114 | def signingPassword = findProperty("signingPassword")
115 | def secretKeyRingFile = findProperty("signing.secretKeyRingFile")
116 |
117 | if (secretKeyRingFile != null && file(secretKeyRingFile).exists()) {
118 | sign publishing.publications
119 | } else if (signingKey != null) {
120 | useInMemoryPgpKeys(signingKey, signingPassword)
121 | sign publishing.publications
122 | }
123 | }
124 |
125 | dependencies {
126 | implementation("org.lsposed.lsplant:lsplant:5.2")
127 | implementation("io.github.vvb2060.ndk:dobby:1.2")
128 | compileOnly("androidx.annotation:annotation:1.3.0")
129 | implementation("org.apache.commons:commons-lang3:3.12.0")
130 | }
--------------------------------------------------------------------------------
/demo/src/main/java/me/fycz/demo/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package me.fycz.demo
2 |
3 | import android.annotation.SuppressLint
4 | import android.os.Bundle
5 | import android.view.View
6 | import android.widget.Button
7 | import android.widget.TextView
8 | import androidx.appcompat.app.AppCompatActivity
9 | import me.fycz.demo.databinding.ActivityMainBinding
10 | import me.fycz.maple.MapleBridge
11 | import me.fycz.maple.MapleUtils
12 | import me.fycz.maple.MethodHook
13 | import me.fycz.maple.MethodReplacement
14 |
15 | /**
16 | * @author fengyue
17 | * @date 2022/3/28 21:15
18 | */
19 | class MainActivity : AppCompatActivity() {
20 | private lateinit var binding: ActivityMainBinding
21 | private var bridge: MapleBridge? = null
22 |
23 | override fun onCreate(savedInstanceState: Bundle?) {
24 | super.onCreate(savedInstanceState)
25 | binding = ActivityMainBinding.inflate(layoutInflater)
26 | setContentView(binding.root)
27 | init()
28 | }
29 |
30 | private fun init() {
31 | binding.btTest.setOnClickListener {
32 | console(it)
33 | console(normal("1", 2, 3F))
34 | }
35 |
36 | binding.btHookBefore.setOnClickListener {
37 | console(it)
38 | try {
39 | bridge =
40 | MapleUtils.findAndHookMethod(
41 | "me.fycz.demo.MainActivity",
42 | this.classLoader,
43 | "normal",
44 | String::class.java,
45 | Int::class.java,
46 | Float::class.java,
47 | object : MethodHook() {
48 | override fun beforeHookedMethod(param: MapleBridge.MethodHookParam) {
49 | param.args[0] = "Hook函数Before-----" + param.args[0]
50 | }
51 | }
52 | )
53 | } catch (e: Exception) {
54 | console(e.stackTraceToString())
55 | }
56 | }
57 |
58 | binding.btHookAfter.setOnClickListener {
59 | console(it)
60 | try {
61 | bridge =
62 | MapleUtils.findAndHookMethod(
63 | "me.fycz.demo.MainActivity",
64 | this.classLoader,
65 | "normal",
66 | String::class.java,
67 | Int::class.java,
68 | Float::class.java,
69 | object : MethodHook() {
70 | override fun afterHookedMethod(param: MapleBridge.MethodHookParam) {
71 | console("Hook函数After-----" + param.args[0])
72 | }
73 | }
74 | )
75 | } catch (e: Exception) {
76 | console(e.stackTraceToString())
77 | }
78 | }
79 |
80 | binding.btHookReplace.setOnClickListener {
81 | console(it)
82 | try {
83 | bridge =
84 | MapleUtils.findAndHookMethod(
85 | "me.fycz.demo.MainActivity",
86 | this.classLoader,
87 | "normal",
88 | String::class.java,
89 | Int::class.java,
90 | Float::class.java,
91 | object : MethodReplacement() {
92 | override fun replaceHookedMethod(param: MapleBridge.MethodHookParam?): Any {
93 | return "Hook函数replace-----"
94 | }
95 | }
96 | )
97 | } catch (e: Exception) {
98 | console(e.stackTraceToString())
99 | }
100 | }
101 |
102 | binding.btUnhook.setOnClickListener {
103 | console(it)
104 | bridge?.unhook()
105 | bridge = null
106 | }
107 | }
108 |
109 | private fun normal(a: String, b: Int, c: Float): String {
110 | return a + b + c
111 | }
112 |
113 | private fun console(v: View) {
114 | if (v is Button)
115 | binding.tvConsole.myAppend(v.text.toString())
116 | }
117 |
118 | private fun console(s: String) {
119 | binding.tvConsole.myAppend(s)
120 | }
121 |
122 | @SuppressLint("SetTextI18n")
123 | fun TextView.myAppend(s: String) {
124 | text = text.toString() + "\n" + s
125 | }
126 | }
--------------------------------------------------------------------------------
/demo/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
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 |
--------------------------------------------------------------------------------
/maple/src/main/java/me/fycz/maple/MapleBridge.java:
--------------------------------------------------------------------------------
1 | package me.fycz.maple;
2 |
3 | import java.lang.reflect.InvocationTargetException;
4 | import java.lang.reflect.Member;
5 | import java.lang.reflect.Method;
6 | import java.lang.reflect.Modifier;
7 |
8 | /**
9 | * @author fengyue
10 | * @date 2022/3/28 14:52
11 | */
12 | public class MapleBridge {
13 |
14 | private Member target;
15 | private Method backup;
16 | public MethodHookParam param;
17 | private MethodHook callback;
18 |
19 | private MapleBridge() {
20 | }
21 |
22 | private native Method doHook(Member original, Method callback);
23 |
24 | public static native boolean doUnhook(Member target);
25 |
26 | public static native boolean hasInitHook();
27 |
28 | public static native boolean isHooked(Member method);
29 |
30 | public static native boolean makeClassInheritable(Class> clazz);
31 |
32 | public Object callback(Object[] args) throws Throwable {
33 | param = new MethodHookParam();
34 | param.method = backup;
35 | if (Modifier.isStatic(target.getModifiers())) {
36 | param.thisObject = null;
37 | param.args = args;
38 | } else {
39 | param.thisObject = args[0];
40 | param.args = new Object[args.length - 1];
41 | System.arraycopy(args, 1, param.args, 0, args.length - 1);
42 | }
43 | // call "before method" callbacks
44 | try {
45 | callback.beforeHookedMethod(param);
46 | } catch (Throwable t) {
47 | MapleUtils.log(t);
48 | // reset result (ignoring what the unexpectedly exiting callback did)
49 | param.setResult(null);
50 | param.returnEarly = false;
51 | }
52 | // call original method if not requested otherwise
53 | if (!param.returnEarly) {
54 | try {
55 | param.setResult(backup.invoke(param.thisObject, param.args));
56 | } catch (InvocationTargetException e) {
57 | param.setThrowable(e.getCause());
58 | }
59 | }
60 | // call "after method" callbacks
61 | Object lastResult = param.getResult();
62 | Throwable lastThrowable = param.getThrowable();
63 | try {
64 | callback.afterHookedMethod(param);
65 | } catch (Throwable t) {
66 | MapleUtils.log(t);
67 | // reset to last result (ignoring what the unexpectedly exiting callback did)
68 | if (lastThrowable == null)
69 | param.setResult(lastResult);
70 | else
71 | param.setThrowable(lastThrowable);
72 | }
73 | // return
74 | if (param.hasThrowable())
75 | throw param.getThrowable();
76 | else {
77 | var result = param.getResult();
78 | if (target instanceof Method) {
79 | var returnType = ((Method) target).getReturnType();
80 | if (!returnType.isPrimitive())
81 | return returnType.cast(result);
82 | }
83 | return result;
84 | }
85 | }
86 |
87 | public boolean unhook() {
88 | return doUnhook(target);
89 | }
90 |
91 | public static MapleBridge hookMethod(Member target, MethodHook callback) {
92 | if (!hasInitHook()) {
93 | throw new RuntimeException("Uninitialized the maple hook!");
94 | }
95 | if (isHooked(target)) {
96 | doUnhook(target);
97 | }
98 | MapleBridge bridge = new MapleBridge();
99 | try {
100 | var callbackMethod = MapleBridge.class.getDeclaredMethod("callback", Object[].class);
101 | var result = bridge.doHook(target, callbackMethod);
102 | if (result == null) return null;
103 | bridge.backup = result;
104 | bridge.target = target;
105 | bridge.callback = callback;
106 | } catch (Exception e) {
107 | e.printStackTrace();
108 | }
109 | return bridge;
110 | }
111 |
112 | /**
113 | * Wraps information about the method call and allows to influence it.
114 | */
115 | public static final class MethodHookParam {
116 |
117 | /**
118 | * The hooked method/constructor backup.
119 | */
120 | public Member method;
121 |
122 | /**
123 | * The {@code this} reference for an instance method, or {@code null} for static methods.
124 | */
125 | public Object thisObject;
126 |
127 | /**
128 | * Arguments to the method call.
129 | */
130 | public Object[] args;
131 |
132 | private Object result = null;
133 | private Throwable throwable = null;
134 | public boolean returnEarly = false;
135 |
136 | /**
137 | * Returns the result of the method call.
138 | */
139 | public Object getResult() {
140 | return result;
141 | }
142 |
143 | /**
144 | * Modify the result of the method call.
145 | *
146 | *
If called from {@link MethodHook#beforeHookedMethod}, it prevents the call to the original method.
147 | */
148 | public void setResult(Object result) {
149 | this.result = result;
150 | this.throwable = null;
151 | this.returnEarly = true;
152 | }
153 |
154 | /**
155 | * Returns the {@link Throwable} thrown by the method, or {@code null}.
156 | */
157 | public Throwable getThrowable() {
158 | return throwable;
159 | }
160 |
161 | /**
162 | * Returns true if an exception was thrown by the method.
163 | */
164 | public boolean hasThrowable() {
165 | return throwable != null;
166 | }
167 |
168 | /**
169 | * Modify the exception thrown of the method call.
170 | *
171 | *
If called from {@link MethodHook#beforeHookedMethod}, it prevents the call to the original method.
172 | */
173 | public void setThrowable(Throwable throwable) {
174 | this.throwable = throwable;
175 | this.result = null;
176 | this.returnEarly = true;
177 | }
178 |
179 | /**
180 | * Returns the result of the method call, or throws the Throwable caused by it.
181 | */
182 | public Object getResultOrThrowable() throws Throwable {
183 | if (throwable != null)
184 | throw throwable;
185 | return result;
186 | }
187 | }
188 | }
189 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU LESSER GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2022 fengyuecanzhu
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 |
9 | This version of the GNU Lesser General Public License incorporates
10 | the terms and conditions of version 3 of the GNU General Public
11 | License, supplemented by the additional permissions listed below.
12 |
13 | 0. Additional Definitions.
14 |
15 | As used herein, "this License" refers to version 3 of the GNU Lesser
16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU
17 | General Public License.
18 |
19 | "The Library" refers to a covered work governed by this License,
20 | other than an Application or a Combined Work as defined below.
21 |
22 | An "Application" is any work that makes use of an interface provided
23 | by the Library, but which is not otherwise based on the Library.
24 | Defining a subclass of a class defined by the Library is deemed a mode
25 | of using an interface provided by the Library.
26 |
27 | A "Combined Work" is a work produced by combining or linking an
28 | Application with the Library. The particular version of the Library
29 | with which the Combined Work was made is also called the "Linked
30 | Version".
31 |
32 | The "Minimal Corresponding Source" for a Combined Work means the
33 | Corresponding Source for the Combined Work, excluding any source code
34 | for portions of the Combined Work that, considered in isolation, are
35 | based on the Application, and not on the Linked Version.
36 |
37 | The "Corresponding Application Code" for a Combined Work means the
38 | object code and/or source code for the Application, including any data
39 | and utility programs needed for reproducing the Combined Work from the
40 | Application, but excluding the System Libraries of the Combined Work.
41 |
42 | 1. Exception to Section 3 of the GNU GPL.
43 |
44 | You may convey a covered work under sections 3 and 4 of this License
45 | without being bound by section 3 of the GNU GPL.
46 |
47 | 2. Conveying Modified Versions.
48 |
49 | If you modify a copy of the Library, and, in your modifications, a
50 | facility refers to a function or data to be supplied by an Application
51 | that uses the facility (other than as an argument passed when the
52 | facility is invoked), then you may convey a copy of the modified
53 | version:
54 |
55 | a) under this License, provided that you make a good faith effort to
56 | ensure that, in the event an Application does not supply the
57 | function or data, the facility still operates, and performs
58 | whatever part of its purpose remains meaningful, or
59 |
60 | b) under the GNU GPL, with none of the additional permissions of
61 | this License applicable to that copy.
62 |
63 | 3. Object Code Incorporating Material from Library Header Files.
64 |
65 | The object code form of an Application may incorporate material from
66 | a header file that is part of the Library. You may convey such object
67 | code under terms of your choice, provided that, if the incorporated
68 | material is not limited to numerical parameters, data structure
69 | layouts and accessors, or small macros, inline functions and templates
70 | (ten or fewer lines in length), you do both of the following:
71 |
72 | a) Give prominent notice with each copy of the object code that the
73 | Library is used in it and that the Library and its use are
74 | covered by this License.
75 |
76 | b) Accompany the object code with a copy of the GNU GPL and this license
77 | document.
78 |
79 | 4. Combined Works.
80 |
81 | You may convey a Combined Work under terms of your choice that,
82 | taken together, effectively do not restrict modification of the
83 | portions of the Library contained in the Combined Work and reverse
84 | engineering for debugging such modifications, if you also do each of
85 | the following:
86 |
87 | a) Give prominent notice with each copy of the Combined Work that
88 | the Library is used in it and that the Library and its use are
89 | covered by this License.
90 |
91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license
92 | document.
93 |
94 | c) For a Combined Work that displays copyright notices during
95 | execution, include the copyright notice for the Library among
96 | these notices, as well as a reference directing the user to the
97 | copies of the GNU GPL and this license document.
98 |
99 | d) Do one of the following:
100 |
101 | 0) Convey the Minimal Corresponding Source under the terms of this
102 | License, and the Corresponding Application Code in a form
103 | suitable for, and under terms that permit, the user to
104 | recombine or relink the Application with a modified version of
105 | the Linked Version to produce a modified Combined Work, in the
106 | manner specified by section 6 of the GNU GPL for conveying
107 | Corresponding Source.
108 |
109 | 1) Use a suitable shared library mechanism for linking with the
110 | Library. A suitable mechanism is one that (a) uses at run time
111 | a copy of the Library already present on the user's computer
112 | system, and (b) will operate properly with a modified version
113 | of the Library that is interface-compatible with the Linked
114 | Version.
115 |
116 | e) Provide Installation Information, but only if you would otherwise
117 | be required to provide such information under section 6 of the
118 | GNU GPL, and only to the extent that such information is
119 | necessary to install and execute a modified version of the
120 | Combined Work produced by recombining or relinking the
121 | Application with a modified version of the Linked Version. (If
122 | you use option 4d0, the Installation Information must accompany
123 | the Minimal Corresponding Source and Corresponding Application
124 | Code. If you use option 4d1, you must provide the Installation
125 | Information in the manner specified by section 6 of the GNU GPL
126 | for conveying Corresponding Source.)
127 |
128 | 5. Combined Libraries.
129 |
130 | You may place library facilities that are a work based on the
131 | Library side by side in a single library together with other library
132 | facilities that are not Applications and are not covered by this
133 | License, and convey such a combined library under terms of your
134 | choice, if you do both of the following:
135 |
136 | a) Accompany the combined library with a copy of the same work based
137 | on the Library, uncombined with any other library facilities,
138 | conveyed under the terms of this License.
139 |
140 | b) Give prominent notice with the combined library that part of it
141 | is a work based on the Library, and explaining where to find the
142 | accompanying uncombined form of the same work.
143 |
144 | 6. Revised Versions of the GNU Lesser General Public License.
145 |
146 | The Free Software Foundation may publish revised and/or new versions
147 | of the GNU Lesser General Public License from time to time. Such new
148 | versions will be similar in spirit to the present version, but may
149 | differ in detail to address new problems or concerns.
150 |
151 | Each version is given a distinguishing version number. If the
152 | Library as you received it specifies that a certain numbered version
153 | of the GNU Lesser General Public License "or any later version"
154 | applies to it, you have the option of following the terms and
155 | conditions either of that published version or of any later version
156 | published by the Free Software Foundation. If the Library as you
157 | received it does not specify a version number of the GNU Lesser
158 | General Public License, you may choose any version of the GNU Lesser
159 | General Public License ever published by the Free Software Foundation.
160 |
161 | If the Library as you received it specifies that a proxy can decide
162 | whether future versions of the GNU Lesser General Public License shall
163 | apply, that proxy's public statement of acceptance of any version is
164 | permanent authorization for you to choose that version for the
165 | Library.
--------------------------------------------------------------------------------
/maple/src/main/jni/elf_util.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include "logging.h"
9 | #include "elf_util.h"
10 |
11 | using namespace SandHook;
12 |
13 | template
14 | inline constexpr auto offsetOf(ElfW(Ehdr) *head, ElfW(Off) off) {
15 | return reinterpret_cast, T, T *>>(
16 | reinterpret_cast(head) + off);
17 | }
18 |
19 | ElfImg::ElfImg(std::string_view base_name) : elf(base_name) {
20 | if (!findModuleBase()) {
21 | base = nullptr;
22 | return;
23 | }
24 |
25 | //load elf
26 | int fd = open(elf.data(), O_RDONLY);
27 | if (fd < 0) {
28 | LOGE("failed to open %s", elf.data());
29 | return;
30 | }
31 |
32 | size = lseek(fd, 0, SEEK_END);
33 | if (size <= 0) {
34 | LOGE("lseek() failed for %s", elf.data());
35 | }
36 |
37 | header = reinterpret_cast(mmap(nullptr, size, PROT_READ, MAP_SHARED, fd, 0));
38 |
39 | close(fd);
40 |
41 | section_header = offsetOf(header, header->e_shoff);
42 |
43 | auto shoff = reinterpret_cast(section_header);
44 | char *section_str = offsetOf(header, section_header[header->e_shstrndx].sh_offset);
45 |
46 | for (int i = 0; i < header->e_shnum; i++, shoff += header->e_shentsize) {
47 | auto *section_h = (ElfW(Shdr) *) shoff;
48 | char *sname = section_h->sh_name + section_str;
49 | auto entsize = section_h->sh_entsize;
50 | switch (section_h->sh_type) {
51 | case SHT_DYNSYM: {
52 | if (bias == -4396) {
53 | dynsym = section_h;
54 | dynsym_offset = section_h->sh_offset;
55 | dynsym_start = offsetOf(header, dynsym_offset);
56 | }
57 | break;
58 | }
59 | case SHT_SYMTAB: {
60 | if (strcmp(sname, ".symtab") == 0) {
61 | symtab = section_h;
62 | symtab_offset = section_h->sh_offset;
63 | symtab_size = section_h->sh_size;
64 | symtab_count = symtab_size / entsize;
65 | symtab_start = offsetOf(header, symtab_offset);
66 | }
67 | break;
68 | }
69 | case SHT_STRTAB: {
70 | if (bias == -4396) {
71 | strtab = section_h;
72 | symstr_offset = section_h->sh_offset;
73 | strtab_start = offsetOf(header, symstr_offset);
74 | }
75 | if (strcmp(sname, ".strtab") == 0) {
76 | symstr_offset_for_symtab = section_h->sh_offset;
77 | }
78 | break;
79 | }
80 | case SHT_PROGBITS: {
81 | if (strtab == nullptr || dynsym == nullptr) break;
82 | if (bias == -4396) {
83 | bias = (off_t) section_h->sh_addr - (off_t) section_h->sh_offset;
84 | }
85 | break;
86 | }
87 | case SHT_HASH: {
88 | auto *d_un = offsetOf(header, section_h->sh_offset);
89 | nbucket_ = d_un[0];
90 | bucket_ = d_un + 2;
91 | chain_ = bucket_ + nbucket_;
92 | break;
93 | }
94 | case SHT_GNU_HASH: {
95 | auto *d_buf = reinterpret_cast(((size_t) header) +
96 | section_h->sh_offset);
97 | gnu_nbucket_ = d_buf[0];
98 | gnu_symndx_ = d_buf[1];
99 | gnu_bloom_size_ = d_buf[2];
100 | gnu_shift2_ = d_buf[3];
101 | gnu_bloom_filter_ = reinterpret_cast(d_buf + 4);
102 | gnu_bucket_ = reinterpret_cast(gnu_bloom_filter_ +
103 | gnu_bloom_size_);
104 | gnu_chain_ = gnu_bucket_ + gnu_nbucket_ - gnu_symndx_;
105 | break;
106 | }
107 | }
108 | }
109 | }
110 |
111 | ElfW(Addr) ElfImg::ElfLookup(std::string_view name, uint32_t hash) const {
112 | if (nbucket_ == 0) return 0;
113 |
114 | char *strings = (char *) strtab_start;
115 |
116 | for (auto n = bucket_[hash % nbucket_]; n != 0; n = chain_[n]) {
117 | auto *sym = dynsym_start + n;
118 | if (name == strings + sym->st_name) {
119 | return sym->st_value;
120 | }
121 | }
122 | return 0;
123 | }
124 |
125 | ElfW(Addr) ElfImg::GnuLookup(std::string_view name, uint32_t hash) const {
126 | static constexpr auto bloom_mask_bits = sizeof(ElfW(Addr)) * 8;
127 |
128 | if (gnu_nbucket_ == 0 || gnu_bloom_size_ == 0) return 0;
129 |
130 | auto bloom_word = gnu_bloom_filter_[(hash / bloom_mask_bits) % gnu_bloom_size_];
131 | uintptr_t mask = 0
132 | | (uintptr_t) 1 << (hash % bloom_mask_bits)
133 | | (uintptr_t) 1 << ((hash >> gnu_shift2_) % bloom_mask_bits);
134 | if ((mask & bloom_word) == mask) {
135 | auto sym_index = gnu_bucket_[hash % gnu_nbucket_];
136 | if (sym_index >= gnu_symndx_) {
137 | char *strings = (char *) strtab_start;
138 | do {
139 | auto *sym = dynsym_start + sym_index;
140 | if (((gnu_chain_[sym_index] ^ hash) >> 1) == 0
141 | && name == strings + sym->st_name) {
142 | return sym->st_value;
143 | }
144 | } while ((gnu_chain_[sym_index++] & 1) == 0);
145 | }
146 | }
147 | return 0;
148 | }
149 |
150 | ElfW(Addr) ElfImg::LinearLookup(std::string_view name) const {
151 | if (symtabs_.empty()) {
152 | symtabs_.reserve(symtab_count);
153 | if (symtab_start != nullptr && symstr_offset_for_symtab != 0) {
154 | for (ElfW(Off) i = 0; i < symtab_count; i++) {
155 | unsigned int st_type = ELF_ST_TYPE(symtab_start[i].st_info);
156 | const char *st_name = offsetOf(header, symstr_offset_for_symtab +
157 | symtab_start[i].st_name);
158 | if ((st_type == STT_FUNC || st_type == STT_OBJECT) && symtab_start[i].st_size) {
159 | symtabs_.emplace(st_name, &symtab_start[i]);
160 | }
161 | }
162 | }
163 | }
164 | if (auto i = symtabs_.find(name); i != symtabs_.end()) {
165 | return i->second->st_value;
166 | } else {
167 | return 0;
168 | }
169 | }
170 |
171 |
172 | ElfImg::~ElfImg() {
173 | //open elf file local
174 | if (buffer) {
175 | free(buffer);
176 | buffer = nullptr;
177 | }
178 | //use mmap
179 | if (header) {
180 | munmap(header, size);
181 | }
182 | }
183 |
184 | ElfW(Addr)
185 | ElfImg::getSymbOffset(std::string_view name, uint32_t gnu_hash, uint32_t elf_hash) const {
186 | if (auto offset = GnuLookup(name, gnu_hash); offset > 0) {
187 | LOGD("found %s %p in %s in dynsym by gnuhash", name.data(),
188 | reinterpret_cast(offset), elf.data());
189 | return offset;
190 | } else if (offset = ElfLookup(name, elf_hash); offset > 0) {
191 | LOGD("found %s %p in %s in dynsym by elfhash", name.data(),
192 | reinterpret_cast(offset), elf.data());
193 | return offset;
194 | } else if (offset = LinearLookup(name); offset > 0) {
195 | LOGD("found %s %p in %s in symtab by linear lookup", name.data(),
196 | reinterpret_cast(offset), elf.data());
197 | return offset;
198 | } else {
199 | return 0;
200 | }
201 |
202 | }
203 |
204 | constexpr inline bool contains(std::string_view a, std::string_view b) {
205 | return a.find(b) != std::string_view::npos;
206 | }
207 |
208 | bool ElfImg::findModuleBase() {
209 | off_t load_addr;
210 | bool found = false;
211 | FILE *maps = fopen("/proc/self/maps", "r");
212 |
213 | char *buff = nullptr;
214 | size_t len = 0;
215 | ssize_t nread;
216 |
217 | while ((nread = getline(&buff, &len, maps)) != -1) {
218 | std::string_view line{buff, static_cast(nread)};
219 |
220 | if ((contains(line, "r-xp") || contains(line, "r--p")) && contains(line, elf)) {
221 | LOGD("found: %*s", static_cast(line.size()), line.data());
222 | if (auto begin = line.find_last_of(' '); begin != std::string_view::npos &&
223 | line[++begin] == '/') {
224 | found = true;
225 | elf = line.substr(begin);
226 | if (elf.back() == '\n') elf.pop_back();
227 | LOGD("update path: %s", elf.data());
228 | break;
229 | }
230 | }
231 | }
232 | if (!found) {
233 | if (buff) free(buff);
234 | LOGE("failed to read load address for %s", elf.data());
235 | fclose(maps);
236 | return false;
237 | }
238 |
239 | if (char *next = buff; load_addr = strtoul(buff, &next, 16), next == buff) {
240 | LOGE("failed to read load address for %s", elf.data());
241 | }
242 |
243 | if (buff) free(buff);
244 |
245 | fclose(maps);
246 |
247 | LOGD("get module base %s: %lx", elf.data(), load_addr);
248 |
249 | base = reinterpret_cast(load_addr);
250 | return true;
251 | }
252 |
--------------------------------------------------------------------------------
/maple/src/main/java/me/fycz/maple/MapleUtils.java:
--------------------------------------------------------------------------------
1 | package me.fycz.maple;
2 |
3 | import android.content.res.AssetManager;
4 | import android.content.res.Resources;
5 | import android.os.Build;
6 | import android.util.Log;
7 |
8 | import androidx.annotation.NonNull;
9 | import androidx.annotation.Nullable;
10 | import androidx.annotation.RequiresApi;
11 |
12 | import org.apache.commons.lang3.ClassUtils;
13 | import org.apache.commons.lang3.reflect.MemberUtilsX;
14 |
15 | import java.io.ByteArrayOutputStream;
16 | import java.io.FileInputStream;
17 | import java.io.IOException;
18 | import java.io.InputStream;
19 | import java.lang.reflect.Constructor;
20 | import java.lang.reflect.Field;
21 | import java.lang.reflect.InvocationTargetException;
22 | import java.lang.reflect.Member;
23 | import java.lang.reflect.Method;
24 | import java.lang.reflect.Modifier;
25 | import java.math.BigInteger;
26 | import java.security.MessageDigest;
27 | import java.security.NoSuchAlgorithmException;
28 | import java.util.Arrays;
29 | import java.util.HashMap;
30 | import java.util.LinkedList;
31 | import java.util.List;
32 | import java.util.Objects;
33 | import java.util.Optional;
34 | import java.util.WeakHashMap;
35 | import java.util.concurrent.ConcurrentHashMap;
36 | import java.util.concurrent.atomic.AtomicInteger;
37 |
38 | /**
39 | * @author fengyue
40 | * @date 2022/3/28 14:57
41 | */
42 | public final class MapleUtils {
43 | static {
44 | try {
45 | System.loadLibrary("maple");
46 | } catch (Throwable e) {
47 | log(e);
48 | throw new RuntimeException("Load maple hook library failed!");
49 | }
50 | }
51 |
52 | private static final String TAG = "MapleUtils";
53 | /**
54 | * The system class loader which can be used to locate Android framework classes.
55 | * Application classes cannot be retrieved from it.
56 | *
57 | * @see ClassLoader#getSystemClassLoader
58 | */
59 | private static final ClassLoader BOOTCLASSLOADER = MapleUtils.class.getClassLoader();
60 |
61 | private static final ConcurrentHashMap fieldCache = new ConcurrentHashMap<>();
62 | private static final ConcurrentHashMap methodCache = new ConcurrentHashMap<>();
63 | private static final ConcurrentHashMap> constructorCache = new ConcurrentHashMap<>();
64 | private static final WeakHashMap