paavohtl Claude Opus 4.6 (1M context) commited on
Commit
eedf656
·
1 Parent(s): 89a6579

chore: remove openwa-harness crate

Browse files

The offline harness (LoadLibraryExA-based WA.exe loading) was an early
experiment superseded by DLL injection + replay testing. It hasn't been
used since initial development and adds maintenance overhead.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

CLAUDE.md CHANGED
@@ -21,9 +21,6 @@ cargo build -p openwa-validator --release
21
  # Run tests (openwa-types is pure Rust, works on any host)
22
  cargo test -p openwa-core
23
 
24
- # Run harness tests (must be 32-bit, needs WA.exe on disk)
25
- cargo test --target i686-pc-windows-msvc -p openwa-harness
26
-
27
  # Single test
28
  cargo test -p openwa-core -- scheme_parse::parse_beginner_v2
29
  ```
@@ -145,7 +142,6 @@ Key env vars:
145
  - **`openwa-core`** — Types, addresses, parsers, ASLR rebasing, and typed WA function wrappers. The source of truth for all reverse-engineered type layouts and known addresses. Contains `registry` (structured address database + field registries), `rebase` (ASLR delta), `wa_call` (calling convention helpers), and `wa/` (typed handle wrappers like `DDGameWrapperHandle`, `CWndHandle`).
146
  - **`openwa-derive`** — Proc macro crate. Provides `#[derive(FieldRegistry)]` for struct field maps and `#[vtable(...)]` for typed vtable definitions with introspection, calling wrappers, and replacement support.
147
  - **`openwa-wormkit`** — Unified WormKit cdylib that replaces WA functions with Rust and optionally validates types against live memory. Logs to `OpenWA.log` (hooks) and `OpenWA_validation.log` (validation). Uses MinHook for inline hooking. Validation is enabled via `OPENWA_VALIDATE=1` env var.
148
- - **`openwa-harness`** — Offline test harness that loads WA.exe into process memory via `LoadLibraryExA(DONT_RESOLVE_DLL_REFERENCES)` for testing without running the game.
149
  - **`openwa-test-runner`** — Headless replay test runner (`openwa-test` binary). Discovers replay tests, runs them concurrently via WA.exe's `/getlog` mode, compares output logs. See "Replay Testing" section.
150
  - **`openwa-debug-cli`** — CLI tool for live memory inspection (`openwa-debug` binary). Connects to the debug server in the DLL.
151
  - **`openwa-debug-proto`** — Shared protocol types (Request/Response enums, MessagePack framing) between CLI and server.
 
21
  # Run tests (openwa-types is pure Rust, works on any host)
22
  cargo test -p openwa-core
23
 
 
 
 
24
  # Single test
25
  cargo test -p openwa-core -- scheme_parse::parse_beginner_v2
26
  ```
 
142
  - **`openwa-core`** — Types, addresses, parsers, ASLR rebasing, and typed WA function wrappers. The source of truth for all reverse-engineered type layouts and known addresses. Contains `registry` (structured address database + field registries), `rebase` (ASLR delta), `wa_call` (calling convention helpers), and `wa/` (typed handle wrappers like `DDGameWrapperHandle`, `CWndHandle`).
143
  - **`openwa-derive`** — Proc macro crate. Provides `#[derive(FieldRegistry)]` for struct field maps and `#[vtable(...)]` for typed vtable definitions with introspection, calling wrappers, and replacement support.
144
  - **`openwa-wormkit`** — Unified WormKit cdylib that replaces WA functions with Rust and optionally validates types against live memory. Logs to `OpenWA.log` (hooks) and `OpenWA_validation.log` (validation). Uses MinHook for inline hooking. Validation is enabled via `OPENWA_VALIDATE=1` env var.
 
145
  - **`openwa-test-runner`** — Headless replay test runner (`openwa-test` binary). Discovers replay tests, runs them concurrently via WA.exe's `/getlog` mode, compares output logs. See "Replay Testing" section.
146
  - **`openwa-debug-cli`** — CLI tool for live memory inspection (`openwa-debug` binary). Connects to the debug server in the DLL.
