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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
//! Lodestone client — injected into Minecraft, drawn inside its own window.
//!
//! Flow:
//! DllMain spawns a thread so the loader lock is released at once
//! init waits for glfw.dll, then hooks glfwSwapBuffers
//! swap_buffers runs once per frame, on the game's render thread:
//! - first call sets up the window hook, GL and JNI
//! - applies the enabled modules through JNI
//! - draws the menu into the frame the game just built
//! - calls the real glfwSwapBuffers
//!
//! Running on the render thread is what makes the JNI side simple: it is a
//! Java thread, already attached, and the game is not concurrently mutating the
//! objects we touch.
pub mod blocks;
pub mod capture;
pub mod config;
pub mod extras;
pub mod cheats;
pub mod hook;
/// Input arrives through a window-procedure subclass on Windows and through
/// GLFW's own callbacks on Linux; both hand the menu the same `UiInput`.
#[cfg(windows)]
pub mod input;
#[cfg(unix)]
#[path = "input_unix.rs"]
pub mod input;
pub mod jni;
pub mod mc;
pub mod overlay;
pub mod state;
pub mod tap;
use std::ffi::c_void;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::OnceLock;
#[cfg(windows)]
use windows_sys::Win32::Foundation::HMODULE;
#[cfg(windows)]
use windows_sys::Win32::System::LibraryLoader::DisableThreadLibraryCalls;
#[cfg(windows)]
use windows_sys::Win32::System::Threading::CreateThread;
use crate::jni::Jni;
use crate::mc::{Interact, Mc, TargetKind, World};
static HOOK: OnceLock<hook::Hook> = OnceLock::new();
#[cfg(windows)]
static MODULE: std::sync::atomic::AtomicIsize = std::sync::atomic::AtomicIsize::new(0);
static UNLOADING: AtomicBool = AtomicBool::new(false);
/// How many threads are currently executing inside our detour. The module must
/// not be freed while this is above zero.
static IN_DETOUR: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
static FRAMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
// ---------------------------------------------------------------------------
// entry point
// ---------------------------------------------------------------------------
#[cfg(windows)]
#[no_mangle]
pub extern "system" fn DllMain(module: HMODULE, reason: u32, _reserved: *mut c_void) -> i32 {
const DLL_PROCESS_ATTACH: u32 = 1;
if reason == DLL_PROCESS_ATTACH {
MODULE.store(module as isize, Ordering::SeqCst);
// SAFETY: both calls are documented as safe from DllMain, and the
// thread body does all the real work outside the loader lock.
unsafe {
DisableThreadLibraryCalls(module);
CreateThread(
std::ptr::null(),
0,
Some(init),
std::ptr::null_mut(),
0,
std::ptr::null_mut(),
);
}
}
1
}
/// Linux entry point. An `.init_array` entry runs both when the loader pulls us
/// in through `LD_PRELOAD` and when a `dlopen` lands us in an already-running
/// game, so one constructor covers both ways in.
#[cfg(unix)]
#[used]
#[link_section = ".init_array"]
static LODESTONE_CTOR: extern "C" fn() = lodestone_start;
#[cfg(unix)]
extern "C" fn lodestone_start() {
// Get off the loader's thread at once, exactly as the Windows path does:
// the dynamic linker holds a lock here, and the body below sleeps waiting
// for GLFW to turn up.
std::thread::spawn(|| unsafe { init_body() });
}
/// The folder this DLL was loaded from. Everything the client reads or writes
/// lives beside it, so the pair can be dropped anywhere and still work.
#[cfg(windows)]
pub fn client_dir() -> std::path::PathBuf {
use windows_sys::Win32::System::LibraryLoader::GetModuleFileNameW;
let module = MODULE.load(Ordering::SeqCst);
let mut buf = [0u16; 520];
// SAFETY: module is our own handle, stored in DllMain; buf is sized in
// characters as the call expects.
let len = unsafe { GetModuleFileNameW(module as HMODULE, buf.as_mut_ptr(), buf.len() as u32) };
if len == 0 {
return std::path::PathBuf::from(".");
}
let path = std::path::PathBuf::from(String::from_utf16_lossy(&buf[..len as usize]));
path.parent().map(|p| p.to_path_buf()).unwrap_or_else(|| std::path::PathBuf::from("."))
}
/// The same question on Linux, asked of the dynamic linker: `dladdr` on one of
/// our own functions reports the file the symbol came from, which is this .so.
#[cfg(unix)]
pub fn client_dir() -> std::path::PathBuf {
let fallback = || std::path::PathBuf::from(".");
// SAFETY: the address is a function in this very library, and the info
// struct is only read after a non-zero (success) return.
unsafe {
let mut info: libc::Dl_info = std::mem::zeroed();
let here = client_dir as *const () as *const c_void;
if libc::dladdr(here, &mut info) == 0 || info.dli_fname.is_null() {
return fallback();
}
let name = std::ffi::CStr::from_ptr(info.dli_fname).to_string_lossy().into_owned();
std::path::PathBuf::from(name)
.parent()
.map(|p| p.to_path_buf())
.unwrap_or_else(fallback)
}
}
/// ARGB for each kind of thing, for the gizmo renderer.
fn kind_colour(kind: TargetKind) -> i32 {
(match kind {
TargetKind::Player => 0xFF_F0606Eu32,
TargetKind::Mob => 0xFF_ECA054,
TargetKind::Animal => 0xFF_7ED88C,
TargetKind::Item => 0xFF_78BEEC,
TargetKind::Other => 0xFF_AAAAAA,
}) as i32
}
pub fn log(msg: &str) {
use std::io::Write;
if let Ok(mut f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(client_dir().join("lodestone.log"))
{
let _ = writeln!(f, "{msg}");
}
}
/// Everything the client does before the first frame. Shared by both platforms:
/// only the way we got here, and the way symbols are looked up, differ.
unsafe fn init_body() {
log("--- lodestone client starting ---");
// A panic inside the render hook would otherwise vanish into catch_unwind.
std::panic::set_hook(Box::new(|info| {
log(&format!("PANIC: {info}"));
}));
// The game loads GLFW early, but not necessarily before us.
let mut swap: *mut c_void = std::ptr::null_mut();
for _ in 0..600 {
if let Some(f) = glfw::proc(b"glfwSwapBuffers\0") {
swap = f as *const () as *mut c_void;
break;
}
std::thread::sleep(std::time::Duration::from_millis(100));
}
if swap.is_null() {
log("glfwSwapBuffers never appeared — giving up");
return;
}
log(&format!("glfwSwapBuffers at {swap:p}"));
let hooked = match hook::install(swap, swap_buffers as *const c_void) {
Ok(h) => {
let _ = HOOK.set(h);
log("hook installed");
state::with(|s| s.status = "hooked".into());
true
}
Err(e) => {
log(&format!("hook failed: {e}"));
state::with(|s| s.status = format!("hook failed: {e}"));
false
}
};
// Watchdog: the loader drops a marker file to ask us to leave, which is how
// a rebuild gets the old copy out of the way without restarting the game.
loop {
std::thread::sleep(std::time::Duration::from_millis(250));
if client_dir().join(UNLOAD_MARKER).exists() {
if !hooked {
log("unload marker seen; nothing was hooked");
return;
}
// If the detour has never run, the game is not drawing and the
// render thread will never see the request — which used to strand
// the hook until the game was restarted, blocking every later
// build. Nothing can be *inside* a detour that has never executed,
// so in that one case it is safe to pull the hook out from here
// rather than wait for a frame that is not coming.
if FRAMES.load(Ordering::SeqCst) == 0 {
UNLOADING.store(true, Ordering::SeqCst);
if let Some(h) = HOOK.get() {
h.remove();
}
log("unload marker seen with no frame ever drawn; hook removed off-thread");
return;
}
// Ask the render thread to unwind the hooks in the right order,
// and keep asking. Returning after one sighting used to strand a
// copy for good: if the marker appeared while the game was not
// drawing, the request was never acted on and there was no longer
// a thread here to repeat it.
state::with(|s| s.eject = true);
if UNLOADING.load(Ordering::SeqCst) {
return;
}
}
}
}
/// The Windows thread entry, which is just the shared body plus a return code.
#[cfg(windows)]
unsafe extern "system" fn init(_: *mut c_void) -> u32 {
init_body();
0
}
const UNLOAD_MARKER: &str = "unload";
// ---------------------------------------------------------------------------
// per-frame
// ---------------------------------------------------------------------------
/// Everything that may only be touched from the render thread.
struct Render {
overlay: overlay::Overlay,
jni: Jni,
mc: Option<Mc>,
world: Option<World>,
blocks: Option<blocks::Blocks>,
interact: Option<Interact>,
extras: Option<extras::Extras>,
tap: Option<tap::Tap>,
skin: Option<mc::Skin>,
/// The last skin we resolved, and the session name. Cached because the
/// profile lookup is heavier than asking an entity, and because neither
/// changes while the game is running.
skin_cache: (u32, bool),
player_name: String,
last_skin_poll: std::time::Instant,
last_tap_poll: std::time::Instant,
blips: Vec<extras::Blip>,
last_chunk_rate: std::time::Instant,
last_base_scan: std::time::Instant,
saved: cheats::Saved,
window: *mut c_void,
/// The Win32 HWND on Windows; unused on Linux, where input rides GLFW's own
/// callbacks and there is no window handle to subclass.
#[cfg_attr(unix, allow(dead_code))]
window_handle: isize,
menu_was_open: bool,
saved_cursor_mode: i32,
}
/// Only ever read or written inside `swap_buffers`, which the game calls from a
/// single thread.
static mut RENDER: Option<Render> = None;
unsafe extern "C" fn swap_buffers(window: *mut c_void) {
IN_DETOUR.fetch_add(1, Ordering::SeqCst);
if !UNLOADING.load(Ordering::SeqCst) {
let n = FRAMES.fetch_add(1, Ordering::Relaxed);
if n % 600 == 0 {
log(&format!("frame {n}"));
}
// A panic must never unwind into the game's C frame.
let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| frame(window)));
}
if let Some(h) = HOOK.get() {
let original: unsafe extern "C" fn(*mut c_void) = std::mem::transmute(h.trampoline);
original(window);
}
IN_DETOUR.fetch_sub(1, Ordering::SeqCst);
}
unsafe fn frame(window: *mut c_void) {
let slot = &raw mut RENDER;
if (*slot).is_none() {
match setup(window) {
Ok(r) => {
*slot = Some(r);
log("render state ready");
}
Err(e) => {
log(&format!("setup failed: {e}"));
state::with(|s| s.status = e.clone());
// Try again next frame: the world may not exist yet.
return;
}
}
}
let Some(r) = (*slot).as_mut() else { return };
// Cursor: while the menu is open the game must release the mouse, and get
// it back exactly as it was when the menu closes.
let open = state::with(|s| s.menu_open).unwrap_or(false);
if open != r.menu_was_open {
if open {
r.saved_cursor_mode = glfw::get_input_mode(r.window, glfw::CURSOR);
glfw::set_input_mode(r.window, glfw::CURSOR, glfw::CURSOR_NORMAL);
} else if r.saved_cursor_mode != 0 {
glfw::set_input_mode(r.window, glfw::CURSOR, r.saved_cursor_mode);
}
// Throw away the mouse motion that happened while the cursor was free,
// on both transitions, so neither open nor close snaps the camera.
if let Some(mcx) = r.mc.as_ref() {
if let Some(instance) = mcx.instance(&r.jni) {
mcx.reset_mouse_delta(&r.jni, instance);
}
}
r.menu_was_open = open;
}
// Modules, inside a local frame so nothing leaks.
if let Some(mcx) = r.mc.as_ref() {
if let Some(_guard) = r.jni.frame(256) {
let cfg = state::with(|s| s.cfg.clone());
if let Some(cfg) = cfg {
let mut game = cheats::apply(
&r.jni,
mcx,
r.world.as_ref(),
r.blocks.as_ref(),
r.interact.as_ref(),
&cfg,
&mut r.saved,
);
// Blocks are scanned incrementally, so this only costs a slice
// of the volume per frame.
if let (Some(scan), true) = (r.blocks.as_mut(), game.in_world) {
if let Some(instance) = mcx.instance(&r.jni) {
if let Some(level) = mcx.level(&r.jni, instance) {
// Ores have to be swept; a slice per frame.
if cfg.esp.xray {
scan.step_ores(
&r.jni,
level,
game.pos,
cfg.esp.block_radius as i32,
&cfg.esp.xray_selected,
// Each position is a Java allocation and
// three calls; this is a per-frame budget,
// so keep it modest.
1024,
);
game.blocks = scan.ores.clone();
}
// Block entities come from a list the client keeps,
// so this is cheap enough to redo periodically
// rather than continuously.
if cfg.esp.containers || cfg.esp.base_finder {
let due = r.last_base_scan.elapsed().as_secs_f32() > 1.0;
if due {
r.last_base_scan = std::time::Instant::now();
scan.scan_block_entities(
&r.jni,
level,
game.pos,
cfg.esp.base_chunk_radius as i32,
cfg.esp.base_finder && !cfg.esp.containers,
);
}
game.base_hits = scan.entities.clone();
}
}
}
}
// ---- the three 26.2 channels --------------------------
if let (Some(ex), Some(instance)) =
(r.extras.as_ref(), mcx.instance(&r.jni))
{
let player = mcx.player(&r.jni, instance);
// Claim a higher chunk absorption rate than we measured.
// Refreshed on a timer because the game recomputes it from
// its own measurements every batch.
if let (true, Some(player)) = (cfg.visuals.fast_chunks, player) {
if r.last_chunk_rate.elapsed().as_millis() > 250 {
r.last_chunk_rate = std::time::Instant::now();
ex.set_chunk_rate(&r.jni, player, cfg.visuals.fast_chunks_rate);
}
}
// Players the server tracks for the locator bar.
if let (true, Some(player)) = (cfg.esp.player_radar, player) {
ex.waypoints(&r.jni, player, &mut r.blips);
game.blips = r
.blips
.iter()
.map(|b| (b.x, b.y, b.z, b.coarse))
.collect();
} else {
r.blips.clear();
}
// Draw through the game's own renderer.
if cfg.esp.gizmo_esp && game.in_world {
let targets = &game.targets;
let blips = &game.blips;
let ghost = game.ghost;
ex.with_gizmos(&r.jni, instance, |pen| {
for t in targets.iter().take(128) {
pen.box_at(t.min, t.max, kind_colour(t.kind), true);
}
if let Some((p, d)) = ghost {
let colour = if d > 1.0 {
0xFF_FF5555u32
} else {
0xFF_78B4FF
} as i32;
pen.box_at(
(p.0 - 0.3, p.1, p.2 - 0.3),
(p.0 + 0.3, p.1 + 1.8, p.2 + 0.3),
colour,
true,
);
}
for (x, y, z, coarse) in blips.iter().take(64) {
let half = if *coarse { 8.0 } else { 0.4 };
let y = if y.is_nan() { game.pos.1 } else { *y };
pen.box_at(
(x - half, y - 1.0, z - half),
(x + half, y + 2.0, z + half),
0xFF_FF78FFu32 as i32,
true,
);
}
});
}
}
// ---- backtrack ----------------------------------------
if let (Some(t), Some(instance)) = (r.tap.as_mut(), mcx.instance(&r.jni)) {
if let Some(player) = mcx.player(&r.jni, instance) {
if cfg.combat.backtrack {
t.attach_backtrack(&r.jni, player);
t.set_backtrack(
&r.jni,
true,
game.backtrack_target,
cfg.combat.backtrack_ms as i64,
);
} else {
t.set_backtrack(&r.jni, false, -1, 0);
}
}
}
// ---- packet tap ---------------------------------------
if let (Some(t), Some(instance)) = (r.tap.as_mut(), mcx.instance(&r.jni)) {
if let Some(player) = mcx.player(&r.jni, instance) {
if cfg.misc.packet_log {
game.tap_attached = t.attach(&r.jni, player);
t.set_recording(&r.jni, true);
// Summarising walks a map; once a second is plenty
// for something a human reads.
if r.last_tap_poll.elapsed().as_millis() > 500 {
r.last_tap_poll = std::time::Instant::now();
if let Some(mut rows) = t.summary(&r.jni) {
rows.sort_by(|a, b| (b.1 + b.2).cmp(&(a.1 + a.2)));
// Mirror to disk so the log is readable
// without seeing the screen.
let mut dump = String::from("packet sent received\n");
for (name, sent, recv) in &rows {
dump.push_str(&format!("{name} {sent} {recv}\n"));
}
let _ = std::fs::write(
client_dir().join("packets.txt"),
dump,
);
game.packets = rows;
}
game.channels = t.channels(&r.jni);
game.server_brand = r
.world
.as_ref()
.and_then(|w| w.server_brand(&r.jni, player))
.unwrap_or_default();
// Fingerprint dump: brand + channels to disk.
let mut fp = format!("brand: {}\n\nchannels:\n", game.server_brand);
for (chan, count) in &game.channels {
fp.push_str(&format!(" {chan} x{count}\n"));
}
let _ = std::fs::write(client_dir().join("fingerprint.txt"), fp);
// Drop the per-packet backlog so it cannot grow.
let _ = t.drain(&r.jni);
}
} else {
t.set_recording(&r.jni, false);
}
}
}
// ---- who you are, and your skin (for the ESP preview) -
// The game already has the skin resident as a GL texture, so
// this only asks which one. In a world the player entity knows;
// at the main menu there is no entity, so the skin manager
// answers for the profile instead — that lookup is heavier, so
// it is only retried every half second.
if let (Some(sk), Some(instance)) = (r.skin.as_ref(), mcx.instance(&r.jni)) {
if r.player_name.is_empty() {
if let Some(name) = sk.name(&r.jni, instance) {
r.player_name = name;
}
}
let from_entity = mcx
.player(&r.jni, instance)
.and_then(|p| sk.of(&r.jni, instance, p));
if let Some(found) = from_entity {
r.skin_cache = found;
} else if r.last_skin_poll.elapsed().as_millis() > 500 {
r.last_skin_poll = std::time::Instant::now();
if let Some(found) = sk.of_profile(&r.jni, instance) {
r.skin_cache = found;
}
}
game.skin_texture = r.skin_cache.0;
game.skin_slim = r.skin_cache.1;
game.player_name = r.player_name.clone();
}
state::with(|s| s.game = game);
}
}
}
let (w, h) = glfw::framebuffer_size(r.window);
if w > 0 && h > 0 {
let fps = r.overlay.fps();
state::with(|s| {
s.game.fps = fps;
r.overlay.draw(w, h, s);
});
}
if state::with(|s| s.eject).unwrap_or(false) {
log("unload requested");
unload(r);
}
}
unsafe fn setup(window: *mut c_void) -> Result<Render, String> {
// Windows subclasses the window procedure, which needs the HWND behind the
// GLFW window. Linux has no such thing and hooks GLFW's callbacks instead.
#[cfg(windows)]
let window_handle = {
let hwnd = glfw::win32_window(window);
if hwnd == 0 {
return Err("glfwGetWin32Window returned null".into());
}
capture::set_window(hwnd);
if !input::install(hwnd as windows_sys::Win32::Foundation::HWND) {
log("window procedure hook failed");
}
hwnd
};
#[cfg(unix)]
let window_handle = {
if !input::install(window) {
log("glfw input hook failed");
}
0isize
};
let overlay = overlay::Overlay::new()?;
log("gl painter created");
let vm = jni::java_vm().ok_or("no JVM in this process")?;
let jni = Jni::current(vm).ok_or("this thread is not attached to the JVM")?;
log("jni environment acquired");
let mut world = None;
let mut block_scan = None;
let mut interact = None;
let mut extra = None;
let mut tap_handler = None;
let mut skin = None;
let mc = match Mc::resolve(&jni) {
Ok(m) => {
if m.missing.is_empty() {
log("all minecraft names resolved");
} else {
log(&format!("unresolved: {}", m.missing.join(", ")));
}
let mut missing = m.missing.clone();
world = World::resolve(&jni, &m, &mut missing);
block_scan = blocks::Blocks::resolve(&jni, &mut missing);
interact = Interact::resolve(&jni, &m, &mut missing);
extra = Some(extras::Extras::resolve(&jni, &m, &mut missing));
tap_handler = tap::Tap::resolve(&jni, &m);
skin = mc::Skin::resolve(&jni, &mut missing);
if tap_handler.is_none() {
log("packet tap unavailable");
}
if interact.is_none() {
log("interaction unavailable: placing and inventory are off");
}
if block_scan.is_none() {
log("block scanning unavailable: x-ray and container esp are off");
}
if world.is_none() {
log("world bindings unavailable: combat and ESP are off");
}
if !missing.is_empty() {
log(&format!("unresolved: {}", missing.join(", ")));
}
state::with(|s| {
s.missing = missing;
s.status = "ready".into();
});
Some(m)
}
Err(e) => {
log(&format!("minecraft bindings failed: {e}"));
state::with(|s| s.status = format!("bindings: {e}"));
None
}
};
// Pick up settings from the last session, if there are any.
match config::load_into_shared() {
Ok(true) => log("config loaded"),
Ok(false) => {}
Err(e) => log(&format!("config load failed: {e}")),
}
Ok(Render {
overlay,
jni,
mc,
world,
blocks: block_scan,
interact,
extras: extra,
tap: tap_handler,
skin,
skin_cache: (0, false),
player_name: String::new(),
last_skin_poll: std::time::Instant::now() - std::time::Duration::from_secs(1),
last_tap_poll: std::time::Instant::now(),
blips: Vec::new(),
last_chunk_rate: std::time::Instant::now(),
last_base_scan: std::time::Instant::now()
- std::time::Duration::from_secs(5),
saved: cheats::Saved::default(),
window,
window_handle,
menu_was_open: false,
saved_cursor_mode: 0,
})
}
/// Stop the client: hooks out, game state restored, nothing drawn.
///
/// It deliberately does **not** unmap the module. A DLL that patched a window
/// procedure, installed a panic hook and left Rust thread-locals behind cannot
/// prove that nothing in the process still points into its code, and unmapping
/// it while one pointer survives crashes the game — which is exactly what an
/// earlier version of this did. A few megabytes of idle address space is a
/// much better trade. Restart the game to be rid of it entirely.
unsafe fn unload(r: &mut Render) {
UNLOADING.store(true, Ordering::SeqCst);
if let Some(mcx) = r.mc.as_ref() {
if let Some(_guard) = r.jni.frame(32) {
cheats::restore(&r.jni, mcx, r.world.as_ref(), &mut r.saved);
}
}
capture::apply(false);
#[cfg(windows)]
let restored = input::remove(r.window_handle as windows_sys::Win32::Foundation::HWND);
#[cfg(unix)]
let restored = input::remove(r.window);
if r.saved_cursor_mode != 0 {
glfw::set_input_mode(r.window, glfw::CURSOR, r.saved_cursor_mode);
}
if let Some(h) = HOOK.get() {
h.remove();
}
state::with(|s| {
s.eject = false;
s.menu_open = false;
s.status = "unloaded".into();
});
log(&format!(
"unloaded: hooks removed, settings restored, window procedure {} — module stays resident",
if restored { "restored" } else { "kept (something subclassed after us)" }
));
}
// ---------------------------------------------------------------------------
// the few GLFW entry points we need
// ---------------------------------------------------------------------------
pub(crate) mod glfw {
use std::ffi::c_void;
#[cfg(windows)]
use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress};
pub const CURSOR: i32 = 0x0003_3001;
pub const CURSOR_NORMAL: i32 = 0x0003_4001;
#[cfg(windows)]
pub(crate) unsafe fn proc(name: &[u8]) -> Option<unsafe extern "system" fn() -> isize> {
let glfw = GetModuleHandleA(c"glfw.dll".as_ptr() as *const u8);
if glfw.is_null() {
return None;
}
GetProcAddress(glfw, name.as_ptr())
}
/// LWJGL dlopens libglfw itself, so the symbol is usually in the global
/// scope; opening the already-loaded library by name covers the case where
/// it went in RTLD_LOCAL. RTLD_NOLOAD means we never pull in a second copy.
#[cfg(unix)]
pub(crate) unsafe fn proc(name: &[u8]) -> Option<unsafe extern "system" fn() -> isize> {
let sym = name.as_ptr() as *const libc::c_char;
let mut p = libc::dlsym(libc::RTLD_DEFAULT, sym);
if p.is_null() {
for lib in [c"libglfw.so".as_ptr(), c"libglfw.so.3".as_ptr()] {
let h = libc::dlopen(lib, libc::RTLD_NOW | libc::RTLD_NOLOAD);
if !h.is_null() {
p = libc::dlsym(h, sym);
if !p.is_null() {
break;
}
}
}
}
if p.is_null() {
None
} else {
Some(std::mem::transmute(p))
}
}
#[cfg(windows)]
pub unsafe fn win32_window(window: *mut c_void) -> isize {
match proc(b"glfwGetWin32Window\0") {
Some(f) => {
let f: unsafe extern "C" fn(*mut c_void) -> isize = std::mem::transmute(f);
f(window)
}
None => 0,
}
}
pub unsafe fn framebuffer_size(window: *mut c_void) -> (i32, i32) {
match proc(b"glfwGetFramebufferSize\0") {
Some(f) => {
let f: unsafe extern "C" fn(*mut c_void, *mut i32, *mut i32) =
std::mem::transmute(f);
let (mut w, mut h) = (0i32, 0i32);
f(window, &mut w, &mut h);
(w, h)
}
None => (0, 0),
}
}
pub unsafe fn get_input_mode(window: *mut c_void, mode: i32) -> i32 {
match proc(b"glfwGetInputMode\0") {
Some(f) => {
let f: unsafe extern "C" fn(*mut c_void, i32) -> i32 = std::mem::transmute(f);
f(window, mode)
}
None => 0,
}
}
pub unsafe fn set_input_mode(window: *mut c_void, mode: i32, value: i32) {
if let Some(f) = proc(b"glfwSetInputMode\0") {
let f: unsafe extern "C" fn(*mut c_void, i32, i32) = std::mem::transmute(f);
f(window, mode, value);
}
}
}