Compare commits

...
14 Commits
11 changed files with 201 additions and 333 deletions

No files matched your search

-2
View File
@@ -1,7 +1,5 @@
[Injection] [Injection]
BootstrapAPIPath = "D:/Development/JuiceLoader/build/libs/bootstrap-api.jar"
JuiceLoaderJarPath = "D:/Development/JuiceLoader/build/libs/JuiceLoader.jar" JuiceLoaderJarPath = "D:/Development/JuiceLoader/build/libs/JuiceLoader.jar"
JuiceLoaderLibPath = ""
EntryJarPath = "D:/Development/JuiceLoader/build/libs/Entry.jar" EntryJarPath = "D:/Development/JuiceLoader/build/libs/Entry.jar"
EntryClass = "cn.xiaozhou233.juiceloader.entry.Entry" EntryClass = "cn.xiaozhou233.juiceloader.entry.Entry"
EntryMethod = "start" EntryMethod = "start"
+1 -2
View File
@@ -7,7 +7,7 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON)
# version # version
set(PROJECT_VERSION_MAJOR 1) set(PROJECT_VERSION_MAJOR 1)
set(PROJECT_VERSION_MINOR 3) set(PROJECT_VERSION_MINOR 3)
set(PROJECT_BUILD_NUMBER 34) set(PROJECT_BUILD_NUMBER 37)
set(PROJECT_VERSION_STRING "v${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}-b${PROJECT_BUILD_NUMBER}") set(PROJECT_VERSION_STRING "v${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}-b${PROJECT_BUILD_NUMBER}")
message(STATUS " ======== Build version: ${PROJECT_VERSION_STRING} ======== ") message(STATUS " ======== Build version: ${PROJECT_VERSION_STRING} ======== ")
@@ -29,7 +29,6 @@ set(INCLUDES ${CMAKE_CURRENT_SOURCE_DIR}/includes)
add_subdirectory(${INCLUDES}/ReflectiveDLLInjection) add_subdirectory(${INCLUDES}/ReflectiveDLLInjection)
add_subdirectory(${INCLUDES}/log.c) add_subdirectory(${INCLUDES}/log.c)
add_subdirectory(${INCLUDES}/tomlc17) add_subdirectory(${INCLUDES}/tomlc17)
add_subdirectory(src/utils)
include(cmake/JuiceModule.cmake) include(cmake/JuiceModule.cmake)
-2
View File
@@ -23,7 +23,6 @@ function(add_juice_module NAME)
${CMAKE_SOURCE_DIR}/includes/log.c ${CMAKE_SOURCE_DIR}/includes/log.c
"${CMAKE_SOURCE_DIR}/src/${NAME}/utils" "${CMAKE_SOURCE_DIR}/src/${NAME}/utils"
"${CMAKE_SOURCE_DIR}/src/${NAME}/include" "${CMAKE_SOURCE_DIR}/src/${NAME}/include"
"${CMAKE_SOURCE_DIR}/src/utils"
) )
# Link common libraries # Link common libraries
@@ -31,7 +30,6 @@ function(add_juice_module NAME)
ReflectiveDLLInjection ReflectiveDLLInjection
log.c log.c
jvm jvm
utils
) )
add_subdirectory("${CMAKE_SOURCE_DIR}/src/${NAME}") add_subdirectory("${CMAKE_SOURCE_DIR}/src/${NAME}")
+1
View File
@@ -12,6 +12,7 @@ typedef struct _InjectionInfo {
char EntryJarPath[INJECT_PATH_MAX]; char EntryJarPath[INJECT_PATH_MAX];
char EntryClass[INJECT_PATH_MAX]; char EntryClass[INJECT_PATH_MAX];
char EntryMethod[INJECT_PATH_MAX]; char EntryMethod[INJECT_PATH_MAX];
char InjectionDir[INJECT_PATH_MAX];
} InjectionInfoType; } InjectionInfoType;
extern InjectionInfoType InjectionInfo; extern InjectionInfoType InjectionInfo;
+20 -6
View File
@@ -9,12 +9,20 @@ typedef struct _JuiceLoaderNative {
} JuiceLoaderNativeType; } JuiceLoaderNativeType;
extern JuiceLoaderNativeType JuiceLoaderNative; extern JuiceLoaderNativeType JuiceLoaderNative;
typedef struct _JavaHookCache { typedef struct {
bool isReady; char *name;
jclass hook_class; unsigned char *bytes;
jmethodID post_method; int len;
} JavaHookCacheType; } ClassBytesCacheType;
extern JavaHookCacheType JavaHookCache;
typedef struct {
ClassBytesCacheType *arr;
int size;
int capacity;
} RetransformClassCacheType;
extern RetransformClassCacheType RetransformClassCache;
jint init_juiceloader(JNIEnv *env, jvmtiEnv *jvmti); jint init_juiceloader(JNIEnv *env, jvmtiEnv *jvmti);
@@ -33,4 +41,10 @@ JNIEXPORT jobjectArray JNICALL loader_getLoadedClasses(JNIEnv *env, jclass loade
JNIEXPORT jbyteArray JNICALL loader_getClassBytes(JNIEnv *env, jclass loader_class, jclass clazz); JNIEXPORT jbyteArray JNICALL loader_getClassBytes(JNIEnv *env, jclass loader_class, jclass clazz);
// public static native byte[] getClassBytesByName(String className); // public static native byte[] getClassBytesByName(String className);
JNIEXPORT jbyteArray JNICALL loader_getClassBytesByName(JNIEnv *env, jclass loader_class, jstring className); JNIEXPORT jbyteArray JNICALL loader_getClassBytesByName(JNIEnv *env, jclass loader_class, jstring className);
// public static native boolean retransformClass(Class<?> clazz, byte[] classBytes, int length);
JNIEXPORT jboolean JNICALL loader_retransformClass(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray classBytes, jint length);
// public static native boolean retransformClassByName(String className, byte[] classBytes, int length);
JNIEXPORT jboolean JNICALL loader_retransformClassByName(JNIEnv *env, jclass loader_class, jstring className, jbyteArray classBytes, jint length);
// public static native Class<?> getClassByName(String className);
JNIEXPORT jclass JNICALL loader_getClassByName(JNIEnv *env, jclass loader_class, jstring className);
#endif #endif
File renamed without changes.
+139 -97
View File
@@ -10,7 +10,7 @@ Desc: JuiceLoader Native, Provide jni function for JuiceLoader
#include "javautils.h" #include "javautils.h"
JuiceLoaderNativeType JuiceLoaderNative; JuiceLoaderNativeType JuiceLoaderNative;
JavaHookCacheType JavaHookCache = {false, NULL, NULL}; RetransformClassCacheType RetransformClassCache = {NULL, 0, 0};
static const char* g_bytecodes_classname = NULL; static const char* g_bytecodes_classname = NULL;
static unsigned char* g_bytecodes = NULL; static unsigned char* g_bytecodes = NULL;
@@ -35,90 +35,54 @@ void JNICALL ClassFileLoadHook(
jint* new_class_data_len, jint* new_class_data_len,
unsigned char** new_classbytes) { unsigned char** new_classbytes) {
// Retransform save class bytes // ---- get class bytecode ---- //
if (g_bytecodes_classname != NULL && g_bytecodes == NULL) { if (g_bytecodes_classname != NULL && g_bytecodes == NULL) {
if (strcmp(name, g_bytecodes_classname) == 0) { if (strcmp(name, g_bytecodes_classname) == 0) {
g_bytecodes_len = class_data_len; g_bytecodes_len = class_data_len;
g_bytecodes = (unsigned char*)malloc(class_data_len); g_bytecodes = (unsigned char*)malloc(class_data_len);
memcpy(g_bytecodes, classbytes, class_data_len); memcpy(g_bytecodes, classbytes, class_data_len);
*new_classbytes = NULL; *new_classbytes = NULL;
*new_class_data_len = 0; *new_class_data_len = 0;
log_trace("[Hook:get] Captured class bytes of %s, len=%d", name, class_data_len);
return;
} }
} }
// ---- get class bytecode ---- //
// Java Hook Event // ---- set class bytecode ---- //
if (JavaHookCache.isReady){ if (RetransformClassCache.size == 0) {
// byte[] -> jbyteArray return;
jbyteArray jBytes = (*jni_env)->NewByteArray(jni_env, class_data_len);
if (jBytes == NULL) return;
// jbyteArray -> byte[]
(*jni_env)->SetByteArrayRegion(jni_env, jBytes, 0, class_data_len, (const jbyte*)classbytes);
jstring jName = (*jni_env)->NewStringUTF(jni_env, name);
// Call Java Hook
jbyteArray result = (jbyteArray)(*jni_env)->CallStaticObjectMethod(
jni_env,
JavaHookCache.hook_class,
JavaHookCache.post_method,
class_being_redefined,
loader,
jName,
protection_domain,
class_data_len,
jBytes
);
// clean up local references
(*jni_env)->DeleteLocalRef(jni_env, jName);
(*jni_env)->DeleteLocalRef(jni_env, jBytes);
// check result
if (result == NULL) {
// log_trace("result == NULL -> nothing to do");
return;
}
// ensure result is a byte array
jclass byteArrCls = (*jni_env)->FindClass(jni_env, "[B");
jboolean isByteArr = (*jni_env)->IsInstanceOf(jni_env, result, byteArrCls);
(*jni_env)->DeleteLocalRef(jni_env, byteArrCls);
if (!isByteArr) {
log_error("result is NOT byte[]");
return;
}
// get result length
jsize newLen = (*jni_env)->GetArrayLength(jni_env, (jarray)result);
// log_trace("newLen = %d", (int)newLen);
// check newLen
if (newLen <= 0 || newLen > 64 * 1024 * 1024) {
log_error("invalid newLen = %d", (int)newLen);
return;
}
// allocate new buffer
unsigned char* buf = NULL;
jint allocRes = (*jvmti_env)->Allocate(jvmti_env, (jlong)newLen, (unsigned char**)&buf);
if (allocRes != JVMTI_ERROR_NONE || buf == NULL) {
log_error("jvmti Allocate failed: %d", allocRes);
return;
}
// copy result to new buffer
(*jni_env)->GetByteArrayRegion(jni_env, (jbyteArray)result, 0, newLen, (jbyte*)buf);
// assign output pointers
*new_classbytes = buf;
*new_class_data_len = (int)newLen;
// log_trace("[*] Assigned output pointers: %p, %d", *new_classbytes, *new_class_data_len);
// clean up
(*jni_env)->DeleteLocalRef(jni_env, result);
} }
for (int i = 0; i < RetransformClassCache.size; i++) {
ClassBytesCacheType *entry = &RetransformClassCache.arr[i];
if (strcmp(entry->name, name) == 0) {
unsigned char *newBytes = NULL;
jvmtiError err = (*jvmti_env)->Allocate(jvmti_env, entry->len, &newBytes);
if (err != JVMTI_ERROR_NONE || newBytes == NULL) {
log_error("[Hook:set] jvmti->Allocate failed for class %s, err=%d", name, err);
return;
}
memcpy(newBytes, entry->bytes, entry->len);
*new_classbytes = newBytes;
*new_class_data_len = entry->len;
log_info("[Hook:set] Patched class: %s, new_len=%d", name, entry->len);
free(entry->name);
free(entry->bytes);
for (int j = i; j < RetransformClassCache.size - 1; j++) {
RetransformClassCache.arr[j] = RetransformClassCache.arr[j + 1];
}
RetransformClassCache.size--;
break;
}
}
// ---- set class bytecode ---- //
} }
@@ -141,9 +105,9 @@ jint init_juiceloader(JNIEnv *env, jvmtiEnv *jvmti) {
// Dynamic register jni functions // Dynamic register jni functions
jclass clazz = (*env)->FindClass(env, "cn/xiaozhou233/juiceloader/JuiceLoaderNative"); jclass clazz = (*env)->FindClass(env, "cn/xiaozhou233/juiceloader/JuiceLoader");
if (clazz == NULL) { if (clazz == NULL) {
log_error("Cannot find JuiceLoaderNative class!"); log_error("Cannot find JuiceLoader class!");
return JNI_ERR; return JNI_ERR;
} }
JNINativeMethod methods[] = { JNINativeMethod methods[] = {
@@ -160,7 +124,13 @@ jint init_juiceloader(JNIEnv *env, jvmtiEnv *jvmti) {
// public static native byte[] getClassBytes(Class<?> clazz); // public static native byte[] getClassBytes(Class<?> clazz);
// public static native byte[] getClassBytesByName(String className); // public static native byte[] getClassBytesByName(String className);
{"getClassBytes", "(Ljava/lang/Class;)[B", (void *)&loader_getClassBytes}, {"getClassBytes", "(Ljava/lang/Class;)[B", (void *)&loader_getClassBytes},
{ "getClassBytesByName", "(Ljava/lang/String;)[B", (void *)&loader_getClassBytesByName} { "getClassBytesByName", "(Ljava/lang/String;)[B", (void *)&loader_getClassBytesByName},
// public static native boolean retransformClass(Class<?> clazz, byte[] classBytes, int length);
{"retransformClass", "(Ljava/lang/Class;[BI)Z", (void *)&loader_retransformClass},
// public static native boolean retransformClassByName(String className, byte[] classBytes, int length);
{"retransformClassByName", "(Ljava/lang/String;[BI)Z", (void *)&loader_retransformClassByName},
// public static native Class<?> getClassByName(String className);
{"getClassByName", "(Ljava/lang/String;)Ljava/lang/Class;", (void *)&loader_getClassByName}
}; };
jint result = (*env)->RegisterNatives(env, clazz, methods, sizeof(methods) / sizeof(methods[0])); jint result = (*env)->RegisterNatives(env, clazz, methods, sizeof(methods) / sizeof(methods[0]));
if (result != JNI_OK) { if (result != JNI_OK) {
@@ -168,6 +138,11 @@ jint init_juiceloader(JNIEnv *env, jvmtiEnv *jvmti) {
return JNI_ERR; return JNI_ERR;
} }
// Init RetransformClassCache
RetransformClassCache.arr = NULL;
RetransformClassCache.size = 0;
RetransformClassCache.capacity = 0;
// Application ability // Application ability
jvmtiCapabilities caps; jvmtiCapabilities caps;
memset(&caps, 0, sizeof(caps)); memset(&caps, 0, sizeof(caps));
@@ -199,26 +174,8 @@ jint init_juiceloader(JNIEnv *env, jvmtiEnv *jvmti) {
// JuiceLoaderNative.init() // JuiceLoaderNative.init()
JNIEXPORT jboolean JNICALL loader_init(JNIEnv *env, jclass loader_class) { JNIEXPORT jboolean JNICALL loader_init(JNIEnv *env, jclass loader_class) {
log_info("init Invoked!"); // Deprcated
// Get JuiceEventBus class log_warn("JuiceLoaderNative.init() is deprecated, init will be done automatically.");
log_info("Find JuiceEventBus class...");
JavaHookCache.hook_class = (*env)->FindClass(env, "cn/xiaozhou233/juiceloader/JuiceEventBus");
if (JavaHookCache.hook_class == NULL) {
log_error("Cannot find JuiceEventBus class!");
return JNI_FALSE;
}
// Get test method
log_info("Find JuiceEventBus post method...");
JavaHookCache.post_method = (*env)->GetStaticMethodID(env, JavaHookCache.hook_class, "postClassFileLoadHook", "(Ljava/lang/Class;Ljava/lang/ClassLoader;Ljava/lang/String;Ljava/lang/Object;I[B)[B");
if (JavaHookCache.post_method == NULL) {
log_error("Cannot find JuiceEventBus hook method!");
return JNI_FALSE;
}
// Set Ready
log_info("JuiceEventBus is ready!");
JavaHookCache.isReady = true;
return JNI_TRUE; return JNI_TRUE;
} }
@@ -381,6 +338,7 @@ JNIEXPORT jbyteArray JNICALL loader_getClassBytes(JNIEnv *env, jclass loader_cla
return NULL; return NULL;
} }
// JVM 内部使用路径名(. 替换为 /)
for (char* p = className; *p; p++) { for (char* p = className; *p; p++) {
if (*p == '.') *p = '/'; if (*p == '.') *p = '/';
} }
@@ -434,3 +392,87 @@ JNIEXPORT jbyteArray JNICALL loader_getClassBytesByName(JNIEnv *env, jclass load
return loader_getClassBytes(env, loader_class, clazz); return loader_getClassBytes(env, loader_class, clazz);
} }
JNIEXPORT jboolean JNICALL loader_retransformClass(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray classBytes, jint length) {
if (JuiceLoaderNative.jvmti == NULL) {
log_error("JuiceLoaderNative.jvmti is NULL! (retransformClass)");
return JNI_FALSE;
}
const char *name_dot = get_class_name(env, clazz);
char* name = strdup(name_dot);
for (char* p = name; *p; ++p) {
if (*p == '.') *p = '/';
}
// get class bytes
jbyte *bytes = (*env)->GetByteArrayElements(env, classBytes, NULL);
jint len = (*env)->GetArrayLength(env, classBytes);
if (RetransformClassCache.size >= RetransformClassCache.capacity) {
int new_capacity = RetransformClassCache.capacity == 0 ? 4 : RetransformClassCache.capacity * 2;
RetransformClassCache.arr = realloc(RetransformClassCache.arr, new_capacity * sizeof(ClassBytesCacheType));
RetransformClassCache.capacity = new_capacity;
}
// save class bytes to cache
ClassBytesCacheType *entry = &RetransformClassCache.arr[RetransformClassCache.size++];
entry->name = _strdup(name);
entry->bytes = malloc(len);
memcpy(entry->bytes, bytes, len);
entry->len = len;
// clean up
(*env)->ReleaseByteArrayElements(env, classBytes, bytes, JNI_ABORT);
// retransform classes
jclass classes[1] = { clazz };
jvmtiError err = (*JuiceLoaderNative.jvmti)->RetransformClasses(JuiceLoaderNative.jvmti, 1, classes);
if (err != JVMTI_ERROR_NONE) {
log_error("RetransformClasses failed! [err=%d]", err);
return JNI_FALSE;
}
log_info("[retransformClass] Class retransformed: %s (len=%d)", entry->name, entry->len);
return JNI_TRUE;
}
JNIEXPORT jboolean JNICALL loader_retransformClassByName(JNIEnv *env, jclass loader_class, jstring className, jbyteArray classBytes, jint length) {
const char *name_dot = (*env)->GetStringUTFChars(env, className, NULL);
char *name = strdup(name_dot);
for (char *p = name; *p; ++p) if (*p == '.') *p = '/';
(*env)->ReleaseStringUTFChars(env, className, name_dot);
jclass target = (*env)->FindClass(env, name);
free(name);
if (!target) {
log_error("FindClass failed in retransformClassByName");
return JNI_FALSE;
}
return loader_retransformClass(env, loader_class, target, classBytes, length);
}
JNIEXPORT jclass JNICALL loader_getClassByName(JNIEnv *env, jclass loader_class, jstring className) {
if (className == NULL) {
return NULL;
}
// jstring -> const char*
const char *name_utf = (*env)->GetStringUTFChars(env, className, NULL);
if (name_utf == NULL) {
return NULL;
}
// find class
jclass clazz = (*env)->FindClass(env, name_utf);
// clean up
(*env)->ReleaseStringUTFChars(env, className, name_utf);
if (clazz == NULL) {
log_error("Failed to find class %s", name_utf);
}
return clazz;
}
+14 -149
View File
@@ -12,7 +12,7 @@ Desc: Entry point for the agent
#include "jvmti.h" #include "jvmti.h"
#include "InjectParameters.h" #include "InjectParameters.h"
#include "log.h" #include "log.h"
#include "GlobalUtils.h" #include "jvmutils.h"
#include "shlwapi.h" #include "shlwapi.h"
#include "tomlc17.h" #include "tomlc17.h"
#include "datautils.h" #include "datautils.h"
@@ -23,6 +23,12 @@ extern HINSTANCE hAppInstance;
InjectionInfoType InjectionInfo; InjectionInfoType InjectionInfo;
struct _JuiceAgent {
bool isAttached;
JavaVM *jvm;
jvmtiEnv *jvmti;
} JuiceAgent = {false, NULL, NULL};
static void initLogger() { static void initLogger() {
log_set_level(LOG_TRACE); log_set_level(LOG_TRACE);
log_is_log_time(false); log_is_log_time(false);
@@ -59,13 +65,6 @@ DWORD WINAPI ThreadProc(LPVOID lpParam) {
} }
toml_free(toml_result); toml_free(toml_result);
log_trace("Checking bootstrap-api.jar");
if (GetFileAttributesA(InjectionInfo.BootstrapAPIPath) == INVALID_FILE_ATTRIBUTES) {
log_error("bootstrap-api.jar not found: %s", InjectionInfo.BootstrapAPIPath);
// MessageBoxA(NULL, "bootstrap-api.jar not found", "Error", MB_OK);
return 1;
}
// Check JuiceLoader.jar // Check JuiceLoader.jar
log_trace("Checking JuiceLoader.jar"); log_trace("Checking JuiceLoader.jar");
@@ -95,6 +94,8 @@ DWORD WINAPI ThreadProc(LPVOID lpParam) {
if (result != JNI_OK) { if (result != JNI_OK) {
log_error("Failed to get JNIEnv (%d)", result); log_error("Failed to get JNIEnv (%d)", result);
// MessageBoxA(NULL, "Failed to get JNIEnv", "Error", MB_OK); // MessageBoxA(NULL, "Failed to get JNIEnv", "Error", MB_OK);
log_error("Maybe the JVM havent been init yet.");
JuiceAgent.isAttached = false;
return 1; return 1;
} }
log_info("Got JNIEnv"); log_info("Got JNIEnv");
@@ -113,9 +114,6 @@ DWORD WINAPI ThreadProc(LPVOID lpParam) {
log_info("Enabled jvmti"); log_info("Enabled jvmti");
// Inject jars // Inject jars
log_info("injecting bootstrap-api jar...");
(*jvmti)->AddToSystemClassLoaderSearch(jvmti, InjectionInfo.BootstrapAPIPath);
log_info("injected bootstrap-api jar");
log_info("injecting loader jar..."); log_info("injecting loader jar...");
(*jvmti)->AddToSystemClassLoaderSearch(jvmti, InjectionInfo.JuiceLoaderJarPath); (*jvmti)->AddToSystemClassLoaderSearch(jvmti, InjectionInfo.JuiceLoaderJarPath);
@@ -130,12 +128,12 @@ DWORD WINAPI ThreadProc(LPVOID lpParam) {
log_info("invoking loader init()..."); log_info("invoking loader init()...");
log_info("============ Loader Info ============\n"); log_info("============ Loader Info ============\n");
jclass cls = (*env)->FindClass(env, "cn/xiaozhou233/juiceloader/JuiceLoader"); jclass cls = (*env)->FindClass(env, "cn/xiaozhou233/juiceloader/JuiceLoaderBootstrap");
if (cls == NULL) { if (cls == NULL) {
log_error("FindClass JuiceLoader failed"); log_error("FindClass JuiceLoaderBootstrap failed");
return 1; return 1;
} }
jmethodID mid = (*env)->GetStaticMethodID(env, cls, "init", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"); jmethodID mid = (*env)->GetStaticMethodID(env, cls, "init", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
if (mid == NULL) { if (mid == NULL) {
log_error("GetStaticMethodID init failed"); log_error("GetStaticMethodID init failed");
if ((*env)->ExceptionCheck(env)) { if ((*env)->ExceptionCheck(env)) {
@@ -148,7 +146,8 @@ DWORD WINAPI ThreadProc(LPVOID lpParam) {
(*env)->CallStaticVoidMethod(env, cls, mid, (*env)->CallStaticVoidMethod(env, cls, mid,
(*env)->NewStringUTF(env, InjectionInfo.EntryJarPath), (*env)->NewStringUTF(env, InjectionInfo.EntryJarPath),
(*env)->NewStringUTF(env, InjectionInfo.EntryClass), (*env)->NewStringUTF(env, InjectionInfo.EntryClass),
(*env)->NewStringUTF(env, InjectionInfo.EntryMethod)); (*env)->NewStringUTF(env, InjectionInfo.EntryMethod),
(*env)->NewStringUTF(env, InjectionInfo.InjectionDir));
log_info("============ Loader Info =============\n"); log_info("============ Loader Info =============\n");
log_info("invoked. "); log_info("invoked. ");
log_info("done. cleaning up..."); log_info("done. cleaning up...");
@@ -184,28 +183,6 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpReserved){
DisableThreadLibraryCalls(hinstDLL); DisableThreadLibraryCalls(hinstDLL);
// JVM Options Inject Method Detection
// TODO: Remove Duplicated Code: GetCreatedJVM/GetEnv and var jvm/env (Duplicated at: ThreadProc)
JavaVM *jvm = NULL;
JNIEnv *env = NULL;
jint result = GetCreatedJVM(&jvm);
// Check if JVM is created
if (result != JNI_OK || jvm == NULL) {
log_error("Failed to get JVM (%d) [JVM: %p]", result, jvm);
MessageBoxA(NULL, "Failed to get JVM [GetCreatedJVM Faliled or JVM is NULL]\nCheck console for more info.", "Error", MB_OK);
return 1;
}
log_info("DllMain GetCreatedJVM OK. Checking if JVM is inited...");
// Check if JVM is inited
// JNI_EDETACHED: jvm not initialized, means Agent loaded before JVM inited (jvm options: -agentpath)
// Will exit DllMain and jvm will invoke Agent_OnLoad
if (GetJNIEnv(jvm, &env) == JNI_EDETACHED) {
log_warn("Inject Method JVM Options Detected! Exiting...");
log_trace("DllMain(DLL_PROCESS_ATTACH) Exiting...");
log_info("Agent Will be injected by the Inject Methood JVM Options.\n");
break;
}
// Allocate memory for local param // Allocate memory for local param
InjectParameters *localParm = (InjectParameters*)malloc(sizeof(InjectParameters)); InjectParameters *localParm = (InjectParameters*)malloc(sizeof(InjectParameters));
if (localParm == NULL) { if (localParm == NULL) {
@@ -263,115 +240,3 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpReserved){
} }
return bReturnValue; return bReturnValue;
} }
/// =========================================================== ///
/// Inject Method: JVM Options -agentpath
/// =========================================================== ///
/// Function: vm_init
/// Description: Called when the JVM is fully initialized. This is a callback function.
/// =========================================================== ///
static char *agent_options = NULL;
static void JNICALL vm_init(jvmtiEnv *jvmti, JNIEnv *env, jthread thread) {
log_info("vminit: VM fully initialized!");
log_info("Use options: %s", agent_options);
log_info("JNIEnv: %p", env);
log_info("jvmtiEnv: %p", jvmti);
log_info("Version: %d", (*env)->GetVersion(env));
// TODO: Remove Duplicated Code
// Check if agent_options is null
if (agent_options == NULL) {
// Use DLL path as default
log_info("agent_options is null, use DLL path as default");
char DllDir[INJECT_PATH_MAX] = {0};
if (GetModuleFileNameA(hAppInstance, DllDir, INJECT_PATH_MAX) == 0) {
// Failed to get module file name
DWORD err = GetLastError();
if (err == ERROR_MOD_NOT_FOUND) {
// Reflective detected, lpReserved must be set.
log_fatal("Reflective load detected! Please set ConfigDir manually! Exit.");
} else {
log_error("Normal Inject: GetModuleFileNameA failed! Error: %lu", err);
}
return;
} else {
// Normal Inject(e.g. CreateRemoteThread+LoadLibraryA), lpReserved can be NULL.
PathRemoveFileSpecA(DllDir);
log_info("GetModuleFileNameA: %s", DllDir);
agent_options = DllDir;
}
}
log_trace("agent_options: %s", agent_options);
// Allocate memory for InjectParameters
InjectParameters *localParm = (InjectParameters*)malloc(sizeof(InjectParameters));
if (localParm == NULL) {
log_error("malloc failed for InjectParameters");
return;
}
memset(localParm, 0, sizeof(InjectParameters));
// safe copy
safe_copy(localParm->ConfigDir, agent_options, INJECT_PATH_MAX);
// Start new thread
HANDLE hThread = CreateThread(NULL, 0, ThreadProc, localParm, 0, NULL);
if (hThread) {
CloseHandle(hThread);
} else {
log_error("CreateThread failed %lu", GetLastError());
free(localParm);
}
}
/// =========================================================== ///
/// Function: Agent_OnLoad
/// Description: Java Agent OnLoad
/// Inject Method: JVM Options A) -agentpath:<path-to-agent>.dll=<param-config-dir>
/// Example: java -agentpath:./libagent.dll=./config -jar myapp.jar
/// =========================================================== ///
// Notice: This function is called by the JVM when the agent is loaded.
// Warning: JVM not initialized yet when this function is called.
JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *vm, char *options, void *reserved) {
initLogger();
log_info("Agent_OnLoad");
log_info("Agent_OnLoad: options: %s", options);
// save options
if (options != NULL) {
agent_options = strdup(options);
}
jvmtiEnv *jvmti;
(*vm)->GetEnv(vm, (void **)&jvmti, JVMTI_VERSION_1_2);
// callbacks
jvmtiEventCallbacks callbacks = {0};
callbacks.VMInit = &vm_init;
(*jvmti)->SetEventCallbacks(jvmti, &callbacks, sizeof(callbacks));
// enable events
(*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, NULL);
log_info("Agent_OnLoad: Done, waiting for JVM Init event.");
return JNI_OK;
}
/// Inject Method: JVM Options -agentpath
/// =========================================================== ///
// Notice: This function is useless but required by the JVM (in Windows).
JNIEXPORT jint JNICALL Agent_OnAttach (JavaVM* vm, char *options, void *reserved) {
log_info("Agent_OnAttach");
#ifdef WIN_X64
log_warn("Agent_OnAttach: Windows will invoke DllMain, Exiting Agent_OnAttach.");
log_info("Agent_OnAttach will exit in Windows, Loading will be done in DllMain.\n");
#endif
return JNI_OK;
}
+25 -61
View File
@@ -8,82 +8,46 @@ Desc: data utils
#include "datautils.h" #include "datautils.h"
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include <stdlib.h>
#include "tomlc17.h" #include "tomlc17.h"
#include "juiceloader.h"
void safe_copy(char *dest, const char *src, size_t dest_size) { void safe_copy(char *dest, const char *src, size_t dest_size) {
if (!dest || dest_size == 0) return; if (!dest || dest_size == 0) return;
strncpy(dest, src, dest_size - 1); strncpy(dest, src, dest_size - 1);
dest[dest_size - 1] = '\0'; dest[dest_size - 1] = '\0';
} }
static void GetTomlStringOrDefault(toml_datum_t tableDatum, const char* key, const char* defaultVal, char* outBuf, size_t bufSize) {
toml_datum_t datum = toml_seek(tableDatum, key);
if (datum.type != TOML_STRING || !datum.u.s || datum.u.s[0] == '\0') {
safe_copy(outBuf, defaultVal, bufSize);
} else {
safe_copy(outBuf, datum.u.s, bufSize);
}
}
bool ReadInjectionInfo(toml_result_t result, InjectParameters* params) { bool ReadInjectionInfo(toml_result_t result, InjectParameters* params) {
if (!result.ok) return false;
toml_datum_t InjectionTree = toml_seek(result.toptab, "Injection"); toml_datum_t InjectionTree = toml_seek(result.toptab, "Injection");
if (InjectionTree.type != TOML_TABLE) {
// ======= BootstrapAPIPath ======= log_error("Injection section missing");
toml_datum_t BootstrapAPIPath = toml_seek(InjectionTree, "BootstrapAPIPath");
char BootstrapAPIPathStr[INJECT_PATH_MAX];
if (BootstrapAPIPath.type != TOML_STRING) {
log_error("BootstrapAPIPath is not a string.");
return false; return false;
} }
if (BootstrapAPIPath.u.s == NULL || strlen(BootstrapAPIPath.u.s) == 0) {
sprintf(BootstrapAPIPathStr, "%s\\bootstrap-api.jar", params->ConfigDir);
} else {
sprintf(BootstrapAPIPathStr, "%s", BootstrapAPIPath.u.s);
}
safe_copy(InjectionInfo.BootstrapAPIPath, BootstrapAPIPathStr, INJECT_PATH_MAX);
// ======= BootstrapAPIPath =======
// ======= JuiceLoaderJarPath ======= char tmp[INJECT_PATH_MAX];
toml_datum_t JuiceLoaderJarPath = toml_seek(InjectionTree, "JuiceLoaderJarPath");
char JuiceLoaderJarPathStr[INJECT_PATH_MAX];
if (JuiceLoaderJarPath.type != TOML_STRING) {
log_error("JuiceLoaderJarPath is not a string.");
return false;
}
if (JuiceLoaderJarPath.u.s == NULL || strlen(JuiceLoaderJarPath.u.s) == 0) {
sprintf(JuiceLoaderJarPathStr, "%s\\JuiceLoader.jar", params->ConfigDir);
} else {
sprintf(JuiceLoaderJarPathStr, "%s", JuiceLoaderJarPath.u.s);
}
safe_copy(InjectionInfo.JuiceLoaderJarPath, JuiceLoaderJarPathStr, INJECT_PATH_MAX);
// ======= JuiceLoaderJarPath =======
// ======= Entry ======= snprintf(tmp, sizeof(tmp), "%s\\JuiceLoader.jar", params->ConfigDir);
toml_datum_t EntryJarPath = toml_seek(InjectionTree, "EntryJarPath"); GetTomlStringOrDefault(InjectionTree, "JuiceLoaderJarPath", tmp, InjectionInfo.JuiceLoaderJarPath, INJECT_PATH_MAX);
char EntryJarPathStr[INJECT_PATH_MAX];
if (EntryJarPath.type != TOML_STRING) {
log_error("EntryJarPath is not a string.");
return false;
}
if (EntryJarPath.u.s == NULL || strlen(EntryJarPath.u.s) == 0) {
sprintf(EntryJarPathStr, "%s\\entry.jar", params->ConfigDir);
} else {
sprintf(EntryJarPathStr, "%s", EntryJarPath.u.s);
}
safe_copy(InjectionInfo.EntryJarPath, EntryJarPathStr, INJECT_PATH_MAX);
toml_datum_t EntryClass = toml_seek(InjectionTree, "EntryClass"); snprintf(tmp, sizeof(tmp), "%s\\entry.jar", params->ConfigDir);
if (EntryClass.type != TOML_STRING) { GetTomlStringOrDefault(InjectionTree, "EntryJarPath", tmp, InjectionInfo.EntryJarPath, INJECT_PATH_MAX);
log_error("EntryClass is not a string.");
return false; GetTomlStringOrDefault(InjectionTree, "EntryClass", "cn.xiaozhou233.juiceloader.entry.Entry", InjectionInfo.EntryClass, INJECT_PATH_MAX);
} GetTomlStringOrDefault(InjectionTree, "EntryMethod", "start", InjectionInfo.EntryMethod, INJECT_PATH_MAX);
if (EntryClass.u.s == NULL || strlen(EntryClass.u.s) == 0) {
safe_copy(InjectionInfo.EntryClass, "cn.xiaozhou233.juiceloader.entry.Entry", INJECT_PATH_MAX); snprintf(tmp, sizeof(tmp), "%s\\injection", params->ConfigDir);
} else { GetTomlStringOrDefault(InjectionTree, "InjectionDir", tmp, InjectionInfo.InjectionDir, INJECT_PATH_MAX);
safe_copy(InjectionInfo.EntryClass, EntryClass.u.s, INJECT_PATH_MAX);
}
toml_datum_t EntryMethod = toml_seek(InjectionTree, "EntryMethod");
if (EntryMethod.type != TOML_STRING) {
log_error("EntryMethod is not a string.");
return false;
}
if (EntryMethod.u.s == NULL || strlen(EntryMethod.u.s) == 0) {
safe_copy(InjectionInfo.EntryMethod, "start", INJECT_PATH_MAX);
} else {
safe_copy(InjectionInfo.EntryMethod, EntryMethod.u.s, INJECT_PATH_MAX);
}
// ======= Entry =======
return true; return true;
} }
@@ -1,4 +1,4 @@
#include "./GlobalUtils.h" #include "jvmutils.h"
// Get JavaVM // Get JavaVM
jint GetCreatedJVM(JavaVM **out_jvm) { jint GetCreatedJVM(JavaVM **out_jvm) {
-13
View File
@@ -1,13 +0,0 @@
# src/utils/CMakeLists.txt
add_library(utils STATIC
JVMUtils.c)
target_include_directories(utils PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_SOURCE_DIR}/includes
${CMAKE_SOURCE_DIR}/includes/jvm
${CMAKE_SOURCE_DIR}/includes/jvm/win32)
target_link_libraries(utils PRIVATE
jvm)