mirror of
https://github.com/xiaozhou233/JuiceAgent.git
synced 2026-12-05 13:05:53 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
011fafb5b0 | ||
|
|
748b118fb1 | ||
|
|
b78839a8d4 | ||
|
|
8894a819f2 | ||
|
|
e25f0c304a | ||
|
|
bbea7b72c3 | ||
|
|
896a856c57 | ||
|
|
c80851adb7 | ||
|
|
49ac4a51a1 | ||
|
|
0d9e5fe836 | ||
|
|
34c8ccd497 | ||
|
|
f73265ac3e | ||
|
|
5e7972779f | ||
|
|
8ad8f45545 | ||
|
|
71965165b9 | ||
|
|
34dbd82a59 | ||
|
|
9aa77848d7 | ||
|
|
ad69f9d11a | ||
|
|
faeaf052b9 | ||
|
|
b0d8b5901f | ||
|
|
4496931bdf | ||
|
|
34cb16d385 | ||
|
|
bad147d898 | ||
|
|
289b0311bf | ||
|
|
1714f7603d | ||
|
|
d6d17aac35 | ||
|
|
6350bfb0ec | ||
|
|
8421d3817a | ||
|
|
3362e2071c | ||
|
|
72c0518ebc | ||
|
|
0a4ec5e97a | ||
|
|
15d7f0295a | ||
|
|
c5817a3b06 | ||
|
|
e5ac60d476 | ||
|
|
3e3f9d1c14 | ||
|
|
3ce1bccf02 | ||
|
|
205e608d60 | ||
|
|
9dab75b5fd | ||
|
|
c9c10686ab | ||
|
|
a110e675c6 | ||
|
|
9b24ea0ae4 | ||
|
|
172f354b04 | ||
|
|
cf49ed0a7b | ||
|
|
ea5ce8258d | ||
|
|
ab9369d8b7 | ||
|
|
2ce6a8e192 | ||
|
|
d8bed79f84 | ||
|
|
6ab3c279aa | ||
|
|
a8c2496292 | ||
|
|
94d881fe63 | ||
|
|
d98e3e818e | ||
|
|
58f76009e4 | ||
|
|
64ca48dfc8 | ||
|
|
4ef94b5ac2 | ||
|
|
339b68c8af | ||
|
|
623445aa5e | ||
|
|
cacdb6a1cd |
No files matched your search
+3
-3
@@ -1,7 +1,7 @@
|
||||
cmake_minimum_required(VERSION 3.15)
|
||||
project(JuiceAgent LANGUAGES C CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
# output directories
|
||||
@@ -16,6 +16,6 @@ link_directories("$ENV{JAVA_HOME}/lib")
|
||||
add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection)
|
||||
|
||||
# modules
|
||||
add_subdirectory(${SRC_DIR}/libagent)
|
||||
add_subdirectory(${SRC_DIR}/libloader)
|
||||
add_subdirectory(${SRC_DIR}/libinjector)
|
||||
add_subdirectory(${SRC_DIR}/libjuiceloader)
|
||||
add_subdirectory(${SRC_DIR}/libagent)
|
||||
@@ -1,102 +1,103 @@
|
||||
|
||||
# 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.
|
||||
|
||||
**NOTICE:** Currently only supports **Windows**, and plans to support **Linux** in the future.
|
||||
|
||||
**NOTICE:** **Version 2.3 Build 1** is the current **stable release and is no longer being updated.** Version 3.0 and later have been rewritten and may contain unknown issues.
|
||||
|
||||
**WARNING:** This project is still in the experimental stage and is not recommended for production use.
|
||||
**Use this at your own risk.**
|
||||
|
||||
## Summary
|
||||
JuiceAgent is a JVMTI-native injection framework that injects native code into a target JVM to dynamically load external JARs and perform bytecode redefinition/transformations without requiring a javaagent (works when DisableAttachMechanism=true).
|
||||
## Features
|
||||
### JuiceAgent (src/libagent)
|
||||
- Initialize JuiceLoader
|
||||
- Lightweight Library (No Javaagent)
|
||||
- Read Config File and Load JARs
|
||||
- Invoke JuiceLoader Bootstrap API
|
||||
This project is an implementation of the JuiceAgent-API. For more details, please see [This](https://github.com/xiaozhou233/JuiceAgent-API/blob/master/src/main/java/cn/xiaozhou233/juiceagent/api/JuiceAgent.java)
|
||||
|
||||
### libinjector (src/libinjector)
|
||||
- Provides JNI functions for injecting DLLs into target processes
|
||||
- Get PID by process name
|
||||
- addToBootstrapClassLoaderSearch
|
||||
- addToSystemClassLoaderSearch
|
||||
- addToClassLoader
|
||||
- defineClass
|
||||
- redefineClass(ByName)
|
||||
- retransformClass(ByName)
|
||||
- getLoadedClasses
|
||||
- getClassByName
|
||||
- getClassBytes(ByName)
|
||||
|
||||
### JuiceLoader Native (src/juiceloader)
|
||||
Native library for [JuiceLoader](https://github.com/xiaozhou233/JuiceLoader) , Inject Jars/ Redefine class Low-level implementation.
|
||||
- Implements JuiceLoader's native API
|
||||
- init
|
||||
- injectJar
|
||||
- redefineClass (redefineClassByName)
|
||||
- retransformClass (retransformClassByName)
|
||||
- getLoadedClasses
|
||||
- getClassBytes (getClassBytesByName)
|
||||
- getClassByName
|
||||
- nativeGetThreadByName* (test function, myself-use)
|
||||
- nativeInjectJarToThread (test function, myself-use)
|
||||
## How To Use (For Version 2.2 Build 1)
|
||||
## How To Use (**For Version 3.0 Build 2**)
|
||||
|
||||
### 1. Download Files
|
||||
- Download `libagent`, `libinjector`, and `libjuiceloader` from the Release to the same directory.
|
||||
- Download JARs `bootstrap-api.jar`, `JuiceLoader.jar`, and `Entry.jar` (or your own JAR) to the same directory.
|
||||
### 1. ⬇️ Download Files
|
||||
- Download `libagent.dll` `libinject.dll` `libloader.dll` `injector.exe` from [Release](https://github.com/xiaozhou233/JuiceAgent/releases) and put them in `YourDir`
|
||||
- Download JARs `JuiceAgent-API-X.X.X+build.X.jar` from [JuiceAgent-API Release] (https://github.com/xiaozhou233/JuiceAgent-API/releases) and put them in `YourDir`
|
||||
|
||||
### 2. Write Config File
|
||||
Create a config file named `AgentConfig.toml` in the same directory. Example:
|
||||
### 2. ✍️ Write Config File
|
||||
Create a config file named `config.toml` in `YourDir`
|
||||
|
||||
```toml
|
||||
# Leave empty to use default values
|
||||
# Default values: <Current Directory>/default-name
|
||||
[JuiceAgent]
|
||||
# Default value: YourDir/JuiceAgent-API.jar
|
||||
JuiceAgentAPIJarPath = ""
|
||||
# Default value: YourDir/libagent.dll
|
||||
JuiceAgentNativePath = ""
|
||||
|
||||
# Example: JuiceLoaderJarPath = "D:\\Development\\JuiceSky\\build\\libs\\JuiceLoader-1.0.jar"
|
||||
# Default: <Current Directory>/JuiceLoader.jar
|
||||
JuiceLoaderJarPath = ""
|
||||
# Default: <Current Directory>/libjuiceloader.dll
|
||||
JuiceLoaderLibraryPath = ""
|
||||
# Default: <Current Directory>/injection/
|
||||
InjectionDir = ""
|
||||
# Default: <Current Directory>/Entry.jar
|
||||
EntryJarPath = "D:\\Development\\JuiceSky\\build\\libs\\JuiceSky-1.0-Hooked.jar"
|
||||
EntryClass = "cn.xiaozhou233.juicesky.LoaderEntry"
|
||||
[Entry]
|
||||
# Default value: YourDir/Entry.jar
|
||||
EntryJarPath = ""
|
||||
# Default value: com.example.Entry
|
||||
EntryClass = ""
|
||||
# Default value: start
|
||||
EntryMethod = "start"
|
||||
|
||||
[Runtime]
|
||||
# Default value: YourDir/injection
|
||||
InjectionDir = ""
|
||||
```
|
||||
| Method| Usage|
|
||||
| - | -|
|
||||
| **Reflective Inject** | Uses `libinjector`. Pass the config directory as a parameter. </br></br> Example: config file at `<YourDir>/AgentConfig.toml`, </br></br>pass `<YourDir>` as parameter.</br></br> Example:</br>`C/C++: libinjector.dll -> inject(pid, agentpath, configpath)`</br>`Java: See 3. Invoke Inject Function`|
|
||||
| **Normal Inject** | Uses `LoadLibraryA + CreateRemoteThread`. Keep `AgentConfig.toml` and all DLLs/JARs in the same directory.</br>
|
||||
|
||||
### 3. Invoke Inject Function
|
||||
C/C++ Use libinjector and invoke inject(int pid, char* path, InjectParameters *params)
|
||||
### 3. 💉 Run Injector
|
||||
#### **Method A** : Use `injector.exe`
|
||||
Run `injector.exe`
|
||||
```
|
||||
114514 loop
|
||||
Input PID:
|
||||
```
|
||||
|
||||
Java Use `Injecor.jar`: `java -jar Injecor.jar` or
|
||||
```
|
||||
package cn.xiaozhou233.juiceagent.injector;
|
||||
Input PID of target process and press Enter
|
||||
|
||||
#### **Method B** : Use JNI to call `inject` function
|
||||
Create a file named cn/xiaozhou233/juiceagent/injector.java in your project
|
||||
```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
|
||||
*/
|
||||
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);
|
||||
/*
|
||||
* @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);
|
||||
}
|
||||
```
|
||||
```
|
||||
Then write it down somewhere
|
||||
```java
|
||||
// Your class
|
||||
import cn.xiaozhou233.juiceagent.injector.InjectorNative;
|
||||
|
||||
System.load("<path-to-libinjector>");
|
||||
System.load("<path-to-libinject>");
|
||||
InjectorNative injectorNative = new InjectorNative();
|
||||
|
||||
injectorNative.inject(<pid>, "<path-to-libagent>", "<path-to-toml-config-dir>");
|
||||
injectorNative.inject(<pid>, "<path-to-libloader>", "<path-to-toml-config-dir>");
|
||||
```
|
||||
### 4. ✅ Done!
|
||||
if injection is successful, target process will load `Entry.jar` (or `EntryClass` in config file) and run `EntryMethod` method(or `start` method in config file)
|
||||
|
||||
### 4. Done!
|
||||
If the injection is successful, EntryClass .EntryMethod() of <EntryJarPath> will be executed.
|
||||
## Hot To Build
|
||||
### Environment
|
||||
- Java 8+
|
||||
@@ -110,9 +111,10 @@ cd JuiceAgent
|
||||
mkdir -p build
|
||||
cmake --build build --
|
||||
```
|
||||
dlls: build/bin/
|
||||
|
||||
jars: see [JuiceLoader](https://github.com/xiaozhou233/JuiceLoader)
|
||||
Dlls will be generated in `build/bin` directory
|
||||
|
||||
Jars can be build or download in project [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API)
|
||||
|
||||
## Full Disclaimer/ 完整免责声明
|
||||
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.
|
||||
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
# JuiceAgent
|
||||
[English](https://github.com/xiaozhou233/JuiceAgent/blob/main/README.md) | [中文](https://github.com/xiaozhou233/JuiceAgent/blob/main/README_zh.md)
|
||||
|
||||
JuiceAgent —— 一个基于 JVMTI 的注入库,用于加载外部 JAR 并对 Java 字节码进行热替换,即使在 DisableAttachMechanism 启用的情况下也可使用。
|
||||
|
||||
**注意:** 当前仅支持 **Windows**,未来计划支持 **Linux**。
|
||||
|
||||
**注意:** **Version 2.3 Build 1** 是当前的 **稳定版本且已停止更新**。3.0 及之后版本已重构,可能存在未知问题。
|
||||
|
||||
**警告:** 本项目仍处于实验阶段,不建议用于生产环境。
|
||||
**使用风险自负。**
|
||||
|
||||
---
|
||||
|
||||
## 简介
|
||||
JuiceAgent 是一个基于 JVMTI 的原生注入框架,通过向目标 JVM 注入代码,实现动态加载外部 JAR 以及字节码热替换,无需使用 javaagent(在 DisableAttachMechanism=true 时仍可工作)。
|
||||
|
||||
---
|
||||
|
||||
## 功能特性
|
||||
|
||||
本项目是 JuiceAgent-API 的Native实现,详细内容请参考:
|
||||
https://github.com/xiaozhou233/JuiceAgent-API/blob/master/src/main/java/cn/xiaozhou233/juiceagent/api/JuiceAgent.java
|
||||
|
||||
- addToBootstrapClassLoaderSearch
|
||||
- addToSystemClassLoaderSearch
|
||||
- addToClassLoader
|
||||
- defineClass
|
||||
- redefineClass(ByName)
|
||||
- retransformClass(ByName)
|
||||
- getLoadedClasses
|
||||
- getClassByName
|
||||
- getClassBytes(ByName)
|
||||
|
||||
---
|
||||
|
||||
## 使用方法(适用于 Version 3.0 Build 2)
|
||||
|
||||
### 1. ⬇️ 下载文件
|
||||
|
||||
- 从 Release 下载:
|
||||
- libagent.dll
|
||||
- libinject.dll
|
||||
- libloader.dll
|
||||
- injector.exe
|
||||
并放入 `YourDir`
|
||||
|
||||
- 从 JuiceAgent-API Release 下载:
|
||||
- JuiceAgent-API-X.X.X+build.X.jar
|
||||
并放入 `YourDir`
|
||||
|
||||
---
|
||||
|
||||
### 2. ✍️ 编写配置文件
|
||||
|
||||
在 `YourDir` 下创建 `config.toml`
|
||||
|
||||
```toml
|
||||
[JuiceAgent]
|
||||
# 默认值: YourDir/JuiceAgent-API.jar
|
||||
JuiceAgentAPIJarPath = ""
|
||||
# 默认值: YourDir/libagent.dll
|
||||
JuiceAgentNativePath = ""
|
||||
|
||||
[Entry]
|
||||
# 默认值: YourDir/Entry.jar
|
||||
EntryJarPath = ""
|
||||
# 默认值: com.example.Entry
|
||||
EntryClass = ""
|
||||
# 默认值: start
|
||||
EntryMethod = "start"
|
||||
|
||||
[Runtime]
|
||||
# 默认值: YourDir/injection
|
||||
InjectionDir = ""
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. 💉 执行注入
|
||||
|
||||
#### 方法 A:使用 injector.exe
|
||||
|
||||
运行`inject.exe`:
|
||||
|
||||
```
|
||||
114514 loop
|
||||
Input PID:
|
||||
```
|
||||
|
||||
输入目标进程 PID 后回车
|
||||
|
||||
---
|
||||
|
||||
#### 方法 B:使用 JNI 调用 inject
|
||||
|
||||
创建文件:
|
||||
`cn/xiaozhou233/juiceagent/injector/InjectorNative.java`
|
||||
|
||||
```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-libinject>");
|
||||
InjectorNative injectorNative = new InjectorNative();
|
||||
|
||||
injectorNative.inject(<pid>, "<path-to-libloader>", "<path-to-toml-config-dir>");
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 4. ✅ 完成
|
||||
|
||||
注入成功后,目标进程将加载:
|
||||
|
||||
- Entry.jar(或配置中的 EntryClass)
|
||||
- 并执行 EntryMethod(默认 start)
|
||||
|
||||
---
|
||||
|
||||
## 如何构建
|
||||
|
||||
### 环境要求
|
||||
|
||||
- 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 可在 JuiceAgent-API 项目中构建或下载。
|
||||
|
||||
---
|
||||
|
||||
## 完整免责声明
|
||||
|
||||
免责声明:本项目仅建议在受控环境中用于学习与研究。作者不对任何因滥用、破解、修改或违反协议/法律行为所产生的后果负责。使用者需自行确保合法合规,并承担全部责任。
|
||||
|
||||
---
|
||||
|
||||
## 致谢
|
||||
|
||||
- ReflectiveDLLInjection — DLL 注入实现
|
||||
- plog — 轻量级 C++ 日志库
|
||||
- tinytoml — C++11 TOML 解析库
|
||||
@@ -0,0 +1 @@
|
||||
VERSION = Version 3.0 Build 2
|
||||
@@ -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
|
||||
@@ -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() << ")";
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
(JNIEnv *env, jclass loader_class) {
|
||||
PLOGI << "Invoked!";
|
||||
// This function is called by Java to initialize the agent.
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init
|
||||
(JNIEnv *env, jclass loader_class) {
|
||||
InitLogger();
|
||||
|
||||
PLOGI << "Initializing JuiceAgent...";
|
||||
|
||||
// Get JavaVM
|
||||
JavaVM* jvm = nullptr;
|
||||
jvmtiEnv* jvmti = nullptr;
|
||||
|
||||
// Get Java VM
|
||||
env->GetJavaVM(&jvm);
|
||||
if (jvm == nullptr) {
|
||||
PLOGE << "Failed to get JavaVM instance";
|
||||
@@ -13,19 +19,15 @@ JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_init
|
||||
}
|
||||
|
||||
// Get JVMTI
|
||||
jvmtiEnv* jvmti = nullptr;
|
||||
jvmtiError err = static_cast<jvmtiError>(jvm->GetEnv(reinterpret_cast<void**>(&jvmti), JVMTI_VERSION_1_2));
|
||||
if (err != JVMTI_ERROR_NONE || jvmti == nullptr) {
|
||||
PLOGE << "Failed to get JVMTI environment, error: " << err;
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
int result = InitJuiceLoader(env, jvmti);
|
||||
if (result != 0) {
|
||||
PLOGE << "Failed to initialize JuiceLoader, error code: " << result;
|
||||
return JNI_FALSE;
|
||||
}
|
||||
// Invoke EntryPoint
|
||||
JuiceAgent::Agent& agent = JuiceAgent::Agent::instance();
|
||||
agent.init(jvm, env, jvmti);
|
||||
|
||||
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
|
||||
@@ -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;
|
||||
@@ -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);
|
||||
@@ -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
|
||||
@@ -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; }
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
#include <jni_impl.hpp>
|
||||
|
||||
+57
-243
@@ -1,251 +1,65 @@
|
||||
#include <jvm/jni.h>
|
||||
#include <jvm/jvmti.h>
|
||||
#include <stdio.h>
|
||||
#include <JuiceAgent/Logger.hpp>
|
||||
#include <libagent.h>
|
||||
#include <thread>
|
||||
#include <tinytoml/toml.h>
|
||||
#include <JuiceAgent/JuiceAgent.h>
|
||||
#include <libagent.hpp>
|
||||
#include <jni_impl.hpp>
|
||||
|
||||
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;
|
||||
namespace JuiceAgent {
|
||||
// ===== Singleton =====
|
||||
Agent& Agent::instance() {
|
||||
static Agent instance;
|
||||
return instance;
|
||||
}
|
||||
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";
|
||||
bool Agent::init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti) {
|
||||
PLOGI << "JuiceAgent Native EntryPoint Invoked!";
|
||||
|
||||
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();
|
||||
// ======== neccessary environment check ========
|
||||
if (jvm == nullptr) {
|
||||
PLOGE << "Failed to initialize JuiceAgent: jvm is null";
|
||||
return false;
|
||||
}
|
||||
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();
|
||||
if (env == nullptr) {
|
||||
PLOGE << "Failed to initialize JuiceAgent: env is null";
|
||||
return false;
|
||||
}
|
||||
return 1;
|
||||
if (jvmti == nullptr) {
|
||||
PLOGE << "Failed to initialize JuiceAgent: jvmti is null";
|
||||
return false;
|
||||
}
|
||||
|
||||
set_jvm(jvm);
|
||||
set_jvmti(jvmti);
|
||||
|
||||
PLOGD << "env: " << env << ", jvmti: " << jvmti;
|
||||
|
||||
// ======== Application ability ========
|
||||
jvmtiCapabilities 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 false;
|
||||
}
|
||||
|
||||
PLOGI << "Abilities added successfully";
|
||||
|
||||
// ======== Register callbacks ========
|
||||
jvmtiEventCallbacks callbacks{};
|
||||
callbacks.ClassFileLoadHook = &ClassFileLoadHook;
|
||||
result = jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks));
|
||||
if (result != JNI_OK) {
|
||||
PLOGE << "Failed to set event callbacks: " << result;
|
||||
}
|
||||
|
||||
// Enable events
|
||||
result = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, NULL);
|
||||
if (result != JNI_OK) {
|
||||
PLOGE << "Failed to enable event notification: " << result;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// 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) {
|
||||
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;
|
||||
}
|
||||
@@ -1,10 +1,19 @@
|
||||
file(
|
||||
GLOB_RECURSE
|
||||
libinjector_sources
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/*.c
|
||||
|
||||
# libinject
|
||||
add_library(inject SHARED libinject.c)
|
||||
|
||||
target_include_directories(inject PRIVATE
|
||||
${CMAKE_SOURCE_DIR}/includes
|
||||
${CMAKE_SOURCE_DIR}/includes/jvm
|
||||
${CMAKE_SOURCE_DIR}/includes/jvm/win32
|
||||
)
|
||||
|
||||
add_library(injector SHARED ${libinjector_sources})
|
||||
target_link_libraries(inject PRIVATE
|
||||
ReflectiveDLLInjection
|
||||
)
|
||||
|
||||
# injector
|
||||
add_executable(injector injector.c)
|
||||
|
||||
target_include_directories(injector PRIVATE
|
||||
${CMAKE_SOURCE_DIR}/includes
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
#include <stdio.h>
|
||||
#include <windows.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define MAX_PATH_LEN 4096
|
||||
|
||||
void ExecuteJps(){
|
||||
// Execute "jps -l" and print the output
|
||||
char command[MAX_PATH] = "jps -l";
|
||||
FILE* pipe = _popen(command, "r");
|
||||
if (!pipe) {
|
||||
printf("Error opening pipe!\n");
|
||||
return;
|
||||
}
|
||||
char buffer[128];
|
||||
while (!feof(pipe)) {
|
||||
if (fgets(buffer, 128, pipe) != NULL)
|
||||
printf("%s", buffer);
|
||||
}
|
||||
_pclose(pipe);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
int pid = 0;
|
||||
char dll_path[MAX_PATH_LEN] = {0};
|
||||
char injector_lib_path[MAX_PATH_LEN] = {0};
|
||||
char cwd[MAX_PATH_LEN] = {0};
|
||||
|
||||
/* If user provided pid and dll path as arguments, use them. */
|
||||
if (argc >= 3) {
|
||||
pid = atoi(argv[1]);
|
||||
strncpy(dll_path, argv[2], MAX_PATH_LEN - 1);
|
||||
if (argc >= 4) {
|
||||
strncpy(injector_lib_path, argv[3], MAX_PATH_LEN - 1);
|
||||
}
|
||||
} else {
|
||||
/* Show jps output to help user find JVM PID */
|
||||
ExecuteJps();
|
||||
printf("Input PID: ");
|
||||
if (scanf("%d", &pid) != 1 || pid <= 0) {
|
||||
printf("Invalid PID input.\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Default dll_path = currentdir\\libloader.dll */
|
||||
if (!GetCurrentDirectoryA(MAX_PATH_LEN, cwd)) {
|
||||
printf("Warning: GetCurrentDirectory failed, using '.'\n");
|
||||
strncpy(cwd, ".", MAX_PATH_LEN - 1);
|
||||
}
|
||||
snprintf(dll_path, MAX_PATH_LEN, "%s\\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.
@@ -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
|
||||
@@ -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
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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
|
||||
)
|
||||
@@ -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
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
#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, bool is_path = 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;
|
||||
// Check if string starts with '.'
|
||||
if (is_path && s.starts_with('.')) {
|
||||
// remove '.'
|
||||
s.erase(0, 1);
|
||||
|
||||
// Check if string starts with '/'
|
||||
// MUST REMOVE '/', or it will cause path error (root directory)
|
||||
if (s.starts_with('/')) {
|
||||
s.erase(0, 1);
|
||||
}
|
||||
|
||||
// runtime_dir + s
|
||||
s = (std::filesystem::path(runtime_dir) / s).string();
|
||||
}
|
||||
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-API.jar"), true, true);
|
||||
|
||||
info.JuiceAgentNativePath = get_or_default<std::string>(
|
||||
"JuiceAgent.JuiceAgentNativePath", get_default_path("libagent.dll"), true, true);
|
||||
|
||||
info.EntryJarPath = get_or_default<std::string>(
|
||||
"Entry.EntryJarPath", get_default_path("Entry.jar"), true, true);
|
||||
|
||||
info.EntryClass = get_or_default<std::string>(
|
||||
"Entry.EntryClass", "com.example.Entry", true, false);
|
||||
|
||||
info.EntryMethod = get_or_default<std::string>(
|
||||
"Entry.EntryMethod", "start", true, false);
|
||||
|
||||
info.InjectionDir = get_or_default<std::string>(
|
||||
"Runtime.InjectionDir", get_default_path("injection"), true, 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
|
||||
@@ -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
|
||||
@@ -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 <JuiceAgent/Logger.hpp>
|
||||
#include <libagent.h>
|
||||
#include <libloader.hpp>
|
||||
|
||||
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) {
|
||||
switch( fdwReason )
|
||||
@@ -8,12 +8,10 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) {
|
||||
case DLL_PROCESS_ATTACH: {
|
||||
InitLogger();
|
||||
PLOGI << "DllMain: DLL_PROCESS_ATTACH";
|
||||
PLOGD.printf("lpReserved: %p", lpReserved);
|
||||
|
||||
const char* runtime_dir = (const char*)lpReserved;
|
||||
PLOGD << "runtime_dir: " << runtime_dir;
|
||||
|
||||
InitJuiceAgent(runtime_dir);
|
||||
libloader::entrypoint(runtime_dir);
|
||||
|
||||
break;
|
||||
}
|
||||
@@ -29,7 +27,6 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) {
|
||||
|
||||
case DLL_PROCESS_DETACH: {
|
||||
PLOGI << "DllMain: DLL_PROCESS_DETACH";
|
||||
PLOGD.printf("lpReserved: %p", lpReserved);
|
||||
break;
|
||||
}
|
||||
}
|
||||
File renamed without changes.
Reference in new issue
Block a user