paavohtl Claude Opus 4.6 commited on
Commit
8372d88
Β·
1 Parent(s): 2951251

feat: add offline test harness that loads WA.exe and calls its functions

Browse files

Loads WA.exe into a 32-bit test process via LoadLibraryExA with
DONT_RESOLVE_DLL_REFERENCES, patches the IAT (445 imports), initializes
the statically-linked MSVC CRT heap, and successfully calls WA.exe
functions including malloc and CTask::Constructor.

9 tests: PE loading, vtable validation, prologue checks, IAT patching,
malloc wrapper call, and CTask constructor call with SEH support.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

Cargo.lock CHANGED
@@ -2,6 +2,21 @@
2
  # It is not intended for manual editing.
3
  version = 4
4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  [[package]]
6
  name = "openwa-types"
7
  version = "0.1.0"
@@ -12,3 +27,76 @@ version = "0.1.0"
12
  dependencies = [
13
  "openwa-types",
14
  ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  # It is not intended for manual editing.
3
  version = 4
4
 
5
+ [[package]]
6
+ name = "libc"
7
+ version = "0.2.182"
8
+ source = "registry+https://github.com/rust-lang/crates.io-index"
9
+ checksum = "6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112"
10
+
11
+ [[package]]
12
+ name = "openwa-harness"
13
+ version = "0.1.0"
14
+ dependencies = [
15
+ "libc",
16
+ "openwa-types",
17
+ "windows-sys",
18
+ ]
19
+
20
  [[package]]
21
  name = "openwa-types"
22
  version = "0.1.0"
 
27
  dependencies = [
28
  "openwa-types",
29
  ]
30
+
31
+ [[package]]
32
+ name = "windows-sys"
33
+ version = "0.59.0"
34
+ source = "registry+https://github.com/rust-lang/crates.io-index"
35
+ checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
36
+ dependencies = [
37
+ "windows-targets",
38
+ ]
39
+
40
+ [[package]]
41
+ name = "windows-targets"
42
+ version = "0.52.6"
43
+ source = "registry+https://github.com/rust-lang/crates.io-index"
44
+ checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
45
+ dependencies = [
46
+ "windows_aarch64_gnullvm",
47
+ "windows_aarch64_msvc",
48
+ "windows_i686_gnu",
49
+ "windows_i686_gnullvm",
50
+ "windows_i686_msvc",
51
+ "windows_x86_64_gnu",
52
+ "windows_x86_64_gnullvm",
53
+ "windows_x86_64_msvc",
54
+ ]
55
+
56
+ [[package]]
57
+ name = "windows_aarch64_gnullvm"
58
+ version = "0.52.6"
59
+ source = "registry+https://github.com/rust-lang/crates.io-index"
60
+ checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
61
+
62
+ [[package]]
63
+ name = "windows_aarch64_msvc"
64
+ version = "0.52.6"
65
+ source = "registry+https://github.com/rust-lang/crates.io-index"
66
+ checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
67
+
68
+ [[package]]
69
+ name = "windows_i686_gnu"
70
+ version = "0.52.6"
71
+ source = "registry+https://github.com/rust-lang/crates.io-index"
72
+ checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
73
+
74
+ [[package]]
75
+ name = "windows_i686_gnullvm"
76
+ version = "0.52.6"
77
+ source = "registry+https://github.com/rust-lang/crates.io-index"
78
+ checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
79
+
80
+ [[package]]
81
+ name = "windows_i686_msvc"
82
+ version = "0.52.6"
83
+ source = "registry+https://github.com/rust-lang/crates.io-index"
84
+ checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
85
+
86
+ [[package]]
87
+ name = "windows_x86_64_gnu"
88
+ version = "0.52.6"
89
+ source = "registry+https://github.com/rust-lang/crates.io-index"
90
+ checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
91
+
92
+ [[package]]
93
+ name = "windows_x86_64_gnullvm"
94
+ version = "0.52.6"
95
+ source = "registry+https://github.com/rust-lang/crates.io-index"
96
+ checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
97
+
98
+ [[package]]
99
+ name = "windows_x86_64_msvc"
100
+ version = "0.52.6"
101
+ source = "registry+https://github.com/rust-lang/crates.io-index"
102
+ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
crates/openwa-harness/Cargo.toml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
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-types = { path = "../openwa-types" }
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 ADDED
@@ -0,0 +1,597 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![allow(non_snake_case)]
2
+
3
+ use openwa_types::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_HANDLER_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
+ ("TaskStateMachine", 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_HANDLER_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
+ ("TaskStateMachine", 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::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,
438
+ 0x51, 0x52, 0x64, 0x85, 0x8D, 0x53, 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!(" CRT heap initialized: handle=0x{:08X}, type=1", heap as u32);
505
+ }
506
+
507
+ #[test]
508
+ fn call_wa_malloc() {
509
+ let _lock = mutation_lock().lock().unwrap();
510
+ let img = wa();
511
+ img.patch_imports().expect("IAT patching failed");
512
+ unsafe { init_wa_crt_heap(img); }
513
+
514
+ // thunk_FUN_005c0ab8 is __cdecl: (size) -> ptr
515
+ // This is WA's malloc wrapper β€” calls _malloc, checks for null
516
+ const WA_MALLOC: u32 = 0x005C_0AE3;
517
+
518
+ type MallocFn = unsafe extern "cdecl" fn(size: u32) -> *mut u8;
519
+
520
+ unsafe {
521
+ let wa_malloc: MallocFn = img.func_ptr(WA_MALLOC);
522
+
523
+ eprintln!("Calling WA malloc wrapper...");
524
+ let ptr = wa_malloc(64);
525
+ assert!(!ptr.is_null(), "malloc should return non-null for 64 bytes");
526
+ eprintln!("WA malloc(64) returned 0x{:08X}", ptr as u32);
527
+
528
+ // Write to it to prove it's real memory
529
+ *ptr = 0x42;
530
+ assert_eq!(*ptr, 0x42);
531
+
532
+ eprintln!("WA malloc wrapper works!");
533
+ }
534
+ }
535
+
536
+ // --- Function call: CTask::Constructor ---
537
+
538
+ #[test]
539
+ fn call_ctask_constructor() {
540
+ let _lock = mutation_lock().lock().unwrap();
541
+ let img = wa();
542
+ img.patch_imports().expect("IAT patching failed");
543
+ unsafe { init_wa_crt_heap(img); }
544
+
545
+ // Initialize security cookie (needed for stack protection in SEH functions)
546
+ const SECURITY_INIT_COOKIE: u32 = 0x005E_7EAB;
547
+ type InitCookieFn = unsafe extern "cdecl" fn();
548
+ unsafe {
549
+ let init_cookie: InitCookieFn = img.func_ptr(SECURITY_INIT_COOKIE);
550
+ init_cookie();
551
+ eprintln!(" Security cookie initialized");
552
+ }
553
+
554
+ // CTask::Constructor is __stdcall: (this, parent, class_type) -> this
555
+ type CTaskCtorFn = unsafe extern "stdcall" fn(this: *mut u8, parent: u32, class_type: u32) -> *mut u8;
556
+
557
+ unsafe {
558
+ let ctor: CTaskCtorFn = img.func_ptr(va::CTASK_CONSTRUCTOR);
559
+
560
+ // Allocate a buffer for CTask (0x30 bytes, zero-initialized)
561
+ let mut task_buf = vec![0u8; 0x30];
562
+ let task_ptr = task_buf.as_mut_ptr();
563
+
564
+ eprintln!("Calling CTask::Constructor...");
565
+ let result = ctor(task_ptr, 0, 0);
566
+
567
+ eprintln!("CTask::Constructor returned 0x{:08X}", result as u32);
568
+ assert_eq!(result, task_ptr, "Constructor should return this");
569
+
570
+ // Verify vtable was set
571
+ let vtable = *(task_ptr as *const u32);
572
+ let vtable_ghidra = img.to_ghidra(vtable);
573
+ assert_eq!(
574
+ vtable_ghidra, va::CTASK_VTABLE,
575
+ "CTask vtable: expected 0x{:08X}, got 0x{vtable_ghidra:08X}",
576
+ va::CTASK_VTABLE
577
+ );
578
+
579
+ // Verify class_type at offset 0x2C
580
+ let stored_class = *((task_ptr as usize + 0x2C) as *const u32);
581
+ assert_eq!(stored_class, 0, "class_type should be 0");
582
+
583
+ // Verify field at 0x08 is 0x10
584
+ let field_08 = *((task_ptr as usize + 0x08) as *const u32);
585
+ assert_eq!(field_08, 0x10, "field 0x08 should be 0x10");
586
+
587
+ // Verify children list was allocated (offset 0x14)
588
+ let children = *((task_ptr as usize + 0x14) as *const u32);
589
+ assert_ne!(children, 0, "children list should be non-null");
590
+
591
+ eprintln!("CTask::Constructor succeeded!");
592
+ eprintln!(" vtable = 0x{vtable_ghidra:08X}");
593
+ eprintln!(" children = 0x{children:08X}");
594
+ eprintln!(" class_type = {stored_class}");
595
+ }
596
+ }
597
+ }
docs/plans/2026-03-05-offline-harness-design.md ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Offline Test Harness Design
2
+
3
+ **Goal:** Load WA.exe into a 32-bit test process via `cargo test`, enabling offline validation of addresses, vtable contents, and eventually calling WA.exe functions β€” without running the game.
4
+
5
+ **Architecture:** A new `openwa-harness` crate that uses `LoadLibraryExA` with `DONT_RESOLVE_DLL_REFERENCES` to map WA.exe into process memory. This gives us a relocated PE image with readable `.text`, `.rdata`, and `.data` sections. Tests run via `cargo test --target i686-pc-windows-msvc -p openwa-harness`.
6
+
7
+ ## How PE Loading Works
8
+
9
+ ```
10
+ LoadLibraryExA("WA.exe", NULL, DONT_RESOLVE_DLL_REFERENCES)
11
+ β†’ Windows maps PE sections into memory
12
+ β†’ Applies base relocations (WA.exe has .reloc section)
13
+ β†’ Does NOT resolve imports (IAT entries are unpatched)
14
+ β†’ Does NOT call entry point
15
+ β†’ Returns HMODULE = base address of mapped image
16
+ ```
17
+
18
+ Delta computation: `loaded_base - IMAGE_BASE (0x400000)`.
19
+ Any Ghidra address `addr` maps to `loaded_base + (addr - 0x400000)`.
20
+
21
+ If `LoadLibraryEx` refuses to load an EXE, fallback: manual PE loader (read file, parse headers, VirtualAlloc, copy sections, apply relocations).
22
+
23
+ ## Test Layers
24
+
25
+ ### Layer 1: Read-only validation (initial scope)
26
+
27
+ Load WA.exe, read memory at known offsets:
28
+ - Vtable entries in `.rdata` match our address constants
29
+ - Function prologues at known `.text` offsets match expected bytes
30
+ - String data at known locations matches expected values
31
+ - Cross-reference consistency (vtable method pointers land in `.text`)
32
+
33
+ This replaces/supplements the runtime validator's static checks but runs via `cargo test` with no game needed.
34
+
35
+ ### Layer 2: Function calls (stretch goal)
36
+
37
+ Call simple WA.exe functions from the test process:
38
+ - Requires resolving at minimum CRT imports (malloc, free, memset, memcpy)
39
+ - IAT patching: find import entries, overwrite with pointers to our own implementations
40
+ - Start with `WA_MallocMemset` (0x53E910) β€” uses EDI register for size, calls malloc+memset
41
+ - Validate return values and memory contents
42
+
43
+ ### Layer 3: Complex function execution (future)
44
+
45
+ - Broader IAT patching for Windows API stubs
46
+ - Mock subsystems (DirectDraw, DirectSound) to prevent crashes
47
+ - Test constructors, initialization sequences
48
+
49
+ ## Crate Structure
50
+
51
+ ```
52
+ crates/openwa-harness/
53
+ Cargo.toml # 32-bit test crate, depends on openwa-types, windows-sys
54
+ src/
55
+ lib.rs # WaImage loader struct, rebase helpers
56
+ tests/ # (or use #[cfg(test)] modules)
57
+ pe_loading.rs # Layer 1: read-only checks
58
+ ```
59
+
60
+ ## Key Type: WaImage
61
+
62
+ ```rust
63
+ pub struct WaImage {
64
+ base: *const u8, // HMODULE from LoadLibraryEx
65
+ delta: i32, // base - 0x400000
66
+ }
67
+
68
+ impl WaImage {
69
+ /// Load WA.exe from given path
70
+ pub fn load(exe_path: &str) -> Result<Self, ...>;
71
+
72
+ /// Convert Ghidra address to pointer in loaded image
73
+ pub fn ptr(&self, ghidra_addr: u32) -> *const u8;
74
+
75
+ /// Read u32 at a Ghidra address
76
+ pub fn read_u32(&self, ghidra_addr: u32) -> u32;
77
+ }
78
+
79
+ impl Drop for WaImage {
80
+ fn drop(&mut self) { FreeLibrary(self.base); }
81
+ }
82
+ ```
83
+
84
+ ## WA.exe Path
85
+
86
+ The harness needs to find WA.exe. Options in priority order:
87
+ 1. `WAEXE_PATH` environment variable
88
+ 2. Known Steam path: `I:\games\SteamLibrary\steamapps\common\Worms Armageddon\WA.exe`
89
+ 3. Skip tests with clear message if not found
90
+
91
+ ## Dependencies
92
+
93
+ - `windows-sys` crate for `LoadLibraryExA`, `FreeLibrary` (links to kernel32)
94
+ - `openwa-types` for address constants and struct definitions
95
+ - No other external dependencies needed for Layer 1
96
+
97
+ ## Risks
98
+
99
+ - `LoadLibraryEx` might refuse to load an EXE (unlikely but possible) β†’ fallback to manual PE mapping
100
+ - WA.exe might not have a `.reloc` section β†’ would need to load at exact base address 0x400000 (but we confirmed it has one: 188KB .reloc section)
101
+ - Function calls (Layer 2+) may crash if they touch unresolved imports β†’ start read-only, add IAT patching incrementally