Compare commits

..
51 Commits
Author SHA1 Message Date
xiaozhou233 896a856c57 Update: Version 3.0 Build 2
Update: Version 3.0 Build 2
2026-04-02 16:10:12 +08:00
xiaozhou233 c80851adb7 Version 3.0 Build 2 2026-04-02 16:09:29 +08:00
xiaozhou233 49ac4a51a1 Delete useless code 2026-04-02 16:09:04 +08:00
xiaozhou233 0d9e5fe836 Breaking Update: Version 3.0 Build 1
Breaking Update: Version 3.0 Build 1
Rename modules
Refactor all function form C to C++
Support JuiceAgent-API
2026-04-02 14:23:27 +08:00
xiaozhou233 34c8ccd497 Breaking Update: Version 3.0 Build 1 2026-04-02 14:20:33 +08:00
xiaozhou233 f73265ac3e Impl: retransform 2026-04-02 14:19:13 +08:00
xiaozhou233 5e7972779f Impl: getLoadedClasses and getClassByName 2026-04-02 13:57:26 +08:00
xiaozhou233 8ad8f45545 impl: Redefine class 2026-04-02 13:42:19 +08:00
xiaozhou233 71965165b9 Refactor: bytecode.cpp 2026-04-02 13:25:57 +08:00
xiaozhou233 34dbd82a59 Impl: getClassBytes/getClassBytesByName 2026-04-02 13:19:07 +08:00
xiaozhou233 9aa77848d7 BugFix and Update: C++ 20 2026-04-02 12:51:23 +08:00
xiaozhou233 ad69f9d11a Impl: Data Structures and set/map 2026-04-02 12:37:31 +08:00
xiaozhou233 faeaf052b9 WIP: ClassFileLoadHook 2026-04-01 18:14:44 +08:00
xiaozhou233 b0d8b5901f Impl: define / redefine class 2026-04-01 18:00:42 +08:00
xiaozhou233 4496931bdf Impl: addToClassLoader 2026-04-01 10:36:39 +08:00
xiaozhou233 34cb16d385 Refactor & Impl: JuiceAgent and init function and AddToClassLoader 2026-04-01 10:19:40 +08:00
xiaozhou233 bad147d898 modified: src/libagent/CMakeLists.txt 2026-03-31 22:48:55 +08:00
xiaozhou233 289b0311bf break: delete agent src 2026-03-31 22:24:14 +08:00
xiaozhou233 1714f7603d Refactor: header file 2026-03-31 22:18:52 +08:00
xiaozhou233 d6d17aac35 BugFix: null jstring 2026-03-30 19:03:10 +08:00
xiaozhou233 6350bfb0ec Refactor: Rename key 2026-03-30 18:51:19 +08:00
xiaozhou233 8421d3817a Fix: #pragma once 2026-03-30 17:40:14 +08:00
xiaozhou233 3362e2071c Patch: AI Fix 2026-03-30 17:38:46 +08:00
xiaozhou233 72c0518ebc BugFix: No default value was retrieved when the configuration value was empty 2026-03-30 14:19:38 +08:00
xiaozhou233 0a4ec5e97a Impl: Invoke JuiceAgentAPI start 2026-03-30 14:14:40 +08:00
xiaozhou233 15d7f0295a Patch: AI Fix 2026-03-30 13:49:47 +08:00
xiaozhou233 c5817a3b06 Impl: Inject JuiceLoaderAPI 2026-03-30 13:37:51 +08:00
xiaozhou233 e5ac60d476 BugFix: Wrong config key 2026-03-30 13:37:30 +08:00
xiaozhou233 3e3f9d1c14 Impl: Attach JavaVM 2026-03-30 13:28:32 +08:00
xiaozhou233 3ce1bccf02 Impl: Read config and print 2026-03-24 19:56:51 +08:00
xiaozhou233 205e608d60 Refactor: Config System 2026-03-24 19:24:37 +08:00
xiaozhou233 9dab75b5fd [Refactor] Config System 2026-03-24 13:53:54 +08:00
xiaozhou233 c9c10686ab [Refactor] Delete 2026-03-08 10:05:03 +08:00
xiaozhou233 a110e675c6 [Refactor] API 2026-03-07 22:38:36 +08:00
xiaozhou233 9b24ea0ae4 [Refactor] libloader 2026-03-07 17:44:27 +08:00
xiaozhou233 172f354b04 [Refactor] Config 2026-03-07 16:41:20 +08:00
xiaozhou233 cf49ed0a7b [Refactor] Rename 2026-03-01 13:07:00 +08:00
xiaozhou233 ea5ce8258d [Refactor] Rename 2026-03-01 13:03:32 +08:00
xiaozhou233 ab9369d8b7 [Refactor] rename and remove useless log 2026-03-01 13:02:33 +08:00
xiaozhou233 2ce6a8e192 [Refactor] Modify the loader structure 2026-03-01 12:50:33 +08:00
xiaozhou233 d8bed79f84 [Refactor] Rename 2026-03-01 12:38:12 +08:00
xiaozhou233 6ab3c279aa [Doc] Update link 2026-01-30 15:36:42 +08:00
xiaozhou233 a8c2496292 Version 2.3 Build 1 2026-01-30 15:32:49 +08:00
xiaozhou233 94d881fe63 [Feat] AddToClassLoader/AddToSystemClassLoaderSearch/AddToBootstrapClassLoaderSearch 2026-01-15 14:36:55 +08:00
xiaozhou233 d98e3e818e [Refactor] Remove unused code 2026-01-15 14:24:57 +08:00
xiaozhou233 58f76009e4 [Refactor] Class 2026-01-15 14:23:43 +08:00
xiaozhou233 64ca48dfc8 [BugFix] Fix class bytecode retrieval under multi-classloader 2026-01-15 14:16:02 +08:00
xiaozhou233 4ef94b5ac2 [Feat] define 2026-01-15 14:13:29 +08:00
xiaozhou233 339b68c8af [Update] jni header 2026-01-15 14:09:37 +08:00
xiaozhou233 623445aa5e Version 2.2 Build 2 2026-01-09 19:52:49 +08:00
xiaozhou233 cacdb6a1cd [Update] Injector 2025-12-12 11:48:07 +08:00
41 changed files with 2074 additions and 1061 deletions

No files matched your search

