|
| 1 | +const std = @import("std"); |
| 2 | +const jni = @import("JNI"); |
| 3 | +const win32 = @import("win32"); |
| 4 | + |
| 5 | +const cjni = jni.cjni; |
| 6 | +const windows = win32.everything; |
| 7 | + |
| 8 | +pub const Lullaby = struct { |
| 9 | + handle: std.os.windows.HMODULE, |
| 10 | + jvm: jni.JavaVM, |
| 11 | + env: jni.JNIEnv, |
| 12 | + |
| 13 | + const log = std.log.scoped(.lullaby); |
| 14 | + |
| 15 | + pub fn init(handle: std.os.windows.HMODULE) !Lullaby { |
| 16 | + var jvm_buf: [1][*c]cjni.JavaVM = undefined; |
| 17 | + var count: cjni.jint = 0; |
| 18 | + |
| 19 | + const res = cjni.JNI_GetCreatedJavaVMs(&jvm_buf, 1, &count); |
| 20 | + if (res != cjni.JNI_OK) { |
| 21 | + log.err("JNI_GetCreatedJavaVMs failed with code: {}", .{res}); |
| 22 | + return error.JniInitFailed; |
| 23 | + } |
| 24 | + if (count == 0) { |
| 25 | + log.err("No JVM found in the target process.", .{}); |
| 26 | + return error.NoJvmFound; |
| 27 | + } |
| 28 | + |
| 29 | + var jvm = jni.JavaVM.warp(jvm_buf[0]); |
| 30 | + var env: jni.JNIEnv = undefined; |
| 31 | + |
| 32 | + try jvm.attachCurrentThreadAsDaemon(&env, null); |
| 33 | + log.info("Attached to JVM successfully.", .{}); |
| 34 | + |
| 35 | + return Lullaby{ |
| 36 | + .handle = handle, |
| 37 | + .jvm = jvm, |
| 38 | + .env = env, |
| 39 | + }; |
| 40 | + } |
| 41 | + |
| 42 | + pub fn deinit(self: *Lullaby) void { |
| 43 | + self.jvm.detachCurrentThread() catch |err| { |
| 44 | + log.err("Failed to detach thread from JVM: {}", .{err}); |
| 45 | + }; |
| 46 | + log.info("Detached from JVM.", .{}); |
| 47 | + } |
| 48 | + |
| 49 | + pub fn run(self: *Lullaby) !void { |
| 50 | + defer self.deinit(); |
| 51 | + |
| 52 | + log.info("Lullaby running.", .{}); |
| 53 | + |
| 54 | + while (windows.GetAsyncKeyState(@as(i32, @intFromEnum(windows.VK_END))) == 0) { |
| 55 | + windows.Sleep(50); |
| 56 | + } |
| 57 | + } |
| 58 | +}; |
| 59 | + |
| 60 | +pub fn threadMain(handle: std.os.windows.HMODULE) void { |
| 61 | + const log = std.log.scoped(.lullaby_thread); |
| 62 | + |
| 63 | + var instance = Lullaby.init(handle) catch |err| { |
| 64 | + log.err("Failed to initialize Lullaby: {}", .{err}); |
| 65 | + windows.FreeLibraryAndExitThread(@ptrCast(handle), 0); |
| 66 | + return; |
| 67 | + }; |
| 68 | + instance.run() catch |err| { |
| 69 | + log.err("Runtime error: {}", .{err}); |
| 70 | + }; |
| 71 | + |
| 72 | + log.info("Unloading Lullaby DLL...", .{}); |
| 73 | + windows.FreeLibraryAndExitThread(@ptrCast(handle), 0); |
| 74 | +} |
0 commit comments