[Update] Remove useless code

This commit is contained in:
xiaozhou233 committed 2025-11-14 21:18:24 +08:00
1 parent c4bbbabe07
commit ebc557c2f2
10 files changed
+23 -3986

No files matched your search

-4
View File
@@ -1,4 +0,0 @@
/scanvalue
/scankey
/parser
/*.so.*
-10
View File
@@ -1,10 +0,0 @@
# includes/tomlc17/CMakeLists.txt
add_library(tomlc17 STATIC tomlc17.c)
set_target_properties(tomlc17 PROPERTIES
OUTPUT_NAME "tomlc17"
)
target_include_directories(tomlc17 PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}
)
-41
View File
@@ -1,41 +0,0 @@
HFILES = tomlc17.h
CFILES = tomlc17.c
OBJ = $(CFILES:.c=.o)
CFLAGS = -std=c17 -fpic -Wmissing-declarations -Wall -Wextra -MMD
LIB_VERSION = 1.0
LIB = libtomlc17.a
LIB_SHARED = libtomlc17.so.$(LIB_VERSION)
EXEC =
ifdef DEBUG
CFLAGS += -O0 -g
else
CFLAGS += -O3 -DNDEBUG
endif
all: $(EXEC) $(LIB) $(LIB_SHARED)
*.o: $(HFILES)
libtomlc17.a: tomlc17.o
ar -rcs $@ $^
$(LIB_SHARED): tomlc17.o
$(CC) -shared -o $@ $^
-include $(OBJ:%.o=%.d) $(EXEC:%=%.d)
test: all
clean:
rm -f *.o *.d *.a *.so.* $(EXEC)
distclean: clean
format:
clang-format -i *.[ch] *.hpp
.PHONY: all clean distclean format
File diff suppressed because it is too large. Load diff
-190
View File
@@ -1,190 +0,0 @@
/* Copyright (c) 2024-2025, CK Tan.
* https://github.com/cktan/tomlc17/blob/main/LICENSE
*/
#ifndef TOMLC17_H
#define TOMLC17_H
/*
* USAGE:
*
* 1. Call toml_parse(), toml_parse_file(), or toml_parse_file_ex()
* 2. Check result.ok
* 3. Use toml_get() or toml_seek() to query and traverse the
* result.toptab
* 4. Call toml_free() to release resources.
*
*/
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#ifdef __cplusplus
#define TOML_EXTERN extern "C"
#else
#define TOML_EXTERN extern
#endif
enum toml_type_t {
TOML_UNKNOWN = 0,
TOML_STRING,
TOML_INT64,
TOML_FP64,
TOML_BOOLEAN,
TOML_DATE,
TOML_TIME,
TOML_DATETIME,
TOML_DATETIMETZ,
TOML_ARRAY,
TOML_TABLE,
};
typedef enum toml_type_t toml_type_t;
/* This is a Node in a Tree that represents a toml document rooted
* at toml_result_t::toptab.
*/
typedef struct toml_datum_t toml_datum_t;
struct toml_datum_t {
toml_type_t type;
uint32_t flag; // internal
union {
const char *s; // same as str.ptr; use if there are no NUL in string.
struct {
const char *ptr; // NUL terminated string
int len; // length excluding the terminating NUL.
} str;
int64_t int64; // integer
double fp64; // float
bool boolean;
struct { // date, time
int16_t year, month, day;
int16_t hour, minute, second;
int32_t usec;
int16_t tz; // in minutes
} ts;
struct { // array
int32_t size; // count elem
toml_datum_t *elem; // elem[]
} arr;
struct { // table
int32_t size; // count key
const char **key; // key[]
int *len; // len[]
toml_datum_t *value; // value[]
} tab;
} u;
};
/* Result returned by toml_parse() */
typedef struct toml_result_t toml_result_t;
struct toml_result_t {
bool ok; // success flag
toml_datum_t toptab; // valid if ok
char errmsg[200]; // valid if not ok
void *__internal; // do not use
};
/**
* Parse a toml document. Returns a toml_result which must be freed
* using toml_free() eventually.
*
* IMPORTANT: src[] must be a NUL terminated string! The len parameter
* does not include the NUL terminator.
*/
TOML_EXTERN toml_result_t toml_parse(const char *src, int len);
/**
* Parse a toml file. Returns a toml_result which must be freed
* using toml_free() eventually.
*
* IMPORTANT: you are still responsible to fclose(fp).
*/
TOML_EXTERN toml_result_t toml_parse_file(FILE *fp);
/**
* Parse a toml file. Returns a toml_result which must be freed
* using toml_free() eventually.
*/
TOML_EXTERN toml_result_t toml_parse_file_ex(const char *fname);
/**
* Release the result.
*/
TOML_EXTERN void toml_free(toml_result_t result);
/**
* Find a key in a toml_table. Return the value of the key if found,
* or a TOML_UNKNOWN otherwise.
*/
TOML_EXTERN toml_datum_t toml_get(toml_datum_t table, const char *key);
/**
* Locate a value starting from a toml_table. Return the value of the key if
* found, or a TOML_UNKNOWN otherwise.
*
* Note: the multipart-key is separated by DOT, and must not have any escape
* chars.
*/
TOML_EXTERN toml_datum_t toml_seek(toml_datum_t table,
const char *multipart_key);
/**
* OBSOLETE: use toml_get() instead.
* Find a key in a toml_table. Return the value of the key if found,
* or a TOML_UNKNOWN otherwise. (
*/
static inline toml_datum_t toml_table_find(toml_datum_t table,
const char *key) {
return toml_get(table, key);
}
/**
* Override values in r1 using r2. Return a new result. All results
* (i.e., r1, r2 and the returned result) must be freed using toml_free()
* after use.
*
* LOGIC:
* ret = copy of r1
* for each item x in r2:
* if x is not in ret:
* override
* elif x in ret is NOT of the same type:
* override
* elif x is an array of tables:
* append r2.x to ret.x
* elif x is a table:
* merge r2.x to ret.x
* else:
* override
*/
TOML_EXTERN toml_result_t toml_merge(const toml_result_t *r1,
const toml_result_t *r2);
/**
* Check if two results are the same. Dictinary and array orders are
* sensitive.
*/
TOML_EXTERN bool toml_equiv(const toml_result_t *r1, const toml_result_t *r2);
/* Options that override tomlc17 defaults globally */
typedef struct toml_option_t toml_option_t;
struct toml_option_t {
bool check_utf8; // Check all chars are valid utf8; default: false.
void *(*mem_realloc)(void *ptr, size_t size); // default: realloc()
void (*mem_free)(void *ptr); // default: free()
};
/**
* Get the default options. IF NECESSARY, use this to initialize
* toml_option_t and override values before calling
* toml_set_option().
*/
TOML_EXTERN toml_option_t toml_default_option(void);
/**
* Set toml options globally. Do this ONLY IF you are not satisfied with the
* defaults.
*/
TOML_EXTERN void toml_set_option(toml_option_t opt);
#endif // TOMLC17_H
-231
View File
@@ -1,231 +0,0 @@
#pragma once
#if !defined(__cplusplus) || __cplusplus < 202002L
#error "This code requires C++20 or later"
#endif
#include "tomlc17.h"
#include <chrono>
#include <cstdint>
#include <optional>
#include <string>
#include <vector>
namespace toml {
class Datum : public toml_datum_t {
public:
using datetime = std::chrono::sys_time<std::chrono::microseconds>;
using time = std::chrono::hh_mm_ss<std::chrono::microseconds>;
using date = std::chrono::year_month_day;
Datum(toml_datum_t dat = toml_datum_t{}) : toml_datum_t(dat) {}
bool is_table() const { return type == TOML_TABLE; }
bool is_array() const { return type == TOML_ARRAY; }
// Retrieve a string.
std::optional<std::string_view> as_str() const {
if (type != TOML_STRING)
return std::nullopt;
else
return std::string_view{u.str.ptr, (size_t)u.str.len};
}
// Retrieve an int.
std::optional<std::int64_t> as_int() const {
if (type != TOML_INT64)
return std::nullopt;
else
return u.int64;
}
// Retrieve a float.
std::optional<double> as_real() const {
if (type != TOML_FP64)
return std::nullopt;
else
return u.fp64;
}
// Retrieve a boolean.
std::optional<bool> as_bool() const {
if (type != TOML_BOOLEAN)
return std::nullopt;
else
return !!u.boolean;
}
// Retrieve a date.
std::optional<date> as_date() const {
using namespace std::chrono;
if (type != TOML_DATE)
return std::nullopt;
else
return date{year(u.ts.year), month(u.ts.month), day(u.ts.day)};
}
// Retrieve a time.
std::optional<time> as_time() const {
using namespace std::chrono;
if (type != TOML_TIME)
return std::nullopt;
else
return time{hours(u.ts.hour) + minutes(u.ts.minute) +
seconds(u.ts.second) + microseconds(u.ts.usec)};
}
// Retrieve a datetime.
std::optional<datetime> as_datetime() const {
using namespace std::chrono;
if (type != TOML_DATETIME) {
return std::nullopt;
}
year_month_day ymd{year{u.ts.year}, month{(unsigned)u.ts.month},
day{(unsigned)u.ts.day}};
auto tod = hours{u.ts.hour} + minutes{u.ts.minute} + seconds{u.ts.second} +
microseconds{u.ts.usec};
return datetime{sys_days{ymd} + tod};
}
// Retrieve a datetime and minute offset from UTC.
std::optional<std::pair<datetime, int>> as_datetimetz() const {
using namespace std::chrono;
if (type != TOML_DATETIMETZ) {
return std::nullopt;
}
year_month_day ymd{year{u.ts.year}, month{(unsigned)u.ts.month},
day{(unsigned)u.ts.day}};
auto tod = hours{u.ts.hour} + minutes{u.ts.minute} + seconds{u.ts.second} +
microseconds{u.ts.usec};
return std::pair{datetime{sys_days{ymd} + tod}, u.ts.tz};
}
// Retrieve an array of Datum from this datum.
std::optional<std::vector<Datum>> as_vector() const {
if (type != TOML_ARRAY) {
return std::nullopt;
}
std::vector<Datum> ret;
ret.assign(u.arr.elem, u.arr.elem + u.arr.size);
return ret;
}
// Retrieve an array of strings from this datum.
std::optional<std::vector<std::string_view>> as_strvec() const {
try {
auto vec = as_vector().value();
std::vector<std::string_view> ret;
ret.resize(vec.size());
for (size_t i = 0; i < vec.size(); i++) {
ret[i] = vec[i].as_str().value();
}
return ret;
} catch (const std::bad_optional_access &ex) {
return std::nullopt;
}
}
// Retrieve an array of ints from this datum
std::optional<std::vector<int64_t>> as_intvec() const {
try {
auto vec = as_vector().value();
std::vector<int64_t> ret;
ret.resize(vec.size());
for (size_t i = 0; i < vec.size(); i++) {
ret[i] = *vec[i].as_int();
}
return ret;
} catch (const std::bad_optional_access &ex) {
return std::nullopt;
}
}
// For tables. Retrieve the value of a composite key from this datum
// (which is a table).
std::optional<Datum> get(std::initializer_list<std::string_view> keys) const {
Datum tab = *this;
Datum value;
for (auto key : keys) {
value = {};
if (tab.type != TOML_TABLE) {
return std::nullopt;
}
for (int i = 0; i < tab.u.tab.size; i++) {
if (key ==
std::string_view{tab.u.tab.key[i], (size_t)tab.u.tab.len[i]}) {
value = tab.u.tab.value[i];
break;
}
}
tab = value;
}
return value;
}
// Retrieve the value of a key
std::optional<Datum> get(std::string_view key) const { return get({key}); }
// Retrieve the value of a multi-part key
std::optional<Datum> seek(const char *multipart_key) const {
auto ret = toml_seek(*this, multipart_key);
if (!ret.type) {
return std::nullopt;
}
return ret;
}
}; // class Datum
class Result : private toml_result_t {
public:
Result(const toml_result_t& result) : toml_result_t(result) {}
~Result() noexcept { toml_free(*this); }
// Disallow copying
Result(const Result&) = delete;
Result& operator=(const Result&) = delete;
// Allow moving
Result(Result&& other) noexcept : toml_result_t() {
swap(*this, other);
}
Result& operator=(Result&& other) noexcept {
swap(*this, other);
return *this;
}
// Access methods
bool ok() const { return toml_result_t::ok; }
Datum toptab() const { return toml_result_t::toptab; }
const char* errmsg() const { return toml_result_t::errmsg; }
// Shortcuts
std::optional<Datum> get(std::initializer_list<std::string_view> keys) const {
return toptab().get(keys);
}
std::optional<Datum> seek(const char *multipart_key) const {
return toptab().seek(multipart_key);
}
private:
friend void swap(Result& a, Result& b) noexcept {
std::swap(static_cast<toml_result_t&>(a), static_cast<toml_result_t&>(b));
}
};
static inline Result parse_file(FILE* fp) {
return Result{toml_parse_file(fp)};
}
static inline Result parse_file_ex(const char* fname) {
return Result{toml_parse_file_ex(fname)};
}
static inline Result parse(const std::string& s) {
return Result{toml_parse(s.data(), s.size())};
}
}; // namespace toml
+23
View File
@@ -0,0 +1,23 @@
Copyright (c) 2014, MAYAH
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-22
View File
@@ -1,22 +0,0 @@
MIT License
Copyright (c) 2024-2025, CK Tan
https://github.com/cktan/tomlc17
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-478
View File
@@ -1,478 +0,0 @@
/*
Author: xiaozhou233 (xiaozhou233@vip.qq.com)
File: juiceloader.c
Desc: JuiceLoader Native, Provide jni function for JuiceLoader
*/
#include <windows.h>
#include "log.h"
#include "juiceloader.h"
#include "javautils.h"
JuiceLoaderNativeType JuiceLoaderNative;
RetransformClassCacheType RetransformClassCache = {NULL, 0, 0};
static const char* g_bytecodes_classname = NULL;
static unsigned char* g_bytecodes = NULL;
static jint g_bytecodes_len = 0;
static void initLogger() {
log_set_level(LOG_TRACE);
log_is_log_time(false);
log_set_name("juiceloader");
log_info("Logger initialized.");
}
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) {
// ---- get class bytecode ---- //
if (g_bytecodes_classname != NULL && g_bytecodes == NULL) {
if (strcmp(name, g_bytecodes_classname) == 0) {
g_bytecodes_len = class_data_len;
g_bytecodes = (unsigned char*)malloc(class_data_len);
memcpy(g_bytecodes, classbytes, class_data_len);
*new_classbytes = NULL;
*new_class_data_len = 0;
log_trace("[Hook:get] Captured class bytes of %s, len=%d", name, class_data_len);
return;
}
}
// ---- get class bytecode ---- //
// ---- set class bytecode ---- //
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 = 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 ---- //
}
jint init_juiceloader(JNIEnv *env, jvmtiEnv *jvmti) {
log_info("[*] libjuiceloader Version %d.%d Build %d", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR, PROJECT_BUILD_NUMBER);
initLogger();
if (env == NULL) {
log_error("env is NULL! env=%p", env);
return JNI_ERR;
}
if (jvmti == NULL) {
log_error("jvmti is NULL! jvmti=%p", jvmti);
return JNI_ERR;
}
JuiceLoaderNative.jvmti = jvmti;
log_debug("[JuiceLoader] JuiceLoaderNative addr = %p", &JuiceLoaderNative);
log_debug("[JuiceLoader] JVMTI ptr = %p", JuiceLoaderNative.jvmti);
// Dynamic register jni functions
jclass clazz = (*env)->FindClass(env, "cn/xiaozhou233/juiceloader/JuiceLoader");
if (clazz == NULL) {
log_error("Cannot find JuiceLoader class!");
return JNI_ERR;
}
JNINativeMethod methods[] = {
// JuiceLoaderNative.init()
{"init", "()Z", (void *)&loader_init},
// JuiceLoaderNative.injectJar(String(jarPath));
{"injectJar", "(Ljava/lang/String;)Z", (void *)&loader_injectJar},
// JuiceLoaderNative.redefineClass(Class<?> clazz, byte[] classBytes, int length);
{"redefineClass", "(Ljava/lang/Class;[BI)Z", (void *)&loader_redefineClass_clazz},
// JuiceLoaderNative.redefineClassByName(String className, byte[] classBytes, int length);
{"redefineClassByName", "(Ljava/lang/String;[BI)Z", (void *)&loader_redefineClass_className},
// JuiceLoaderNative.getLoadedClasses();
{"getLoadedClasses", "()[Ljava/lang/Class;", (void *)&loader_getLoadedClasses},
// public static native byte[] getClassBytes(Class<?> clazz);
// public static native byte[] getClassBytesByName(String className);
{"getClassBytes", "(Ljava/lang/Class;)[B", (void *)&loader_getClassBytes},
{ "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]));
if (result != JNI_OK) {
log_error("Cannot register JNI methods for JuiceLoaderNative class! [result=%d]", result);
return JNI_ERR;
}
// Init RetransformClassCache
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;
result = (*JuiceLoaderNative.jvmti)->AddCapabilities(JuiceLoaderNative.jvmti, &caps);
if (result != JNI_OK) {
log_error("Cannot add JVMTI capabilities! [result=%d]", result);
return JNI_ERR;
}
// Register callbacks
jvmtiEventCallbacks callbacks;
memset(&callbacks, 0, sizeof(callbacks));
callbacks.ClassFileLoadHook = &ClassFileLoadHook;
(*jvmti)->SetEventCallbacks(jvmti, &callbacks, sizeof(callbacks));
// Enable events
(*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, NULL);
return JNI_OK;
}
/// ============ JNI Function ============ ///
// JuiceLoaderNative.init()
JNIEXPORT jboolean JNICALL loader_init(JNIEnv *env, jclass loader_class) {
// Deprcated
log_warn("JuiceLoaderNative.init() is deprecated, init will be done automatically.");
return JNI_TRUE;
}
// JuiceLoaderNative.injectJar(String)
JNIEXPORT jboolean JNICALL loader_injectJar(JNIEnv *env, jclass loader_class, jstring jarPath) {
log_info("injectJar Invoked!");
jboolean return_value = JNI_FALSE;
const char *pathStr = (*env)->GetStringUTFChars(env, jarPath, NULL);
if (pathStr == NULL) {
log_error("jar path is NULL!");
return_value = JNI_FALSE;
goto cleanup;
}
log_info("Injecting jar: %s", pathStr);
if (JuiceLoaderNative.jvmti == NULL) {
log_error("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
return_value = JNI_FALSE;
goto cleanup;
}
jvmtiError result = (*JuiceLoaderNative.jvmti)->AddToSystemClassLoaderSearch(JuiceLoaderNative.jvmti, pathStr);
if (result != JNI_OK) {
log_error("Cannot inject jar [result=%d]", result);
return_value = JNI_FALSE;
goto cleanup;
}
return_value = JNI_TRUE;
cleanup:
if (pathStr != NULL)
(*env)->ReleaseStringUTFChars(env, jarPath, pathStr);
return return_value;
}
// JuiceLoaderNative.redefineClass(Class, byte[], int)
JNIEXPORT jboolean JNICALL loader_redefineClass_clazz(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray classBytes, jint length) {
log_info("redefineClass_clazz Invoked!");
jboolean return_value = JNI_FALSE;
jbyte* buf = NULL;
if (JuiceLoaderNative.jvmti == NULL) {
log_error("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
return_value = JNI_FALSE;
goto cleanup;
}
log_info("Creating class definition...");
log_trace("class: %p", clazz);
log_trace("Class bytes length: %d", length);
buf = (*env)->GetByteArrayElements(env, classBytes, NULL);
if (buf == NULL) {
log_error("Cannot get class bytes");
return_value = JNI_FALSE;
goto cleanup;
}
jvmtiClassDefinition defs[1];
defs[0].klass = clazz;
defs[0].class_byte_count = length;
defs[0].class_bytes = (const unsigned char*) buf;
jvmtiError result = (*JuiceLoaderNative.jvmti)->RedefineClasses(JuiceLoaderNative.jvmti, 1, defs);
if (result != JVMTI_ERROR_NONE) {
log_error("Cannot redefine class [result=%d]", result);
return_value = JNI_FALSE;
goto cleanup;
}
return_value = JNI_TRUE;
log_info("Class redefined successfully!");
cleanup:
if (buf != NULL) {
(*env)->ReleaseByteArrayElements(env, classBytes, buf, JNI_ABORT);
}
return return_value;
}
JNIEXPORT jboolean JNICALL loader_redefineClass_className(JNIEnv *env, jclass loader_class, jstring className, jbyteArray classBytes, jint length) {
log_info("redefineClass_className Invoked!");
jboolean return_value = JNI_FALSE;
if (JuiceLoaderNative.jvmti == NULL) {
log_error("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
return_value = JNI_FALSE;
goto cleanup;
}
const char* cname = (*env)->GetStringUTFChars(env, className, NULL);
log_info("Finding class %s", cname);
if (cname == NULL) {
log_error("Class name is NULL!");
return_value = JNI_FALSE;
goto cleanup;
}
jclass clazz = (*env)->FindClass(env, cname);
if (clazz == NULL) {
log_error("Class not found! [ClassName=%s, clazz=%p]", cname, clazz);
return_value = JNI_FALSE;
goto cleanup;
}
return_value = loader_redefineClass_clazz(env, loader_class, clazz, classBytes, length);
cleanup:
if (cname != NULL) {
(*env)->ReleaseStringUTFChars(env, className, cname);
}
return return_value;
}
JNIEXPORT jobjectArray JNICALL loader_getLoadedClasses(JNIEnv *env, jclass loader_class) {
log_info("loader_getLoadedClasses invoked!");
if (JuiceLoaderNative.jvmti == NULL) {
log_error("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
return NULL;
}
// Debug
jvmtiPhase phase; (*JuiceLoaderNative.jvmti)->GetPhase(JuiceLoaderNative.jvmti, &phase);
log_debug("JVMTI Phase=%d [getLoadedClasses]", phase);
jint count = 0;
jclass* classes = NULL;
jvmtiError result = (*JuiceLoaderNative.jvmti)->GetLoadedClasses(JuiceLoaderNative.jvmti, &count, &classes);
if (result != JVMTI_ERROR_NONE || count == 0) {
(*JuiceLoaderNative.jvmti)->Deallocate(JuiceLoaderNative.jvmti, (unsigned char*)classes);
return (*env)->NewObjectArray(env, 0, (*env)->FindClass(env, "java/lang/Class"), NULL);
}
jclass classClass = (*env)->FindClass(env, "java/lang/Class");
jobjectArray classArray = (*env)->NewObjectArray(env, count, classClass, NULL);
for (int i = 0; i < count; i++) {
(*env)->SetObjectArrayElement(env, classArray, i, classes[i]);
}
if (classes != NULL) {
(*JuiceLoaderNative.jvmti)->Deallocate(JuiceLoaderNative.jvmti, (unsigned char*)classes);
}
return classArray;
}
JNIEXPORT jbyteArray JNICALL loader_getClassBytes(JNIEnv *env, jclass loader_class, jclass clazz) {
log_info("getClassBytes Invoked!");
if (JuiceLoaderNative.jvmti == NULL) {
log_error("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
return NULL;
}
char* className = get_class_name(env, clazz);
if (className == NULL) {
log_error("Failed to get class name!");
return NULL;
}
// JVM 内部使用路径名(. 替换为 /)
for (char* p = className; *p; p++) {
if (*p == '.') *p = '/';
}
g_bytecodes = NULL;
g_bytecodes_classname = className;
g_bytecodes_len = 0;
jclass classes[1] = { clazz };
jvmtiError err = (*JuiceLoaderNative.jvmti)->RetransformClasses(JuiceLoaderNative.jvmti, 1, classes);
if (err != JVMTI_ERROR_NONE) {
log_error("RetransformClasses failed: %d", err);
free((void*)className);
return NULL;
}
if (g_bytecodes != NULL) {
jbyteArray result = (*env)->NewByteArray(env, g_bytecodes_len);
(*env)->SetByteArrayRegion(env, result, 0, g_bytecodes_len, (jbyte*)g_bytecodes);
free((void*)g_bytecodes);
free((void*)className);
g_bytecodes = NULL;
g_bytecodes_classname = NULL;
g_bytecodes_len = 0;
return result;
}
log_warn("No bytecode captured for class: %s", className);
free((void*)className);
return NULL;
}
JNIEXPORT jbyteArray JNICALL loader_getClassBytesByName(JNIEnv *env, jclass loader_class, jstring className) {
log_info("getClassBytesByName Invoked!");
if (JuiceLoaderNative.jvmti == NULL) {
log_error("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
return NULL;
}
const char* cname = (*env)->GetStringUTFChars(env, className, NULL);
jclass clazz = (*env)->FindClass(env, cname);
(*env)->ReleaseStringUTFChars(env, className, cname);
if (clazz == NULL) {
log_error("Failed to find class %s", cname);
return NULL;
}
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;
}
-242
View File
@@ -1,242 +0,0 @@
/*
Author: xiaozhou233 (xiaozhou233@vip.qq.com)
File: libagent.c
Desc: Entry point for the agent
*/
#include "ReflectiveLoader.h"
#include "windows.h"
#include "unistd.h"
#include "stdio.h"
#include "jni.h"
#include "jvmti.h"
#include "InjectParameters.h"
#include "log.h"
#include "jvmutils.h"
#include "shlwapi.h"
#include "tomlc17.h"
#include "datautils.h"
#include "juiceloader.h"
#define WIN_X64
extern HINSTANCE hAppInstance;
InjectionInfoType InjectionInfo;
struct _JuiceAgent {
bool isAttached;
JavaVM *jvm;
jvmtiEnv *jvmti;
} JuiceAgent = {false, NULL, NULL};
static void initLogger() {
log_set_level(LOG_TRACE);
log_is_log_time(false);
log_set_name("libagent");
log_info("Logger initialized.");
}
DWORD WINAPI ThreadProc(LPVOID lpParam) {
log_trace("New thread started.");
memset(&InjectionInfo, 0, sizeof(InjectionInfo));
/// ======== Check Environment ======== ///
InjectParameters *param = (InjectParameters*)lpParam;
if (!param) {
log_error("ThreadProc got NULL param");
return 1;
}
if (!param->ConfigDir || param->ConfigDir[0] == '\0') {
log_error("ThreadProc got NULL or empty ConfigPath");
return 1;
}
char ConfigPath[INJECT_PATH_MAX];
snprintf(ConfigPath, sizeof(ConfigPath), "%s\\AgentConfig.toml", param->ConfigDir);
toml_result_t toml_result = toml_parse_file_ex(ConfigPath);
if (!toml_result.ok) {
log_error("ThreadProc failed to parse config file: %s", toml_result.errmsg);
return 1;
}
if (!ReadInjectionInfo(toml_result, param)) {
log_error("Failed to read injection info");
return 1;
}
toml_free(toml_result);
// Check JuiceLoader.jar
log_trace("Checking JuiceLoader.jar");
if (GetFileAttributesA(InjectionInfo.JuiceLoaderJarPath) == INVALID_FILE_ATTRIBUTES) {
log_error("JuiceLoader.jar not found: %s", InjectionInfo.JuiceLoaderJarPath);
// MessageBoxA(NULL, "JuiceLoader.jar not found", "Error", MB_OK);
return 1;
}
/// ======== Check Environment ======== ///
// Init vars
jint result = JNI_ERR;
JavaVM *jvm = NULL;
JNIEnv *env = NULL;
jvmtiEnv *jvmti = NULL;
result = GetCreatedJVM(&jvm);
if (result != JNI_OK) {
log_error("Failed to get JVM (%d)", result);
MessageBoxA(NULL, "Failed to get JVM", "Error", MB_OK);
return 1;
}
log_info("Got JVM");
result = GetJNIEnv(jvm, &env);
if (result != JNI_OK) {
log_error("Failed to get JNIEnv (%d)", result);
// MessageBoxA(NULL, "Failed to get JNIEnv", "Error", MB_OK);
log_error("Maybe the JVM havent been init yet.");
JuiceAgent.isAttached = false;
return 1;
}
log_info("Got JNIEnv");
// Debug: JVM version
jint version = (*env)->GetVersion(env);
log_trace("JVM version: 0x%x", version);
// Init and enable jvmti
result = GetJVMTI(jvm, &jvmti);
if (result != JNI_OK) {
log_error("Failed to get JVMTI (%d)", result);
// MessageBoxA(NULL, "Failed to get JVMTI", "Error", MB_OK);
return 1;
}
log_info("Enabled jvmti");
// Inject jars
log_info("injecting loader jar...");
(*jvmti)->AddToSystemClassLoaderSearch(jvmti, InjectionInfo.JuiceLoaderJarPath);
log_info("injected loader jar");
// init juiceloader
log_info("init juice loader...");
init_juiceloader(env, jvmti);
initLogger();
log_info("juice loader init done");
log_info("invoking loader init()...");
log_info("============ Loader Info ============\n");
jclass cls = (*env)->FindClass(env, "cn/xiaozhou233/juiceloader/JuiceLoaderBootstrap");
if (cls == NULL) {
log_error("FindClass JuiceLoaderBootstrap failed");
return 1;
}
jmethodID mid = (*env)->GetStaticMethodID(env, cls, "init", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
if (mid == NULL) {
log_error("GetStaticMethodID init failed");
if ((*env)->ExceptionCheck(env)) {
(*env)->ExceptionDescribe(env);
(*env)->ExceptionClear(env);
}
return 1;
}
(*env)->CallStaticVoidMethod(env, cls, mid,
(*env)->NewStringUTF(env, InjectionInfo.EntryJarPath),
(*env)->NewStringUTF(env, InjectionInfo.EntryClass),
(*env)->NewStringUTF(env, InjectionInfo.EntryMethod),
(*env)->NewStringUTF(env, InjectionInfo.InjectionDir));
log_info("============ Loader Info =============\n");
log_info("invoked. ");
log_info("done. cleaning up...");
// :(
// (*jvm)->DetachCurrentThread(jvm);
free(param);
log_info("exit.");
return 0;
}
/// =========================================================== ///
/// Function: DllMain
/// Description: DLL Injection Entry Point
/// Inject Method: A) ReflectiveDLLInjection B) LoadLibraryA+CreateRemoteThread
/// =========================================================== ///
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpReserved){
BOOL bReturnValue = TRUE;
switch (dwReason){
case DLL_QUERY_HMODULE:
if (lpReserved != NULL)
*(HMODULE *)lpReserved = hAppInstance;
break;
case DLL_PROCESS_ATTACH:
hAppInstance = hinstDLL;
// Initialize log
initLogger();
log_info("DLL_PROCESS_ATTACH");
log_info("[*] JuiceAgent Version %d.%d Build %d", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR, PROJECT_BUILD_NUMBER);
DisableThreadLibraryCalls(hinstDLL);
// Allocate memory for local param
InjectParameters *localParm = (InjectParameters*)malloc(sizeof(InjectParameters));
if (localParm == NULL) {
log_error("malloc failed for InjectParameters");
break;
}
memset(localParm, 0, sizeof(InjectParameters));
// Check if lpReserved is not NULL
if (lpReserved != NULL) {
// Copy remote param to local param
InjectParameters *remoteParm = (InjectParameters*)lpReserved;
safe_copy(localParm->ConfigDir, remoteParm->ConfigDir, sizeof(localParm->ConfigDir));
} else {
log_info("RemoteParm is NULL!");
char DllDir[INJECT_PATH_MAX] = {0};
if (GetModuleFileNameA(hinstDLL, 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);
}
break;
} else {
// Normal Inject(e.g. CreateRemoteThread+LoadLibraryA), lpReserved can be NULL.
PathRemoveFileSpecA(DllDir);
log_info("GetModuleFileNameA: %s", DllDir);
safe_copy(localParm->ConfigDir, DllDir, INJECT_PATH_MAX);
}
}
log_info("ConfigDir: %s", localParm->ConfigDir);
HANDLE hThread = CreateThread(NULL, 0, ThreadProc, localParm, 0, NULL);
if (hThread) {
CloseHandle(hThread);
} else {
log_error("CreateThread failed %lu", GetLastError());
free(localParm);
}
break;
case DLL_PROCESS_DETACH:
log_info("DLL_PROCESS_DETACH");
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
break;
}
return bReturnValue;
}