+3 -3
View File
@@ -1,7 +1,7 @@
cmake_minimum_required(VERSION 3.15) cmake_minimum_required(VERSION 3.15)
project(JuiceAgent LANGUAGES C CXX) project(JuiceAgent LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_STANDARD_REQUIRED ON)
# output directories # output directories
@@ -16,6 +16,6 @@ link_directories("$ENV{JAVA_HOME}/lib")
add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection) add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection)
# modules # modules
add_subdirectory(${SRC_DIR}/libagent) add_subdirectory(${SRC_DIR}/libloader)
add_subdirectory(${SRC_DIR}/libinjector) add_subdirectory(${SRC_DIR}/libinjector)
add_subdirectory(${SRC_DIR}/libjuiceloader) add_subdirectory(${SRC_DIR}/libagent)
+7 -2
View File
@@ -1,6 +1,7 @@
# JuiceAgent # JuiceAgent
[English]() | [中文]() [English](https://github.com/xiaozhou233/JuiceAgent/blob/main/README.md) | [中文](https://github.com/xiaozhou233/JuiceAgent/blob/main/README_zh.md)
JuiceAgent — a JVMTI-based injection library for loading external JARs and transforming Java bytecode, even when DisableAttachMechanism is enabled. JuiceAgent — a JVMTI-based injection library for loading external JARs and transforming Java bytecode, even when DisableAttachMechanism is enabled.
@@ -13,12 +14,14 @@ JuiceAgent — a JVMTI-based injection library for loading external JARs and tra
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). 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 ## Features
### JuiceAgent (src/libagent) ### JuiceAgent (src/libagent)
Low-level injection implementation for loading JuiceLoader
- Initialize JuiceLoader - Initialize JuiceLoader
- Lightweight Library (No Javaagent) - Lightweight Library (No Javaagent)
- Read Config File and Load JARs - Read Config File and Load JARs
- Invoke JuiceLoader Bootstrap API - Invoke JuiceLoader Bootstrap API
### libinjector (src/libinjector) ### libinjector (src/libinjector)
Injector, supporting **ReflectiveDLLInjection** and CreateRemoteThread Inject.
- Provides JNI functions for injecting DLLs into target processes - Provides JNI functions for injecting DLLs into target processes
- Get PID by process name - Get PID by process name
@@ -32,9 +35,11 @@ JuiceAgent is a JVMTI-native injection framework that injects native code into a
- getLoadedClasses - getLoadedClasses
- getClassBytes (getClassBytesByName) - getClassBytes (getClassBytesByName)
- getClassByName - getClassByName
- AddToBootstrapClassLoaderSearch
- AddToSystemClassLoaderSearch
- nativeGetThreadByName* (test function, myself-use) - nativeGetThreadByName* (test function, myself-use)
- nativeInjectJarToThread (test function, myself-use) - nativeInjectJarToThread (test function, myself-use)
## How To Use (For Version 2.2 Build 1) ## How To Use (For Version 2.3 Build 1)
### 1. Download Files ### 1. Download Files
- Download `libagent`, `libinjector`, and `libjuiceloader` from the Release to the same directory. - Download `libagent`, `libinjector`, and `libjuiceloader` from the Release to the same directory.
+204
View File
@@ -0,0 +1,204 @@
# JuiceAgent
[English](https://github.com/xiaozhou233/JuiceAgent/blob/main/README.md) | [中文](https://github.com/xiaozhou233/JuiceAgent/blob/main/README_zh.md)
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 解析库
+1
View File
@@ -0,0 +1 @@
VERSION = Version 3.0 Build 2
-18
View File
@@ -1,18 +0,0 @@
#ifndef JUICEAGENT_H
#define JUICEAGENT_H
#define INJECT_PATH_MAX 260
typedef struct _InjectionInfo {
char BootstrapAPIPath[INJECT_PATH_MAX];
char JuiceLoaderJarPath[INJECT_PATH_MAX];
char EntryJarPath[INJECT_PATH_MAX];
char EntryClass[INJECT_PATH_MAX];
char EntryMethod[INJECT_PATH_MAX];
char InjectionDir[INJECT_PATH_MAX];
char JuiceLoaderLibraryPath[INJECT_PATH_MAX];
} InjectionInfoType;
extern InjectionInfoType InjectionInfo;
#endif // JUICEAGENT_H
+14
View File
@@ -0,0 +1,14 @@
#pragma once
#include <string>
struct InjectionInfo {
std::string JuiceAgentAPIJarPath;
std::string JuiceAgentNativePath;
std::string EntryJarPath;
std::string EntryClass;
std::string EntryMethod;
std::string InjectionDir;
};
@@ -0,0 +1,62 @@
#include <jni_impl.hpp>
#include <iostream>
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) {
if (!name) {
PLOGW << "name is null";
return;
}
/* =========================
* 1. Capture original bytes
* ========================= */
std::lock_guard<std::mutex> lock(classDataMutex);
if (classToCapture.contains(name)) {
if (!classFileDataMap.contains(name)) {
ClassFileData data;
data.classname = name;
data.bytecode.assign(classbytes, classbytes + class_data_len);
// Experimental: class/classloader/protection_domain references (to be used in future features, e.g. dynamic patching)
data.clazz = class_being_redefined;
data.classloader = loader;
data.protection_domain = protection_domain;
classFileDataMap[name] = std::move(data);
classToCapture.erase(name);
PLOGI << "Captured class: " << name << " (length: " << class_data_len << ")";
}
}
/* =========================
* 2. Apply patches
* ========================= */
if (pendingRetransform.contains(name)) {
auto& bytes = pendingRetransform[name];
unsigned char* new_buf = nullptr;
jvmti_env->Allocate(bytes.size(), &new_buf);
memcpy(new_buf, bytes.data(), bytes.size());
*new_class_data_len = (jint)bytes.size();
*new_classbytes = new_buf;
pendingRetransform.erase(name);
PLOGI << "Retransformed: " << name << " (new length: " << bytes.size() << ")";
}
}
+8
View File
@@ -0,0 +1,8 @@
#include <global.hpp>
std::unordered_set<std::string> classToCapture;
std::unordered_map<std::string, ClassFileData> classFileDataMap;
std::mutex classDataMutex;
std::unordered_map<std::string, std::vector<unsigned char>> pendingRetransform;
std::mutex pendingRetransformMutex;
@@ -1,11 +1,17 @@
#include <jni_impl.h> #include <jni_impl.hpp>
#include <libagent.hpp>
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_init // This function is called by Java to initialize the agent.
(JNIEnv *env, jclass loader_class) { JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init
PLOGI << "Invoked!"; (JNIEnv *env, jclass loader_class) {
InitLogger();
PLOGI << "Initializing JuiceAgent...";
// Get JavaVM
JavaVM* jvm = nullptr; JavaVM* jvm = nullptr;
jvmtiEnv* jvmti = nullptr;
// Get Java VM
env->GetJavaVM(&jvm); env->GetJavaVM(&jvm);
if (jvm == nullptr) { if (jvm == nullptr) {
PLOGE << "Failed to get JavaVM instance"; PLOGE << "Failed to get JavaVM instance";
@@ -13,19 +19,15 @@ JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_init
} }
// Get JVMTI // Get JVMTI
jvmtiEnv* jvmti = nullptr;
jvmtiError err = static_cast<jvmtiError>(jvm->GetEnv(reinterpret_cast<void**>(&jvmti), JVMTI_VERSION_1_2)); jvmtiError err = static_cast<jvmtiError>(jvm->GetEnv(reinterpret_cast<void**>(&jvmti), JVMTI_VERSION_1_2));
if (err != JVMTI_ERROR_NONE || jvmti == nullptr) { if (err != JVMTI_ERROR_NONE || jvmti == nullptr) {
PLOGE << "Failed to get JVMTI environment, error: " << err; PLOGE << "Failed to get JVMTI environment, error: " << err;
return JNI_FALSE; return JNI_FALSE;
} }
int result = InitJuiceLoader(env, jvmti); // Invoke EntryPoint
if (result != 0) { JuiceAgent::Agent& agent = JuiceAgent::Agent::instance();
PLOGE << "Failed to initialize JuiceLoader, error code: " << result; agent.init(jvm, env, jvmti);
return JNI_FALSE;
}
PLOGI << "JuiceLoader initialized successfully";
return JNI_TRUE; return JNI_TRUE;
} }
@@ -0,0 +1,117 @@
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class cn_xiaozhou233_juiceagent_api_JuiceAgent */
#ifndef _Included_cn_xiaozhou233_juiceagent_api_JuiceAgent
#define _Included_cn_xiaozhou233_juiceagent_api_JuiceAgent
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
* Method: init
* Signature: ()Z
*/
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init
(JNIEnv *, jclass);
/*
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
* Method: addToBootstrapClassLoaderSearch
* Signature: (Ljava/lang/String;)Z
*/
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToBootstrapClassLoaderSearch
(JNIEnv *, jclass, jstring);
/*
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
* Method: addToSystemClassLoaderSearch
* Signature: (Ljava/lang/String;)Z
*/
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToSystemClassLoaderSearch
(JNIEnv *, jclass, jstring);
/*
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
* Method: addToClassLoader
* Signature: (Ljava/lang/String;Ljava/lang/ClassLoader;)Z
*/
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToClassLoader
(JNIEnv *, jclass, jstring, jobject);
/*
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
* Method: defineClass
* Signature: (Ljava/lang/ClassLoader;[B)Ljava/lang/Class;
*/
JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_defineClass
(JNIEnv *, jclass, jobject, jbyteArray);
/*
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
* Method: redefineClass
* Signature: (Ljava/lang/Class;[BI)Z
*/
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClass
(JNIEnv *, jclass, jclass, jbyteArray, jint);
/*
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
* Method: redefineClassByName
* Signature: (Ljava/lang/String;[BI)Z
*/
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClassByName
(JNIEnv *, jclass, jstring, jbyteArray, jint);
/*
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
* Method: retransformClass
* Signature: (Ljava/lang/Class;[BI)Z
*/
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClass
(JNIEnv *, jclass, jclass, jbyteArray, jint);
/*
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
* Method: retransformClassByName
* Signature: (Ljava/lang/String;[BI)Z
*/
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClassByName
(JNIEnv *, jclass, jstring, jbyteArray, jint);
/*
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
* Method: getLoadedClasses
* Signature: ()[Ljava/lang/Class;
*/
JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getLoadedClasses
(JNIEnv *, jclass);
/*
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
* Method: getClassByName
* Signature: (Ljava/lang/String;)Ljava/lang/Class;
*/
JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassByName
(JNIEnv *, jclass, jstring);
/*
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
* Method: getClassBytes
* Signature: (Ljava/lang/Class;)[B
*/
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytes
(JNIEnv *, jclass, jclass);
/*
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
* Method: getClassBytesByName
* Signature: (Ljava/lang/String;)[B
*/
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytesByName
(JNIEnv *, jclass, jstring);
#ifdef __cplusplus
}
#endif
#endif
+38
View File
@@ -0,0 +1,38 @@
#pragma once
#include <jni.h>
#include <jvmti.h>
#include <vector>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <mutex>
// Data Structures
struct ClassRetransformRequest {
std::string classname;
std::vector<unsigned char> bytecode;
};
struct ClassFileData {
std::string classname;
std::vector<unsigned char> bytecode;
// ======== Global references to prevent GC ========
// Remember to release these references when they are no longer needed, otherwise it will cause memory leaks
jclass clazz;
jobject classloader;
jobject protection_domain;
};
// Set of target class internal names to capture (e.g. java/lang/String)
extern std::unordered_set<std::string> classToCapture;
// Cache of captured class bytecode, keyed by internal class name
extern std::unordered_map<std::string, ClassFileData> classFileDataMap;
// Mutex protecting access to classToCapture and classFileDataMap (thread-safe for JVMTI callbacks)
extern std::mutex classDataMutex;
extern std::unordered_map<std::string, std::vector<unsigned char>> pendingRetransform;
extern std::mutex pendingRetransformMutex;
+26
View File
@@ -0,0 +1,26 @@
#pragma once
#include <jni.h>
#include <jvmti.h>
#include <JuiceAgent/Logger.hpp>
#include <libagent.hpp>
#include <utils.hpp>
#include <global.hpp>
#include <algorithm>
// Generated by JuiceAgent-API
#include <cn_xiaozhou233_juiceagent_api_JuiceAgent.h>
// Event callbacks
// See https://docs.oracle.com/javase/8/docs/platform/jvmti/jvmti.html#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);
-10
View File
@@ -1,10 +0,0 @@
#ifndef LIBAGENT_H
#define LIBAGENT_H
#include <stdbool.h>
extern "C" __declspec(dllexport)
bool InitJuiceAgent(const char* runtime_path);
#endif // LIBAGENT_H
+35
View File
@@ -0,0 +1,35 @@
#pragma once
#include <JuiceAgent/Logger.hpp>
#include <jni.h>
#include <jvmti.h>
namespace JuiceAgent {
class Agent {
private:
JavaVM* jvm;
jvmtiEnv* jvmti;
private:
Agent() = default;
~Agent() = default;
public:
// ===== Singleton =====
static Agent& instance();
Agent(const Agent&) = delete;
Agent& operator=(const Agent&) = delete;
// EntryPoint
bool init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti);
// getters
JavaVM* get_jvm() const { return jvm; }
jvmtiEnv* get_jvmti() const { return jvmti; }
// setters
void set_jvm(JavaVM* jvm) { this->jvm = jvm; }
void set_jvmti(jvmtiEnv* jvmti) { this->jvmti = jvmti; }
};
}
+43
View File
@@ -0,0 +1,43 @@
#pragma once
#include <libagent.hpp>
inline bool check_env(JuiceAgent::Agent& agent) {
if (agent.get_jvm() == nullptr) {
PLOGE << "Failed to get JavaVM instance";
return false;
}
if (agent.get_jvmti() == nullptr) {
PLOGE << "Failed to get JVMTI environment";
return false;
}
return true;
}
inline std::string get_class_name(JNIEnv* env, jclass clazz) {
if (!env || !clazz) return "";
jclass clsClass = env->FindClass("java/lang/Class");
if (!clsClass) return "";
jmethodID mid = env->GetMethodID(clsClass, "getName", "()Ljava/lang/String;");
if (!mid) {
env->DeleteLocalRef(clsClass);
return "";
}
jstring nameStr = static_cast<jstring>(env->CallObjectMethod(clazz, mid));
std::string result;
if (nameStr) {
const char* tmp = env->GetStringUTFChars(nameStr, nullptr);
if (tmp) {
result = tmp; // copy to std::string
env->ReleaseStringUTFChars(nameStr, tmp);
}
env->DeleteLocalRef(nameStr);
}
env->DeleteLocalRef(clsClass);
return result;
}
+328
View File
@@ -0,0 +1,328 @@
#include <jni_impl.hpp>
#include <algorithm>
#include <string>
#include <cstring>
// ============================
// Get class bytecode (already captured)
// ============================
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytes
(JNIEnv *env, jclass, jclass clazz) {
auto& agent = JuiceAgent::Agent::instance();
if (!check_env(agent)) return nullptr;
char* signature = nullptr;
if (agent.get_jvmti()->GetClassSignature(clazz, &signature, nullptr) != JVMTI_ERROR_NONE || !signature)
return nullptr;
// Convert Lxxx; -> xxx
std::string internalName(signature + 1, strlen(signature) - 2);
agent.get_jvmti()->Deallocate(reinterpret_cast<unsigned char*>(signature));
// ============================
// 1. Mark class for capture
// ============================
{
std::lock_guard<std::mutex> lock(classDataMutex);
classToCapture.insert(internalName);
}
// ============================
// 2. Trigger class retransform
// ============================
jvmtiError err = agent.get_jvmti()->RetransformClasses(1, &clazz);
if (err != JVMTI_ERROR_NONE) {
PLOGE << "Retransform class failed: " << err;
return nullptr;
}
// ============================
// 3. Retrieve bytecode from cache
// ============================
ClassFileData data;
{
std::lock_guard<std::mutex> lock(classDataMutex);
auto it = classFileDataMap.find(internalName);
if (it != classFileDataMap.end()) {
data = it->second;
}
}
if (data.bytecode.empty()) {
PLOGE << "Failed to capture bytecode for class: " << internalName;
return nullptr;
}
jbyteArray out = env->NewByteArray(static_cast<jsize>(data.bytecode.size()));
if (!out || env->ExceptionCheck()) {
env->ExceptionClear();
return nullptr;
}
env->SetByteArrayRegion(out, 0, static_cast<jsize>(data.bytecode.size()), reinterpret_cast<const jbyte*>(data.bytecode.data()));
return out;
}
// ============================
// Get class bytecode by class name
// ============================
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytesByName
(JNIEnv *env, jclass loader_class, jstring name) {
if (!name) return nullptr;
auto& agent = JuiceAgent::Agent::instance();
if (!check_env(agent)) return nullptr;
// ============================
// 1. Convert jstring -> internal name
// ============================
const char* utf = env->GetStringUTFChars(name, nullptr);
if (!utf) return nullptr;
std::string internalName(utf);
env->ReleaseStringUTFChars(name, utf);
// Convert dots to slashes: a.b.C -> a/b/C
std::replace(internalName.begin(), internalName.end(), '.', '/');
// ============================
// 2. Iterate loaded classes
// ============================
jint count = 0;
jclass* classes = nullptr;
jvmtiEnv* jvmti = agent.get_jvmti();
if (jvmti->GetLoadedClasses(&count, &classes) != JVMTI_ERROR_NONE || count == 0) {
return nullptr;
}
jclass targetClass = nullptr;
for (jint i = 0; i < count; i++) {
char* signature = nullptr;
if (jvmti->GetClassSignature(classes[i], &signature, nullptr) == JVMTI_ERROR_NONE && signature) {
size_t len = strlen(signature);
if (len > 2 && signature[0] == 'L' && signature[len - 1] == ';') {
if (internalName == std::string_view(signature + 1, len - 2)) {
targetClass = classes[i];
jvmti->Deallocate(reinterpret_cast<unsigned char*>(signature));
break;
}
}
jvmti->Deallocate(reinterpret_cast<unsigned char*>(signature));
}
}
if (classes) {
jvmti->Deallocate(reinterpret_cast<unsigned char*>(classes));
}
if (!targetClass) {
PLOGE << "Class not loaded: " << internalName;
return nullptr;
}
// ============================
// 3. Reuse getClassBytes logic
// ============================
return Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytes(env, loader_class, targetClass);
}
// ============================
// Redefine class using jclass
// ============================
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClass
(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray class_bytes, jint class_bytes_len) {
// Get singleton agent instance
auto& agent = JuiceAgent::Agent::instance();
if (!check_env(agent))
return JNI_FALSE;
// Get byte array elements
jbyte* buf = env->GetByteArrayElements(class_bytes, nullptr);
if (!buf) {
PLOGE << "Cannot get class bytes";
return JNI_FALSE;
}
// Prepare JVMTI class definition
jvmtiClassDefinition defs[1];
defs[0].klass = clazz;
defs[0].class_byte_count = class_bytes_len;
defs[0].class_bytes = reinterpret_cast<const unsigned char*>(buf);
// Redefine class via JVMTI
jvmtiError result = agent.get_jvmti()->RedefineClasses(1, defs);
// Release byte array (no need to copy back)
env->ReleaseByteArrayElements(class_bytes, buf, JNI_ABORT);
if (result != JVMTI_ERROR_NONE) {
PLOGE << "Redefine class failed: " << result;
return JNI_FALSE;
}
PLOGD << "Class redefined successfully!";
return JNI_TRUE;
}
// ============================================
// Redefine class using its fully qualified name
// Supports automatic '.' -> '/' conversion
// ============================================
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClassByName
(JNIEnv *env, jclass loader_class, jstring class_name, jbyteArray class_bytes, jint class_bytes_len) {
// Convert jstring to C string
const char* cname = env->GetStringUTFChars(class_name, nullptr);
if (!cname) {
PLOGE << "Class name is NULL!";
return JNI_FALSE;
}
// Copy and replace '.' with '/' for JVM internal class name
std::string internal_name(cname);
std::replace(internal_name.begin(), internal_name.end(), '.', '/');
// Release the original Java string
env->ReleaseStringUTFChars(class_name, cname);
// Find class by internal name
jclass clazz = env->FindClass(internal_name.c_str());
if (!clazz) {
PLOGE << "Cannot find class: " << internal_name;
return JNI_FALSE;
}
// Call redefineClass with the found class
return Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClass(
env, loader_class, clazz, class_bytes, class_bytes_len
);
}
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClass
(JNIEnv* env, jclass, jclass clazz, jbyteArray bytecodes, jint length) {
auto& agent = JuiceAgent::Agent::instance();
// =========================
// 1. Check environment & parameters
// =========================
if (!check_env(agent) || !clazz || !bytecodes) {
return JNI_FALSE;
}
// =========================
// 2. Get class internal name
// =========================
std::string nameDot = get_class_name(env, clazz);
if (nameDot.empty()) {
PLOGE << "Failed to get class name for retransform";
return JNI_FALSE;
}
// Convert '.' to '/' for internal name
for (auto& c : nameDot) if (c == '.') c = '/';
// =========================
// 3. Extract bytecode from jbyteArray
// =========================
jbyte* bytes = env->GetByteArrayElements(bytecodes, nullptr);
jint len = env->GetArrayLength(bytecodes);
if (!bytes || len <= 0) {
return JNI_FALSE;
}
// =========================
// 4. Cache bytecode & class info for ClassFileLoadHook
// =========================
{
std::lock_guard<std::mutex> lock(classDataMutex);
ClassFileData data;
data.classname = nameDot;
data.bytecode.assign(bytes, bytes + len);
data.clazz = static_cast<jclass>(env->NewGlobalRef(clazz)); // prevent GC
data.classloader = nullptr; // optional
data.protection_domain = nullptr;
classFileDataMap[nameDot] = std::move(data);
}
env->ReleaseByteArrayElements(bytecodes, bytes, JNI_ABORT);
// =========================
// 5. Trigger JVMTI retransform
// =========================
jclass classes[1] = { clazz };
jvmtiError err = agent.get_jvmti()->RetransformClasses(1, classes);
if (err != JVMTI_ERROR_NONE) {
PLOGE << "[retransformClass] failed: " << err << " for " << nameDot;
return JNI_FALSE;
}
PLOGI << "[retransformClass] OK: " << nameDot << " (" << len << " bytes)";
return JNI_TRUE;
}
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClassByName
(JNIEnv* env, jclass, jstring className, jbyteArray bytecodes, jint length) {
auto& agent = JuiceAgent::Agent::instance();
if (!check_env(agent) || !className || !bytecodes) {
return JNI_FALSE;
}
// =========================
// 1. Get UTF string from jstring
// =========================
const char* utf = env->GetStringUTFChars(className, nullptr);
if (!utf) return JNI_FALSE;
std::string internalName(utf);
env->ReleaseStringUTFChars(className, utf);
// Convert '.' to '/' for internal name
for (auto& c : internalName) if (c == '.') c = '/';
// =========================
// 2. Find loaded class by internal name (inline)
// =========================
jclass target = nullptr;
{
jint classCount = 0;
jclass* loadedClasses = nullptr;
if (agent.get_jvmti()->GetLoadedClasses(&classCount, &loadedClasses) == JVMTI_ERROR_NONE && classCount > 0) {
for (jint i = 0; i < classCount; ++i) {
char* sig = nullptr;
if (agent.get_jvmti()->GetClassSignature(loadedClasses[i], &sig, nullptr) == JVMTI_ERROR_NONE && sig) {
// sig: "Lnet/minecraft/client/Minecraft;"
if (sig[0] == 'L') {
size_t len = strlen(sig);
if (len > 2 && internalName == std::string(sig + 1, len - 2)) {
target = loadedClasses[i];
agent.get_jvmti()->Deallocate(reinterpret_cast<unsigned char*>(sig));
break;
}
}
agent.get_jvmti()->Deallocate(reinterpret_cast<unsigned char*>(sig));
}
}
agent.get_jvmti()->Deallocate(reinterpret_cast<unsigned char*>(loadedClasses));
}
}
if (!target) {
PLOGE << "[retransformClassByName] class not loaded: " << internalName;
return JNI_FALSE;
}
// =========================
// 3. Delegate to retransformClass
// =========================
return Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClass(
env, nullptr, target, bytecodes, length
);
}
+275
View File
@@ -0,0 +1,275 @@
#include <jni_impl.hpp>
// Add jar to bootstrap classloader search path
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToBootstrapClassLoaderSearch
(JNIEnv *env, jclass, jstring jar_path) {
auto& agent = JuiceAgent::Agent::instance();
if (!check_env(agent))
return JNI_FALSE;
const char* j_jar_path = env->GetStringUTFChars(jar_path, nullptr);
if (!j_jar_path) {
PLOGE << "Path is NULL!";
return JNI_FALSE;
}
jvmtiError result = agent.get_jvmti()->AddToBootstrapClassLoaderSearch(j_jar_path);
if (result != JVMTI_ERROR_NONE) {
PLOGE.printf("Cannot AddToBootstrapClassLoaderSearch [result=%d]", result);
env->ReleaseStringUTFChars(jar_path, j_jar_path);
return JNI_FALSE;
}
PLOGI << "AddToBootstrapClassLoaderSearch: " << j_jar_path;
env->ReleaseStringUTFChars(jar_path, j_jar_path);
return JNI_TRUE;
}
// Add jar to system classloader search path
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToSystemClassLoaderSearch
(JNIEnv *env, jclass, jstring jar_path) {
auto& agent = JuiceAgent::Agent::instance();
if (!check_env(agent))
return JNI_FALSE;
const char* j_jar_path = env->GetStringUTFChars(jar_path, nullptr);
if (!j_jar_path) {
PLOGE << "Path is NULL!";
return JNI_FALSE;
}
jvmtiError result = agent.get_jvmti()->AddToSystemClassLoaderSearch(j_jar_path);
if (result != JVMTI_ERROR_NONE) {
PLOGE.printf("Cannot AddToSystemClassLoaderSearch [result=%d]", result);
env->ReleaseStringUTFChars(jar_path, j_jar_path);
return JNI_FALSE;
}
PLOGI << "AddToSystemClassLoaderSearch: " << j_jar_path;
env->ReleaseStringUTFChars(jar_path, j_jar_path);
return JNI_TRUE;
}
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToClassLoader
(JNIEnv *env, jclass, jstring jar_path, jobject target_classloader) {
auto& agent = JuiceAgent::Agent::instance();
if (!check_env(agent))
return JNI_FALSE;
if (!jar_path || !target_classloader)
return JNI_FALSE;
// --- Try URLClassLoader path ---
jclass urlClassLoader = env->FindClass("java/net/URLClassLoader");
if (env->ExceptionCheck() || !urlClassLoader) {
env->ExceptionClear();
goto FALLBACK;
}
if (env->IsInstanceOf(target_classloader, urlClassLoader)) {
jclass fileClass = env->FindClass("java/io/File");
if (env->ExceptionCheck() || !fileClass) {
env->ExceptionClear();
goto FALLBACK;
}
jmethodID fileInit = env->GetMethodID(fileClass, "<init>", "(Ljava/lang/String;)V");
if (env->ExceptionCheck() || !fileInit) {
env->ExceptionClear();
goto FALLBACK;
}
jobject file = env->NewObject(fileClass, fileInit, jar_path);
if (env->ExceptionCheck() || !file) {
env->ExceptionClear();
goto FALLBACK;
}
jmethodID toURI = env->GetMethodID(fileClass, "toURI", "()Ljava/net/URI;");
if (env->ExceptionCheck() || !toURI) {
env->ExceptionClear();
env->DeleteLocalRef(file);
goto FALLBACK;
}
jobject uri = env->CallObjectMethod(file, toURI);
if (env->ExceptionCheck() || !uri) {
env->ExceptionClear();
env->DeleteLocalRef(file);
goto FALLBACK;
}
jclass uriClass = env->FindClass("java/net/URI");
if (env->ExceptionCheck() || !uriClass) {
env->ExceptionClear();
env->DeleteLocalRef(file);
env->DeleteLocalRef(uri);
goto FALLBACK;
}
jmethodID toURL = env->GetMethodID(uriClass, "toURL", "()Ljava/net/URL;");
if (env->ExceptionCheck() || !toURL) {
env->ExceptionClear();
env->DeleteLocalRef(file);
env->DeleteLocalRef(uri);
goto FALLBACK;
}
jobject url = env->CallObjectMethod(uri, toURL);
if (env->ExceptionCheck() || !url) {
env->ExceptionClear();
env->DeleteLocalRef(file);
env->DeleteLocalRef(uri);
goto FALLBACK;
}
jmethodID addURL = env->GetMethodID(urlClassLoader, "addURL", "(Ljava/net/URL;)V");
if (env->ExceptionCheck() || !addURL) {
env->ExceptionClear();
env->DeleteLocalRef(file);
env->DeleteLocalRef(uri);
env->DeleteLocalRef(url);
goto FALLBACK;
}
env->CallVoidMethod(target_classloader, addURL, url);
if (env->ExceptionCheck()) {
env->ExceptionClear();
env->DeleteLocalRef(file);
env->DeleteLocalRef(uri);
env->DeleteLocalRef(url);
goto FALLBACK;
}
// cleanup
env->DeleteLocalRef(file);
env->DeleteLocalRef(uri);
env->DeleteLocalRef(url);
return JNI_TRUE;
}
FALLBACK:
// --- JVMTI fallback ---
const char* j_jar_path = env->GetStringUTFChars(jar_path, nullptr);
if (!j_jar_path)
return JNI_FALSE;
jvmtiError err = agent.get_jvmti()->AddToSystemClassLoaderSearch(j_jar_path);
env->ReleaseStringUTFChars(jar_path, j_jar_path);
if (err != JVMTI_ERROR_NONE) {
return JNI_FALSE;
}
return JNI_TRUE;
}
// TODO: Safety and Compatibility: Define Class
// Define class using target classloader
JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_defineClass
(JNIEnv *env, jclass, jobject target_classloader, jbyteArray bytes) {
auto& agent = JuiceAgent::Agent::instance();
if (!check_env(agent))
return nullptr;
jclass clClass = env->FindClass("java/lang/ClassLoader");
jmethodID defineClass = env->GetMethodID(clClass, "defineClass", "([BII)Ljava/lang/Class;");
jobject classDefined = env->CallObjectMethod(target_classloader, defineClass, bytes, 0,
env->GetArrayLength(bytes));
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
return nullptr;
}
return (jclass)classDefined;
}
JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getLoadedClasses
(JNIEnv *env, jclass) {
auto& agent = JuiceAgent::Agent::instance();
if (!check_env(agent))
return nullptr;
jint count = 0;
jclass* classes = nullptr;
jvmtiError err = agent.get_jvmti()->GetLoadedClasses(&count, &classes);
if (err != JVMTI_ERROR_NONE) {
PLOGE.printf("GetLoadedClasses failed: %d", err);
return nullptr;
}
jclass classClass = env->FindClass("java/lang/Class");
jobjectArray classesArray = env->NewObjectArray(count, classClass, nullptr);
for (int i = 0; i < count; i++) {
env->SetObjectArrayElement(classesArray, i, classes[i]);
}
agent.get_jvmti()->Deallocate((unsigned char*)classes);
return classesArray;
}
JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassByName
(JNIEnv *env, jclass, jstring name) {
auto& agent = JuiceAgent::Agent::instance();
if (!check_env(agent))
return nullptr;
const char* utf = env->GetStringUTFChars(name, nullptr);
if (!utf) {
PLOGE << "Class name is NULL!";
return nullptr;
}
// Convert Java name to internal name: a.b.C -> a/b/C
std::string internal_name(utf);
std::replace(internal_name.begin(), internal_name.end(), '.', '/');
env->ReleaseStringUTFChars(name, utf);
// Get all loaded classes
jint count = 0;
jclass* classes = nullptr;
if (agent.get_jvmti()->GetLoadedClasses(&count, &classes) != JVMTI_ERROR_NONE || count == 0) {
PLOGE << "GetLoadedClasses failed or no classes loaded";
return nullptr;
}
jclass result = nullptr;
for (jint i = 0; i < count; i++) {
char* signature = nullptr;
if (agent.get_jvmti()->GetClassSignature(classes[i], &signature, nullptr) != JVMTI_ERROR_NONE || !signature)
continue;
size_t sig_len = strlen(signature);
if (sig_len > 2 && signature[0] == 'L' && signature[sig_len - 1] == ';' &&
internal_name.size() == sig_len - 2 &&
strncmp(signature + 1, internal_name.c_str(), sig_len - 2) == 0) {
result = classes[i];
agent.get_jvmti()->Deallocate((unsigned char*)signature);
break;
}
agent.get_jvmti()->Deallocate((unsigned char*)signature);
}
if (classes) {
agent.get_jvmti()->Deallocate((unsigned char*)classes);
}
if (!result) {
PLOGE << "Failed to find loaded class: " << internal_name;
}
return result;
}
+2
View File
@@ -0,0 +1,2 @@
#include <jni_impl.hpp>
+51 -237
View File
@@ -1,251 +1,65 @@
#include <jvm/jni.h> #include <libagent.hpp>
#include <jvm/jvmti.h> #include <jni_impl.hpp>
#include <stdio.h>
#include <JuiceAgent/Logger.hpp>
#include <libagent.h>
#include <thread>
#include <tinytoml/toml.h>
#include <JuiceAgent/JuiceAgent.h>
struct _JuiceAgent { namespace JuiceAgent {
bool isAttached; // ===== Singleton =====
JavaVM *jvm; Agent& Agent::instance() {
jvmtiEnv *jvmti; static Agent instance;
JNIEnv *env; return instance;
} JuiceAgent = {false, NULL, NULL, NULL}; }
InjectionInfoType InjectionInfo; bool Agent::init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti) {
PLOGI << "JuiceAgent Native EntryPoint Invoked!";
static int ReadConfig(const char* ConfigDir) // ======== neccessary environment check ========
{ if (jvm == nullptr) {
// ConfigDir/config.toml PLOGE << "Failed to initialize JuiceAgent: jvm is null";
std::string path = std::string(ConfigDir) + "\\config.toml"; return false;
std::ifstream ifs(path); }
if (!ifs) return -1; if (env == nullptr) {
PLOGE << "Failed to initialize JuiceAgent: env is null";
// Parse toml return false;
toml::ParseResult pr = toml::parse(ifs); }
if (!pr.valid()) return -2; if (jvmti == nullptr) {
PLOGE << "Failed to initialize JuiceAgent: jvmti is null";
const toml::Value& tbl = pr.value; return false;
// Helper function: get string from toml
auto get_str = [&](const char* key, const char* def, char* out) {
const toml::Value* v = tbl.find(key);
if (v && v->is<std::string>()) {
std::string s = v->as<std::string>();
if (!s.empty()) {
strncpy(out, s.c_str(), INJECT_PATH_MAX - 1);
PLOGD << "Found parameter: " << key << " = " << s.c_str();
} else {
strncpy(out, def, INJECT_PATH_MAX - 1);
PLOGD << "Parameter " << key << " is empty, use default: " << def;
}
} else {
strncpy(out, def, INJECT_PATH_MAX - 1);
PLOGD << "Not found parameter: " << key << ", use default: " << def;
} }
out[INJECT_PATH_MAX - 1] = '\0';
};
// Default values set_jvm(jvm);
std::string defaultJuiceLoader = std::string(ConfigDir) + "\\JuiceLoader.jar"; set_jvmti(jvmti);
std::string defaultJuiceLoaderLibrary = std::string(ConfigDir) + "\\libjuiceloader.dll";
std::string defaultEntryJar = std::string(ConfigDir) + "\\Entry.jar";
std::string defaultInjectionDir = std::string(ConfigDir) + "\\injection";
get_str("JuiceLoaderJarPath", defaultJuiceLoader.c_str(), InjectionInfo.JuiceLoaderJarPath); PLOGD << "env: " << env << ", jvmti: " << jvmti;
get_str("JuiceLoaderLibraryPath", defaultJuiceLoaderLibrary.c_str(), InjectionInfo.JuiceLoaderLibraryPath);
get_str("InjectionDir", defaultInjectionDir.c_str(), InjectionInfo.InjectionDir);
get_str("EntryJarPath", defaultEntryJar.c_str(), InjectionInfo.EntryJarPath);
get_str("EntryClass", "cn.xiaozhou233.test.Entry", InjectionInfo.EntryClass);
get_str("EntryMethod", "start", InjectionInfo.EntryMethod);
PLOGD << "JuiceLoaderJarPath: " << InjectionInfo.JuiceLoaderJarPath; // ======== Application ability ========
PLOGD << "JuiceLoaderLibraryPath: " << InjectionInfo.JuiceLoaderLibraryPath; jvmtiCapabilities caps{};
PLOGD << "InjectionDir: " << InjectionInfo.InjectionDir; caps.can_get_bytecodes = 1;
PLOGD << "EntryJarPath: " << InjectionInfo.EntryJarPath; caps.can_redefine_classes = 1;
PLOGD << "EntryClass: " << InjectionInfo.EntryClass; caps.can_redefine_any_class = 1;
PLOGD << "EntryMethod: " << InjectionInfo.EntryMethod; caps.can_retransform_classes = 1;
caps.can_retransform_any_class = 1;
caps.can_generate_all_class_hook_events = 1;
jint result = jvmti->AddCapabilities(&caps);
if (result != JNI_OK) {
PLOGE << "Failed to add capabilities: " << result;
return false;
}
return 0; PLOGI << "Abilities added successfully";
}
// ======== Register callbacks ========
static int GetJavaEnv() { jvmtiEventCallbacks callbacks{};
jint res = JNI_ERR; callbacks.ClassFileLoadHook = &ClassFileLoadHook;
JavaVM *jvm = NULL; result = jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks));
jvmtiEnv *jvmti = NULL; if (result != JNI_OK) {
JNIEnv *env = NULL; PLOGE << "Failed to set event callbacks: " << result;
int max_try = 30;
// Get the JVM
max_try = 30;
do {
res = JNI_GetCreatedJavaVMs(&jvm, 1, NULL);
if (res != JNI_OK || jvm == NULL) {
PLOGE.printf("JNI_GetCreatedJavaVMs failed: %d", res);
PLOGD << "JVM NULL: " << (jvm == NULL);
}
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
max_try--;
if (jvm != NULL) {
break;
} else {
PLOGI.printf("Waiting for JVM... (%d)", max_try);
} }
} while (jvm == NULL && max_try > 0);
if (jvm == NULL) {
PLOGE << "GetJavaEnv failed";
return res;
}
JuiceAgent.jvm = jvm;
PLOGI << "Got the JVM";
// Get the JNIEnv // Enable events
max_try = 30; result = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, NULL);
do { if (result != JNI_OK) {
res = jvm->GetEnv((void**)&env, JNI_VERSION_1_8); PLOGE << "Failed to enable event notification: " << result;
if (res != JNI_OK || env == NULL) {
PLOGI << "GetEnv failed, trying to attach.";
PLOGD << "env NULL: " << (env == NULL);
res = jvm->AttachCurrentThread((void**)&env, NULL);
if (res != JNI_OK || env == NULL) {
PLOGE.printf("AttachCurrentThread failed: %d", res);
PLOGD << "env NULL: " << (env == NULL);
return res;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
max_try--;
if (env != NULL) {
break;
} else {
PLOGI.printf("Waiting for JNI... (%d)", max_try);
} }
} while (env == NULL && max_try > 0);
if (env == NULL) {
PLOGE << "Get JNI failed";
return res;
}
JuiceAgent.env = env;
PLOGI << "Got the JNIEnv";
// Get the JVMTI
res = jvm->GetEnv((void**)&jvmti, JVMTI_VERSION_1_2);
if (res != JNI_OK || jvmti == NULL) {
PLOGE.printf("GetEnv failed: %d", res);
PLOGD << "jvmti NULL: " << (jvmti == NULL);
return res;
}
JuiceAgent.jvmti = jvmti;
PLOGI << "Got the JVMTI";
return 0;
}
static int InvokeJuiceLoaderInit(const char* ConfigDir) {
// Variables
int result = JNI_ERR;
JNIEnv *env = JuiceAgent.env;
jvmtiEnv *jvmti = JuiceAgent.jvmti;
const char *bootstrap_class = "cn/xiaozhou233/juiceloader/JuiceLoaderBootstrap";
const char *method_name = "init";
const char *method_signature = "([Ljava/lang/String;)V";
PLOGI << "Invoke JuiceLoader Init";
PLOGI << "================ JuiceLoader Init =================";
// Find class
jclass cls = env->FindClass(bootstrap_class);
if (cls == NULL) {
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
}
PLOGE << "FindClass failed";
return 1;
}
// Find method
jmethodID mid = env->GetStaticMethodID(cls, method_name, method_signature);
if (mid == NULL) {
PLOGE << "GetStaticMethodID failed";
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
}
return 1;
}
// arguments array return true;
const char* args[] = {
InjectionInfo.EntryJarPath,
InjectionInfo.EntryClass,
InjectionInfo.EntryMethod,
InjectionInfo.InjectionDir,
InjectionInfo.JuiceLoaderLibraryPath
};
int argCount = sizeof(args)/sizeof(args[0]);
jclass stringCls = env->FindClass("java/lang/String");
jobjectArray jArgs = env->NewObjectArray(argCount, stringCls, nullptr);
for (int i = 0; i < argCount; i++) {
env->SetObjectArrayElement(jArgs, i, env->NewStringUTF(args[i]));
}
// Invoke method
env->CallStaticVoidMethod(cls, mid, jArgs);
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
} }
PLOGI << "================ JuiceLoader Init =================";
PLOGI << "Invoke JuiceLoader Init done";
return 0;
}
extern "C" __declspec(dllexport)
bool InitJuiceAgent(const char* runtime_path) {
PLOGI << "--------> InitJuiceAgent Invoke <--------";
PLOGD << "runtime_path: " << runtime_path;
// Read Config
PLOGI << "ReadConfig ...";
if (ReadConfig(runtime_path) != 0) {
PLOGE << "ReadConfig failed";
return false;
}
PLOGI << "[OK] ReadConfig";
// Get JavaEnv
PLOGI << "Get JavaEnv ...";
if (GetJavaEnv() != 0) {
PLOGE << "GetJavaEnv failed";
return false;
}
PLOGI << "[OK] Get JavaEnv";
// Inject JuiceLoader jar
PLOGI << "Inject JuiceLoader jar ...";
if (JuiceAgent.jvmti->AddToSystemClassLoaderSearch(InjectionInfo.JuiceLoaderJarPath) != JNI_OK) {
PLOGE << "AddToSystemClassLoaderSearch failed";
return false;
}
PLOGI << "[OK] Inject JuiceLoader jar";
// Invoke JuiceLoader Init
PLOGI << "Invoke JuiceLoader Init ...";
if (InvokeJuiceLoaderInit(runtime_path) != 0) {
PLOGE << "Invoke JuiceLoader Init failed";
return false;
}
PLOGI << "[OK] Invoke JuiceLoader Init";
// Load JuiceLoaderLibrary
PLOGI << "--------> InitJuiceAgent Succeed <--------";
return true;
} }
+14 -5
View File
@@ -1,10 +1,19 @@
file(
GLOB_RECURSE # libinject
libinjector_sources add_library(inject SHARED libinject.c)
${CMAKE_CURRENT_SOURCE_DIR}/*.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 target_include_directories(injector PRIVATE
${CMAKE_SOURCE_DIR}/includes ${CMAKE_SOURCE_DIR}/includes
+107
View File
@@ -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\\libloader.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.
-22
View File
@@ -1,22 +0,0 @@
file(
GLOB_RECURSE
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})
target_include_directories(juiceloader PRIVATE
${CMAKE_SOURCE_DIR}/includes
${CMAKE_SOURCE_DIR}/includes/jvm
${CMAKE_SOURCE_DIR}/includes/jvm/win32
${CMAKE_CURRENT_SOURCE_DIR}/includes
)
target_link_libraries(juiceloader PRIVATE
ReflectiveDLLInjection
jvm
)
@@ -1,109 +0,0 @@
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class cn_xiaozhou233_juiceloader_JuiceLoader */
#ifndef _Included_cn_xiaozhou233_juiceloader_JuiceLoader
#define _Included_cn_xiaozhou233_juiceloader_JuiceLoader
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
* Method: init
* Signature: ()Z
*/
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_init
(JNIEnv *, jclass);
/*
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
* Method: injectJar
* Signature: (Ljava/lang/String;)Z
*/
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_injectJar
(JNIEnv *, jclass, jstring);
/*
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
* Method: redefineClass
* Signature: (Ljava/lang/Class;[BI)Z
*/
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_redefineClass
(JNIEnv *, jclass, jclass, jbyteArray, jint);
/*
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
* Method: redefineClassByName
* Signature: (Ljava/lang/String;[BI)Z
*/
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_redefineClassByName
(JNIEnv *, jclass, jstring, jbyteArray, jint);
/*
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
* Method: getLoadedClasses
* Signature: ()[Ljava/lang/Class;
*/
JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getLoadedClasses
(JNIEnv *, jclass);
/*
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
* Method: getClassBytes
* Signature: (Ljava/lang/Class;)[B
*/
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytes
(JNIEnv *, jclass, jclass);
/*
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
* Method: getClassBytesByName
* Signature: (Ljava/lang/String;)[B
*/
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytesByName
(JNIEnv *, jclass, jstring);
/*
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
* Method: retransformClass
* Signature: (Ljava/lang/Class;[BI)Z
*/
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClass
(JNIEnv *, jclass, jclass, jbyteArray, jint);
/*
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
* Method: retransformClassByName
* Signature: (Ljava/lang/String;[BI)Z
*/
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClassByName
(JNIEnv *, jclass, jstring, jbyteArray, jint);
/*
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
* Method: getClassByName
* Signature: (Ljava/lang/String;)Ljava/lang/Class;
*/
JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassByName
(JNIEnv *, jclass, jstring);
/*
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
* Method: nativeGetThreadByName
* Signature: (Ljava/lang/String;)Ljava/lang/Thread;
*/
JNIEXPORT jobject JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_nativeGetThreadByName
(JNIEnv *, jclass, jstring);
/*
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
* Method: nativeInjectJarToThread
* Signature: (Ljava/lang/Thread;Ljava/lang/String;)Ljava/lang/ClassLoader;
*/
JNIEXPORT jobject JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_nativeInjectJarToThread
(JNIEnv *, jclass, jobject, jstring);
#ifdef __cplusplus
}
#endif
#endif
-51
View File
@@ -1,51 +0,0 @@
#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
-29
View File
@@ -1,29 +0,0 @@
#ifndef JUICELOADER_H
#define JUICELOADER_H
#include <jni.h>
#include <jvmti.h>
typedef struct _JuiceLoaderNative {
jvmtiEnv *jvmti;
} JuiceLoaderNativeType;
extern JuiceLoaderNativeType JuiceLoaderNative;
typedef struct {
char *name;
unsigned char *bytes;
int len;
} ClassBytesCacheType;
typedef struct {
ClassBytesCacheType *arr;
int size;
int capacity;
} RetransformClassCacheType;
extern RetransformClassCacheType RetransformClassCache;
extern "C" __declspec(dllexport)
int InitJuiceLoader(JNIEnv *env, jvmtiEnv *jvmti);
#endif
@@ -1,72 +0,0 @@
#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;
}
}
}
-136
View File
@@ -1,136 +0,0 @@
#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;
}
-90
View File
@@ -1,90 +0,0 @@
#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;
}
@@ -1,57 +0,0 @@
#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;
}
@@ -1,72 +0,0 @@
#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);
}
-64
View File
@@ -1,64 +0,0 @@
#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
}
-67
View File
@@ -1,67 +0,0 @@
// JVM
#include <jni.h>
#include <jvmti.h>
#include <JuiceAgent/Logger.hpp>
#include <juiceloader.h>
#include <jni_impl.h>
JuiceLoaderNativeType JuiceLoaderNative;
static int ConfigureJVMTI(JNIEnv *env, _jvmtiEnv *jvmti) {
// Retransform Class Cache : to store classes that need to be retransformed
RetransformClassCache.arr = NULL;
RetransformClassCache.size = 0;
RetransformClassCache.capacity = 0;
// Application ability
jvmtiCapabilities caps;
memset(&caps, 0, sizeof(caps));
caps.can_get_bytecodes = 1;
caps.can_redefine_classes = 1;
caps.can_redefine_any_class = 1;
caps.can_retransform_classes = 1;
caps.can_retransform_any_class = 1;
caps.can_generate_all_class_hook_events = 1;
jint result = jvmti->AddCapabilities(&caps);
if (result != JNI_OK) {
PLOGE << "Failed to add capabilities: " << result;
return JNI_ERR;
}
// Register callbacks
jvmtiEventCallbacks callbacks;
memset(&callbacks, 0, sizeof(callbacks));
callbacks.ClassFileLoadHook = &ClassFileLoadHook;
jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks));
// Enable events
jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, NULL);
return JNI_OK;
}
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) {
PLOGE.printf("[-] Failed to initialize libjuiceloader: env is null");
return -1;
}
if (jvmti == nullptr) {
PLOGE.printf("[-] Failed to initialize libjuiceloader: jvmti is null");
return -1;
}
JuiceLoaderNative.jvmti = jvmti;
// Step 2: Configure JVMTI
if (ConfigureJVMTI(env, jvmti) != JNI_OK) {
PLOGE.printf("[-] Failed to initialize libjuiceloader: ConfigureJVMTI failed");
return -1;
}
return 0;
}
+29
View File
@@ -0,0 +1,29 @@
file(GLOB_RECURSE loader_sources
${CMAKE_CURRENT_SOURCE_DIR}/common/*.cpp
${CMAKE_CURRENT_SOURCE_DIR}/common/*.c
)
if (WIN32)
message(STATUS "Detected System: Windows")
file(GLOB_RECURSE windows_sources
${CMAKE_CURRENT_SOURCE_DIR}/windows/*.cpp
${CMAKE_CURRENT_SOURCE_DIR}/windows/*.c
)
list(APPEND loader_sources ${windows_sources})
endif()
add_library(loader SHARED ${loader_sources})
target_include_directories(loader PRIVATE
${CMAKE_SOURCE_DIR}/includes
${CMAKE_SOURCE_DIR}/includes/jvm
${CMAKE_SOURCE_DIR}/includes/jvm/win32
${CMAKE_CURRENT_SOURCE_DIR}/includes
)
target_link_libraries(loader PRIVATE
ReflectiveDLLInjection
jvm
)
+131
View File
@@ -0,0 +1,131 @@
#include <JuiceAgent/Logger.hpp>
#include <libloader.hpp>
#include <config.hpp>
#include <jvm.hpp>
namespace libloader {
namespace {
// Check for JNI exceptions and clear them
bool check_and_clear_exception(JNIEnv* env, const char* context) {
if (env->ExceptionCheck()) {
PLOGE << "JNI Exception occurred at: " << context;
env->ExceptionDescribe();
env->ExceptionClear();
return true;
}
return false;
}
// RAII wrapper for local JNI references
template<typename T>
class LocalRef {
private:
JNIEnv* env;
T ref;
public:
LocalRef(JNIEnv* env, T ref) : env(env), ref(ref) {}
~LocalRef() {
if (ref) env->DeleteLocalRef(ref);
}
T get() const { return ref; }
operator T() const { return ref; }
};
}
// Invoke JuiceAgentBootstrap.start(String) via JNI
bool invoke_juiceagent_init(JNIEnv* env, const InjectionInfo& info) {
const char* bootstrap_class = "cn/xiaozhou233/juiceagent/api/JuiceAgentBootstrap";
const char* method_name = "start";
const char* method_desc = "(Ljava/lang/String;)V";
// Find Java class
LocalRef<jclass> cls(env, env->FindClass(bootstrap_class));
if (!cls.get() || check_and_clear_exception(env, "FindClass")) {
PLOGE << "Failed to find class: " << bootstrap_class;
return false;
}
// Find static method
jmethodID method_id = env->GetStaticMethodID(cls, method_name, method_desc);
if (!method_id || check_and_clear_exception(env, "GetStaticMethodID")) {
PLOGE << "Failed to find method: " << method_name;
return false;
}
// Serialize InjectionInfo to string
std::string args = config::Config::serialize(info);
PLOGD << "Invoke args: " << args;
// Create Java string
jstring jArgs = env->NewStringUTF(args.c_str());
if (!jArgs || check_and_clear_exception(env, "NewStringUTF")) {
PLOGE << "Failed to create jstring";
return false;
}
// Call the static method
env->CallStaticVoidMethod(cls, method_id, jArgs);
// Check for exceptions
if (check_and_clear_exception(env, "CallStaticVoidMethod")) {
return false;
}
PLOGI << "JuiceAgentBootstrap.start invoked successfully";
return true;
}
// Entrypoint function for loader
void entrypoint(const char* runtime_dir) {
if (!runtime_dir) {
PLOGW << "runtime_dir is null, using empty path";
}
// Load configuration
config::Config cfg(runtime_dir);
if (!cfg.is_valid()) {
PLOGW << "Invalid config, using default values";
}
// Get InjectionInfo
InjectionInfo info = cfg.get_injection_info();
config::print_injection_info(info);
// Validate essential paths
if (info.JuiceAgentAPIJarPath.empty()) {
PLOGE << "JuiceAgentAPIJarPath is empty, abort injection";
return;
}
// Attach to JVM
jvm::Jvm jvm;
if (!jvm.attach()) {
PLOGE << "Attach to JVM failed";
return;
}
JNIEnv* env = jvm.get_env();
auto* jvmti = jvm.get_jvmti();
if (!env || !jvmti) {
PLOGE << "JNIEnv or JVMTI is null";
return;
}
// Inject JuiceAgent jar into system class loader
jint status = jvmti->AddToSystemClassLoaderSearch(info.JuiceAgentAPIJarPath.c_str());
if (status != JNI_OK) {
PLOGE << "AddToSystemClassLoaderSearch failed: " << status;
return;
}
PLOGI << "Jar injected successfully: " << info.JuiceAgentAPIJarPath;
// Invoke JuiceAgent initialization
if (!invoke_juiceagent_init(env, info)) {
PLOGE << "invoke_juiceagent_init failed";
}
}
} // namespace libloader
+246
View File
@@ -0,0 +1,246 @@
#include <jvm/jni.h>
#include <jvm/jvmti.h>
#include <stdio.h>
#include <JuiceAgent/Logger.hpp>
#include <libloader.h>
#include <thread>
#include <tinytoml/toml.h>
#include <JuiceAgent/JuiceAgent.h>
struct _JuiceAgent {
bool isAttached;
JavaVM *jvm;
jvmtiEnv *jvmti;
JNIEnv *env;
} JuiceAgent = {false, NULL, NULL, NULL};
InjectionInfoType InjectionInfo;
static int ReadConfig(const char* ConfigDir)
{
// ConfigDir/config.toml
std::string path = std::string(ConfigDir) + "\\config.toml";
std::ifstream ifs(path);
if (!ifs) return -1;
// Parse toml
toml::ParseResult pr = toml::parse(ifs);
if (!pr.valid()) return -2;
const toml::Value& tbl = pr.value;
// Helper function: get string from toml
auto get_str = [&](const char* key, const char* def, char* out) {
const toml::Value* v = tbl.find(key);
if (v && v->is<std::string>()) {
std::string s = v->as<std::string>();
if (!s.empty()) {
strncpy(out, s.c_str(), INJECT_PATH_MAX - 1);
PLOGD << "Found parameter: " << key << " = " << s.c_str();
} else {
strncpy(out, def, INJECT_PATH_MAX - 1);
PLOGD << "Parameter " << key << " is empty, use default: " << def;
}
} else {
strncpy(out, def, INJECT_PATH_MAX - 1);
PLOGD << "Not found parameter: " << key << ", use default: " << def;
}
out[INJECT_PATH_MAX - 1] = '\0';
};
// Default values
std::string defaultJuiceLoader = std::string(ConfigDir) + "\\JuiceLoader.jar";
std::string defaultJuiceLoaderLibrary = std::string(ConfigDir) + "\\libjuiceloader.dll";
std::string defaultEntryJar = std::string(ConfigDir) + "\\Entry.jar";
std::string defaultInjectionDir = std::string(ConfigDir) + "\\injection";
get_str("JuiceLoaderJarPath", defaultJuiceLoader.c_str(), InjectionInfo.JuiceLoaderJarPath);
get_str("JuiceLoaderLibraryPath", defaultJuiceLoaderLibrary.c_str(), InjectionInfo.JuiceLoaderLibraryPath);
get_str("InjectionDir", defaultInjectionDir.c_str(), InjectionInfo.InjectionDir);
get_str("EntryJarPath", defaultEntryJar.c_str(), InjectionInfo.EntryJarPath);
get_str("EntryClass", "cn.xiaozhou233.test.Entry", InjectionInfo.EntryClass);
get_str("EntryMethod", "start", InjectionInfo.EntryMethod);
PLOGD << "JuiceLoaderJarPath: " << InjectionInfo.JuiceLoaderJarPath;
PLOGD << "JuiceLoaderLibraryPath: " << InjectionInfo.JuiceLoaderLibraryPath;
PLOGD << "InjectionDir: " << InjectionInfo.InjectionDir;
PLOGD << "EntryJarPath: " << InjectionInfo.EntryJarPath;
PLOGD << "EntryClass: " << InjectionInfo.EntryClass;
PLOGD << "EntryMethod: " << InjectionInfo.EntryMethod;
return 0;
}
static int GetJavaEnv() {
jint res = JNI_ERR;
JavaVM *jvm = NULL;
jvmtiEnv *jvmti = NULL;
JNIEnv *env = NULL;
int max_try = 30;
// Get the JVM
max_try = 30;
do {
res = JNI_GetCreatedJavaVMs(&jvm, 1, NULL);
if (res != JNI_OK || jvm == NULL) {
PLOGE.printf("JNI_GetCreatedJavaVMs failed: %d", res);
PLOGD << "JVM NULL: " << (jvm == NULL);
}
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
max_try--;
if (jvm != NULL) {
break;
} else {
PLOGI.printf("Waiting for JVM... (%d)", max_try);
}
} while (jvm == NULL && max_try > 0);
if (jvm == NULL) {
PLOGE << "GetJavaEnv failed";
return res;
}
JuiceAgent.jvm = jvm;
PLOGI << "Got the JVM";
// Get the JNIEnv
max_try = 30;
do {
res = jvm->GetEnv((void**)&env, JNI_VERSION_1_8);
if (res != JNI_OK || env == NULL) {
PLOGI << "GetEnv failed, trying to attach.";
PLOGD << "env NULL: " << (env == NULL);
res = jvm->AttachCurrentThread((void**)&env, NULL);
if (res != JNI_OK || env == NULL) {
PLOGE.printf("AttachCurrentThread failed: %d", res);
PLOGD << "env NULL: " << (env == NULL);
return res;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
max_try--;
if (env != NULL) {
break;
} else {
PLOGI.printf("Waiting for JNI... (%d)", max_try);
}
} while (env == NULL && max_try > 0);
if (env == NULL) {
PLOGE << "Get JNI failed";
return res;
}
JuiceAgent.env = env;
PLOGI << "Got the JNIEnv";
// Get the JVMTI
res = jvm->GetEnv((void**)&jvmti, JVMTI_VERSION_1_2);
if (res != JNI_OK || jvmti == NULL) {
PLOGE.printf("GetEnv failed: %d", res);
PLOGD << "jvmti NULL: " << (jvmti == NULL);
return res;
}
JuiceAgent.jvmti = jvmti;
PLOGI << "Got the JVMTI";
return 0;
}
static int InvokeJuiceLoaderInit(const char* ConfigDir) {
// Variables
int result = JNI_ERR;
JNIEnv *env = JuiceAgent.env;
jvmtiEnv *jvmti = JuiceAgent.jvmti;
const char *bootstrap_class = "cn/xiaozhou233/juiceloader/JuiceLoaderBootstrap";
const char *method_name = "init";
const char *method_signature = "([Ljava/lang/String;)V";
PLOGI << "Invoke JuiceLoader Init";
PLOGI << "================ JuiceLoader Init =================";
// Find class
jclass cls = env->FindClass(bootstrap_class);
if (cls == NULL) {
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
}
PLOGE << "FindClass failed";
return 1;
}
// Find method
jmethodID mid = env->GetStaticMethodID(cls, method_name, method_signature);
if (mid == NULL) {
PLOGE << "GetStaticMethodID failed";
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
}
return 1;
}
// arguments array
const char* args[] = {
InjectionInfo.EntryJarPath,
InjectionInfo.EntryClass,
InjectionInfo.EntryMethod,
InjectionInfo.InjectionDir,
InjectionInfo.JuiceLoaderLibraryPath
};
int argCount = sizeof(args)/sizeof(args[0]);
jclass stringCls = env->FindClass("java/lang/String");
jobjectArray jArgs = env->NewObjectArray(argCount, stringCls, nullptr);
for (int i = 0; i < argCount; i++) {
env->SetObjectArrayElement(jArgs, i, env->NewStringUTF(args[i]));
}
// Invoke method
env->CallStaticVoidMethod(cls, mid, jArgs);
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
}
PLOGI << "================ JuiceLoader Init =================";
PLOGI << "Invoke JuiceLoader Init done";
return 0;
}
extern "C" __declspec(dllexport)
bool InitJuiceAgent(const char* runtime_path) {
PLOGD << "runtime_path: " << runtime_path;
// Read Config
if (ReadConfig(runtime_path) != 0) {
PLOGE << "ReadConfig failed";
return false;
}
PLOGI << "[OK] ReadConfig";
// Get JavaEnv
if (GetJavaEnv() != 0) {
PLOGE << "GetJavaEnv failed";
return false;
}
PLOGI << "[OK] Get JavaEnv";
// Inject JuiceLoader jar
if (JuiceAgent.jvmti->AddToSystemClassLoaderSearch(InjectionInfo.JuiceLoaderJarPath) != JNI_OK) {
PLOGE << "AddToSystemClassLoaderSearch failed";
return false;
}
PLOGI << "[OK] Inject JuiceLoader jar";
// Invoke JuiceLoader Init
if (InvokeJuiceLoaderInit(runtime_path) != 0) {
PLOGE << "Invoke JuiceLoader Init failed";
return false;
}
PLOGI << "[OK] Invoke JuiceLoader Init";
// Load JuiceLoaderLibrary
PLOGI << "--------> InitJuiceAgent Succeed <--------";
return true;
}
+181
View File
@@ -0,0 +1,181 @@
#pragma once
#include <JuiceAgent/Logger.hpp>
#include <JuiceAgent/JuiceAgent.hpp>
#include <tinytoml/toml.h>
#include <filesystem>
#include <fstream>
#include <string>
namespace config {
class Config {
private:
std::string runtime_dir; // Runtime directory
toml::Value config{}; // Parsed TOML configuration
bool valid = false; // Whether the config is successfully loaded
// Escape special characters ';' = '\'
static std::string escape(const std::string& s) {
std::string out;
out.reserve(s.size());
for (char c : s) {
if (c == ';' || c == '=' || c == '\\') {
out += '\\';
}
out += c;
}
return out;
}
// Append key=value pair to string
static void append_kv(std::string& out, const char* key, const std::string& value, bool& first) {
if (!first) out += ';';
first = false;
out += key;
out += '=';
out += escape(value);
}
// Helper function: find value by dot-separated key
const toml::Value* find_value(const std::string& key) const {
if (!valid) return nullptr;
const toml::Value* current = &config;
size_t start = 0;
while (true) {
size_t dot = key.find('.', start);
std::string part = key.substr(start, dot - start);
if (!current->is<toml::Table>()) return nullptr;
const auto& table = current->as<toml::Table>();
auto it = table.find(part);
if (it == table.end()) return nullptr;
current = &it->second;
if (dot == std::string::npos) break;
start = dot + 1;
}
return current;
}
public:
explicit Config(const char* c_runtime_dir)
: runtime_dir(c_runtime_dir ? c_runtime_dir : "")
{
if (runtime_dir.empty()) {
PLOGW << "runtime_dir is empty";
return;
}
std::filesystem::path path = std::filesystem::path(runtime_dir) / "config.toml";
std::ifstream ifs(path);
if (!ifs.is_open()) {
PLOGE << "Failed to open config file: " << path;
return;
}
try {
auto pr = toml::parse(ifs);
if (!pr.valid()) {
PLOGE << "Invalid TOML file: " << pr.errorReason;
return;
}
config = pr.value;
valid = true;
} catch (const std::exception& e) {
PLOGE << "TOML parse error: " << e.what();
}
}
// Get value by key with default
template<typename T>
T get_or_default(const std::string& key, const T& default_value, bool use_default_if_empty = false) const {
const toml::Value* val = find_value(key);
if (!val) return default_value;
try {
if constexpr (std::is_same_v<T, std::string>) {
std::string s = val->as<std::string>();
if (use_default_if_empty && s.empty()) return default_value;
return s;
} else {
return val->as<T>();
}
} catch (...) {
return default_value;
}
}
bool is_valid() const {
return valid;
}
// Get InjectionInfo struct from config
InjectionInfo get_injection_info() const {
InjectionInfo info;
auto get_default_path = [&](const std::string& name) {
return (std::filesystem::path(runtime_dir) / name).string();
};
info.JuiceAgentAPIJarPath = get_or_default<std::string>(
"JuiceAgent.JuiceAgentAPIJarPath", get_default_path("JuiceAgent.jar"), true);
info.JuiceAgentNativePath = get_or_default<std::string>(
"JuiceAgent.JuiceAgentNativePath", get_default_path("libagent.dll"), true);
info.EntryJarPath = get_or_default<std::string>(
"Entry.EntryJarPath", get_default_path("entry.jar"), true);
info.EntryClass = get_or_default<std::string>(
"Entry.EntryClass", "com.example.Entry", true);
info.EntryMethod = get_or_default<std::string>(
"Entry.EntryMethod", "start", true);
info.InjectionDir = get_or_default<std::string>(
"Runtime.InjectionDir", get_default_path("injection"), true);
return info;
}
// Serialize InjectionInfo to key=value; format
static std::string serialize(const InjectionInfo& info) {
std::string result;
result.reserve(256);
bool first = true;
append_kv(result, "Version", "1", first);
append_kv(result, "EntryJarPath", info.EntryJarPath, first);
append_kv(result, "EntryClass", info.EntryClass, first);
append_kv(result, "EntryMethod", info.EntryMethod, first);
append_kv(result, "JuiceAgentAPIJarPath", info.JuiceAgentAPIJarPath, first);
append_kv(result, "JuiceAgentNativePath", info.JuiceAgentNativePath, first);
append_kv(result, "InjectionDir", info.InjectionDir, first);
PLOGD << "Serialized args: " << result;
return result;
}
std::string serialize() const {
return serialize(get_injection_info());
}
};
// Print InjectionInfo (debug)
inline void print_injection_info(const InjectionInfo& info) {
PLOGI << "JuiceAgent Injection Info:";
PLOGI << " JuiceAgentAPIJarPath: " << info.JuiceAgentAPIJarPath;
PLOGI << " JuiceAgentNativePath: " << info.JuiceAgentNativePath;
PLOGI << " EntryJarPath: " << info.EntryJarPath;
PLOGI << " EntryClass: " << info.EntryClass;
PLOGI << " EntryMethod: " << info.EntryMethod;
PLOGI << " InjectionDir: " << info.InjectionDir;
}
} // namespace config
+122
View File
@@ -0,0 +1,122 @@
#pragma once
#include <JuiceAgent/Logger.hpp>
#include <jvm/jni.h>
#include <jvm/jvmti.h>
#include <thread>
#include <chrono>
namespace jvm
{
class Jvm {
private:
JavaVM* jvm = nullptr;
jvmtiEnv* jvmti = nullptr;
thread_local static JNIEnv* env;
bool attached = false;
int max_try = 30;
public:
Jvm() = default;
~Jvm() = default;
JavaVM* get_jvm() const { return jvm; }
JNIEnv* get_env() const { return env; }
jvmtiEnv* get_jvmti() const { return jvmti; }
bool attach() {
// reset state
jvm = nullptr;
jvmti = nullptr;
env = nullptr;
attached = false;
jint status = JNI_ERR;
// ======== Get JavaVM ========
for (int i = 0; i < max_try; i++) {
status = JNI_GetCreatedJavaVMs(&jvm, 1, nullptr);
if (status == JNI_OK && jvm != nullptr) {
PLOGI << "Got JavaVM";
break;
}
PLOGE << "Failed to get JavaVM: " << status;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
if (!jvm) {
PLOGF << "JavaVM not found!";
return false;
}
// ======== Get JNIEnv ========
for (int i = 0; i < max_try; i++) {
status = jvm->GetEnv((void**)&env, JNI_VERSION_1_6);
if (status == JNI_OK && env != nullptr) {
PLOGI << "Got JNIEnv (already attached)";
break;
}
// try attach
status = jvm->AttachCurrentThread((void**)&env, nullptr);
if (status == JNI_OK && env != nullptr) {
attached = true;
PLOGI << "Attached current thread";
break;
}
PLOGE << "Attach failed: " << status;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
if (!env) {
PLOGF << "Failed to get JNIEnv";
return false;
}
// ======== Get JVMTI ========
for (int i = 0; i < max_try; i++) {
status = jvm->GetEnv((void**)&jvmti, JVMTI_VERSION_1_2);
if (status == JNI_OK && jvmti != nullptr) {
PLOGI << "Got JVMTI";
break;
}
PLOGE << "Failed to get JVMTI: " << status;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
if (!jvmti) {
PLOGF << "Failed to get JVMTI";
return false;
}
return true;
}
bool detach() {
if (jvm && attached) {
jint res = jvm->DetachCurrentThread();
if (res != JNI_OK) {
PLOGE << "DetachCurrentThread failed: " << res;
return false;
}
PLOGI << "Thread detached";
attached = false;
env = nullptr;
}
return true;
}
};
thread_local JNIEnv* Jvm::env = nullptr;
} // namespace jvm
+14
View File
@@ -0,0 +1,14 @@
#pragma once
#include <JuiceAgent/JuiceAgent.hpp>
#include <string>
#include <JuiceAgent/Logger.hpp>
#include <jvm/jni.h>
#include <jvm/jvmti.h>
namespace libloader
{
void entrypoint(const char* runtime_dir);
bool invoke_juiceagent_init(JNIEnv* env, const InjectionInfo& info);
} // namespace libloader
@@ -1,6 +1,6 @@
#include <windows.h> #include <windows.h>
#include <JuiceAgent/Logger.hpp> #include <JuiceAgent/Logger.hpp>
#include <libagent.h> #include <libloader.hpp>
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) { BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) {
switch( fdwReason ) switch( fdwReason )
@@ -8,12 +8,10 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) {
case DLL_PROCESS_ATTACH: { case DLL_PROCESS_ATTACH: {
InitLogger(); InitLogger();
PLOGI << "DllMain: DLL_PROCESS_ATTACH"; PLOGI << "DllMain: DLL_PROCESS_ATTACH";
PLOGD.printf("lpReserved: %p", lpReserved);
const char* runtime_dir = (const char*)lpReserved; const char* runtime_dir = (const char*)lpReserved;
PLOGD << "runtime_dir: " << runtime_dir;
InitJuiceAgent(runtime_dir); libloader::entrypoint(runtime_dir);
break; break;
} }
@@ -29,7 +27,6 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) {
case DLL_PROCESS_DETACH: { case DLL_PROCESS_DETACH: {
PLOGI << "DllMain: DLL_PROCESS_DETACH"; PLOGI << "DllMain: DLL_PROCESS_DETACH";
PLOGD.printf("lpReserved: %p", lpReserved);
break; break;
} }
} }
File renamed without changes.