147
  - **`openwa-debug-proto`** — Shared protocol types (Request/Response enums, MessagePack framing) between CLI and server.
Cargo.lock CHANGED
@@ -1515,15 +1515,6 @@ dependencies = [
1515
  "syn",
1516
  ]
1517
 
1518
- [[package]]
1519
- name = "openwa-harness"
1520
- version = "0.1.0"
1521
- dependencies = [
1522
- "libc",
1523
- "openwa-core",
1524
- "windows-sys 0.59.0",
1525
- ]
1526
-
1527
  [[package]]
1528
  name = "openwa-launcher"
1529
  version = "0.1.0"
 
1515
  "syn",
1516
  ]
1517
 
 
 
 
 
 
 
 
 
 
1518
  [[package]]
1519
  name = "openwa-launcher"
1520
  version = "0.1.0"
crates/openwa-harness/Cargo.toml DELETED
@@ -1,12 +0,0 @@
1
- [package]
2
- name = "openwa-harness"
3
- version = "0.1.0"
4
- edition = "2021"
5
- description = "Offline test harness — loads WA.exe into process memory for validation"
6
-
7
- [dependencies]
8
- openwa-core = { path = "../openwa-core" }
9
- libc = "0.2"
10
-
11
- [target.'cfg(target_os = "windows")'.dependencies]
12
- windows-sys = { version = "0.59", features = ["Win32_Foundation", "Win32_System_LibraryLoader", "Win32_System_Memory"] }
 
 
 
 
 
 
 
 
 
 
 
 
 
