mirror of
https://github.com/xiaozhou233/JuiceAgent.git
synced 2026-12-05 21:15:56 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
No files matched your search
+3
-3
@@ -1,7 +1,7 @@
|
|||||||
cmake_minimum_required(VERSION 3.15)
|
cmake_minimum_required(VERSION 3.15)
|
||||||
project(JuiceAgent LANGUAGES C CXX)
|
project(JuiceAgent LANGUAGES C CXX)
|
||||||
|
|
||||||
set(CMAKE_CXX_STANDARD 17)
|
set(CMAKE_CXX_STANDARD 20)
|
||||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||||
|
|
||||||
# output directories
|
# output directories
|
||||||
@@ -16,6 +16,6 @@ link_directories("$ENV{JAVA_HOME}/lib")
|
|||||||
add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection)
|
add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection)
|
||||||
|
|
||||||
# modules
|
# modules
|
||||||
add_subdirectory(${SRC_DIR}/libagent)
|
add_subdirectory(${SRC_DIR}/libloader)
|
||||||
add_subdirectory(${SRC_DIR}/libinjector)
|
add_subdirectory(${SRC_DIR}/libinjector)
|
||||||
add_subdirectory(${SRC_DIR}/libjuiceloader)
|
add_subdirectory(${SRC_DIR}/libagent)
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
|
|
||||||
# JuiceAgent
|
# JuiceAgent
|
||||||
[English]() | [中文]()
|
[English](https://github.com/xiaozhou233/JuiceAgent/blob/main/README.md) | [中文](https://github.com/xiaozhou233/JuiceAgent/blob/main/README_zh.md)
|
||||||
|
|
||||||
|
|
||||||
JuiceAgent — a JVMTI-based injection library for loading external JARs and transforming Java bytecode, even when DisableAttachMechanism is enabled.
|
JuiceAgent — a JVMTI-based injection library for loading external JARs and transforming Java bytecode, even when DisableAttachMechanism is enabled.
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
# JuiceAgent
|
# JuiceAgent
|
||||||
[English]() | [中文]()
|
[English](https://github.com/xiaozhou233/JuiceAgent/blob/main/README.md) | [中文](https://github.com/xiaozhou233/JuiceAgent/blob/main/README_zh.md)
|
||||||
|
|
||||||
JuiceAgent —— 一个基于 **JVMTI** 的注入库,用于在 **DisableAttachMechanism 启用的情况下**,向目标 JVM 注入外部 JAR 并对 Java 字节码进行转换。
|
JuiceAgent —— 一个基于 **JVMTI** 的注入库,用于在 **DisableAttachMechanism 启用的情况下**,向目标 JVM 注入外部 JAR 并对 Java 字节码进行转换。
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1 +1 @@
|
|||||||
VERSION = Version 2.3 Build 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
|
// This function is called by Java to initialize the agent.
|
||||||
(JNIEnv *env, jclass loader_class) {
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init
|
||||||
PLOGI << "Invoked!";
|
(JNIEnv *env, jclass loader_class) {
|
||||||
|
InitLogger();
|
||||||
|
|
||||||
|
PLOGI << "Initializing JuiceAgent...";
|
||||||
|
|
||||||
// Get JavaVM
|
|
||||||
JavaVM* jvm = nullptr;
|
JavaVM* jvm = nullptr;
|
||||||
|
jvmtiEnv* jvmti = nullptr;
|
||||||
|
|
||||||
|
// Get Java VM
|
||||||
env->GetJavaVM(&jvm);
|
env->GetJavaVM(&jvm);
|
||||||
if (jvm == nullptr) {
|
if (jvm == nullptr) {
|
||||||
PLOGE << "Failed to get JavaVM instance";
|
PLOGE << "Failed to get JavaVM instance";
|
||||||
@@ -13,19 +19,15 @@ JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_init
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Get JVMTI
|
// Get JVMTI
|
||||||
jvmtiEnv* jvmti = nullptr;
|
|
||||||
jvmtiError err = static_cast<jvmtiError>(jvm->GetEnv(reinterpret_cast<void**>(&jvmti), JVMTI_VERSION_1_2));
|
jvmtiError err = static_cast<jvmtiError>(jvm->GetEnv(reinterpret_cast<void**>(&jvmti), JVMTI_VERSION_1_2));
|
||||||
if (err != JVMTI_ERROR_NONE || jvmti == nullptr) {
|
if (err != JVMTI_ERROR_NONE || jvmti == nullptr) {
|
||||||
PLOGE << "Failed to get JVMTI environment, error: " << err;
|
PLOGE << "Failed to get JVMTI environment, error: " << err;
|
||||||
return JNI_FALSE;
|
return JNI_FALSE;
|
||||||
}
|
}
|
||||||
|
|
||||||
int result = InitJuiceLoader(env, jvmti);
|
// Invoke EntryPoint
|
||||||
if (result != 0) {
|
JuiceAgent::Agent& agent = JuiceAgent::Agent::instance();
|
||||||
PLOGE << "Failed to initialize JuiceLoader, error code: " << result;
|
agent.init(jvm, env, jvmti);
|
||||||
return JNI_FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
PLOGI << "JuiceLoader initialized successfully";
|
return JNI_TRUE;
|
||||||
return JNI_TRUE;
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
/* DO NOT EDIT THIS FILE - it is machine generated */
|
||||||
|
#include <jni.h>
|
||||||
|
/* Header for class cn_xiaozhou233_juiceagent_api_JuiceAgent */
|
||||||
|
|
||||||
|
#ifndef _Included_cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||||
|
#define _Included_cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||||
|
* Method: init
|
||||||
|
* Signature: ()Z
|
||||||
|
*/
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init
|
||||||
|
(JNIEnv *, jclass);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||||
|
* Method: addToBootstrapClassLoaderSearch
|
||||||
|
* Signature: (Ljava/lang/String;)Z
|
||||||
|
*/
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToBootstrapClassLoaderSearch
|
||||||
|
(JNIEnv *, jclass, jstring);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||||
|
* Method: addToSystemClassLoaderSearch
|
||||||
|
* Signature: (Ljava/lang/String;)Z
|
||||||
|
*/
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToSystemClassLoaderSearch
|
||||||
|
(JNIEnv *, jclass, jstring);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||||
|
* Method: addToClassLoader
|
||||||
|
* Signature: (Ljava/lang/String;Ljava/lang/ClassLoader;)Z
|
||||||
|
*/
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToClassLoader
|
||||||
|
(JNIEnv *, jclass, jstring, jobject);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||||
|
* Method: defineClass
|
||||||
|
* Signature: (Ljava/lang/ClassLoader;[B)Ljava/lang/Class;
|
||||||
|
*/
|
||||||
|
JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_defineClass
|
||||||
|
(JNIEnv *, jclass, jobject, jbyteArray);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||||
|
* Method: redefineClass
|
||||||
|
* Signature: (Ljava/lang/Class;[BI)Z
|
||||||
|
*/
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClass
|
||||||
|
(JNIEnv *, jclass, jclass, jbyteArray, jint);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||||
|
* Method: redefineClassByName
|
||||||
|
* Signature: (Ljava/lang/String;[BI)Z
|
||||||
|
*/
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClassByName
|
||||||
|
(JNIEnv *, jclass, jstring, jbyteArray, jint);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||||
|
* Method: retransformClass
|
||||||
|
* Signature: (Ljava/lang/Class;[BI)Z
|
||||||
|
*/
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClass
|
||||||
|
(JNIEnv *, jclass, jclass, jbyteArray, jint);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||||
|
* Method: retransformClassByName
|
||||||
|
* Signature: (Ljava/lang/String;[BI)Z
|
||||||
|
*/
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClassByName
|
||||||
|
(JNIEnv *, jclass, jstring, jbyteArray, jint);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||||
|
* Method: getLoadedClasses
|
||||||
|
* Signature: ()[Ljava/lang/Class;
|
||||||
|
*/
|
||||||
|
JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getLoadedClasses
|
||||||
|
(JNIEnv *, jclass);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||||
|
* Method: getClassByName
|
||||||
|
* Signature: (Ljava/lang/String;)Ljava/lang/Class;
|
||||||
|
*/
|
||||||
|
JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassByName
|
||||||
|
(JNIEnv *, jclass, jstring);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||||
|
* Method: getClassBytes
|
||||||
|
* Signature: (Ljava/lang/Class;)[B
|
||||||
|
*/
|
||||||
|
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytes
|
||||||
|
(JNIEnv *, jclass, jclass);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||||
|
* Method: getClassBytesByName
|
||||||
|
* Signature: (Ljava/lang/String;)[B
|
||||||
|
*/
|
||||||
|
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytesByName
|
||||||
|
(JNIEnv *, jclass, jstring);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
@@ -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;
|
||||||
@@ -1,17 +1,18 @@
|
|||||||
#ifndef JNI_IMPL_H
|
#pragma once
|
||||||
#define JNI_IMPL_H
|
|
||||||
|
|
||||||
#include <jni.h>
|
#include <jni.h>
|
||||||
#include <jvmti.h>
|
#include <jvmti.h>
|
||||||
#include <juiceloader.h>
|
|
||||||
#include <JuiceAgent/Logger.hpp>
|
#include <JuiceAgent/Logger.hpp>
|
||||||
#include <cn_xiaozhou233_juiceloader_JuiceLoader.h>
|
#include <libagent.hpp>
|
||||||
|
#include <utils.hpp>
|
||||||
|
#include <global.hpp>
|
||||||
|
#include <algorithm>
|
||||||
|
|
||||||
// Variables
|
// Generated by JuiceAgent-API
|
||||||
extern const char* g_target_internal_name;
|
#include <cn_xiaozhou233_juiceagent_api_JuiceAgent.h>
|
||||||
extern unsigned char* g_bytecodes;
|
|
||||||
extern jint g_bytecodes_len;
|
|
||||||
|
|
||||||
|
// Event callbacks
|
||||||
|
// See https://docs.oracle.com/javase/8/docs/platform/jvmti/jvmti.html#ClassFileLoadHook
|
||||||
void JNICALL ClassFileLoadHook(
|
void JNICALL ClassFileLoadHook(
|
||||||
jvmtiEnv* jvmti_env,
|
jvmtiEnv* jvmti_env,
|
||||||
JNIEnv* jni_env,
|
JNIEnv* jni_env,
|
||||||
@@ -22,6 +23,4 @@ void JNICALL ClassFileLoadHook(
|
|||||||
jint class_data_len,
|
jint class_data_len,
|
||||||
const unsigned char* classbytes,
|
const unsigned char* classbytes,
|
||||||
jint* new_class_data_len,
|
jint* new_class_data_len,
|
||||||
unsigned char** new_classbytes);
|
unsigned char** new_classbytes);
|
||||||
|
|
||||||
#endif // JNI_IMPL_H
|
|
||||||
@@ -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 <libagent.hpp>
|
||||||
#include <jvm/jvmti.h>
|
#include <jni_impl.hpp>
|
||||||
#include <stdio.h>
|
|
||||||
#include <JuiceAgent/Logger.hpp>
|
|
||||||
#include <libagent.h>
|
|
||||||
#include <thread>
|
|
||||||
#include <tinytoml/toml.h>
|
|
||||||
#include <JuiceAgent/JuiceAgent.h>
|
|
||||||
|
|
||||||
struct _JuiceAgent {
|
namespace JuiceAgent {
|
||||||
bool isAttached;
|
// ===== Singleton =====
|
||||||
JavaVM *jvm;
|
Agent& Agent::instance() {
|
||||||
jvmtiEnv *jvmti;
|
static Agent instance;
|
||||||
JNIEnv *env;
|
return instance;
|
||||||
} JuiceAgent = {false, NULL, NULL, NULL};
|
|
||||||
|
|
||||||
InjectionInfoType InjectionInfo;
|
|
||||||
|
|
||||||
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
|
bool Agent::init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti) {
|
||||||
res = jvm->GetEnv((void**)&jvmti, JVMTI_VERSION_1_2);
|
PLOGI << "JuiceAgent Native EntryPoint Invoked!";
|
||||||
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;
|
// ======== neccessary environment check ========
|
||||||
}
|
if (jvm == nullptr) {
|
||||||
|
PLOGE << "Failed to initialize JuiceAgent: jvm is null";
|
||||||
static int InvokeJuiceLoaderInit(const char* ConfigDir) {
|
return false;
|
||||||
// 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";
|
if (env == nullptr) {
|
||||||
return 1;
|
PLOGE << "Failed to initialize JuiceAgent: env is null";
|
||||||
}
|
return false;
|
||||||
|
|
||||||
// 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;
|
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;
|
|
||||||
}
|
}
|
||||||
@@ -48,7 +48,7 @@ int main(int argc, char **argv) {
|
|||||||
printf("Warning: GetCurrentDirectory failed, using '.'\n");
|
printf("Warning: GetCurrentDirectory failed, using '.'\n");
|
||||||
strncpy(cwd, ".", MAX_PATH_LEN - 1);
|
strncpy(cwd, ".", MAX_PATH_LEN - 1);
|
||||||
}
|
}
|
||||||
snprintf(dll_path, MAX_PATH_LEN, "%s\\libagent.dll", cwd);
|
snprintf(dll_path, MAX_PATH_LEN, "%s\\libloader.dll", cwd);
|
||||||
printf("Using DLL path: %s\n", dll_path);
|
printf("Using DLL path: %s\n", dll_path);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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,141 +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: AddToBootstrapClassLoaderSearch
|
|
||||||
* Signature: (Ljava/lang/String;)Z
|
|
||||||
*/
|
|
||||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_AddToBootstrapClassLoaderSearch
|
|
||||||
(JNIEnv *, jclass, jstring);
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
|
||||||
* Method: AddToSystemClassLoaderSearch
|
|
||||||
* Signature: (Ljava/lang/String;)Z
|
|
||||||
*/
|
|
||||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_AddToSystemClassLoaderSearch
|
|
||||||
(JNIEnv *, jclass, jstring);
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
|
||||||
* Method: AddToClassLoader
|
|
||||||
* Signature: (Ljava/lang/String;Ljava/lang/ClassLoader;)Z
|
|
||||||
*/
|
|
||||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_AddToClassLoader
|
|
||||||
(JNIEnv *, jclass, jstring, jobject);
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
|
||||||
* Method: defineClass
|
|
||||||
* Signature: (Ljava/lang/ClassLoader;[B)Ljava/lang/Class;
|
|
||||||
*/
|
|
||||||
JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_defineClass
|
|
||||||
(JNIEnv *, jclass, jobject, jbyteArray);
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
|
||||||
* Method: redefineClass
|
|
||||||
* 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,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,74 +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*,
|
|
||||||
jclass,
|
|
||||||
jobject,
|
|
||||||
const char* name,
|
|
||||||
jobject,
|
|
||||||
jint class_data_len,
|
|
||||||
const unsigned char* classbytes,
|
|
||||||
jint* new_class_data_len,
|
|
||||||
unsigned char** new_classbytes) {
|
|
||||||
|
|
||||||
if (!name) return;
|
|
||||||
|
|
||||||
/* =========================
|
|
||||||
* 1. Capture original bytes
|
|
||||||
* ========================= */
|
|
||||||
if (g_target_internal_name &&
|
|
||||||
g_bytecodes == nullptr &&
|
|
||||||
strcmp(name, g_target_internal_name) == 0) {
|
|
||||||
|
|
||||||
g_bytecodes_len = class_data_len;
|
|
||||||
g_bytecodes = (unsigned char*)malloc(class_data_len);
|
|
||||||
memcpy(g_bytecodes, classbytes, class_data_len);
|
|
||||||
|
|
||||||
// IMPORTANT:
|
|
||||||
// Do NOT touch new_classbytes here
|
|
||||||
// Let JVM continue normally
|
|
||||||
PLOGD.printf("[Hook:get] Captured class bytes: %s (%d)", name, class_data_len);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* =========================
|
|
||||||
* 2. Apply redefine patch
|
|
||||||
* ========================= */
|
|
||||||
if (RetransformClassCache.size == 0) return;
|
|
||||||
|
|
||||||
for (int i = 0; i < RetransformClassCache.size; i++) {
|
|
||||||
ClassBytesCacheType* entry = &RetransformClassCache.arr[i];
|
|
||||||
if (strcmp(entry->name, name) == 0) {
|
|
||||||
|
|
||||||
unsigned char* newBytes = nullptr;
|
|
||||||
if (jvmti_env->Allocate(entry->len, &newBytes) != JVMTI_ERROR_NONE) {
|
|
||||||
PLOGE.printf("[Hook:set] Allocate failed: %s", name);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
memcpy(newBytes, entry->bytes, entry->len);
|
|
||||||
*new_classbytes = newBytes;
|
|
||||||
*new_class_data_len = entry->len;
|
|
||||||
|
|
||||||
PLOGI.printf("[Hook:set] Redefined class: %s (%d)", name, entry->len);
|
|
||||||
|
|
||||||
free(entry->name);
|
|
||||||
free(entry->bytes);
|
|
||||||
for (int j = i; j < RetransformClassCache.size - 1; j++) {
|
|
||||||
RetransformClassCache.arr[j] = RetransformClassCache.arr[j + 1];
|
|
||||||
}
|
|
||||||
RetransformClassCache.size--;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,176 +0,0 @@
|
|||||||
#include <jni_impl.h>
|
|
||||||
#include <string>
|
|
||||||
#include <cstring>
|
|
||||||
#include <algorithm>
|
|
||||||
|
|
||||||
/* =========================
|
|
||||||
* Global bytecode capture
|
|
||||||
* ========================= */
|
|
||||||
const char* g_target_internal_name = nullptr;
|
|
||||||
unsigned char* g_bytecodes = nullptr;
|
|
||||||
jint g_bytecodes_len = 0;
|
|
||||||
|
|
||||||
/* =========================
|
|
||||||
* Utils
|
|
||||||
* ========================= */
|
|
||||||
|
|
||||||
// Convert java name to internal name: a.b.C -> a/b/C
|
|
||||||
static void to_internal_name(char* s) {
|
|
||||||
for (; *s; ++s) {
|
|
||||||
if (*s == '.') *s = '/';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* =========================
|
|
||||||
* JVMTI: enumerate loaded classes
|
|
||||||
* ========================= */
|
|
||||||
static jclass findLoadedClassByInternalName(jvmtiEnv* jvmti, const char* internalName) {
|
|
||||||
jint count = 0;
|
|
||||||
jclass* classes = nullptr;
|
|
||||||
|
|
||||||
if (jvmti->GetLoadedClasses(&count, &classes) != JVMTI_ERROR_NONE || count == 0) {
|
|
||||||
return nullptr;
|
|
||||||
}
|
|
||||||
|
|
||||||
jclass result = nullptr;
|
|
||||||
|
|
||||||
for (jint i = 0; i < count; i++) {
|
|
||||||
char* signature = nullptr;
|
|
||||||
if (jvmti->GetClassSignature(classes[i], &signature, nullptr) == JVMTI_ERROR_NONE && signature) {
|
|
||||||
// signature format: Lnet/minecraft/xxx;
|
|
||||||
size_t len = strlen(signature);
|
|
||||||
if (len > 2 && signature[0] == 'L' && signature[len - 1] == ';') {
|
|
||||||
if (strncmp(signature + 1, internalName, len - 2) == 0) {
|
|
||||||
result = classes[i];
|
|
||||||
jvmti->Deallocate((unsigned char*)signature);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
jvmti->Deallocate((unsigned char*)signature);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (classes) {
|
|
||||||
jvmti->Deallocate((unsigned char*)classes);
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* =========================
|
|
||||||
* Exposed: get all loaded classes
|
|
||||||
* ========================= */
|
|
||||||
JNIEXPORT jobjectArray JNICALL
|
|
||||||
Java_cn_xiaozhou233_juiceloader_JuiceLoader_getLoadedClasses
|
|
||||||
(JNIEnv* env, jclass) {
|
|
||||||
|
|
||||||
if (!JuiceLoaderNative.jvmti) return nullptr;
|
|
||||||
|
|
||||||
jint count = 0;
|
|
||||||
jclass* classes = nullptr;
|
|
||||||
if (JuiceLoaderNative.jvmti->GetLoadedClasses(&count, &classes) != JVMTI_ERROR_NONE || count == 0) {
|
|
||||||
return env->NewObjectArray(0, env->FindClass("java/lang/Class"), nullptr);
|
|
||||||
}
|
|
||||||
|
|
||||||
jclass classClass = env->FindClass("java/lang/Class");
|
|
||||||
jobjectArray result = env->NewObjectArray(count, classClass, nullptr);
|
|
||||||
|
|
||||||
for (jint i = 0; i < count; i++) {
|
|
||||||
env->SetObjectArrayElement(result, i, classes[i]);
|
|
||||||
}
|
|
||||||
|
|
||||||
JuiceLoaderNative.jvmti->Deallocate((unsigned char*)classes);
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* =========================
|
|
||||||
* Get bytecode by jclass
|
|
||||||
* ========================= */
|
|
||||||
JNIEXPORT jbyteArray JNICALL
|
|
||||||
Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytes
|
|
||||||
(JNIEnv* env, jclass, jclass clazz) {
|
|
||||||
|
|
||||||
if (!JuiceLoaderNative.jvmti || !clazz) return nullptr;
|
|
||||||
|
|
||||||
char* signature = nullptr;
|
|
||||||
if (JuiceLoaderNative.jvmti->GetClassSignature(clazz, &signature, nullptr) != JVMTI_ERROR_NONE || !signature) {
|
|
||||||
return nullptr;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Lxxx; -> xxx
|
|
||||||
std::string internalName(signature + 1, strlen(signature) - 2);
|
|
||||||
JuiceLoaderNative.jvmti->Deallocate((unsigned char*)signature);
|
|
||||||
|
|
||||||
g_target_internal_name = internalName.c_str();
|
|
||||||
g_bytecodes = nullptr;
|
|
||||||
g_bytecodes_len = 0;
|
|
||||||
|
|
||||||
jvmtiError err = JuiceLoaderNative.jvmti->RetransformClasses(1, &clazz);
|
|
||||||
if (err != JVMTI_ERROR_NONE || !g_bytecodes) {
|
|
||||||
return nullptr;
|
|
||||||
}
|
|
||||||
|
|
||||||
jbyteArray out = env->NewByteArray(g_bytecodes_len);
|
|
||||||
env->SetByteArrayRegion(out, 0, g_bytecodes_len, (jbyte*)g_bytecodes);
|
|
||||||
|
|
||||||
free(g_bytecodes);
|
|
||||||
g_bytecodes = nullptr;
|
|
||||||
g_target_internal_name = nullptr;
|
|
||||||
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* =========================
|
|
||||||
* Get bytecode by class name
|
|
||||||
* ========================= */
|
|
||||||
JNIEXPORT jbyteArray JNICALL
|
|
||||||
Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytesByName
|
|
||||||
(JNIEnv* env, jclass loader_class, jstring className) {
|
|
||||||
|
|
||||||
if (!JuiceLoaderNative.jvmti || !className) return nullptr;
|
|
||||||
|
|
||||||
const char* utf = env->GetStringUTFChars(className, nullptr);
|
|
||||||
if (!utf) return nullptr;
|
|
||||||
|
|
||||||
char internal[512];
|
|
||||||
strncpy(internal, utf, sizeof(internal) - 1);
|
|
||||||
internal[sizeof(internal) - 1] = '\0';
|
|
||||||
env->ReleaseStringUTFChars(className, utf);
|
|
||||||
|
|
||||||
to_internal_name(internal);
|
|
||||||
|
|
||||||
jclass clazz = findLoadedClassByInternalName(JuiceLoaderNative.jvmti, internal);
|
|
||||||
if (!clazz) {
|
|
||||||
PLOGE.printf("Class not loaded: %s", internal);
|
|
||||||
return nullptr;
|
|
||||||
}
|
|
||||||
|
|
||||||
return Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytes(
|
|
||||||
env, loader_class, clazz
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* =========================
|
|
||||||
* Get jclass by name (no ClassLoader)
|
|
||||||
* ========================= */
|
|
||||||
JNIEXPORT jclass JNICALL
|
|
||||||
Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassByName
|
|
||||||
(JNIEnv* env, jclass, jstring className) {
|
|
||||||
|
|
||||||
if (!JuiceLoaderNative.jvmti || !className) return nullptr;
|
|
||||||
|
|
||||||
const char* utf = env->GetStringUTFChars(className, nullptr);
|
|
||||||
if (!utf) return nullptr;
|
|
||||||
|
|
||||||
char internal[512];
|
|
||||||
strncpy(internal, utf, sizeof(internal) - 1);
|
|
||||||
internal[sizeof(internal) - 1] = '\0';
|
|
||||||
env->ReleaseStringUTFChars(className, utf);
|
|
||||||
|
|
||||||
to_internal_name(internal);
|
|
||||||
|
|
||||||
jclass clazz = findLoadedClassByInternalName(JuiceLoaderNative.jvmti, internal);
|
|
||||||
if (!clazz) {
|
|
||||||
PLOGE.printf("Failed to find loaded class: %s", internal);
|
|
||||||
}
|
|
||||||
return clazz;
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
#include <jni_impl.h>
|
|
||||||
|
|
||||||
JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_defineClass
|
|
||||||
(JNIEnv *env, jclass, jobject cl, jbyteArray bytes) {
|
|
||||||
PLOGD << "Invoked!";
|
|
||||||
jclass clClass = env->FindClass("java/lang/ClassLoader");
|
|
||||||
jmethodID defineClass = env->GetMethodID(clClass, "defineClass", "([BII)Ljava/lang/Class;");
|
|
||||||
jobject classDefined = env->CallObjectMethod(cl, defineClass, bytes, 0,
|
|
||||||
env->GetArrayLength(bytes));
|
|
||||||
return (jclass)classDefined;
|
|
||||||
}
|
|
||||||
@@ -1,195 +0,0 @@
|
|||||||
#include <jni_impl.h>
|
|
||||||
|
|
||||||
// Deprecated
|
|
||||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_injectJar
|
|
||||||
(JNIEnv *env, jclass loader_class, jstring jarPath) {
|
|
||||||
PLOGI << "Invoked!";
|
|
||||||
const char *pathStr = env->GetStringUTFChars(jarPath, NULL);
|
|
||||||
if (!pathStr) {
|
|
||||||
PLOGE << "Path is NULL!";
|
|
||||||
return JNI_FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!JuiceLoaderNative.jvmti) {
|
|
||||||
PLOGE.printf("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
|
||||||
env->ReleaseStringUTFChars(jarPath, pathStr);
|
|
||||||
return JNI_FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
jvmtiError result = JuiceLoaderNative.jvmti->AddToSystemClassLoaderSearch(pathStr);
|
|
||||||
if (result != JVMTI_ERROR_NONE) {
|
|
||||||
PLOGE.printf("Cannot inject jar [result=%d]", result);
|
|
||||||
env->ReleaseStringUTFChars(jarPath, pathStr);
|
|
||||||
return JNI_FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
env->ReleaseStringUTFChars(jarPath, pathStr);
|
|
||||||
PLOGI << "Jar injected: " << pathStr;
|
|
||||||
return JNI_TRUE;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated
|
|
||||||
JNIEXPORT jobject JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_nativeInjectJarToThread
|
|
||||||
(JNIEnv* env, jclass, jobject threadObj, jstring jJarPath)
|
|
||||||
{
|
|
||||||
// Convert jstring -> std::string
|
|
||||||
const char* cJarPath = env->GetStringUTFChars(jJarPath, nullptr);
|
|
||||||
|
|
||||||
// new File(jarPath)
|
|
||||||
jclass fileClass = env->FindClass("java/io/File");
|
|
||||||
jmethodID fileCtor = env->GetMethodID(fileClass, "<init>", "(Ljava/lang/String;)V");
|
|
||||||
jstring jPathCopy = env->NewStringUTF(cJarPath);
|
|
||||||
jobject fileObj = env->NewObject(fileClass, fileCtor, jPathCopy);
|
|
||||||
|
|
||||||
// File.toURI()
|
|
||||||
jmethodID midToURI = env->GetMethodID(fileClass, "toURI", "()Ljava/net/URI;");
|
|
||||||
jobject uriObj = env->CallObjectMethod(fileObj, midToURI);
|
|
||||||
|
|
||||||
// URI.toURL()
|
|
||||||
jclass uriClass = env->FindClass("java/net/URI");
|
|
||||||
jmethodID midToURL = env->GetMethodID(uriClass, "toURL", "()Ljava/net/URL;");
|
|
||||||
jobject urlObj = env->CallObjectMethod(uriObj, midToURL);
|
|
||||||
|
|
||||||
// Thread.getContextClassLoader()
|
|
||||||
jclass threadClass = env->FindClass("java/lang/Thread");
|
|
||||||
jmethodID midGetCL = env->GetMethodID(
|
|
||||||
threadClass, "getContextClassLoader", "()Ljava/lang/ClassLoader;"
|
|
||||||
);
|
|
||||||
jobject originalCL = env->CallObjectMethod(threadObj, midGetCL);
|
|
||||||
|
|
||||||
// URLClassLoader(URL[] urls, ClassLoader parent)
|
|
||||||
jclass urlClassLoaderClass = env->FindClass("java/net/URLClassLoader");
|
|
||||||
jmethodID urlCLCtor = env->GetMethodID(
|
|
||||||
urlClassLoaderClass,
|
|
||||||
"<init>",
|
|
||||||
"([Ljava/net/URL;Ljava/lang/ClassLoader;)V"
|
|
||||||
);
|
|
||||||
|
|
||||||
// Create URL[] array with 1 element
|
|
||||||
jobjectArray urlArray = env->NewObjectArray(1, env->FindClass("java/net/URL"), nullptr);
|
|
||||||
env->SetObjectArrayElement(urlArray, 0, urlObj);
|
|
||||||
|
|
||||||
// Create new URLClassLoader
|
|
||||||
jobject newClassLoader = env->NewObject(
|
|
||||||
urlClassLoaderClass,
|
|
||||||
urlCLCtor,
|
|
||||||
urlArray,
|
|
||||||
originalCL
|
|
||||||
);
|
|
||||||
|
|
||||||
// thread.setContextClassLoader(newCL)
|
|
||||||
jmethodID midSetCL = env->GetMethodID(
|
|
||||||
threadClass,
|
|
||||||
"setContextClassLoader",
|
|
||||||
"(Ljava/lang/ClassLoader;)V"
|
|
||||||
);
|
|
||||||
env->CallVoidMethod(threadObj, midSetCL, newClassLoader);
|
|
||||||
|
|
||||||
env->ReleaseStringUTFChars(jJarPath, cJarPath);
|
|
||||||
|
|
||||||
return newClassLoader;
|
|
||||||
}
|
|
||||||
|
|
||||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_AddToBootstrapClassLoaderSearch
|
|
||||||
(JNIEnv *env, jclass, jstring jarPath) {
|
|
||||||
PLOGD << "Invoked!";
|
|
||||||
const char *pathStr = env->GetStringUTFChars(jarPath, NULL);
|
|
||||||
if (!pathStr) {
|
|
||||||
PLOGE << "Path is NULL!";
|
|
||||||
return JNI_FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!JuiceLoaderNative.jvmti) {
|
|
||||||
PLOGE.printf("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
|
||||||
env->ReleaseStringUTFChars(jarPath, pathStr);
|
|
||||||
return JNI_FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
jvmtiError result = JuiceLoaderNative.jvmti->AddToBootstrapClassLoaderSearch(pathStr);
|
|
||||||
if (result != JVMTI_ERROR_NONE) {
|
|
||||||
PLOGE.printf("Cannot AddToBootstrapClassLoaderSearch [result=%d]", result);
|
|
||||||
env->ReleaseStringUTFChars(jarPath, pathStr);
|
|
||||||
return JNI_FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
env->ReleaseStringUTFChars(jarPath, pathStr);
|
|
||||||
PLOGI << "AddToBootstrapClassLoaderSearch: " << pathStr;
|
|
||||||
return JNI_TRUE;
|
|
||||||
}
|
|
||||||
|
|
||||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_AddToSystemClassLoaderSearch
|
|
||||||
(JNIEnv *env, jclass, jstring jarPath) {
|
|
||||||
PLOGD << "Invoked!";
|
|
||||||
const char *pathStr = env->GetStringUTFChars(jarPath, NULL);
|
|
||||||
if (!pathStr) {
|
|
||||||
PLOGE << "Path is NULL!";
|
|
||||||
return JNI_FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!JuiceLoaderNative.jvmti) {
|
|
||||||
PLOGE.printf("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
|
||||||
env->ReleaseStringUTFChars(jarPath, pathStr);
|
|
||||||
return JNI_FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
jvmtiError result = JuiceLoaderNative.jvmti->AddToSystemClassLoaderSearch(pathStr);
|
|
||||||
if (result != JVMTI_ERROR_NONE) {
|
|
||||||
PLOGE.printf("Cannot AddToSystemClassLoaderSearch [result=%d]", result);
|
|
||||||
env->ReleaseStringUTFChars(jarPath, pathStr);
|
|
||||||
return JNI_FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
env->ReleaseStringUTFChars(jarPath, pathStr);
|
|
||||||
PLOGI << "AddToSystemClassLoaderSearch: " << pathStr;
|
|
||||||
return JNI_TRUE;
|
|
||||||
}
|
|
||||||
|
|
||||||
JNIEXPORT jboolean JNICALL
|
|
||||||
Java_cn_xiaozhou233_juiceloader_JuiceLoader_AddToClassLoader
|
|
||||||
(JNIEnv *env, jclass, jstring path, jobject loader) {
|
|
||||||
|
|
||||||
jclass urlClassLoader = env->FindClass("java/net/URLClassLoader");
|
|
||||||
|
|
||||||
if (env->IsInstanceOf(loader, urlClassLoader)) {
|
|
||||||
jclass fileClass = env->FindClass("java/io/File");
|
|
||||||
jmethodID fileInit = env->GetMethodID(
|
|
||||||
fileClass,
|
|
||||||
"<init>",
|
|
||||||
"(Ljava/lang/String;)V"
|
|
||||||
);
|
|
||||||
|
|
||||||
jobject file = env->NewObject(fileClass, fileInit, path);
|
|
||||||
|
|
||||||
jmethodID toURI = env->GetMethodID(
|
|
||||||
fileClass,
|
|
||||||
"toURI",
|
|
||||||
"()Ljava/net/URI;"
|
|
||||||
);
|
|
||||||
jobject uri = env->CallObjectMethod(file, toURI);
|
|
||||||
|
|
||||||
jclass uriClass = env->FindClass("java/net/URI");
|
|
||||||
jmethodID toURL = env->GetMethodID(
|
|
||||||
uriClass,
|
|
||||||
"toURL",
|
|
||||||
"()Ljava/net/URL;"
|
|
||||||
);
|
|
||||||
jobject url = env->CallObjectMethod(uri, toURL);
|
|
||||||
|
|
||||||
jmethodID addURL = env->GetMethodID(
|
|
||||||
urlClassLoader,
|
|
||||||
"addURL",
|
|
||||||
"(Ljava/net/URL;)V"
|
|
||||||
);
|
|
||||||
env->CallVoidMethod(loader, addURL, url);
|
|
||||||
} else {
|
|
||||||
// jstring -> const char*
|
|
||||||
const char* nativePath = env->GetStringUTFChars(path, nullptr);
|
|
||||||
|
|
||||||
JuiceLoaderNative.jvmti->AddToSystemClassLoaderSearch(nativePath);
|
|
||||||
|
|
||||||
// Release UTF string
|
|
||||||
env->ReleaseStringUTFChars(path, nativePath);
|
|
||||||
}
|
|
||||||
|
|
||||||
return JNI_TRUE;
|
|
||||||
}
|
|
||||||
@@ -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,142 +0,0 @@
|
|||||||
#include <jni_impl.h>
|
|
||||||
#include <string.h>
|
|
||||||
|
|
||||||
/* =========================
|
|
||||||
* utils
|
|
||||||
* ========================= */
|
|
||||||
|
|
||||||
static char* get_class_name(JNIEnv* env, jclass clazz) {
|
|
||||||
jclass clsClass = env->FindClass("java/lang/Class");
|
|
||||||
jmethodID mid = env->GetMethodID(clsClass, "getName", "()Ljava/lang/String;");
|
|
||||||
jstring nameStr = (jstring)env->CallObjectMethod(clazz, mid);
|
|
||||||
|
|
||||||
const char* tmp = env->GetStringUTFChars(nameStr, nullptr);
|
|
||||||
char* result = _strdup(tmp);
|
|
||||||
env->ReleaseStringUTFChars(nameStr, tmp);
|
|
||||||
env->DeleteLocalRef(nameStr);
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* =========================
|
|
||||||
* JVMTI global lookup
|
|
||||||
* ========================= */
|
|
||||||
|
|
||||||
static jclass findLoadedClassByInternalName(
|
|
||||||
jvmtiEnv* jvmti,
|
|
||||||
const char* internalName
|
|
||||||
) {
|
|
||||||
jint count = 0;
|
|
||||||
jclass* classes = nullptr;
|
|
||||||
|
|
||||||
if (jvmti->GetLoadedClasses(&count, &classes) != JVMTI_ERROR_NONE || count == 0) {
|
|
||||||
return nullptr;
|
|
||||||
}
|
|
||||||
|
|
||||||
jclass result = nullptr;
|
|
||||||
|
|
||||||
for (jint i = 0; i < count; i++) {
|
|
||||||
char* sig = nullptr;
|
|
||||||
if (jvmti->GetClassSignature(classes[i], &sig, nullptr) == JVMTI_ERROR_NONE && sig) {
|
|
||||||
// Lnet/minecraft/client/Minecraft;
|
|
||||||
if (sig[0] == 'L') {
|
|
||||||
size_t len = strlen(sig);
|
|
||||||
if (len > 2 &&
|
|
||||||
strncmp(sig + 1, internalName, len - 2) == 0 &&
|
|
||||||
internalName[len - 2] == '\0') {
|
|
||||||
result = classes[i];
|
|
||||||
jvmti->Deallocate((unsigned char*)sig);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
jvmti->Deallocate((unsigned char*)sig);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
jvmti->Deallocate((unsigned char*)classes);
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* =========================
|
|
||||||
* retransform by jclass
|
|
||||||
* ========================= */
|
|
||||||
|
|
||||||
JNIEXPORT jboolean JNICALL
|
|
||||||
Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClass
|
|
||||||
(JNIEnv* env, jclass, jclass clazz, jbyteArray classBytes, jint) {
|
|
||||||
|
|
||||||
if (!JuiceLoaderNative.jvmti || !clazz || !classBytes) {
|
|
||||||
return JNI_FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
char* nameDot = get_class_name(env, clazz);
|
|
||||||
for (char* p = nameDot; *p; ++p)
|
|
||||||
if (*p == '.') *p = '/';
|
|
||||||
|
|
||||||
jbyte* bytes = env->GetByteArrayElements(classBytes, nullptr);
|
|
||||||
jint len = env->GetArrayLength(classBytes);
|
|
||||||
|
|
||||||
if (RetransformClassCache.size >= RetransformClassCache.capacity) {
|
|
||||||
int newCap = RetransformClassCache.capacity == 0 ? 4 : RetransformClassCache.capacity * 2;
|
|
||||||
RetransformClassCache.arr =
|
|
||||||
(ClassBytesCacheType*)realloc(RetransformClassCache.arr, newCap * sizeof(ClassBytesCacheType));
|
|
||||||
RetransformClassCache.capacity = newCap;
|
|
||||||
}
|
|
||||||
|
|
||||||
ClassBytesCacheType* entry =
|
|
||||||
&RetransformClassCache.arr[RetransformClassCache.size++];
|
|
||||||
|
|
||||||
entry->name = _strdup(nameDot);
|
|
||||||
entry->bytes = (unsigned char*)malloc(len);
|
|
||||||
memcpy(entry->bytes, bytes, len);
|
|
||||||
entry->len = len;
|
|
||||||
|
|
||||||
env->ReleaseByteArrayElements(classBytes, bytes, JNI_ABORT);
|
|
||||||
|
|
||||||
jclass arr[1] = { clazz };
|
|
||||||
jvmtiError err = JuiceLoaderNative.jvmti->RetransformClasses(1, arr);
|
|
||||||
|
|
||||||
free(nameDot);
|
|
||||||
|
|
||||||
if (err != JVMTI_ERROR_NONE) {
|
|
||||||
PLOGE.printf("RetransformClasses failed: %d", err);
|
|
||||||
return JNI_FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
PLOGI.printf("[retransformClass] OK: %s (%d)", entry->name, entry->len);
|
|
||||||
return JNI_TRUE;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* =========================
|
|
||||||
* retransform by name (NO FindClass)
|
|
||||||
* ========================= */
|
|
||||||
|
|
||||||
JNIEXPORT jboolean JNICALL
|
|
||||||
Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClassByName
|
|
||||||
(JNIEnv* env, jclass loader_class, jstring className, jbyteArray classBytes, jint length) {
|
|
||||||
|
|
||||||
if (!JuiceLoaderNative.jvmti || !className) {
|
|
||||||
return JNI_FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
const char* utf = env->GetStringUTFChars(className, nullptr);
|
|
||||||
char internalName[512];
|
|
||||||
strncpy(internalName, utf, sizeof(internalName) - 1);
|
|
||||||
internalName[sizeof(internalName) - 1] = 0;
|
|
||||||
|
|
||||||
for (char* p = internalName; *p; ++p)
|
|
||||||
if (*p == '.') *p = '/';
|
|
||||||
|
|
||||||
env->ReleaseStringUTFChars(className, utf);
|
|
||||||
|
|
||||||
jclass target =
|
|
||||||
findLoadedClassByInternalName(JuiceLoaderNative.jvmti, internalName);
|
|
||||||
|
|
||||||
if (!target) {
|
|
||||||
PLOGE.printf("Class not loaded: %s", internalName);
|
|
||||||
return JNI_FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
return Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClass(
|
|
||||||
env, loader_class, target, classBytes, length
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -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,181 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <JuiceAgent/Logger.hpp>
|
||||||
|
#include <JuiceAgent/JuiceAgent.hpp>
|
||||||
|
#include <tinytoml/toml.h>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <fstream>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
namespace config {
|
||||||
|
|
||||||
|
class Config {
|
||||||
|
private:
|
||||||
|
std::string runtime_dir; // Runtime directory
|
||||||
|
toml::Value config{}; // Parsed TOML configuration
|
||||||
|
bool valid = false; // Whether the config is successfully loaded
|
||||||
|
|
||||||
|
// Escape special characters ';' = '\'
|
||||||
|
static std::string escape(const std::string& s) {
|
||||||
|
std::string out;
|
||||||
|
out.reserve(s.size());
|
||||||
|
for (char c : s) {
|
||||||
|
if (c == ';' || c == '=' || c == '\\') {
|
||||||
|
out += '\\';
|
||||||
|
}
|
||||||
|
out += c;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Append key=value pair to string
|
||||||
|
static void append_kv(std::string& out, const char* key, const std::string& value, bool& first) {
|
||||||
|
if (!first) out += ';';
|
||||||
|
first = false;
|
||||||
|
out += key;
|
||||||
|
out += '=';
|
||||||
|
out += escape(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper function: find value by dot-separated key
|
||||||
|
const toml::Value* find_value(const std::string& key) const {
|
||||||
|
if (!valid) return nullptr;
|
||||||
|
const toml::Value* current = &config;
|
||||||
|
size_t start = 0;
|
||||||
|
while (true) {
|
||||||
|
size_t dot = key.find('.', start);
|
||||||
|
std::string part = key.substr(start, dot - start);
|
||||||
|
|
||||||
|
if (!current->is<toml::Table>()) return nullptr;
|
||||||
|
|
||||||
|
const auto& table = current->as<toml::Table>();
|
||||||
|
auto it = table.find(part);
|
||||||
|
if (it == table.end()) return nullptr;
|
||||||
|
|
||||||
|
current = &it->second;
|
||||||
|
|
||||||
|
if (dot == std::string::npos) break;
|
||||||
|
start = dot + 1;
|
||||||
|
}
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
public:
|
||||||
|
explicit Config(const char* c_runtime_dir)
|
||||||
|
: runtime_dir(c_runtime_dir ? c_runtime_dir : "")
|
||||||
|
{
|
||||||
|
if (runtime_dir.empty()) {
|
||||||
|
PLOGW << "runtime_dir is empty";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::filesystem::path path = std::filesystem::path(runtime_dir) / "config.toml";
|
||||||
|
std::ifstream ifs(path);
|
||||||
|
if (!ifs.is_open()) {
|
||||||
|
PLOGE << "Failed to open config file: " << path;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
auto pr = toml::parse(ifs);
|
||||||
|
if (!pr.valid()) {
|
||||||
|
PLOGE << "Invalid TOML file: " << pr.errorReason;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
config = pr.value;
|
||||||
|
valid = true;
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
PLOGE << "TOML parse error: " << e.what();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get value by key with default
|
||||||
|
template<typename T>
|
||||||
|
T get_or_default(const std::string& key, const T& default_value, bool use_default_if_empty = false) const {
|
||||||
|
const toml::Value* val = find_value(key);
|
||||||
|
if (!val) return default_value;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if constexpr (std::is_same_v<T, std::string>) {
|
||||||
|
std::string s = val->as<std::string>();
|
||||||
|
if (use_default_if_empty && s.empty()) return default_value;
|
||||||
|
return s;
|
||||||
|
} else {
|
||||||
|
return val->as<T>();
|
||||||
|
}
|
||||||
|
} catch (...) {
|
||||||
|
return default_value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool is_valid() const {
|
||||||
|
return valid;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get InjectionInfo struct from config
|
||||||
|
InjectionInfo get_injection_info() const {
|
||||||
|
InjectionInfo info;
|
||||||
|
|
||||||
|
auto get_default_path = [&](const std::string& name) {
|
||||||
|
return (std::filesystem::path(runtime_dir) / name).string();
|
||||||
|
};
|
||||||
|
|
||||||
|
info.JuiceAgentAPIJarPath = get_or_default<std::string>(
|
||||||
|
"JuiceAgent.JuiceAgentAPIJarPath", get_default_path("JuiceAgent.jar"), true);
|
||||||
|
|
||||||
|
info.JuiceAgentNativePath = get_or_default<std::string>(
|
||||||
|
"JuiceAgent.JuiceAgentNativePath", get_default_path("libagent.dll"), true);
|
||||||
|
|
||||||
|
info.EntryJarPath = get_or_default<std::string>(
|
||||||
|
"Entry.EntryJarPath", get_default_path("entry.jar"), true);
|
||||||
|
|
||||||
|
info.EntryClass = get_or_default<std::string>(
|
||||||
|
"Entry.EntryClass", "com.example.Entry", true);
|
||||||
|
|
||||||
|
info.EntryMethod = get_or_default<std::string>(
|
||||||
|
"Entry.EntryMethod", "start", true);
|
||||||
|
|
||||||
|
info.InjectionDir = get_or_default<std::string>(
|
||||||
|
"Runtime.InjectionDir", get_default_path("injection"), true);
|
||||||
|
|
||||||
|
return info;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Serialize InjectionInfo to key=value; format
|
||||||
|
static std::string serialize(const InjectionInfo& info) {
|
||||||
|
std::string result;
|
||||||
|
result.reserve(256);
|
||||||
|
bool first = true;
|
||||||
|
|
||||||
|
append_kv(result, "Version", "1", first);
|
||||||
|
|
||||||
|
append_kv(result, "EntryJarPath", info.EntryJarPath, first);
|
||||||
|
append_kv(result, "EntryClass", info.EntryClass, first);
|
||||||
|
append_kv(result, "EntryMethod", info.EntryMethod, first);
|
||||||
|
|
||||||
|
append_kv(result, "JuiceAgentAPIJarPath", info.JuiceAgentAPIJarPath, first);
|
||||||
|
append_kv(result, "JuiceAgentNativePath", info.JuiceAgentNativePath, first);
|
||||||
|
|
||||||
|
append_kv(result, "InjectionDir", info.InjectionDir, first);
|
||||||
|
|
||||||
|
PLOGD << "Serialized args: " << result;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string serialize() const {
|
||||||
|
return serialize(get_injection_info());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Print InjectionInfo (debug)
|
||||||
|
inline void print_injection_info(const InjectionInfo& info) {
|
||||||
|
PLOGI << "JuiceAgent Injection Info:";
|
||||||
|
PLOGI << " JuiceAgentAPIJarPath: " << info.JuiceAgentAPIJarPath;
|
||||||
|
PLOGI << " JuiceAgentNativePath: " << info.JuiceAgentNativePath;
|
||||||
|
PLOGI << " EntryJarPath: " << info.EntryJarPath;
|
||||||
|
PLOGI << " EntryClass: " << info.EntryClass;
|
||||||
|
PLOGI << " EntryMethod: " << info.EntryMethod;
|
||||||
|
PLOGI << " InjectionDir: " << info.InjectionDir;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace config
|
||||||
@@ -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 <windows.h>
|
||||||
#include <JuiceAgent/Logger.hpp>
|
#include <JuiceAgent/Logger.hpp>
|
||||||
#include <libagent.h>
|
#include <libloader.hpp>
|
||||||
|
|
||||||
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) {
|
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) {
|
||||||
switch( fdwReason )
|
switch( fdwReason )
|
||||||
@@ -8,12 +8,10 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) {
|
|||||||
case DLL_PROCESS_ATTACH: {
|
case DLL_PROCESS_ATTACH: {
|
||||||
InitLogger();
|
InitLogger();
|
||||||
PLOGI << "DllMain: DLL_PROCESS_ATTACH";
|
PLOGI << "DllMain: DLL_PROCESS_ATTACH";
|
||||||
PLOGD.printf("lpReserved: %p", lpReserved);
|
|
||||||
|
|
||||||
const char* runtime_dir = (const char*)lpReserved;
|
const char* runtime_dir = (const char*)lpReserved;
|
||||||
PLOGD << "runtime_dir: " << runtime_dir;
|
|
||||||
|
|
||||||
InitJuiceAgent(runtime_dir);
|
libloader::entrypoint(runtime_dir);
|
||||||
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -29,7 +27,6 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) {
|
|||||||
|
|
||||||
case DLL_PROCESS_DETACH: {
|
case DLL_PROCESS_DETACH: {
|
||||||
PLOGI << "DllMain: DLL_PROCESS_DETACH";
|
PLOGI << "DllMain: DLL_PROCESS_DETACH";
|
||||||
PLOGD.printf("lpReserved: %p", lpReserved);
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
File renamed without changes.
Reference in new issue
Block a user