common.rs (1457B) - raw


      1 use jni::{objects::GlobalRef, JavaVM};
      2 use once_cell::sync::{Lazy, OnceCell};
      3 
      4 use crate::mapped_lib::MappedLib;
      5 
      6 static NATIVE_LIB_INSTANCE: OnceCell<GlobalRef> = OnceCell::new();
      7 static JAVA_VM: OnceCell<usize> = OnceCell::new();
      8 
      9 pub static CLIENT_MODULE: Lazy<MappedLib> = Lazy::new(|| {
     10     let mut client_module = MappedLib::new("libclient.so".into());
     11 
     12     if let Err(error) = client_module.search() {
     13         warn!("Unable to find libclient.so: {}", error);
     14 
     15         client_module = MappedLib::new("split_config.arm".into());
     16 
     17         if let Err(error) = client_module.search() {
     18             panic!("Unable to find split_config.arm: {}", error);
     19         }
     20     }
     21 
     22     client_module
     23 });
     24 
     25 
     26 pub fn set_native_lib_instance(instance: GlobalRef) {
     27     NATIVE_LIB_INSTANCE.set(instance).expect("NativeLib instance already set");
     28 }
     29 
     30 pub fn native_lib_instance() -> GlobalRef {
     31     NATIVE_LIB_INSTANCE.get().expect("NativeLib instance not set").clone()
     32 }
     33 
     34 pub fn set_java_vm(vm: *mut jni::sys::JavaVM) {
     35     JAVA_VM.set(vm as usize).expect("JavaVM already set");
     36 }
     37 
     38 pub fn java_vm() -> JavaVM {
     39     unsafe {
     40         JavaVM::from_raw(*JAVA_VM.get().expect("JavaVM not set") as *mut jni::sys::JavaVM).expect("Failed to get JavaVM")
     41     }
     42 }
     43 
     44 pub fn attach_jni_env(block: impl FnOnce(&mut jni::JNIEnv)) {
     45     let jvm = java_vm();
     46     let mut env: jni::AttachGuard = jvm.attach_current_thread().expect("Failed to attach to current thread");
     47 
     48     block(&mut env);
     49 }