crates/openwa-harness/src/lib.rs DELETED
@@ -1,606 +0,0 @@
1
- #![allow(non_snake_case)]
2
-
3
- use openwa_core::address::va;
4
-
5
- #[cfg(target_os = "windows")]
6
- use windows_sys::Win32::System::LibraryLoader::{LoadLibraryExA, DONT_RESOLVE_DLL_REFERENCES};
7
-
8
- /// A loaded WA.exe image mapped into our process memory.
9
- ///
10
- /// Uses `LoadLibraryExA` with `DONT_RESOLVE_DLL_REFERENCES` to map the PE
11
- /// with relocations applied but no imports resolved and no entry point called.
12
- // SAFETY: WaImage holds a module handle that is valid for the process lifetime.
13
- // The loaded image is read-only (no imports resolved, no entry point called).
14
- unsafe impl Send for WaImage {}
15
- unsafe impl Sync for WaImage {}
16
-
17
- pub struct WaImage {
18
- #[cfg(target_os = "windows")]
19
- #[allow(dead_code)] // kept to prevent FreeLibrary on the HMODULE
20
- handle: isize,
21
- base: usize,
22
- }
23
-
24
- impl WaImage {
25
- /// Load WA.exe from the given path.
26
- ///
27
- /// Tries `WAEXE_PATH` env var first, then the provided path.
28
- #[cfg(target_os = "windows")]
29
- pub fn load() -> Result<Self, String> {
30
- let path = std::env::var("WAEXE_PATH").unwrap_or_else(|_| {
31
- r"I:\games\SteamLibrary\steamapps\common\Worms Armageddon\WA.exe".to_string()
32
- });
33
-
34
- if !std::path::Path::new(&path).exists() {
35
- return Err(format!("WA.exe not found at: {path}"));
36
- }
37
-
38
- let mut path_bytes: Vec<u8> = path.bytes().collect();
39
- path_bytes.push(0); // null terminator
40
-
41
- let handle = unsafe {
42
- LoadLibraryExA(
43
- path_bytes.as_ptr(),
44
- std::ptr::null_mut(),
45
- DONT_RESOLVE_DLL_REFERENCES,
46
- )
47
- };
48
-
49
- if handle.is_null() {
50
- let err = std::io::Error::last_os_error();
51
- return Err(format!("LoadLibraryExA failed: {err}"));
52
- }
53
-
54
- let handle = handle as isize;
55
- let base = handle as usize;
56
- eprintln!(
57
- "WA.exe loaded at 0x{:08X} (delta from 0x400000: {:+})",
58
- base,
59
- base as i64 - va::IMAGE_BASE as i64
60
- );
61
-
62
- Ok(WaImage { handle, base })
63
- }
64
-
65
- #[cfg(not(target_os = "windows"))]
66
- pub fn load() -> Result<Self, String> {
67
- Err("WaImage only works on Windows".to_string())
68
- }
69
-
70
- /// Base address of the loaded image.
71
- pub fn base(&self) -> usize {
72
- self.base
73
- }
74
-
75
- /// Convert a Ghidra virtual address to a pointer in the loaded image.
76
- pub fn ptr(&self, ghidra_addr: u32) -> *const u8 {
77
- let offset = ghidra_addr.wrapping_sub(va::IMAGE_BASE);
78
- (self.base + offset as usize) as *const u8
79
- }
80
-
81
- /// Read a u32 at a Ghidra virtual address.
82
- pub fn read_u32(&self, ghidra_addr: u32) -> u32 {
83
- unsafe { (self.ptr(ghidra_addr) as *const u32).read_unaligned() }
84
- }
85
-
86
- /// Read a byte at a Ghidra virtual address.
87
- pub fn read_u8(&self, ghidra_addr: u32) -> u8 {
88
- unsafe { *self.ptr(ghidra_addr) }
89
- }
90
-
91
- /// Read a slice of bytes at a Ghidra virtual address.
92
- pub fn read_bytes(&self, ghidra_addr: u32, len: usize) -> &[u8] {
93
- unsafe { std::slice::from_raw_parts(self.ptr(ghidra_addr), len) }
94
- }
95
-
96
- /// Check if a Ghidra address falls within the .rdata section.
97
- pub fn is_rdata(&self, ghidra_addr: u32) -> bool {
98
- ghidra_addr >= va::RDATA_START && ghidra_addr < va::DATA_START
99
- }
100
-
101
- /// Check if a Ghidra address falls within the .text section.
102
- pub fn is_text(&self, ghidra_addr: u32) -> bool {
103
- ghidra_addr >= va::TEXT_START && ghidra_addr <= va::TEXT_END
104
- }
105
-
106
- /// Convert a relocated runtime address back to a Ghidra address.
107
- pub fn to_ghidra(&self, runtime_addr: u32) -> u32 {
108
- (runtime_addr as i64 - self.base as i64 + va::IMAGE_BASE as i64) as u32
109
- }
110
-
111
- /// Convert a Ghidra address to the relocated runtime address.
112
- pub fn to_runtime(&self, ghidra_addr: u32) -> u32 {
113
- (ghidra_addr as i64 - va::IMAGE_BASE as i64 + self.base as i64) as u32
114
- }
115
-
116
- /// Get a function pointer at a Ghidra address, cast to the desired type.
117
- ///
118
- /// # Safety
119
- /// Caller must ensure the function signature matches and imports are resolved.
120
- pub unsafe fn func_ptr<T>(&self, ghidra_addr: u32) -> T {
121
- let ptr = self.ptr(ghidra_addr);
122
- std::mem::transmute_copy(&ptr)
123
- }
124
-
125
- /// Patch the import address table, resolving all DLL imports.
126
- ///
127
- /// This must be called before calling any WA.exe functions that use
128
- /// imported APIs (malloc, memset, etc.).
129
- #[cfg(target_os = "windows")]
130
- pub fn patch_imports(&self) -> Result<usize, String> {
131
- unsafe { iat::patch_iat(self.base) }
132
- }
133
- }
134
-
135
- // No Drop impl — FreeLibrary not needed for test harness.
136
- // The OS reclaims resources when the process exits.
137
-
138
- // ---------------------------------------------------------------------------
139
- // IAT patching — resolve imports so we can call WA.exe functions
140
- // ---------------------------------------------------------------------------
141
-
142
- #[cfg(target_os = "windows")]
143
- mod iat {
144
- use std::ffi::CStr;
145
-
146
- /// PE image import descriptor (20 bytes each, array terminated by zeroed entry)
147
- #[repr(C)]
148
- struct ImageImportDescriptor {
149
- original_first_thunk: u32, // RVA to INT (Import Name Table)
150
- time_date_stamp: u32,
151
- forwarder_chain: u32,
152
- name: u32, // RVA to DLL name string
153
- first_thunk: u32, // RVA to IAT (Import Address Table) — this is what we patch
154
- }
155
-
156
- /// PE import-by-name entry
157
- #[repr(C)]
158
- struct ImageImportByName {
159
- hint: u16,
160
- name: [u8; 1], // variable length, null-terminated
161
- }
162
-
163
- /// Patch the IAT of a loaded PE image, resolving imports from our own process.
164
- ///
165
- /// For each imported DLL, we call LoadLibraryA to get the real DLL handle,
166
- /// then GetProcAddress for each import, and write the result into the IAT slot.
167
- ///
168
- /// Returns the number of imports patched.
169
- pub unsafe fn patch_iat(base: usize) -> Result<usize, String> {
170
- use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryA};
171
- use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_READWRITE};
172
-
173
- // Parse PE headers
174
- let dos_header = base as *const u8;
175
- let e_lfanew = *(dos_header.add(0x3C) as *const u32) as usize;
176
- let pe_sig = base + e_lfanew;
177
-
178
- // Verify PE signature
179
- if *(pe_sig as *const u32) != 0x4550 {
180
- return Err("Invalid PE signature".to_string());
181
- }
182
-
183
- // Optional header starts at PE + 24
184
- let opt_header = pe_sig + 24;
185
-
186
- // Import directory is data directory entry #1 (at optional_header + 104 for PE32)
187
- let import_dir_rva = *((opt_header + 104) as *const u32) as usize;
188
- if import_dir_rva == 0 {
189
- return Err("No import directory".to_string());
190
- }
191
-
192
- let mut patched = 0usize;
193
- let mut desc_ptr = (base + import_dir_rva) as *const ImageImportDescriptor;
194
-
195
- loop {
196
- let desc = &*desc_ptr;
197
- if desc.name == 0 {
198
- break; // End of import descriptor array
199
- }
200
-
201
- let dll_name_ptr = (base + desc.name as usize) as *const u8;
202
- let dll_name = CStr::from_ptr(dll_name_ptr as *const i8);
203
-
204
- // Load the actual DLL into our process
205
- let dll_handle = LoadLibraryA(dll_name_ptr);
206
- if dll_handle.is_null() {
207
- eprintln!(" [IAT] Could not load DLL: {}", dll_name.to_string_lossy());
208
- desc_ptr = desc_ptr.add(1);
209
- continue;
210
- }
211
-
212
- // Walk the INT (Original First Thunk) and IAT (First Thunk) in parallel
213
- let int_rva = if desc.original_first_thunk != 0 {
214
- desc.original_first_thunk as usize
215
- } else {
216
- desc.first_thunk as usize
217
- };
218
-
219
- let mut int_entry = (base + int_rva) as *const u32;
220
- let mut iat_entry = (base + desc.first_thunk as usize) as *mut u32;
221
-
222
- let mut dll_count = 0u32;
223
- loop {
224
- let thunk_data = *int_entry;
225
- if thunk_data == 0 {
226
- break; // End of import list for this DLL
227
- }
228
-
229
- let proc_addr = if thunk_data & 0x80000000 != 0 {
230
- // Import by ordinal
231
- let ordinal = (thunk_data & 0xFFFF) as u16;
232
- GetProcAddress(dll_handle, ordinal as *const u8)
233
- } else {
234
- // Import by name
235
- let import_by_name = (base + thunk_data as usize) as *const ImageImportByName;
236
- let func_name = (*import_by_name).name.as_ptr();
237
- GetProcAddress(dll_handle, func_name as *const u8)
238
- };
239
-
240
- if let Some(addr) = proc_addr {
241
- // Make IAT entry writable, write the resolved address
242
- let mut old_protect = 0u32;
243
- VirtualProtect(iat_entry as *mut _, 4, PAGE_READWRITE, &mut old_protect);
244
- *iat_entry = addr as u32;
245
- VirtualProtect(iat_entry as *mut _, 4, old_protect, &mut old_protect);
246
- dll_count += 1;
247
- }
248
-
249
- int_entry = int_entry.add(1);
250
- iat_entry = iat_entry.add(1);
251
- }
252
-
253
- patched += dll_count as usize;
254
- desc_ptr = desc_ptr.add(1);
255
- }
256
-
257
- Ok(patched)
258
- }
259
- }
260
-
261
- // ---------------------------------------------------------------------------
262
- // Tests
263
- // ---------------------------------------------------------------------------
264
-
265
- #[cfg(test)]
266
- mod tests {
267
- use super::*;
268
- use std::sync::{Mutex, OnceLock};
269
-
270
- /// Load WA.exe once for all tests (expensive operation).
271
- fn wa() -> &'static WaImage {
272
- static IMAGE: OnceLock<WaImage> = OnceLock::new();
273
- IMAGE.get_or_init(|| {
274
- WaImage::load().expect(
275
- "Failed to load WA.exe. Set WAEXE_PATH or ensure WA.exe exists at default path.",
276
- )
277
- })
278
- }
279
-
280
- /// Mutex to serialize tests that mutate global state (IAT, CRT heap, etc.).
281
- /// Tests that only read from the loaded image don't need this.
282
- fn mutation_lock() -> &'static Mutex<()> {
283
- static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
284
- LOCK.get_or_init(|| Mutex::new(()))
285
- }
286
-
287
- #[test]
288
- fn load_wa_exe() {
289
- let img = wa();
290
- assert!(img.base() != 0, "base address should be non-zero");
291
- eprintln!("WA.exe base: 0x{:08X}", img.base());
292
- }
293
-
294
- // --- Vtable location checks ---
295
-
296
- #[test]
297
- fn vtable_locations_in_rdata() {
298
- let img = wa();
299
- let vtables = [
300
- ("CTask", va::CTASK_VTABLE),
301
- ("CGameTask", va::CGAMETASK_VTABLE),
302
- ("CGameTask2", va::CGAMETASK_VTABLE2),
303
- ("DDGameWrapper", va::DDGAME_WRAPPER_VTABLE),
304
- ("GfxHandler", va::GFX_DIR_VTABLE),
305
- ("DisplayGfx", va::DISPLAY_GFX_VTABLE),
306
- ("PCLandscape", va::PC_LANDSCAPE_VTABLE),
307
- ("LandscapeShader", va::LANDSCAPE_SHADER_VTABLE),
308
- ("DSSound", va::DS_SOUND_VTABLE),
309
- ("BitGrid", va::TASK_STATE_MACHINE_VTABLE),
310
- ("OpenGLCPU", va::OPENGL_CPU_VTABLE),
311
- ("WaterEffect", va::WATER_EFFECT_VTABLE),
312
- ];
313
-
314
- for (name, addr) in vtables {
315
- assert!(
316
- img.is_rdata(addr),
317
- "{name} vtable 0x{addr:08X} should be in .rdata"
318
- );
319
- }
320
- }
321
-
322
- #[test]
323
- fn vtable_first_entries_point_to_text() {
324
- let img = wa();
325
- let vtables = [
326
- ("CTask", va::CTASK_VTABLE),
327
- ("CGameTask", va::CGAMETASK_VTABLE),
328
- ("DDGameWrapper", va::DDGAME_WRAPPER_VTABLE),
329
- ("GfxHandler", va::GFX_DIR_VTABLE),
330
- ("DisplayGfx", va::DISPLAY_GFX_VTABLE),
331
- ("PCLandscape", va::PC_LANDSCAPE_VTABLE),
332
- ("LandscapeShader", va::LANDSCAPE_SHADER_VTABLE),
333
- ("DSSound", va::DS_SOUND_VTABLE),
334
- ("BitGrid", va::TASK_STATE_MACHINE_VTABLE),
335
- ("OpenGLCPU", va::OPENGL_CPU_VTABLE),
336
- ("WaterEffect", va::WATER_EFFECT_VTABLE),
337
- ];
338
-
339
- for (name, vtable_addr) in vtables {
340
- // Vtable entries are relocated pointers — convert back to Ghidra space
341
- let first_entry_runtime = img.read_u32(vtable_addr);
342
- let first_entry_ghidra = img.to_ghidra(first_entry_runtime);
343
- assert!(
344
- img.is_text(first_entry_ghidra),
345
- "{name} vtable first entry 0x{first_entry_ghidra:08X} (runtime 0x{first_entry_runtime:08X}) should be in .text"
346
- );
347
- }
348
- }
349
-
350
- // --- CTask vtable method verification ---
351
-
352
- #[test]
353
- fn ctask_vtable_methods() {
354
- let img = wa();
355
- let expected: &[(&str, u32)] = &[
356
- ("vt0_init", va::CTASK_VT0_INIT),
357
- ("vt1_Free", va::CTASK_VT1_FREE),
358
- ("vt2_HandleMessage", va::CTASK_VT2_HANDLE_MESSAGE),
359
- ("vt3", va::CTASK_VT3),
360
- ("vt4", va::CTASK_VT4),
361
- ("vt5", va::CTASK_VT5),
362
- ("vt6", va::CTASK_VT6),
363
- ("vt7_ProcessFrame", va::CTASK_VT7_PROCESS_FRAME),
364
- ];
365
-
366
- for (i, (name, expected_ghidra)) in expected.iter().enumerate() {
367
- let slot_addr = va::CTASK_VTABLE + (i as u32) * 4;
368
- let actual_runtime = img.read_u32(slot_addr);
369
- let actual_ghidra = img.to_ghidra(actual_runtime);
370
- assert_eq!(
371
- actual_ghidra, *expected_ghidra,
372
- "CTask::{name} at vtable+0x{:02X}: expected 0x{expected_ghidra:08X}, got 0x{actual_ghidra:08X}",
373
- i * 4
374
- );
375
- }
376
- }
377
-
378
- // --- Function prologue checks ---
379
-
380
- #[test]
381
- fn function_prologues() {
382
- let img = wa();
383
-
384
- let valid_prologues: &[u8] = &[
385
- 0x55, // push ebp
386
- 0x56, // push esi
387
- 0x57, // push edi
388
- 0x83, // sub esp, ...
389
- 0x8B, // mov reg, ...
390
- 0x6A, // push imm8
391
- 0x81, // sub esp, imm32
392
- 0xB8, // mov eax, imm32
393
- 0x51, // push ecx
394
- 0x52, // push edx
395
- 0x64, // FS: segment prefix (SEH)
396
- 0x85, // test
397
- 0x8D, // lea
398
- 0x53, // push ebx
399
- ];
400
-
401
- let functions: &[(&str, u32)] = &[
402
- ("CTask::Constructor", va::CTASK_CONSTRUCTOR),
403
- ("CGameTask::Constructor", va::CGAMETASK_CONSTRUCTOR),
404
- ("DDGameWrapper::Constructor", va::CONSTRUCT_DD_GAME_WRAPPER),
405
- ("DDGame::Constructor", va::CONSTRUCT_DD_GAME),
406
- ("CreateExplosion", va::CREATE_EXPLOSION),
407
- ("SpawnObject", va::SPAWN_OBJECT),
408
- ("WeaponRelease", va::WEAPON_RELEASE),
409
- ("FireWeapon", va::FIRE_WEAPON),
410
- ("InitWeaponTable", va::INIT_WEAPON_TABLE),
411
- ("BlitScreen", va::BLIT_SCREEN),
412
- ("RenderDrawingQueue", va::RQ_RENDER_DRAWING_QUEUE),
413
- ("DrawLandscape", va::DRAW_LANDSCAPE),
414
- ("ConstructPCLandscape", va::CONSTRUCT_PC_LANDSCAPE),
415
- ("ConstructDSSound", va::CONSTRUCT_DS_SOUND),
416
- ("ShowChatMessage", va::SHOW_CHAT_MESSAGE),
417
- ("FrontendChangeScreen", va::FRONTEND_CHANGE_SCREEN),
418
- ("WA_MallocMemset", va::WA_MALLOC_MEMSET),
419
- ];
420
-
421
- for (name, addr) in functions {
422
- let first_byte = img.read_u8(*addr);
423
- assert!(
424
- valid_prologues.contains(&first_byte),
425
- "{name} at 0x{addr:08X}: unexpected prologue byte 0x{first_byte:02X}"
426
- );
427
- }
428
- }
429
-
430
- // --- Cross-reference: vtable methods should have valid prologues ---
431
-
432
- #[test]
433
- fn vtable_method_prologues() {
434
- let img = wa();
435
-
436
- let valid_prologues: &[u8] = &[
437
- 0x55, 0x56, 0x57, 0x83, 0x8B, 0x6A, 0x81, 0xB8, 0x51, 0x52, 0x64, 0x85, 0x8D, 0x53,
438
- 0xC2, 0xC3, 0x33,
439
- ];
440
-
441
- // Read all CTask vtable entries and check their prologues
442
- for i in 0..8 {
443
- let method_ghidra = img.to_ghidra(img.read_u32(va::CTASK_VTABLE + i * 4));
444
- let first_byte = img.read_u8(method_ghidra);
445
- assert!(
446
- valid_prologues.contains(&first_byte),
447
- "CTask vtable[{i}] at 0x{method_ghidra:08X}: unexpected byte 0x{first_byte:02X}"
448
- );
449
- }
450
-
451
- // CGameTask vtable (20 entries)
452
- for i in 0..20 {
453
- let method_ghidra = img.to_ghidra(img.read_u32(va::CGAMETASK_VTABLE + i * 4));
454
- if img.is_text(method_ghidra) {
455
- let first_byte = img.read_u8(method_ghidra);
456
- assert!(
457
- valid_prologues.contains(&first_byte),
458
- "CGameTask vtable[{i}] at 0x{method_ghidra:08X}: unexpected byte 0x{first_byte:02X}"
459
- );
460
- }
461
- }
462
- }
463
-
464
- // --- IAT patching ---
465
-
466
- #[test]
467
- fn patch_imports() {
468
- let _lock = mutation_lock().lock().unwrap();
469
- let img = wa();
470
- let count = img.patch_imports().expect("IAT patching failed");
471
- eprintln!("Patched {count} IAT entries");
472
- assert!(count > 100, "Expected many imports, got {count}");
473
- }
474
-
475
- // --- Function call: WA's malloc wrapper ---
476
-
477
- /// Initialize WA.exe's CRT heap so that _malloc/_free work.
478
- ///
479
- /// The statically-linked MSVC CRT checks DAT_006b2198 (heap handle)
480
- /// and DAT_008c3128 (heap type selector). We set these directly
481
- /// rather than calling __heap_init.
482
- unsafe fn init_wa_crt_heap(img: &WaImage) {
483
- use windows_sys::Win32::System::Memory::GetProcessHeap;
484
-
485
- // DAT_006b2198 = heap handle (HANDLE)
486
- let heap_handle_ptr = img.ptr(0x006B_2198) as *mut u32;
487
- // DAT_008c3128 = heap type (1 = simple HeapAlloc mode)
488
- let heap_type_ptr = img.ptr(0x008C_3128) as *mut u32;
489
-
490
- let heap = GetProcessHeap();
491
- assert!(!heap.is_null(), "GetProcessHeap failed");
492
-
493
- // Make .data writable (it should already be, but be safe)
494
- let mut old_protect = 0u32;
495
- windows_sys::Win32::System::Memory::VirtualProtect(
496
- heap_handle_ptr as *mut _,
497
- 8,
498
- windows_sys::Win32::System::Memory::PAGE_READWRITE,
499
- &mut old_protect,
500
- );
501
-
502
- *heap_handle_ptr = heap as u32;
503
- *heap_type_ptr = 1; // Simple HeapAlloc mode — no SBH
504
- eprintln!(
505
- " CRT heap initialized: handle=0x{:08X}, type=1",
506
- heap as u32
507
- );
508
- }
509
-
510
- #[test]
511
- fn call_wa_malloc() {
512
- let _lock = mutation_lock().lock().unwrap();
513
- let img = wa();
514
- img.patch_imports().expect("IAT patching failed");
515
- unsafe {
516
- init_wa_crt_heap(img);
517
- }
518
-
519
- // thunk_FUN_005c0ab8 is __cdecl: (size) -> ptr
520
- // This is WA's malloc wrapper — calls _malloc, checks for null
521
- const WA_MALLOC: u32 = 0x005C_0AE3;
522
-
523
- type MallocFn = unsafe extern "cdecl" fn(size: u32) -> *mut u8;
524
-
525
- unsafe {
526
- let wa_malloc: MallocFn = img.func_ptr(WA_MALLOC);
527
-
528
- eprintln!("Calling WA malloc wrapper...");
529
- let ptr = wa_malloc(64);
530
- assert!(!ptr.is_null(), "malloc should return non-null for 64 bytes");
531
- eprintln!("WA malloc(64) returned 0x{:08X}", ptr as u32);
532
-
533
- // Write to it to prove it's real memory
534
- *ptr = 0x42;
535
- assert_eq!(*ptr, 0x42);
536
-
537
- eprintln!("WA malloc wrapper works!");
538
- }
539
- }
540
-
541
- // --- Function call: CTask::Constructor ---
542
-
543
- #[test]
544
- fn call_ctask_constructor() {
545
- let _lock = mutation_lock().lock().unwrap();
546
- let img = wa();
547
- img.patch_imports().expect("IAT patching failed");
548
- unsafe {
549
- init_wa_crt_heap(img);
550
- }
551
-
552
- // Initialize security cookie (needed for stack protection in SEH functions)
553
- const SECURITY_INIT_COOKIE: u32 = 0x005E_7EAB;
554
- type InitCookieFn = unsafe extern "cdecl" fn();
555
- unsafe {
556
- let init_cookie: InitCookieFn = img.func_ptr(SECURITY_INIT_COOKIE);
557
- init_cookie();
558
- eprintln!(" Security cookie initialized");
559
- }
560
-
561
- // CTask::Constructor is __stdcall: (this, parent, ddgame) -> this
562
- type CTaskCtorFn =
563
- unsafe extern "stdcall" fn(this: *mut u8, parent: u32, ddgame: u32) -> *mut u8;
564
-
565
- unsafe {
566
- let ctor: CTaskCtorFn = img.func_ptr(va::CTASK_CONSTRUCTOR);
567
-
568
- // Allocate a buffer for CTask (0x30 bytes, zero-initialized)
569
- let mut task_buf = vec![0u8; 0x30];
570
- let task_ptr = task_buf.as_mut_ptr();
571
-
572
- eprintln!("Calling CTask::Constructor...");
573
- let result = ctor(task_ptr, 0, 0);
574
-
575
- eprintln!("CTask::Constructor returned 0x{:08X}", result as u32);
576
- assert_eq!(result, task_ptr, "Constructor should return this");
577
-
578
- // Verify vtable was set
579
- let vtable = *(task_ptr as *const u32);
580
- let vtable_ghidra = img.to_ghidra(vtable);
581
- assert_eq!(
582
- vtable_ghidra,
583
- va::CTASK_VTABLE,
584
- "CTask vtable: expected 0x{:08X}, got 0x{vtable_ghidra:08X}",
585
- va::CTASK_VTABLE
586
- );
587
-
588
- // Verify ddgame pointer at offset 0x2C (3rd ctor param, we passed 0)
589
- let stored_ddgame = *((task_ptr as usize + 0x2C) as *const u32);
590
- assert_eq!(stored_ddgame, 0, "ddgame should be 0 (we passed 0)");
591
-
592
- // Verify field at 0x08 is 0x10
593
- let field_08 = *((task_ptr as usize + 0x08) as *const u32);
594
- assert_eq!(field_08, 0x10, "field 0x08 should be 0x10");
595
-
596
- // Verify children list was allocated (offset 0x14)
597
- let children = *((task_ptr as usize + 0x14) as *const u32);
598
- assert_ne!(children, 0, "children list should be non-null");
599
-
600
- eprintln!("CTask::Constructor succeeded!");
601
- eprintln!(" vtable = 0x{vtable_ghidra:08X}");
602
- eprintln!(" children = 0x{children:08X}");
603
- eprintln!(" ddgame = {stored_ddgame}");
604
- }
605
- }
606
- }