├── .gitignore ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── cpp │ ├── CMakeLists.txt │ ├── test.cpp │ ├── test_jni_bad.cpp │ ├── test_jni_err.cpp │ ├── test_lib.cpp │ └── test_nojni.cpp │ └── java │ └── io │ └── github │ └── eirv │ └── elfloader │ ├── HiddenApi.java │ └── MainActivity.java ├── build.gradle ├── elfloader ├── .gitignore ├── build.gradle ├── consumer-rules.pro ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ └── java │ └── io │ └── github │ └── eirv │ └── elfloader │ ├── ElfImg.java │ └── ElfLoader.java ├── gradle.properties ├── gradle ├── libs.versions.toml └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── stub ├── .gitignore ├── apibridge ├── .gitignore ├── build.gradle └── src │ └── main │ └── java │ └── io │ └── github │ └── eirv │ └── elfloader │ └── ApiBridge.java ├── build.gradle └── src └── main ├── AndroidManifest.xml └── java ├── dalvik └── system │ └── VMRuntime.java └── sun └── misc └── Unsafe.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea 5 | .DS_Store 6 | /build 7 | /captures 8 | .externalNativeBuild 9 | .cxx 10 | local.properties 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ElfLoader 2 | 3 | ![](https://img.shields.io/badge/Android-7%20~%2016dp1-brightgreen) 4 | ![](https://img.shields.io/badge/Arch-arm64%20%2F%20arm%20%2F%20x86%20%2F%20x64%20%2F%20riscv64-red.svg) 5 | 6 | Loading ELF in android using pure java 7 | 8 | 使用纯 java 在 android 上加载 ELF 9 | 10 | ## Features 11 | 12 | - [x] Loading shared libraries and call `JNI_OnLoad` if exists 13 | - [ ] Loading in-memory shared libraries 14 | - [x] arm64 15 | - [ ] arm 16 | - [ ] x86 17 | - [ ] x64 18 | - [ ] riscv64 19 | - [x] Lookup symbols in `.dynsym` 20 | - [x] Lookup debugging symbols in `.symtab` 21 | - [ ] Lookup debugging symbols in `.gnu_debugdata` (not planned, do we really need it?) 22 | 23 | ## 特征 24 | 25 | - [x] 加载动态库,如果存在则调用 `JNI_OnLoad` 26 | - [ ] 加载内存中的动态库 27 | - [x] arm64 28 | - [ ] arm 29 | - [ ] x86 30 | - [ ] x64 31 | - [ ] riscv64 32 | - [x] 查找 `.dynsym` 中的符号 33 | - [x] 查找 `.symtab` 中的调试符号 34 | - [ ] 查找 `.gnu_debugdata` 中的调试符号 (未计划, 真的需要?) 35 | 36 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | alias(libs.plugins.androidApplication) 3 | } 4 | 5 | android { 6 | namespace 'io.github.eirv.elfloader' 7 | compileSdk rootProject.ext.compileSdk 8 | ndkVersion rootProject.ext.ndk 9 | 10 | defaultConfig { 11 | applicationId "io.github.eirv.elfloader" 12 | minSdk rootProject.ext.minSdk 13 | targetSdk rootProject.ext.targetSdk 14 | versionCode rootProject.ext.versionCode 15 | versionName rootProject.ext.version 16 | 17 | externalNativeBuild { 18 | cmake { 19 | cppFlags '-std=c++23' 20 | arguments += '-DANDROID_STL=none' 21 | arguments += '-DCMAKE_BUILD_TYPE=Release' 22 | arguments += '-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON' 23 | } 24 | } 25 | ndk.abiFilters 'arm64-v8a', 'armeabi-v7a', 'x86', 'x86_64', 'riscv64' 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 rootProject.ext.java 36 | targetCompatibility rootProject.ext.java 37 | } 38 | externalNativeBuild { 39 | cmake { 40 | path 'src/main/cpp/CMakeLists.txt' 41 | version rootProject.ext.cmake 42 | } 43 | } 44 | packagingOptions { 45 | jniLibs.useLegacyPackaging true 46 | } 47 | } 48 | 49 | dependencies { 50 | compileOnly(project(':stub')) 51 | implementation(project(':elfloader')) 52 | implementation(project(':stub:apibridge')) 53 | } -------------------------------------------------------------------------------- /app/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 -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 8 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /app/src/main/cpp/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.22.1) 2 | 3 | if (ANDROID_ABI STREQUAL "riscv64") 4 | set(ANDROID_PLATFORM "android-35") 5 | endif () 6 | 7 | project("test") 8 | 9 | add_library(test_lib SHARED test_lib.cpp) 10 | 11 | add_library(test SHARED test.cpp) 12 | target_link_libraries(test PUBLIC log test_lib) 13 | 14 | add_library(test-jni-err SHARED test_jni_err.cpp) 15 | 16 | add_library(test-jni-bad SHARED test_jni_bad.cpp) 17 | 18 | add_library(test-nojni SHARED test_nojni.cpp) 19 | target_link_libraries(test-nojni PUBLIC log) 20 | -------------------------------------------------------------------------------- /app/src/main/cpp/test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int test_lib_add(int a, int b); 8 | 9 | extern "C" void test_func() {} 10 | 11 | jint JNI_OnLoad(JavaVM *vm, void *handle) { 12 | __android_log_print(ANDROID_LOG_INFO, "JNI-main", "loaded"); 13 | if (!vm) { 14 | android_set_abort_message("vm == nullptr"); 15 | abort(); 16 | } 17 | if (!handle) { 18 | android_set_abort_message("handle == nullptr"); 19 | abort(); 20 | } 21 | JNIEnv *env; 22 | vm->GetEnv((void **) &env, JNI_VERSION_1_6); 23 | jclass cls = env->FindClass("java/lang/System"); 24 | jfieldID fid = env->GetStaticFieldID(cls, "out", "Ljava/io/PrintStream;"); 25 | jobject out = env->GetStaticObjectField(cls, fid); 26 | jmethodID mid = env->GetMethodID(env->FindClass("java/io/PrintStream"), "println", 27 | "(Ljava/lang/String;)V"); 28 | env->CallVoidMethod(out, mid, env->NewStringUTF("JNI: loaded")); 29 | env->CallVoidMethod(out, mid, env->NewStringUTF( 30 | dlsym(handle, "test_func") == test_func ? "JNI: handle ok" : "JNI: handle error")); 31 | return test_lib_add(JNI_VERSION_1_6 - 123, 123); 32 | } 33 | -------------------------------------------------------------------------------- /app/src/main/cpp/test_jni_bad.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | jint JNI_OnLoad(JavaVM *, void *) { 4 | return 123456; 5 | } 6 | -------------------------------------------------------------------------------- /app/src/main/cpp/test_jni_err.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | jint JNI_OnLoad(JavaVM *, void *) { 4 | return JNI_ERR; 5 | } 6 | -------------------------------------------------------------------------------- /app/src/main/cpp/test_lib.cpp: -------------------------------------------------------------------------------- 1 | [[gnu::visibility("default")]] int test_lib_add(int a, int b) { 2 | return a + b; 3 | } 4 | -------------------------------------------------------------------------------- /app/src/main/cpp/test_nojni.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | [[gnu::constructor, maybe_unused]] void entry() { 4 | __android_log_print(ANDROID_LOG_INFO, "JNI-nojni", "loaded"); 5 | } -------------------------------------------------------------------------------- /app/src/main/java/io/github/eirv/elfloader/HiddenApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2023 Eirv 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.github.eirv.elfloader; 18 | 19 | import android.os.Build; 20 | 21 | import sun.misc.Unsafe; 22 | 23 | public class HiddenApi { 24 | public static void setExemptions(String... signaturePrefixes) { 25 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) return; 26 | try { 27 | //noinspection JavaReflectionMemberAccess 28 | var unsafe = (Unsafe) Unsafe.class.getMethod("getUnsafe").invoke(null); 29 | assert unsafe != null; 30 | 31 | var stubs = Compiler.class.getDeclaredMethods(); 32 | var stub = stubs[0]; 33 | 34 | var size = unsafe.getLong(stubs[1], 24) - unsafe.getLong(stub, 24); 35 | var methods = unsafe.getLong(ApiBridge.VMRuntime_class(), 48); 36 | var count = unsafe.getInt(methods); 37 | 38 | methods += unsafe.addressSize(); 39 | 40 | for (int i = 0; count > i; i++) { 41 | var method = i * size + methods; 42 | unsafe.putLong(stub, 24, method); 43 | 44 | var name = stub.getName(); 45 | if (!"setHiddenApiExemptions".equals(name)) continue; 46 | 47 | stub.invoke(ApiBridge.VMRuntime_getRuntime(), new Object[] {signaturePrefixes}); 48 | } 49 | } catch (Exception e) { 50 | throw new ExceptionInInitializerError(e); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /app/src/main/java/io/github/eirv/elfloader/MainActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2024 Eirv 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.github.eirv.elfloader; 18 | 19 | import android.app.Activity; 20 | import android.os.Bundle; 21 | import android.util.Log; 22 | 23 | public class MainActivity extends Activity { 24 | private static final String TAG = "MainActivity"; 25 | 26 | @Override 27 | protected void onCreate(Bundle savedInstanceState) { 28 | super.onCreate(savedInstanceState); 29 | HiddenApi.setExemptions(""); 30 | ElfLoader loader = ElfLoader.getLoader(); 31 | String nativeLibraryDir = getApplicationInfo().nativeLibraryDir; 32 | loadLibrary(loader, nativeLibraryDir, "test"); 33 | loadLibrary(loader, nativeLibraryDir, "test-nojni"); 34 | try { 35 | loadLibrary(loader, nativeLibraryDir, "test-jni-err"); 36 | } catch (UnsatisfiedLinkError e) { 37 | Log.w(TAG, e); 38 | } 39 | try { 40 | loadLibrary(loader, nativeLibraryDir, "test-jni-bad"); 41 | } catch (UnsatisfiedLinkError e) { 42 | Log.w(TAG, e); 43 | } 44 | try { 45 | loadLibrary(loader, nativeLibraryDir, "test-not-found"); 46 | } catch (UnsatisfiedLinkError e) { 47 | Log.w(TAG, e); 48 | } 49 | loader.release(); 50 | } 51 | 52 | private static void loadLibrary(ElfLoader elfLoader, String nativeLibraryDir, String name) { 53 | elfLoader.load(nativeLibraryDir + "/lib" + name + ".so"); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | plugins { 3 | alias(libs.plugins.androidApplication) apply false 4 | alias(libs.plugins.androidLibrary) apply false 5 | } 6 | 7 | ext { 8 | compileSdk = 34 9 | ndk = '27.2.12479018' 10 | cmake = '3.30.5' 11 | java = JavaVersion.VERSION_17 12 | 13 | minSdk = 24 14 | targetSdk = 34 15 | version = '1.0.0' 16 | versionCode = 1 17 | } 18 | -------------------------------------------------------------------------------- /elfloader/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /elfloader/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | alias(libs.plugins.androidLibrary) 3 | } 4 | 5 | android { 6 | namespace 'io.github.eirv.elfloader.core' 7 | compileSdk rootProject.ext.compileSdk 8 | 9 | defaultConfig { 10 | minSdk rootProject.ext.minSdk 11 | 12 | consumerProguardFiles "consumer-rules.pro" 13 | } 14 | 15 | buildTypes { 16 | release { 17 | minifyEnabled false 18 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 19 | } 20 | } 21 | compileOptions { 22 | sourceCompatibility rootProject.ext.java 23 | targetCompatibility rootProject.ext.java 24 | } 25 | } 26 | 27 | dependencies { 28 | compileOnly(project(':stub')) 29 | implementation(project(':stub:apibridge')) 30 | } -------------------------------------------------------------------------------- /elfloader/consumer-rules.pro: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eirv/ElfLoader/25e022867c88601bbed4e96aea2f6271383eed31/elfloader/consumer-rules.pro -------------------------------------------------------------------------------- /elfloader/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 -------------------------------------------------------------------------------- /elfloader/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /elfloader/src/main/java/io/github/eirv/elfloader/ElfImg.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2024 Eirv 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.github.eirv.elfloader; 18 | 19 | import java.io.BufferedReader; 20 | import java.io.File; 21 | import java.io.FileInputStream; 22 | import java.io.FileReader; 23 | import java.io.IOException; 24 | import java.nio.ByteOrder; 25 | import java.nio.MappedByteBuffer; 26 | import java.nio.channels.FileChannel.MapMode; 27 | import java.util.HashMap; 28 | import java.util.Map; 29 | 30 | public class ElfImg { 31 | private static final int EI_CLASS = 4; 32 | private static final int EI_NIDENT = 16; 33 | private static final int SHT_SYMTAB = 2; 34 | private static final int SHT_DYNSYM = 11; 35 | private static final int SHN_UNDEF = 0; 36 | private static final int PT_LOAD = 1; 37 | 38 | private final HashMap symbols = new HashMap<>(); 39 | 40 | public ElfImg(String filename) { 41 | this(filename, false); 42 | } 43 | 44 | public ElfImg(String filename, boolean searchDebugSymbols) { 45 | try { 46 | filename = new File(filename).getCanonicalPath(); 47 | } catch (IOException ignored) { 48 | } 49 | 50 | var base = 0L; 51 | try (var reader = new BufferedReader(new FileReader("/proc/self/maps"))) { 52 | var permissions = new char[4]; 53 | for (String line; (line = reader.readLine()) != null; ) { 54 | if (line.isEmpty()) continue; 55 | 56 | var index = line.indexOf(' ') + 1; 57 | line.getChars(index, index + 4, permissions, 0); 58 | 59 | // r--p r-xp --xp 60 | if (permissions[1] == 'w') continue; 61 | if (permissions[3] != 'p') continue; 62 | if (permissions[0] != 'r' && permissions[2] != 'x') continue; 63 | if (!line.endsWith(filename)) continue; 64 | 65 | base = Long.parseLong(line.substring(0, line.indexOf('-')), 16); 66 | filename = line.substring(line.lastIndexOf(' ') + 1); 67 | break; 68 | } 69 | } catch (IOException ignored) { 70 | } 71 | 72 | if (base == 0) return; 73 | var file = new File(filename); 74 | 75 | try (var raf = new FileInputStream(file)) { 76 | var elf = raf.getChannel().map(MapMode.READ_ONLY, 0, file.length()); 77 | elf.order(ByteOrder.LITTLE_ENDIAN); 78 | 79 | elf.position(EI_CLASS); 80 | var is64Bit = elf.get() == 2; 81 | var ptr = is64Bit ? 8 : 4; 82 | elf.position(EI_NIDENT + 2 + 2 + 4 + ptr); 83 | var phoff = (int) getPointer(elf, is64Bit); 84 | var shoff = (int) getPointer(elf, is64Bit); 85 | elf.position(elf.position() + 4 + 2); 86 | var e_phentsize = elf.getShort(); 87 | var e_phnum = elf.getShort(); 88 | var e_shentsize = elf.getShort(); 89 | var e_shnum = elf.getShort(); 90 | 91 | var min_vaddr = Integer.MAX_VALUE; 92 | for (var i = 0; e_phnum > i; i++) { 93 | elf.position(phoff + i * e_phentsize); 94 | var p_type = elf.getInt(); 95 | if (p_type != PT_LOAD) continue; 96 | elf.position(elf.position() + 4); 97 | var p_vaddr = (int) getPointer(elf, is64Bit); 98 | if (min_vaddr > p_vaddr) min_vaddr = p_vaddr; 99 | } 100 | base -= min_vaddr; 101 | 102 | boolean dynsym = false; 103 | boolean symtab = false; 104 | 105 | for (var i = 0; e_shnum > i; i++) { 106 | elf.position(shoff + i * e_shentsize + 4); 107 | var sh_type = elf.getInt(); 108 | if (sh_type != SHT_DYNSYM && (!searchDebugSymbols || sh_type != SHT_SYMTAB)) 109 | continue; 110 | elf.position(elf.position() + ptr * 2); 111 | var sym_offset = (int) getPointer(elf, is64Bit); 112 | var sh_size = getPointer(elf, is64Bit); 113 | var sh_link = elf.getInt(); 114 | elf.position(elf.position() + 4 + ptr); 115 | var sym_count = (int) (sh_size / getPointer(elf, is64Bit)); 116 | elf.position(shoff + sh_link * e_shentsize + 4 * 2 + ptr * 2); 117 | var str_offset = (int) getPointer(elf, is64Bit); 118 | var str_size = (int) getPointer(elf, is64Bit); 119 | if (sh_type == SHT_DYNSYM) { 120 | searchSymbols( 121 | symbols, 122 | base, 123 | elf, 124 | is64Bit, 125 | sym_offset, 126 | sym_count, 127 | str_offset, 128 | str_size); 129 | dynsym = true; 130 | if (!searchDebugSymbols) break; 131 | } else { 132 | searchSymbols( 133 | symbols, 134 | base, 135 | elf, 136 | is64Bit, 137 | sym_offset, 138 | sym_count, 139 | str_offset, 140 | str_size); 141 | symtab = true; 142 | } 143 | if (dynsym && symtab) break; 144 | } 145 | } catch (IOException ignored) { 146 | } 147 | } 148 | 149 | private static void searchSymbols( 150 | HashMap result, 151 | long base, 152 | MappedByteBuffer elf, 153 | boolean is64Bit, 154 | int sym_off, 155 | int sym_count, 156 | int str_off, 157 | int str_size) { 158 | if (sym_count == 0 || str_size == 0) { 159 | return; 160 | } 161 | 162 | var strings = new byte[str_size]; 163 | elf.position(str_off); 164 | elf.get(strings); 165 | 166 | elf.position(sym_off); 167 | for (var n = 0; sym_count > n; n++) { 168 | var st_name = elf.getInt(); 169 | long st_value; 170 | if (is64Bit) { 171 | elf.position(elf.position() + 1 + 1 + 2); 172 | st_value = elf.getLong(); 173 | var st_size = elf.getLong(); 174 | if (st_size == 0) continue; 175 | } else { 176 | st_value = elf.getInt(); 177 | var st_size = elf.getInt(); 178 | elf.position(elf.position() + 1 + 1 + 2); 179 | if (st_size == 0) continue; 180 | } 181 | if (st_name == SHN_UNDEF) continue; 182 | var length = -1; 183 | //noinspection StatementWithEmptyBody 184 | while (strings[st_name + ++length] != 0) 185 | ; 186 | if (length == 0) continue; 187 | result.put(new String(strings, st_name, length), base + st_value); 188 | } 189 | } 190 | 191 | private static long getPointer(MappedByteBuffer elf, boolean is64Bit) { 192 | return is64Bit ? elf.getLong() : elf.getInt(); 193 | } 194 | 195 | public boolean isEmpty() { 196 | return symbols.isEmpty(); 197 | } 198 | 199 | public long getSymbolAddress(String symbol) { 200 | var address = symbols.get(symbol); 201 | return address == null ? 0 : address; 202 | } 203 | 204 | public long getSymbolAddressBestMatch(String symbol) { 205 | Map.Entry previous = null; 206 | for (Map.Entry e : symbols.entrySet()) { 207 | if (!e.getKey().contains(symbol)) continue; 208 | if (previous == null) { 209 | previous = e; 210 | } else { 211 | throw new UnsupportedOperationException( 212 | "Multiple symbols were found: '" 213 | + previous.getKey() 214 | + "', '" 215 | + e.getKey() 216 | + '\''); 217 | } 218 | } 219 | return previous == null ? 0 : previous.getValue(); 220 | } 221 | 222 | public Map getSymbols() { 223 | return symbols; 224 | } 225 | } 226 | -------------------------------------------------------------------------------- /elfloader/src/main/java/io/github/eirv/elfloader/ElfLoader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2024 Eirv 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.github.eirv.elfloader; 18 | 19 | import android.annotation.SuppressLint; 20 | import android.os.Build; 21 | import android.system.ErrnoException; 22 | import android.system.Os; 23 | 24 | import sun.misc.Unsafe; 25 | 26 | import java.io.FileDescriptor; 27 | import java.io.InterruptedIOException; 28 | import java.lang.reflect.Field; 29 | import java.lang.reflect.InvocationTargetException; 30 | import java.lang.reflect.Method; 31 | import java.util.Random; 32 | 33 | public class ElfLoader { 34 | private static final int JNI_ERR = -1; 35 | private static final int JNI_VERSION_1_2 = 0x00010002; 36 | private static final int JNI_VERSION_1_4 = 0x00010004; 37 | private static final int JNI_VERSION_1_6 = 0x00010006; 38 | private static final int SHELLCODE_SIZE = 0x200; 39 | 40 | private static final Unsafe theUnsafe; 41 | private static final Field artMethodField; 42 | private static final Method nativeMethod; 43 | private static ElfLoader instance; 44 | 45 | static { 46 | Field field = null; 47 | try { 48 | var executableClass = Method.class.getSuperclass(); 49 | assert executableClass != null; 50 | field = executableClass.getDeclaredField("artMethod"); 51 | field.setAccessible(true); 52 | } catch (ReflectiveOperationException ignored) { 53 | } 54 | artMethodField = field; 55 | 56 | try { 57 | nativeMethod = ElfLoader.class.getDeclaredMethod("a"); 58 | 59 | @SuppressLint("DiscouragedPrivateApi") 60 | var theUnsafeField = Unsafe.class.getDeclaredField("theUnsafe"); 61 | theUnsafeField.setAccessible(true); 62 | var u = (Unsafe) theUnsafeField.get(null); 63 | assert u != null; 64 | theUnsafe = u; 65 | } catch (ReflectiveOperationException e) { 66 | throw new ExceptionInInitializerError(e); 67 | } 68 | } 69 | 70 | private long mmapAddress; 71 | private int libraryFdOffset; 72 | 73 | private ElfLoader() {} 74 | 75 | public static ElfLoader getLoader() { 76 | var loader = instance; 77 | if (loader != null) return loader; 78 | return instance = new ElfLoader(); 79 | } 80 | 81 | private static void registerNative(Method method, long function) { 82 | var u = theUnsafe; 83 | var addressSize = u.addressSize(); 84 | var stubs = Compiler.class.getDeclaredMethods(); 85 | var artMethodSize = getArtMethod(stubs[1]) - getArtMethod(stubs[0]); 86 | var address = getArtMethod(method) + artMethodSize - addressSize * 2L; 87 | if (addressSize == 8) { 88 | u.putLong(address, function); 89 | } else { 90 | u.putInt(address, (int) function); 91 | } 92 | } 93 | 94 | private static long getArtMethod(Method method) { 95 | var field = artMethodField; 96 | if (field != null) { 97 | try { 98 | return field.getLong(method); 99 | } catch (IllegalAccessException ignored) { 100 | } 101 | } 102 | // sdk >= 28 103 | return theUnsafe.getLong(method, 24); 104 | } 105 | 106 | private static void putString(long addr, String str) { 107 | var bytes = str.getBytes(); 108 | var len = bytes.length; 109 | copyMemory(bytes, addr, len); 110 | theUnsafe.putByte(addr + len, (byte) 0); 111 | } 112 | 113 | private static void copyMemory(Object srcArray, long dstAddr, int len) { 114 | var u = theUnsafe; 115 | try { 116 | u.copyMemoryFromPrimitiveArray(srcArray, 0, dstAddr, len); 117 | return; 118 | } catch (NoSuchMethodError ignored) { 119 | } 120 | Object[] arr = {srcArray}; 121 | int srcAddr = 122 | u.getInt(arr, u.arrayBaseOffset(Object[].class)) 123 | + u.arrayBaseOffset(srcArray.getClass()); 124 | u.copyMemory(srcAddr, dstAddr, len); 125 | } 126 | 127 | private static void copyMemory(long srcAddr, Object dstArray, int len) { 128 | var u = theUnsafe; 129 | try { 130 | u.copyMemoryToPrimitiveArray(srcAddr, dstArray, 0, len); 131 | return; 132 | } catch (NoSuchMethodError ignored) { 133 | } 134 | Object[] arr = {dstArray}; 135 | int dstAddr = 136 | u.getInt(arr, u.arrayBaseOffset(Object[].class)) 137 | + u.arrayBaseOffset(dstArray.getClass()); 138 | u.copyMemory(srcAddr, dstAddr, len); 139 | } 140 | 141 | private static long[] getNativeBridgeFunctions() { 142 | var elf = new ElfImg("/libnativebridge.so"); 143 | long dlopen = elf.getSymbolAddress("NativeBridgeLoadLibrary"); 144 | long dlsym, dlerror; 145 | if (dlopen != 0) { 146 | dlsym = elf.getSymbolAddress("NativeBridgeGetTrampoline"); 147 | dlerror = elf.getSymbolAddress("NativeBridgeGetError"); 148 | } else { 149 | dlopen = elf.getSymbolAddress("_ZN7android23NativeBridgeLoadLibraryEPKci"); 150 | dlsym = elf.getSymbolAddress("_ZN7android25NativeBridgeGetTrampolineEPvPKcS2_j"); 151 | dlerror = elf.getSymbolAddress("_ZN7android20NativeBridgeGetErrorEv"); 152 | } 153 | return dlopen == 0 || dlsym == 0 ? new long[3] : new long[] {dlopen, dlsym, dlerror}; 154 | } 155 | 156 | private static String toJavaString(long ptr) { 157 | final var maxStringSize = 1024; 158 | 159 | if (ptr >= 0 && ptr < 0x8000) { 160 | return ""; 161 | } 162 | 163 | var buf = new byte[maxStringSize + 1]; 164 | copyMemory(ptr, buf, maxStringSize); 165 | 166 | var length = 0; 167 | for (; ; length++) { 168 | if (buf[length] == 0) break; 169 | } 170 | 171 | return new String(buf, 0, length); 172 | } 173 | 174 | private static String getJniReturnedMessage(String path, int version) { 175 | return switch (version) { 176 | case JNI_ERR -> "JNI_ERR returned from JNI_OnLoad in \"" + path + '\"'; 177 | case JNI_VERSION_1_6, JNI_VERSION_1_4, JNI_VERSION_1_2 -> null; 178 | default -> "Bad JNI version returned from JNI_OnLoad in \"" + path + "\": " + version; 179 | }; 180 | } 181 | 182 | private static int getFdInt(FileDescriptor fd) { 183 | try { 184 | //noinspection JavaReflectionMemberAccess 185 | var method = FileDescriptor.class.getDeclaredMethod("getInt$"); 186 | method.setAccessible(true); 187 | //noinspection DataFlowIssue 188 | return (int) method.invoke(fd); 189 | } catch (ReflectiveOperationException e) { 190 | throw new RuntimeException(e); 191 | } 192 | } 193 | 194 | private static long callNativeMethod() { 195 | try { 196 | var r = nativeMethod.invoke(null); 197 | assert r != null; 198 | return (long) r; 199 | } catch (IllegalAccessException e) { 200 | throw new RuntimeException(e); 201 | } catch (InvocationTargetException e) { 202 | throw rethrow(e.getTargetException()); 203 | } 204 | } 205 | 206 | @SuppressWarnings("unchecked") 207 | private static RuntimeException rethrow(Throwable e) throws X { 208 | throw (X) e; 209 | } 210 | 211 | @SuppressWarnings("JavaJniMissingFunction") 212 | private static native long a(); 213 | 214 | private void initTrampoline(long mem, String arch, long dlopen, long dlsym, long dlerror) { 215 | Object code; 216 | int length; 217 | long[] nativeBridgeFunctions = null; 218 | 219 | switch (arch) { 220 | case "arm64" -> { 221 | int[] shellcode = { 222 | 0xd10083ff, 0xf9000ffe, 0xf9400002, 0xf9436c42, 0x910023e1, 0xd63f0040, 223 | 0x10000f40, 0x52800041, 0xaa1f03e2, 0xaa1f03e3, 0x180003e5, 0x34000045, 224 | 0x100002c2, 0x58000424, 0xd63f0080, 0xb40001a0, 0xf9000be0, 0x10000461, 225 | 0x580003c2, 0xd63f0040, 0xaa0003e2, 0xb4000080, 0xa94087e0, 0xd63f0040, 226 | 0x14000007, 0x18000040, 0x14000005, 0x00010006, 0x580002c0, 0xd63f0000, 227 | 0xb2440000, 0xf9400ffe, 0x910083ff, 0xd65f03c0, 0x00000050, 0x00000000, 228 | 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 229 | 0x00000000, 0x00000000, 0x00000000, 0x00000000, 230 | }; 231 | code = shellcode; 232 | length = shellcode.length * 4; 233 | libraryFdOffset = length - 4 * 5; 234 | } 235 | case "x86_64" -> { 236 | byte[] shellcode = { 237 | (byte) 0x41, (byte) 0x56, (byte) 0x53, (byte) 0x50, (byte) 0x48, (byte) 0x89, 238 | (byte) 0xe6, (byte) 0x48, (byte) 0x89, (byte) 0x3e, (byte) 0x48, (byte) 0x8b, 239 | (byte) 0x07, (byte) 0xff, (byte) 0x90, (byte) 0xd8, (byte) 0x06, (byte) 0x00, 240 | (byte) 0x00, (byte) 0x48, (byte) 0x8d, (byte) 0x05, (byte) 0xb8, (byte) 0x00, 241 | (byte) 0x00, (byte) 0x00, (byte) 0x48, (byte) 0x8d, (byte) 0x3d, (byte) 0xdf, 242 | (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x6a, (byte) 0x02, (byte) 0x5e, 243 | (byte) 0xff, (byte) 0x10, (byte) 0x48, (byte) 0x85, (byte) 0xc0, (byte) 0x74, 244 | (byte) 0x2c, (byte) 0x49, (byte) 0x89, (byte) 0xc6, (byte) 0x48, (byte) 0x8d, 245 | (byte) 0x05, (byte) 0xa5, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x48, 246 | (byte) 0x8d, (byte) 0x35, (byte) 0xc6, (byte) 0x00, (byte) 0x00, (byte) 0x00, 247 | (byte) 0x4c, (byte) 0x89, (byte) 0xf7, (byte) 0xff, (byte) 0x10, (byte) 0x48, 248 | (byte) 0x89, (byte) 0xc1, (byte) 0x48, (byte) 0x85, (byte) 0xc0, (byte) 0x74, 249 | (byte) 0x58, (byte) 0x48, (byte) 0x8b, (byte) 0x3c, (byte) 0x24, (byte) 0x4c, 250 | (byte) 0x89, (byte) 0xf6, (byte) 0xff, (byte) 0xd1, (byte) 0x48, (byte) 0x63, 251 | (byte) 0xd8, (byte) 0xeb, (byte) 0x70, (byte) 0x48, (byte) 0x8d, (byte) 0x0d, 252 | (byte) 0x84, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x31, (byte) 0xc0, 253 | (byte) 0xff, (byte) 0x11, (byte) 0x48, (byte) 0x89, (byte) 0xc3, (byte) 0x48, 254 | (byte) 0x8d, (byte) 0x05, (byte) 0x7e, (byte) 0x00, (byte) 0x00, (byte) 0x00, 255 | (byte) 0x48, (byte) 0x8b, (byte) 0x08, (byte) 0x48, (byte) 0x85, (byte) 0xc9, 256 | (byte) 0x74, (byte) 0x4e, (byte) 0x48, (byte) 0x8d, (byte) 0x3d, (byte) 0x85, 257 | (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x6a, (byte) 0x02, (byte) 0x5e, 258 | (byte) 0xff, (byte) 0xd1, (byte) 0x48, (byte) 0x85, (byte) 0xc0, (byte) 0x74, 259 | (byte) 0x23, (byte) 0x49, (byte) 0x89, (byte) 0xc6, (byte) 0x48, (byte) 0x8d, 260 | (byte) 0x05, (byte) 0x63, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x48, 261 | (byte) 0x8d, (byte) 0x35, (byte) 0x6c, (byte) 0x00, (byte) 0x00, (byte) 0x00, 262 | (byte) 0x4c, (byte) 0x89, (byte) 0xf7, (byte) 0x31, (byte) 0xd2, (byte) 0x31, 263 | (byte) 0xc9, (byte) 0xff, (byte) 0x10, (byte) 0xeb, (byte) 0xa0, (byte) 0xbb, 264 | (byte) 0x06, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0xeb, (byte) 0x1f, 265 | (byte) 0x48, (byte) 0x8d, (byte) 0x05, (byte) 0x4b, (byte) 0x00, (byte) 0x00, 266 | (byte) 0x00, (byte) 0x48, (byte) 0x8b, (byte) 0x08, (byte) 0x48, (byte) 0x85, 267 | (byte) 0xc9, (byte) 0x74, (byte) 0x0b, (byte) 0x31, (byte) 0xc0, (byte) 0xff, 268 | (byte) 0xd1, (byte) 0x48, (byte) 0x85, (byte) 0xc0, (byte) 0x48, (byte) 0x0f, 269 | (byte) 0x45, (byte) 0xd8, (byte) 0x48, (byte) 0x0f, (byte) 0xba, (byte) 0xeb, 270 | (byte) 0x3c, (byte) 0x48, (byte) 0x89, (byte) 0xd8, (byte) 0x48, (byte) 0x83, 271 | (byte) 0xc4, (byte) 0x08, (byte) 0x5b, (byte) 0x41, (byte) 0x5e, (byte) 0xc3, 272 | }; 273 | code = shellcode; 274 | length = shellcode.length; 275 | nativeBridgeFunctions = getNativeBridgeFunctions(); 276 | } 277 | case "riscv64" -> { 278 | char[] shellcode = { 279 | 0x7179, 0xf406, 0xf022, 0xec26, 0xe84a, 0x1597, 0x0000, 0xb583, 0x2c65, 0x6190, 280 | 0x892a, 0x0517, 0x0000, 0x0513, 0x1ea5, 0x4589, 0x9602, 0xc915, 0x84aa, 0x1517, 281 | 0x0000, 0x3503, 0x2b25, 0x6110, 0x0517, 0x0000, 0x0593, 0x0625, 0x8526, 0x9602, 282 | 0xc51d, 0x842a, 0x3503, 0x0009, 0x3603, 0x6d85, 0x002c, 0x854a, 0x9602, 0x6522, 283 | 0x85a6, 0x9402, 0xa829, 0x1517, 0x0000, 0x3503, 0x28a5, 0x6108, 0x9502, 0x4585, 284 | 0x15f2, 0x8d4d, 0xa019, 0x6541, 0x2519, 0x70a2, 0x7402, 0x64e2, 0x6942, 0x6145, 285 | 0x8082, 286 | }; 287 | code = shellcode; 288 | length = shellcode.length * 2; 289 | } 290 | case "arm" -> { 291 | int[] shellcode = { 292 | 0xe92d48fc, 0xe28db018, 0xe59f2084, 0xe1a05000, 0xe3a01000, 0xe3a04000, 293 | 0xe28f0e1e, 0xe12fff32, 0xe3500000, 0x0a000014, 0xe1a06000, 0xe59f2064, 294 | 0xe1a00006, 0xe28f1064, 0xe12fff32, 0xe3500000, 0x0a00000a, 0xe1a07000, 295 | 0xe5950000, 0xe28d1004, 0xe590236c, 0xe1a00005, 0xe12fff32, 0xe59d0004, 296 | 0xe1a01006, 0xe12fff37, 0xe1a04fc0, 0xea000005, 0xe59f0000, 0xea000003, 297 | 0x00010006, 0xe59f0018, 0xe12fff30, 0xe3a04201, 0xe1a01004, 0xe24bd010, 298 | 0xe8bd88f0, 299 | }; 300 | code = shellcode; 301 | length = shellcode.length * 4; 302 | } 303 | case "x86" -> { 304 | byte[] shellcode = { 305 | (byte) 0x55, (byte) 0x89, (byte) 0xe5, (byte) 0x53, (byte) 0x57, (byte) 0x56, 306 | (byte) 0x83, (byte) 0xe4, (byte) 0xf0, (byte) 0x83, (byte) 0xec, (byte) 0x10, 307 | (byte) 0xe8, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x5b, 308 | (byte) 0x81, (byte) 0xc3, (byte) 0x3b, (byte) 0x12, (byte) 0x00, (byte) 0x00, 309 | (byte) 0x8d, (byte) 0x45, (byte) 0x08, (byte) 0x8b, (byte) 0x08, (byte) 0x8b, 310 | (byte) 0x11, (byte) 0x83, (byte) 0xec, (byte) 0x08, (byte) 0x50, (byte) 0x51, 311 | (byte) 0xff, (byte) 0x92, (byte) 0x6c, (byte) 0x03, (byte) 0x00, (byte) 0x00, 312 | (byte) 0x83, (byte) 0xc4, (byte) 0x08, (byte) 0x8d, (byte) 0xb3, (byte) 0xb4, 313 | (byte) 0xef, (byte) 0xff, (byte) 0xff, (byte) 0x6a, (byte) 0x00, (byte) 0x56, 314 | (byte) 0xff, (byte) 0x93, (byte) 0x8e, (byte) 0xee, (byte) 0xff, (byte) 0xff, 315 | (byte) 0x83, (byte) 0xc4, (byte) 0x10, (byte) 0x85, (byte) 0xc0, (byte) 0x74, 316 | (byte) 0x2f, (byte) 0x89, (byte) 0xc7, (byte) 0x83, (byte) 0xec, (byte) 0x08, 317 | (byte) 0x8d, (byte) 0x83, (byte) 0xa6, (byte) 0xee, (byte) 0xff, (byte) 0xff, 318 | (byte) 0x50, (byte) 0x57, (byte) 0xff, (byte) 0x93, (byte) 0x92, (byte) 0xee, 319 | (byte) 0xff, (byte) 0xff, (byte) 0x83, (byte) 0xc4, (byte) 0x10, (byte) 0x85, 320 | (byte) 0xc0, (byte) 0x74, (byte) 0x50, (byte) 0x83, (byte) 0xec, (byte) 0x08, 321 | (byte) 0x57, (byte) 0xff, (byte) 0x75, (byte) 0x08, (byte) 0xff, (byte) 0xd0, 322 | (byte) 0x83, (byte) 0xc4, (byte) 0x10, (byte) 0x89, (byte) 0xc7, (byte) 0x89, 323 | (byte) 0xc2, (byte) 0xc1, (byte) 0xfa, (byte) 0x1f, (byte) 0xeb, (byte) 0x5e, 324 | (byte) 0xff, (byte) 0x93, (byte) 0x96, (byte) 0xee, (byte) 0xff, (byte) 0xff, 325 | (byte) 0x89, (byte) 0xc7, (byte) 0x8b, (byte) 0x83, (byte) 0x9a, (byte) 0xee, 326 | (byte) 0xff, (byte) 0xff, (byte) 0x85, (byte) 0xc0, (byte) 0x74, (byte) 0x47, 327 | (byte) 0x89, (byte) 0x7c, (byte) 0x24, (byte) 0x08, (byte) 0x83, (byte) 0xec, 328 | (byte) 0x08, (byte) 0x6a, (byte) 0x00, (byte) 0x56, (byte) 0xff, (byte) 0xd0, 329 | (byte) 0x83, (byte) 0xc4, (byte) 0x10, (byte) 0x85, (byte) 0xc0, (byte) 0x74, 330 | (byte) 0x1f, (byte) 0x89, (byte) 0xc7, (byte) 0x8d, (byte) 0x83, (byte) 0xa6, 331 | (byte) 0xee, (byte) 0xff, (byte) 0xff, (byte) 0x6a, (byte) 0x00, (byte) 0x6a, 332 | (byte) 0x00, (byte) 0x50, (byte) 0x57, (byte) 0xff, (byte) 0x93, (byte) 0x9e, 333 | (byte) 0xee, (byte) 0xff, (byte) 0xff, (byte) 0xeb, (byte) 0xa9, (byte) 0x31, 334 | (byte) 0xd2, (byte) 0xbf, (byte) 0x06, (byte) 0x00, (byte) 0x01, (byte) 0x00, 335 | (byte) 0xeb, (byte) 0x1a, (byte) 0x8b, (byte) 0x83, (byte) 0xa2, (byte) 0xee, 336 | (byte) 0xff, (byte) 0xff, (byte) 0x85, (byte) 0xc0, (byte) 0x8b, (byte) 0x7c, 337 | (byte) 0x24, (byte) 0x08, (byte) 0x74, (byte) 0x07, (byte) 0xff, (byte) 0xd0, 338 | (byte) 0x85, (byte) 0xc0, (byte) 0x0f, (byte) 0x45, (byte) 0xf8, (byte) 0xba, 339 | (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x10, (byte) 0x89, (byte) 0xf8, 340 | (byte) 0x8d, (byte) 0x65, (byte) 0xf4, (byte) 0x5e, (byte) 0x5f, (byte) 0x5b, 341 | (byte) 0x5d, (byte) 0xc3, 342 | }; 343 | code = shellcode; 344 | length = shellcode.length; 345 | nativeBridgeFunctions = getNativeBridgeFunctions(); 346 | } 347 | default -> throw new RuntimeException(arch + " is unsupported"); 348 | } 349 | 350 | var u = theUnsafe; 351 | copyMemory(code, mem, length); 352 | if (u.addressSize() == 8) { 353 | u.putLong(mem += length, dlopen); 354 | u.putLong(mem += 8, dlsym); 355 | u.putLong(mem += 8, dlerror); 356 | if (nativeBridgeFunctions != null) { 357 | u.putLong(mem += 8, nativeBridgeFunctions[0]); 358 | u.putLong(mem += 8, nativeBridgeFunctions[1]); 359 | u.putLong(mem += 8, nativeBridgeFunctions[2]); 360 | } 361 | mem += 8; 362 | } else { 363 | u.putInt(mem += length, (int) dlopen); 364 | u.putInt(mem += 4, (int) dlsym); 365 | u.putInt(mem += 4, (int) dlerror); 366 | if (nativeBridgeFunctions != null) { 367 | u.putInt(mem += 4, (int) nativeBridgeFunctions[0]); 368 | u.putInt(mem += 4, (int) nativeBridgeFunctions[1]); 369 | u.putInt(mem += 4, (int) nativeBridgeFunctions[2]); 370 | } 371 | mem += 4; 372 | } 373 | 374 | putString(mem, "JNI_OnLoad"); 375 | } 376 | 377 | private boolean ensureInitialized() { 378 | if (mmapAddress != 0) return true; 379 | try { 380 | var u = theUnsafe; 381 | var mem = mmapAddress = Os.mmap(0, u.pageSize(), 0x7, 0x22, FileDescriptor.in, 0); 382 | registerNative(nativeMethod, mem); 383 | 384 | var arch = ApiBridge.VMRuntime_vmInstructionSet(); 385 | var is64Bit = u.addressSize() == 8; 386 | var hasMemoryElfSupport = "arm64".equals(arch); 387 | var dl = new ElfImg(is64Bit ? "/system/lib64/libdl.so" : "/system/lib/libdl.so"); 388 | 389 | long dlopen, dlsym, dlerror; 390 | 391 | if (dl.isEmpty()) { 392 | // sdk < 26 393 | var linker = 394 | new ElfImg(is64Bit ? "/system/bin/linker64" : "/system/bin/linker", true); 395 | if (hasMemoryElfSupport) { 396 | dlopen = linker.getSymbolAddressBestMatch("android_dlopen_ext"); 397 | } else { 398 | dlopen = linker.getSymbolAddress("__dl_dlopen"); 399 | if (dlopen == 0) { 400 | dlopen = linker.getSymbolAddressBestMatch("8__dlopen"); 401 | } 402 | } 403 | if (dlopen == 0) { 404 | throw new UnsupportedOperationException("dlopen not found in linker"); 405 | } 406 | dlsym = linker.getSymbolAddress("__dl_dlsym"); 407 | if (dlsym == 0) { 408 | dlsym = linker.getSymbolAddressBestMatch("7__dlsym"); 409 | } 410 | if (dlsym == 0) { 411 | throw new UnsupportedOperationException("dlsym not found in linker"); 412 | } 413 | dlerror = linker.getSymbolAddress("__dl_dlerror"); 414 | if (dlerror == 0) { 415 | dlerror = linker.getSymbolAddressBestMatch("9__dlerror"); 416 | } 417 | } else { 418 | dlopen = dl.getSymbolAddress(hasMemoryElfSupport ? "android_dlopen_ext" : "dlopen"); 419 | if (dlopen == 0) { 420 | throw new UnsupportedOperationException("dlopen not found in libdl.so"); 421 | } 422 | dlsym = dl.getSymbolAddress("dlsym"); 423 | if (dlsym == 0) { 424 | throw new UnsupportedOperationException("dlsym not found in libdl.so"); 425 | } 426 | dlerror = dl.getSymbolAddress("dlerror"); 427 | } 428 | 429 | initTrampoline(mem, arch, dlopen, dlsym, dlerror); 430 | return true; 431 | } catch (ErrnoException ignored) { 432 | } 433 | return false; 434 | } 435 | 436 | public boolean load(String path) { 437 | if (!ensureInitialized() || path.length() >= 0x1000 - SHELLCODE_SIZE) return false; 438 | putString(mmapAddress + SHELLCODE_SIZE, path); 439 | var result = callNativeMethod(); 440 | var msg = 441 | result >>> 56 != 0x10 442 | ? getJniReturnedMessage(path, (int) result) 443 | : toJavaString(result & ((1L << 56) - 1)); 444 | if (msg != null) { 445 | throw new UnsatisfiedLinkError(msg); 446 | } 447 | return true; 448 | } 449 | 450 | public boolean load(byte[] elf) { 451 | return load(elf, 0, elf.length, null); 452 | } 453 | 454 | public boolean load(byte[] elf, String libraryId) { 455 | return load(elf, 0, elf.length, libraryId); 456 | } 457 | 458 | public boolean load(byte[] elf, int off, int len, String libraryId) { 459 | // TODO: sdk < 30 support 460 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { 461 | throw new UnsupportedOperationException("memfd not available"); 462 | } 463 | 464 | // TODO: Supports more architectures 465 | if (!"arm64".equals(ApiBridge.VMRuntime_vmInstructionSet())) { 466 | throw new UnsupportedOperationException("Function not implemented"); 467 | } 468 | 469 | if (libraryId == null) { 470 | var random = new Random(); 471 | char[] chars = new char[16]; 472 | for (int i = 0; i < chars.length; i++) { 473 | chars[i] = (char) ('a' + random.nextInt(26)); 474 | } 475 | libraryId = new String(chars); 476 | } 477 | 478 | if (!ensureInitialized() || libraryId.length() >= 0x1000 - SHELLCODE_SIZE) return false; 479 | 480 | FileDescriptor fd; 481 | try { 482 | fd = Os.memfd_create(libraryId, 0); 483 | Os.write(fd, elf, off, len); 484 | } catch (ErrnoException | InterruptedIOException e) { 485 | throw new RuntimeException(e); 486 | } 487 | 488 | String libraryName; 489 | if (libraryFdOffset != 0) { 490 | // aarch64 491 | libraryName = libraryId; 492 | theUnsafe.putInt(mmapAddress + libraryFdOffset, getFdInt(fd)); 493 | } else { 494 | libraryName = "/proc/self/fd/" + getFdInt(fd); 495 | } 496 | putString(mmapAddress + SHELLCODE_SIZE, libraryName); 497 | 498 | long result; 499 | 500 | try { 501 | result = callNativeMethod(); 502 | } finally { 503 | if (libraryFdOffset != 0) { 504 | theUnsafe.putInt(mmapAddress + libraryFdOffset, 0); 505 | } 506 | try { 507 | Os.close(fd); 508 | } catch (ErrnoException ignored) { 509 | } 510 | } 511 | 512 | var msg = 513 | result >>> 56 != 0x10 514 | ? getJniReturnedMessage(libraryId, (int) result) 515 | : toJavaString(result & ((1L << 56) - 1)); 516 | if (msg != null) { 517 | throw new UnsatisfiedLinkError(msg); 518 | } 519 | return true; 520 | } 521 | 522 | public void release() { 523 | if (mmapAddress == 0) return; 524 | try { 525 | Os.munmap(mmapAddress, theUnsafe.pageSize()); 526 | } catch (ErrnoException ignored) { 527 | } 528 | mmapAddress = 0; 529 | instance = null; 530 | } 531 | } 532 | -------------------------------------------------------------------------------- /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. For more details, visit 12 | # https://developer.android.com/r/tools/gradle-multi-project-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 | # Kotlin code style for this project: "official" or "obsolete": 19 | kotlin.code.style=official 20 | # Enables namespacing of each library's R class so that its R class includes only the 21 | # resources declared in the library itself and none from the library's dependencies, 22 | # thereby reducing the size of the R class for that library 23 | android.nonTransitiveRClass=true -------------------------------------------------------------------------------- /gradle/libs.versions.toml: -------------------------------------------------------------------------------- 1 | [versions] 2 | agp = "8.6.1" 3 | 4 | [libraries] 5 | 6 | [plugins] 7 | androidApplication = { id = "com.android.application", version.ref = "agp" } 8 | androidLibrary = { id = "com.android.library", version.ref = "agp" } 9 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eirv/ElfLoader/25e022867c88601bbed4e96aea2f6271383eed31/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sat Apr 20 21:27:34 CST 2024 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | distributionUrl=https\://mirrors.cloud.tencent.com/gradle/gradle-8.10.2-bin.zip 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original 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 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s 90 | ' "$PWD" ) || exit 91 | 92 | # Use the maximum available, or set MAX_FD != -1 to use that value. 93 | MAX_FD=maximum 94 | 95 | warn () { 96 | echo "$*" 97 | } >&2 98 | 99 | die () { 100 | echo 101 | echo "$*" 102 | echo 103 | exit 1 104 | } >&2 105 | 106 | # OS specific support (must be 'true' or 'false'). 107 | cygwin=false 108 | msys=false 109 | darwin=false 110 | nonstop=false 111 | case "$( uname )" in #( 112 | CYGWIN* ) cygwin=true ;; #( 113 | Darwin* ) darwin=true ;; #( 114 | MSYS* | MINGW* ) msys=true ;; #( 115 | NONSTOP* ) nonstop=true ;; 116 | esac 117 | 118 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 119 | 120 | 121 | # Determine the Java command to use to start the JVM. 122 | if [ -n "$JAVA_HOME" ] ; then 123 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 124 | # IBM's JDK on AIX uses strange locations for the executables 125 | JAVACMD=$JAVA_HOME/jre/sh/java 126 | else 127 | JAVACMD=$JAVA_HOME/bin/java 128 | fi 129 | if [ ! -x "$JAVACMD" ] ; then 130 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 131 | 132 | Please set the JAVA_HOME variable in your environment to match the 133 | location of your Java installation." 134 | fi 135 | else 136 | JAVACMD=java 137 | if ! command -v java >/dev/null 2>&1 138 | then 139 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 140 | 141 | Please set the JAVA_HOME variable in your environment to match the 142 | location of your Java installation." 143 | fi 144 | fi 145 | 146 | # Increase the maximum file descriptors if we can. 147 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 148 | case $MAX_FD in #( 149 | max*) 150 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 151 | # shellcheck disable=SC2039,SC3045 152 | MAX_FD=$( ulimit -H -n ) || 153 | warn "Could not query maximum file descriptor limit" 154 | esac 155 | case $MAX_FD in #( 156 | '' | soft) :;; #( 157 | *) 158 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 159 | # shellcheck disable=SC2039,SC3045 160 | ulimit -n "$MAX_FD" || 161 | warn "Could not set maximum file descriptor limit to $MAX_FD" 162 | esac 163 | fi 164 | 165 | # Collect all arguments for the java command, stacking in reverse order: 166 | # * args from the command line 167 | # * the main class name 168 | # * -classpath 169 | # * -D...appname settings 170 | # * --module-path (only if needed) 171 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 172 | 173 | # For Cygwin or MSYS, switch paths to Windows format before running java 174 | if "$cygwin" || "$msys" ; then 175 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 176 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 177 | 178 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 179 | 180 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 181 | for arg do 182 | if 183 | case $arg in #( 184 | -*) false ;; # don't mess with options #( 185 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 186 | [ -e "$t" ] ;; #( 187 | *) false ;; 188 | esac 189 | then 190 | arg=$( cygpath --path --ignore --mixed "$arg" ) 191 | fi 192 | # Roll the args list around exactly as many times as the number of 193 | # args, so each arg winds up back in the position where it started, but 194 | # possibly modified. 195 | # 196 | # NB: a `for` loop captures its iteration list before it begins, so 197 | # changing the positional parameters here affects neither the number of 198 | # iterations, nor the values presented in `arg`. 199 | shift # remove old arg 200 | set -- "$@" "$arg" # push replacement arg 201 | done 202 | fi 203 | 204 | 205 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 206 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 207 | 208 | # Collect all arguments for the java command: 209 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 210 | # and any embedded shellness will be escaped. 211 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 212 | # treated as '${Hostname}' itself on the command line. 213 | 214 | set -- \ 215 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 216 | -classpath "$CLASSPATH" \ 217 | org.gradle.wrapper.GradleWrapperMain \ 218 | "$@" 219 | 220 | # Stop when "xargs" is not available. 221 | if ! command -v xargs >/dev/null 2>&1 222 | then 223 | die "xargs is not available" 224 | fi 225 | 226 | # Use "xargs" to parse quoted args. 227 | # 228 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 229 | # 230 | # In Bash we could simply go: 231 | # 232 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 233 | # set -- "${ARGS[@]}" "$@" 234 | # 235 | # but POSIX shell has neither arrays nor command substitution, so instead we 236 | # post-process each arg (as a line of input to sed) to backslash-escape any 237 | # character that might be a shell metacharacter, then use eval to reverse 238 | # that process (while maintaining the separation between arguments), and wrap 239 | # the whole thing up as a single "set" statement. 240 | # 241 | # This will of course break if any of these variables contains a newline or 242 | # an unmatched quote. 243 | # 244 | 245 | eval "set -- $( 246 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 247 | xargs -n1 | 248 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 249 | tr '\n' ' ' 250 | )" '"$@"' 251 | 252 | exec "$JAVACMD" "$@" 253 | -------------------------------------------------------------------------------- /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 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 78 | 79 | :end 80 | @rem End local scope for the variables with windows NT shell 81 | if %ERRORLEVEL% equ 0 goto mainEnd 82 | 83 | :fail 84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 85 | rem the _cmd.exe /c_ return code! 86 | set EXIT_CODE=%ERRORLEVEL% 87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 89 | exit /b %EXIT_CODE% 90 | 91 | :mainEnd 92 | if "%OS%"=="Windows_NT" endlocal 93 | 94 | :omega 95 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | maven { url 'https://maven.aliyun.com/repository/public/' } 4 | maven { url 'https://maven.aliyun.com/repository/google/' } 5 | maven { url 'https://maven.aliyun.com/repository/gradle-plugin/' } 6 | google { 7 | content { 8 | includeGroupByRegex("com\\.android.*") 9 | includeGroupByRegex("com\\.google.*") 10 | includeGroupByRegex("androidx.*") 11 | } 12 | } 13 | mavenCentral() 14 | gradlePluginPortal() 15 | } 16 | } 17 | dependencyResolutionManagement { 18 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) 19 | repositories { 20 | maven { url 'https://maven.aliyun.com/repository/public/' } 21 | maven { url 'https://maven.aliyun.com/repository/google/' } 22 | google() 23 | mavenCentral() 24 | } 25 | } 26 | 27 | rootProject.name = "ElfLoader" 28 | include ':app' 29 | include ':elfloader' 30 | include ':stub' 31 | include ':stub:apibridge' 32 | -------------------------------------------------------------------------------- /stub/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /stub/apibridge/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /stub/apibridge/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java-library' 3 | } 4 | 5 | java { 6 | sourceCompatibility = rootProject.ext.java 7 | targetCompatibility = rootProject.ext.java 8 | } 9 | 10 | dependencies { 11 | compileOnly(project(':stub')) 12 | } 13 | -------------------------------------------------------------------------------- /stub/apibridge/src/main/java/io/github/eirv/elfloader/ApiBridge.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2024 Eirv 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.github.eirv.elfloader; 18 | 19 | import dalvik.system.VMRuntime; 20 | 21 | final class ApiBridge { 22 | public static Class VMRuntime_class() { 23 | return VMRuntime.class; 24 | } 25 | 26 | public static Object VMRuntime_getRuntime() { 27 | return VMRuntime.getRuntime(); 28 | } 29 | 30 | public static String VMRuntime_vmInstructionSet() { 31 | return VMRuntime.getRuntime().vmInstructionSet(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /stub/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java-library' 3 | } 4 | 5 | java { 6 | sourceCompatibility = JavaVersion.VERSION_1_8 7 | targetCompatibility = JavaVersion.VERSION_1_8 8 | } 9 | 10 | dependencies { 11 | compileOnly files("${System.env.ANDROID_HOME}/platforms/android-${rootProject.ext.compileSdk}/android.jar") 12 | } 13 | -------------------------------------------------------------------------------- /stub/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /stub/src/main/java/dalvik/system/VMRuntime.java: -------------------------------------------------------------------------------- 1 | package dalvik.system; 2 | 3 | @SuppressWarnings("ALL") 4 | public class VMRuntime { 5 | public static native VMRuntime getRuntime(); 6 | 7 | public native String vmInstructionSet(); 8 | 9 | public native void setHiddenApiExemptions(String... signaturePrefixes); 10 | } 11 | -------------------------------------------------------------------------------- /stub/src/main/java/sun/misc/Unsafe.java: -------------------------------------------------------------------------------- 1 | package sun.misc; 2 | 3 | @SuppressWarnings("ALL") 4 | public final class Unsafe { 5 | private static final Unsafe theUnsafe = new Unsafe(); 6 | 7 | public int arrayBaseOffset(Class clazz) { 8 | throw new RuntimeException("Stub!"); 9 | } 10 | 11 | public native int addressSize(); 12 | 13 | public native int pageSize(); 14 | 15 | public native void putByte(long address, byte x); 16 | 17 | public native int getInt(long address); 18 | 19 | public native int getInt(Object obj, long offset); 20 | 21 | public native void putInt(long address, int x); 22 | 23 | public native long getLong(long address); 24 | 25 | public native long getLong(Object obj, long offset); 26 | 27 | public native void putLong(long address, long x); 28 | 29 | public native void putLong(Object obj, long offset, long x); 30 | 31 | public native void copyMemoryToPrimitiveArray(long srcAddr, Object dst, long dstOffset, long bytes); 32 | 33 | public native void copyMemoryFromPrimitiveArray(Object src, long srcOffset, long dstAddr, long bytes); 34 | 35 | public native void copyMemory(long srcAddr, long dstAddr, long bytes); 36 | } 37 | --------------------------------------------------------------------------------