1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
//! A thin JNI layer.
//!
//! Inside the process we no longer have to decode HotSpot's heap by hand: the
//! JVM exposes a proper API. `JNI_GetCreatedJavaVMs` hands us the VM that is
//! already running, and because our hook executes on the game's render thread —
//! itself a Java thread — `GetEnv` gives us a usable environment with no
//! attaching required.
//!
//! Two rules keep this safe:
//! * every frame runs inside a local reference frame, so references we make
//! while drawing are released together instead of leaking the heap away;
//! * every call that can throw is followed by an exception check, because a
//! pending exception makes the *next* JNI call undefined behaviour.
#![allow(non_snake_case)]
use std::ffi::{c_void, CString};
use jni_sys::{
jboolean, jclass, jdouble, jfieldID, jfloat, jint, jmethodID, jobject, jvalue, JNIEnv, JavaVM,
JNI_OK, JNI_VERSION_1_6,
};
#[cfg(windows)]
use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress};
type GetCreatedJavaVMs =
unsafe extern "system" fn(*mut *mut JavaVM, jint, *mut jint) -> jint;
/// Look up `JNI_GetCreatedJavaVMs` in the JVM we are living inside.
#[cfg(windows)]
unsafe fn get_created_java_vms() -> Option<GetCreatedJavaVMs> {
// SAFETY: jvm.dll is loaded (we are inside the JVM); the export is looked
// up by name and null-checked before being called.
let module = GetModuleHandleA(c"jvm.dll".as_ptr() as *const u8);
if module.is_null() {
return None;
}
let f = GetProcAddress(module, c"JNI_GetCreatedJavaVMs".as_ptr() as *const u8)?;
Some(std::mem::transmute(f))
}
/// The same, through the dynamic linker. libjvm.so is already mapped into this
/// process and exports the symbol globally, so the default scope finds it; the
/// explicit open is a fallback for a JVM loaded into a private namespace.
#[cfg(unix)]
unsafe fn get_created_java_vms() -> Option<GetCreatedJavaVMs> {
let name = c"JNI_GetCreatedJavaVMs";
let mut p = libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr());
if p.is_null() {
let h = libc::dlopen(c"libjvm.so".as_ptr(), libc::RTLD_NOW | libc::RTLD_NOLOAD);
if !h.is_null() {
p = libc::dlsym(h, name.as_ptr());
}
}
if p.is_null() {
return None;
}
Some(std::mem::transmute(p))
}
/// The JVM already running in this process, or None if there isn't one.
pub fn java_vm() -> Option<*mut JavaVM> {
// SAFETY: the export is looked up by name and null-checked before the call,
// and the out-parameters are plain stack slots.
unsafe {
let f = get_created_java_vms()?;
let mut vm: *mut JavaVM = std::ptr::null_mut();
let mut count: jint = 0;
if f(&mut vm, 1, &mut count) != JNI_OK || count < 1 || vm.is_null() {
return None;
}
Some(vm)
}
}
#[derive(Clone, Copy)]
pub struct Jni {
pub env: *mut JNIEnv,
}
impl Jni {
/// An environment for the calling thread, if it is already a Java thread.
/// The render thread is, which is exactly where our hook runs.
pub fn current(vm: *mut JavaVM) -> Option<Jni> {
// SAFETY: vm came from JNI_GetCreatedJavaVMs and its vtable is valid.
unsafe {
let mut env: *mut c_void = std::ptr::null_mut();
let get_env = (**vm).GetEnv?;
if get_env(vm, &mut env, JNI_VERSION_1_6 as jint) != JNI_OK || env.is_null() {
return None;
}
Some(Jni { env: env as *mut JNIEnv })
}
}
/// Reserve a batch of local references; dropping the guard frees them all.
pub fn frame(&self, capacity: jint) -> Option<Frame> {
// SAFETY: env is valid for this thread.
unsafe {
let push = (**self.env).PushLocalFrame?;
if push(self.env, capacity) != JNI_OK {
return None;
}
Some(Frame { env: self.env })
}
}
/// Clear any pending exception. A live exception poisons every later call,
/// so this runs after anything that can throw.
pub fn clear_exception(&self) -> bool {
// SAFETY: env is valid; both entry points are always present.
unsafe {
let check = match (**self.env).ExceptionCheck {
Some(f) => f,
None => return false,
};
if check(self.env) == 0 {
return false;
}
if let Some(clear) = (**self.env).ExceptionClear {
clear(self.env);
}
true
}
}
/// Look up a class by binary name ("net/minecraft/client/Minecraft").
///
/// `FindClass` resolves against the class loader of the current native
/// frame. In the render thread that is LWJGL's, which under Fabric is the
/// same loader the game's classes live in — but if that ever stops being
/// true we fall back to asking the thread's context class loader directly.
pub fn find_class(&self, name: &str) -> Option<jclass> {
// SAFETY: name is NUL-terminated for the call; result is checked.
unsafe {
let c = CString::new(name).ok()?;
let find = (**self.env).FindClass?;
let cls = find(self.env, c.as_ptr());
if !cls.is_null() {
return Some(cls);
}
self.clear_exception();
self.find_class_via_context_loader(name)
}
}
unsafe fn find_class_via_context_loader(&self, name: &str) -> Option<jclass> {
let find = (**self.env).FindClass?;
let thread_cls = find(self.env, c"java/lang/Thread".as_ptr());
if thread_cls.is_null() {
self.clear_exception();
return None;
}
let current = self.static_method(thread_cls, "currentThread", "()Ljava/lang/Thread;")?;
let call_obj = (**self.env).CallStaticObjectMethodA?;
let thread = call_obj(self.env, thread_cls, current, std::ptr::null());
if self.clear_exception() || thread.is_null() {
return None;
}
let get_loader =
self.method(thread_cls, "getContextClassLoader", "()Ljava/lang/ClassLoader;")?;
let call = (**self.env).CallObjectMethodA?;
let loader = call(self.env, thread, get_loader, std::ptr::null());
if self.clear_exception() || loader.is_null() {
return None;
}
let loader_cls = find(self.env, c"java/lang/ClassLoader".as_ptr());
if loader_cls.is_null() {
self.clear_exception();
return None;
}
let load = self.method(loader_cls, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;")?;
// loadClass wants dots, not slashes.
let dotted = self.new_string(&name.replace('/', "."))?;
let args = [jvalue { l: dotted }];
let cls = call(self.env, loader, load, args.as_ptr());
if self.clear_exception() || cls.is_null() {
return None;
}
Some(cls as jclass)
}
/// Define a class into a running class loader from raw bytecode.
///
/// This is how a handler written in Java gets into a game that was never
/// built to accept one: compile it here, hand the bytes to the loader that
/// already holds the game's classes, and it can see and be seen by them.
pub fn define_class(&self, name: &str, loader: jobject, bytes: &[u8]) -> Option<jclass> {
// SAFETY: name is NUL-terminated, and the buffer outlives the call.
unsafe {
let c = CString::new(name).ok()?;
let f = (**self.env).DefineClass?;
let cls = f(
self.env,
c.as_ptr(),
loader,
bytes.as_ptr() as *const i8,
bytes.len() as i32,
);
if self.clear_exception() || cls.is_null() {
None
} else {
Some(cls)
}
}
}
pub fn new_string(&self, s: &str) -> Option<jobject> {
// SAFETY: the UTF-8 buffer is NUL-terminated and outlives the call.
unsafe {
let c = CString::new(s).ok()?;
let f = (**self.env).NewStringUTF?;
let o = f(self.env, c.as_ptr());
if self.clear_exception() || o.is_null() {
None
} else {
Some(o)
}
}
}
/// Release one local reference early. Scanning thousands of entities in a
/// frame would otherwise pile up references until the frame ends.
pub fn delete_local(&self, obj: jobject) {
if obj.is_null() {
return;
}
// SAFETY: obj is a live local reference created on this thread.
unsafe {
if let Some(f) = (**self.env).DeleteLocalRef {
f(self.env, obj);
}
}
}
/// Promote a reference so it survives past the current frame.
pub fn global(&self, obj: jobject) -> Option<jobject> {
// SAFETY: obj is a live local reference.
unsafe {
let f = (**self.env).NewGlobalRef?;
let g = f(self.env, obj);
if g.is_null() {
None
} else {
Some(g)
}
}
}
/// Release a global reference. Pairs with `global`.
pub fn delete_global(&self, obj: jobject) {
if obj.is_null() {
return;
}
// SAFETY: obj came from NewGlobalRef and is released exactly once.
unsafe {
if let Some(f) = (**self.env).DeleteGlobalRef {
f(self.env, obj);
}
}
}
pub fn field(&self, cls: jclass, name: &str, sig: &str) -> Option<jfieldID> {
// SAFETY: both strings are NUL-terminated; a miss throws, so clear it.
unsafe {
let n = CString::new(name).ok()?;
let s = CString::new(sig).ok()?;
let f = (**self.env).GetFieldID?;
let id = f(self.env, cls, n.as_ptr(), s.as_ptr());
if self.clear_exception() || id.is_null() {
None
} else {
Some(id)
}
}
}
pub fn static_field(&self, cls: jclass, name: &str, sig: &str) -> Option<jfieldID> {
// SAFETY: as above.
unsafe {
let n = CString::new(name).ok()?;
let s = CString::new(sig).ok()?;
let f = (**self.env).GetStaticFieldID?;
let id = f(self.env, cls, n.as_ptr(), s.as_ptr());
if self.clear_exception() || id.is_null() {
None
} else {
Some(id)
}
}
}
pub fn method(&self, cls: jclass, name: &str, sig: &str) -> Option<jmethodID> {
// SAFETY: as above.
unsafe {
let n = CString::new(name).ok()?;
let s = CString::new(sig).ok()?;
let f = (**self.env).GetMethodID?;
let id = f(self.env, cls, n.as_ptr(), s.as_ptr());
if self.clear_exception() || id.is_null() {
None
} else {
Some(id)
}
}
}
pub fn static_method(&self, cls: jclass, name: &str, sig: &str) -> Option<jmethodID> {
// SAFETY: as above.
unsafe {
let n = CString::new(name).ok()?;
let s = CString::new(sig).ok()?;
let f = (**self.env).GetStaticMethodID?;
let id = f(self.env, cls, n.as_ptr(), s.as_ptr());
if self.clear_exception() || id.is_null() {
None
} else {
Some(id)
}
}
}
// ---- reads -------------------------------------------------------------
pub fn obj_field(&self, obj: jobject, id: jfieldID) -> Option<jobject> {
if obj.is_null() {
return None;
}
// SAFETY: obj is live and id was resolved against its class.
unsafe {
let f = (**self.env).GetObjectField?;
let v = f(self.env, obj, id);
if v.is_null() {
None
} else {
Some(v)
}
}
}
pub fn static_obj_field(&self, cls: jclass, id: jfieldID) -> Option<jobject> {
// SAFETY: cls is live and id was resolved against it.
unsafe {
let f = (**self.env).GetStaticObjectField?;
let v = f(self.env, cls, id);
if v.is_null() {
None
} else {
Some(v)
}
}
}
pub fn bool_field(&self, obj: jobject, id: jfieldID) -> Option<bool> {
if obj.is_null() {
return None;
}
// SAFETY: obj is live and id matches its class.
unsafe { Some((**self.env).GetBooleanField?(self.env, obj, id) != 0) }
}
pub fn int_field(&self, obj: jobject, id: jfieldID) -> Option<i32> {
if obj.is_null() {
return None;
}
// SAFETY: as above.
unsafe { Some((**self.env).GetIntField?(self.env, obj, id)) }
}
pub fn float_field(&self, obj: jobject, id: jfieldID) -> Option<f32> {
if obj.is_null() {
return None;
}
// SAFETY: as above.
unsafe { Some((**self.env).GetFloatField?(self.env, obj, id)) }
}
pub fn double_field(&self, obj: jobject, id: jfieldID) -> Option<f64> {
if obj.is_null() {
return None;
}
// SAFETY: as above.
unsafe { Some((**self.env).GetDoubleField?(self.env, obj, id)) }
}
// ---- writes ------------------------------------------------------------
//
// Unlike the external build, these go through the JVM, so the GC's write
// barriers run and object fields are as safe to set as primitive ones.
pub fn set_bool(&self, obj: jobject, id: jfieldID, v: bool) {
if obj.is_null() {
return;
}
// SAFETY: obj is live and id matches its class.
unsafe {
if let Some(f) = (**self.env).SetBooleanField {
f(self.env, obj, id, v as jboolean);
}
}
}
pub fn set_int(&self, obj: jobject, id: jfieldID, v: i32) {
if obj.is_null() {
return;
}
// SAFETY: as above.
unsafe {
if let Some(f) = (**self.env).SetIntField {
f(self.env, obj, id, v);
}
}
}
pub fn set_float(&self, obj: jobject, id: jfieldID, v: f32) {
if obj.is_null() {
return;
}
// SAFETY: as above.
unsafe {
if let Some(f) = (**self.env).SetFloatField {
f(self.env, obj, id, v as jfloat);
}
}
}
pub fn set_double(&self, obj: jobject, id: jfieldID, v: f64) {
if obj.is_null() {
return;
}
// SAFETY: as above.
unsafe {
if let Some(f) = (**self.env).SetDoubleField {
f(self.env, obj, id, v as jdouble);
}
}
}
pub fn set_static_bool(&self, cls: jclass, id: jfieldID, v: bool) {
// SAFETY: cls declares the field and it is a boolean.
unsafe {
if let Some(f) = (**self.env).SetStaticBooleanField {
f(self.env, cls, id, v as jboolean);
}
}
}
pub fn set_static_int(&self, cls: jclass, id: jfieldID, v: i32) {
// SAFETY: cls declares the static int field.
unsafe {
if let Some(f) = (**self.env).SetStaticIntField {
f(self.env, cls, id, v);
}
}
}
pub fn set_static_long(&self, cls: jclass, id: jfieldID, v: i64) {
// SAFETY: cls declares the static long field.
unsafe {
if let Some(f) = (**self.env).SetStaticLongField {
f(self.env, cls, id, v);
}
}
}
pub fn set_obj(&self, obj: jobject, id: jfieldID, v: jobject) {
if obj.is_null() {
return;
}
// SAFETY: as above; v may legitimately be null.
unsafe {
if let Some(f) = (**self.env).SetObjectField {
f(self.env, obj, id, v);
}
}
}
// ---- calls -------------------------------------------------------------
pub fn call_void(&self, obj: jobject, id: jmethodID, args: &[jvalue]) {
if obj.is_null() {
return;
}
// SAFETY: args matches the method's descriptor at every call site.
unsafe {
if let Some(f) = (**self.env).CallVoidMethodA {
f(self.env, obj, id, args.as_ptr());
}
self.clear_exception();
}
}
pub fn call_obj(&self, obj: jobject, id: jmethodID, args: &[jvalue]) -> Option<jobject> {
if obj.is_null() {
return None;
}
// SAFETY: as above.
unsafe {
let f = (**self.env).CallObjectMethodA?;
let v = f(self.env, obj, id, args.as_ptr());
if self.clear_exception() || v.is_null() {
None
} else {
Some(v)
}
}
}
pub fn call_static_obj(
&self,
cls: jclass,
id: jmethodID,
args: &[jvalue],
) -> Option<jobject> {
// SAFETY: args matches the method's descriptor at every call site.
unsafe {
let f = (**self.env).CallStaticObjectMethodA?;
let v = f(self.env, cls, id, args.as_ptr());
if self.clear_exception() || v.is_null() {
None
} else {
Some(v)
}
}
}
pub fn call_static_int(&self, cls: jclass, id: jmethodID, args: &[jvalue]) -> Option<i32> {
// SAFETY: args matches the method's descriptor at every call site.
unsafe {
let f = (**self.env).CallStaticIntMethodA?;
let v = f(self.env, cls, id, args.as_ptr());
if self.clear_exception() {
None
} else {
Some(v)
}
}
}
/// Construct a Java object. Used for the block positions the level wants.
pub fn new_object(&self, cls: jclass, ctor: jmethodID, args: &[jvalue]) -> Option<jobject> {
// SAFETY: ctor belongs to cls and args matches its descriptor.
unsafe {
let f = (**self.env).NewObjectA?;
let v = f(self.env, cls, ctor, args.as_ptr());
if self.clear_exception() || v.is_null() {
None
} else {
Some(v)
}
}
}
pub fn call_bool(&self, obj: jobject, id: jmethodID, args: &[jvalue]) -> Option<bool> {
if obj.is_null() {
return None;
}
// SAFETY: as above.
unsafe {
let f = (**self.env).CallBooleanMethodA?;
let v = f(self.env, obj, id, args.as_ptr());
if self.clear_exception() {
None
} else {
Some(v != 0)
}
}
}
/// Call a method without virtual dispatch — which is how a private method
/// has to be invoked, since it has no vtable slot to look up.
pub fn call_nonvirtual_bool(
&self,
obj: jobject,
cls: jclass,
id: jmethodID,
args: &[jvalue],
) -> Option<bool> {
if obj.is_null() {
return None;
}
// SAFETY: cls declares the method and args matches its descriptor.
unsafe {
let f = (**self.env).CallNonvirtualBooleanMethodA?;
let v = f(self.env, obj, cls, id, args.as_ptr());
if self.clear_exception() {
None
} else {
Some(v != 0)
}
}
}
pub fn call_float(&self, obj: jobject, id: jmethodID, args: &[jvalue]) -> Option<f32> {
if obj.is_null() {
return None;
}
// SAFETY: as above.
unsafe {
let f = (**self.env).CallFloatMethodA?;
let v = f(self.env, obj, id, args.as_ptr());
if self.clear_exception() {
None
} else {
Some(v)
}
}
}
pub fn call_double(&self, obj: jobject, id: jmethodID, args: &[jvalue]) -> Option<f64> {
if obj.is_null() {
return None;
}
// SAFETY: as above.
unsafe {
let f = (**self.env).CallDoubleMethodA?;
let v = f(self.env, obj, id, args.as_ptr());
if self.clear_exception() {
None
} else {
Some(v)
}
}
}
pub fn call_int(&self, obj: jobject, id: jmethodID, args: &[jvalue]) -> Option<i32> {
if obj.is_null() {
return None;
}
// SAFETY: as above.
unsafe {
let f = (**self.env).CallIntMethodA?;
let v = f(self.env, obj, id, args.as_ptr());
if self.clear_exception() {
None
} else {
Some(v)
}
}
}
/// Reference identity, used to keep the local player out of scans.
pub fn same_object(&self, a: jobject, b: jobject) -> bool {
// SAFETY: both are live references (or null, which is allowed).
unsafe {
match (**self.env).IsSameObject {
Some(f) => f(self.env, a, b) != 0,
None => false,
}
}
}
/// `obj instanceof cls`
pub fn is_instance(&self, obj: jobject, cls: jclass) -> bool {
if obj.is_null() || cls.is_null() {
return false;
}
// SAFETY: both references are live.
unsafe {
match (**self.env).IsInstanceOf {
Some(f) => f(self.env, obj, cls) != 0,
None => false,
}
}
}
pub fn rust_string(&self, s: jobject) -> Option<String> {
if s.is_null() {
return None;
}
// SAFETY: s is a java.lang.String; the buffer is released before return.
unsafe {
let get = (**self.env).GetStringUTFChars?;
let release = (**self.env).ReleaseStringUTFChars?;
let ptr = get(self.env, s, std::ptr::null_mut());
if ptr.is_null() {
return None;
}
let out = std::ffi::CStr::from_ptr(ptr).to_string_lossy().into_owned();
release(self.env, s, ptr);
Some(out)
}
}
}
/// Releases every local reference made inside it.
pub struct Frame {
env: *mut JNIEnv,
}
impl Drop for Frame {
fn drop(&mut self) {
// SAFETY: matched with the PushLocalFrame that produced this guard.
unsafe {
if let Some(pop) = (**self.env).PopLocalFrame {
pop(self.env, std::ptr::null_mut());
}
}
}
}