forked from BynBang/OpenPrestige
140 lines
5.5 KiB
Rust
140 lines
5.5 KiB
Rust
//! JVMTI state and the two natives of dev.zprestige.prestige.inject.NativeBridge.
|
|
use crate::jni::*;
|
|
use std::ffi::{c_char, c_void};
|
|
use std::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};
|
|
use std::sync::Mutex;
|
|
|
|
static JVMTI: AtomicPtr<*const *const c_void> = AtomicPtr::new(std::ptr::null_mut());
|
|
/// jclass whose bytes the ClassFileLoadHook should capture during the current RetransformClasses call (0 = none).
|
|
static CAPTURE_TARGET: AtomicUsize = AtomicUsize::new(0);
|
|
static CAPTURED: Mutex<Option<Vec<u8>>> = Mutex::new(None);
|
|
/// Serialises classBytes calls: CAPTURE_TARGET holds a thread-local jclass reference, so only one thread may capture at a time.
|
|
static CAPTURE_LOCK: Mutex<()> = Mutex::new(());
|
|
|
|
/// Acquires the JVMTI capabilities and enables the class file load hook. Called once from the worker thread.
|
|
pub unsafe fn init_jvmti(vm: VmPtr) -> Result<(), String> {
|
|
let jvmti = get_jvmti(vm)?;
|
|
let mut caps = Capabilities::default();
|
|
for bit in [CAN_REDEFINE_CLASSES, CAN_REDEFINE_ANY_CLASS, CAN_GENERATE_ALL_CLASS_HOOK_EVENTS, CAN_RETRANSFORM_CLASSES, CAN_RETRANSFORM_ANY_CLASS] {
|
|
caps.set(bit);
|
|
}
|
|
let rc = add_capabilities(jvmti, &caps);
|
|
if rc != 0 {
|
|
return Err(format!("AddCapabilities failed ({rc})"));
|
|
}
|
|
enable_class_file_load_hook(jvmti, class_file_load_hook)?;
|
|
JVMTI.store(jvmti, Ordering::SeqCst);
|
|
Ok(())
|
|
}
|
|
|
|
/// Copies the class bytes the JVM hands to us while a classBytes() call retransforms its target; never modifies anything.
|
|
unsafe extern "system" fn class_file_load_hook(
|
|
_jvmti: JvmtiPtr,
|
|
env: EnvPtr,
|
|
class_being_redefined: JClass,
|
|
_loader: JObject,
|
|
_name: *const c_char,
|
|
_domain: JObject,
|
|
data_len: JInt,
|
|
data: *const u8,
|
|
_new_len: *mut JInt,
|
|
_new_data: *mut *mut u8,
|
|
) {
|
|
let target = CAPTURE_TARGET.load(Ordering::SeqCst);
|
|
if target == 0 || class_being_redefined.is_null() || data.is_null() {
|
|
return;
|
|
}
|
|
let jni = Jni::new(env);
|
|
if jni.is_same_object(class_being_redefined, target as JObject) {
|
|
if let Ok(mut slot) = CAPTURED.lock() {
|
|
*slot = Some(std::slice::from_raw_parts(data, data_len as usize).to_vec());
|
|
}
|
|
}
|
|
}
|
|
|
|
/// byte[] classBytes(Class): the bytes the JVM currently holds for the class (HotSpot reconstitutes them for retransformation).
|
|
pub unsafe extern "system" fn native_class_bytes(env: EnvPtr, _cls: JClass, target: JClass) -> JObject {
|
|
let jvmti = JVMTI.load(Ordering::SeqCst);
|
|
if jvmti.is_null() {
|
|
return std::ptr::null_mut();
|
|
}
|
|
let _serial = CAPTURE_LOCK.lock();
|
|
if let Ok(mut slot) = CAPTURED.lock() {
|
|
*slot = None;
|
|
}
|
|
CAPTURE_TARGET.store(target as usize, Ordering::SeqCst);
|
|
let rc = retransform_class(jvmti, target);
|
|
CAPTURE_TARGET.store(0, Ordering::SeqCst);
|
|
if rc != 0 {
|
|
crate::log!("RetransformClasses failed ({rc})");
|
|
return std::ptr::null_mut();
|
|
}
|
|
let bytes = CAPTURED.lock().ok().and_then(|mut slot| slot.take());
|
|
let Some(bytes) = bytes else {
|
|
return std::ptr::null_mut();
|
|
};
|
|
let jni = Jni::new(env);
|
|
let array = jni.new_byte_array(bytes.len() as JInt);
|
|
if !array.is_null() {
|
|
jni.set_byte_array_region(array, 0, bytes.len() as JInt, bytes.as_ptr());
|
|
}
|
|
array
|
|
}
|
|
|
|
/// int redefine(Class, byte[]): JVMTI RedefineClasses of a single class; returns the JVMTI error code (0 = success).
|
|
pub unsafe extern "system" fn native_redefine(env: EnvPtr, _cls: JClass, target: JClass, bytes: JObject) -> JInt {
|
|
let jvmti = JVMTI.load(Ordering::SeqCst);
|
|
if jvmti.is_null() || bytes.is_null() {
|
|
return -1;
|
|
}
|
|
let jni = Jni::new(env);
|
|
let len = jni.get_array_length(bytes);
|
|
if len < 0 {
|
|
return -1;
|
|
}
|
|
let mut buf = vec![0u8; len as usize];
|
|
jni.get_byte_array_region(bytes, 0, len, buf.as_mut_ptr());
|
|
let def = ClassDefinition { klass: target, class_byte_count: len, class_bytes: buf.as_ptr() };
|
|
let rc = redefine_class(jvmti, &def);
|
|
if rc != 0 {
|
|
crate::log!("RedefineClasses failed ({rc})");
|
|
}
|
|
rc
|
|
}
|
|
|
|
/// void log(String): lets the Java side write progress lines into prestige-native.log.
|
|
pub unsafe extern "system" fn native_log(env: EnvPtr, _cls: JClass, message: JObject) {
|
|
if message.is_null() {
|
|
return;
|
|
}
|
|
let text = Jni::new(env).get_string_utf(message);
|
|
crate::log!("[java] {text}");
|
|
}
|
|
|
|
extern "system" {
|
|
fn FreeLibraryAndExitThread(module: *mut c_void, exit_code: u32) -> !;
|
|
}
|
|
|
|
/// void release(): stops the JVMTI hook and unloads this DLL after a short delay (self destruct).
|
|
/// Java must not call any native of NativeBridge afterwards.
|
|
pub unsafe extern "system" fn native_release(env: EnvPtr, cls: JClass) {
|
|
let jvmti = JVMTI.swap(std::ptr::null_mut(), Ordering::SeqCst);
|
|
if !jvmti.is_null() {
|
|
if let Err(e) = disable_class_file_load_hook(jvmti) {
|
|
crate::log!("release: {e}");
|
|
}
|
|
}
|
|
// Late calls from Java then throw UnsatisfiedLinkError instead of jumping into the unmapped DLL.
|
|
let rc = Jni::new(env).unregister_natives(cls);
|
|
if rc != JNI_OK {
|
|
crate::log!("release: UnregisterNatives failed ({rc})");
|
|
}
|
|
crate::log!("[java] released, unloading the loader");
|
|
let module = crate::MODULE as usize;
|
|
// The thread below runs code from this DLL until FreeLibraryAndExitThread; the delay lets in-flight native calls return.
|
|
let _ = std::thread::Builder::new().name("prestige-unload".into()).spawn(move || {
|
|
std::thread::sleep(std::time::Duration::from_millis(2000));
|
|
FreeLibraryAndExitThread(module as *mut c_void, 0);
|
|
});
|
|
}
|