mirror of
https://github.com/xiaozhou233/JuiceAgent.git
synced 2026-12-05 13:05:53 +08:00
Update Version 2.2 Build 1
Update Version 2.2 Build 1
This commit is contained in:
13 files changed
+617
-600
No files matched your search
@@ -7,33 +7,34 @@ 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)
|
||||
- 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)
|
||||
- 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
|
||||
- nativeGetThreadByName* (test function, myself-use)
|
||||
- nativeInjectJarToThread (test function, myself-use)
|
||||
## How To Use (For Version 2.2 Build 1)
|
||||
|
||||
### 1. Download Files
|
||||
- Download `libagent`, `libinjector`, and `libjuiceloader` from the Release to the same directory.
|
||||
@@ -43,19 +44,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 +122,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.
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
#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_bytecodes_classname;
|
||||
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);
|
||||
|
||||
// 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 // 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,72 @@
|
||||
#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* 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) {
|
||||
|
||||
// PLOGI << "[Hook] ClassFileLoadHook: " << name;
|
||||
|
||||
// ---- 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
#include <jni_impl.h>
|
||||
|
||||
const char* g_bytecodes_classname = NULL;
|
||||
unsigned char* g_bytecodes = NULL;
|
||||
jint g_bytecodes_len = 0;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
static 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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -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,90 @@
|
||||
#include <jni_impl.h>
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -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,72 @@
|
||||
#include <jni_impl.h>
|
||||
|
||||
static 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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -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