mirror of
https://github.com/xiaozhou233/JuiceAgent.git
synced 2026-12-05 21:15:56 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63c9e55355 | ||
|
|
7f9e381bc3 | ||
|
|
e2a3119af6 | ||
|
|
681a86cb36 | ||
|
|
353fe3e5a5 | ||
|
|
ffaa234bbf | ||
|
|
76055183d2 | ||
|
|
80713ace68 | ||
|
|
01caa4c8cb | ||
|
|
07a71eab12 | ||
|
|
ad827fabff | ||
|
|
ebc557c2f2 | ||
|
|
c4bbbabe07 | ||
|
|
4c184cbb95 | ||
|
|
ffd42c5e30 | ||
|
|
6628b5bfd5 | ||
|
|
56cd994715 | ||
|
|
e3481d007c | ||
|
|
386dc14a01 | ||
|
|
c8c255b233 | ||
|
|
094e7bc0d4 | ||
|
|
acf2cd2c1d | ||
|
|
bd2e9ca730 | ||
|
|
7039e0f914 | ||
|
|
25153d2062 | ||
|
|
eefee5d04d | ||
|
|
df6bc29360 | ||
|
|
9f2782a126 | ||
|
|
21df0346db | ||
|
|
73910150b2 | ||
|
|
8e8f08c986 | ||
|
|
01b437cd9f | ||
|
|
1ea23faab9 | ||
|
|
8966125ad9 | ||
|
|
de971d6481 | ||
|
|
ee97c10702 | ||
|
|
87a1701f22 | ||
|
|
e265e39be9 | ||
|
|
34323a68fe | ||
|
|
39fad40655 | ||
|
|
bf5a6b0804 | ||
|
|
30d379521a | ||
|
|
fe495657d4 | ||
|
|
40707231c0 | ||
|
|
3dc83d83db | ||
|
|
9bb9faacdf | ||
|
|
7cdd3e4b11 | ||
|
|
a44f2d9753 | ||
|
|
7c3f1c302e | ||
|
|
f311b51b43 | ||
|
|
8fd8432032 | ||
|
|
6113ea47c2 | ||
|
|
c5e6f3e180 | ||
|
|
f3c2b7d0e6 | ||
|
|
c642280142 | ||
|
|
390f2c2241 | ||
|
|
8563e2b447 | ||
|
|
8e42780eed | ||
|
|
b46802faaa | ||
|
|
96fee27476 | ||
|
|
09eca1b802 | ||
|
|
0bb717b935 | ||
|
|
88e8835f8a | ||
|
|
f317ea3e8d | ||
|
|
8b2ab3e588 |
No files matched your search
@@ -1,7 +0,0 @@
|
|||||||
[Injection]
|
|
||||||
BootstrapAPIPath = "D:/Development/JuiceLoader/build/libs/bootstrap-api.jar"
|
|
||||||
JuiceLoaderJarPath = "D:/Development/JuiceLoader/build/libs/JuiceLoader.jar"
|
|
||||||
JuiceLoaderLibPath = ""
|
|
||||||
EntryJarPath = "D:/Development/JuiceLoader/build/libs/Entry.jar"
|
|
||||||
EntryClass = "cn.xiaozhou233.juiceloader.entry.Entry"
|
|
||||||
EntryMethod = "start"
|
|
||||||
+6
-24
@@ -4,36 +4,18 @@ project(JuiceAgent LANGUAGES C CXX)
|
|||||||
set(CMAKE_CXX_STANDARD 17)
|
set(CMAKE_CXX_STANDARD 17)
|
||||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||||
|
|
||||||
# version
|
|
||||||
set(PROJECT_VERSION_MAJOR 1)
|
|
||||||
set(PROJECT_VERSION_MINOR 1)
|
|
||||||
set(PROJECT_BUILD_NUMBER 25)
|
|
||||||
set(PROJECT_VERSION_STRING "v${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}-b${PROJECT_BUILD_NUMBER}")
|
|
||||||
message(STATUS " ======== Build version: ${PROJECT_VERSION_STRING} ======== ")
|
|
||||||
|
|
||||||
add_compile_definitions(
|
|
||||||
PROJECT_VERSION_MAJOR=${PROJECT_VERSION_MAJOR}
|
|
||||||
PROJECT_VERSION_MINOR=${PROJECT_VERSION_MINOR}
|
|
||||||
PROJECT_BUILD_NUMBER=${PROJECT_BUILD_NUMBER}
|
|
||||||
PROJECT_VERSION_STRING=\"${PROJECT_VERSION_STRING}\")
|
|
||||||
|
|
||||||
# output directories
|
# output directories
|
||||||
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
||||||
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
||||||
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||||
|
|
||||||
# includes
|
set(SRC_DIR ${CMAKE_SOURCE_DIR}/src)
|
||||||
set(INCLUDES ${CMAKE_CURRENT_SOURCE_DIR}/includes)
|
link_directories("$ENV{JAVA_HOME}/lib")
|
||||||
|
|
||||||
# libraries
|
# libraries
|
||||||
add_subdirectory(${INCLUDES}/ReflectiveDLLInjection)
|
add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection)
|
||||||
add_subdirectory(${INCLUDES}/log.c)
|
|
||||||
add_subdirectory(${INCLUDES}/tomlc17)
|
|
||||||
add_subdirectory(src/utils)
|
|
||||||
|
|
||||||
include(cmake/JuiceModule.cmake)
|
|
||||||
|
|
||||||
# modules
|
# modules
|
||||||
add_juice_module(agent)
|
add_subdirectory(${SRC_DIR}/libagent)
|
||||||
add_juice_module(juiceloader)
|
add_subdirectory(${SRC_DIR}/libinjector)
|
||||||
add_juice_module(injector)
|
add_subdirectory(${SRC_DIR}/libjuiceloader)
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
# JuiceModule.cmake
|
|
||||||
# Function to add a JuiceAgent module (agent, injector, juiceloader)
|
|
||||||
|
|
||||||
function(add_juice_module NAME)
|
|
||||||
link_directories("$ENV{JAVA_HOME}/lib")
|
|
||||||
|
|
||||||
# Collect all source files in module src and utils
|
|
||||||
file(GLOB MODULE_SOURCES
|
|
||||||
"${CMAKE_SOURCE_DIR}/src/${NAME}/*.c"
|
|
||||||
"${CMAKE_SOURCE_DIR}/src/${NAME}/utils/*.c"
|
|
||||||
)
|
|
||||||
|
|
||||||
# Create shared library
|
|
||||||
add_library(${NAME} SHARED ${MODULE_SOURCES})
|
|
||||||
|
|
||||||
# Include directories
|
|
||||||
target_include_directories(${NAME} PRIVATE
|
|
||||||
${CMAKE_SOURCE_DIR}/includes
|
|
||||||
${CMAKE_SOURCE_DIR}/includes/jvm
|
|
||||||
${CMAKE_SOURCE_DIR}/includes/jvm/win32
|
|
||||||
${CMAKE_SOURCE_DIR}/includes/JuiceAgent
|
|
||||||
${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection
|
|
||||||
${CMAKE_SOURCE_DIR}/includes/log.c
|
|
||||||
"${CMAKE_SOURCE_DIR}/src/${NAME}/utils"
|
|
||||||
"${CMAKE_SOURCE_DIR}/src/${NAME}/include"
|
|
||||||
"${CMAKE_SOURCE_DIR}/src/utils"
|
|
||||||
)
|
|
||||||
|
|
||||||
# Link common libraries
|
|
||||||
target_link_libraries(${NAME} PRIVATE
|
|
||||||
ReflectiveDLLInjection
|
|
||||||
log.c
|
|
||||||
jvm
|
|
||||||
utils
|
|
||||||
)
|
|
||||||
|
|
||||||
add_subdirectory("${CMAKE_SOURCE_DIR}/src/${NAME}")
|
|
||||||
endfunction()
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
#ifndef INJECTPARAMETERS_H
|
|
||||||
#define INJECTPARAMETERS_H
|
|
||||||
|
|
||||||
#include <windows.h>
|
|
||||||
|
|
||||||
#define INJECT_PATH_MAX 4096
|
|
||||||
|
|
||||||
typedef struct InjectParameters{
|
|
||||||
char ConfigDir[INJECT_PATH_MAX];
|
|
||||||
} InjectParameters;
|
|
||||||
|
|
||||||
#endif
|
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
#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,17 @@
|
|||||||
|
// Logger.hpp
|
||||||
|
#pragma once
|
||||||
|
#include <plog/Log.h>
|
||||||
|
#include <plog/Init.h>
|
||||||
|
#include <plog/Formatters/TxtFormatter.h>
|
||||||
|
#include <plog/Appenders/ConsoleAppender.h>
|
||||||
|
#include <plog/Appenders/DebugOutputAppender.h>
|
||||||
|
|
||||||
|
inline void InitLogger()
|
||||||
|
{
|
||||||
|
static plog::ConsoleAppender<plog::TxtFormatter> consoleAppender;
|
||||||
|
static plog::DebugOutputAppender<plog::TxtFormatter> debugAppender;
|
||||||
|
|
||||||
|
plog::init(plog::debug, &consoleAppender).addAppender(&debugAppender);
|
||||||
|
|
||||||
|
PLOG_INFO << "Logger initialized: Console + Debug Output";
|
||||||
|
}
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
add_library(log.c STATIC
|
|
||||||
log.c
|
|
||||||
)
|
|
||||||
|
|
||||||
target_include_directories(log.c PUBLIC
|
|
||||||
${CMAKE_CURRENT_SOURCE_DIR}
|
|
||||||
)
|
|
||||||
|
|
||||||
target_compile_definitions(log.c PRIVATE LOG_USE_COLOR)
|
|
||||||
@@ -1,241 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright (c) 2020 rxi
|
|
||||||
*
|
|
||||||
* 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.
|
|
||||||
*/
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Modified by xiaozhou233 (2025), based on work by rxi (MIT License).
|
|
||||||
* - Add log setting
|
|
||||||
* - log time switch
|
|
||||||
* - log level switch
|
|
||||||
* - log filename switch
|
|
||||||
* - log line number switch
|
|
||||||
* - log name prefix
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include "log.h"
|
|
||||||
|
|
||||||
#define MAX_CALLBACKS 32
|
|
||||||
|
|
||||||
typedef struct {
|
|
||||||
log_LogFn fn;
|
|
||||||
void *udata;
|
|
||||||
int level;
|
|
||||||
} Callback;
|
|
||||||
|
|
||||||
static struct {
|
|
||||||
void *udata;
|
|
||||||
log_LockFn lock;
|
|
||||||
int level;
|
|
||||||
bool quiet;
|
|
||||||
Callback callbacks[MAX_CALLBACKS];
|
|
||||||
|
|
||||||
bool is_log_time;
|
|
||||||
bool is_log_level;
|
|
||||||
bool is_log_filename;
|
|
||||||
bool is_log_line;
|
|
||||||
|
|
||||||
const char *logname;
|
|
||||||
} L = {
|
|
||||||
.is_log_time = true,
|
|
||||||
.is_log_level = true,
|
|
||||||
.is_log_filename = false,
|
|
||||||
.is_log_line = false,
|
|
||||||
.logname = NULL
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
static const char *level_strings[] = {
|
|
||||||
"TRACE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL"
|
|
||||||
};
|
|
||||||
|
|
||||||
#ifdef LOG_USE_COLOR
|
|
||||||
static const char *level_colors[] = {
|
|
||||||
"\x1b[94m", "\x1b[36m", "\x1b[32m", "\x1b[33m", "\x1b[31m", "\x1b[35m"
|
|
||||||
};
|
|
||||||
#endif
|
|
||||||
|
|
||||||
|
|
||||||
static void stdout_callback(log_Event *ev) {
|
|
||||||
char buf[64] = {0};
|
|
||||||
|
|
||||||
if (L.is_log_time) {
|
|
||||||
strftime(buf, sizeof(buf), "%H:%M:%S", ev->time);
|
|
||||||
}
|
|
||||||
|
|
||||||
#ifdef LOG_USE_COLOR
|
|
||||||
fprintf(ev->udata, "%s", LOG_USE_COLOR ? level_colors[ev->level] : "");
|
|
||||||
|
|
||||||
if (L.is_log_time)
|
|
||||||
fprintf(ev->udata, "%s ", buf);
|
|
||||||
|
|
||||||
if (L.is_log_level)
|
|
||||||
fprintf(ev->udata, "%-5s ", level_strings[ev->level]);
|
|
||||||
|
|
||||||
fprintf(ev->udata, "\x1b[0m");
|
|
||||||
|
|
||||||
if (L.is_log_filename)
|
|
||||||
fprintf(ev->udata, "\x1b[90m%s", ev->file);
|
|
||||||
|
|
||||||
if (L.is_log_line)
|
|
||||||
fprintf(ev->udata, ":%d", ev->line);
|
|
||||||
|
|
||||||
if (L.is_log_filename || L.is_log_line)
|
|
||||||
fprintf(ev->udata, ":\x1b[0m ");
|
|
||||||
#else
|
|
||||||
if (L.is_log_time)
|
|
||||||
fprintf(ev->udata, "%s ", buf);
|
|
||||||
|
|
||||||
if (L.is_log_level)
|
|
||||||
fprintf(ev->udata, "%-5s ", level_strings[ev->level]);
|
|
||||||
|
|
||||||
if (L.is_log_filename)
|
|
||||||
fprintf(ev->udata, "%s", ev->file);
|
|
||||||
|
|
||||||
if (L.is_log_line)
|
|
||||||
fprintf(ev->udata, ":%d", ev->line);
|
|
||||||
|
|
||||||
if (L.is_log_filename || L.is_log_line)
|
|
||||||
fprintf(ev->udata, ": ");
|
|
||||||
#endif
|
|
||||||
|
|
||||||
if (L.logname) fprintf(ev->udata, "[%s] ", L.logname);
|
|
||||||
|
|
||||||
vfprintf(ev->udata, ev->fmt, ev->ap);
|
|
||||||
fprintf(ev->udata, "\n");
|
|
||||||
fflush(ev->udata);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
static void file_callback(log_Event *ev) {
|
|
||||||
char buf[64];
|
|
||||||
buf[strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", ev->time)] = '\0';
|
|
||||||
fprintf(ev->udata, "%s %-5s ", buf, level_strings[ev->level]);
|
|
||||||
fprintf(ev->udata, "%s:%d: ", ev->file, ev->line);
|
|
||||||
if (L.logname) fprintf(ev->udata, "[%s] ", L.logname);
|
|
||||||
vfprintf(ev->udata, ev->fmt, ev->ap);
|
|
||||||
fprintf(ev->udata, "\n");
|
|
||||||
fflush(ev->udata);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
static void lock(void) {
|
|
||||||
if (L.lock) { L.lock(true, L.udata); }
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
static void unlock(void) {
|
|
||||||
if (L.lock) { L.lock(false, L.udata); }
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
const char* log_level_string(int level) {
|
|
||||||
return level_strings[level];
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
void log_set_lock(log_LockFn fn, void *udata) {
|
|
||||||
L.lock = fn;
|
|
||||||
L.udata = udata;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
void log_set_level(int level) {
|
|
||||||
L.level = level;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
void log_set_quiet(bool enable) {
|
|
||||||
L.quiet = enable;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
int log_add_callback(log_LogFn fn, void *udata, int level) {
|
|
||||||
for (int i = 0; i < MAX_CALLBACKS; i++) {
|
|
||||||
if (!L.callbacks[i].fn) {
|
|
||||||
L.callbacks[i] = (Callback) { fn, udata, level };
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
int log_add_fp(FILE *fp, int level) {
|
|
||||||
return log_add_callback(file_callback, fp, level);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
static void init_event(log_Event *ev, void *udata) {
|
|
||||||
if (!ev->time) {
|
|
||||||
time_t t = time(NULL);
|
|
||||||
ev->time = localtime(&t);
|
|
||||||
}
|
|
||||||
ev->udata = udata;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
void log_log(int level, const char *file, int line, const char *fmt, ...) {
|
|
||||||
|
|
||||||
log_Event ev = {
|
|
||||||
.fmt = fmt,
|
|
||||||
.file = file,
|
|
||||||
.line = line,
|
|
||||||
.level = level,
|
|
||||||
};
|
|
||||||
|
|
||||||
lock();
|
|
||||||
|
|
||||||
if (!L.quiet && level >= L.level) {
|
|
||||||
init_event(&ev, stderr);
|
|
||||||
va_start(ev.ap, fmt);
|
|
||||||
stdout_callback(&ev);
|
|
||||||
va_end(ev.ap);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (int i = 0; i < MAX_CALLBACKS && L.callbacks[i].fn; i++) {
|
|
||||||
Callback *cb = &L.callbacks[i];
|
|
||||||
if (level >= cb->level) {
|
|
||||||
init_event(&ev, cb->udata);
|
|
||||||
va_start(ev.ap, fmt);
|
|
||||||
cb->fn(&ev);
|
|
||||||
va_end(ev.ap);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
unlock();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
void log_is_log_time(bool enable) {
|
|
||||||
L.is_log_time = enable;
|
|
||||||
}
|
|
||||||
void log_is_log_level(bool enable) {
|
|
||||||
L.is_log_level = enable;
|
|
||||||
}
|
|
||||||
void log_is_log_filename(bool enable) {
|
|
||||||
L.is_log_filename = enable;
|
|
||||||
}
|
|
||||||
void log_is_log_line(bool enable) {
|
|
||||||
L.is_log_line = enable;
|
|
||||||
}
|
|
||||||
void log_set_name(const char *name) {
|
|
||||||
L.logname = name;
|
|
||||||
}
|
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
/**
|
|
||||||
* Copyright (c) 2020 rxi
|
|
||||||
*
|
|
||||||
* This library is free software; you can redistribute it and/or modify it
|
|
||||||
* under the terms of the MIT license. See `log.c` for details.
|
|
||||||
*/
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Modified by xiaozhou233 (2025), based on work by rxi (MIT License).
|
|
||||||
* See `log.c` for details.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#ifndef LOG_H
|
|
||||||
#define LOG_H
|
|
||||||
|
|
||||||
#include <stdio.h>
|
|
||||||
#include <stdarg.h>
|
|
||||||
#include <stdbool.h>
|
|
||||||
#include <time.h>
|
|
||||||
|
|
||||||
#define LOG_VERSION "0.1.0"
|
|
||||||
|
|
||||||
typedef struct {
|
|
||||||
va_list ap;
|
|
||||||
const char *fmt;
|
|
||||||
const char *file;
|
|
||||||
struct tm *time;
|
|
||||||
void *udata;
|
|
||||||
int line;
|
|
||||||
int level;
|
|
||||||
} log_Event;
|
|
||||||
|
|
||||||
typedef void (*log_LogFn)(log_Event *ev);
|
|
||||||
typedef void (*log_LockFn)(bool lock, void *udata);
|
|
||||||
|
|
||||||
enum { LOG_TRACE, LOG_DEBUG, LOG_INFO, LOG_WARN, LOG_ERROR, LOG_FATAL };
|
|
||||||
|
|
||||||
#define log_trace(...) log_log(LOG_TRACE, __FILE__, __LINE__, __VA_ARGS__)
|
|
||||||
#define log_debug(...) log_log(LOG_DEBUG, __FILE__, __LINE__, __VA_ARGS__)
|
|
||||||
#define log_info(...) log_log(LOG_INFO, __FILE__, __LINE__, __VA_ARGS__)
|
|
||||||
#define log_warn(...) log_log(LOG_WARN, __FILE__, __LINE__, __VA_ARGS__)
|
|
||||||
#define log_error(...) log_log(LOG_ERROR, __FILE__, __LINE__, __VA_ARGS__)
|
|
||||||
#define log_fatal(...) log_log(LOG_FATAL, __FILE__, __LINE__, __VA_ARGS__)
|
|
||||||
|
|
||||||
const char* log_level_string(int level);
|
|
||||||
void log_set_lock(log_LockFn fn, void *udata);
|
|
||||||
void log_set_level(int level);
|
|
||||||
void log_set_quiet(bool enable);
|
|
||||||
int log_add_callback(log_LogFn fn, void *udata, int level);
|
|
||||||
int log_add_fp(FILE *fp, int level);
|
|
||||||
|
|
||||||
// Add custom log formatting function
|
|
||||||
void log_is_log_time(bool enable);
|
|
||||||
void log_is_log_level(bool enable);
|
|
||||||
void log_is_log_filename(bool enable);
|
|
||||||
void log_is_log_line(bool enable);
|
|
||||||
void log_set_name(const char *name);
|
|
||||||
|
|
||||||
void log_log(int level, const char *file, int line, const char *fmt, ...);
|
|
||||||
|
|
||||||
#endif
|
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <plog/Appenders/IAppender.h>
|
||||||
|
#include <android/log.h>
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
template<class Formatter>
|
||||||
|
class PLOG_LINKAGE_HIDDEN AndroidAppender : public IAppender
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
AndroidAppender(const char* tag) : m_tag(tag)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
virtual void write(const Record& record) PLOG_OVERRIDE
|
||||||
|
{
|
||||||
|
std::string str = Formatter::format(record);
|
||||||
|
|
||||||
|
__android_log_print(toPriority(record.getSeverity()), m_tag, "%s", str.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
static android_LogPriority toPriority(Severity severity)
|
||||||
|
{
|
||||||
|
switch (severity)
|
||||||
|
{
|
||||||
|
case fatal:
|
||||||
|
return ANDROID_LOG_FATAL;
|
||||||
|
case error:
|
||||||
|
return ANDROID_LOG_ERROR;
|
||||||
|
case warning:
|
||||||
|
return ANDROID_LOG_WARN;
|
||||||
|
case info:
|
||||||
|
return ANDROID_LOG_INFO;
|
||||||
|
case debug:
|
||||||
|
return ANDROID_LOG_DEBUG;
|
||||||
|
case verbose:
|
||||||
|
return ANDROID_LOG_VERBOSE;
|
||||||
|
default:
|
||||||
|
return ANDROID_LOG_UNKNOWN;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
const char* const m_tag;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <plog/Appenders/IAppender.h>
|
||||||
|
#include <Arduino.h>
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
template<class Formatter>
|
||||||
|
class PLOG_LINKAGE_HIDDEN ArduinoAppender : public IAppender
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
ArduinoAppender(Stream &stream) : m_stream(stream)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
virtual void write(const Record &record) PLOG_OVERRIDE
|
||||||
|
{
|
||||||
|
m_stream.print(Formatter::format(record).c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
Stream &m_stream;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <plog/Appenders/ConsoleAppender.h>
|
||||||
|
#include <plog/WinApi.h>
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
template<class Formatter>
|
||||||
|
class PLOG_LINKAGE_HIDDEN ColorConsoleAppender : public ConsoleAppender<Formatter>
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
#ifdef _WIN32
|
||||||
|
# ifdef _MSC_VER
|
||||||
|
# pragma warning(suppress: 26812) // Prefer 'enum class' over 'enum'
|
||||||
|
# endif
|
||||||
|
ColorConsoleAppender(OutputStream outStream = streamStdOut)
|
||||||
|
: ConsoleAppender<Formatter>(outStream)
|
||||||
|
, m_originalAttr()
|
||||||
|
{
|
||||||
|
if (this->m_isatty)
|
||||||
|
{
|
||||||
|
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
|
||||||
|
GetConsoleScreenBufferInfo(this->m_outputHandle, &csbiInfo);
|
||||||
|
|
||||||
|
m_originalAttr = csbiInfo.wAttributes;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
ColorConsoleAppender(OutputStream outStream = streamStdOut)
|
||||||
|
: ConsoleAppender<Formatter>(outStream)
|
||||||
|
{}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
virtual void write(const Record& record) PLOG_OVERRIDE
|
||||||
|
{
|
||||||
|
util::nstring str = Formatter::format(record);
|
||||||
|
util::MutexLock lock(this->m_mutex);
|
||||||
|
|
||||||
|
setColor(record.getSeverity());
|
||||||
|
this->writestr(str);
|
||||||
|
resetColor();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected:
|
||||||
|
void setColor(Severity severity)
|
||||||
|
{
|
||||||
|
if (this->m_isatty)
|
||||||
|
{
|
||||||
|
switch (severity)
|
||||||
|
{
|
||||||
|
#ifdef _WIN32
|
||||||
|
case fatal:
|
||||||
|
SetConsoleTextAttribute(this->m_outputHandle, foreground::kRed | foreground::kGreen | foreground::kBlue | foreground::kIntensity | background::kRed); // white on red background
|
||||||
|
break;
|
||||||
|
|
||||||
|
case error:
|
||||||
|
SetConsoleTextAttribute(this->m_outputHandle, static_cast<WORD>(foreground::kRed | foreground::kIntensity | (m_originalAttr & 0xf0))); // red
|
||||||
|
break;
|
||||||
|
|
||||||
|
case warning:
|
||||||
|
SetConsoleTextAttribute(this->m_outputHandle, static_cast<WORD>(foreground::kRed | foreground::kGreen | foreground::kIntensity | (m_originalAttr & 0xf0))); // yellow
|
||||||
|
break;
|
||||||
|
|
||||||
|
case debug:
|
||||||
|
case verbose:
|
||||||
|
SetConsoleTextAttribute(this->m_outputHandle, static_cast<WORD>(foreground::kGreen | foreground::kBlue | foreground::kIntensity | (m_originalAttr & 0xf0))); // cyan
|
||||||
|
break;
|
||||||
|
#else
|
||||||
|
case fatal:
|
||||||
|
this->m_outputStream << "\x1B[97m\x1B[41m"; // white on red background
|
||||||
|
break;
|
||||||
|
|
||||||
|
case error:
|
||||||
|
this->m_outputStream << "\x1B[91m"; // red
|
||||||
|
break;
|
||||||
|
|
||||||
|
case warning:
|
||||||
|
this->m_outputStream << "\x1B[93m"; // yellow
|
||||||
|
break;
|
||||||
|
|
||||||
|
case debug:
|
||||||
|
case verbose:
|
||||||
|
this->m_outputStream << "\x1B[96m"; // cyan
|
||||||
|
break;
|
||||||
|
#endif
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void resetColor()
|
||||||
|
{
|
||||||
|
if (this->m_isatty)
|
||||||
|
{
|
||||||
|
#ifdef _WIN32
|
||||||
|
SetConsoleTextAttribute(this->m_outputHandle, m_originalAttr);
|
||||||
|
#else
|
||||||
|
this->m_outputStream << "\x1B[0m\x1B[0K";
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
#ifdef _WIN32
|
||||||
|
WORD m_originalAttr;
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <plog/Appenders/IAppender.h>
|
||||||
|
#include <plog/Util.h>
|
||||||
|
#include <plog/WinApi.h>
|
||||||
|
#include <iostream>
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
enum OutputStream
|
||||||
|
{
|
||||||
|
streamStdOut,
|
||||||
|
streamStdErr
|
||||||
|
};
|
||||||
|
|
||||||
|
template<class Formatter>
|
||||||
|
class PLOG_LINKAGE_HIDDEN ConsoleAppender : public IAppender
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
#ifdef _WIN32
|
||||||
|
# ifdef _MSC_VER
|
||||||
|
# pragma warning(suppress: 26812) // Prefer 'enum class' over 'enum'
|
||||||
|
# endif
|
||||||
|
ConsoleAppender(OutputStream outStream = streamStdOut)
|
||||||
|
: m_isatty(!!_isatty(_fileno(outStream == streamStdOut ? stdout : stderr)))
|
||||||
|
, m_outputStream(outStream == streamStdOut ? std::cout : std::cerr)
|
||||||
|
, m_outputHandle()
|
||||||
|
{
|
||||||
|
if (m_isatty)
|
||||||
|
{
|
||||||
|
m_outputHandle = GetStdHandle(outStream == streamStdOut ? stdHandle::kOutput : stdHandle::kErrorOutput);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
ConsoleAppender(OutputStream outStream = streamStdOut)
|
||||||
|
: m_isatty(!!isatty(fileno(outStream == streamStdOut ? stdout : stderr)))
|
||||||
|
, m_outputStream(outStream == streamStdOut ? std::cout : std::cerr)
|
||||||
|
{}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
virtual void write(const Record& record) PLOG_OVERRIDE
|
||||||
|
{
|
||||||
|
util::nstring str = Formatter::format(record);
|
||||||
|
util::MutexLock lock(m_mutex);
|
||||||
|
|
||||||
|
writestr(str);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected:
|
||||||
|
void writestr(const util::nstring& str)
|
||||||
|
{
|
||||||
|
#ifdef _WIN32
|
||||||
|
if (m_isatty)
|
||||||
|
{
|
||||||
|
const std::wstring& wstr = util::toWide(str);
|
||||||
|
WriteConsoleW(m_outputHandle, wstr.c_str(), static_cast<DWORD>(wstr.size()), NULL, NULL);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
# if PLOG_CHAR_IS_UTF8
|
||||||
|
m_outputStream << str << std::flush;
|
||||||
|
# else
|
||||||
|
m_outputStream << util::toNarrow(str, codePage::kActive) << std::flush;
|
||||||
|
# endif
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
m_outputStream << str << std::flush;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
#ifdef __BORLANDC__
|
||||||
|
static int _isatty(int fd) { return ::isatty(fd); }
|
||||||
|
#endif
|
||||||
|
|
||||||
|
protected:
|
||||||
|
util::Mutex m_mutex;
|
||||||
|
const bool m_isatty;
|
||||||
|
std::ostream& m_outputStream;
|
||||||
|
#ifdef _WIN32
|
||||||
|
HANDLE m_outputHandle;
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <plog/Appenders/IAppender.h>
|
||||||
|
#include <plog/WinApi.h>
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
template<class Formatter>
|
||||||
|
class PLOG_LINKAGE_HIDDEN DebugOutputAppender : public IAppender
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
virtual void write(const Record& record) PLOG_OVERRIDE
|
||||||
|
{
|
||||||
|
OutputDebugStringW(util::toWide(Formatter::format(record)).c_str());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <plog/Appenders/IAppender.h>
|
||||||
|
#include <set>
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
class PLOG_LINKAGE_HIDDEN DynamicAppender : public IAppender
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
DynamicAppender& addAppender(IAppender* appender)
|
||||||
|
{
|
||||||
|
assert(appender != this);
|
||||||
|
|
||||||
|
util::MutexLock lock(m_mutex);
|
||||||
|
m_appenders.insert(appender);
|
||||||
|
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
DynamicAppender& removeAppender(IAppender* appender)
|
||||||
|
{
|
||||||
|
util::MutexLock lock(m_mutex);
|
||||||
|
m_appenders.erase(appender);
|
||||||
|
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
virtual void write(const Record& record) PLOG_OVERRIDE
|
||||||
|
{
|
||||||
|
util::MutexLock lock(m_mutex);
|
||||||
|
|
||||||
|
for (std::set<IAppender*>::iterator it = m_appenders.begin(); it != m_appenders.end(); ++it)
|
||||||
|
{
|
||||||
|
(*it)->write(record);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
mutable util::Mutex m_mutex;
|
||||||
|
std::set<IAppender*> m_appenders;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <plog/Appenders/IAppender.h>
|
||||||
|
#include <plog/WinApi.h>
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
template <class Formatter>
|
||||||
|
class PLOG_LINKAGE_HIDDEN EventLogAppender : public IAppender
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
EventLogAppender(const util::nchar* sourceName) : m_eventSource(RegisterEventSourceW(NULL, util::toWide(sourceName).c_str()))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
~EventLogAppender()
|
||||||
|
{
|
||||||
|
DeregisterEventSource(m_eventSource);
|
||||||
|
}
|
||||||
|
|
||||||
|
virtual void write(const Record& record) PLOG_OVERRIDE
|
||||||
|
{
|
||||||
|
util::nstring str = Formatter::format(record);
|
||||||
|
|
||||||
|
write(record.getSeverity(), util::toWide(str).c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
void write(Severity severity, const wchar_t* str)
|
||||||
|
{
|
||||||
|
const wchar_t* logMessagePtr[] = { str };
|
||||||
|
|
||||||
|
ReportEventW(m_eventSource, logSeverityToType(severity), static_cast<WORD>(severity), 0, NULL, 1, 0, logMessagePtr, NULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
static WORD logSeverityToType(plog::Severity severity)
|
||||||
|
{
|
||||||
|
switch (severity)
|
||||||
|
{
|
||||||
|
case plog::fatal:
|
||||||
|
case plog::error:
|
||||||
|
return eventLog::kErrorType;
|
||||||
|
|
||||||
|
case plog::warning:
|
||||||
|
return eventLog::kWarningType;
|
||||||
|
|
||||||
|
case plog::info:
|
||||||
|
case plog::debug:
|
||||||
|
case plog::verbose:
|
||||||
|
default:
|
||||||
|
return eventLog::kInformationType;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
HANDLE m_eventSource;
|
||||||
|
};
|
||||||
|
|
||||||
|
class EventLogAppenderRegistry
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
static bool add(const util::nchar* sourceName, const util::nchar* logName = PLOG_NSTR("Application"))
|
||||||
|
{
|
||||||
|
std::wstring logKeyName;
|
||||||
|
std::wstring sourceKeyName;
|
||||||
|
getKeyNames(sourceName, logName, sourceKeyName, logKeyName);
|
||||||
|
|
||||||
|
HKEY sourceKey;
|
||||||
|
if (0 != RegCreateKeyExW(hkey::kLocalMachine, sourceKeyName.c_str(), 0, NULL, 0, regSam::kSetValue, NULL, &sourceKey, NULL))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DWORD kTypesSupported = eventLog::kErrorType | eventLog::kWarningType | eventLog::kInformationType;
|
||||||
|
RegSetValueExW(sourceKey, L"TypesSupported", 0, regType::kDword, reinterpret_cast<const BYTE*>(&kTypesSupported), sizeof(kTypesSupported));
|
||||||
|
|
||||||
|
const wchar_t kEventMessageFile[] = L"%windir%\\Microsoft.NET\\Framework\\v4.0.30319\\EventLogMessages.dll;%windir%\\Microsoft.NET\\Framework\\v2.0.50727\\EventLogMessages.dll";
|
||||||
|
RegSetValueExW(sourceKey, L"EventMessageFile", 0, regType::kExpandSz, reinterpret_cast<const BYTE*>(kEventMessageFile), sizeof(kEventMessageFile) - sizeof(*kEventMessageFile));
|
||||||
|
|
||||||
|
RegCloseKey(sourceKey);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool exists(const util::nchar* sourceName, const util::nchar* logName = PLOG_NSTR("Application"))
|
||||||
|
{
|
||||||
|
std::wstring logKeyName;
|
||||||
|
std::wstring sourceKeyName;
|
||||||
|
getKeyNames(sourceName, logName, sourceKeyName, logKeyName);
|
||||||
|
|
||||||
|
HKEY sourceKey;
|
||||||
|
if (0 != RegOpenKeyExW(hkey::kLocalMachine, sourceKeyName.c_str(), 0, regSam::kQueryValue, &sourceKey))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
RegCloseKey(sourceKey);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void remove(const util::nchar* sourceName, const util::nchar* logName = PLOG_NSTR("Application"))
|
||||||
|
{
|
||||||
|
std::wstring logKeyName;
|
||||||
|
std::wstring sourceKeyName;
|
||||||
|
getKeyNames(sourceName, logName, sourceKeyName, logKeyName);
|
||||||
|
|
||||||
|
RegDeleteKeyW(hkey::kLocalMachine, sourceKeyName.c_str());
|
||||||
|
RegDeleteKeyW(hkey::kLocalMachine, logKeyName.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
static void getKeyNames(const util::nchar* sourceName, const util::nchar* logName, std::wstring& sourceKeyName, std::wstring& logKeyName)
|
||||||
|
{
|
||||||
|
const std::wstring kPrefix = L"SYSTEM\\CurrentControlSet\\Services\\EventLog\\";
|
||||||
|
logKeyName = kPrefix + util::toWide(logName);
|
||||||
|
sourceKeyName = logKeyName + L"\\" + util::toWide(sourceName);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <plog/Record.h>
|
||||||
|
#include <plog/Util.h>
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
class PLOG_LINKAGE IAppender
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
virtual ~IAppender()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
virtual void write(const Record& record) = 0;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <plog/Appenders/IAppender.h>
|
||||||
|
#include <plog/Converters/UTF8Converter.h>
|
||||||
|
#include <plog/Converters/NativeEOLConverter.h>
|
||||||
|
#include <plog/Util.h>
|
||||||
|
#include <algorithm>
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
template<class Formatter, class Converter = NativeEOLConverter<UTF8Converter> >
|
||||||
|
class PLOG_LINKAGE_HIDDEN RollingFileAppender : public IAppender
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
RollingFileAppender(const util::nchar* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
||||||
|
: m_fileSize()
|
||||||
|
, m_maxFileSize()
|
||||||
|
, m_maxFiles(maxFiles)
|
||||||
|
, m_firstWrite(true)
|
||||||
|
{
|
||||||
|
setFileName(fileName);
|
||||||
|
setMaxFileSize(maxFileSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
#if defined(_WIN32) && !PLOG_CHAR_IS_UTF8
|
||||||
|
RollingFileAppender(const char* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
||||||
|
: m_fileSize()
|
||||||
|
, m_maxFileSize()
|
||||||
|
, m_maxFiles(maxFiles)
|
||||||
|
, m_firstWrite(true)
|
||||||
|
{
|
||||||
|
setFileName(fileName);
|
||||||
|
setMaxFileSize(maxFileSize);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
virtual void write(const Record& record) PLOG_OVERRIDE
|
||||||
|
{
|
||||||
|
util::MutexLock lock(m_mutex);
|
||||||
|
|
||||||
|
if (m_firstWrite)
|
||||||
|
{
|
||||||
|
openLogFile();
|
||||||
|
m_firstWrite = false;
|
||||||
|
}
|
||||||
|
else if (m_maxFiles > 0 && m_fileSize > m_maxFileSize && static_cast<size_t>(-1) != m_fileSize)
|
||||||
|
{
|
||||||
|
rollLogFiles();
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t bytesWritten = m_file.write(Converter::convert(Formatter::format(record)));
|
||||||
|
|
||||||
|
if (static_cast<size_t>(-1) != bytesWritten)
|
||||||
|
{
|
||||||
|
m_fileSize += bytesWritten;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void setFileName(const util::nchar* fileName)
|
||||||
|
{
|
||||||
|
util::MutexLock lock(m_mutex);
|
||||||
|
|
||||||
|
util::splitFileName(fileName, m_fileNameNoExt, m_fileExt);
|
||||||
|
|
||||||
|
m_file.close();
|
||||||
|
m_firstWrite = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
#if defined(_WIN32) && !PLOG_CHAR_IS_UTF8
|
||||||
|
void setFileName(const char* fileName)
|
||||||
|
{
|
||||||
|
setFileName(util::toWide(fileName).c_str());
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
void setMaxFiles(int maxFiles)
|
||||||
|
{
|
||||||
|
m_maxFiles = maxFiles;
|
||||||
|
}
|
||||||
|
|
||||||
|
void setMaxFileSize(size_t maxFileSize)
|
||||||
|
{
|
||||||
|
m_maxFileSize = (std::max)(maxFileSize, static_cast<size_t>(1000)); // set a lower limit for the maxFileSize
|
||||||
|
}
|
||||||
|
|
||||||
|
void rollLogFiles()
|
||||||
|
{
|
||||||
|
m_file.close();
|
||||||
|
|
||||||
|
util::nstring lastFileName = buildFileName(m_maxFiles - 1);
|
||||||
|
util::File::unlink(lastFileName);
|
||||||
|
|
||||||
|
for (int fileNumber = m_maxFiles - 2; fileNumber >= 0; --fileNumber)
|
||||||
|
{
|
||||||
|
util::nstring currentFileName = buildFileName(fileNumber);
|
||||||
|
util::nstring nextFileName = buildFileName(fileNumber + 1);
|
||||||
|
|
||||||
|
util::File::rename(currentFileName, nextFileName);
|
||||||
|
}
|
||||||
|
|
||||||
|
openLogFile();
|
||||||
|
m_firstWrite = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
void openLogFile()
|
||||||
|
{
|
||||||
|
m_fileSize = m_file.open(buildFileName());
|
||||||
|
|
||||||
|
if (0 == m_fileSize)
|
||||||
|
{
|
||||||
|
size_t bytesWritten = m_file.write(Converter::header(Formatter::header()));
|
||||||
|
|
||||||
|
if (static_cast<size_t>(-1) != bytesWritten)
|
||||||
|
{
|
||||||
|
m_fileSize += bytesWritten;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
util::nstring buildFileName(int fileNumber = 0)
|
||||||
|
{
|
||||||
|
util::nostringstream ss;
|
||||||
|
ss << m_fileNameNoExt;
|
||||||
|
|
||||||
|
if (fileNumber > 0)
|
||||||
|
{
|
||||||
|
ss << '.' << fileNumber;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!m_fileExt.empty())
|
||||||
|
{
|
||||||
|
ss << '.' << m_fileExt;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ss.str();
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
util::Mutex m_mutex;
|
||||||
|
util::File m_file;
|
||||||
|
size_t m_fileSize;
|
||||||
|
size_t m_maxFileSize;
|
||||||
|
int m_maxFiles;
|
||||||
|
util::nstring m_fileExt;
|
||||||
|
util::nstring m_fileNameNoExt;
|
||||||
|
bool m_firstWrite;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <plog/Converters/UTF8Converter.h>
|
||||||
|
#include <plog/Util.h>
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
template<class NextConverter = UTF8Converter>
|
||||||
|
class NativeEOLConverter : public NextConverter
|
||||||
|
{
|
||||||
|
#ifdef _WIN32
|
||||||
|
public:
|
||||||
|
static std::string header(const util::nstring& str)
|
||||||
|
{
|
||||||
|
return NextConverter::header(fixLineEndings(str));
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::string convert(const util::nstring& str)
|
||||||
|
{
|
||||||
|
return NextConverter::convert(fixLineEndings(str));
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
static util::nstring fixLineEndings(const util::nstring& str)
|
||||||
|
{
|
||||||
|
util::nstring output;
|
||||||
|
output.reserve(str.length() * 2); // the worst case requires 2x chars
|
||||||
|
|
||||||
|
for (size_t i = 0; i < str.size(); ++i)
|
||||||
|
{
|
||||||
|
util::nchar ch = str[i];
|
||||||
|
|
||||||
|
if (ch == PLOG_NSTR('\n'))
|
||||||
|
{
|
||||||
|
output.push_back(PLOG_NSTR('\r'));
|
||||||
|
}
|
||||||
|
|
||||||
|
output.push_back(ch);
|
||||||
|
}
|
||||||
|
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <plog/Util.h>
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
class UTF8Converter
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
static std::string header(const util::nstring& str)
|
||||||
|
{
|
||||||
|
const char kBOM[] = "\xEF\xBB\xBF";
|
||||||
|
|
||||||
|
return std::string(kBOM) + convert(str);
|
||||||
|
}
|
||||||
|
|
||||||
|
#if PLOG_CHAR_IS_UTF8
|
||||||
|
static const std::string& convert(const util::nstring& str)
|
||||||
|
{
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
static std::string convert(const util::nstring& str)
|
||||||
|
{
|
||||||
|
return util::toNarrow(str, codePage::kUTF8);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <plog/Record.h>
|
||||||
|
#include <plog/Util.h>
|
||||||
|
#include <iomanip>
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
template<bool useUtcTime>
|
||||||
|
class CsvFormatterImpl
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
static util::nstring header()
|
||||||
|
{
|
||||||
|
return PLOG_NSTR("Date;Time;Severity;TID;This;Function;Message\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
static util::nstring format(const Record& record)
|
||||||
|
{
|
||||||
|
tm t;
|
||||||
|
useUtcTime ? util::gmtime_s(&t, &record.getTime().time) : util::localtime_s(&t, &record.getTime().time);
|
||||||
|
|
||||||
|
util::nostringstream ss;
|
||||||
|
ss << t.tm_year + 1900 << PLOG_NSTR("/") << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_mon + 1 << PLOG_NSTR("/") << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_mday << PLOG_NSTR(";");
|
||||||
|
ss << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_hour << PLOG_NSTR(":") << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_min << PLOG_NSTR(":") << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_sec << PLOG_NSTR(".") << std::setfill(PLOG_NSTR('0')) << std::setw(3) << static_cast<int> (record.getTime().millitm) << PLOG_NSTR(";");
|
||||||
|
ss << severityToString(record.getSeverity()) << PLOG_NSTR(";");
|
||||||
|
ss << record.getTid() << PLOG_NSTR(";");
|
||||||
|
ss << record.getObject() << PLOG_NSTR(";");
|
||||||
|
ss << record.getFunc() << PLOG_NSTR("@") << record.getLine() << PLOG_NSTR(";");
|
||||||
|
|
||||||
|
util::nstring message = record.getMessage();
|
||||||
|
|
||||||
|
if (message.size() > kMaxMessageSize)
|
||||||
|
{
|
||||||
|
message.resize(kMaxMessageSize);
|
||||||
|
message.append(PLOG_NSTR("..."));
|
||||||
|
}
|
||||||
|
|
||||||
|
util::nistringstream split(message);
|
||||||
|
util::nstring token;
|
||||||
|
|
||||||
|
while (!split.eof())
|
||||||
|
{
|
||||||
|
std::getline(split, token, PLOG_NSTR('"'));
|
||||||
|
ss << PLOG_NSTR("\"") << token << PLOG_NSTR("\"");
|
||||||
|
}
|
||||||
|
|
||||||
|
ss << PLOG_NSTR("\n");
|
||||||
|
|
||||||
|
return ss.str();
|
||||||
|
}
|
||||||
|
|
||||||
|
static const size_t kMaxMessageSize = 32000;
|
||||||
|
};
|
||||||
|
|
||||||
|
class CsvFormatter : public CsvFormatterImpl<false> {};
|
||||||
|
class CsvFormatterUtcTime : public CsvFormatterImpl<true> {};
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <plog/Record.h>
|
||||||
|
#include <plog/Util.h>
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
class FuncMessageFormatter
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
static util::nstring header()
|
||||||
|
{
|
||||||
|
return util::nstring();
|
||||||
|
}
|
||||||
|
|
||||||
|
static util::nstring format(const Record& record)
|
||||||
|
{
|
||||||
|
util::nostringstream ss;
|
||||||
|
ss << record.getFunc() << PLOG_NSTR("@") << record.getLine() << PLOG_NSTR(": ") << record.getMessage() << PLOG_NSTR("\n");
|
||||||
|
|
||||||
|
return ss.str();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <plog/Record.h>
|
||||||
|
#include <plog/Util.h>
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
class MessageOnlyFormatter
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
static util::nstring header()
|
||||||
|
{
|
||||||
|
return util::nstring();
|
||||||
|
}
|
||||||
|
|
||||||
|
static util::nstring format(const Record& record)
|
||||||
|
{
|
||||||
|
util::nostringstream ss;
|
||||||
|
ss << record.getMessage() << PLOG_NSTR("\n");
|
||||||
|
|
||||||
|
return ss.str();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <plog/Record.h>
|
||||||
|
#include <plog/Util.h>
|
||||||
|
#include <iomanip>
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
template<bool useUtcTime>
|
||||||
|
class TxtFormatterImpl
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
static util::nstring header()
|
||||||
|
{
|
||||||
|
return util::nstring();
|
||||||
|
}
|
||||||
|
|
||||||
|
static util::nstring format(const Record& record)
|
||||||
|
{
|
||||||
|
tm t;
|
||||||
|
useUtcTime ? util::gmtime_s(&t, &record.getTime().time) : util::localtime_s(&t, &record.getTime().time);
|
||||||
|
|
||||||
|
util::nostringstream ss;
|
||||||
|
ss << t.tm_year + 1900 << "-" << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_mon + 1 << PLOG_NSTR("-") << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_mday << PLOG_NSTR(" ");
|
||||||
|
ss << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_hour << PLOG_NSTR(":") << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_min << PLOG_NSTR(":") << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_sec << PLOG_NSTR(".") << std::setfill(PLOG_NSTR('0')) << std::setw(3) << static_cast<int> (record.getTime().millitm) << PLOG_NSTR(" ");
|
||||||
|
ss << std::setfill(PLOG_NSTR(' ')) << std::setw(5) << std::left << severityToString(record.getSeverity()) << PLOG_NSTR(" ");
|
||||||
|
ss << PLOG_NSTR("[") << record.getTid() << PLOG_NSTR("] ");
|
||||||
|
ss << PLOG_NSTR("[") << record.getFunc() << PLOG_NSTR("@") << record.getLine() << PLOG_NSTR("] ");
|
||||||
|
ss << record.getMessage() << PLOG_NSTR("\n");
|
||||||
|
|
||||||
|
return ss.str();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
class TxtFormatter : public TxtFormatterImpl<false> {};
|
||||||
|
class TxtFormatterUtcTime : public TxtFormatterImpl<true> {};
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <plog/Util.h>
|
||||||
|
#include <cctype>
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
class AscDump
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
AscDump(const void* ptr, size_t size)
|
||||||
|
: m_ptr(static_cast<const char*>(ptr))
|
||||||
|
, m_size(size)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
friend util::nostringstream& operator<<(util::nostringstream& stream, const AscDump& ascDump);
|
||||||
|
|
||||||
|
private:
|
||||||
|
const char* m_ptr;
|
||||||
|
size_t m_size;
|
||||||
|
};
|
||||||
|
|
||||||
|
inline util::nostringstream& operator<<(util::nostringstream& stream, const AscDump& ascDump)
|
||||||
|
{
|
||||||
|
for (size_t i = 0; i < ascDump.m_size; ++i)
|
||||||
|
{
|
||||||
|
stream << (std::isprint(ascDump.m_ptr[i]) ? ascDump.m_ptr[i] : '.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline AscDump ascdump(const void* ptr, size_t size) { return AscDump(ptr, size); }
|
||||||
|
|
||||||
|
template<class Container>
|
||||||
|
inline AscDump ascdump(const Container& container) { return AscDump(container.data(), container.size() * sizeof(*container.data())); }
|
||||||
|
|
||||||
|
template<class T, size_t N>
|
||||||
|
inline AscDump ascdump(const T (&arr)[N]) { return AscDump(arr, N * sizeof(*arr)); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <plog/Util.h>
|
||||||
|
#include <iomanip>
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
class HexDump
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
HexDump(const void* ptr, size_t size)
|
||||||
|
: m_ptr(static_cast<const unsigned char*>(ptr))
|
||||||
|
, m_size(size)
|
||||||
|
, m_group(8)
|
||||||
|
, m_digitSeparator(" ")
|
||||||
|
, m_groupSeparator(" ")
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
HexDump& group(size_t group)
|
||||||
|
{
|
||||||
|
m_group = group;
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
HexDump& separator(const char* digitSeparator)
|
||||||
|
{
|
||||||
|
m_digitSeparator = digitSeparator;
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
HexDump& separator(const char* digitSeparator, const char* groupSeparator)
|
||||||
|
{
|
||||||
|
m_digitSeparator = digitSeparator;
|
||||||
|
m_groupSeparator = groupSeparator;
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
friend util::nostringstream& operator<<(util::nostringstream& stream, const HexDump&);
|
||||||
|
|
||||||
|
private:
|
||||||
|
const unsigned char* m_ptr;
|
||||||
|
size_t m_size;
|
||||||
|
size_t m_group;
|
||||||
|
const char* m_digitSeparator;
|
||||||
|
const char* m_groupSeparator;
|
||||||
|
};
|
||||||
|
|
||||||
|
inline util::nostringstream& operator<<(util::nostringstream& stream, const HexDump& hexDump)
|
||||||
|
{
|
||||||
|
stream << std::hex << std::setfill(PLOG_NSTR('0'));
|
||||||
|
|
||||||
|
for (size_t i = 0; i < hexDump.m_size;)
|
||||||
|
{
|
||||||
|
stream << std::setw(2) << static_cast<int>(hexDump.m_ptr[i]);
|
||||||
|
|
||||||
|
if (++i < hexDump.m_size)
|
||||||
|
{
|
||||||
|
if (hexDump.m_group > 0 && i % hexDump.m_group == 0)
|
||||||
|
{
|
||||||
|
stream << hexDump.m_groupSeparator;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
stream << hexDump.m_digitSeparator;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline HexDump hexdump(const void* ptr, size_t size) { return HexDump(ptr, size); }
|
||||||
|
|
||||||
|
template<class Container>
|
||||||
|
inline HexDump hexdump(const Container& container) { return HexDump(container.data(), container.size() * sizeof(*container.data())); }
|
||||||
|
|
||||||
|
template<class T, size_t N>
|
||||||
|
inline HexDump hexdump(const T (&arr)[N]) { return HexDump(arr, N * sizeof(*arr)); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#define PLOG_IMPL_PRINT_VAR_1(a1) #a1 ": " << a1
|
||||||
|
#define PLOG_IMPL_PRINT_VAR_2(a1, a2) PLOG_IMPL_PRINT_VAR_1(a1) PLOG_IMPL_PRINT_VAR_TAIL(a2)
|
||||||
|
#define PLOG_IMPL_PRINT_VAR_3(a1, a2, a3) PLOG_IMPL_PRINT_VAR_2(a1, a2) PLOG_IMPL_PRINT_VAR_TAIL(a3)
|
||||||
|
#define PLOG_IMPL_PRINT_VAR_4(a1, a2, a3, a4) PLOG_IMPL_PRINT_VAR_3(a1, a2, a3) PLOG_IMPL_PRINT_VAR_TAIL(a4)
|
||||||
|
#define PLOG_IMPL_PRINT_VAR_5(a1, a2, a3, a4, a5) PLOG_IMPL_PRINT_VAR_4(a1, a2, a3, a4) PLOG_IMPL_PRINT_VAR_TAIL(a5)
|
||||||
|
#define PLOG_IMPL_PRINT_VAR_6(a1, a2, a3, a4, a5, a6) PLOG_IMPL_PRINT_VAR_5(a1, a2, a3, a4, a5) PLOG_IMPL_PRINT_VAR_TAIL(a6)
|
||||||
|
#define PLOG_IMPL_PRINT_VAR_7(a1, a2, a3, a4, a5, a6, a7) PLOG_IMPL_PRINT_VAR_6(a1, a2, a3, a4, a5, a6) PLOG_IMPL_PRINT_VAR_TAIL(a7)
|
||||||
|
#define PLOG_IMPL_PRINT_VAR_8(a1, a2, a3, a4, a5, a6, a7, a8) PLOG_IMPL_PRINT_VAR_7(a1, a2, a3, a4, a5, a6, a7) PLOG_IMPL_PRINT_VAR_TAIL(a8)
|
||||||
|
#define PLOG_IMPL_PRINT_VAR_9(a1, a2, a3, a4, a5, a6, a7, a8, a9) PLOG_IMPL_PRINT_VAR_8(a1, a2, a3, a4, a5, a6, a7, a8) PLOG_IMPL_PRINT_VAR_TAIL(a9)
|
||||||
|
#define PLOG_IMPL_PRINT_VAR_TAIL(a) << ", " PLOG_IMPL_PRINT_VAR_1(a)
|
||||||
|
|
||||||
|
#define PLOG_IMPL_PRINT_VAR_EXPAND(x) x
|
||||||
|
|
||||||
|
#ifdef __GNUC__
|
||||||
|
#pragma GCC system_header // disable warning: variadic macros are a C99 feature
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define PLOG_IMPL_PRINT_VAR_GET_MACRO(x1, x2, x3, x4, x5, x6, x7, x8, x9, NAME, ...) NAME
|
||||||
|
|
||||||
|
#define PLOG_PRINT_VAR(...) PLOG_IMPL_PRINT_VAR_EXPAND(PLOG_IMPL_PRINT_VAR_GET_MACRO(__VA_ARGS__,\
|
||||||
|
PLOG_IMPL_PRINT_VAR_9, PLOG_IMPL_PRINT_VAR_8, PLOG_IMPL_PRINT_VAR_7, PLOG_IMPL_PRINT_VAR_6, PLOG_IMPL_PRINT_VAR_5,\
|
||||||
|
PLOG_IMPL_PRINT_VAR_4, PLOG_IMPL_PRINT_VAR_3, PLOG_IMPL_PRINT_VAR_2, PLOG_IMPL_PRINT_VAR_1, UNUSED)(__VA_ARGS__))
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <plog/Logger.h>
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
template<int instanceId>
|
||||||
|
PLOG_LINKAGE_HIDDEN inline Logger<instanceId>& init(Severity maxSeverity = none, IAppender* appender = NULL)
|
||||||
|
{
|
||||||
|
static Logger<instanceId> logger(maxSeverity);
|
||||||
|
return appender ? logger.addAppender(appender) : logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Logger<PLOG_DEFAULT_INSTANCE_ID>& init(Severity maxSeverity = none, IAppender* appender = NULL)
|
||||||
|
{
|
||||||
|
return init<PLOG_DEFAULT_INSTANCE_ID>(maxSeverity, appender);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <plog/Appenders/ColorConsoleAppender.h>
|
||||||
|
#include <plog/Init.h>
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
//////////////////////////////////////////////////////////////////////////
|
||||||
|
// ColorConsoleAppender with any Formatter
|
||||||
|
|
||||||
|
template<class Formatter, int instanceId>
|
||||||
|
PLOG_LINKAGE_HIDDEN inline Logger<instanceId>& init(Severity maxSeverity, OutputStream outputStream)
|
||||||
|
{
|
||||||
|
static ColorConsoleAppender<Formatter> appender(outputStream);
|
||||||
|
return init<instanceId>(maxSeverity, &appender);
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class Formatter>
|
||||||
|
inline Logger<PLOG_DEFAULT_INSTANCE_ID>& init(Severity maxSeverity, OutputStream outputStream)
|
||||||
|
{
|
||||||
|
return init<Formatter, PLOG_DEFAULT_INSTANCE_ID>(maxSeverity, outputStream);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <plog/Appenders/RollingFileAppender.h>
|
||||||
|
#include <plog/Formatters/TxtFormatter.h>
|
||||||
|
#include <plog/Formatters/CsvFormatter.h>
|
||||||
|
#include <plog/Init.h>
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
//////////////////////////////////////////////////////////////////////////
|
||||||
|
// RollingFileAppender with any Formatter
|
||||||
|
|
||||||
|
template<class Formatter, int instanceId>
|
||||||
|
PLOG_LINKAGE_HIDDEN inline Logger<instanceId>& init(Severity maxSeverity, const util::nchar* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
||||||
|
{
|
||||||
|
static RollingFileAppender<Formatter> rollingFileAppender(fileName, maxFileSize, maxFiles);
|
||||||
|
return init<instanceId>(maxSeverity, &rollingFileAppender);
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class Formatter>
|
||||||
|
inline Logger<PLOG_DEFAULT_INSTANCE_ID>& init(Severity maxSeverity, const util::nchar* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
||||||
|
{
|
||||||
|
return init<Formatter, PLOG_DEFAULT_INSTANCE_ID>(maxSeverity, fileName, maxFileSize, maxFiles);
|
||||||
|
}
|
||||||
|
|
||||||
|
//////////////////////////////////////////////////////////////////////////
|
||||||
|
// RollingFileAppender with TXT/CSV chosen by file extension
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
inline bool isCsv(const util::nchar* fileName)
|
||||||
|
{
|
||||||
|
const util::nchar* dot = util::findExtensionDot(fileName);
|
||||||
|
#if PLOG_CHAR_IS_UTF8
|
||||||
|
return dot && 0 == std::strcmp(dot, ".csv");
|
||||||
|
#else
|
||||||
|
return dot && 0 == std::wcscmp(dot, L".csv");
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
template<int instanceId>
|
||||||
|
inline Logger<instanceId>& init(Severity maxSeverity, const util::nchar* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
||||||
|
{
|
||||||
|
return isCsv(fileName) ? init<CsvFormatter, instanceId>(maxSeverity, fileName, maxFileSize, maxFiles) : init<TxtFormatter, instanceId>(maxSeverity, fileName, maxFileSize, maxFiles);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Logger<PLOG_DEFAULT_INSTANCE_ID>& init(Severity maxSeverity, const util::nchar* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
||||||
|
{
|
||||||
|
return init<PLOG_DEFAULT_INSTANCE_ID>(maxSeverity, fileName, maxFileSize, maxFiles);
|
||||||
|
}
|
||||||
|
|
||||||
|
//////////////////////////////////////////////////////////////////////////
|
||||||
|
// CHAR variants for Windows
|
||||||
|
|
||||||
|
#if defined(_WIN32) && !PLOG_CHAR_IS_UTF8
|
||||||
|
template<class Formatter, int instanceId>
|
||||||
|
inline Logger<instanceId>& init(Severity maxSeverity, const char* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
||||||
|
{
|
||||||
|
return init<Formatter, instanceId>(maxSeverity, util::toWide(fileName).c_str(), maxFileSize, maxFiles);
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class Formatter>
|
||||||
|
inline Logger<PLOG_DEFAULT_INSTANCE_ID>& init(Severity maxSeverity, const char* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
||||||
|
{
|
||||||
|
return init<Formatter, PLOG_DEFAULT_INSTANCE_ID>(maxSeverity, fileName, maxFileSize, maxFiles);
|
||||||
|
}
|
||||||
|
|
||||||
|
template<int instanceId>
|
||||||
|
inline Logger<instanceId>& init(Severity maxSeverity, const char* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
||||||
|
{
|
||||||
|
return init<instanceId>(maxSeverity, util::toWide(fileName).c_str(), maxFileSize, maxFiles);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Logger<PLOG_DEFAULT_INSTANCE_ID>& init(Severity maxSeverity, const char* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
||||||
|
{
|
||||||
|
return init<PLOG_DEFAULT_INSTANCE_ID>(maxSeverity, fileName, maxFileSize, maxFiles);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
}
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
//////////////////////////////////////////////////////////////////////////
|
||||||
|
// Plog - portable and simple log for C++
|
||||||
|
// Documentation and sources: https://github.com/SergiusTheBest/plog
|
||||||
|
// License: MIT, https://choosealicense.com/licenses/mit
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
#include <plog/Logger.h>
|
||||||
|
|
||||||
|
//////////////////////////////////////////////////////////////////////////
|
||||||
|
// Helper macros that get context info
|
||||||
|
|
||||||
|
#if defined(PLOG_ENABLE_GET_THIS) && defined(_MSC_VER) && _MSC_VER >= 1600 && !defined(__INTELLISENSE__) && !defined(__INTEL_COMPILER) && !defined(__llvm__) && !defined(__RESHARPER__) // >= Visual Studio 2010, skip IntelliSense, Intel Compiler, Clang Code Model and ReSharper
|
||||||
|
# define PLOG_GET_THIS() __if_exists(this) { this } __if_not_exists(this) { 0 }
|
||||||
|
#else
|
||||||
|
# define PLOG_GET_THIS() reinterpret_cast<void*>(0)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef _MSC_VER
|
||||||
|
# define PLOG_GET_FUNC() __FUNCTION__
|
||||||
|
#elif defined(__BORLANDC__)
|
||||||
|
# define PLOG_GET_FUNC() __FUNC__
|
||||||
|
#else
|
||||||
|
# define PLOG_GET_FUNC() __PRETTY_FUNCTION__
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef PLOG_CAPTURE_FILE
|
||||||
|
# define PLOG_GET_FILE() __FILE__
|
||||||
|
#else
|
||||||
|
# define PLOG_GET_FILE() ""
|
||||||
|
#endif
|
||||||
|
|
||||||
|
//////////////////////////////////////////////////////////////////////////
|
||||||
|
// Log severity level checker
|
||||||
|
|
||||||
|
#ifdef PLOG_DISABLE_LOGGING
|
||||||
|
# ifdef _MSC_VER
|
||||||
|
# define IF_PLOG_(instanceId, severity) __pragma(warning(push)) __pragma(warning(disable:4127)) if (true) {;} else __pragma(warning(pop)) // conditional expression is constant
|
||||||
|
# else
|
||||||
|
# define IF_PLOG_(instanceId, severity) if (true) {;} else
|
||||||
|
# endif
|
||||||
|
#else
|
||||||
|
# define IF_PLOG_(instanceId, severity) if (!plog::get<instanceId>() || !plog::get<instanceId>()->checkSeverity(severity)) {;} else
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define IF_PLOG(severity) IF_PLOG_(PLOG_DEFAULT_INSTANCE_ID, severity)
|
||||||
|
|
||||||
|
//////////////////////////////////////////////////////////////////////////
|
||||||
|
// Main logging macros
|
||||||
|
|
||||||
|
#ifdef PLOG_MESSAGE_PREFIX
|
||||||
|
# define PLOG_PRINT_MESSAGE_PREFIX() << PLOG_MESSAGE_PREFIX
|
||||||
|
#else
|
||||||
|
# define PLOG_PRINT_MESSAGE_PREFIX()
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define PLOG_(instanceId, severity) IF_PLOG_(instanceId, severity) (*plog::get<instanceId>()) += \
|
||||||
|
plog::Record(severity, PLOG_GET_FUNC(), __LINE__, PLOG_GET_FILE(), PLOG_GET_THIS(), instanceId).ref() PLOG_PRINT_MESSAGE_PREFIX()
|
||||||
|
#define PLOG(severity) PLOG_(PLOG_DEFAULT_INSTANCE_ID, severity)
|
||||||
|
|
||||||
|
#define PLOG_VERBOSE PLOG(plog::verbose)
|
||||||
|
#define PLOG_DEBUG PLOG(plog::debug)
|
||||||
|
#define PLOG_INFO PLOG(plog::info)
|
||||||
|
#define PLOG_WARNING PLOG(plog::warning)
|
||||||
|
#define PLOG_ERROR PLOG(plog::error)
|
||||||
|
#define PLOG_FATAL PLOG(plog::fatal)
|
||||||
|
#define PLOG_NONE PLOG(plog::none)
|
||||||
|
|
||||||
|
#define PLOG_VERBOSE_(instanceId) PLOG_(instanceId, plog::verbose)
|
||||||
|
#define PLOG_DEBUG_(instanceId) PLOG_(instanceId, plog::debug)
|
||||||
|
#define PLOG_INFO_(instanceId) PLOG_(instanceId, plog::info)
|
||||||
|
#define PLOG_WARNING_(instanceId) PLOG_(instanceId, plog::warning)
|
||||||
|
#define PLOG_ERROR_(instanceId) PLOG_(instanceId, plog::error)
|
||||||
|
#define PLOG_FATAL_(instanceId) PLOG_(instanceId, plog::fatal)
|
||||||
|
#define PLOG_NONE_(instanceId) PLOG_(instanceId, plog::none)
|
||||||
|
|
||||||
|
#define PLOGV PLOG_VERBOSE
|
||||||
|
#define PLOGD PLOG_DEBUG
|
||||||
|
#define PLOGI PLOG_INFO
|
||||||
|
#define PLOGW PLOG_WARNING
|
||||||
|
#define PLOGE PLOG_ERROR
|
||||||
|
#define PLOGF PLOG_FATAL
|
||||||
|
#define PLOGN PLOG_NONE
|
||||||
|
|
||||||
|
#define PLOGV_(instanceId) PLOG_VERBOSE_(instanceId)
|
||||||
|
#define PLOGD_(instanceId) PLOG_DEBUG_(instanceId)
|
||||||
|
#define PLOGI_(instanceId) PLOG_INFO_(instanceId)
|
||||||
|
#define PLOGW_(instanceId) PLOG_WARNING_(instanceId)
|
||||||
|
#define PLOGE_(instanceId) PLOG_ERROR_(instanceId)
|
||||||
|
#define PLOGF_(instanceId) PLOG_FATAL_(instanceId)
|
||||||
|
#define PLOGN_(instanceId) PLOG_NONE_(instanceId)
|
||||||
|
|
||||||
|
//////////////////////////////////////////////////////////////////////////
|
||||||
|
// Conditional logging macros
|
||||||
|
|
||||||
|
#define PLOG_IF_(instanceId, severity, condition) if (!(condition)) {;} else PLOG_(instanceId, severity)
|
||||||
|
#define PLOG_IF(severity, condition) PLOG_IF_(PLOG_DEFAULT_INSTANCE_ID, severity, condition)
|
||||||
|
|
||||||
|
#define PLOG_VERBOSE_IF(condition) PLOG_IF(plog::verbose, condition)
|
||||||
|
#define PLOG_DEBUG_IF(condition) PLOG_IF(plog::debug, condition)
|
||||||
|
#define PLOG_INFO_IF(condition) PLOG_IF(plog::info, condition)
|
||||||
|
#define PLOG_WARNING_IF(condition) PLOG_IF(plog::warning, condition)
|
||||||
|
#define PLOG_ERROR_IF(condition) PLOG_IF(plog::error, condition)
|
||||||
|
#define PLOG_FATAL_IF(condition) PLOG_IF(plog::fatal, condition)
|
||||||
|
#define PLOG_NONE_IF(condition) PLOG_IF(plog::none, condition)
|
||||||
|
|
||||||
|
#define PLOG_VERBOSE_IF_(instanceId, condition) PLOG_IF_(instanceId, plog::verbose, condition)
|
||||||
|
#define PLOG_DEBUG_IF_(instanceId, condition) PLOG_IF_(instanceId, plog::debug, condition)
|
||||||
|
#define PLOG_INFO_IF_(instanceId, condition) PLOG_IF_(instanceId, plog::info, condition)
|
||||||
|
#define PLOG_WARNING_IF_(instanceId, condition) PLOG_IF_(instanceId, plog::warning, condition)
|
||||||
|
#define PLOG_ERROR_IF_(instanceId, condition) PLOG_IF_(instanceId, plog::error, condition)
|
||||||
|
#define PLOG_FATAL_IF_(instanceId, condition) PLOG_IF_(instanceId, plog::fatal, condition)
|
||||||
|
#define PLOG_NONE_IF_(instanceId, condition) PLOG_IF_(instanceId, plog::none, condition)
|
||||||
|
|
||||||
|
#define PLOGV_IF(condition) PLOG_VERBOSE_IF(condition)
|
||||||
|
#define PLOGD_IF(condition) PLOG_DEBUG_IF(condition)
|
||||||
|
#define PLOGI_IF(condition) PLOG_INFO_IF(condition)
|
||||||
|
#define PLOGW_IF(condition) PLOG_WARNING_IF(condition)
|
||||||
|
#define PLOGE_IF(condition) PLOG_ERROR_IF(condition)
|
||||||
|
#define PLOGF_IF(condition) PLOG_FATAL_IF(condition)
|
||||||
|
#define PLOGN_IF(condition) PLOG_NONE_IF(condition)
|
||||||
|
|
||||||
|
#define PLOGV_IF_(instanceId, condition) PLOG_VERBOSE_IF_(instanceId, condition)
|
||||||
|
#define PLOGD_IF_(instanceId, condition) PLOG_DEBUG_IF_(instanceId, condition)
|
||||||
|
#define PLOGI_IF_(instanceId, condition) PLOG_INFO_IF_(instanceId, condition)
|
||||||
|
#define PLOGW_IF_(instanceId, condition) PLOG_WARNING_IF_(instanceId, condition)
|
||||||
|
#define PLOGE_IF_(instanceId, condition) PLOG_ERROR_IF_(instanceId, condition)
|
||||||
|
#define PLOGF_IF_(instanceId, condition) PLOG_FATAL_IF_(instanceId, condition)
|
||||||
|
#define PLOGN_IF_(instanceId, condition) PLOG_NONE_IF_(instanceId, condition)
|
||||||
|
|
||||||
|
// Old macro names for downward compatibility. To bypass including these macro names, add
|
||||||
|
// #define PLOG_OMIT_LOG_DEFINES before #include <plog/Log.h>
|
||||||
|
#ifndef PLOG_OMIT_LOG_DEFINES
|
||||||
|
|
||||||
|
//////////////////////////////////////////////////////////////////////////
|
||||||
|
// Main logging macros - can be changed later to point at macros for a different logging package
|
||||||
|
|
||||||
|
#define LOG_(instanceId, severity) PLOG_(instanceId, severity)
|
||||||
|
#define LOG(severity) PLOG(severity)
|
||||||
|
|
||||||
|
#define LOG_VERBOSE PLOG_VERBOSE
|
||||||
|
#define LOG_DEBUG PLOG_DEBUG
|
||||||
|
#define LOG_INFO PLOG_INFO
|
||||||
|
#define LOG_WARNING PLOG_WARNING
|
||||||
|
#define LOG_ERROR PLOG_ERROR
|
||||||
|
#define LOG_FATAL PLOG_FATAL
|
||||||
|
#define LOG_NONE PLOG_NONE
|
||||||
|
|
||||||
|
#define LOG_VERBOSE_(instanceId) PLOG_VERBOSE_(instanceId)
|
||||||
|
#define LOG_DEBUG_(instanceId) PLOG_DEBUG_(instanceId)
|
||||||
|
#define LOG_INFO_(instanceId) PLOG_INFO_(instanceId)
|
||||||
|
#define LOG_WARNING_(instanceId) PLOG_WARNING_(instanceId)
|
||||||
|
#define LOG_ERROR_(instanceId) PLOG_ERROR_(instanceId)
|
||||||
|
#define LOG_FATAL_(instanceId) PLOG_FATAL_(instanceId)
|
||||||
|
#define LOG_NONE_(instanceId) PLOG_NONE_(instanceId)
|
||||||
|
|
||||||
|
#define LOGV PLOGV
|
||||||
|
#define LOGD PLOGD
|
||||||
|
#define LOGI PLOGI
|
||||||
|
#define LOGW PLOGW
|
||||||
|
#define LOGE PLOGE
|
||||||
|
#define LOGF PLOGF
|
||||||
|
#define LOGN PLOGN
|
||||||
|
|
||||||
|
#define LOGV_(instanceId) PLOGV_(instanceId)
|
||||||
|
#define LOGD_(instanceId) PLOGD_(instanceId)
|
||||||
|
#define LOGI_(instanceId) PLOGI_(instanceId)
|
||||||
|
#define LOGW_(instanceId) PLOGW_(instanceId)
|
||||||
|
#define LOGE_(instanceId) PLOGE_(instanceId)
|
||||||
|
#define LOGF_(instanceId) PLOGF_(instanceId)
|
||||||
|
#define LOGN_(instanceId) PLOGN_(instanceId)
|
||||||
|
|
||||||
|
//////////////////////////////////////////////////////////////////////////
|
||||||
|
// Conditional logging macros
|
||||||
|
|
||||||
|
#define LOG_IF_(instanceId, severity, condition) PLOG_IF_(instanceId, severity, condition)
|
||||||
|
#define LOG_IF(severity, condition) PLOG_IF(severity, condition)
|
||||||
|
|
||||||
|
#define LOG_VERBOSE_IF(condition) PLOG_VERBOSE_IF(condition)
|
||||||
|
#define LOG_DEBUG_IF(condition) PLOG_DEBUG_IF(condition)
|
||||||
|
#define LOG_INFO_IF(condition) PLOG_INFO_IF(condition)
|
||||||
|
#define LOG_WARNING_IF(condition) PLOG_WARNING_IF(condition)
|
||||||
|
#define LOG_ERROR_IF(condition) PLOG_ERROR_IF(condition)
|
||||||
|
#define LOG_FATAL_IF(condition) PLOG_FATAL_IF(condition)
|
||||||
|
#define LOG_NONE_IF(condition) PLOG_NONE_IF(condition)
|
||||||
|
|
||||||
|
#define LOG_VERBOSE_IF_(instanceId, condition) PLOG_VERBOSE_IF_(instanceId, condition)
|
||||||
|
#define LOG_DEBUG_IF_(instanceId, condition) PLOG_DEBUG_IF_(instanceId, condition)
|
||||||
|
#define LOG_INFO_IF_(instanceId, condition) PLOG_INFO_IF_(instanceId, condition)
|
||||||
|
#define LOG_WARNING_IF_(instanceId, condition) PLOG_WARNING_IF_(instanceId, condition)
|
||||||
|
#define LOG_ERROR_IF_(instanceId, condition) PLOG_ERROR_IF_(instanceId, condition)
|
||||||
|
#define LOG_FATAL_IF_(instanceId, condition) PLOG_FATAL_IF_(instanceId, condition)
|
||||||
|
#define LOG_NONE_IF_(instanceId, condition) PLOG_NONE_IF_(instanceId, condition)
|
||||||
|
|
||||||
|
#define LOGV_IF(condition) PLOGV_IF(condition)
|
||||||
|
#define LOGD_IF(condition) PLOGD_IF(condition)
|
||||||
|
#define LOGI_IF(condition) PLOGI_IF(condition)
|
||||||
|
#define LOGW_IF(condition) PLOGW_IF(condition)
|
||||||
|
#define LOGE_IF(condition) PLOGE_IF(condition)
|
||||||
|
#define LOGF_IF(condition) PLOGF_IF(condition)
|
||||||
|
#define LOGN_IF(condition) PLOGN_IF(condition)
|
||||||
|
|
||||||
|
#define LOGV_IF_(instanceId, condition) PLOGV_IF_(instanceId, condition)
|
||||||
|
#define LOGD_IF_(instanceId, condition) PLOGD_IF_(instanceId, condition)
|
||||||
|
#define LOGI_IF_(instanceId, condition) PLOGI_IF_(instanceId, condition)
|
||||||
|
#define LOGW_IF_(instanceId, condition) PLOGW_IF_(instanceId, condition)
|
||||||
|
#define LOGE_IF_(instanceId, condition) PLOGE_IF_(instanceId, condition)
|
||||||
|
#define LOGF_IF_(instanceId, condition) PLOGF_IF_(instanceId, condition)
|
||||||
|
#define LOGN_IF_(instanceId, condition) PLOGN_IF_(instanceId, condition)
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <plog/Appenders/IAppender.h>
|
||||||
|
#include <plog/Util.h>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#ifdef PLOG_DEFAULT_INSTANCE // for backward compatibility
|
||||||
|
# define PLOG_DEFAULT_INSTANCE_ID PLOG_DEFAULT_INSTANCE
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef PLOG_DEFAULT_INSTANCE_ID
|
||||||
|
# define PLOG_DEFAULT_INSTANCE_ID 0
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
template<int instanceId>
|
||||||
|
class PLOG_LINKAGE Logger : public util::Singleton<Logger<instanceId> >, public IAppender
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
Logger(Severity maxSeverity = none) : m_maxSeverity(maxSeverity)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
Logger& addAppender(IAppender* appender)
|
||||||
|
{
|
||||||
|
assert(appender != this);
|
||||||
|
m_appenders.push_back(appender);
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
Severity getMaxSeverity() const
|
||||||
|
{
|
||||||
|
return m_maxSeverity;
|
||||||
|
}
|
||||||
|
|
||||||
|
void setMaxSeverity(Severity severity)
|
||||||
|
{
|
||||||
|
m_maxSeverity = severity;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool checkSeverity(Severity severity) const
|
||||||
|
{
|
||||||
|
return severity <= m_maxSeverity;
|
||||||
|
}
|
||||||
|
|
||||||
|
virtual void write(const Record& record) PLOG_OVERRIDE
|
||||||
|
{
|
||||||
|
if (checkSeverity(record.getSeverity()))
|
||||||
|
{
|
||||||
|
*this += record;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void operator+=(const Record& record)
|
||||||
|
{
|
||||||
|
for (std::vector<IAppender*>::iterator it = m_appenders.begin(); it != m_appenders.end(); ++it)
|
||||||
|
{
|
||||||
|
(*it)->write(record);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
Severity m_maxSeverity;
|
||||||
|
#ifdef _MSC_VER
|
||||||
|
# pragma warning(push)
|
||||||
|
# pragma warning(disable:4251) // needs to have dll-interface to be used by clients of class
|
||||||
|
#endif
|
||||||
|
std::vector<IAppender*> m_appenders;
|
||||||
|
#ifdef _MSC_VER
|
||||||
|
# pragma warning(pop)
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
|
||||||
|
template<int instanceId>
|
||||||
|
inline Logger<instanceId>* get()
|
||||||
|
{
|
||||||
|
return Logger<instanceId>::getInstance();
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Logger<PLOG_DEFAULT_INSTANCE_ID>* get()
|
||||||
|
{
|
||||||
|
return Logger<PLOG_DEFAULT_INSTANCE_ID>::getInstance();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,465 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <cstdarg>
|
||||||
|
#include <plog/Severity.h>
|
||||||
|
#include <plog/Util.h>
|
||||||
|
|
||||||
|
#ifdef __cplusplus_cli
|
||||||
|
#include <vcclr.h> // For PtrToStringChars
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
namespace detail
|
||||||
|
{
|
||||||
|
#if !defined(_MSC_VER) || _MSC_VER > 1400 // MSVC 2005 doesn't understand `enableIf`, so drop all `meta`
|
||||||
|
namespace meta
|
||||||
|
{
|
||||||
|
template<class T>
|
||||||
|
inline T& declval()
|
||||||
|
{
|
||||||
|
#ifdef __INTEL_COMPILER
|
||||||
|
# pragma warning(suppress: 327) // NULL reference is not allowed
|
||||||
|
#endif
|
||||||
|
return *reinterpret_cast<T*>(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
template<bool B, class T = void>
|
||||||
|
struct enableIf {};
|
||||||
|
|
||||||
|
template<class T>
|
||||||
|
struct enableIf<true, T> { typedef T type; };
|
||||||
|
|
||||||
|
struct No { char a[1]; };
|
||||||
|
struct Yes { char a[2]; };
|
||||||
|
|
||||||
|
template <class From, class To>
|
||||||
|
struct isConvertible
|
||||||
|
{
|
||||||
|
// `+ sizeof(U*)` is required for GCC 4.5-4.7
|
||||||
|
template<class U>
|
||||||
|
static typename enableIf<!!(sizeof(static_cast<To>(meta::declval<U>())) + sizeof(U*)), Yes>::type test(int);
|
||||||
|
|
||||||
|
template<class U>
|
||||||
|
static No test(...);
|
||||||
|
|
||||||
|
enum { value = sizeof(test<From>(0)) == sizeof(Yes) };
|
||||||
|
};
|
||||||
|
|
||||||
|
template <class T>
|
||||||
|
struct isConvertibleToString : isConvertible<T, std::string> {};
|
||||||
|
|
||||||
|
#if PLOG_ENABLE_WCHAR_INPUT
|
||||||
|
template <class T>
|
||||||
|
struct isConvertibleToWString : isConvertible<T, std::wstring> {};
|
||||||
|
#endif
|
||||||
|
|
||||||
|
template <class T>
|
||||||
|
struct isContainer
|
||||||
|
{
|
||||||
|
template<class U>
|
||||||
|
static typename meta::enableIf<!!(sizeof(
|
||||||
|
#if defined(_MSC_VER) && _MSC_VER < 1700 // MSVC 2010 doesn't understand `typename T::const_iterator`
|
||||||
|
meta::declval<U>().begin()) + sizeof(meta::declval<U>().end()
|
||||||
|
#else
|
||||||
|
typename U::const_iterator
|
||||||
|
#endif
|
||||||
|
)), Yes>::type test(int);
|
||||||
|
|
||||||
|
template<class U>
|
||||||
|
static No test(...);
|
||||||
|
|
||||||
|
enum { value = sizeof(test<T>(0)) == sizeof(Yes) };
|
||||||
|
};
|
||||||
|
|
||||||
|
// Detects `std::filesystem::path` and `boost::filesystem::path`. They look like containers
|
||||||
|
// but we don't want to treat them as containers, so we use this detector to filter them out.
|
||||||
|
template <class T>
|
||||||
|
struct isFilesystemPath
|
||||||
|
{
|
||||||
|
template<class U>
|
||||||
|
static typename meta::enableIf<!!(sizeof(meta::declval<U>().preferred_separator)), Yes>::type test(int);
|
||||||
|
|
||||||
|
template<class U>
|
||||||
|
static No test(...);
|
||||||
|
|
||||||
|
enum { value = sizeof(test<T>(0)) == sizeof(Yes) };
|
||||||
|
};
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
//////////////////////////////////////////////////////////////////////////
|
||||||
|
// Stream output operators as free functions
|
||||||
|
|
||||||
|
#if PLOG_ENABLE_WCHAR_INPUT
|
||||||
|
inline void operator<<(util::nostringstream& stream, const wchar_t* data)
|
||||||
|
{
|
||||||
|
data = data ? data : L"(null)";
|
||||||
|
|
||||||
|
# ifdef _WIN32
|
||||||
|
# if PLOG_CHAR_IS_UTF8
|
||||||
|
std::operator<<(stream, util::toNarrow(data, codePage::kUTF8));
|
||||||
|
# else
|
||||||
|
std::operator<<(stream, data);
|
||||||
|
# endif
|
||||||
|
# else
|
||||||
|
std::operator<<(stream, util::toNarrow(data));
|
||||||
|
# endif
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void operator<<(util::nostringstream& stream, wchar_t* data)
|
||||||
|
{
|
||||||
|
plog::detail::operator<<(stream, const_cast<const wchar_t*>(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void operator<<(util::nostringstream& stream, const std::wstring& data)
|
||||||
|
{
|
||||||
|
plog::detail::operator<<(stream, data.c_str());
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
inline void operator<<(util::nostringstream& stream, const char* data)
|
||||||
|
{
|
||||||
|
data = data ? data : "(null)";
|
||||||
|
|
||||||
|
#if defined(_WIN32) && defined(__BORLANDC__)
|
||||||
|
# if PLOG_CHAR_IS_UTF8
|
||||||
|
stream << data;
|
||||||
|
# else
|
||||||
|
stream << util::toWide(data);
|
||||||
|
# endif
|
||||||
|
#elif defined(_WIN32)
|
||||||
|
# if PLOG_CHAR_IS_UTF8
|
||||||
|
std::operator<<(stream, data);
|
||||||
|
# else
|
||||||
|
std::operator<<(stream, util::toWide(data));
|
||||||
|
# endif
|
||||||
|
#else
|
||||||
|
std::operator<<(stream, data);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void operator<<(util::nostringstream& stream, char* data)
|
||||||
|
{
|
||||||
|
plog::detail::operator<<(stream, const_cast<const char*>(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void operator<<(util::nostringstream& stream, const std::string& data)
|
||||||
|
{
|
||||||
|
plog::detail::operator<<(stream, data.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifdef __cpp_char8_t
|
||||||
|
inline void operator<<(util::nostringstream& stream, const char8_t* data)
|
||||||
|
{
|
||||||
|
# if PLOG_CHAR_IS_UTF8
|
||||||
|
plog::detail::operator<<(stream, reinterpret_cast<const char*>(data));
|
||||||
|
# else
|
||||||
|
plog::detail::operator<<(stream, util::toWide(reinterpret_cast<const char*>(data), codePage::kUTF8));
|
||||||
|
# endif
|
||||||
|
}
|
||||||
|
#endif //__cpp_char8_t
|
||||||
|
|
||||||
|
// Print `std::pair`
|
||||||
|
template<class T1, class T2>
|
||||||
|
inline void operator<<(util::nostringstream& stream, const std::pair<T1, T2>& data)
|
||||||
|
{
|
||||||
|
stream << data.first;
|
||||||
|
stream << ":";
|
||||||
|
stream << data.second;
|
||||||
|
}
|
||||||
|
|
||||||
|
#if defined(__clang__) || !defined(__GNUC__) || (__GNUC__ * 100 + __GNUC_MINOR__) >= 405 // skip for GCC < 4.5 due to https://gcc.gnu.org/bugzilla/show_bug.cgi?id=38600
|
||||||
|
#if !defined(_MSC_VER) || _MSC_VER > 1400 // MSVC 2005 doesn't understand `enableIf`, so drop all `meta`
|
||||||
|
// Print data that can be casted to `std::string`
|
||||||
|
template<class T>
|
||||||
|
inline typename meta::enableIf<meta::isConvertibleToString<T>::value, void>::type operator<<(util::nostringstream& stream, const T& data)
|
||||||
|
{
|
||||||
|
plog::detail::operator<<(stream, static_cast<std::string>(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
#if PLOG_ENABLE_WCHAR_INPUT
|
||||||
|
// Print data that can be casted to `std::wstring`
|
||||||
|
template<class T>
|
||||||
|
inline typename meta::enableIf<meta::isConvertibleToWString<T>::value, void>::type operator<<(util::nostringstream& stream, const T& data)
|
||||||
|
{
|
||||||
|
plog::detail::operator<<(stream, static_cast<std::wstring>(data));
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Print std containers
|
||||||
|
template<class T>
|
||||||
|
inline typename meta::enableIf<meta::isContainer<T>::value &&
|
||||||
|
!meta::isConvertibleToString<T>::value &&
|
||||||
|
#if PLOG_ENABLE_WCHAR_INPUT
|
||||||
|
!meta::isConvertibleToWString<T>::value &&
|
||||||
|
#endif
|
||||||
|
!meta::isFilesystemPath<T>::value, void>::type operator<<(util::nostringstream& stream, const T& data)
|
||||||
|
{
|
||||||
|
stream << "[";
|
||||||
|
|
||||||
|
for (typename T::const_iterator it = data.begin(); it != data.end();)
|
||||||
|
{
|
||||||
|
stream << *it;
|
||||||
|
|
||||||
|
if (++it == data.end())
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
stream << ", ";
|
||||||
|
}
|
||||||
|
|
||||||
|
stream << "]";
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef __cplusplus_cli
|
||||||
|
// Print managed C++ `System::String^`
|
||||||
|
inline void operator<<(util::nostringstream& stream, System::String^ data)
|
||||||
|
{
|
||||||
|
cli::pin_ptr<const System::Char> ptr = PtrToStringChars(data);
|
||||||
|
plog::detail::operator<<(stream, static_cast<const wchar_t*>(ptr));
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if PLOG_ENABLE_WCHAR_INPUT && (!defined(_MSC_VER) || _MSC_VER > 1400) // MSVC 2005 doesn't understand `enableIf`, so drop all `meta`
|
||||||
|
namespace meta
|
||||||
|
{
|
||||||
|
template<bool Value>
|
||||||
|
struct valueType { enum { value = Value }; };
|
||||||
|
|
||||||
|
template<class T, class Stream>
|
||||||
|
inline No operator<<(Stream&, const T&);
|
||||||
|
|
||||||
|
template<class T, class Stream>
|
||||||
|
struct isStreamable : valueType<sizeof(operator<<(meta::declval<Stream>(), meta::declval<const T>())) != sizeof(No)> {};
|
||||||
|
|
||||||
|
template<class Stream>
|
||||||
|
struct isStreamable<std::ios_base& PLOG_CDECL (std::ios_base&), Stream> : valueType<true> {};
|
||||||
|
|
||||||
|
template<class Stream, size_t N>
|
||||||
|
struct isStreamable<wchar_t[N], Stream> : valueType<false> {};
|
||||||
|
|
||||||
|
template<class Stream, size_t N>
|
||||||
|
struct isStreamable<const wchar_t[N], Stream> : valueType<false> {};
|
||||||
|
|
||||||
|
// meta doesn't work well for deleted functions and C++20 has `operator<<(std::ostream&, const wchar_t*) = delete` so explicitly define it
|
||||||
|
template<>
|
||||||
|
struct isStreamable<const wchar_t*, std::ostream> : valueType<false> {};
|
||||||
|
|
||||||
|
# ifdef __cpp_char8_t
|
||||||
|
// meta doesn't work well for deleted functions and C++20 has `operator<<(std::ostream&, const char8_t*) = delete` so explicitly define it
|
||||||
|
template<class Stream, size_t N>
|
||||||
|
struct isStreamable<char8_t[N], Stream> : valueType<false> {};
|
||||||
|
|
||||||
|
template<class Stream>
|
||||||
|
struct isStreamable<const char8_t*, Stream> : valueType<false> {};
|
||||||
|
# endif //__cpp_char8_t
|
||||||
|
}
|
||||||
|
|
||||||
|
# if PLOG_CHAR_IS_UTF8
|
||||||
|
// Print types that can be streamed into `std::owstringstream` but not into `std::ostringstream` when we use UTF-8 on Windows
|
||||||
|
template<class T>
|
||||||
|
inline typename meta::enableIf<meta::isStreamable<T, std::wostream>::value &&
|
||||||
|
!meta::isStreamable<T, std::ostream>::value &&
|
||||||
|
!meta::isConvertibleToWString<T>::value, void>::type operator<<(std::ostringstream& stream, const T& data)
|
||||||
|
{
|
||||||
|
std::wostringstream ss;
|
||||||
|
ss << data;
|
||||||
|
stream << ss.str();
|
||||||
|
}
|
||||||
|
# else
|
||||||
|
// Print types that can be streamed into `std::ostringstream` but not into `std::owstringstream` when we use `wchar_t` on Windows
|
||||||
|
template<class T>
|
||||||
|
inline typename meta::enableIf<meta::isStreamable<T, std::ostream>::value &&
|
||||||
|
!meta::isStreamable<T, std::wostream>::value &&
|
||||||
|
!meta::isConvertibleToString<T>::value, void>::type operator<<(std::wostringstream& stream, const T& data)
|
||||||
|
{
|
||||||
|
std::ostringstream ss;
|
||||||
|
ss << data;
|
||||||
|
stream << ss.str();
|
||||||
|
}
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
class Record
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
Record(Severity severity, const char* func, size_t line, const char* file, const void* object, int instanceId)
|
||||||
|
: m_severity(severity), m_tid(util::gettid()), m_object(object), m_line(line), m_func(func), m_file(file), m_instanceId(instanceId)
|
||||||
|
{
|
||||||
|
util::ftime(&m_time);
|
||||||
|
}
|
||||||
|
|
||||||
|
Record& ref()
|
||||||
|
{
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
//////////////////////////////////////////////////////////////////////////
|
||||||
|
// Stream output operators
|
||||||
|
|
||||||
|
Record& operator<<(char data)
|
||||||
|
{
|
||||||
|
char str[] = { data, 0 };
|
||||||
|
return *this << str;
|
||||||
|
}
|
||||||
|
|
||||||
|
#if PLOG_ENABLE_WCHAR_INPUT
|
||||||
|
Record& operator<<(wchar_t data)
|
||||||
|
{
|
||||||
|
wchar_t str[] = { data, 0 };
|
||||||
|
return *this << str;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
Record& operator<<(util::nostream& (PLOG_CDECL *data)(util::nostream&))
|
||||||
|
{
|
||||||
|
m_message << data;
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifdef QT_VERSION
|
||||||
|
Record& operator<<(const QString& data)
|
||||||
|
{
|
||||||
|
# if PLOG_CHAR_IS_UTF8
|
||||||
|
return *this << data.toStdString();
|
||||||
|
# else
|
||||||
|
return *this << data.toStdWString();
|
||||||
|
# endif
|
||||||
|
}
|
||||||
|
|
||||||
|
# if QT_VERSION < 0x060000
|
||||||
|
Record& operator<<(const QStringRef& data)
|
||||||
|
{
|
||||||
|
return *this << data.toString();
|
||||||
|
}
|
||||||
|
# endif
|
||||||
|
|
||||||
|
# ifdef QSTRINGVIEW_H
|
||||||
|
Record& operator<<(QStringView data)
|
||||||
|
{
|
||||||
|
return *this << data.toString();
|
||||||
|
}
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
template<typename T>
|
||||||
|
Record& operator<<(const T& data)
|
||||||
|
{
|
||||||
|
using namespace plog::detail;
|
||||||
|
|
||||||
|
m_message << data;
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifndef __cplusplus_cli
|
||||||
|
Record& printf(const char* format, ...)
|
||||||
|
{
|
||||||
|
using namespace util;
|
||||||
|
|
||||||
|
char* str = NULL;
|
||||||
|
va_list ap;
|
||||||
|
|
||||||
|
va_start(ap, format);
|
||||||
|
int len = vasprintf(&str, format, ap);
|
||||||
|
static_cast<void>(len);
|
||||||
|
va_end(ap);
|
||||||
|
|
||||||
|
*this << str;
|
||||||
|
free(str);
|
||||||
|
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
Record& printf(const wchar_t* format, ...)
|
||||||
|
{
|
||||||
|
using namespace util;
|
||||||
|
|
||||||
|
wchar_t* str = NULL;
|
||||||
|
va_list ap;
|
||||||
|
|
||||||
|
va_start(ap, format);
|
||||||
|
int len = vaswprintf(&str, format, ap);
|
||||||
|
static_cast<void>(len);
|
||||||
|
va_end(ap);
|
||||||
|
|
||||||
|
*this << str;
|
||||||
|
free(str);
|
||||||
|
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
#endif //__cplusplus_cli
|
||||||
|
|
||||||
|
//////////////////////////////////////////////////////////////////////////
|
||||||
|
// Getters
|
||||||
|
|
||||||
|
virtual const util::Time& getTime() const
|
||||||
|
{
|
||||||
|
return m_time;
|
||||||
|
}
|
||||||
|
|
||||||
|
virtual Severity getSeverity() const
|
||||||
|
{
|
||||||
|
return m_severity;
|
||||||
|
}
|
||||||
|
|
||||||
|
virtual unsigned int getTid() const
|
||||||
|
{
|
||||||
|
return m_tid;
|
||||||
|
}
|
||||||
|
|
||||||
|
virtual const void* getObject() const
|
||||||
|
{
|
||||||
|
return m_object;
|
||||||
|
}
|
||||||
|
|
||||||
|
virtual size_t getLine() const
|
||||||
|
{
|
||||||
|
return m_line;
|
||||||
|
}
|
||||||
|
|
||||||
|
virtual const util::nchar* getMessage() const
|
||||||
|
{
|
||||||
|
m_messageStr = m_message.str();
|
||||||
|
return m_messageStr.c_str();
|
||||||
|
}
|
||||||
|
|
||||||
|
virtual const char* getFunc() const
|
||||||
|
{
|
||||||
|
m_funcStr = util::processFuncName(m_func);
|
||||||
|
return m_funcStr.c_str();
|
||||||
|
}
|
||||||
|
|
||||||
|
virtual const char* getFile() const
|
||||||
|
{
|
||||||
|
return m_file;
|
||||||
|
}
|
||||||
|
|
||||||
|
virtual ~Record() // virtual destructor to satisfy -Wnon-virtual-dtor warning
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
virtual int getInstanceId() const
|
||||||
|
{
|
||||||
|
return m_instanceId;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
util::Time m_time;
|
||||||
|
const Severity m_severity;
|
||||||
|
const unsigned int m_tid;
|
||||||
|
const void* const m_object;
|
||||||
|
const size_t m_line;
|
||||||
|
util::nostringstream m_message;
|
||||||
|
const char* const m_func;
|
||||||
|
const char* const m_file;
|
||||||
|
const int m_instanceId;
|
||||||
|
mutable std::string m_funcStr;
|
||||||
|
mutable util::nstring m_messageStr;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <cctype>
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
enum Severity
|
||||||
|
{
|
||||||
|
none = 0,
|
||||||
|
fatal = 1,
|
||||||
|
error = 2,
|
||||||
|
warning = 3,
|
||||||
|
info = 4,
|
||||||
|
debug = 5,
|
||||||
|
verbose = 6
|
||||||
|
};
|
||||||
|
|
||||||
|
#ifdef _MSC_VER
|
||||||
|
# pragma warning(suppress: 26812) // Prefer 'enum class' over 'enum'
|
||||||
|
#endif
|
||||||
|
inline const char* severityToString(Severity severity)
|
||||||
|
{
|
||||||
|
switch (severity)
|
||||||
|
{
|
||||||
|
case fatal:
|
||||||
|
return "FATAL";
|
||||||
|
case error:
|
||||||
|
return "ERROR";
|
||||||
|
case warning:
|
||||||
|
return "WARN";
|
||||||
|
case info:
|
||||||
|
return "INFO";
|
||||||
|
case debug:
|
||||||
|
return "DEBUG";
|
||||||
|
case verbose:
|
||||||
|
return "VERB";
|
||||||
|
default:
|
||||||
|
return "NONE";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Severity severityFromString(const char* str)
|
||||||
|
{
|
||||||
|
switch (std::toupper(str[0]))
|
||||||
|
{
|
||||||
|
case 'F':
|
||||||
|
return fatal;
|
||||||
|
case 'E':
|
||||||
|
return error;
|
||||||
|
case 'W':
|
||||||
|
return warning;
|
||||||
|
case 'I':
|
||||||
|
return info;
|
||||||
|
case 'D':
|
||||||
|
return debug;
|
||||||
|
case 'V':
|
||||||
|
return verbose;
|
||||||
|
default:
|
||||||
|
return none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,635 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <cassert>
|
||||||
|
#include <cstring>
|
||||||
|
#include <cstdio>
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <sstream>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
|
||||||
|
#ifndef PLOG_ENABLE_WCHAR_INPUT
|
||||||
|
# ifdef _WIN32
|
||||||
|
# define PLOG_ENABLE_WCHAR_INPUT 1
|
||||||
|
# else
|
||||||
|
# define PLOG_ENABLE_WCHAR_INPUT 0
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
//////////////////////////////////////////////////////////////////////////
|
||||||
|
// PLOG_CHAR_IS_UTF8 specifies character encoding of `char` type. On *nix
|
||||||
|
// systems it's set to UTF-8 while on Windows in can be ANSI or UTF-8. It
|
||||||
|
// automatically detects `/utf-8` command line option in MSVC. Also it can
|
||||||
|
// be set manually if required.
|
||||||
|
// This option allows to support http://utf8everywhere.org approach.
|
||||||
|
|
||||||
|
#ifndef PLOG_CHAR_IS_UTF8
|
||||||
|
# if defined(_WIN32) && !defined(_UTF8)
|
||||||
|
# define PLOG_CHAR_IS_UTF8 0
|
||||||
|
# else
|
||||||
|
# define PLOG_CHAR_IS_UTF8 1
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
# if defined(PLOG_EXPORT)
|
||||||
|
# define PLOG_LINKAGE __declspec(dllexport)
|
||||||
|
# elif defined(PLOG_IMPORT)
|
||||||
|
# define PLOG_LINKAGE __declspec(dllimport)
|
||||||
|
# endif
|
||||||
|
# if defined(PLOG_GLOBAL)
|
||||||
|
# error "PLOG_GLOBAL isn't supported on Windows"
|
||||||
|
# endif
|
||||||
|
#else
|
||||||
|
# if defined(PLOG_GLOBAL)
|
||||||
|
# define PLOG_LINKAGE __attribute__ ((visibility ("default")))
|
||||||
|
# elif defined(PLOG_LOCAL)
|
||||||
|
# define PLOG_LINKAGE __attribute__ ((visibility ("hidden")))
|
||||||
|
# define PLOG_LINKAGE_HIDDEN PLOG_LINKAGE
|
||||||
|
# endif
|
||||||
|
# if defined(PLOG_EXPORT) || defined(PLOG_IMPORT)
|
||||||
|
# error "PLOG_EXPORT/PLOG_IMPORT is supported only on Windows"
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef PLOG_LINKAGE
|
||||||
|
# define PLOG_LINKAGE
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef PLOG_LINKAGE_HIDDEN
|
||||||
|
# define PLOG_LINKAGE_HIDDEN
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
# include <plog/WinApi.h>
|
||||||
|
# include <time.h>
|
||||||
|
# include <sys/timeb.h>
|
||||||
|
# include <io.h>
|
||||||
|
# include <share.h>
|
||||||
|
#else
|
||||||
|
# include <unistd.h>
|
||||||
|
# include <sys/time.h>
|
||||||
|
# if defined(__linux__) || defined(__FreeBSD__)
|
||||||
|
# include <sys/syscall.h>
|
||||||
|
# elif defined(__rtems__)
|
||||||
|
# include <rtems.h>
|
||||||
|
# endif
|
||||||
|
# if defined(_POSIX_THREADS)
|
||||||
|
# include <pthread.h>
|
||||||
|
# endif
|
||||||
|
# if PLOG_ENABLE_WCHAR_INPUT
|
||||||
|
# include <iconv.h>
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef __FREERTOS__ // There is no standard way to know if the code is compiled for FreeRTOS. We expect __FREERTOS__ macro to be defined in such case.
|
||||||
|
# include <FreeRTOS.h>
|
||||||
|
# include <semphr.h>
|
||||||
|
# include <task.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if PLOG_CHAR_IS_UTF8
|
||||||
|
# define PLOG_NSTR(x) x
|
||||||
|
#else
|
||||||
|
# define _PLOG_NSTR(x) L##x
|
||||||
|
# define PLOG_NSTR(x) _PLOG_NSTR(x)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
# define PLOG_CDECL __cdecl
|
||||||
|
#else
|
||||||
|
# define PLOG_CDECL
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if __cplusplus >= 201103L || defined(_MSC_VER) && _MSC_VER >= 1700
|
||||||
|
# define PLOG_OVERRIDE override
|
||||||
|
#else
|
||||||
|
# define PLOG_OVERRIDE
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
namespace util
|
||||||
|
{
|
||||||
|
#if PLOG_CHAR_IS_UTF8
|
||||||
|
typedef std::string nstring;
|
||||||
|
typedef std::ostringstream nostringstream;
|
||||||
|
typedef std::istringstream nistringstream;
|
||||||
|
typedef std::ostream nostream;
|
||||||
|
typedef char nchar;
|
||||||
|
#else
|
||||||
|
typedef std::wstring nstring;
|
||||||
|
typedef std::wostringstream nostringstream;
|
||||||
|
typedef std::wistringstream nistringstream;
|
||||||
|
typedef std::wostream nostream;
|
||||||
|
typedef wchar_t nchar;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
inline void localtime_s(struct tm* t, const time_t* time)
|
||||||
|
{
|
||||||
|
#if defined(_WIN32) && defined(__BORLANDC__)
|
||||||
|
::localtime_s(time, t);
|
||||||
|
#elif defined(_WIN32) && defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
|
||||||
|
*t = *::localtime(time);
|
||||||
|
#elif defined(_WIN32)
|
||||||
|
::localtime_s(t, time);
|
||||||
|
#else
|
||||||
|
::localtime_r(time, t);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void gmtime_s(struct tm* t, const time_t* time)
|
||||||
|
{
|
||||||
|
#if defined(_WIN32) && defined(__BORLANDC__)
|
||||||
|
::gmtime_s(time, t);
|
||||||
|
#elif defined(_WIN32) && defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
|
||||||
|
*t = *::gmtime(time);
|
||||||
|
#elif defined(_WIN32)
|
||||||
|
::gmtime_s(t, time);
|
||||||
|
#else
|
||||||
|
::gmtime_r(time, t);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
typedef timeb Time;
|
||||||
|
|
||||||
|
inline void ftime(Time* t)
|
||||||
|
{
|
||||||
|
::ftime(t);
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
struct Time
|
||||||
|
{
|
||||||
|
time_t time;
|
||||||
|
unsigned short millitm;
|
||||||
|
};
|
||||||
|
|
||||||
|
inline void ftime(Time* t)
|
||||||
|
{
|
||||||
|
timeval tv;
|
||||||
|
::gettimeofday(&tv, NULL);
|
||||||
|
|
||||||
|
t->time = tv.tv_sec;
|
||||||
|
t->millitm = static_cast<unsigned short>(tv.tv_usec / 1000);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
inline unsigned int gettid()
|
||||||
|
{
|
||||||
|
#if defined(__FREERTOS__) && defined(INCLUDE_xTaskGetCurrentTaskHandle)
|
||||||
|
return static_cast<unsigned int>(reinterpret_cast<uintptr_t>(xTaskGetCurrentTaskHandle()));
|
||||||
|
#elif defined(_WIN32)
|
||||||
|
return GetCurrentThreadId();
|
||||||
|
#elif defined(__linux__)
|
||||||
|
return static_cast<unsigned int>(::syscall(__NR_gettid));
|
||||||
|
#elif defined(__FreeBSD__)
|
||||||
|
long tid;
|
||||||
|
syscall(SYS_thr_self, &tid);
|
||||||
|
return static_cast<unsigned int>(tid);
|
||||||
|
#elif defined(__rtems__)
|
||||||
|
return rtems_task_self();
|
||||||
|
#elif defined(__APPLE__)
|
||||||
|
uint64_t tid64;
|
||||||
|
pthread_threadid_np(NULL, &tid64);
|
||||||
|
return static_cast<unsigned int>(tid64);
|
||||||
|
#else
|
||||||
|
return 0;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifndef _GNU_SOURCE
|
||||||
|
inline int vasprintf(char** strp, const char* format, va_list ap)
|
||||||
|
{
|
||||||
|
va_list ap_copy;
|
||||||
|
#if defined(_MSC_VER) && _MSC_VER <= 1600
|
||||||
|
ap_copy = ap; // there is no va_copy on Visual Studio 2010
|
||||||
|
#else
|
||||||
|
va_copy(ap_copy, ap);
|
||||||
|
#endif
|
||||||
|
#ifndef __STDC_SECURE_LIB__
|
||||||
|
int charCount = vsnprintf(NULL, 0, format, ap_copy);
|
||||||
|
#else
|
||||||
|
int charCount = _vscprintf(format, ap_copy);
|
||||||
|
#endif
|
||||||
|
va_end(ap_copy);
|
||||||
|
if (charCount < 0)
|
||||||
|
{
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t bufferCharCount = static_cast<size_t>(charCount) + 1;
|
||||||
|
|
||||||
|
char* str = static_cast<char*>(malloc(bufferCharCount));
|
||||||
|
if (!str)
|
||||||
|
{
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifndef __STDC_SECURE_LIB__
|
||||||
|
int retval = vsnprintf(str, bufferCharCount, format, ap);
|
||||||
|
#else
|
||||||
|
int retval = vsnprintf_s(str, bufferCharCount, static_cast<size_t>(-1), format, ap);
|
||||||
|
#endif
|
||||||
|
if (retval < 0)
|
||||||
|
{
|
||||||
|
free(str);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
*strp = str;
|
||||||
|
return retval;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
inline int vaswprintf(wchar_t** strp, const wchar_t* format, va_list ap)
|
||||||
|
{
|
||||||
|
#if defined(__BORLANDC__)
|
||||||
|
int charCount = 0x1000; // there is no _vscwprintf on Borland/Embarcadero
|
||||||
|
#else
|
||||||
|
int charCount = _vscwprintf(format, ap);
|
||||||
|
if (charCount < 0)
|
||||||
|
{
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
size_t bufferCharCount = static_cast<size_t>(charCount) + 1;
|
||||||
|
|
||||||
|
wchar_t* str = static_cast<wchar_t*>(malloc(bufferCharCount * sizeof(wchar_t)));
|
||||||
|
if (!str)
|
||||||
|
{
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
#if defined(__BORLANDC__)
|
||||||
|
int retval = vsnwprintf_s(str, bufferCharCount, format, ap);
|
||||||
|
#elif defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
|
||||||
|
int retval = _vsnwprintf(str, bufferCharCount, format, ap);
|
||||||
|
#else
|
||||||
|
int retval = _vsnwprintf_s(str, bufferCharCount, charCount, format, ap);
|
||||||
|
#endif
|
||||||
|
if (retval < 0)
|
||||||
|
{
|
||||||
|
free(str);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
*strp = str;
|
||||||
|
return retval;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
inline std::wstring toWide(const char* str, UINT cp = codePage::kChar)
|
||||||
|
{
|
||||||
|
size_t len = ::strlen(str);
|
||||||
|
std::wstring wstr(len, 0);
|
||||||
|
|
||||||
|
if (!wstr.empty())
|
||||||
|
{
|
||||||
|
int wlen = MultiByteToWideChar(cp, 0, str, static_cast<int>(len), &wstr[0], static_cast<int>(wstr.size()));
|
||||||
|
wstr.resize(wlen);
|
||||||
|
}
|
||||||
|
|
||||||
|
return wstr;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline std::wstring toWide(const std::string& str, UINT cp = codePage::kChar)
|
||||||
|
{
|
||||||
|
return toWide(str.c_str(), cp);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline const std::wstring& toWide(const std::wstring& str) // do nothing for already wide string
|
||||||
|
{
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline std::string toNarrow(const std::wstring& wstr, long page)
|
||||||
|
{
|
||||||
|
int len = WideCharToMultiByte(page, 0, wstr.c_str(), static_cast<int>(wstr.size()), 0, 0, 0, 0);
|
||||||
|
std::string str(len, 0);
|
||||||
|
|
||||||
|
if (!str.empty())
|
||||||
|
{
|
||||||
|
WideCharToMultiByte(page, 0, wstr.c_str(), static_cast<int>(wstr.size()), &str[0], len, 0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
#elif PLOG_ENABLE_WCHAR_INPUT
|
||||||
|
inline std::string toNarrow(const wchar_t* wstr)
|
||||||
|
{
|
||||||
|
size_t wlen = ::wcslen(wstr);
|
||||||
|
std::string str(wlen * sizeof(wchar_t), 0);
|
||||||
|
|
||||||
|
if (!str.empty())
|
||||||
|
{
|
||||||
|
const char* in = reinterpret_cast<const char*>(&wstr[0]);
|
||||||
|
char* out = &str[0];
|
||||||
|
size_t inBytes = wlen * sizeof(wchar_t);
|
||||||
|
size_t outBytes = str.size();
|
||||||
|
|
||||||
|
iconv_t cd = ::iconv_open("UTF-8", "WCHAR_T");
|
||||||
|
::iconv(cd, const_cast<char**>(&in), &inBytes, &out, &outBytes);
|
||||||
|
::iconv_close(cd);
|
||||||
|
|
||||||
|
str.resize(str.size() - outBytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
inline std::string processFuncName(const char* func)
|
||||||
|
{
|
||||||
|
#if (defined(_WIN32) && !defined(__MINGW32__)) || defined(__OBJC__)
|
||||||
|
return std::string(func);
|
||||||
|
#else
|
||||||
|
const char* funcBegin = func;
|
||||||
|
const char* funcEnd = ::strchr(funcBegin, '(');
|
||||||
|
int foundTemplate = 0;
|
||||||
|
|
||||||
|
if (!funcEnd)
|
||||||
|
{
|
||||||
|
return std::string(func);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const char* i = funcEnd - 1; i >= funcBegin; --i) // search backwards for the first space char
|
||||||
|
{
|
||||||
|
if (*i == '>')
|
||||||
|
{
|
||||||
|
foundTemplate++;
|
||||||
|
}
|
||||||
|
else if (*i == '<')
|
||||||
|
{
|
||||||
|
foundTemplate--;
|
||||||
|
}
|
||||||
|
else if (*i == ' ' && foundTemplate == 0)
|
||||||
|
{
|
||||||
|
funcBegin = i + 1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return std::string(funcBegin, funcEnd);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
inline const nchar* findExtensionDot(const nchar* fileName)
|
||||||
|
{
|
||||||
|
#if PLOG_CHAR_IS_UTF8
|
||||||
|
return std::strrchr(fileName, '.');
|
||||||
|
#else
|
||||||
|
return std::wcsrchr(fileName, L'.');
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void splitFileName(const nchar* fileName, nstring& fileNameNoExt, nstring& fileExt)
|
||||||
|
{
|
||||||
|
const nchar* dot = findExtensionDot(fileName);
|
||||||
|
|
||||||
|
if (dot)
|
||||||
|
{
|
||||||
|
fileNameNoExt.assign(fileName, dot);
|
||||||
|
fileExt.assign(dot + 1);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
fileNameNoExt.assign(fileName);
|
||||||
|
fileExt.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class PLOG_LINKAGE NonCopyable
|
||||||
|
{
|
||||||
|
protected:
|
||||||
|
NonCopyable()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
NonCopyable(const NonCopyable&);
|
||||||
|
NonCopyable& operator=(const NonCopyable&);
|
||||||
|
};
|
||||||
|
|
||||||
|
class PLOG_LINKAGE_HIDDEN File : NonCopyable
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
File() : m_file(-1)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
~File()
|
||||||
|
{
|
||||||
|
close();
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t open(const nstring& fileName)
|
||||||
|
{
|
||||||
|
#if defined(_WIN32) && (defined(__BORLANDC__) || defined(__MINGW32__))
|
||||||
|
m_file = ::_wsopen(toWide(fileName).c_str(), _O_CREAT | _O_WRONLY | _O_BINARY | _O_NOINHERIT, SH_DENYWR, _S_IREAD | _S_IWRITE);
|
||||||
|
#elif defined(_WIN32)
|
||||||
|
::_wsopen_s(&m_file, toWide(fileName).c_str(), _O_CREAT | _O_WRONLY | _O_BINARY | _O_NOINHERIT, _SH_DENYWR, _S_IREAD | _S_IWRITE);
|
||||||
|
#elif defined(O_CLOEXEC)
|
||||||
|
m_file = ::open(fileName.c_str(), O_CREAT | O_APPEND | O_WRONLY | O_CLOEXEC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
|
||||||
|
#else
|
||||||
|
m_file = ::open(fileName.c_str(), O_CREAT | O_APPEND | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
|
||||||
|
#endif
|
||||||
|
return seek(0, SEEK_END);
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t write(const void* buf, size_t count)
|
||||||
|
{
|
||||||
|
return m_file != -1 ? static_cast<size_t>(
|
||||||
|
#ifdef _WIN32
|
||||||
|
::_write(m_file, buf, static_cast<unsigned int>(count))
|
||||||
|
#else
|
||||||
|
::write(m_file, buf, count)
|
||||||
|
#endif
|
||||||
|
) : static_cast<size_t>(-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class CharType>
|
||||||
|
size_t write(const std::basic_string<CharType>& str)
|
||||||
|
{
|
||||||
|
return write(str.data(), str.size() * sizeof(CharType));
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t seek(size_t offset, int whence)
|
||||||
|
{
|
||||||
|
return m_file != -1 ? static_cast<size_t>(
|
||||||
|
#if defined(_WIN32) && (defined(__BORLANDC__) || defined(__MINGW32__))
|
||||||
|
::_lseek(m_file, static_cast<off_t>(offset), whence)
|
||||||
|
#elif defined(_WIN32)
|
||||||
|
::_lseeki64(m_file, static_cast<off_t>(offset), whence)
|
||||||
|
#else
|
||||||
|
::lseek(m_file, static_cast<off_t>(offset), whence)
|
||||||
|
#endif
|
||||||
|
) : static_cast<size_t>(-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
void close()
|
||||||
|
{
|
||||||
|
if (m_file != -1)
|
||||||
|
{
|
||||||
|
#ifdef _WIN32
|
||||||
|
::_close(m_file);
|
||||||
|
#else
|
||||||
|
::close(m_file);
|
||||||
|
#endif
|
||||||
|
m_file = -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static int unlink(const nstring& fileName)
|
||||||
|
{
|
||||||
|
#ifdef _WIN32
|
||||||
|
return ::_wunlink(toWide(fileName).c_str());
|
||||||
|
#else
|
||||||
|
return ::unlink(fileName.c_str());
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
static int rename(const nstring& oldFilename, const nstring& newFilename)
|
||||||
|
{
|
||||||
|
#ifdef _WIN32
|
||||||
|
return MoveFileW(toWide(oldFilename).c_str(), toWide(newFilename).c_str());
|
||||||
|
#else
|
||||||
|
return ::rename(oldFilename.c_str(), newFilename.c_str());
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
int m_file;
|
||||||
|
};
|
||||||
|
|
||||||
|
class PLOG_LINKAGE_HIDDEN Mutex : NonCopyable
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
Mutex()
|
||||||
|
{
|
||||||
|
#ifdef __FREERTOS__
|
||||||
|
m_sync = xSemaphoreCreateBinary();
|
||||||
|
xSemaphoreGive(m_sync);
|
||||||
|
#elif defined(_WIN32)
|
||||||
|
InitializeCriticalSection(&m_sync);
|
||||||
|
#elif defined(__rtems__)
|
||||||
|
rtems_semaphore_create(0, 1,
|
||||||
|
RTEMS_PRIORITY |
|
||||||
|
RTEMS_BINARY_SEMAPHORE |
|
||||||
|
RTEMS_INHERIT_PRIORITY, 1, &m_sync);
|
||||||
|
#elif defined(_POSIX_THREADS)
|
||||||
|
::pthread_mutex_init(&m_sync, 0);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
~Mutex()
|
||||||
|
{
|
||||||
|
#ifdef __FREERTOS__
|
||||||
|
vSemaphoreDelete(m_sync);
|
||||||
|
#elif defined(_WIN32)
|
||||||
|
DeleteCriticalSection(&m_sync);
|
||||||
|
#elif defined(__rtems__)
|
||||||
|
rtems_semaphore_delete(m_sync);
|
||||||
|
#elif defined(_POSIX_THREADS)
|
||||||
|
::pthread_mutex_destroy(&m_sync);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
friend class MutexLock;
|
||||||
|
|
||||||
|
private:
|
||||||
|
void lock()
|
||||||
|
{
|
||||||
|
#ifdef __FREERTOS__
|
||||||
|
xSemaphoreTake(m_sync, portMAX_DELAY);
|
||||||
|
#elif defined(_WIN32)
|
||||||
|
EnterCriticalSection(&m_sync);
|
||||||
|
#elif defined(__rtems__)
|
||||||
|
rtems_semaphore_obtain(m_sync, RTEMS_WAIT, RTEMS_NO_TIMEOUT);
|
||||||
|
#elif defined(_POSIX_THREADS)
|
||||||
|
::pthread_mutex_lock(&m_sync);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
void unlock()
|
||||||
|
{
|
||||||
|
#ifdef __FREERTOS__
|
||||||
|
xSemaphoreGive(m_sync);
|
||||||
|
#elif defined(_WIN32)
|
||||||
|
LeaveCriticalSection(&m_sync);
|
||||||
|
#elif defined(__rtems__)
|
||||||
|
rtems_semaphore_release(m_sync);
|
||||||
|
#elif defined(_POSIX_THREADS)
|
||||||
|
::pthread_mutex_unlock(&m_sync);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
#ifdef __FREERTOS__
|
||||||
|
SemaphoreHandle_t m_sync;
|
||||||
|
#elif defined(_WIN32)
|
||||||
|
CRITICAL_SECTION m_sync;
|
||||||
|
#elif defined(__rtems__)
|
||||||
|
rtems_id m_sync;
|
||||||
|
#elif defined(_POSIX_THREADS)
|
||||||
|
pthread_mutex_t m_sync;
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
|
||||||
|
class PLOG_LINKAGE_HIDDEN MutexLock : NonCopyable
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
MutexLock(Mutex& mutex) : m_mutex(mutex)
|
||||||
|
{
|
||||||
|
m_mutex.lock();
|
||||||
|
}
|
||||||
|
|
||||||
|
~MutexLock()
|
||||||
|
{
|
||||||
|
m_mutex.unlock();
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
Mutex& m_mutex;
|
||||||
|
};
|
||||||
|
|
||||||
|
template<class T>
|
||||||
|
#ifdef _WIN32
|
||||||
|
class Singleton : NonCopyable
|
||||||
|
#else
|
||||||
|
class PLOG_LINKAGE Singleton : NonCopyable
|
||||||
|
#endif
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
#if (defined(__clang__) || defined(__GNUC__) && __GNUC__ >= 8) && !defined(__BORLANDC__)
|
||||||
|
// This constructor is called before the `T` object is fully constructed, and
|
||||||
|
// pointers are not dereferenced anyway, so UBSan shouldn't check vptrs.
|
||||||
|
__attribute__((no_sanitize("vptr")))
|
||||||
|
#endif
|
||||||
|
Singleton()
|
||||||
|
{
|
||||||
|
assert(!m_instance);
|
||||||
|
m_instance = static_cast<T*>(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
~Singleton()
|
||||||
|
{
|
||||||
|
assert(m_instance);
|
||||||
|
m_instance = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static T* getInstance()
|
||||||
|
{
|
||||||
|
return m_instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
static T* m_instance;
|
||||||
|
};
|
||||||
|
|
||||||
|
template<class T>
|
||||||
|
T* Singleton<T>::m_instance = NULL;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
|
||||||
|
// These windows structs must be in a global namespace
|
||||||
|
struct HKEY__;
|
||||||
|
struct _SECURITY_ATTRIBUTES;
|
||||||
|
struct _CONSOLE_SCREEN_BUFFER_INFO;
|
||||||
|
struct _RTL_CRITICAL_SECTION;
|
||||||
|
|
||||||
|
namespace plog
|
||||||
|
{
|
||||||
|
typedef unsigned long DWORD;
|
||||||
|
typedef unsigned short WORD;
|
||||||
|
typedef unsigned char BYTE;
|
||||||
|
typedef unsigned int UINT;
|
||||||
|
typedef int BOOL;
|
||||||
|
typedef long LSTATUS;
|
||||||
|
typedef char* LPSTR;
|
||||||
|
typedef wchar_t* LPWSTR;
|
||||||
|
typedef const char* LPCSTR;
|
||||||
|
typedef const wchar_t* LPCWSTR;
|
||||||
|
typedef void* HANDLE;
|
||||||
|
typedef HKEY__* HKEY;
|
||||||
|
typedef size_t ULONG_PTR;
|
||||||
|
|
||||||
|
struct CRITICAL_SECTION
|
||||||
|
{
|
||||||
|
void* DebugInfo;
|
||||||
|
long LockCount;
|
||||||
|
long RecursionCount;
|
||||||
|
HANDLE OwningThread;
|
||||||
|
HANDLE LockSemaphore;
|
||||||
|
ULONG_PTR SpinCount;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct COORD
|
||||||
|
{
|
||||||
|
short X;
|
||||||
|
short Y;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct SMALL_RECT
|
||||||
|
{
|
||||||
|
short Left;
|
||||||
|
short Top;
|
||||||
|
short Right;
|
||||||
|
short Bottom;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct CONSOLE_SCREEN_BUFFER_INFO
|
||||||
|
{
|
||||||
|
COORD dwSize;
|
||||||
|
COORD dwCursorPosition;
|
||||||
|
WORD wAttributes;
|
||||||
|
SMALL_RECT srWindow;
|
||||||
|
COORD dwMaximumWindowSize;
|
||||||
|
};
|
||||||
|
|
||||||
|
namespace codePage
|
||||||
|
{
|
||||||
|
const UINT kActive = 0;
|
||||||
|
const UINT kUTF8 = 65001;
|
||||||
|
#if PLOG_CHAR_IS_UTF8
|
||||||
|
const UINT kChar = kUTF8;
|
||||||
|
#else
|
||||||
|
const UINT kChar = kActive;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace eventLog
|
||||||
|
{
|
||||||
|
const WORD kErrorType = 0x0001;
|
||||||
|
const WORD kWarningType = 0x0002;
|
||||||
|
const WORD kInformationType = 0x0004;
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace hkey
|
||||||
|
{
|
||||||
|
const HKEY kLocalMachine = reinterpret_cast<HKEY>(static_cast<ULONG_PTR>(0x80000002));
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace regSam
|
||||||
|
{
|
||||||
|
const DWORD kQueryValue = 0x0001;
|
||||||
|
const DWORD kSetValue = 0x0002;
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace regType
|
||||||
|
{
|
||||||
|
const DWORD kExpandSz = 2;
|
||||||
|
const DWORD kDword = 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace stdHandle
|
||||||
|
{
|
||||||
|
const DWORD kOutput = static_cast<DWORD>(-11);
|
||||||
|
const DWORD kErrorOutput = static_cast<DWORD>(-12);
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace foreground
|
||||||
|
{
|
||||||
|
const WORD kBlue = 0x0001;
|
||||||
|
const WORD kGreen = 0x0002;
|
||||||
|
const WORD kRed = 0x0004;
|
||||||
|
const WORD kIntensity = 0x0008;
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace background
|
||||||
|
{
|
||||||
|
const WORD kBlue = 0x0010;
|
||||||
|
const WORD kGreen = 0x0020;
|
||||||
|
const WORD kRed = 0x0040;
|
||||||
|
const WORD kIntensity = 0x0080;
|
||||||
|
}
|
||||||
|
|
||||||
|
extern "C"
|
||||||
|
{
|
||||||
|
__declspec(dllimport) int __stdcall MultiByteToWideChar(UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr, int cbMultiByte, LPWSTR lpWideCharStr, int cchWideChar);
|
||||||
|
__declspec(dllimport) int __stdcall WideCharToMultiByte(UINT CodePage, DWORD dwFlags, LPCWSTR lpWideCharStr, int cchWideChar, LPSTR lpMultiByteStr, int cbMultiByte, const char* lpDefaultChar, BOOL* lpUsedDefaultChar);
|
||||||
|
|
||||||
|
__declspec(dllimport) DWORD __stdcall GetCurrentThreadId();
|
||||||
|
|
||||||
|
__declspec(dllimport) BOOL __stdcall MoveFileW(LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName);
|
||||||
|
|
||||||
|
__declspec(dllimport) void __stdcall InitializeCriticalSection(_RTL_CRITICAL_SECTION* lpCriticalSection);
|
||||||
|
__declspec(dllimport) void __stdcall EnterCriticalSection(_RTL_CRITICAL_SECTION* lpCriticalSection);
|
||||||
|
__declspec(dllimport) void __stdcall LeaveCriticalSection(_RTL_CRITICAL_SECTION* lpCriticalSection);
|
||||||
|
__declspec(dllimport) void __stdcall DeleteCriticalSection(_RTL_CRITICAL_SECTION* lpCriticalSection);
|
||||||
|
|
||||||
|
__declspec(dllimport) HANDLE __stdcall RegisterEventSourceW(LPCWSTR lpUNCServerName, LPCWSTR lpSourceName);
|
||||||
|
__declspec(dllimport) BOOL __stdcall DeregisterEventSource(HANDLE hEventLog);
|
||||||
|
__declspec(dllimport) BOOL __stdcall ReportEventW(HANDLE hEventLog, WORD wType, WORD wCategory, DWORD dwEventID, void* lpUserSid, WORD wNumStrings, DWORD dwDataSize, LPCWSTR* lpStrings, void* lpRawData);
|
||||||
|
|
||||||
|
__declspec(dllimport) LSTATUS __stdcall RegCreateKeyExW(HKEY hKey, LPCWSTR lpSubKey, DWORD Reserved, LPWSTR lpClass, DWORD dwOptions, DWORD samDesired, _SECURITY_ATTRIBUTES* lpSecurityAttributes, HKEY* phkResult, DWORD* lpdwDisposition);
|
||||||
|
__declspec(dllimport) LSTATUS __stdcall RegSetValueExW(HKEY hKey, LPCWSTR lpValueName, DWORD Reserved, DWORD dwType, const BYTE* lpData, DWORD cbData);
|
||||||
|
__declspec(dllimport) LSTATUS __stdcall RegCloseKey(HKEY hKey);
|
||||||
|
__declspec(dllimport) LSTATUS __stdcall RegOpenKeyExW(HKEY hKey, LPCWSTR lpSubKey, DWORD ulOptions, DWORD samDesired, HKEY* phkResult);
|
||||||
|
__declspec(dllimport) LSTATUS __stdcall RegDeleteKeyW(HKEY hKey, LPCWSTR lpSubKey);
|
||||||
|
|
||||||
|
__declspec(dllimport) HANDLE __stdcall GetStdHandle(DWORD nStdHandle);
|
||||||
|
|
||||||
|
__declspec(dllimport) BOOL __stdcall WriteConsoleW(HANDLE hConsoleOutput, const void* lpBuffer, DWORD nNumberOfCharsToWrite, DWORD* lpNumberOfCharsWritten, void* lpReserved);
|
||||||
|
__declspec(dllimport) BOOL __stdcall GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, _CONSOLE_SCREEN_BUFFER_INFO* lpConsoleScreenBufferInfo);
|
||||||
|
__declspec(dllimport) BOOL __stdcall SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttributes);
|
||||||
|
|
||||||
|
__declspec(dllimport) void __stdcall OutputDebugStringW(LPCWSTR lpOutputString);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void InitializeCriticalSection(CRITICAL_SECTION* criticalSection)
|
||||||
|
{
|
||||||
|
plog::InitializeCriticalSection(reinterpret_cast<_RTL_CRITICAL_SECTION*>(criticalSection));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void EnterCriticalSection(CRITICAL_SECTION* criticalSection)
|
||||||
|
{
|
||||||
|
plog::EnterCriticalSection(reinterpret_cast<_RTL_CRITICAL_SECTION*>(criticalSection));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void LeaveCriticalSection(CRITICAL_SECTION* criticalSection)
|
||||||
|
{
|
||||||
|
plog::LeaveCriticalSection(reinterpret_cast<_RTL_CRITICAL_SECTION*>(criticalSection));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void DeleteCriticalSection(CRITICAL_SECTION* criticalSection)
|
||||||
|
{
|
||||||
|
plog::DeleteCriticalSection(reinterpret_cast<_RTL_CRITICAL_SECTION*>(criticalSection));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline BOOL GetConsoleScreenBufferInfo(HANDLE consoleOutput, CONSOLE_SCREEN_BUFFER_INFO* consoleScreenBufferInfo)
|
||||||
|
{
|
||||||
|
return plog::GetConsoleScreenBufferInfo(consoleOutput, reinterpret_cast<_CONSOLE_SCREEN_BUFFER_INFO*>(consoleScreenBufferInfo));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif // _WIN32
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -1,4 +0,0 @@
|
|||||||
/scanvalue
|
|
||||||
/scankey
|
|
||||||
/parser
|
|
||||||
/*.so.*
|
|
||||||
@@ -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}
|
|
||||||
)
|
|
||||||
@@ -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
@@ -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
|
|
||||||
@@ -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
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
Copyright (c) 2020 rxi
|
|
||||||
|
|
||||||
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.
|
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
MIT License
|
MIT License
|
||||||
|
|
||||||
Copyright (c) 2024-2025, CK Tan
|
Copyright (c) 2022 Sergey Podobry
|
||||||
https://github.com/cktan/tomlc17
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
@@ -19,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
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
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
SOFTWARE.
|
SOFTWARE.
|
||||||
@@ -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.
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
# src/agent/CMakeLists.txt
|
|
||||||
|
|
||||||
target_include_directories(agent PRIVATE ${CMAKE_SOURCE_DIR}/includes/tomlc17)
|
|
||||||
|
|
||||||
target_link_libraries(agent PRIVATE shlwapi tomlc17)
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
#ifndef DATAUTILS_H
|
|
||||||
#define DATAUTILS_H
|
|
||||||
|
|
||||||
#include <string.h>
|
|
||||||
#include "InjectParameters.h"
|
|
||||||
#include "tomlc17.h"
|
|
||||||
#include "log.h"
|
|
||||||
|
|
||||||
typedef struct _InjectionInfo {
|
|
||||||
char BootstrapAPIPath[INJECT_PATH_MAX];
|
|
||||||
char JuiceLoaderJarPath[INJECT_PATH_MAX];
|
|
||||||
char JuiceLoaderLibPath[INJECT_PATH_MAX];
|
|
||||||
char EntryJarPath[INJECT_PATH_MAX];
|
|
||||||
char EntryClass[INJECT_PATH_MAX];
|
|
||||||
char EntryMethod[INJECT_PATH_MAX];
|
|
||||||
} InjectionInfoType;
|
|
||||||
extern InjectionInfoType InjectionInfo;
|
|
||||||
|
|
||||||
void safe_copy(char *dest, const char *src, size_t dest_size);
|
|
||||||
bool ReadInjectionInfo(toml_result_t result, InjectParameters* params);
|
|
||||||
|
|
||||||
#endif // DATAUTILS_H
|
|
||||||
@@ -1,313 +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 "GlobalUtils.h"
|
|
||||||
#include "shlwapi.h"
|
|
||||||
#include "tomlc17.h"
|
|
||||||
#include "datautils.h"
|
|
||||||
|
|
||||||
#define WIN_X64
|
|
||||||
extern HINSTANCE hAppInstance;
|
|
||||||
|
|
||||||
InjectionInfoType InjectionInfo;
|
|
||||||
|
|
||||||
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);
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
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);
|
|
||||||
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 bootstrap-api jar...");
|
|
||||||
(*jvmti)->AddToSystemClassLoaderSearch(jvmti, InjectionInfo.BootstrapAPIPath);
|
|
||||||
log_info("injected bootstrap-api jar");
|
|
||||||
|
|
||||||
log_info("injecting loader jar...");
|
|
||||||
(*jvmti)->AddToSystemClassLoaderSearch(jvmti, InjectionInfo.JuiceLoaderJarPath);
|
|
||||||
log_info("injected loader jar");
|
|
||||||
|
|
||||||
// Invoke loader.init(JuiceLoaderLibPath, EntryJarPath)
|
|
||||||
log_info("invoking loader init()...");
|
|
||||||
log_info("============ Loader Info ============\n");
|
|
||||||
jclass cls = (*env)->FindClass(env, "cn/xiaozhou233/juiceloader/JuiceLoader");
|
|
||||||
if (cls == NULL) {
|
|
||||||
log_error("FindClass JuiceLoader 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.JuiceLoaderLibPath),
|
|
||||||
(*env)->NewStringUTF(env, InjectionInfo.EntryJarPath),
|
|
||||||
(*env)->NewStringUTF(env, InjectionInfo.EntryClass),
|
|
||||||
(*env)->NewStringUTF(env, InjectionInfo.EntryMethod));
|
|
||||||
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);
|
|
||||||
|
|
||||||
// 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 ((*jvm)->GetEnv(jvm, (void **)&env, JNI_VERSION_1_6) == 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
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// =========================================================== ///
|
|
||||||
/// Inject Method: JVM Options -agentpath
|
|
||||||
|
|
||||||
/// =========================================================== ///
|
|
||||||
/// Function: vm_init
|
|
||||||
/// Description: Called when the JVM is fully initialized. This is a callback function.
|
|
||||||
/// =========================================================== ///
|
|
||||||
static char *agentpath_options = NULL;
|
|
||||||
static void JNICALL vm_init(jvmtiEnv *jvmti, JNIEnv *env, jthread thread) {
|
|
||||||
log_info("vminit: VM fully initialized!");
|
|
||||||
log_info("Use options: %s", agentpath_options);
|
|
||||||
|
|
||||||
log_info("JNIEnv: %p", env);
|
|
||||||
log_info("jvmtiEnv: %p", jvmti);
|
|
||||||
|
|
||||||
log_info("Version: %d", (*env)->GetVersion(env));
|
|
||||||
|
|
||||||
//TODO: Impl vm_init and load agent
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
/// =========================================================== ///
|
|
||||||
/// 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) {
|
|
||||||
agentpath_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;
|
|
||||||
}
|
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
/*
|
|
||||||
Author: xiaozhou233 (xiaozhou233@vip.qq.com)
|
|
||||||
File: datautils.c
|
|
||||||
Desc: data utils
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
|
||||||
#include "datautils.h"
|
|
||||||
#include <stdio.h>
|
|
||||||
#include <string.h>
|
|
||||||
#include "tomlc17.h"
|
|
||||||
|
|
||||||
void safe_copy(char *dest, const char *src, size_t dest_size) {
|
|
||||||
if (!dest || dest_size == 0) return;
|
|
||||||
strncpy(dest, src, dest_size - 1);
|
|
||||||
dest[dest_size - 1] = '\0';
|
|
||||||
}
|
|
||||||
|
|
||||||
bool ReadInjectionInfo(toml_result_t result, InjectParameters* params) {
|
|
||||||
toml_datum_t InjectionTree = toml_seek(result.toptab, "Injection");
|
|
||||||
|
|
||||||
// ======= BootstrapAPIPath =======
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
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 =======
|
|
||||||
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 =======
|
|
||||||
|
|
||||||
// ======= JuiceLoaderLibPath =======
|
|
||||||
toml_datum_t JuiceLoaderLibPath = toml_seek(InjectionTree, "JuiceLoaderLibPath");
|
|
||||||
char JuiceLoaderLibPathStr[INJECT_PATH_MAX];
|
|
||||||
if (JuiceLoaderLibPath.type != TOML_STRING) {
|
|
||||||
log_error("JuiceLoaderLibPath is not a string.");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (JuiceLoaderLibPath.u.s == NULL || strlen(JuiceLoaderLibPath.u.s) == 0) {
|
|
||||||
sprintf(JuiceLoaderLibPathStr, "%s\\libjuiceloader.dll", params->ConfigDir);
|
|
||||||
} else {
|
|
||||||
sprintf(JuiceLoaderLibPathStr, "%s", JuiceLoaderLibPath.u.s);
|
|
||||||
}
|
|
||||||
safe_copy(InjectionInfo.JuiceLoaderLibPath, JuiceLoaderLibPathStr, INJECT_PATH_MAX);
|
|
||||||
// ======= JuiceLoaderLibPath =======
|
|
||||||
|
|
||||||
// ======= Entry =======
|
|
||||||
toml_datum_t EntryJarPath = toml_seek(InjectionTree, "EntryJarPath");
|
|
||||||
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");
|
|
||||||
if (EntryClass.type != TOML_STRING) {
|
|
||||||
log_error("EntryClass is not a string.");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (EntryClass.u.s == NULL || strlen(EntryClass.u.s) == 0) {
|
|
||||||
safe_copy(InjectionInfo.EntryClass, "cn.xiaozhou233.juiceloader.entry.Entry", INJECT_PATH_MAX);
|
|
||||||
} else {
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
# src/injector/CMakeLists.txt
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
/* DO NOT EDIT THIS FILE - it is machine generated */
|
|
||||||
#include <jni.h>
|
|
||||||
/* Header for class cn_xiaozhou233_juiceagent_injector_InjectorNative */
|
|
||||||
|
|
||||||
#ifndef _Included_cn_xiaozhou233_juiceagent_injector_InjectorNative
|
|
||||||
#define _Included_cn_xiaozhou233_juiceagent_injector_InjectorNative
|
|
||||||
#ifdef __cplusplus
|
|
||||||
extern "C" {
|
|
||||||
#endif
|
|
||||||
/*
|
|
||||||
* Class: cn_xiaozhou233_juiceagent_injector_InjectorNative
|
|
||||||
* Method: inject
|
|
||||||
* Signature: (ILjava/lang/String;)Z
|
|
||||||
*/
|
|
||||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorNative_inject__ILjava_lang_String_2
|
|
||||||
(JNIEnv *, jobject, jint, jstring);
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Class: cn_xiaozhou233_juiceagent_injector_InjectorNative
|
|
||||||
* Method: inject
|
|
||||||
* Signature: (ILjava/lang/String;Ljava/lang/String;)Z
|
|
||||||
*/
|
|
||||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorNative_inject__ILjava_lang_String_2Ljava_lang_String_2
|
|
||||||
(JNIEnv *, jobject, jint, jstring, jstring);
|
|
||||||
|
|
||||||
#ifdef __cplusplus
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
#endif
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
#ifndef INJECTOR_UTILS_H
|
|
||||||
#define INJECTOR_UTILS_H
|
|
||||||
|
|
||||||
#include "windows.h"
|
|
||||||
|
|
||||||
WORD get_pe_machine(LPVOID, DWORD);
|
|
||||||
BOOL has_reflective_loader_export(LPVOID, DWORD);
|
|
||||||
const char* machine_to_str(WORD);
|
|
||||||
|
|
||||||
#endif
|
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
#include "InjectorUtils.h"
|
|
||||||
|
|
||||||
/* Helpers: parse PE header to get Machine and check for ReflectiveLoader export */
|
|
||||||
|
|
||||||
/* return IMAGE_FILE_MACHINE_* value or 0 on error */
|
|
||||||
WORD get_pe_machine(LPVOID buffer, DWORD length) {
|
|
||||||
if (!buffer || length < sizeof(IMAGE_DOS_HEADER)) return 0;
|
|
||||||
PIMAGE_DOS_HEADER dos = (PIMAGE_DOS_HEADER)buffer;
|
|
||||||
if (dos->e_magic != IMAGE_DOS_SIGNATURE) return 0;
|
|
||||||
if ((DWORD)dos->e_lfanew + sizeof(IMAGE_NT_HEADERS) > length) return 0;
|
|
||||||
PIMAGE_NT_HEADERS nt = (PIMAGE_NT_HEADERS)((BYTE*)buffer + dos->e_lfanew);
|
|
||||||
if (nt->Signature != IMAGE_NT_SIGNATURE) return 0;
|
|
||||||
return nt->FileHeader.Machine;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* return TRUE if export table contains "ReflectiveLoader" */
|
|
||||||
BOOL has_reflective_loader_export(LPVOID buffer, DWORD length) {
|
|
||||||
if (!buffer || length < sizeof(IMAGE_DOS_HEADER)) return FALSE;
|
|
||||||
PIMAGE_DOS_HEADER dos = (PIMAGE_DOS_HEADER)buffer;
|
|
||||||
if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
|
|
||||||
PIMAGE_NT_HEADERS nt = (PIMAGE_NT_HEADERS)((BYTE*)buffer + dos->e_lfanew);
|
|
||||||
if (nt->Signature != IMAGE_NT_SIGNATURE) return FALSE;
|
|
||||||
|
|
||||||
DWORD exportRVA = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
|
|
||||||
DWORD exportSize = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
|
|
||||||
if (!exportRVA || exportSize == 0) return FALSE;
|
|
||||||
|
|
||||||
// Need to convert RVA -> raw offset: iterate sections
|
|
||||||
PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(nt);
|
|
||||||
WORD numberOfSections = nt->FileHeader.NumberOfSections;
|
|
||||||
DWORD exportOffset = 0;
|
|
||||||
for (WORD i = 0; i < numberOfSections; ++i) {
|
|
||||||
DWORD va = section[i].VirtualAddress;
|
|
||||||
DWORD vs = section[i].Misc.VirtualSize;
|
|
||||||
DWORD ptr = section[i].PointerToRawData;
|
|
||||||
DWORD size = section[i].SizeOfRawData;
|
|
||||||
if (exportRVA >= va && exportRVA < va + vs) {
|
|
||||||
exportOffset = ptr + (exportRVA - va);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!exportOffset) return FALSE;
|
|
||||||
if ((DWORD)exportOffset + sizeof(IMAGE_EXPORT_DIRECTORY) > length) return FALSE;
|
|
||||||
|
|
||||||
PIMAGE_EXPORT_DIRECTORY exp = (PIMAGE_EXPORT_DIRECTORY)((BYTE*)buffer + exportOffset);
|
|
||||||
if (exp->NumberOfNames == 0) return FALSE;
|
|
||||||
|
|
||||||
// locate arrays
|
|
||||||
DWORD addrOfNamesRVA = exp->AddressOfNames;
|
|
||||||
DWORD addrOfNameOrdinalsRVA = exp->AddressOfNameOrdinals;
|
|
||||||
if (!addrOfNamesRVA || !addrOfNameOrdinalsRVA) return FALSE;
|
|
||||||
|
|
||||||
// find raw offsets for these arrays
|
|
||||||
DWORD namesOffset = 0;
|
|
||||||
DWORD ordinalsOffset = 0;
|
|
||||||
for (WORD i = 0; i < numberOfSections; ++i) {
|
|
||||||
DWORD va = section[i].VirtualAddress;
|
|
||||||
DWORD vs = section[i].Misc.VirtualSize;
|
|
||||||
DWORD ptr = section[i].PointerToRawData;
|
|
||||||
if (addrOfNamesRVA >= va && addrOfNamesRVA < va + vs) {
|
|
||||||
namesOffset = ptr + (addrOfNamesRVA - va);
|
|
||||||
}
|
|
||||||
if (addrOfNameOrdinalsRVA >= va && addrOfNameOrdinalsRVA < va + vs) {
|
|
||||||
ordinalsOffset = ptr + (addrOfNameOrdinalsRVA - va);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!namesOffset || !ordinalsOffset) return FALSE;
|
|
||||||
if ((DWORD)namesOffset + exp->NumberOfNames * sizeof(DWORD) > length) return FALSE;
|
|
||||||
if ((DWORD)ordinalsOffset + exp->NumberOfNames * sizeof(WORD) > length) return FALSE;
|
|
||||||
|
|
||||||
// iterate names
|
|
||||||
for (DWORD i = 0; i < exp->NumberOfNames; ++i) {
|
|
||||||
DWORD nameRVA = *(DWORD*)((BYTE*)buffer + namesOffset + i * sizeof(DWORD));
|
|
||||||
// convert nameRVA to raw offset
|
|
||||||
DWORD nameOffset = 0;
|
|
||||||
for (WORD s = 0; s < numberOfSections; ++s) {
|
|
||||||
DWORD va = section[s].VirtualAddress;
|
|
||||||
DWORD vs = section[s].Misc.VirtualSize;
|
|
||||||
DWORD ptr = section[s].PointerToRawData;
|
|
||||||
if (nameRVA >= va && nameRVA < va + vs) {
|
|
||||||
nameOffset = ptr + (nameRVA - va);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!nameOffset) continue;
|
|
||||||
if ((DWORD)nameOffset >= length) continue;
|
|
||||||
char *name = (char*)((BYTE*)buffer + nameOffset);
|
|
||||||
// safe compare - ensure string is within buffer
|
|
||||||
size_t maxlen = length - nameOffset;
|
|
||||||
if (strncasecmp(name, "ReflectiveLoader", maxlen) == 0) return TRUE;
|
|
||||||
}
|
|
||||||
return FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Pretty-print machine */
|
|
||||||
const char* machine_to_str(WORD machine) {
|
|
||||||
switch(machine) {
|
|
||||||
case IMAGE_FILE_MACHINE_I386: return "x86 (IMAGE_FILE_MACHINE_I386)";
|
|
||||||
case IMAGE_FILE_MACHINE_AMD64: return "x64 (IMAGE_FILE_MACHINE_AMD64)";
|
|
||||||
case IMAGE_FILE_MACHINE_ARM: return "ARM";
|
|
||||||
case IMAGE_FILE_MACHINE_ARM64: return "ARM64";
|
|
||||||
default: return "Unknown";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
# src/loader/CMakeLists.txt
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
#ifndef JUICELOADER_H
|
|
||||||
#define JUICELOADER_H
|
|
||||||
|
|
||||||
#include <jni.h>
|
|
||||||
#include <jvmti.h>
|
|
||||||
|
|
||||||
struct _JuiceLoaderNative {
|
|
||||||
JavaVM *jvm;
|
|
||||||
jvmtiEnv *jvmti;
|
|
||||||
JNIEnv *env;
|
|
||||||
} JuiceLoaderNative;
|
|
||||||
|
|
||||||
|
|
||||||
#endif
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
/* DO NOT EDIT THIS FILE - it is machine generated */
|
|
||||||
#include <jni.h>
|
|
||||||
/* Header for class cn_xiaozhou233_juiceloader_JuiceLoaderNative */
|
|
||||||
|
|
||||||
#ifndef _Included_cn_xiaozhou233_juiceloader_JuiceLoaderNative
|
|
||||||
#define _Included_cn_xiaozhou233_juiceloader_JuiceLoaderNative
|
|
||||||
#ifdef __cplusplus
|
|
||||||
extern "C" {
|
|
||||||
#endif
|
|
||||||
/*
|
|
||||||
* Class: cn_xiaozhou233_juiceloader_JuiceLoaderNative
|
|
||||||
* Method: init
|
|
||||||
* Signature: ()Z
|
|
||||||
*/
|
|
||||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoaderNative_init
|
|
||||||
(JNIEnv *, jobject);
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Class: cn_xiaozhou233_juiceloader_JuiceLoaderNative
|
|
||||||
* Method: injectJar
|
|
||||||
* Signature: (Ljava/lang/String;)Z
|
|
||||||
*/
|
|
||||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoaderNative_injectJar
|
|
||||||
(JNIEnv *, jobject, jstring);
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Class: cn_xiaozhou233_juiceloader_JuiceLoaderNative
|
|
||||||
* Method: redefineClass
|
|
||||||
* Signature: (Ljava/lang/Class;[BI)Z
|
|
||||||
*/
|
|
||||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoaderNative_redefineClass__Ljava_lang_Class_2_3BI
|
|
||||||
(JNIEnv *, jobject, jclass, jbyteArray, jint);
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Class: cn_xiaozhou233_juiceloader_JuiceLoaderNative
|
|
||||||
* Method: redefineClass
|
|
||||||
* Signature: (Ljava/lang/String;[BI)Z
|
|
||||||
*/
|
|
||||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoaderNative_redefineClass__Ljava_lang_String_2_3BI
|
|
||||||
(JNIEnv *, jobject, jstring, jbyteArray, jint);
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Class: cn_xiaozhou233_juiceloader_JuiceLoaderNative
|
|
||||||
* Method: getLoadedClasses
|
|
||||||
* Signature: ()[Ljava/lang/Class;
|
|
||||||
*/
|
|
||||||
JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoaderNative_getLoadedClasses
|
|
||||||
(JNIEnv *, jobject);
|
|
||||||
|
|
||||||
#ifdef __cplusplus
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
#endif
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
#ifndef JUICELOADER_UTILS_H
|
|
||||||
#define JUICELOADER_UTILS_H
|
|
||||||
|
|
||||||
#include "jvmti.h"
|
|
||||||
|
|
||||||
char* get_method_fullname(jvmtiEnv*, JNIEnv*, jthread, jmethodID);
|
|
||||||
|
|
||||||
#endif
|
|
||||||
@@ -1,222 +0,0 @@
|
|||||||
#include "windows.h"
|
|
||||||
#include "JuiceLoaderNative.h"
|
|
||||||
#include "jvmti.h"
|
|
||||||
#include "log.h"
|
|
||||||
#include "JuiceLoaderUtils.h"
|
|
||||||
#include "JuiceLoader.h"
|
|
||||||
|
|
||||||
#define LOG_PREFIX "[JuiceLoader]"
|
|
||||||
static void check_jvmti_error(jvmtiEnv *j, jvmtiError err, const char *msg) {
|
|
||||||
if (err != JVMTI_ERROR_NONE) {
|
|
||||||
char *errname = NULL;
|
|
||||||
(*j)->GetErrorName(j, err, &errname);
|
|
||||||
log_error("JVMTI ERROR: %s: %d (%s)", msg, err, (errname==NULL?"Unknown":errname));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Method entry callback */
|
|
||||||
static void JNICALL callbackMethodEntry(jvmtiEnv *j, JNIEnv *env, jthread thread, jmethodID method) {
|
|
||||||
char *fullname = get_method_fullname(j, env, thread, method);
|
|
||||||
if (fullname) {
|
|
||||||
log_info("ENTER: %s", fullname);
|
|
||||||
free(fullname);
|
|
||||||
} else {
|
|
||||||
log_warn("ENTER: <unknown method>");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
int setup(JNIEnv *env) {
|
|
||||||
log_is_log_filename(false);
|
|
||||||
log_is_log_line(false);
|
|
||||||
log_is_log_time(false);
|
|
||||||
log_set_level(LOG_DEBUG);
|
|
||||||
|
|
||||||
log_info("[*] libjuiceloader Version %d.%d Build %d", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR, PROJECT_BUILD_NUMBER);
|
|
||||||
|
|
||||||
log_info("%s setup!", LOG_PREFIX);
|
|
||||||
{// Get JavaVM
|
|
||||||
if (JNI_GetCreatedJavaVMs(&JuiceLoaderNative.jvm, 1, NULL) != JNI_OK || !JuiceLoaderNative.jvm) {
|
|
||||||
log_error("%s JNI_GetCreatedJavaVMs failed", LOG_PREFIX);
|
|
||||||
return 1;
|
|
||||||
} else {
|
|
||||||
log_info("%s JNI_GetCreatedJavaVMs success", LOG_PREFIX);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get JNIEnv
|
|
||||||
if ((*JuiceLoaderNative.jvm)->AttachCurrentThread(JuiceLoaderNative.jvm, (void **)&JuiceLoaderNative.env, NULL) != JNI_OK) {
|
|
||||||
log_error("%s AttachCurrentThread failed", LOG_PREFIX);
|
|
||||||
return 1;
|
|
||||||
} else {
|
|
||||||
log_info("%s AttachCurrentThread success", LOG_PREFIX);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Debug: JVM version
|
|
||||||
jint version = (*JuiceLoaderNative.env)->GetVersion(JuiceLoaderNative.env);
|
|
||||||
log_debug("%s JVM version: 0x%x", LOG_PREFIX, version);
|
|
||||||
|
|
||||||
jint res = (*JuiceLoaderNative.jvm)->GetEnv(JuiceLoaderNative.jvm, (void**)&JuiceLoaderNative.jvmti, JVMTI_VERSION_1_2);
|
|
||||||
if (res != JNI_OK || JuiceLoaderNative.jvmti == NULL) {
|
|
||||||
log_error("%s GetEnv failed", LOG_PREFIX);
|
|
||||||
return 1;
|
|
||||||
} else {
|
|
||||||
log_info("%s GetEnv success", LOG_PREFIX);
|
|
||||||
}}
|
|
||||||
log_info("%s Enabled JVMTI.");
|
|
||||||
|
|
||||||
jvmtiError err;
|
|
||||||
// jvmtiEventCallbacks callbacks;
|
|
||||||
|
|
||||||
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;
|
|
||||||
|
|
||||||
err = (*JuiceLoaderNative.jvmti)->AddCapabilities(JuiceLoaderNative.jvmti, &caps);
|
|
||||||
check_jvmti_error(JuiceLoaderNative.jvmti, err, "AddCapabilities");
|
|
||||||
|
|
||||||
// memset(&callbacks, 0, sizeof(callbacks));
|
|
||||||
// callbacks.MethodEntry = &callbackMethodEntry;
|
|
||||||
// err = (*JuiceLoaderNative.jvmti)->SetEventCallbacks(JuiceLoaderNative.jvmti, &callbacks, (jint)sizeof(callbacks));
|
|
||||||
// check_jvmti_error(JuiceLoaderNative.jvmti, err, "SetEventCallbacks");
|
|
||||||
|
|
||||||
// err = (*JuiceLoaderNative.jvmti)->SetEventNotificationMode(JuiceLoaderNative.jvmti, JVMTI_ENABLE, JVMTI_EVENT_METHOD_ENTRY, NULL);
|
|
||||||
// check_jvmti_error(JuiceLoaderNative.jvmti, err, "EnableMethodEntry");
|
|
||||||
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
JNI Func: JuiceLoaderNative.init()
|
|
||||||
Desc: Init environment
|
|
||||||
*/
|
|
||||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoaderNative_init
|
|
||||||
(JNIEnv *env, jobject obj) {
|
|
||||||
log_info("%s JNI Func Init Invoke!");
|
|
||||||
if(setup(env) == 0) {
|
|
||||||
return JNI_TRUE;
|
|
||||||
}
|
|
||||||
return JNI_FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
JNI Func: JuiceLoaderNative.injectJar(path)
|
|
||||||
Desc: add jar to boostrap classloader
|
|
||||||
*/
|
|
||||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoaderNative_injectJar
|
|
||||||
(JNIEnv *env, jobject obj, jstring path) {
|
|
||||||
log_info("%s JNI Func InjectJar Invoke!", LOG_PREFIX);
|
|
||||||
jvmtiError err;
|
|
||||||
if(JuiceLoaderNative.jvmti == NULL) {
|
|
||||||
log_error("%s JVM not init!", LOG_PREFIX);
|
|
||||||
return JNI_FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
const char *pathStr = (*env)->GetStringUTFChars(env, path, NULL);
|
|
||||||
log_info("%s InjectJar: %s", LOG_PREFIX, pathStr);
|
|
||||||
|
|
||||||
err = (*JuiceLoaderNative.jvmti)->AddToSystemClassLoaderSearch(JuiceLoaderNative.jvmti, pathStr);
|
|
||||||
check_jvmti_error(JuiceLoaderNative.jvmti, err, "AddToSystemClassLoaderSearch");
|
|
||||||
return JNI_TRUE;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
JNI Func: JuiceLoaderNative.redefine
|
|
||||||
Desc: Redefine Class (class, bytecodes, len)
|
|
||||||
*/
|
|
||||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoaderNative_redefineClass__Ljava_lang_Class_2_3BI
|
|
||||||
(JNIEnv *env, jobject obj, jclass clazz, jbyteArray bytecodes, jint len) {
|
|
||||||
log_info("%s JNI Func RedefineClass Invoke!", LOG_PREFIX);
|
|
||||||
jvmtiError err;
|
|
||||||
|
|
||||||
if (JuiceLoaderNative.jvmti == NULL) {
|
|
||||||
log_error("%s JVM not init!", LOG_PREFIX);
|
|
||||||
return JNI_FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
log_info("%s Creating class definition...", LOG_PREFIX);
|
|
||||||
jbyte* buf = (*env)->GetByteArrayElements(env, bytecodes, NULL); // get raw bytes
|
|
||||||
|
|
||||||
jvmtiClassDefinition defs[1];
|
|
||||||
defs[0].klass = clazz;
|
|
||||||
defs[0].class_byte_count = len;
|
|
||||||
defs[0].class_bytes = (const unsigned char*) buf;
|
|
||||||
|
|
||||||
log_info("%s Redefining class...", LOG_PREFIX);
|
|
||||||
err = (*JuiceLoaderNative.jvmti)->RedefineClasses(JuiceLoaderNative.jvmti, 1, defs);
|
|
||||||
check_jvmti_error(JuiceLoaderNative.jvmti, err, "RedefineClasses");
|
|
||||||
|
|
||||||
(*env)->ReleaseByteArrayElements(env, bytecodes, buf, JNI_ABORT); // do not copy back, just release
|
|
||||||
|
|
||||||
log_info("%s RedefineClass Done!", LOG_PREFIX);
|
|
||||||
return JNI_TRUE;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/*
|
|
||||||
JNI Func: JuiceLoaderNative.redifine
|
|
||||||
Desc: Redefine Class (classname, bytecodes, len)
|
|
||||||
*/
|
|
||||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoaderNative_redefineClass__Ljava_lang_String_2_3BI
|
|
||||||
(JNIEnv *env, jobject obj, jstring classname, jbyteArray bytecodes, jint len) {
|
|
||||||
log_info("%s RedefineClass Invoke!", LOG_PREFIX);
|
|
||||||
jvmtiError err;
|
|
||||||
|
|
||||||
if (JuiceLoaderNative.jvmti == NULL) {
|
|
||||||
log_error("%s JVM not init!", LOG_PREFIX);
|
|
||||||
return JNI_FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- 获取 class 名称 ---
|
|
||||||
const char* cname = (*env)->GetStringUTFChars(env, classname, NULL);
|
|
||||||
log_debug("%s Finding class: %s", LOG_PREFIX, cname);
|
|
||||||
|
|
||||||
jclass clazz = (*env)->FindClass(env, cname);
|
|
||||||
(*env)->ReleaseStringUTFChars(env, classname, cname); // 正确释放
|
|
||||||
|
|
||||||
if (clazz == NULL) {
|
|
||||||
log_error("%s Class not found!", LOG_PREFIX);
|
|
||||||
return JNI_FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- 获取字节数组 ---
|
|
||||||
jbyte* buf = (*env)->GetByteArrayElements(env, bytecodes, NULL);
|
|
||||||
|
|
||||||
jvmtiClassDefinition defs[1];
|
|
||||||
defs[0].klass = clazz;
|
|
||||||
defs[0].class_byte_count = len;
|
|
||||||
defs[0].class_bytes = (const unsigned char*) buf;
|
|
||||||
|
|
||||||
log_info("%s Redefining class...", LOG_PREFIX);
|
|
||||||
err = (*JuiceLoaderNative.jvmti)->RedefineClasses(JuiceLoaderNative.jvmti, 1, defs);
|
|
||||||
check_jvmti_error(JuiceLoaderNative.jvmti, err, "RedefineClasses");
|
|
||||||
|
|
||||||
(*env)->ReleaseByteArrayElements(env, bytecodes, buf, JNI_ABORT); // 用之前的 buf
|
|
||||||
|
|
||||||
log_info("%s Done!", LOG_PREFIX);
|
|
||||||
return JNI_TRUE;
|
|
||||||
}
|
|
||||||
|
|
||||||
JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoaderNative_getLoadedClasses
|
|
||||||
(JNIEnv *env, jobject obj) {
|
|
||||||
jint count = 0;
|
|
||||||
jclass* classes = NULL;
|
|
||||||
|
|
||||||
jvmtiError err = (*JuiceLoaderNative.jvmti)->GetLoadedClasses(JuiceLoaderNative.jvmti, &count, &classes);
|
|
||||||
if (err != JVMTI_ERROR_NONE || count == 0) {
|
|
||||||
return (*env)->NewObjectArray(env, 0, (*env)->FindClass(env, "java/lang/Class"), NULL);
|
|
||||||
}
|
|
||||||
|
|
||||||
jclass classClass = (*env)->FindClass(env, "java/lang/Class");
|
|
||||||
jobjectArray result = (*env)->NewObjectArray(env, count, classClass, NULL);
|
|
||||||
|
|
||||||
for (int i = 0; i < count; i++) {
|
|
||||||
(*env)->SetObjectArrayElement(env, result, i, classes[i]);
|
|
||||||
}
|
|
||||||
|
|
||||||
(*JuiceLoaderNative.jvmti)->Deallocate(JuiceLoaderNative.jvmti, (unsigned char*)classes);
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
#include "JuiceLoaderUtils.h"
|
|
||||||
#include "windows.h"
|
|
||||||
|
|
||||||
/* Helper: get method full name: ClassName.methodName(signature) */
|
|
||||||
char* get_method_fullname(jvmtiEnv *j, JNIEnv *env, jthread thread, jmethodID method) {
|
|
||||||
char *mname = NULL, *msig = NULL, *mgeneric = NULL;
|
|
||||||
jclass declaring = NULL;
|
|
||||||
char *cls_sig = NULL;
|
|
||||||
char *result = NULL;
|
|
||||||
|
|
||||||
jvmtiError err;
|
|
||||||
|
|
||||||
err = (*j)->GetMethodName(j, method, &mname, &msig, &mgeneric);
|
|
||||||
if (err != JVMTI_ERROR_NONE) goto cleanup;
|
|
||||||
|
|
||||||
err = (*j)->GetMethodDeclaringClass(j, method, &declaring);
|
|
||||||
if (err != JVMTI_ERROR_NONE) goto cleanup;
|
|
||||||
|
|
||||||
err = (*j)->GetClassSignature(j, declaring, &cls_sig, NULL);
|
|
||||||
if (err != JVMTI_ERROR_NONE) goto cleanup;
|
|
||||||
|
|
||||||
/* cls_sig is like "Lcom/example/MyClass;" -> make it human-friendly */
|
|
||||||
size_t len = strlen(cls_sig) + strlen(mname) + strlen(msig) + 4;
|
|
||||||
result = (char*)malloc(len);
|
|
||||||
if (result) {
|
|
||||||
/* remove leading L and trailing ; from class signature if present */
|
|
||||||
char *cls_nice = cls_sig;
|
|
||||||
if (cls_sig[0] == 'L') cls_nice = cls_sig + 1;
|
|
||||||
size_t cls_len = strlen(cls_nice);
|
|
||||||
if (cls_nice[cls_len - 1] == ';') cls_nice[cls_len - 1] = '\0';
|
|
||||||
snprintf(result, len, "%s.%s%s", cls_nice, mname, msig);
|
|
||||||
}
|
|
||||||
|
|
||||||
cleanup:
|
|
||||||
if (mname) (*j)->Deallocate(j, (unsigned char*)mname);
|
|
||||||
if (msig) (*j)->Deallocate(j, (unsigned char*)msig);
|
|
||||||
if (mgeneric) (*j)->Deallocate(j, (unsigned char*)mgeneric);
|
|
||||||
if (cls_sig) (*j)->Deallocate(j, (unsigned char*)cls_sig);
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
file(
|
||||||
|
GLOB_RECURSE
|
||||||
|
agent_sources
|
||||||
|
${CMAKE_CURRENT_SOURCE_DIR}/*.cpp
|
||||||
|
${CMAKE_CURRENT_SOURCE_DIR}/*.c
|
||||||
|
)
|
||||||
|
|
||||||
|
add_library(agent SHARED ${agent_sources})
|
||||||
|
|
||||||
|
target_include_directories(agent PRIVATE
|
||||||
|
${CMAKE_SOURCE_DIR}/includes
|
||||||
|
${CMAKE_SOURCE_DIR}/includes/jvm
|
||||||
|
${CMAKE_SOURCE_DIR}/includes/jvm/win32
|
||||||
|
${CMAKE_CURRENT_SOURCE_DIR}/includes
|
||||||
|
)
|
||||||
|
|
||||||
|
target_link_libraries(agent PRIVATE
|
||||||
|
ReflectiveDLLInjection
|
||||||
|
jvm
|
||||||
|
)
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
#include <windows.h>
|
||||||
|
#include <JuiceAgent/Logger.hpp>
|
||||||
|
#include <libagent.h>
|
||||||
|
|
||||||
|
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) {
|
||||||
|
switch( fdwReason )
|
||||||
|
{
|
||||||
|
case DLL_PROCESS_ATTACH: {
|
||||||
|
InitLogger();
|
||||||
|
PLOGI << "DllMain: DLL_PROCESS_ATTACH";
|
||||||
|
PLOGD.printf("lpReserved: %p", lpReserved);
|
||||||
|
|
||||||
|
const char* runtime_dir = (const char*)lpReserved;
|
||||||
|
PLOGD << "runtime_dir: " << runtime_dir;
|
||||||
|
|
||||||
|
InitJuiceAgent(runtime_dir);
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case DLL_THREAD_ATTACH: {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case DLL_THREAD_DETACH: {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
case DLL_PROCESS_DETACH: {
|
||||||
|
PLOGI << "DllMain: DLL_PROCESS_DETACH";
|
||||||
|
PLOGD.printf("lpReserved: %p", lpReserved);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return TRUE;
|
||||||
|
}
|
||||||
@@ -0,0 +1,480 @@
|
|||||||
|
//===============================================================================================//
|
||||||
|
// Copyright (c) 2012, Stephen Fewer of Harmony Security (www.harmonysecurity.com)
|
||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// * Neither the name of Harmony Security nor the names of its contributors may be used to
|
||||||
|
// endorse or promote products derived from this software without specific prior written permission.
|
||||||
|
//
|
||||||
|
// 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 OWNER 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.
|
||||||
|
//===============================================================================================//
|
||||||
|
#include "ReflectiveLoader.h"
|
||||||
|
|
||||||
|
#define WIN_X64
|
||||||
|
#define REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR
|
||||||
|
|
||||||
|
//===============================================================================================//
|
||||||
|
// Our loader will set this to a pseudo correct HINSTANCE/HMODULE value
|
||||||
|
HINSTANCE hAppInstance = NULL;
|
||||||
|
//===============================================================================================//
|
||||||
|
#pragma intrinsic( _ReturnAddress )
|
||||||
|
// This function can not be inlined by the compiler or we will not get the address we expect. Ideally
|
||||||
|
// this code will be compiled with the /O2 and /Ob1 switches. Bonus points if we could take advantage of
|
||||||
|
// RIP relative addressing in this instance but I dont believe we can do so with the compiler intrinsics
|
||||||
|
// available (and no inline asm available under x64).
|
||||||
|
// __declspec(noinline) ULONG_PTR caller( VOID ) { return (ULONG_PTR)_ReturnAddress(); }
|
||||||
|
|
||||||
|
// OK, it's will be fine :/
|
||||||
|
__declspec(noinline) ULONG_PTR caller( VOID ) { return (ULONG_PTR) __builtin_return_address(0); }
|
||||||
|
|
||||||
|
//===============================================================================================//
|
||||||
|
|
||||||
|
// Note 1: If you want to have your own DllMain, define REFLECTIVEDLLINJECTION_CUSTOM_DLLMAIN,
|
||||||
|
// otherwise the DllMain at the end of this file will be used.
|
||||||
|
|
||||||
|
// Note 2: If you are injecting the DLL via LoadRemoteLibraryR, define REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR,
|
||||||
|
// otherwise it is assumed you are calling the ReflectiveLoader via a stub.
|
||||||
|
|
||||||
|
// This is our position independent reflective DLL loader/injector
|
||||||
|
#ifdef REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR
|
||||||
|
DLLEXPORT ULONG_PTR WINAPI ReflectiveLoader( LPVOID lpParameter )
|
||||||
|
#else
|
||||||
|
DLLEXPORT ULONG_PTR WINAPI ReflectiveLoader( VOID )
|
||||||
|
#endif
|
||||||
|
{
|
||||||
|
// the functions we need
|
||||||
|
LOADLIBRARYA pLoadLibraryA = NULL;
|
||||||
|
GETPROCADDRESS pGetProcAddress = NULL;
|
||||||
|
VIRTUALALLOC pVirtualAlloc = NULL;
|
||||||
|
NTFLUSHINSTRUCTIONCACHE pNtFlushInstructionCache = NULL;
|
||||||
|
|
||||||
|
USHORT usCounter;
|
||||||
|
|
||||||
|
// the initial location of this image in memory
|
||||||
|
ULONG_PTR uiLibraryAddress;
|
||||||
|
// the kernels base address and later this images newly loaded base address
|
||||||
|
ULONG_PTR uiBaseAddress;
|
||||||
|
|
||||||
|
// variables for processing the kernels export table
|
||||||
|
ULONG_PTR uiAddressArray;
|
||||||
|
ULONG_PTR uiNameArray;
|
||||||
|
ULONG_PTR uiExportDir;
|
||||||
|
ULONG_PTR uiNameOrdinals;
|
||||||
|
DWORD dwHashValue;
|
||||||
|
|
||||||
|
// variables for loading this image
|
||||||
|
ULONG_PTR uiHeaderValue;
|
||||||
|
ULONG_PTR uiValueA;
|
||||||
|
ULONG_PTR uiValueB;
|
||||||
|
ULONG_PTR uiValueC;
|
||||||
|
ULONG_PTR uiValueD;
|
||||||
|
ULONG_PTR uiValueE;
|
||||||
|
|
||||||
|
// STEP 0: calculate our images current base address
|
||||||
|
|
||||||
|
// we will start searching backwards from our callers return address.
|
||||||
|
uiLibraryAddress = caller();
|
||||||
|
|
||||||
|
// loop through memory backwards searching for our images base address
|
||||||
|
// we dont need SEH style search as we shouldnt generate any access violations with this
|
||||||
|
while( TRUE )
|
||||||
|
{
|
||||||
|
if( ((PIMAGE_DOS_HEADER)uiLibraryAddress)->e_magic == IMAGE_DOS_SIGNATURE )
|
||||||
|
{
|
||||||
|
uiHeaderValue = ((PIMAGE_DOS_HEADER)uiLibraryAddress)->e_lfanew;
|
||||||
|
// some x64 dll's can trigger a bogus signature (IMAGE_DOS_SIGNATURE == 'POP r10'),
|
||||||
|
// we sanity check the e_lfanew with an upper threshold value of 1024 to avoid problems.
|
||||||
|
if( uiHeaderValue >= sizeof(IMAGE_DOS_HEADER) && uiHeaderValue < 1024 )
|
||||||
|
{
|
||||||
|
uiHeaderValue += uiLibraryAddress;
|
||||||
|
// break if we have found a valid MZ/PE header
|
||||||
|
if( ((PIMAGE_NT_HEADERS)uiHeaderValue)->Signature == IMAGE_NT_SIGNATURE )
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
uiLibraryAddress--;
|
||||||
|
}
|
||||||
|
|
||||||
|
// STEP 1: process the kernels exports for the functions our loader needs...
|
||||||
|
|
||||||
|
// get the Process Enviroment Block
|
||||||
|
#ifdef WIN_X64
|
||||||
|
uiBaseAddress = __readgsqword( 0x60 );
|
||||||
|
#else
|
||||||
|
#ifdef WIN_X86
|
||||||
|
uiBaseAddress = __readfsdword( 0x30 );
|
||||||
|
#else WIN_ARM
|
||||||
|
uiBaseAddress = *(DWORD *)( (BYTE *)_MoveFromCoprocessor( 15, 0, 13, 0, 2 ) + 0x30 );
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// get the processes loaded modules. ref: http://msdn.microsoft.com/en-us/library/aa813708(VS.85).aspx
|
||||||
|
uiBaseAddress = (ULONG_PTR)((_PPEB)uiBaseAddress)->pLdr;
|
||||||
|
|
||||||
|
// get the first entry of the InMemoryOrder module list
|
||||||
|
uiValueA = (ULONG_PTR)((PPEB_LDR_DATA)uiBaseAddress)->InMemoryOrderModuleList.Flink;
|
||||||
|
while( uiValueA )
|
||||||
|
{
|
||||||
|
// get pointer to current modules name (unicode string)
|
||||||
|
uiValueB = (ULONG_PTR)((PLDR_DATA_TABLE_ENTRY)uiValueA)->BaseDllName.pBuffer;
|
||||||
|
// set bCounter to the length for the loop
|
||||||
|
usCounter = ((PLDR_DATA_TABLE_ENTRY)uiValueA)->BaseDllName.Length;
|
||||||
|
// clear uiValueC which will store the hash of the module name
|
||||||
|
uiValueC = 0;
|
||||||
|
|
||||||
|
// compute the hash of the module name...
|
||||||
|
do
|
||||||
|
{
|
||||||
|
uiValueC = ror( (DWORD)uiValueC );
|
||||||
|
// normalize to uppercase if the madule name is in lowercase
|
||||||
|
if( *((BYTE *)uiValueB) >= 'a' )
|
||||||
|
uiValueC += *((BYTE *)uiValueB) - 0x20;
|
||||||
|
else
|
||||||
|
uiValueC += *((BYTE *)uiValueB);
|
||||||
|
uiValueB++;
|
||||||
|
} while( --usCounter );
|
||||||
|
|
||||||
|
// compare the hash with that of kernel32.dll
|
||||||
|
if( (DWORD)uiValueC == KERNEL32DLL_HASH )
|
||||||
|
{
|
||||||
|
// get this modules base address
|
||||||
|
uiBaseAddress = (ULONG_PTR)((PLDR_DATA_TABLE_ENTRY)uiValueA)->DllBase;
|
||||||
|
|
||||||
|
// get the VA of the modules NT Header
|
||||||
|
uiExportDir = uiBaseAddress + ((PIMAGE_DOS_HEADER)uiBaseAddress)->e_lfanew;
|
||||||
|
|
||||||
|
// uiNameArray = the address of the modules export directory entry
|
||||||
|
uiNameArray = (ULONG_PTR)&((PIMAGE_NT_HEADERS)uiExportDir)->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_EXPORT ];
|
||||||
|
|
||||||
|
// get the VA of the export directory
|
||||||
|
uiExportDir = ( uiBaseAddress + ((PIMAGE_DATA_DIRECTORY)uiNameArray)->VirtualAddress );
|
||||||
|
|
||||||
|
// get the VA for the array of name pointers
|
||||||
|
uiNameArray = ( uiBaseAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfNames );
|
||||||
|
|
||||||
|
// get the VA for the array of name ordinals
|
||||||
|
uiNameOrdinals = ( uiBaseAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfNameOrdinals );
|
||||||
|
|
||||||
|
usCounter = 3;
|
||||||
|
|
||||||
|
// loop while we still have imports to find
|
||||||
|
while( usCounter > 0 )
|
||||||
|
{
|
||||||
|
// compute the hash values for this function name
|
||||||
|
dwHashValue = hash( (char *)( uiBaseAddress + DEREF_32( uiNameArray ) ) );
|
||||||
|
|
||||||
|
// if we have found a function we want we get its virtual address
|
||||||
|
if( dwHashValue == LOADLIBRARYA_HASH || dwHashValue == GETPROCADDRESS_HASH || dwHashValue == VIRTUALALLOC_HASH )
|
||||||
|
{
|
||||||
|
// get the VA for the array of addresses
|
||||||
|
uiAddressArray = ( uiBaseAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfFunctions );
|
||||||
|
|
||||||
|
// use this functions name ordinal as an index into the array of name pointers
|
||||||
|
uiAddressArray += ( DEREF_16( uiNameOrdinals ) * sizeof(DWORD) );
|
||||||
|
|
||||||
|
// store this functions VA
|
||||||
|
if( dwHashValue == LOADLIBRARYA_HASH )
|
||||||
|
pLoadLibraryA = (LOADLIBRARYA)( uiBaseAddress + DEREF_32( uiAddressArray ) );
|
||||||
|
else if( dwHashValue == GETPROCADDRESS_HASH )
|
||||||
|
pGetProcAddress = (GETPROCADDRESS)( uiBaseAddress + DEREF_32( uiAddressArray ) );
|
||||||
|
else if( dwHashValue == VIRTUALALLOC_HASH )
|
||||||
|
pVirtualAlloc = (VIRTUALALLOC)( uiBaseAddress + DEREF_32( uiAddressArray ) );
|
||||||
|
|
||||||
|
// decrement our counter
|
||||||
|
usCounter--;
|
||||||
|
}
|
||||||
|
|
||||||
|
// get the next exported function name
|
||||||
|
uiNameArray += sizeof(DWORD);
|
||||||
|
|
||||||
|
// get the next exported function name ordinal
|
||||||
|
uiNameOrdinals += sizeof(WORD);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if( (DWORD)uiValueC == NTDLLDLL_HASH )
|
||||||
|
{
|
||||||
|
// get this modules base address
|
||||||
|
uiBaseAddress = (ULONG_PTR)((PLDR_DATA_TABLE_ENTRY)uiValueA)->DllBase;
|
||||||
|
|
||||||
|
// get the VA of the modules NT Header
|
||||||
|
uiExportDir = uiBaseAddress + ((PIMAGE_DOS_HEADER)uiBaseAddress)->e_lfanew;
|
||||||
|
|
||||||
|
// uiNameArray = the address of the modules export directory entry
|
||||||
|
uiNameArray = (ULONG_PTR)&((PIMAGE_NT_HEADERS)uiExportDir)->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_EXPORT ];
|
||||||
|
|
||||||
|
// get the VA of the export directory
|
||||||
|
uiExportDir = ( uiBaseAddress + ((PIMAGE_DATA_DIRECTORY)uiNameArray)->VirtualAddress );
|
||||||
|
|
||||||
|
// get the VA for the array of name pointers
|
||||||
|
uiNameArray = ( uiBaseAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfNames );
|
||||||
|
|
||||||
|
// get the VA for the array of name ordinals
|
||||||
|
uiNameOrdinals = ( uiBaseAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfNameOrdinals );
|
||||||
|
|
||||||
|
usCounter = 1;
|
||||||
|
|
||||||
|
// loop while we still have imports to find
|
||||||
|
while( usCounter > 0 )
|
||||||
|
{
|
||||||
|
// compute the hash values for this function name
|
||||||
|
dwHashValue = hash( (char *)( uiBaseAddress + DEREF_32( uiNameArray ) ) );
|
||||||
|
|
||||||
|
// if we have found a function we want we get its virtual address
|
||||||
|
if( dwHashValue == NTFLUSHINSTRUCTIONCACHE_HASH )
|
||||||
|
{
|
||||||
|
// get the VA for the array of addresses
|
||||||
|
uiAddressArray = ( uiBaseAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfFunctions );
|
||||||
|
|
||||||
|
// use this functions name ordinal as an index into the array of name pointers
|
||||||
|
uiAddressArray += ( DEREF_16( uiNameOrdinals ) * sizeof(DWORD) );
|
||||||
|
|
||||||
|
// store this functions VA
|
||||||
|
if( dwHashValue == NTFLUSHINSTRUCTIONCACHE_HASH )
|
||||||
|
pNtFlushInstructionCache = (NTFLUSHINSTRUCTIONCACHE)( uiBaseAddress + DEREF_32( uiAddressArray ) );
|
||||||
|
|
||||||
|
// decrement our counter
|
||||||
|
usCounter--;
|
||||||
|
}
|
||||||
|
|
||||||
|
// get the next exported function name
|
||||||
|
uiNameArray += sizeof(DWORD);
|
||||||
|
|
||||||
|
// get the next exported function name ordinal
|
||||||
|
uiNameOrdinals += sizeof(WORD);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// we stop searching when we have found everything we need.
|
||||||
|
if( pLoadLibraryA && pGetProcAddress && pVirtualAlloc && pNtFlushInstructionCache )
|
||||||
|
break;
|
||||||
|
|
||||||
|
// get the next entry
|
||||||
|
uiValueA = DEREF( uiValueA );
|
||||||
|
}
|
||||||
|
|
||||||
|
// STEP 2: load our image into a new permanent location in memory...
|
||||||
|
|
||||||
|
// get the VA of the NT Header for the PE to be loaded
|
||||||
|
uiHeaderValue = uiLibraryAddress + ((PIMAGE_DOS_HEADER)uiLibraryAddress)->e_lfanew;
|
||||||
|
|
||||||
|
// allocate all the memory for the DLL to be loaded into. we can load at any address because we will
|
||||||
|
// relocate the image. Also zeros all memory and marks it as READ, WRITE and EXECUTE to avoid any problems.
|
||||||
|
uiBaseAddress = (ULONG_PTR)pVirtualAlloc( NULL, ((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.SizeOfImage, MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READWRITE );
|
||||||
|
|
||||||
|
// we must now copy over the headers
|
||||||
|
uiValueA = ((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.SizeOfHeaders;
|
||||||
|
uiValueB = uiLibraryAddress;
|
||||||
|
uiValueC = uiBaseAddress;
|
||||||
|
|
||||||
|
while( uiValueA-- )
|
||||||
|
*(BYTE *)uiValueC++ = *(BYTE *)uiValueB++;
|
||||||
|
|
||||||
|
// STEP 3: load in all of our sections...
|
||||||
|
|
||||||
|
// uiValueA = the VA of the first section
|
||||||
|
uiValueA = ( (ULONG_PTR)&((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader + ((PIMAGE_NT_HEADERS)uiHeaderValue)->FileHeader.SizeOfOptionalHeader );
|
||||||
|
|
||||||
|
// itterate through all sections, loading them into memory.
|
||||||
|
uiValueE = ((PIMAGE_NT_HEADERS)uiHeaderValue)->FileHeader.NumberOfSections;
|
||||||
|
while( uiValueE-- )
|
||||||
|
{
|
||||||
|
// uiValueB is the VA for this section
|
||||||
|
uiValueB = ( uiBaseAddress + ((PIMAGE_SECTION_HEADER)uiValueA)->VirtualAddress );
|
||||||
|
|
||||||
|
// uiValueC if the VA for this sections data
|
||||||
|
uiValueC = ( uiLibraryAddress + ((PIMAGE_SECTION_HEADER)uiValueA)->PointerToRawData );
|
||||||
|
|
||||||
|
// copy the section over
|
||||||
|
uiValueD = ((PIMAGE_SECTION_HEADER)uiValueA)->SizeOfRawData;
|
||||||
|
|
||||||
|
while( uiValueD-- )
|
||||||
|
*(BYTE *)uiValueB++ = *(BYTE *)uiValueC++;
|
||||||
|
|
||||||
|
// get the VA of the next section
|
||||||
|
uiValueA += sizeof( IMAGE_SECTION_HEADER );
|
||||||
|
}
|
||||||
|
|
||||||
|
// STEP 4: process our images import table...
|
||||||
|
|
||||||
|
// uiValueB = the address of the import directory
|
||||||
|
uiValueB = (ULONG_PTR)&((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_IMPORT ];
|
||||||
|
|
||||||
|
// we assume their is an import table to process
|
||||||
|
// uiValueC is the first entry in the import table
|
||||||
|
uiValueC = ( uiBaseAddress + ((PIMAGE_DATA_DIRECTORY)uiValueB)->VirtualAddress );
|
||||||
|
|
||||||
|
// itterate through all imports
|
||||||
|
while( ((PIMAGE_IMPORT_DESCRIPTOR)uiValueC)->Name )
|
||||||
|
{
|
||||||
|
// use LoadLibraryA to load the imported module into memory
|
||||||
|
uiLibraryAddress = (ULONG_PTR)pLoadLibraryA( (LPCSTR)( uiBaseAddress + ((PIMAGE_IMPORT_DESCRIPTOR)uiValueC)->Name ) );
|
||||||
|
|
||||||
|
// uiValueD = VA of the OriginalFirstThunk
|
||||||
|
uiValueD = ( uiBaseAddress + ((PIMAGE_IMPORT_DESCRIPTOR)uiValueC)->OriginalFirstThunk );
|
||||||
|
|
||||||
|
// uiValueA = VA of the IAT (via first thunk not origionalfirstthunk)
|
||||||
|
uiValueA = ( uiBaseAddress + ((PIMAGE_IMPORT_DESCRIPTOR)uiValueC)->FirstThunk );
|
||||||
|
|
||||||
|
// itterate through all imported functions, importing by ordinal if no name present
|
||||||
|
while( DEREF(uiValueA) )
|
||||||
|
{
|
||||||
|
// sanity check uiValueD as some compilers only import by FirstThunk
|
||||||
|
if( uiValueD && ((PIMAGE_THUNK_DATA)uiValueD)->u1.Ordinal & IMAGE_ORDINAL_FLAG )
|
||||||
|
{
|
||||||
|
// get the VA of the modules NT Header
|
||||||
|
uiExportDir = uiLibraryAddress + ((PIMAGE_DOS_HEADER)uiLibraryAddress)->e_lfanew;
|
||||||
|
|
||||||
|
// uiNameArray = the address of the modules export directory entry
|
||||||
|
uiNameArray = (ULONG_PTR)&((PIMAGE_NT_HEADERS)uiExportDir)->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_EXPORT ];
|
||||||
|
|
||||||
|
// get the VA of the export directory
|
||||||
|
uiExportDir = ( uiLibraryAddress + ((PIMAGE_DATA_DIRECTORY)uiNameArray)->VirtualAddress );
|
||||||
|
|
||||||
|
// get the VA for the array of addresses
|
||||||
|
uiAddressArray = ( uiLibraryAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfFunctions );
|
||||||
|
|
||||||
|
// use the import ordinal (- export ordinal base) as an index into the array of addresses
|
||||||
|
uiAddressArray += ( ( IMAGE_ORDINAL( ((PIMAGE_THUNK_DATA)uiValueD)->u1.Ordinal ) - ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->Base ) * sizeof(DWORD) );
|
||||||
|
|
||||||
|
// patch in the address for this imported function
|
||||||
|
DEREF(uiValueA) = ( uiLibraryAddress + DEREF_32(uiAddressArray) );
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// get the VA of this functions import by name struct
|
||||||
|
uiValueB = ( uiBaseAddress + DEREF(uiValueA) );
|
||||||
|
|
||||||
|
// use GetProcAddress and patch in the address for this imported function
|
||||||
|
DEREF(uiValueA) = (ULONG_PTR)pGetProcAddress( (HMODULE)uiLibraryAddress, (LPCSTR)((PIMAGE_IMPORT_BY_NAME)uiValueB)->Name );
|
||||||
|
}
|
||||||
|
// get the next imported function
|
||||||
|
uiValueA += sizeof( ULONG_PTR );
|
||||||
|
if( uiValueD )
|
||||||
|
uiValueD += sizeof( ULONG_PTR );
|
||||||
|
}
|
||||||
|
|
||||||
|
// get the next import
|
||||||
|
uiValueC += sizeof( IMAGE_IMPORT_DESCRIPTOR );
|
||||||
|
}
|
||||||
|
|
||||||
|
// STEP 5: process all of our images relocations...
|
||||||
|
|
||||||
|
// calculate the base address delta and perform relocations (even if we load at desired image base)
|
||||||
|
uiLibraryAddress = uiBaseAddress - ((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.ImageBase;
|
||||||
|
|
||||||
|
// uiValueB = the address of the relocation directory
|
||||||
|
uiValueB = (ULONG_PTR)&((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_BASERELOC ];
|
||||||
|
|
||||||
|
// check if their are any relocations present
|
||||||
|
if( ((PIMAGE_DATA_DIRECTORY)uiValueB)->Size )
|
||||||
|
{
|
||||||
|
// uiValueC is now the first entry (IMAGE_BASE_RELOCATION)
|
||||||
|
uiValueC = ( uiBaseAddress + ((PIMAGE_DATA_DIRECTORY)uiValueB)->VirtualAddress );
|
||||||
|
|
||||||
|
// and we itterate through all entries...
|
||||||
|
while( ((PIMAGE_BASE_RELOCATION)uiValueC)->SizeOfBlock )
|
||||||
|
{
|
||||||
|
// uiValueA = the VA for this relocation block
|
||||||
|
uiValueA = ( uiBaseAddress + ((PIMAGE_BASE_RELOCATION)uiValueC)->VirtualAddress );
|
||||||
|
|
||||||
|
// uiValueB = number of entries in this relocation block
|
||||||
|
uiValueB = ( ((PIMAGE_BASE_RELOCATION)uiValueC)->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION) ) / sizeof( IMAGE_RELOC );
|
||||||
|
|
||||||
|
// uiValueD is now the first entry in the current relocation block
|
||||||
|
uiValueD = uiValueC + sizeof(IMAGE_BASE_RELOCATION);
|
||||||
|
|
||||||
|
// we itterate through all the entries in the current block...
|
||||||
|
while( uiValueB-- )
|
||||||
|
{
|
||||||
|
// perform the relocation, skipping IMAGE_REL_BASED_ABSOLUTE as required.
|
||||||
|
// we dont use a switch statement to avoid the compiler building a jump table
|
||||||
|
// which would not be very position independent!
|
||||||
|
if( ((PIMAGE_RELOC)uiValueD)->type == IMAGE_REL_BASED_DIR64 )
|
||||||
|
*(ULONG_PTR *)(uiValueA + ((PIMAGE_RELOC)uiValueD)->offset) += uiLibraryAddress;
|
||||||
|
else if( ((PIMAGE_RELOC)uiValueD)->type == IMAGE_REL_BASED_HIGHLOW )
|
||||||
|
*(DWORD *)(uiValueA + ((PIMAGE_RELOC)uiValueD)->offset) += (DWORD)uiLibraryAddress;
|
||||||
|
#ifdef WIN_ARM
|
||||||
|
// Note: On ARM, the compiler optimization /O2 seems to introduce an off by one issue, possibly a code gen bug. Using /O1 instead avoids this problem.
|
||||||
|
else if( ((PIMAGE_RELOC)uiValueD)->type == IMAGE_REL_BASED_ARM_MOV32T )
|
||||||
|
{
|
||||||
|
register DWORD dwInstruction;
|
||||||
|
register DWORD dwAddress;
|
||||||
|
register WORD wImm;
|
||||||
|
// get the MOV.T instructions DWORD value (We add 4 to the offset to go past the first MOV.W which handles the low word)
|
||||||
|
dwInstruction = *(DWORD *)( uiValueA + ((PIMAGE_RELOC)uiValueD)->offset + sizeof(DWORD) );
|
||||||
|
// flip the words to get the instruction as expected
|
||||||
|
dwInstruction = MAKELONG( HIWORD(dwInstruction), LOWORD(dwInstruction) );
|
||||||
|
// sanity chack we are processing a MOV instruction...
|
||||||
|
if( (dwInstruction & ARM_MOV_MASK) == ARM_MOVT )
|
||||||
|
{
|
||||||
|
// pull out the encoded 16bit value (the high portion of the address-to-relocate)
|
||||||
|
wImm = (WORD)( dwInstruction & 0x000000FF);
|
||||||
|
wImm |= (WORD)((dwInstruction & 0x00007000) >> 4);
|
||||||
|
wImm |= (WORD)((dwInstruction & 0x04000000) >> 15);
|
||||||
|
wImm |= (WORD)((dwInstruction & 0x000F0000) >> 4);
|
||||||
|
// apply the relocation to the target address
|
||||||
|
dwAddress = ( (WORD)HIWORD(uiLibraryAddress) + wImm ) & 0xFFFF;
|
||||||
|
// now create a new instruction with the same opcode and register param.
|
||||||
|
dwInstruction = (DWORD)( dwInstruction & ARM_MOV_MASK2 );
|
||||||
|
// patch in the relocated address...
|
||||||
|
dwInstruction |= (DWORD)(dwAddress & 0x00FF);
|
||||||
|
dwInstruction |= (DWORD)(dwAddress & 0x0700) << 4;
|
||||||
|
dwInstruction |= (DWORD)(dwAddress & 0x0800) << 15;
|
||||||
|
dwInstruction |= (DWORD)(dwAddress & 0xF000) << 4;
|
||||||
|
// now flip the instructions words and patch back into the code...
|
||||||
|
*(DWORD *)( uiValueA + ((PIMAGE_RELOC)uiValueD)->offset + sizeof(DWORD) ) = MAKELONG( HIWORD(dwInstruction), LOWORD(dwInstruction) );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
else if( ((PIMAGE_RELOC)uiValueD)->type == IMAGE_REL_BASED_HIGH )
|
||||||
|
*(WORD *)(uiValueA + ((PIMAGE_RELOC)uiValueD)->offset) += HIWORD(uiLibraryAddress);
|
||||||
|
else if( ((PIMAGE_RELOC)uiValueD)->type == IMAGE_REL_BASED_LOW )
|
||||||
|
*(WORD *)(uiValueA + ((PIMAGE_RELOC)uiValueD)->offset) += LOWORD(uiLibraryAddress);
|
||||||
|
|
||||||
|
// get the next entry in the current relocation block
|
||||||
|
uiValueD += sizeof( IMAGE_RELOC );
|
||||||
|
}
|
||||||
|
|
||||||
|
// get the next entry in the relocation directory
|
||||||
|
uiValueC = uiValueC + ((PIMAGE_BASE_RELOCATION)uiValueC)->SizeOfBlock;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// STEP 6: call our images entry point
|
||||||
|
|
||||||
|
// uiValueA = the VA of our newly loaded DLL/EXE's entry point
|
||||||
|
uiValueA = ( uiBaseAddress + ((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.AddressOfEntryPoint );
|
||||||
|
|
||||||
|
// We must flush the instruction cache to avoid stale code being used which was updated by our relocation processing.
|
||||||
|
pNtFlushInstructionCache( (HANDLE)-1, NULL, 0 );
|
||||||
|
|
||||||
|
// call our respective entry point, fudging our hInstance value
|
||||||
|
#ifdef REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR
|
||||||
|
// if we are injecting a DLL via LoadRemoteLibraryR we call DllMain and pass in our parameter (via the DllMain lpReserved parameter)
|
||||||
|
((DLLMAIN)uiValueA)( (HINSTANCE)uiBaseAddress, DLL_PROCESS_ATTACH, lpParameter );
|
||||||
|
#else
|
||||||
|
// if we are injecting an DLL via a stub we call DllMain with no parameter
|
||||||
|
((DLLMAIN)uiValueA)( (HINSTANCE)uiBaseAddress, DLL_PROCESS_ATTACH, NULL );
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// STEP 8: return our new entry point address so whatever called us can call DllMain() if needed.
|
||||||
|
return uiValueA;
|
||||||
|
}
|
||||||
|
//===============================================================================================//
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
#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,251 @@
|
|||||||
|
#include <jvm/jni.h>
|
||||||
|
#include <jvm/jvmti.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <JuiceAgent/Logger.hpp>
|
||||||
|
#include <libagent.h>
|
||||||
|
#include <thread>
|
||||||
|
#include <tinytoml/toml.h>
|
||||||
|
#include <JuiceAgent/JuiceAgent.h>
|
||||||
|
|
||||||
|
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) {
|
||||||
|
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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
file(
|
||||||
|
GLOB_RECURSE
|
||||||
|
libinjector_sources
|
||||||
|
${CMAKE_CURRENT_SOURCE_DIR}/*.c
|
||||||
|
)
|
||||||
|
|
||||||
|
add_library(injector SHARED ${libinjector_sources})
|
||||||
|
|
||||||
|
target_include_directories(injector PRIVATE
|
||||||
|
${CMAKE_SOURCE_DIR}/includes
|
||||||
|
${CMAKE_SOURCE_DIR}/includes/jvm
|
||||||
|
${CMAKE_SOURCE_DIR}/includes/jvm/win32
|
||||||
|
)
|
||||||
|
|
||||||
|
target_link_libraries(injector PRIVATE
|
||||||
|
ReflectiveDLLInjection
|
||||||
|
)
|
||||||
@@ -1,17 +1,15 @@
|
|||||||
// injector_debug.c
|
|
||||||
#include "InjectorUtils.h"
|
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include "LoadLibraryR.h"
|
#include <jni.h>
|
||||||
#include "InjectorNative.h"
|
#include <ReflectiveDLLInjection/LoadLibraryR.h>
|
||||||
#include "InjectParameters.h"
|
|
||||||
#include "log.c"
|
|
||||||
|
|
||||||
#define WIN_X64
|
#define WIN_X64
|
||||||
#define BREAK_WITH_ERROR( e ) { log_error("[-] %s. Error=%l", e, GetLastError()); break; }
|
#define BREAK_WITH_ERROR( e ) { printf("[-] %s. Error=%l", e, GetLastError()); break; }
|
||||||
|
#define MAX_PATH 260
|
||||||
|
|
||||||
int inject(int pid, char *path, InjectParameters *params){
|
__declspec(dllexport)
|
||||||
|
int inject(int pid, char *path, char *params){
|
||||||
HANDLE hFile = NULL;
|
HANDLE hFile = NULL;
|
||||||
HANDLE hRemoteThread = NULL;
|
HANDLE hRemoteThread = NULL;
|
||||||
HANDLE hProcess = NULL;
|
HANDLE hProcess = NULL;
|
||||||
@@ -24,18 +22,11 @@ int inject(int pid, char *path, InjectParameters *params){
|
|||||||
TOKEN_PRIVILEGES priv = {0};
|
TOKEN_PRIVILEGES priv = {0};
|
||||||
BOOL bSuccess = FALSE;
|
BOOL bSuccess = FALSE;
|
||||||
|
|
||||||
log_set_level(LOG_DEBUG);
|
printf("Injector process pointer size = %zu bytes\n", sizeof(void*));
|
||||||
log_is_log_filename(false);
|
|
||||||
log_is_log_line(false);
|
|
||||||
log_is_log_time(false);
|
|
||||||
|
|
||||||
log_info("[*] libinjector Version %d.%d Build %d", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR, PROJECT_BUILD_NUMBER);
|
|
||||||
|
|
||||||
log_debug("Injector process pointer size = %zu bytes", sizeof(void*));
|
|
||||||
|
|
||||||
do {
|
do {
|
||||||
if (!params) {
|
if (!params) {
|
||||||
log_warn("[!] No parameters provided");
|
printf("[!] No parameters provided\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
/* open DLL file */
|
/* open DLL file */
|
||||||
@@ -45,20 +36,20 @@ int inject(int pid, char *path, InjectParameters *params){
|
|||||||
/* Debug helper: print the path being opened and its absolute path */
|
/* Debug helper: print the path being opened and its absolute path */
|
||||||
char fullPath[MAX_PATH] = {0};
|
char fullPath[MAX_PATH] = {0};
|
||||||
if (GetFullPathNameA(path, MAX_PATH, fullPath, NULL) != 0) {
|
if (GetFullPathNameA(path, MAX_PATH, fullPath, NULL) != 0) {
|
||||||
log_debug("Injector GetFullPathNameA success: %s", fullPath);
|
printf("Injector GetFullPathNameA success: %s\n", fullPath);
|
||||||
} else {
|
} else {
|
||||||
log_error("[*] Injector GetFullPathNameA failed: %lu", GetLastError());
|
printf("[*] Injector GetFullPathNameA failed: %lu\n", GetLastError());
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Before CreateFileA, print which file we are about to open */
|
/* Before CreateFileA, print which file we are about to open */
|
||||||
log_debug("[*] About to open DLL: %s", path);
|
printf("[*] About to open DLL: %s\n", path);
|
||||||
|
|
||||||
/* after ReadFile (or after loading into lpBuffer), verify exports again on the buffer we actually read */
|
/* after ReadFile (or after loading into lpBuffer), verify exports again on the buffer we actually read */
|
||||||
|
|
||||||
/* get file size */
|
/* get file size */
|
||||||
dwLength = GetFileSize(hFile, NULL);
|
dwLength = GetFileSize(hFile, NULL);
|
||||||
if (dwLength == INVALID_FILE_SIZE || dwLength == 0)
|
if (dwLength == INVALID_FILE_SIZE || dwLength == 0)
|
||||||
BREAK_WITH_ERROR("Failed to get DLL file size");
|
BREAK_WITH_ERROR("Failed to get DLL file size\n");
|
||||||
|
|
||||||
/* alloc local buffer and read file */
|
/* alloc local buffer and read file */
|
||||||
lpBuffer = HeapAlloc(GetProcessHeap(), 0, dwLength);
|
lpBuffer = HeapAlloc(GetProcessHeap(), 0, dwLength);
|
||||||
@@ -68,14 +59,6 @@ int inject(int pid, char *path, InjectParameters *params){
|
|||||||
if (!ReadFile(hFile, lpBuffer, dwLength, &dwBytesRead, NULL) || dwBytesRead != dwLength)
|
if (!ReadFile(hFile, lpBuffer, dwLength, &dwBytesRead, NULL) || dwBytesRead != dwLength)
|
||||||
BREAK_WITH_ERROR("ReadFile failed or incomplete");
|
BREAK_WITH_ERROR("ReadFile failed or incomplete");
|
||||||
|
|
||||||
/* print machine type of DLL buffer */
|
|
||||||
WORD dllMachine = get_pe_machine(lpBuffer, dwLength);
|
|
||||||
log_debug("[*] DLL PE machine: %s (0x%04x)", machine_to_str(dllMachine), dllMachine);
|
|
||||||
|
|
||||||
/* check if DLL has ReflectiveLoader export */
|
|
||||||
BOOL hasRL = has_reflective_loader_export(lpBuffer, dwLength);
|
|
||||||
log_debug("[*] DLL has ReflectiveLoader export: %s", hasRL ? "YES" : "NO");
|
|
||||||
|
|
||||||
/* enable SeDebugPrivilege (best-effort) */
|
/* enable SeDebugPrivilege (best-effort) */
|
||||||
if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) {
|
if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) {
|
||||||
priv.PrivilegeCount = 1;
|
priv.PrivilegeCount = 1;
|
||||||
@@ -94,57 +77,42 @@ int inject(int pid, char *path, InjectParameters *params){
|
|||||||
/* detect target architecture */
|
/* detect target architecture */
|
||||||
BOOL targetIsWow64 = FALSE;
|
BOOL targetIsWow64 = FALSE;
|
||||||
if (!IsWow64Process(hProcess, &targetIsWow64)) {
|
if (!IsWow64Process(hProcess, &targetIsWow64)) {
|
||||||
log_error("IsWow64Process failed");
|
printf("IsWow64Process failed\n");
|
||||||
} else {
|
} else {
|
||||||
log_info("Is target process wow64 = %d (TRUE means 32-bit process on 64-bit OS)", targetIsWow64);
|
printf("Is target process wow64 = %d (TRUE means 32-bit process on 64-bit OS)\n", targetIsWow64);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* compare architectures */
|
|
||||||
#if defined(_M_X64) || defined(__x86_64__) || defined(__amd64__)
|
|
||||||
log_info("Injector compiled as: x64");
|
|
||||||
#else
|
|
||||||
log_info("Injector compiled as: x86");
|
|
||||||
#endif
|
|
||||||
|
|
||||||
if (dllMachine == IMAGE_FILE_MACHINE_AMD64) {
|
|
||||||
log_info("[*] DLL is x64");
|
|
||||||
#if !defined(_M_X64) && !defined(__x86_64__)
|
|
||||||
log_warn("[-] MISMATCH: injector is 32-bit but DLL is x64. This will fail.");
|
|
||||||
#endif
|
|
||||||
} else if (dllMachine == IMAGE_FILE_MACHINE_I386) {
|
|
||||||
log_info("[*] DLL is x86");
|
|
||||||
#if defined(_M_X64) || defined(__x86_64__)
|
|
||||||
log_warn("[-] MISMATCH: injector is 64-bit but DLL is x86. This will fail.");
|
|
||||||
#endif
|
|
||||||
} else {
|
|
||||||
log_error("Unknown DLL machine type; proceed with caution");
|
|
||||||
}
|
|
||||||
|
|
||||||
/* allocate remote memory for InjectParameters */
|
/* allocate remote memory for InjectParameters */
|
||||||
lpRemoteParam = VirtualAllocEx(hProcess, NULL, sizeof(InjectParameters), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
|
lpRemoteParam = VirtualAllocEx(hProcess, NULL, MAX_PATH, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
|
||||||
if (!lpRemoteParam)
|
if (!lpRemoteParam)
|
||||||
BREAK_WITH_ERROR("VirtualAllocEx for remote param failed");
|
BREAK_WITH_ERROR("VirtualAllocEx for remote param failed\n");
|
||||||
|
|
||||||
log_debug("remote param addr = %p", lpRemoteParam);
|
printf("remote param addr = %p\n", lpRemoteParam);
|
||||||
|
|
||||||
/* write params to remote memory */
|
/* write params to remote memory */
|
||||||
SIZE_T written = 0;
|
SIZE_T written = 0;
|
||||||
if (params) {
|
if (params) {
|
||||||
if (!WriteProcessMemory(hProcess, lpRemoteParam, params, sizeof(InjectParameters), &written) || written != sizeof(InjectParameters))
|
if (!WriteProcessMemory(hProcess, lpRemoteParam, params, MAX_PATH, &written) || written != MAX_PATH)
|
||||||
BREAK_WITH_ERROR("WriteProcessMemory for remote param failed");
|
BREAK_WITH_ERROR("WriteProcessMemory for remote param failed\n");
|
||||||
} else {
|
} else {
|
||||||
log_warn("No parameters provided; using null pointer");
|
printf("No parameters provided; using null pointer\n");
|
||||||
lpRemoteParam = NULL;
|
lpRemoteParam = NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* read back some bytes to verify write */
|
/* read back some bytes to verify write */
|
||||||
{
|
{
|
||||||
InjectParameters verify;
|
char verify[MAX_PATH] = {0};
|
||||||
SIZE_T read = 0;
|
SIZE_T read = 0;
|
||||||
if (ReadProcessMemory(hProcess, lpRemoteParam, &verify, sizeof(InjectParameters), &read)) {
|
|
||||||
log_debug("[*] Read back remote param, ConfigDir=%.*s", (int)sizeof(verify.ConfigDir), verify.ConfigDir);
|
if (lpRemoteParam) {
|
||||||
|
if (ReadProcessMemory(hProcess, lpRemoteParam, verify, MAX_PATH, &read)) {
|
||||||
|
printf("[*] Read back remote param, ConfigDir=%s\n", verify);
|
||||||
|
} else {
|
||||||
|
printf("[-] ReadProcessMemory failed: %lu\n", GetLastError());
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
log_error("[-] ReadProcessMemory failed: %lu", GetLastError());
|
printf("[*] lpRemoteParam == NULL, skip verify\n");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -152,20 +120,18 @@ int inject(int pid, char *path, InjectParameters *params){
|
|||||||
hRemoteThread = LoadRemoteLibraryR(hProcess, lpBuffer, dwLength, lpRemoteParam);
|
hRemoteThread = LoadRemoteLibraryR(hProcess, lpBuffer, dwLength, lpRemoteParam);
|
||||||
if (!hRemoteThread) {
|
if (!hRemoteThread) {
|
||||||
/* library didn't set last error; print hint info we gathered */
|
/* library didn't set last error; print hint info we gathered */
|
||||||
log_error("[-] LoadRemoteLibraryR returned NULL. GetLastError=%lu", GetLastError());
|
printf("[-] LoadRemoteLibraryR returned NULL. GetLastError=%lu\n", GetLastError());
|
||||||
log_error("[-] Diagnostic summary: dllMachine=0x%04x, hasReflectiveLoader=%d, targetIsWow64=%d",
|
|
||||||
dllMachine, hasRL ? 1 : 0, targetIsWow64 ? 1 : 0);
|
|
||||||
BREAK_WITH_ERROR("LoadRemoteLibraryR returned NULL");
|
BREAK_WITH_ERROR("LoadRemoteLibraryR returned NULL");
|
||||||
}
|
}
|
||||||
|
|
||||||
log_info("[+] DLL injected: '%s' into PID %d, remote param at %p", path, dwProcessId, lpRemoteParam);
|
printf("[+] DLL injected: '%s' into PID %d, remote param at %p\n", path, dwProcessId, lpRemoteParam);
|
||||||
/* wait for reflective loader thread to complete */
|
/* wait for reflective loader thread to complete */
|
||||||
WaitForSingleObject(hRemoteThread, INFINITE);
|
WaitForSingleObject(hRemoteThread, INFINITE);
|
||||||
|
|
||||||
/* get remote thread exit code */
|
/* get remote thread exit code */
|
||||||
DWORD exitCode = 0;
|
DWORD exitCode = 0;
|
||||||
if (GetExitCodeThread(hRemoteThread, &exitCode))
|
if (GetExitCodeThread(hRemoteThread, &exitCode))
|
||||||
log_info("[+] Remote thread exit code: %lu", exitCode);
|
printf("[+] Remote thread exit code: %lu\n", exitCode);
|
||||||
|
|
||||||
bSuccess = TRUE;
|
bSuccess = TRUE;
|
||||||
|
|
||||||
@@ -215,21 +181,77 @@ JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorNativ
|
|||||||
*/
|
*/
|
||||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorNative_inject__ILjava_lang_String_2Ljava_lang_String_2
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorNative_inject__ILjava_lang_String_2Ljava_lang_String_2
|
||||||
(JNIEnv *env, jobject obj, jint pid , jstring path, jstring configDir){
|
(JNIEnv *env, jobject obj, jint pid , jstring path, jstring configDir){
|
||||||
// Injection Path
|
|
||||||
const char* InjectionDLL = (*env)->GetStringUTFChars(env, path, NULL);
|
const char* InjectionDLL = (*env)->GetStringUTFChars(env, path, NULL);
|
||||||
// Config Path
|
|
||||||
const char* ConfigDir = (*env)->GetStringUTFChars(env, configDir, NULL);
|
const char* ConfigDir = (*env)->GetStringUTFChars(env, configDir, NULL);
|
||||||
|
|
||||||
InjectParameters params;
|
char params[MAX_PATH] = {0}; /* use a real buffer */
|
||||||
memset(¶ms, 0, sizeof(params));
|
strncpy(params, ConfigDir ? ConfigDir : "", MAX_PATH - 1);
|
||||||
|
|
||||||
strncpy(params.ConfigDir, ConfigDir ? ConfigDir : "", sizeof(params.ConfigDir)-1);
|
int ret = inject(pid, (char*)InjectionDLL, params);
|
||||||
|
|
||||||
int ret = inject(pid, (char*)InjectionDLL, ¶ms);
|
|
||||||
|
|
||||||
// Clean up
|
|
||||||
(*env)->ReleaseStringUTFChars(env, path, InjectionDLL);
|
(*env)->ReleaseStringUTFChars(env, path, InjectionDLL);
|
||||||
(*env)->ReleaseStringUTFChars(env, configDir, ConfigDir);
|
(*env)->ReleaseStringUTFChars(env, configDir, ConfigDir);
|
||||||
|
|
||||||
return (ret == 0) ? JNI_TRUE : JNI_FALSE;
|
return (ret == 0) ? JNI_TRUE : JNI_FALSE;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// ================ FindWindowsByTitle =================
|
||||||
|
#define MAX_RESULTS 128
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
wchar_t title[256];
|
||||||
|
DWORD pid;
|
||||||
|
} WindowData;
|
||||||
|
|
||||||
|
static wchar_t g_keyword[256];
|
||||||
|
static WindowData g_results[MAX_RESULTS];
|
||||||
|
static int g_count = 0;
|
||||||
|
|
||||||
|
|
||||||
|
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam) {
|
||||||
|
wchar_t title[256];
|
||||||
|
GetWindowTextW(hwnd, title, 256);
|
||||||
|
if (wcslen(title) == 0) return TRUE;
|
||||||
|
|
||||||
|
if (wcsstr(title, g_keyword)) {
|
||||||
|
DWORD pid = 0;
|
||||||
|
GetWindowThreadProcessId(hwnd, &pid);
|
||||||
|
|
||||||
|
if (g_count < MAX_RESULTS && pid) {
|
||||||
|
wcsncpy(g_results[g_count].title, title, 255);
|
||||||
|
g_results[g_count].pid = pid;
|
||||||
|
g_count++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return TRUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorNative_findWindowsByTitle
|
||||||
|
(JNIEnv *env, jclass clazz, jstring keyword) {
|
||||||
|
|
||||||
|
const jchar *input = (*env)->GetStringChars(env, keyword, NULL);
|
||||||
|
wcsncpy(g_keyword, (const wchar_t *)input, 255);
|
||||||
|
g_keyword[255] = L'\0';
|
||||||
|
(*env)->ReleaseStringChars(env, keyword, input);
|
||||||
|
|
||||||
|
g_count = 0;
|
||||||
|
EnumWindows(EnumWindowsProc, 0);
|
||||||
|
|
||||||
|
jclass infoClass = (*env)->FindClass(env, "cn/xiaozhou233/juiceagent/injector/InjectorNative$WindowInfo");
|
||||||
|
if (!infoClass) return NULL;
|
||||||
|
|
||||||
|
jmethodID ctor = (*env)->GetMethodID(env, infoClass, "<init>", "(Ljava/lang/String;I)V");
|
||||||
|
if (!ctor) return NULL;
|
||||||
|
|
||||||
|
jobjectArray array = (*env)->NewObjectArray(env, g_count, infoClass, NULL);
|
||||||
|
|
||||||
|
for (int i = 0; i < g_count; i++) {
|
||||||
|
jstring title = (*env)->NewString(env, (jchar*)g_results[i].title, wcslen(g_results[i].title));
|
||||||
|
jobject obj = (*env)->NewObject(env, infoClass, ctor, title, (jint)g_results[i].pid);
|
||||||
|
(*env)->SetObjectArrayElement(env, array, i, obj);
|
||||||
|
}
|
||||||
|
|
||||||
|
return array;
|
||||||
|
}
|
||||||
|
/// ===============================================================================
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
file(
|
||||||
|
GLOB_RECURSE
|
||||||
|
libjuiceloader_sources
|
||||||
|
${CMAKE_CURRENT_SOURCE_DIR}/*.cpp
|
||||||
|
${CMAKE_CURRENT_SOURCE_DIR}/*.c
|
||||||
|
)
|
||||||
|
|
||||||
|
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
|
||||||
|
)
|
||||||
@@ -0,0 +1,530 @@
|
|||||||
|
#include <juiceloader.h>
|
||||||
|
#include <cn_xiaozhou233_juiceloader_JuiceLoader.h>
|
||||||
|
#include <jni.h>
|
||||||
|
#include <jvmti.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <JuiceAgent/Logger.hpp>
|
||||||
|
|
||||||
|
RetransformClassCacheType RetransformClassCache = {NULL, 0, 0};
|
||||||
|
|
||||||
|
static const char* g_bytecodes_classname = NULL;
|
||||||
|
static unsigned char* g_bytecodes = NULL;
|
||||||
|
static jint g_bytecodes_len = 0;
|
||||||
|
|
||||||
|
/// ================= Utility ================= ///
|
||||||
|
|
||||||
|
char* get_class_name(JNIEnv* env, jclass clazz) {
|
||||||
|
jclass clsClass = env->FindClass("java/lang/Class");
|
||||||
|
jmethodID mid_getName = env->GetMethodID(clsClass, "getName", "()Ljava/lang/String;");
|
||||||
|
jstring nameStr = (jstring)env->CallObjectMethod(clazz, mid_getName);
|
||||||
|
|
||||||
|
const char* temp = env->GetStringUTFChars(nameStr, NULL);
|
||||||
|
char* result = _strdup(temp);
|
||||||
|
env->ReleaseStringUTFChars(nameStr, temp);
|
||||||
|
env->DeleteLocalRef(nameStr);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper: macro to throw RuntimeException with message
|
||||||
|
static void throwRuntimeException(JNIEnv *env, const char *msg) {
|
||||||
|
jclass rte = env->FindClass("java/lang/RuntimeException");
|
||||||
|
if (rte != NULL) {
|
||||||
|
env->ThrowNew(rte, msg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// ================= ClassFileLoadHook ================= ///
|
||||||
|
|
||||||
|
void JNICALL ClassFileLoadHook(
|
||||||
|
jvmtiEnv* jvmti_env,
|
||||||
|
JNIEnv* jni_env,
|
||||||
|
jclass class_being_redefined,
|
||||||
|
jobject loader,
|
||||||
|
const char* name,
|
||||||
|
jobject protection_domain,
|
||||||
|
jint class_data_len,
|
||||||
|
const unsigned char* classbytes,
|
||||||
|
jint* new_class_data_len,
|
||||||
|
unsigned char** new_classbytes) {
|
||||||
|
|
||||||
|
// ---- capture class bytes ---- //
|
||||||
|
if (g_bytecodes_classname != NULL && g_bytecodes == NULL) {
|
||||||
|
if (strcmp(name, g_bytecodes_classname) == 0) {
|
||||||
|
g_bytecodes_len = class_data_len;
|
||||||
|
g_bytecodes = (unsigned char*)malloc(class_data_len);
|
||||||
|
memcpy(g_bytecodes, classbytes, class_data_len);
|
||||||
|
|
||||||
|
*new_classbytes = NULL;
|
||||||
|
*new_class_data_len = 0;
|
||||||
|
|
||||||
|
PLOGD.printf("[Hook:get] Captured class bytes of %s, len=%d", name, class_data_len);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- set class bytes from cache ---- //
|
||||||
|
if (RetransformClassCache.size == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < RetransformClassCache.size; i++) {
|
||||||
|
ClassBytesCacheType *entry = &RetransformClassCache.arr[i];
|
||||||
|
if (strcmp(entry->name, name) == 0) {
|
||||||
|
|
||||||
|
unsigned char *newBytes = nullptr;
|
||||||
|
jvmtiError err = jvmti_env->Allocate(entry->len, &newBytes);
|
||||||
|
if (err != JVMTI_ERROR_NONE || newBytes == nullptr) {
|
||||||
|
PLOGE.printf("[Hook:set] jvmti->Allocate failed for class %s, err=%d", name, err);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
memcpy(newBytes, entry->bytes, entry->len);
|
||||||
|
*new_classbytes = newBytes;
|
||||||
|
*new_class_data_len = entry->len;
|
||||||
|
|
||||||
|
PLOGI.printf("[Hook:set] Patched class: %s, new_len=%d", name, entry->len);
|
||||||
|
|
||||||
|
free(entry->name);
|
||||||
|
free(entry->bytes);
|
||||||
|
for (int j = i; j < RetransformClassCache.size - 1; j++) {
|
||||||
|
RetransformClassCache.arr[j] = RetransformClassCache.arr[j + 1];
|
||||||
|
}
|
||||||
|
RetransformClassCache.size--;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// ============ JNI Function ============ ///
|
||||||
|
C_EXPORT
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_init
|
||||||
|
(JNIEnv *env, jclass loader_class) {
|
||||||
|
PLOGI << "Invoked!";
|
||||||
|
|
||||||
|
// Get JavaVM
|
||||||
|
JavaVM* jvm = nullptr;
|
||||||
|
env->GetJavaVM(&jvm);
|
||||||
|
if (jvm == nullptr) {
|
||||||
|
PLOGE << "Failed to get JavaVM instance";
|
||||||
|
return JNI_FALSE;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get JVMTI
|
||||||
|
jvmtiEnv* jvmti = nullptr;
|
||||||
|
jvmtiError err = static_cast<jvmtiError>(jvm->GetEnv(reinterpret_cast<void**>(&jvmti), JVMTI_VERSION_1_2));
|
||||||
|
if (err != JVMTI_ERROR_NONE || jvmti == nullptr) {
|
||||||
|
PLOGE << "Failed to get JVMTI environment, error: " << err;
|
||||||
|
return JNI_FALSE;
|
||||||
|
}
|
||||||
|
|
||||||
|
int result = InitJuiceLoader(env, jvmti);
|
||||||
|
if (result != 0) {
|
||||||
|
PLOGE << "Failed to initialize JuiceLoader, error code: " << result;
|
||||||
|
return JNI_FALSE;
|
||||||
|
}
|
||||||
|
|
||||||
|
PLOGI << "JuiceLoader initialized successfully";
|
||||||
|
return JNI_TRUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
C_EXPORT
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
C_EXPORT
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
C_EXPORT
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
C_EXPORT
|
||||||
|
JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getLoadedClasses
|
||||||
|
(JNIEnv *env, jclass loader_class) {
|
||||||
|
PLOGI << "loader_getLoadedClasses invoked!";
|
||||||
|
|
||||||
|
if (!JuiceLoaderNative.jvmti) {
|
||||||
|
PLOGE << "JuiceLoaderNative.jvmti is NULL!";
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
jint count = 0;
|
||||||
|
jclass* classes = NULL;
|
||||||
|
jvmtiError result = JuiceLoaderNative.jvmti->GetLoadedClasses(&count, &classes);
|
||||||
|
if (result != JVMTI_ERROR_NONE || count == 0) {
|
||||||
|
if (classes) JuiceLoaderNative.jvmti->Deallocate((unsigned char*)classes);
|
||||||
|
return env->NewObjectArray(0, env->FindClass("java/lang/Class"), NULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
jclass classClass = env->FindClass("java/lang/Class");
|
||||||
|
jobjectArray classArray = env->NewObjectArray(count, classClass, NULL);
|
||||||
|
|
||||||
|
for (int i = 0; i < count; i++) {
|
||||||
|
env->SetObjectArrayElement(classArray, i, classes[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (classes) JuiceLoaderNative.jvmti->Deallocate((unsigned char*)classes);
|
||||||
|
return classArray;
|
||||||
|
}
|
||||||
|
|
||||||
|
C_EXPORT
|
||||||
|
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytes
|
||||||
|
(JNIEnv *env, jclass loader_class, jclass clazz) {
|
||||||
|
PLOGI << "getClassBytes Invoked!";
|
||||||
|
if (!JuiceLoaderNative.jvmti) {
|
||||||
|
PLOGE << "JuiceLoaderNative.jvmti is NULL!";
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
char* className = get_class_name(env, clazz);
|
||||||
|
if (!className) {
|
||||||
|
PLOGE << "Failed to get class name!";
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (char* p = className; *p; ++p) if (*p == '.') *p = '/';
|
||||||
|
|
||||||
|
g_bytecodes_classname = className;
|
||||||
|
g_bytecodes = NULL;
|
||||||
|
g_bytecodes_len = 0;
|
||||||
|
|
||||||
|
jclass classes[1] = { clazz };
|
||||||
|
jvmtiError err = JuiceLoaderNative.jvmti->RetransformClasses(1, classes);
|
||||||
|
if (err != JVMTI_ERROR_NONE) {
|
||||||
|
PLOGE.printf("RetransformClasses failed: %d", err);
|
||||||
|
free(className);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!g_bytecodes) {
|
||||||
|
PLOGW.printf("No bytecode captured for class: %s", className);
|
||||||
|
free(className);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
jbyteArray result = env->NewByteArray(g_bytecodes_len);
|
||||||
|
env->SetByteArrayRegion(result, 0, g_bytecodes_len, (jbyte*)g_bytecodes);
|
||||||
|
|
||||||
|
free(g_bytecodes);
|
||||||
|
free(className);
|
||||||
|
g_bytecodes = NULL;
|
||||||
|
g_bytecodes_classname = NULL;
|
||||||
|
g_bytecodes_len = 0;
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
C_EXPORT
|
||||||
|
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytesByName
|
||||||
|
(JNIEnv *env, jclass loader_class, jstring className) {
|
||||||
|
PLOGI << "getClassBytesByName Invoked!";
|
||||||
|
if (!JuiceLoaderNative.jvmti) {
|
||||||
|
PLOGE << "JuiceLoaderNative.jvmti is NULL!";
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char* cname = env->GetStringUTFChars(className, NULL);
|
||||||
|
jclass clazz = env->FindClass(cname);
|
||||||
|
env->ReleaseStringUTFChars(className, cname);
|
||||||
|
|
||||||
|
if (!clazz) {
|
||||||
|
PLOGE.printf("Failed to find class %s", cname);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytes(env, loader_class, clazz);
|
||||||
|
}
|
||||||
|
|
||||||
|
C_EXPORT
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClass
|
||||||
|
(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray classBytes, jint length) {
|
||||||
|
if (!JuiceLoaderNative.jvmti) {
|
||||||
|
PLOGE << "JuiceLoaderNative.jvmti is NULL! (retransformClass)";
|
||||||
|
return JNI_FALSE;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *name_dot = get_class_name(env, clazz);
|
||||||
|
char* name = _strdup(name_dot);
|
||||||
|
for (char* p = name; *p; ++p) if (*p == '.') *p = '/';
|
||||||
|
|
||||||
|
jbyte* bytes = env->GetByteArrayElements(classBytes, NULL);
|
||||||
|
jint len = env->GetArrayLength(classBytes);
|
||||||
|
|
||||||
|
if (RetransformClassCache.size >= RetransformClassCache.capacity) {
|
||||||
|
int new_capacity = RetransformClassCache.capacity == 0 ? 4 : RetransformClassCache.capacity * 2;
|
||||||
|
RetransformClassCache.arr = (ClassBytesCacheType*)realloc(RetransformClassCache.arr, new_capacity * sizeof(ClassBytesCacheType));
|
||||||
|
RetransformClassCache.capacity = new_capacity;
|
||||||
|
}
|
||||||
|
|
||||||
|
ClassBytesCacheType *entry = &RetransformClassCache.arr[RetransformClassCache.size++];
|
||||||
|
entry->name = _strdup(name);
|
||||||
|
entry->bytes = (unsigned char*)malloc(len);
|
||||||
|
memcpy(entry->bytes, bytes, len);
|
||||||
|
entry->len = len;
|
||||||
|
|
||||||
|
env->ReleaseByteArrayElements(classBytes, bytes, JNI_ABORT);
|
||||||
|
|
||||||
|
jclass classes[1] = { clazz };
|
||||||
|
jvmtiError err = JuiceLoaderNative.jvmti->RetransformClasses(1, classes);
|
||||||
|
if (err != JVMTI_ERROR_NONE) {
|
||||||
|
PLOGE.printf("RetransformClasses failed! [err=%d]", err);
|
||||||
|
free(name);
|
||||||
|
return JNI_FALSE;
|
||||||
|
}
|
||||||
|
|
||||||
|
PLOGI.printf("[retransformClass] Class retransformed: %s (len=%d)", entry->name, entry->len);
|
||||||
|
free(name);
|
||||||
|
return JNI_TRUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
C_EXPORT
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClassByName
|
||||||
|
(JNIEnv *env, jclass loader_class, jstring className, jbyteArray classBytes, jint length) {
|
||||||
|
const char *name_dot = env->GetStringUTFChars(className, NULL);
|
||||||
|
char *name = _strdup(name_dot);
|
||||||
|
for (char *p = name; *p; ++p) if (*p == '.') *p = '/';
|
||||||
|
env->ReleaseStringUTFChars(className, name_dot);
|
||||||
|
|
||||||
|
jclass target = env->FindClass(name);
|
||||||
|
free(name);
|
||||||
|
|
||||||
|
if (!target) {
|
||||||
|
PLOGE << "FindClass failed in retransformClassByName";
|
||||||
|
return JNI_FALSE;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClass(env, loader_class, target, classBytes, length);
|
||||||
|
}
|
||||||
|
|
||||||
|
C_EXPORT
|
||||||
|
JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassByName
|
||||||
|
(JNIEnv *env, jclass loader_class, jstring className) {
|
||||||
|
|
||||||
|
if (className == NULL) {
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
// jstring -> const char*
|
||||||
|
const char *name_utf = env->GetStringUTFChars(className, NULL);
|
||||||
|
if (name_utf == NULL) {
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
// find class
|
||||||
|
jclass clazz = env->FindClass(name_utf);
|
||||||
|
|
||||||
|
// clean up
|
||||||
|
env->ReleaseStringUTFChars(className, name_utf);
|
||||||
|
|
||||||
|
if (clazz == NULL) {
|
||||||
|
PLOGE.printf("Failed to find class %s", name_utf);
|
||||||
|
}
|
||||||
|
return clazz;
|
||||||
|
}
|
||||||
|
|
||||||
|
// static native Thread getThreadByName(String name)
|
||||||
|
C_EXPORT
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// static native ClassLoader injectJarToThread(Thread thread, String jarPath)
|
||||||
|
C_EXPORT
|
||||||
|
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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
/* DO NOT EDIT THIS FILE - it is machine generated */
|
||||||
|
#include <jni.h>
|
||||||
|
/* Header for class cn_xiaozhou233_juiceloader_JuiceLoader */
|
||||||
|
|
||||||
|
#ifndef _Included_cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
#define _Included_cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
* Method: init
|
||||||
|
* Signature: ()Z
|
||||||
|
*/
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_init
|
||||||
|
(JNIEnv *, jclass);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
* Method: injectJar
|
||||||
|
* Signature: (Ljava/lang/String;)Z
|
||||||
|
*/
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_injectJar
|
||||||
|
(JNIEnv *, jclass, jstring);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
* Method: redefineClass
|
||||||
|
* Signature: (Ljava/lang/Class;[BI)Z
|
||||||
|
*/
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_redefineClass
|
||||||
|
(JNIEnv *, jclass, jclass, jbyteArray, jint);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
* Method: redefineClassByName
|
||||||
|
* Signature: (Ljava/lang/String;[BI)Z
|
||||||
|
*/
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_redefineClassByName
|
||||||
|
(JNIEnv *, jclass, jstring, jbyteArray, jint);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
* Method: getLoadedClasses
|
||||||
|
* Signature: ()[Ljava/lang/Class;
|
||||||
|
*/
|
||||||
|
JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getLoadedClasses
|
||||||
|
(JNIEnv *, jclass);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
* Method: getClassBytes
|
||||||
|
* Signature: (Ljava/lang/Class;)[B
|
||||||
|
*/
|
||||||
|
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytes
|
||||||
|
(JNIEnv *, jclass, jclass);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
* Method: getClassBytesByName
|
||||||
|
* Signature: (Ljava/lang/String;)[B
|
||||||
|
*/
|
||||||
|
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytesByName
|
||||||
|
(JNIEnv *, jclass, jstring);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
* Method: retransformClass
|
||||||
|
* Signature: (Ljava/lang/Class;[BI)Z
|
||||||
|
*/
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClass
|
||||||
|
(JNIEnv *, jclass, jclass, jbyteArray, jint);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
* Method: retransformClassByName
|
||||||
|
* Signature: (Ljava/lang/String;[BI)Z
|
||||||
|
*/
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClassByName
|
||||||
|
(JNIEnv *, jclass, jstring, jbyteArray, jint);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
* Method: getClassByName
|
||||||
|
* Signature: (Ljava/lang/String;)Ljava/lang/Class;
|
||||||
|
*/
|
||||||
|
JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassByName
|
||||||
|
(JNIEnv *, jclass, jstring);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
* Method: nativeGetThreadByName
|
||||||
|
* Signature: (Ljava/lang/String;)Ljava/lang/Thread;
|
||||||
|
*/
|
||||||
|
JNIEXPORT jobject JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_nativeGetThreadByName
|
||||||
|
(JNIEnv *, jclass, jstring);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceloader_JuiceLoader
|
||||||
|
* Method: nativeInjectJarToThread
|
||||||
|
* Signature: (Ljava/lang/Thread;Ljava/lang/String;)Ljava/lang/ClassLoader;
|
||||||
|
*/
|
||||||
|
JNIEXPORT jobject JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_nativeInjectJarToThread
|
||||||
|
(JNIEnv *, jclass, jobject, jstring);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
#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;
|
||||||
|
|
||||||
|
#define C_EXPORT extern "C" __declspec(dllexport)
|
||||||
|
|
||||||
|
extern "C" __declspec(dllexport)
|
||||||
|
int InitJuiceLoader(JNIEnv *env, jvmtiEnv *jvmti);
|
||||||
|
|
||||||
|
void JNICALL ClassFileLoadHook(
|
||||||
|
jvmtiEnv* jvmti_env,
|
||||||
|
JNIEnv* jni_env,
|
||||||
|
jclass class_being_redefined,
|
||||||
|
jobject loader,
|
||||||
|
const char* name,
|
||||||
|
jobject protection_domain,
|
||||||
|
jint class_data_len,
|
||||||
|
const unsigned char* classbytes,
|
||||||
|
jint* new_class_data_len,
|
||||||
|
unsigned char** new_classbytes);
|
||||||
|
|
||||||
|
// JNI Functions
|
||||||
|
// public native static boolean init();
|
||||||
|
JNIEXPORT jboolean JNICALL loader_init(JNIEnv *env, jclass loader_class);
|
||||||
|
// public native static boolean injectJar(String jarPath);
|
||||||
|
JNIEXPORT jboolean JNICALL loader_injectJar(JNIEnv *env, jclass loader_class, jstring jarPath);
|
||||||
|
// public native static boolean redefineClass(Class<?> clazz, byte[] classBytes, int length);
|
||||||
|
JNIEXPORT jboolean JNICALL loader_redefineClass_clazz(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray classBytes, jint length);
|
||||||
|
// public native static boolean redefineClass(String className, byte[] classBytes, int length);
|
||||||
|
JNIEXPORT jboolean JNICALL loader_redefineClass_className(JNIEnv *env, jclass loader_class, jstring className, jbyteArray classBytes, jint length);
|
||||||
|
// public native static Class<?>[] getLoadedClasses();
|
||||||
|
JNIEXPORT jobjectArray JNICALL loader_getLoadedClasses(JNIEnv *env, jclass loader_class);
|
||||||
|
// public static native byte[] getClassBytes(Class<?> clazz);
|
||||||
|
JNIEXPORT jbyteArray JNICALL loader_getClassBytes(JNIEnv *env, jclass loader_class, jclass clazz);
|
||||||
|
// public static native byte[] getClassBytesByName(String className);
|
||||||
|
JNIEXPORT jbyteArray JNICALL loader_getClassBytesByName(JNIEnv *env, jclass loader_class, jstring className);
|
||||||
|
// public static native boolean retransformClass(Class<?> clazz, byte[] classBytes, int length);
|
||||||
|
JNIEXPORT jboolean JNICALL loader_retransformClass(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray classBytes, jint length);
|
||||||
|
// public static native boolean retransformClassByName(String className, byte[] classBytes, int length);
|
||||||
|
JNIEXPORT jboolean JNICALL loader_retransformClassByName(JNIEnv *env, jclass loader_class, jstring className, jbyteArray classBytes, jint length);
|
||||||
|
// public static native Class<?> getClassByName(String className);
|
||||||
|
JNIEXPORT jclass JNICALL loader_getClassByName(JNIEnv *env, jclass loader_class, jstring className);
|
||||||
|
JNIEXPORT jobject JNICALL loader_nativeGetThreadByName (JNIEnv* env, jclass, jstring jName);
|
||||||
|
JNIEXPORT jobject JNICALL loader_nativeInjectJarToThread (JNIEnv* env, jclass, jobject threadObj, jstring jJarPath);
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
// JVM
|
||||||
|
#include <jni.h>
|
||||||
|
#include <jvmti.h>
|
||||||
|
#include <JuiceAgent/Logger.hpp>
|
||||||
|
#include <juiceloader.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) {
|
||||||
|
// 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;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -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)
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
#ifndef GLOBALUTILS_H
|
|
||||||
#define GLOBALUTILS_H
|
|
||||||
|
|
||||||
#include "windows.h"
|
|
||||||
#include "stdio.h"
|
|
||||||
#include "jni.h"
|
|
||||||
#include "jvmti.h"
|
|
||||||
|
|
||||||
jint GetCreatedJVM(JavaVM**);
|
|
||||||
jint GetJNIEnv(JavaVM*, JNIEnv**);
|
|
||||||
jint GetJVMTI(JavaVM*, jvmtiEnv**);
|
|
||||||
|
|
||||||
#endif
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
#include "./GlobalUtils.h"
|
|
||||||
|
|
||||||
// Get JavaVM
|
|
||||||
jint GetCreatedJVM(JavaVM **out_jvm) {
|
|
||||||
if (!out_jvm) return JNI_ERR;
|
|
||||||
*out_jvm = NULL;
|
|
||||||
|
|
||||||
jint res = JNI_GetCreatedJavaVMs(out_jvm, 1, NULL);
|
|
||||||
if (res != JNI_OK || *out_jvm == NULL) {
|
|
||||||
MessageBoxA(NULL, "JNI_GetCreatedJavaVMs failed", "Error", MB_OK);
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
return JNI_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get JNIEnv
|
|
||||||
jint GetJNIEnv(JavaVM *jvm, JNIEnv **out_env) {
|
|
||||||
if (!jvm || !out_env) return JNI_ERR;
|
|
||||||
*out_env = NULL;
|
|
||||||
|
|
||||||
void *env = NULL;
|
|
||||||
jint res = (*jvm)->GetEnv(jvm, &env, JNI_VERSION_1_8);
|
|
||||||
if (res == JNI_OK && env != NULL) {
|
|
||||||
*out_env = (JNIEnv *)env;
|
|
||||||
return JNI_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Attach current thread
|
|
||||||
res = (*jvm)->AttachCurrentThread(jvm, &env, NULL);
|
|
||||||
if (res != JNI_OK || env == NULL) {
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
*out_env = (JNIEnv *)env;
|
|
||||||
return JNI_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get JVMTI
|
|
||||||
jint GetJVMTI(JavaVM *jvm, jvmtiEnv **out_jvmti) {
|
|
||||||
if (!jvm || !out_jvmti) return JNI_ERR;
|
|
||||||
*out_jvmti = NULL;
|
|
||||||
|
|
||||||
jint res = (*jvm)->GetEnv(jvm, (void**)out_jvmti, JVMTI_VERSION_1_2);
|
|
||||||
if (res == JNI_OK && *out_jvmti != NULL) {
|
|
||||||
return JNI_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
*out_jvmti = NULL;
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
Reference in new issue
Block a user