mirror of
https://github.com/xiaozhou233/JuiceAgent.git
synced 2026-12-05 13:05:53 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a8c2496292 | ||
|
|
94d881fe63 | ||
|
|
d98e3e818e | ||
|
|
58f76009e4 | ||
|
|
64ca48dfc8 | ||
|
|
4ef94b5ac2 | ||
|
|
339b68c8af | ||
|
|
623445aa5e | ||
|
|
cacdb6a1cd | ||
|
|
f5a6564fd0 | ||
|
|
338f4eb50c | ||
|
|
9b5f29eee4 | ||
|
|
797cf8aed9 |
No files matched your search
@@ -7,33 +7,38 @@ JuiceAgent — a JVMTI-based injection library for loading external JARs and tra
|
||||
**NOTICE:** Currently only supports **Windows**, and plans to support **Linux** in the future.
|
||||
|
||||
**WARNING:** This project is still in the experimental stage and is not recommended for production use.
|
||||
**Disclaimer: This project is for learning and research in controlled environments only. The author is not responsible for any illegal or unauthorized use. Users must ensure their actions are legal. (See Full Disclaimer below)**
|
||||
***免责声明: 本项目仅供受控环境下的学习和研究使用。作者不对任何非法或未授权的使用承担责任。使用者应确保自己的行为合法。(在下方查看完整免责声明)***
|
||||
**Use this at your own risk.**
|
||||
|
||||
## Summary
|
||||
JuiceAgent is a JVMTI-native injection framework that injects native code into a target JVM to dynamically load external JARs and perform bytecode redefinition/transformations without requiring a javaagent (works when DisableAttachMechanism=true).
|
||||
## Features
|
||||
### Injector (src/injector)
|
||||
Reflective injector, can be invoke in java (java/InjectorNative.java)
|
||||
- Inject Dlls. (with no params)
|
||||
- Inject JuiceAgent library. (with params)
|
||||
### JuiceAgent (src/libagent)
|
||||
Low-level injection implementation for loading JuiceLoader
|
||||
- Initialize JuiceLoader
|
||||
- Lightweight Library (No Javaagent)
|
||||
- Read Config File and Load JARs
|
||||
- Invoke JuiceLoader Bootstrap API
|
||||
|
||||
### JuiceAgent (src/agent)
|
||||
Minimize loading, inject to target jvm.
|
||||
- Get JVM / JNI / JVMTI
|
||||
- Inject bootstrap-api.jar
|
||||
- Inject JuiceLoader.jar
|
||||
- Invoke Java Function JuiceLoader init
|
||||
### libinjector (src/libinjector)
|
||||
Injector, supporting **ReflectiveDLLInjection** and CreateRemoteThread Inject.
|
||||
- Provides JNI functions for injecting DLLs into target processes
|
||||
- Get PID by process name
|
||||
|
||||
### JuiceLoader Native (src/juiceloader)
|
||||
Native library for [JuiceLoader](https://github.com/xiaozhou233/JuiceLoader) , Inject Jars/ Redefine class Low-level implementation.
|
||||
- Get JVM / JNI / JVMTI
|
||||
- Inject Custom Jars
|
||||
- Redefine class
|
||||
- Get Loaded Classes
|
||||
- JNI Function (Can be invoke in java)
|
||||
## How To Use
|
||||
***TODO: Update How to Use***
|
||||
***Notice: Tutorial for Version 1.0***
|
||||
- Implements JuiceLoader's native API
|
||||
- init
|
||||
- injectJar
|
||||
- redefineClass (redefineClassByName)
|
||||
- retransformClass (retransformClassByName)
|
||||
- getLoadedClasses
|
||||
- getClassBytes (getClassBytesByName)
|
||||
- getClassByName
|
||||
- AddToBootstrapClassLoaderSearch
|
||||
- AddToSystemClassLoaderSearch
|
||||
- nativeGetThreadByName* (test function, myself-use)
|
||||
- nativeInjectJarToThread (test function, myself-use)
|
||||
## How To Use (For Version 2.3 Build 1)
|
||||
|
||||
### 1. Download Files
|
||||
- Download `libagent`, `libinjector`, and `libjuiceloader` from the Release to the same directory.
|
||||
@@ -43,19 +48,25 @@ JuiceAgent is a JVMTI-native injection framework that injects native code into a
|
||||
Create a config file named `AgentConfig.toml` in the same directory. Example:
|
||||
|
||||
```toml
|
||||
[Injection]
|
||||
BootstrapAPIPath = "<YourDir>/bootstrap-api.jar"
|
||||
JuiceLoaderJarPath = "<YourDir>/JuiceLoader.jar"
|
||||
# Leave empty to use the DLL directory (Normal Inject) or the directory passed as parameter (Reflective Inject)
|
||||
JuiceLoaderLibPath = ""
|
||||
EntryJarPath = "<YourDir>/Entry.jar"
|
||||
EntryClass = "entry.class"
|
||||
EntryMethod = "entryMethod"
|
||||
# Leave empty to use default values
|
||||
# Default values: <Current Directory>/default-name
|
||||
|
||||
# Example: JuiceLoaderJarPath = "D:\\Development\\JuiceSky\\build\\libs\\JuiceLoader-1.0.jar"
|
||||
# Default: <Current Directory>/JuiceLoader.jar
|
||||
JuiceLoaderJarPath = ""
|
||||
# Default: <Current Directory>/libjuiceloader.dll
|
||||
JuiceLoaderLibraryPath = ""
|
||||
# Default: <Current Directory>/injection/
|
||||
InjectionDir = ""
|
||||
# Default: <Current Directory>/Entry.jar
|
||||
EntryJarPath = "D:\\Development\\JuiceSky\\build\\libs\\JuiceSky-1.0-Hooked.jar"
|
||||
EntryClass = "cn.xiaozhou233.juicesky.LoaderEntry"
|
||||
EntryMethod = "start"
|
||||
```
|
||||
| Method| Usage|
|
||||
| - | -|
|
||||
| **Reflective Inject** | Uses `libinjector`. Pass the config directory as a parameter. </br> Example: config file at `<YourDir>/AgentConfig.toml`, pass `<YourDir>` as parameter. If a key is empty (e.g., `BootstrapAPIPath = ""`), it defaults to `<DirA>/default-name` (e.g., `<DirA>/bootstrap-api.jar`). |
|
||||
| **Normal Inject** | Uses `LoadLibraryA + CreateRemoteThread`. Keep `AgentConfig.toml` and all DLLs/JARs in the same directory.
|
||||
| **Reflective Inject** | Uses `libinjector`. Pass the config directory as a parameter. </br></br> Example: config file at `<YourDir>/AgentConfig.toml`, </br></br>pass `<YourDir>` as parameter.</br></br> Example:</br>`C/C++: libinjector.dll -> inject(pid, agentpath, configpath)`</br>`Java: See 3. Invoke Inject Function`|
|
||||
| **Normal Inject** | Uses `LoadLibraryA + CreateRemoteThread`. Keep `AgentConfig.toml` and all DLLs/JARs in the same directory.</br>
|
||||
|
||||
### 3. Invoke Inject Function
|
||||
C/C++ Use libinjector and invoke inject(int pid, char* path, InjectParameters *params)
|
||||
@@ -115,6 +126,6 @@ Disclaimer: This project is intended for learning and research in controlled env
|
||||
## Acknowledgements
|
||||
|
||||
- [ReflectiveDLLInjection](https://github.com/stephenfewer/ReflectiveDLLInjection) - DLL Inject
|
||||
- [log.c](https://github.com/rxi/log.c) - A simple logger system
|
||||
- [tomlc17](https://github.com/cktan/tomlc17) - TOML parser in C17
|
||||
- [plog](https://github.com/SergiusTheBest/plog) - portable, simple and extensible C++ logging library
|
||||
- [tinytoml](https://github.com/mayah/tinytoml) - A header only C++11 library for parsing TOML.
|
||||
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
# JuiceAgent
|
||||
[English]() | [中文]()
|
||||
|
||||
JuiceAgent —— 一个基于 **JVMTI** 的注入库,用于在 **DisableAttachMechanism 启用的情况下**,向目标 JVM 注入外部 JAR 并对 Java 字节码进行转换。
|
||||
|
||||
**注意:** 当前仅支持 **Windows**,未来计划支持 **Linux**。
|
||||
|
||||
**警告:** 本项目仍处于实验阶段,不建议用于生产环境。
|
||||
**使用风险自负。**
|
||||
|
||||
---
|
||||
|
||||
## 简介(Summary)
|
||||
|
||||
JuiceAgent 是一个基于 **JVMTI 的原生注入框架**,通过向目标 JVM 注入原生代码,实现 **动态加载外部 JAR** 以及 **类重定义 / 类重转换**,并且 **无需使用 javaagent**(即使 `DisableAttachMechanism=true` 也可正常工作)。
|
||||
|
||||
---
|
||||
|
||||
## 特性(Features)
|
||||
|
||||
### JuiceAgent(`src/libagent`)
|
||||
用于加载 JuiceLoader 的底层注入实现:
|
||||
|
||||
- 初始化 JuiceLoader
|
||||
- 轻量级库(无需 Java Agent)
|
||||
- 读取配置文件并加载 JAR
|
||||
- 调用 JuiceLoader Bootstrap API
|
||||
|
||||
---
|
||||
|
||||
### libinjector(`src/libinjector`)
|
||||
注入器模块,支持 **ReflectiveDLLInjection** 与 **CreateRemoteThread** 注入方式:
|
||||
|
||||
- 提供 JNI 接口,用于向目标进程注入 DLL
|
||||
- 支持通过进程名获取 PID
|
||||
|
||||
---
|
||||
|
||||
### JuiceLoader Native(`src/juiceloader`)
|
||||
[JuiceLoader](https://github.com/xiaozhou233/JuiceLoader) 的原生实现,用于 JAR 注入与类重定义的底层支持。
|
||||
|
||||
实现的 Native API 包括:
|
||||
|
||||
- `init`
|
||||
- `injectJar`
|
||||
- `redefineClass`(`redefineClassByName`)
|
||||
- `retransformClass`(`retransformClassByName`)
|
||||
- `getLoadedClasses`
|
||||
- `getClassBytes`(`getClassBytesByName`)
|
||||
- `getClassByName`
|
||||
- `AddToBootstrapClassLoaderSearch`
|
||||
- `AddToSystemClassLoaderSearch`
|
||||
- `nativeGetThreadByName`(测试函数,自用)
|
||||
- `nativeInjectJarToThread`(测试函数,自用)
|
||||
|
||||
---
|
||||
|
||||
## 使用方法(How To Use,Version 2.3 Build 1)
|
||||
|
||||
### 1. 下载文件
|
||||
|
||||
- 从 Release 页面下载 `libagent`、`libinjector`、`libjuiceloader`,并放置在 **同一目录**
|
||||
- 下载以下 JAR 并放置在同一目录:
|
||||
- `bootstrap-api.jar`
|
||||
- `JuiceLoader.jar`
|
||||
- `Entry.jar`(或你自己的 JAR)
|
||||
|
||||
---
|
||||
|
||||
### 2. 编写配置文件
|
||||
|
||||
在同一目录下创建 `AgentConfig.toml`,示例如下:
|
||||
|
||||
```toml
|
||||
# 留空表示使用默认值
|
||||
# 默认值:<当前目录>/default-name
|
||||
|
||||
# 示例:
|
||||
# JuiceLoaderJarPath = "D:\Development\JuiceSky\build\libs\JuiceLoader-1.0.jar"
|
||||
|
||||
# 默认:<当前目录>/JuiceLoader.jar
|
||||
JuiceLoaderJarPath = ""
|
||||
|
||||
# 默认:<当前目录>/libjuiceloader.dll
|
||||
JuiceLoaderLibraryPath = ""
|
||||
|
||||
# 默认:<当前目录>/injection/
|
||||
InjectionDir = ""
|
||||
|
||||
# 默认:<当前目录>/Entry.jar
|
||||
EntryJarPath = "D:\Development\JuiceSky\build\libs\JuiceSky-1.0-Hooked.jar"
|
||||
|
||||
EntryClass = "cn.xiaozhou233.juicesky.LoaderEntry"
|
||||
EntryMethod = "start"
|
||||
```
|
||||
|
||||
#### 注入方式说明
|
||||
|
||||
| 注入方式 | 说明 |
|
||||
|---------|------|
|
||||
| **Reflective 注入** | 使用 `libinjector`,将 **配置文件所在目录** 作为参数传入。<br/><br/>示例:配置文件位于 `<YourDir>/AgentConfig.toml`,则传入 `<YourDir>`。<br/><br/>调用示例:<br/>`C/C++: libinjector.dll -> inject(pid, agentPath, configPath)`<br/>`Java: 见下方步骤` |
|
||||
| **普通注入** | 使用 `LoadLibraryA + CreateRemoteThread`。<br/>要求 `AgentConfig.toml` 与所有 DLL / JAR 位于同一目录 |
|
||||
|
||||
---
|
||||
|
||||
### 3. 调用注入函数
|
||||
|
||||
#### C / C++
|
||||
|
||||
使用 `libinjector`,调用:
|
||||
|
||||
```
|
||||
inject(int pid, char* path, InjectParameters *params)
|
||||
```
|
||||
|
||||
#### Java
|
||||
|
||||
使用 `Injecor.jar`:
|
||||
|
||||
```
|
||||
java -jar Injecor.jar
|
||||
```
|
||||
|
||||
或通过 Native 接口:
|
||||
|
||||
```java
|
||||
package cn.xiaozhou233.juiceagent.injector;
|
||||
|
||||
public class InjectorNative {
|
||||
|
||||
/*
|
||||
* @param pid target process id
|
||||
*/
|
||||
public native boolean inject(int pid, String path);
|
||||
|
||||
/*
|
||||
* @param pid target process id
|
||||
* @param path injection dll path
|
||||
* @param configPath config file path
|
||||
*/
|
||||
public native boolean inject(int pid, String path, String configPath);
|
||||
}
|
||||
```
|
||||
|
||||
使用示例:
|
||||
|
||||
```java
|
||||
import cn.xiaozhou233.juiceagent.injector.InjectorNative;
|
||||
|
||||
System.load("<path-to-libinjector>");
|
||||
InjectorNative injectorNative = new InjectorNative();
|
||||
|
||||
injectorNative.inject(<pid>, "<path-to-libagent>", "<path-to-toml-config-dir>");
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 4. 完成
|
||||
|
||||
如果注入成功,将会执行 `<EntryJarPath>` 中配置的:
|
||||
|
||||
```
|
||||
EntryClass.EntryMethod()
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 构建方式(How To Build)
|
||||
|
||||
### 构建环境
|
||||
|
||||
- Java 8+
|
||||
- MinGW
|
||||
- CMake
|
||||
- Ninja
|
||||
|
||||
```bash
|
||||
git clone https://github.com/xiaozhou233/JuiceAgent.git
|
||||
cd JuiceAgent
|
||||
|
||||
mkdir -p build
|
||||
cmake --build build --
|
||||
```
|
||||
|
||||
- DLL 输出目录:`build/bin/`
|
||||
- JAR 文件:请参考 [JuiceLoader](https://github.com/xiaozhou233/JuiceLoader)
|
||||
|
||||
---
|
||||
|
||||
## 完整免责声明(Full Disclaimer)
|
||||
|
||||
**免责声明(英文):**
|
||||
This project is intended for learning and research in controlled environments only. The author is not responsible for any consequences arising from unauthorized use, modification, cracking, or violation of any applicable agreements or laws. Users are responsible for ensuring their actions are legal and compliant.
|
||||
|
||||
**免责声明(中文):**
|
||||
本项目仅建议在受控环境中用于学习与研究。任何利用本项目实施破解、篡改、未经授权获取源码或其他违反目标协议或法律的行为所导致的一切后果,作者概不负责。使用者应自行确保其行为合法合规,并对相应后果承担全部责任。
|
||||
|
||||
---
|
||||
|
||||
## 致谢(Acknowledgements)
|
||||
|
||||
- [ReflectiveDLLInjection](https://github.com/stephenfewer/ReflectiveDLLInjection) —— DLL 注入实现
|
||||
- [plog](https://github.com/SergiusTheBest/plog) —— 轻量级、可扩展的 C++ 日志库
|
||||
- [tinytoml](https://github.com/mayah/tinytoml) —— 仅头文件的 C++11 TOML 解析库
|
||||
@@ -0,0 +1 @@
|
||||
VERSION = Version 2.3 Build 1
|
||||
@@ -1,10 +1,19 @@
|
||||
file(
|
||||
GLOB_RECURSE
|
||||
libinjector_sources
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/*.c
|
||||
|
||||
# libinject
|
||||
add_library(inject SHARED libinject.c)
|
||||
|
||||
target_include_directories(inject PRIVATE
|
||||
${CMAKE_SOURCE_DIR}/includes
|
||||
${CMAKE_SOURCE_DIR}/includes/jvm
|
||||
${CMAKE_SOURCE_DIR}/includes/jvm/win32
|
||||
)
|
||||
|
||||
add_library(injector SHARED ${libinjector_sources})
|
||||
target_link_libraries(inject PRIVATE
|
||||
ReflectiveDLLInjection
|
||||
)
|
||||
|
||||
# injector
|
||||
add_executable(injector injector.c)
|
||||
|
||||
target_include_directories(injector PRIVATE
|
||||
${CMAKE_SOURCE_DIR}/includes
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
#include <stdio.h>
|
||||
#include <windows.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define MAX_PATH_LEN 4096
|
||||
|
||||
void ExecuteJps(){
|
||||
// Execute "jps -l" and print the output
|
||||
char command[MAX_PATH] = "jps -l";
|
||||
FILE* pipe = _popen(command, "r");
|
||||
if (!pipe) {
|
||||
printf("Error opening pipe!\n");
|
||||
return;
|
||||
}
|
||||
char buffer[128];
|
||||
while (!feof(pipe)) {
|
||||
if (fgets(buffer, 128, pipe) != NULL)
|
||||
printf("%s", buffer);
|
||||
}
|
||||
_pclose(pipe);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
int pid = 0;
|
||||
char dll_path[MAX_PATH_LEN] = {0};
|
||||
char injector_lib_path[MAX_PATH_LEN] = {0};
|
||||
char cwd[MAX_PATH_LEN] = {0};
|
||||
|
||||
/* If user provided pid and dll path as arguments, use them. */
|
||||
if (argc >= 3) {
|
||||
pid = atoi(argv[1]);
|
||||
strncpy(dll_path, argv[2], MAX_PATH_LEN - 1);
|
||||
if (argc >= 4) {
|
||||
strncpy(injector_lib_path, argv[3], MAX_PATH_LEN - 1);
|
||||
}
|
||||
} else {
|
||||
/* Show jps output to help user find JVM PID */
|
||||
ExecuteJps();
|
||||
printf("Input PID: ");
|
||||
if (scanf("%d", &pid) != 1 || pid <= 0) {
|
||||
printf("Invalid PID input.\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Default dll_path = currentdir\\libloader.dll */
|
||||
if (!GetCurrentDirectoryA(MAX_PATH_LEN, cwd)) {
|
||||
printf("Warning: GetCurrentDirectory failed, using '.'\n");
|
||||
strncpy(cwd, ".", MAX_PATH_LEN - 1);
|
||||
}
|
||||
snprintf(dll_path, MAX_PATH_LEN, "%s\\libagent.dll", cwd);
|
||||
printf("Using DLL path: %s\n", dll_path);
|
||||
}
|
||||
|
||||
if (pid <= 0) {
|
||||
printf("Invalid or missing PID.\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Load injector library */
|
||||
HMODULE hLib = NULL;
|
||||
if (injector_lib_path[0] != '\0') {
|
||||
hLib = LoadLibraryA(injector_lib_path);
|
||||
if (!hLib) {
|
||||
printf("[-] Failed to load injector library: %s (Error=%lu)\n", injector_lib_path, GetLastError());
|
||||
return 2;
|
||||
}
|
||||
} else {
|
||||
/* Try to load by name from current dir / PATH */
|
||||
hLib = LoadLibraryA("libinject.dll");
|
||||
if (!hLib) {
|
||||
printf("[-] Failed to load libinjector.dll by name (Error=%lu).\n", GetLastError());
|
||||
printf(" Provide full path as the 3rd argument if needed.\n");
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
printf("[+] Loaded injector library.\n");
|
||||
|
||||
/* Define function pointer type (cdecl) - match the DLL export */
|
||||
typedef int (__cdecl *inject_fn_t)(int, const char*, void*);
|
||||
|
||||
/* GetProcAddress for 'inject' */
|
||||
FARPROC proc = GetProcAddress(hLib, "inject");
|
||||
if (!proc) {
|
||||
/* Try common alternative name */
|
||||
proc = GetProcAddress(hLib, "Inject");
|
||||
}
|
||||
if (!proc) {
|
||||
printf("[-] GetProcAddress failed for 'inject' (Error=%lu). Make sure your injector exports C symbol 'inject'.\n", GetLastError());
|
||||
FreeLibrary(hLib);
|
||||
return 3;
|
||||
}
|
||||
|
||||
inject_fn_t inject = (inject_fn_t)proc;
|
||||
|
||||
printf("[*] Calling inject(pid=%d, dllPath=\"%s\", currentDir=\"%s\")\n", pid, dll_path, cwd);
|
||||
int ret = inject(pid, dll_path, cwd);
|
||||
|
||||
if (ret == 0) {
|
||||
printf("[+] inject returned success (0)\n");
|
||||
} else {
|
||||
printf("[-] inject returned failure (%d)\n", ret);
|
||||
}
|
||||
|
||||
FreeLibrary(hLib);
|
||||
return (ret == 0) ? 0 : 4;
|
||||
}
|
||||
File renamed without changes.
@@ -3,6 +3,8 @@ file(
|
||||
libjuiceloader_sources
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/*.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/*.c
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/jni/*.c
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/jni/*.cpp
|
||||
)
|
||||
|
||||
add_library(juiceloader SHARED ${libjuiceloader_sources})
|
||||
|
||||
@@ -1,530 +0,0 @@
|
||||
#include <juiceloader.h>
|
||||
#include <cn_xiaozhou233_juiceloader_JuiceLoader.h>
|
||||
#include <jni.h>
|
||||
#include <jvmti.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <JuiceAgent/Logger.hpp>
|
||||
|
||||
RetransformClassCacheType RetransformClassCache = {NULL, 0, 0};
|
||||
|
||||
static const char* g_bytecodes_classname = NULL;
|
||||
static unsigned char* g_bytecodes = NULL;
|
||||
static jint g_bytecodes_len = 0;
|
||||
|
||||
/// ================= Utility ================= ///
|
||||
|
||||
char* get_class_name(JNIEnv* env, jclass clazz) {
|
||||
jclass clsClass = env->FindClass("java/lang/Class");
|
||||
jmethodID mid_getName = env->GetMethodID(clsClass, "getName", "()Ljava/lang/String;");
|
||||
jstring nameStr = (jstring)env->CallObjectMethod(clazz, mid_getName);
|
||||
|
||||
const char* temp = env->GetStringUTFChars(nameStr, NULL);
|
||||
char* result = _strdup(temp);
|
||||
env->ReleaseStringUTFChars(nameStr, temp);
|
||||
env->DeleteLocalRef(nameStr);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Helper: macro to throw RuntimeException with message
|
||||
static void throwRuntimeException(JNIEnv *env, const char *msg) {
|
||||
jclass rte = env->FindClass("java/lang/RuntimeException");
|
||||
if (rte != NULL) {
|
||||
env->ThrowNew(rte, msg);
|
||||
}
|
||||
}
|
||||
|
||||
/// ================= ClassFileLoadHook ================= ///
|
||||
|
||||
void JNICALL ClassFileLoadHook(
|
||||
jvmtiEnv* jvmti_env,
|
||||
JNIEnv* jni_env,
|
||||
jclass class_being_redefined,
|
||||
jobject loader,
|
||||
const char* name,
|
||||
jobject protection_domain,
|
||||
jint class_data_len,
|
||||
const unsigned char* classbytes,
|
||||
jint* new_class_data_len,
|
||||
unsigned char** new_classbytes) {
|
||||
|
||||
// ---- capture class bytes ---- //
|
||||
if (g_bytecodes_classname != NULL && g_bytecodes == NULL) {
|
||||
if (strcmp(name, g_bytecodes_classname) == 0) {
|
||||
g_bytecodes_len = class_data_len;
|
||||
g_bytecodes = (unsigned char*)malloc(class_data_len);
|
||||
memcpy(g_bytecodes, classbytes, class_data_len);
|
||||
|
||||
*new_classbytes = NULL;
|
||||
*new_class_data_len = 0;
|
||||
|
||||
PLOGD.printf("[Hook:get] Captured class bytes of %s, len=%d", name, class_data_len);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- set class bytes from cache ---- //
|
||||
if (RetransformClassCache.size == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < RetransformClassCache.size; i++) {
|
||||
ClassBytesCacheType *entry = &RetransformClassCache.arr[i];
|
||||
if (strcmp(entry->name, name) == 0) {
|
||||
|
||||
unsigned char *newBytes = nullptr;
|
||||
jvmtiError err = jvmti_env->Allocate(entry->len, &newBytes);
|
||||
if (err != JVMTI_ERROR_NONE || newBytes == nullptr) {
|
||||
PLOGE.printf("[Hook:set] jvmti->Allocate failed for class %s, err=%d", name, err);
|
||||
return;
|
||||
}
|
||||
|
||||
memcpy(newBytes, entry->bytes, entry->len);
|
||||
*new_classbytes = newBytes;
|
||||
*new_class_data_len = entry->len;
|
||||
|
||||
PLOGI.printf("[Hook:set] Patched class: %s, new_len=%d", name, entry->len);
|
||||
|
||||
free(entry->name);
|
||||
free(entry->bytes);
|
||||
for (int j = i; j < RetransformClassCache.size - 1; j++) {
|
||||
RetransformClassCache.arr[j] = RetransformClassCache.arr[j + 1];
|
||||
}
|
||||
RetransformClassCache.size--;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// ============ JNI Function ============ ///
|
||||
C_EXPORT
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_init
|
||||
(JNIEnv *env, jclass loader_class) {
|
||||
PLOGI << "Invoked!";
|
||||
|
||||
// Get JavaVM
|
||||
JavaVM* jvm = nullptr;
|
||||
env->GetJavaVM(&jvm);
|
||||
if (jvm == nullptr) {
|
||||
PLOGE << "Failed to get JavaVM instance";
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
// Get JVMTI
|
||||
jvmtiEnv* jvmti = nullptr;
|
||||
jvmtiError err = static_cast<jvmtiError>(jvm->GetEnv(reinterpret_cast<void**>(&jvmti), JVMTI_VERSION_1_2));
|
||||
if (err != JVMTI_ERROR_NONE || jvmti == nullptr) {
|
||||
PLOGE << "Failed to get JVMTI environment, error: " << err;
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
int result = InitJuiceLoader(env, jvmti);
|
||||
if (result != 0) {
|
||||
PLOGE << "Failed to initialize JuiceLoader, error code: " << result;
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
PLOGI << "JuiceLoader initialized successfully";
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
C_EXPORT
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_injectJar
|
||||
(JNIEnv *env, jclass loader_class, jstring jarPath) {
|
||||
PLOGI << "Invoked!";
|
||||
const char *pathStr = env->GetStringUTFChars(jarPath, NULL);
|
||||
if (!pathStr) {
|
||||
PLOGE << "Path is NULL!";
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
if (!JuiceLoaderNative.jvmti) {
|
||||
PLOGE.printf("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
||||
env->ReleaseStringUTFChars(jarPath, pathStr);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
jvmtiError result = JuiceLoaderNative.jvmti->AddToSystemClassLoaderSearch(pathStr);
|
||||
if (result != JVMTI_ERROR_NONE) {
|
||||
PLOGE.printf("Cannot inject jar [result=%d]", result);
|
||||
env->ReleaseStringUTFChars(jarPath, pathStr);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
env->ReleaseStringUTFChars(jarPath, pathStr);
|
||||
PLOGI << "Jar injected: " << pathStr;
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
C_EXPORT
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_redefineClass
|
||||
(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray classBytes, jint length) {
|
||||
PLOGI << "Invoked!";
|
||||
if (!JuiceLoaderNative.jvmti) {
|
||||
PLOGE.printf("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
jbyte* buf = env->GetByteArrayElements(classBytes, NULL);
|
||||
if (!buf) {
|
||||
PLOGE << "Cannot get class bytes";
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
jvmtiClassDefinition defs[1];
|
||||
defs[0].klass = clazz;
|
||||
defs[0].class_byte_count = length;
|
||||
defs[0].class_bytes = reinterpret_cast<const unsigned char*>(buf);
|
||||
|
||||
jvmtiError result = JuiceLoaderNative.jvmti->RedefineClasses(1, defs);
|
||||
env->ReleaseByteArrayElements(classBytes, buf, JNI_ABORT);
|
||||
|
||||
if (result != JVMTI_ERROR_NONE) {
|
||||
PLOGE.printf("Cannot redefine class [result=%d]", result);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
PLOGI.printf("Class redefined successfully!");
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
C_EXPORT
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_redefineClassByName
|
||||
(JNIEnv *env, jclass loader_class, jstring className, jbyteArray classBytes, jint length) {
|
||||
PLOGI << "redefineClass_className Invoked!";
|
||||
if (!JuiceLoaderNative.jvmti) {
|
||||
PLOGE.printf("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
const char* cname = env->GetStringUTFChars(className, NULL);
|
||||
if (!cname) {
|
||||
PLOGE << "Class name is NULL!";
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
jclass clazz = env->FindClass(cname);
|
||||
if (!clazz) {
|
||||
PLOGE.printf("Class not found! [ClassName=%s]", cname);
|
||||
env->ReleaseStringUTFChars(className, cname);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
jboolean ret = Java_cn_xiaozhou233_juiceloader_JuiceLoader_redefineClass(env, loader_class, clazz, classBytes, length);
|
||||
env->ReleaseStringUTFChars(className, cname);
|
||||
return ret;
|
||||
}
|
||||
|
||||
C_EXPORT
|
||||
JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getLoadedClasses
|
||||
(JNIEnv *env, jclass loader_class) {
|
||||
PLOGI << "loader_getLoadedClasses invoked!";
|
||||
|
||||
if (!JuiceLoaderNative.jvmti) {
|
||||
PLOGE << "JuiceLoaderNative.jvmti is NULL!";
|
||||
return NULL;
|
||||
}
|
||||
|
||||
jint count = 0;
|
||||
jclass* classes = NULL;
|
||||
jvmtiError result = JuiceLoaderNative.jvmti->GetLoadedClasses(&count, &classes);
|
||||
if (result != JVMTI_ERROR_NONE || count == 0) {
|
||||
if (classes) JuiceLoaderNative.jvmti->Deallocate((unsigned char*)classes);
|
||||
return env->NewObjectArray(0, env->FindClass("java/lang/Class"), NULL);
|
||||
}
|
||||
|
||||
jclass classClass = env->FindClass("java/lang/Class");
|
||||
jobjectArray classArray = env->NewObjectArray(count, classClass, NULL);
|
||||
|
||||
for (int i = 0; i < count; i++) {
|
||||
env->SetObjectArrayElement(classArray, i, classes[i]);
|
||||
}
|
||||
|
||||
if (classes) JuiceLoaderNative.jvmti->Deallocate((unsigned char*)classes);
|
||||
return classArray;
|
||||
}
|
||||
|
||||
C_EXPORT
|
||||
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytes
|
||||
(JNIEnv *env, jclass loader_class, jclass clazz) {
|
||||
PLOGI << "getClassBytes Invoked!";
|
||||
if (!JuiceLoaderNative.jvmti) {
|
||||
PLOGE << "JuiceLoaderNative.jvmti is NULL!";
|
||||
return NULL;
|
||||
}
|
||||
|
||||
char* className = get_class_name(env, clazz);
|
||||
if (!className) {
|
||||
PLOGE << "Failed to get class name!";
|
||||
return NULL;
|
||||
}
|
||||
|
||||
for (char* p = className; *p; ++p) if (*p == '.') *p = '/';
|
||||
|
||||
g_bytecodes_classname = className;
|
||||
g_bytecodes = NULL;
|
||||
g_bytecodes_len = 0;
|
||||
|
||||
jclass classes[1] = { clazz };
|
||||
jvmtiError err = JuiceLoaderNative.jvmti->RetransformClasses(1, classes);
|
||||
if (err != JVMTI_ERROR_NONE) {
|
||||
PLOGE.printf("RetransformClasses failed: %d", err);
|
||||
free(className);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (!g_bytecodes) {
|
||||
PLOGW.printf("No bytecode captured for class: %s", className);
|
||||
free(className);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
jbyteArray result = env->NewByteArray(g_bytecodes_len);
|
||||
env->SetByteArrayRegion(result, 0, g_bytecodes_len, (jbyte*)g_bytecodes);
|
||||
|
||||
free(g_bytecodes);
|
||||
free(className);
|
||||
g_bytecodes = NULL;
|
||||
g_bytecodes_classname = NULL;
|
||||
g_bytecodes_len = 0;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
C_EXPORT
|
||||
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytesByName
|
||||
(JNIEnv *env, jclass loader_class, jstring className) {
|
||||
PLOGI << "getClassBytesByName Invoked!";
|
||||
if (!JuiceLoaderNative.jvmti) {
|
||||
PLOGE << "JuiceLoaderNative.jvmti is NULL!";
|
||||
return NULL;
|
||||
}
|
||||
|
||||
const char* cname = env->GetStringUTFChars(className, NULL);
|
||||
jclass clazz = env->FindClass(cname);
|
||||
env->ReleaseStringUTFChars(className, cname);
|
||||
|
||||
if (!clazz) {
|
||||
PLOGE.printf("Failed to find class %s", cname);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
return Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytes(env, loader_class, clazz);
|
||||
}
|
||||
|
||||
C_EXPORT
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClass
|
||||
(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray classBytes, jint length) {
|
||||
if (!JuiceLoaderNative.jvmti) {
|
||||
PLOGE << "JuiceLoaderNative.jvmti is NULL! (retransformClass)";
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
const char *name_dot = get_class_name(env, clazz);
|
||||
char* name = _strdup(name_dot);
|
||||
for (char* p = name; *p; ++p) if (*p == '.') *p = '/';
|
||||
|
||||
jbyte* bytes = env->GetByteArrayElements(classBytes, NULL);
|
||||
jint len = env->GetArrayLength(classBytes);
|
||||
|
||||
if (RetransformClassCache.size >= RetransformClassCache.capacity) {
|
||||
int new_capacity = RetransformClassCache.capacity == 0 ? 4 : RetransformClassCache.capacity * 2;
|
||||
RetransformClassCache.arr = (ClassBytesCacheType*)realloc(RetransformClassCache.arr, new_capacity * sizeof(ClassBytesCacheType));
|
||||
RetransformClassCache.capacity = new_capacity;
|
||||
}
|
||||
|
||||
ClassBytesCacheType *entry = &RetransformClassCache.arr[RetransformClassCache.size++];
|
||||
entry->name = _strdup(name);
|
||||
entry->bytes = (unsigned char*)malloc(len);
|
||||
memcpy(entry->bytes, bytes, len);
|
||||
entry->len = len;
|
||||
|
||||
env->ReleaseByteArrayElements(classBytes, bytes, JNI_ABORT);
|
||||
|
||||
jclass classes[1] = { clazz };
|
||||
jvmtiError err = JuiceLoaderNative.jvmti->RetransformClasses(1, classes);
|
||||
if (err != JVMTI_ERROR_NONE) {
|
||||
PLOGE.printf("RetransformClasses failed! [err=%d]", err);
|
||||
free(name);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
PLOGI.printf("[retransformClass] Class retransformed: %s (len=%d)", entry->name, entry->len);
|
||||
free(name);
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
C_EXPORT
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClassByName
|
||||
(JNIEnv *env, jclass loader_class, jstring className, jbyteArray classBytes, jint length) {
|
||||
const char *name_dot = env->GetStringUTFChars(className, NULL);
|
||||
char *name = _strdup(name_dot);
|
||||
for (char *p = name; *p; ++p) if (*p == '.') *p = '/';
|
||||
env->ReleaseStringUTFChars(className, name_dot);
|
||||
|
||||
jclass target = env->FindClass(name);
|
||||
free(name);
|
||||
|
||||
if (!target) {
|
||||
PLOGE << "FindClass failed in retransformClassByName";
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
return Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClass(env, loader_class, target, classBytes, length);
|
||||
}
|
||||
|
||||
C_EXPORT
|
||||
JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassByName
|
||||
(JNIEnv *env, jclass loader_class, jstring className) {
|
||||
|
||||
if (className == NULL) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// jstring -> const char*
|
||||
const char *name_utf = env->GetStringUTFChars(className, NULL);
|
||||
if (name_utf == NULL) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// find class
|
||||
jclass clazz = env->FindClass(name_utf);
|
||||
|
||||
// clean up
|
||||
env->ReleaseStringUTFChars(className, name_utf);
|
||||
|
||||
if (clazz == NULL) {
|
||||
PLOGE.printf("Failed to find class %s", name_utf);
|
||||
}
|
||||
return clazz;
|
||||
}
|
||||
|
||||
// static native Thread getThreadByName(String name)
|
||||
C_EXPORT
|
||||
JNIEXPORT jobject JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_nativeGetThreadByName
|
||||
(JNIEnv* env, jclass, jstring jName)
|
||||
{
|
||||
// Convert jstring to std::string
|
||||
const char* cName = env->GetStringUTFChars(jName, nullptr);
|
||||
std::string targetName = cName;
|
||||
env->ReleaseStringUTFChars(jName, cName);
|
||||
|
||||
// Thread class
|
||||
jclass threadClass = env->FindClass("java/lang/Thread");
|
||||
|
||||
// Call Thread.getAllStackTraces(), signature: ()Ljava/util/Map;
|
||||
jmethodID midGetAll = env->GetStaticMethodID(
|
||||
threadClass,
|
||||
"getAllStackTraces",
|
||||
"()Ljava/util/Map;"
|
||||
);
|
||||
|
||||
jobject mapObj = env->CallStaticObjectMethod(threadClass, midGetAll);
|
||||
|
||||
// Map.keySet() -> Set
|
||||
jclass mapClass = env->FindClass("java/util/Map");
|
||||
jmethodID midKeySet = env->GetMethodID(
|
||||
mapClass,
|
||||
"keySet",
|
||||
"()Ljava/util/Set;"
|
||||
);
|
||||
jobject setObj = env->CallObjectMethod(mapObj, midKeySet);
|
||||
|
||||
// Set.iterator() -> Iterator
|
||||
jclass setClass = env->FindClass("java/util/Set");
|
||||
jmethodID midIterator = env->GetMethodID(
|
||||
setClass,
|
||||
"iterator",
|
||||
"()Ljava/util/Iterator;"
|
||||
);
|
||||
jobject iteratorObj = env->CallObjectMethod(setObj, midIterator);
|
||||
|
||||
// Iterator.hasNext() / next()
|
||||
jclass iteratorClass = env->FindClass("java/util/Iterator");
|
||||
jmethodID midHasNext = env->GetMethodID(iteratorClass, "hasNext", "()Z");
|
||||
jmethodID midNext = env->GetMethodID(iteratorClass, "next", "()Ljava/lang/Object;");
|
||||
|
||||
// Thread.getName()
|
||||
jmethodID midGetName = env->GetMethodID(threadClass, "getName", "()Ljava/lang/String;");
|
||||
|
||||
while (env->CallBooleanMethod(iteratorObj, midHasNext)) {
|
||||
jobject threadObj = env->CallObjectMethod(iteratorObj, midNext);
|
||||
jstring jThreadName = (jstring)env->CallObjectMethod(threadObj, midGetName);
|
||||
|
||||
const char* cThreadName = env->GetStringUTFChars(jThreadName, nullptr);
|
||||
bool match = (targetName == cThreadName);
|
||||
env->ReleaseStringUTFChars(jThreadName, cThreadName);
|
||||
|
||||
if (match) {
|
||||
return threadObj; // Found target
|
||||
}
|
||||
}
|
||||
|
||||
return nullptr; // Not found
|
||||
}
|
||||
|
||||
|
||||
|
||||
// static native ClassLoader injectJarToThread(Thread thread, String jarPath)
|
||||
C_EXPORT
|
||||
JNIEXPORT jobject JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_nativeInjectJarToThread
|
||||
(JNIEnv* env, jclass, jobject threadObj, jstring jJarPath)
|
||||
{
|
||||
// Convert jstring -> std::string
|
||||
const char* cJarPath = env->GetStringUTFChars(jJarPath, nullptr);
|
||||
|
||||
// new File(jarPath)
|
||||
jclass fileClass = env->FindClass("java/io/File");
|
||||
jmethodID fileCtor = env->GetMethodID(fileClass, "<init>", "(Ljava/lang/String;)V");
|
||||
jstring jPathCopy = env->NewStringUTF(cJarPath);
|
||||
jobject fileObj = env->NewObject(fileClass, fileCtor, jPathCopy);
|
||||
|
||||
// File.toURI()
|
||||
jmethodID midToURI = env->GetMethodID(fileClass, "toURI", "()Ljava/net/URI;");
|
||||
jobject uriObj = env->CallObjectMethod(fileObj, midToURI);
|
||||
|
||||
// URI.toURL()
|
||||
jclass uriClass = env->FindClass("java/net/URI");
|
||||
jmethodID midToURL = env->GetMethodID(uriClass, "toURL", "()Ljava/net/URL;");
|
||||
jobject urlObj = env->CallObjectMethod(uriObj, midToURL);
|
||||
|
||||
// Thread.getContextClassLoader()
|
||||
jclass threadClass = env->FindClass("java/lang/Thread");
|
||||
jmethodID midGetCL = env->GetMethodID(
|
||||
threadClass, "getContextClassLoader", "()Ljava/lang/ClassLoader;"
|
||||
);
|
||||
jobject originalCL = env->CallObjectMethod(threadObj, midGetCL);
|
||||
|
||||
// URLClassLoader(URL[] urls, ClassLoader parent)
|
||||
jclass urlClassLoaderClass = env->FindClass("java/net/URLClassLoader");
|
||||
jmethodID urlCLCtor = env->GetMethodID(
|
||||
urlClassLoaderClass,
|
||||
"<init>",
|
||||
"([Ljava/net/URL;Ljava/lang/ClassLoader;)V"
|
||||
);
|
||||
|
||||
// Create URL[] array with 1 element
|
||||
jobjectArray urlArray = env->NewObjectArray(1, env->FindClass("java/net/URL"), nullptr);
|
||||
env->SetObjectArrayElement(urlArray, 0, urlObj);
|
||||
|
||||
// Create new URLClassLoader
|
||||
jobject newClassLoader = env->NewObject(
|
||||
urlClassLoaderClass,
|
||||
urlCLCtor,
|
||||
urlArray,
|
||||
originalCL
|
||||
);
|
||||
|
||||
// thread.setContextClassLoader(newCL)
|
||||
jmethodID midSetCL = env->GetMethodID(
|
||||
threadClass,
|
||||
"setContextClassLoader",
|
||||
"(Ljava/lang/ClassLoader;)V"
|
||||
);
|
||||
env->CallVoidMethod(threadObj, midSetCL, newClassLoader);
|
||||
|
||||
env->ReleaseStringUTFChars(jJarPath, cJarPath);
|
||||
|
||||
return newClassLoader;
|
||||
}
|
||||
@@ -23,6 +23,38 @@ JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_init
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_injectJar
|
||||
(JNIEnv *, jclass, jstring);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||
* Method: AddToBootstrapClassLoaderSearch
|
||||
* Signature: (Ljava/lang/String;)Z
|
||||
*/
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_AddToBootstrapClassLoaderSearch
|
||||
(JNIEnv *, jclass, jstring);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||
* Method: AddToSystemClassLoaderSearch
|
||||
* Signature: (Ljava/lang/String;)Z
|
||||
*/
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_AddToSystemClassLoaderSearch
|
||||
(JNIEnv *, jclass, jstring);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||
* Method: AddToClassLoader
|
||||
* Signature: (Ljava/lang/String;Ljava/lang/ClassLoader;)Z
|
||||
*/
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_AddToClassLoader
|
||||
(JNIEnv *, jclass, jstring, jobject);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||
* Method: defineClass
|
||||
* Signature: (Ljava/lang/ClassLoader;[B)Ljava/lang/Class;
|
||||
*/
|
||||
JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_defineClass
|
||||
(JNIEnv *, jclass, jobject, jbyteArray);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||
* Method: redefineClass
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
#ifndef JNI_IMPL_H
|
||||
#define JNI_IMPL_H
|
||||
|
||||
#include <jni.h>
|
||||
#include <jvmti.h>
|
||||
#include <juiceloader.h>
|
||||
#include <JuiceAgent/Logger.hpp>
|
||||
#include <cn_xiaozhou233_juiceloader_JuiceLoader.h>
|
||||
|
||||
// Variables
|
||||
extern const char* g_target_internal_name;
|
||||
extern unsigned char* g_bytecodes;
|
||||
extern jint g_bytecodes_len;
|
||||
|
||||
void JNICALL ClassFileLoadHook(
|
||||
jvmtiEnv* jvmti_env,
|
||||
JNIEnv* jni_env,
|
||||
jclass class_being_redefined,
|
||||
jobject loader,
|
||||
const char* name,
|
||||
jobject protection_domain,
|
||||
jint class_data_len,
|
||||
const unsigned char* classbytes,
|
||||
jint* new_class_data_len,
|
||||
unsigned char** new_classbytes);
|
||||
|
||||
#endif // JNI_IMPL_H
|
||||
@@ -23,44 +23,7 @@ typedef struct {
|
||||
|
||||
extern RetransformClassCacheType RetransformClassCache;
|
||||
|
||||
#define C_EXPORT extern "C" __declspec(dllexport)
|
||||
|
||||
extern "C" __declspec(dllexport)
|
||||
int InitJuiceLoader(JNIEnv *env, jvmtiEnv *jvmti);
|
||||
|
||||
void JNICALL ClassFileLoadHook(
|
||||
jvmtiEnv* jvmti_env,
|
||||
JNIEnv* jni_env,
|
||||
jclass class_being_redefined,
|
||||
jobject loader,
|
||||
const char* name,
|
||||
jobject protection_domain,
|
||||
jint class_data_len,
|
||||
const unsigned char* classbytes,
|
||||
jint* new_class_data_len,
|
||||
unsigned char** new_classbytes);
|
||||
|
||||
// JNI Functions
|
||||
// public native static boolean init();
|
||||
JNIEXPORT jboolean JNICALL loader_init(JNIEnv *env, jclass loader_class);
|
||||
// public native static boolean injectJar(String jarPath);
|
||||
JNIEXPORT jboolean JNICALL loader_injectJar(JNIEnv *env, jclass loader_class, jstring jarPath);
|
||||
// public native static boolean redefineClass(Class<?> clazz, byte[] classBytes, int length);
|
||||
JNIEXPORT jboolean JNICALL loader_redefineClass_clazz(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray classBytes, jint length);
|
||||
// public native static boolean redefineClass(String className, byte[] classBytes, int length);
|
||||
JNIEXPORT jboolean JNICALL loader_redefineClass_className(JNIEnv *env, jclass loader_class, jstring className, jbyteArray classBytes, jint length);
|
||||
// public native static Class<?>[] getLoadedClasses();
|
||||
JNIEXPORT jobjectArray JNICALL loader_getLoadedClasses(JNIEnv *env, jclass loader_class);
|
||||
// public static native byte[] getClassBytes(Class<?> clazz);
|
||||
JNIEXPORT jbyteArray JNICALL loader_getClassBytes(JNIEnv *env, jclass loader_class, jclass clazz);
|
||||
// public static native byte[] getClassBytesByName(String className);
|
||||
JNIEXPORT jbyteArray JNICALL loader_getClassBytesByName(JNIEnv *env, jclass loader_class, jstring className);
|
||||
// public static native boolean retransformClass(Class<?> clazz, byte[] classBytes, int length);
|
||||
JNIEXPORT jboolean JNICALL loader_retransformClass(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray classBytes, jint length);
|
||||
// public static native boolean retransformClassByName(String className, byte[] classBytes, int length);
|
||||
JNIEXPORT jboolean JNICALL loader_retransformClassByName(JNIEnv *env, jclass loader_class, jstring className, jbyteArray classBytes, jint length);
|
||||
// public static native Class<?> getClassByName(String className);
|
||||
JNIEXPORT jclass JNICALL loader_getClassByName(JNIEnv *env, jclass loader_class, jstring className);
|
||||
JNIEXPORT jobject JNICALL loader_nativeGetThreadByName (JNIEnv* env, jclass, jstring jName);
|
||||
JNIEXPORT jobject JNICALL loader_nativeInjectJarToThread (JNIEnv* env, jclass, jobject threadObj, jstring jJarPath);
|
||||
#endif
|
||||
@@ -0,0 +1,74 @@
|
||||
#include <jni_impl.h>
|
||||
|
||||
RetransformClassCacheType RetransformClassCache = {NULL, 0, 0};
|
||||
|
||||
static void throwRuntimeException(JNIEnv *env, const char *msg) {
|
||||
jclass rte = env->FindClass("java/lang/RuntimeException");
|
||||
if (rte != NULL) {
|
||||
env->ThrowNew(rte, msg);
|
||||
}
|
||||
}
|
||||
|
||||
void JNICALL ClassFileLoadHook(
|
||||
jvmtiEnv* jvmti_env,
|
||||
JNIEnv*,
|
||||
jclass,
|
||||
jobject,
|
||||
const char* name,
|
||||
jobject,
|
||||
jint class_data_len,
|
||||
const unsigned char* classbytes,
|
||||
jint* new_class_data_len,
|
||||
unsigned char** new_classbytes) {
|
||||
|
||||
if (!name) return;
|
||||
|
||||
/* =========================
|
||||
* 1. Capture original bytes
|
||||
* ========================= */
|
||||
if (g_target_internal_name &&
|
||||
g_bytecodes == nullptr &&
|
||||
strcmp(name, g_target_internal_name) == 0) {
|
||||
|
||||
g_bytecodes_len = class_data_len;
|
||||
g_bytecodes = (unsigned char*)malloc(class_data_len);
|
||||
memcpy(g_bytecodes, classbytes, class_data_len);
|
||||
|
||||
// IMPORTANT:
|
||||
// Do NOT touch new_classbytes here
|
||||
// Let JVM continue normally
|
||||
PLOGD.printf("[Hook:get] Captured class bytes: %s (%d)", name, class_data_len);
|
||||
return;
|
||||
}
|
||||
|
||||
/* =========================
|
||||
* 2. Apply redefine patch
|
||||
* ========================= */
|
||||
if (RetransformClassCache.size == 0) return;
|
||||
|
||||
for (int i = 0; i < RetransformClassCache.size; i++) {
|
||||
ClassBytesCacheType* entry = &RetransformClassCache.arr[i];
|
||||
if (strcmp(entry->name, name) == 0) {
|
||||
|
||||
unsigned char* newBytes = nullptr;
|
||||
if (jvmti_env->Allocate(entry->len, &newBytes) != JVMTI_ERROR_NONE) {
|
||||
PLOGE.printf("[Hook:set] Allocate failed: %s", name);
|
||||
return;
|
||||
}
|
||||
|
||||
memcpy(newBytes, entry->bytes, entry->len);
|
||||
*new_classbytes = newBytes;
|
||||
*new_class_data_len = entry->len;
|
||||
|
||||
PLOGI.printf("[Hook:set] Redefined class: %s (%d)", name, entry->len);
|
||||
|
||||
free(entry->name);
|
||||
free(entry->bytes);
|
||||
for (int j = i; j < RetransformClassCache.size - 1; j++) {
|
||||
RetransformClassCache.arr[j] = RetransformClassCache.arr[j + 1];
|
||||
}
|
||||
RetransformClassCache.size--;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
#include <jni_impl.h>
|
||||
#include <string>
|
||||
#include <cstring>
|
||||
#include <algorithm>
|
||||
|
||||
/* =========================
|
||||
* Global bytecode capture
|
||||
* ========================= */
|
||||
const char* g_target_internal_name = nullptr;
|
||||
unsigned char* g_bytecodes = nullptr;
|
||||
jint g_bytecodes_len = 0;
|
||||
|
||||
/* =========================
|
||||
* Utils
|
||||
* ========================= */
|
||||
|
||||
// Convert java name to internal name: a.b.C -> a/b/C
|
||||
static void to_internal_name(char* s) {
|
||||
for (; *s; ++s) {
|
||||
if (*s == '.') *s = '/';
|
||||
}
|
||||
}
|
||||
|
||||
/* =========================
|
||||
* JVMTI: enumerate loaded classes
|
||||
* ========================= */
|
||||
static jclass findLoadedClassByInternalName(jvmtiEnv* jvmti, const char* internalName) {
|
||||
jint count = 0;
|
||||
jclass* classes = nullptr;
|
||||
|
||||
if (jvmti->GetLoadedClasses(&count, &classes) != JVMTI_ERROR_NONE || count == 0) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
jclass result = nullptr;
|
||||
|
||||
for (jint i = 0; i < count; i++) {
|
||||
char* signature = nullptr;
|
||||
if (jvmti->GetClassSignature(classes[i], &signature, nullptr) == JVMTI_ERROR_NONE && signature) {
|
||||
// signature format: Lnet/minecraft/xxx;
|
||||
size_t len = strlen(signature);
|
||||
if (len > 2 && signature[0] == 'L' && signature[len - 1] == ';') {
|
||||
if (strncmp(signature + 1, internalName, len - 2) == 0) {
|
||||
result = classes[i];
|
||||
jvmti->Deallocate((unsigned char*)signature);
|
||||
break;
|
||||
}
|
||||
}
|
||||
jvmti->Deallocate((unsigned char*)signature);
|
||||
}
|
||||
}
|
||||
|
||||
if (classes) {
|
||||
jvmti->Deallocate((unsigned char*)classes);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/* =========================
|
||||
* Exposed: get all loaded classes
|
||||
* ========================= */
|
||||
JNIEXPORT jobjectArray JNICALL
|
||||
Java_cn_xiaozhou233_juiceloader_JuiceLoader_getLoadedClasses
|
||||
(JNIEnv* env, jclass) {
|
||||
|
||||
if (!JuiceLoaderNative.jvmti) return nullptr;
|
||||
|
||||
jint count = 0;
|
||||
jclass* classes = nullptr;
|
||||
if (JuiceLoaderNative.jvmti->GetLoadedClasses(&count, &classes) != JVMTI_ERROR_NONE || count == 0) {
|
||||
return env->NewObjectArray(0, env->FindClass("java/lang/Class"), nullptr);
|
||||
}
|
||||
|
||||
jclass classClass = env->FindClass("java/lang/Class");
|
||||
jobjectArray result = env->NewObjectArray(count, classClass, nullptr);
|
||||
|
||||
for (jint i = 0; i < count; i++) {
|
||||
env->SetObjectArrayElement(result, i, classes[i]);
|
||||
}
|
||||
|
||||
JuiceLoaderNative.jvmti->Deallocate((unsigned char*)classes);
|
||||
return result;
|
||||
}
|
||||
|
||||
/* =========================
|
||||
* Get bytecode by jclass
|
||||
* ========================= */
|
||||
JNIEXPORT jbyteArray JNICALL
|
||||
Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytes
|
||||
(JNIEnv* env, jclass, jclass clazz) {
|
||||
|
||||
if (!JuiceLoaderNative.jvmti || !clazz) return nullptr;
|
||||
|
||||
char* signature = nullptr;
|
||||
if (JuiceLoaderNative.jvmti->GetClassSignature(clazz, &signature, nullptr) != JVMTI_ERROR_NONE || !signature) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Lxxx; -> xxx
|
||||
std::string internalName(signature + 1, strlen(signature) - 2);
|
||||
JuiceLoaderNative.jvmti->Deallocate((unsigned char*)signature);
|
||||
|
||||
g_target_internal_name = internalName.c_str();
|
||||
g_bytecodes = nullptr;
|
||||
g_bytecodes_len = 0;
|
||||
|
||||
jvmtiError err = JuiceLoaderNative.jvmti->RetransformClasses(1, &clazz);
|
||||
if (err != JVMTI_ERROR_NONE || !g_bytecodes) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
jbyteArray out = env->NewByteArray(g_bytecodes_len);
|
||||
env->SetByteArrayRegion(out, 0, g_bytecodes_len, (jbyte*)g_bytecodes);
|
||||
|
||||
free(g_bytecodes);
|
||||
g_bytecodes = nullptr;
|
||||
g_target_internal_name = nullptr;
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
/* =========================
|
||||
* Get bytecode by class name
|
||||
* ========================= */
|
||||
JNIEXPORT jbyteArray JNICALL
|
||||
Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytesByName
|
||||
(JNIEnv* env, jclass loader_class, jstring className) {
|
||||
|
||||
if (!JuiceLoaderNative.jvmti || !className) return nullptr;
|
||||
|
||||
const char* utf = env->GetStringUTFChars(className, nullptr);
|
||||
if (!utf) return nullptr;
|
||||
|
||||
char internal[512];
|
||||
strncpy(internal, utf, sizeof(internal) - 1);
|
||||
internal[sizeof(internal) - 1] = '\0';
|
||||
env->ReleaseStringUTFChars(className, utf);
|
||||
|
||||
to_internal_name(internal);
|
||||
|
||||
jclass clazz = findLoadedClassByInternalName(JuiceLoaderNative.jvmti, internal);
|
||||
if (!clazz) {
|
||||
PLOGE.printf("Class not loaded: %s", internal);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytes(
|
||||
env, loader_class, clazz
|
||||
);
|
||||
}
|
||||
|
||||
/* =========================
|
||||
* Get jclass by name (no ClassLoader)
|
||||
* ========================= */
|
||||
JNIEXPORT jclass JNICALL
|
||||
Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassByName
|
||||
(JNIEnv* env, jclass, jstring className) {
|
||||
|
||||
if (!JuiceLoaderNative.jvmti || !className) return nullptr;
|
||||
|
||||
const char* utf = env->GetStringUTFChars(className, nullptr);
|
||||
if (!utf) return nullptr;
|
||||
|
||||
char internal[512];
|
||||
strncpy(internal, utf, sizeof(internal) - 1);
|
||||
internal[sizeof(internal) - 1] = '\0';
|
||||
env->ReleaseStringUTFChars(className, utf);
|
||||
|
||||
to_internal_name(internal);
|
||||
|
||||
jclass clazz = findLoadedClassByInternalName(JuiceLoaderNative.jvmti, internal);
|
||||
if (!clazz) {
|
||||
PLOGE.printf("Failed to find loaded class: %s", internal);
|
||||
}
|
||||
return clazz;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
#include <jni_impl.h>
|
||||
|
||||
JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_defineClass
|
||||
(JNIEnv *env, jclass, jobject cl, jbyteArray bytes) {
|
||||
PLOGD << "Invoked!";
|
||||
jclass clClass = env->FindClass("java/lang/ClassLoader");
|
||||
jmethodID defineClass = env->GetMethodID(clClass, "defineClass", "([BII)Ljava/lang/Class;");
|
||||
jobject classDefined = env->CallObjectMethod(cl, defineClass, bytes, 0,
|
||||
env->GetArrayLength(bytes));
|
||||
return (jclass)classDefined;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
#include <jni_impl.h>
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_init
|
||||
(JNIEnv *env, jclass loader_class) {
|
||||
PLOGI << "Invoked!";
|
||||
|
||||
// Get JavaVM
|
||||
JavaVM* jvm = nullptr;
|
||||
env->GetJavaVM(&jvm);
|
||||
if (jvm == nullptr) {
|
||||
PLOGE << "Failed to get JavaVM instance";
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
// Get JVMTI
|
||||
jvmtiEnv* jvmti = nullptr;
|
||||
jvmtiError err = static_cast<jvmtiError>(jvm->GetEnv(reinterpret_cast<void**>(&jvmti), JVMTI_VERSION_1_2));
|
||||
if (err != JVMTI_ERROR_NONE || jvmti == nullptr) {
|
||||
PLOGE << "Failed to get JVMTI environment, error: " << err;
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
int result = InitJuiceLoader(env, jvmti);
|
||||
if (result != 0) {
|
||||
PLOGE << "Failed to initialize JuiceLoader, error code: " << result;
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
PLOGI << "JuiceLoader initialized successfully";
|
||||
return JNI_TRUE;
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
#include <jni_impl.h>
|
||||
|
||||
// Deprecated
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_injectJar
|
||||
(JNIEnv *env, jclass loader_class, jstring jarPath) {
|
||||
PLOGI << "Invoked!";
|
||||
const char *pathStr = env->GetStringUTFChars(jarPath, NULL);
|
||||
if (!pathStr) {
|
||||
PLOGE << "Path is NULL!";
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
if (!JuiceLoaderNative.jvmti) {
|
||||
PLOGE.printf("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
||||
env->ReleaseStringUTFChars(jarPath, pathStr);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
jvmtiError result = JuiceLoaderNative.jvmti->AddToSystemClassLoaderSearch(pathStr);
|
||||
if (result != JVMTI_ERROR_NONE) {
|
||||
PLOGE.printf("Cannot inject jar [result=%d]", result);
|
||||
env->ReleaseStringUTFChars(jarPath, pathStr);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
env->ReleaseStringUTFChars(jarPath, pathStr);
|
||||
PLOGI << "Jar injected: " << pathStr;
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
// Deprecated
|
||||
JNIEXPORT jobject JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_nativeInjectJarToThread
|
||||
(JNIEnv* env, jclass, jobject threadObj, jstring jJarPath)
|
||||
{
|
||||
// Convert jstring -> std::string
|
||||
const char* cJarPath = env->GetStringUTFChars(jJarPath, nullptr);
|
||||
|
||||
// new File(jarPath)
|
||||
jclass fileClass = env->FindClass("java/io/File");
|
||||
jmethodID fileCtor = env->GetMethodID(fileClass, "<init>", "(Ljava/lang/String;)V");
|
||||
jstring jPathCopy = env->NewStringUTF(cJarPath);
|
||||
jobject fileObj = env->NewObject(fileClass, fileCtor, jPathCopy);
|
||||
|
||||
// File.toURI()
|
||||
jmethodID midToURI = env->GetMethodID(fileClass, "toURI", "()Ljava/net/URI;");
|
||||
jobject uriObj = env->CallObjectMethod(fileObj, midToURI);
|
||||
|
||||
// URI.toURL()
|
||||
jclass uriClass = env->FindClass("java/net/URI");
|
||||
jmethodID midToURL = env->GetMethodID(uriClass, "toURL", "()Ljava/net/URL;");
|
||||
jobject urlObj = env->CallObjectMethod(uriObj, midToURL);
|
||||
|
||||
// Thread.getContextClassLoader()
|
||||
jclass threadClass = env->FindClass("java/lang/Thread");
|
||||
jmethodID midGetCL = env->GetMethodID(
|
||||
threadClass, "getContextClassLoader", "()Ljava/lang/ClassLoader;"
|
||||
);
|
||||
jobject originalCL = env->CallObjectMethod(threadObj, midGetCL);
|
||||
|
||||
// URLClassLoader(URL[] urls, ClassLoader parent)
|
||||
jclass urlClassLoaderClass = env->FindClass("java/net/URLClassLoader");
|
||||
jmethodID urlCLCtor = env->GetMethodID(
|
||||
urlClassLoaderClass,
|
||||
"<init>",
|
||||
"([Ljava/net/URL;Ljava/lang/ClassLoader;)V"
|
||||
);
|
||||
|
||||
// Create URL[] array with 1 element
|
||||
jobjectArray urlArray = env->NewObjectArray(1, env->FindClass("java/net/URL"), nullptr);
|
||||
env->SetObjectArrayElement(urlArray, 0, urlObj);
|
||||
|
||||
// Create new URLClassLoader
|
||||
jobject newClassLoader = env->NewObject(
|
||||
urlClassLoaderClass,
|
||||
urlCLCtor,
|
||||
urlArray,
|
||||
originalCL
|
||||
);
|
||||
|
||||
// thread.setContextClassLoader(newCL)
|
||||
jmethodID midSetCL = env->GetMethodID(
|
||||
threadClass,
|
||||
"setContextClassLoader",
|
||||
"(Ljava/lang/ClassLoader;)V"
|
||||
);
|
||||
env->CallVoidMethod(threadObj, midSetCL, newClassLoader);
|
||||
|
||||
env->ReleaseStringUTFChars(jJarPath, cJarPath);
|
||||
|
||||
return newClassLoader;
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_AddToBootstrapClassLoaderSearch
|
||||
(JNIEnv *env, jclass, jstring jarPath) {
|
||||
PLOGD << "Invoked!";
|
||||
const char *pathStr = env->GetStringUTFChars(jarPath, NULL);
|
||||
if (!pathStr) {
|
||||
PLOGE << "Path is NULL!";
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
if (!JuiceLoaderNative.jvmti) {
|
||||
PLOGE.printf("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
||||
env->ReleaseStringUTFChars(jarPath, pathStr);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
jvmtiError result = JuiceLoaderNative.jvmti->AddToBootstrapClassLoaderSearch(pathStr);
|
||||
if (result != JVMTI_ERROR_NONE) {
|
||||
PLOGE.printf("Cannot AddToBootstrapClassLoaderSearch [result=%d]", result);
|
||||
env->ReleaseStringUTFChars(jarPath, pathStr);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
env->ReleaseStringUTFChars(jarPath, pathStr);
|
||||
PLOGI << "AddToBootstrapClassLoaderSearch: " << pathStr;
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_AddToSystemClassLoaderSearch
|
||||
(JNIEnv *env, jclass, jstring jarPath) {
|
||||
PLOGD << "Invoked!";
|
||||
const char *pathStr = env->GetStringUTFChars(jarPath, NULL);
|
||||
if (!pathStr) {
|
||||
PLOGE << "Path is NULL!";
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
if (!JuiceLoaderNative.jvmti) {
|
||||
PLOGE.printf("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
||||
env->ReleaseStringUTFChars(jarPath, pathStr);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
jvmtiError result = JuiceLoaderNative.jvmti->AddToSystemClassLoaderSearch(pathStr);
|
||||
if (result != JVMTI_ERROR_NONE) {
|
||||
PLOGE.printf("Cannot AddToSystemClassLoaderSearch [result=%d]", result);
|
||||
env->ReleaseStringUTFChars(jarPath, pathStr);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
env->ReleaseStringUTFChars(jarPath, pathStr);
|
||||
PLOGI << "AddToSystemClassLoaderSearch: " << pathStr;
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL
|
||||
Java_cn_xiaozhou233_juiceloader_JuiceLoader_AddToClassLoader
|
||||
(JNIEnv *env, jclass, jstring path, jobject loader) {
|
||||
|
||||
jclass urlClassLoader = env->FindClass("java/net/URLClassLoader");
|
||||
|
||||
if (env->IsInstanceOf(loader, urlClassLoader)) {
|
||||
jclass fileClass = env->FindClass("java/io/File");
|
||||
jmethodID fileInit = env->GetMethodID(
|
||||
fileClass,
|
||||
"<init>",
|
||||
"(Ljava/lang/String;)V"
|
||||
);
|
||||
|
||||
jobject file = env->NewObject(fileClass, fileInit, path);
|
||||
|
||||
jmethodID toURI = env->GetMethodID(
|
||||
fileClass,
|
||||
"toURI",
|
||||
"()Ljava/net/URI;"
|
||||
);
|
||||
jobject uri = env->CallObjectMethod(file, toURI);
|
||||
|
||||
jclass uriClass = env->FindClass("java/net/URI");
|
||||
jmethodID toURL = env->GetMethodID(
|
||||
uriClass,
|
||||
"toURL",
|
||||
"()Ljava/net/URL;"
|
||||
);
|
||||
jobject url = env->CallObjectMethod(uri, toURL);
|
||||
|
||||
jmethodID addURL = env->GetMethodID(
|
||||
urlClassLoader,
|
||||
"addURL",
|
||||
"(Ljava/net/URL;)V"
|
||||
);
|
||||
env->CallVoidMethod(loader, addURL, url);
|
||||
} else {
|
||||
// jstring -> const char*
|
||||
const char* nativePath = env->GetStringUTFChars(path, nullptr);
|
||||
|
||||
JuiceLoaderNative.jvmti->AddToSystemClassLoaderSearch(nativePath);
|
||||
|
||||
// Release UTF string
|
||||
env->ReleaseStringUTFChars(path, nativePath);
|
||||
}
|
||||
|
||||
return JNI_TRUE;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
#include <jni_impl.h>
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_redefineClass
|
||||
(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray classBytes, jint length) {
|
||||
PLOGI << "Invoked!";
|
||||
if (!JuiceLoaderNative.jvmti) {
|
||||
PLOGE.printf("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
jbyte* buf = env->GetByteArrayElements(classBytes, NULL);
|
||||
if (!buf) {
|
||||
PLOGE << "Cannot get class bytes";
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
jvmtiClassDefinition defs[1];
|
||||
defs[0].klass = clazz;
|
||||
defs[0].class_byte_count = length;
|
||||
defs[0].class_bytes = reinterpret_cast<const unsigned char*>(buf);
|
||||
|
||||
jvmtiError result = JuiceLoaderNative.jvmti->RedefineClasses(1, defs);
|
||||
env->ReleaseByteArrayElements(classBytes, buf, JNI_ABORT);
|
||||
|
||||
if (result != JVMTI_ERROR_NONE) {
|
||||
PLOGE.printf("Cannot redefine class [result=%d]", result);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
PLOGI.printf("Class redefined successfully!");
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_redefineClassByName
|
||||
(JNIEnv *env, jclass loader_class, jstring className, jbyteArray classBytes, jint length) {
|
||||
PLOGI << "redefineClass_className Invoked!";
|
||||
if (!JuiceLoaderNative.jvmti) {
|
||||
PLOGE.printf("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
const char* cname = env->GetStringUTFChars(className, NULL);
|
||||
if (!cname) {
|
||||
PLOGE << "Class name is NULL!";
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
jclass clazz = env->FindClass(cname);
|
||||
if (!clazz) {
|
||||
PLOGE.printf("Class not found! [ClassName=%s]", cname);
|
||||
env->ReleaseStringUTFChars(className, cname);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
jboolean ret = Java_cn_xiaozhou233_juiceloader_JuiceLoader_redefineClass(env, loader_class, clazz, classBytes, length);
|
||||
env->ReleaseStringUTFChars(className, cname);
|
||||
return ret;
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
#include <jni_impl.h>
|
||||
#include <string.h>
|
||||
|
||||
/* =========================
|
||||
* utils
|
||||
* ========================= */
|
||||
|
||||
static char* get_class_name(JNIEnv* env, jclass clazz) {
|
||||
jclass clsClass = env->FindClass("java/lang/Class");
|
||||
jmethodID mid = env->GetMethodID(clsClass, "getName", "()Ljava/lang/String;");
|
||||
jstring nameStr = (jstring)env->CallObjectMethod(clazz, mid);
|
||||
|
||||
const char* tmp = env->GetStringUTFChars(nameStr, nullptr);
|
||||
char* result = _strdup(tmp);
|
||||
env->ReleaseStringUTFChars(nameStr, tmp);
|
||||
env->DeleteLocalRef(nameStr);
|
||||
return result;
|
||||
}
|
||||
|
||||
/* =========================
|
||||
* JVMTI global lookup
|
||||
* ========================= */
|
||||
|
||||
static jclass findLoadedClassByInternalName(
|
||||
jvmtiEnv* jvmti,
|
||||
const char* internalName
|
||||
) {
|
||||
jint count = 0;
|
||||
jclass* classes = nullptr;
|
||||
|
||||
if (jvmti->GetLoadedClasses(&count, &classes) != JVMTI_ERROR_NONE || count == 0) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
jclass result = nullptr;
|
||||
|
||||
for (jint i = 0; i < count; i++) {
|
||||
char* sig = nullptr;
|
||||
if (jvmti->GetClassSignature(classes[i], &sig, nullptr) == JVMTI_ERROR_NONE && sig) {
|
||||
// Lnet/minecraft/client/Minecraft;
|
||||
if (sig[0] == 'L') {
|
||||
size_t len = strlen(sig);
|
||||
if (len > 2 &&
|
||||
strncmp(sig + 1, internalName, len - 2) == 0 &&
|
||||
internalName[len - 2] == '\0') {
|
||||
result = classes[i];
|
||||
jvmti->Deallocate((unsigned char*)sig);
|
||||
break;
|
||||
}
|
||||
}
|
||||
jvmti->Deallocate((unsigned char*)sig);
|
||||
}
|
||||
}
|
||||
|
||||
jvmti->Deallocate((unsigned char*)classes);
|
||||
return result;
|
||||
}
|
||||
|
||||
/* =========================
|
||||
* retransform by jclass
|
||||
* ========================= */
|
||||
|
||||
JNIEXPORT jboolean JNICALL
|
||||
Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClass
|
||||
(JNIEnv* env, jclass, jclass clazz, jbyteArray classBytes, jint) {
|
||||
|
||||
if (!JuiceLoaderNative.jvmti || !clazz || !classBytes) {
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
char* nameDot = get_class_name(env, clazz);
|
||||
for (char* p = nameDot; *p; ++p)
|
||||
if (*p == '.') *p = '/';
|
||||
|
||||
jbyte* bytes = env->GetByteArrayElements(classBytes, nullptr);
|
||||
jint len = env->GetArrayLength(classBytes);
|
||||
|
||||
if (RetransformClassCache.size >= RetransformClassCache.capacity) {
|
||||
int newCap = RetransformClassCache.capacity == 0 ? 4 : RetransformClassCache.capacity * 2;
|
||||
RetransformClassCache.arr =
|
||||
(ClassBytesCacheType*)realloc(RetransformClassCache.arr, newCap * sizeof(ClassBytesCacheType));
|
||||
RetransformClassCache.capacity = newCap;
|
||||
}
|
||||
|
||||
ClassBytesCacheType* entry =
|
||||
&RetransformClassCache.arr[RetransformClassCache.size++];
|
||||
|
||||
entry->name = _strdup(nameDot);
|
||||
entry->bytes = (unsigned char*)malloc(len);
|
||||
memcpy(entry->bytes, bytes, len);
|
||||
entry->len = len;
|
||||
|
||||
env->ReleaseByteArrayElements(classBytes, bytes, JNI_ABORT);
|
||||
|
||||
jclass arr[1] = { clazz };
|
||||
jvmtiError err = JuiceLoaderNative.jvmti->RetransformClasses(1, arr);
|
||||
|
||||
free(nameDot);
|
||||
|
||||
if (err != JVMTI_ERROR_NONE) {
|
||||
PLOGE.printf("RetransformClasses failed: %d", err);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
PLOGI.printf("[retransformClass] OK: %s (%d)", entry->name, entry->len);
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
/* =========================
|
||||
* retransform by name (NO FindClass)
|
||||
* ========================= */
|
||||
|
||||
JNIEXPORT jboolean JNICALL
|
||||
Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClassByName
|
||||
(JNIEnv* env, jclass loader_class, jstring className, jbyteArray classBytes, jint length) {
|
||||
|
||||
if (!JuiceLoaderNative.jvmti || !className) {
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
const char* utf = env->GetStringUTFChars(className, nullptr);
|
||||
char internalName[512];
|
||||
strncpy(internalName, utf, sizeof(internalName) - 1);
|
||||
internalName[sizeof(internalName) - 1] = 0;
|
||||
|
||||
for (char* p = internalName; *p; ++p)
|
||||
if (*p == '.') *p = '/';
|
||||
|
||||
env->ReleaseStringUTFChars(className, utf);
|
||||
|
||||
jclass target =
|
||||
findLoadedClassByInternalName(JuiceLoaderNative.jvmti, internalName);
|
||||
|
||||
if (!target) {
|
||||
PLOGE.printf("Class not loaded: %s", internalName);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
return Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClass(
|
||||
env, loader_class, target, classBytes, length
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
#include <jni_impl.h>
|
||||
|
||||
JNIEXPORT jobject JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_nativeGetThreadByName
|
||||
(JNIEnv* env, jclass, jstring jName)
|
||||
{
|
||||
// Convert jstring to std::string
|
||||
const char* cName = env->GetStringUTFChars(jName, nullptr);
|
||||
std::string targetName = cName;
|
||||
env->ReleaseStringUTFChars(jName, cName);
|
||||
|
||||
// Thread class
|
||||
jclass threadClass = env->FindClass("java/lang/Thread");
|
||||
|
||||
// Call Thread.getAllStackTraces(), signature: ()Ljava/util/Map;
|
||||
jmethodID midGetAll = env->GetStaticMethodID(
|
||||
threadClass,
|
||||
"getAllStackTraces",
|
||||
"()Ljava/util/Map;"
|
||||
);
|
||||
|
||||
jobject mapObj = env->CallStaticObjectMethod(threadClass, midGetAll);
|
||||
|
||||
// Map.keySet() -> Set
|
||||
jclass mapClass = env->FindClass("java/util/Map");
|
||||
jmethodID midKeySet = env->GetMethodID(
|
||||
mapClass,
|
||||
"keySet",
|
||||
"()Ljava/util/Set;"
|
||||
);
|
||||
jobject setObj = env->CallObjectMethod(mapObj, midKeySet);
|
||||
|
||||
// Set.iterator() -> Iterator
|
||||
jclass setClass = env->FindClass("java/util/Set");
|
||||
jmethodID midIterator = env->GetMethodID(
|
||||
setClass,
|
||||
"iterator",
|
||||
"()Ljava/util/Iterator;"
|
||||
);
|
||||
jobject iteratorObj = env->CallObjectMethod(setObj, midIterator);
|
||||
|
||||
// Iterator.hasNext() / next()
|
||||
jclass iteratorClass = env->FindClass("java/util/Iterator");
|
||||
jmethodID midHasNext = env->GetMethodID(iteratorClass, "hasNext", "()Z");
|
||||
jmethodID midNext = env->GetMethodID(iteratorClass, "next", "()Ljava/lang/Object;");
|
||||
|
||||
// Thread.getName()
|
||||
jmethodID midGetName = env->GetMethodID(threadClass, "getName", "()Ljava/lang/String;");
|
||||
|
||||
while (env->CallBooleanMethod(iteratorObj, midHasNext)) {
|
||||
jobject threadObj = env->CallObjectMethod(iteratorObj, midNext);
|
||||
jstring jThreadName = (jstring)env->CallObjectMethod(threadObj, midGetName);
|
||||
|
||||
const char* cThreadName = env->GetStringUTFChars(jThreadName, nullptr);
|
||||
bool match = (targetName == cThreadName);
|
||||
env->ReleaseStringUTFChars(jThreadName, cThreadName);
|
||||
|
||||
if (match) {
|
||||
return threadObj; // Found target
|
||||
}
|
||||
}
|
||||
|
||||
return nullptr; // Not found
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <jvmti.h>
|
||||
#include <JuiceAgent/Logger.hpp>
|
||||
#include <juiceloader.h>
|
||||
#include <jni_impl.h>
|
||||
|
||||
JuiceLoaderNativeType JuiceLoaderNative;
|
||||
|
||||
@@ -30,7 +31,7 @@ static int ConfigureJVMTI(JNIEnv *env, _jvmtiEnv *jvmti) {
|
||||
// Register callbacks
|
||||
jvmtiEventCallbacks callbacks;
|
||||
memset(&callbacks, 0, sizeof(callbacks));
|
||||
// callbacks.ClassFileLoadHook = &ClassFileLoadHook;
|
||||
callbacks.ClassFileLoadHook = &ClassFileLoadHook;
|
||||
jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks));
|
||||
|
||||
// Enable events
|
||||
@@ -41,6 +42,7 @@ static int ConfigureJVMTI(JNIEnv *env, _jvmtiEnv *jvmti) {
|
||||
|
||||
extern "C" __declspec(dllexport)
|
||||
int InitJuiceLoader(JNIEnv *env, _jvmtiEnv *jvmti) {
|
||||
InitLogger();
|
||||
// Step 1: Check if env/jvmti is null
|
||||
PLOGD.printf("env: %p, jvmti: %p", env, jvmti);
|
||||
if (env == nullptr) {
|
||||
|
||||
Reference in new issue
Block a user