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
//! BytesSwitch Handler for bytecode switching
use super::address_strategy::AddressStrategy;
use crate::memory::{read_memory_bytes, MemoryError};
use crate::memory_hook::BytesSwitch;
use super::super::register::ModifierHandler;
#[derive(Clone, Debug)]
pub struct BytesSwitchConfig {
pub name: String,
pub byte_count: usize,
pub patch_bytes: Vec<u8>,
}
pub struct BytesSwitchHandler {
config: BytesSwitchConfig,
/// Address resolution strategy - stores enough info to resolve at activation time
address_strategy: AddressStrategy,
cached_address: Option<usize>,
instance: Option<BytesSwitch>,
}
impl BytesSwitchHandler {
fn new(config: BytesSwitchConfig, address_strategy: AddressStrategy) -> Self {
Self {
config,
address_strategy,
cached_address: None,
instance: None,
}
}
/// Create a BytesSwitchHandler with static address pattern.
///
/// Architecture is automatically detected at activation time from ProcessContext.
///
/// # Arguments
/// * `name` - Switch name (must be unique)
/// * `pattern` - Static address pattern string (e.g., "game.exe+1000")
/// * `byte_count` - Number of bytes to switch
/// * `patch_bytes` - Bytes to write when enabled
///
/// # Example
/// ```no_run
/// use win_auto_utils::memory_manager::builtin::BytesSwitchHandler;
///
/// let switch = BytesSwitchHandler::new_bytes_switch(
/// "nop_patch",
/// "game.exe+2000",
/// 2,
/// vec![0x90, 0x90],
/// )?;
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
pub fn new_bytes_switch(
name: impl Into<String>,
pattern: &str,
byte_count: usize,
patch_bytes: Vec<u8>,
) -> Result<Box<dyn ModifierHandler>, crate::memory_resolver::ParseError> {
let config = BytesSwitchConfig {
name: name.into(),
byte_count,
patch_bytes,
};
Ok(Box::new(Self::new(
config,
AddressStrategy::static_pattern(pattern),
)))
}
/// Create a NOP switch with static address pattern.
pub fn new_nop_switch(
name: impl Into<String>,
pattern: &str,
byte_count: usize,
) -> Result<Box<dyn ModifierHandler>, crate::memory_resolver::ParseError> {
Self::new_bytes_switch(name, pattern, byte_count, vec![0x90; byte_count])
}
/// Create a BytesSwitchHandler with AOB scanning.
///
/// Uses AOB pattern scanning to find the target address at runtime.
/// Architecture-independent.
///
/// # Performance Note
/// - First activation: Executes AOB scan (may take 10-500ms)
/// - Subsequent activations: Reuses cached address
/// - Cache auto-invalidates when PID changes
///
/// # Arguments
/// * `name` - Switch name
/// * `pattern` - AOB pattern string (space-separated hex bytes)
/// * `byte_count` - Number of bytes to switch
/// * `patch_bytes` - Bytes to write when enabled
///
/// # Example
/// ```no_run
/// use win_auto_utils::memory_manager::builtin::BytesSwitchHandler;
///
/// let switch = BytesSwitchHandler::new_bytes_switch_aob(
/// "nop_patch",
/// "90 90 90 90 90",
/// 2,
/// vec![0x90, 0x90],
/// )?;
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
pub fn new_bytes_switch_aob(
name: impl Into<String>,
pattern: &str,
byte_count: usize,
patch_bytes: Vec<u8>,
) -> Result<Box<dyn ModifierHandler>, String> {
let config = BytesSwitchConfig {
name: name.into(),
byte_count,
patch_bytes,
};
Ok(Box::new(Self::new(
config,
AddressStrategy::aob_pattern(pattern),
)))
}
/// Create a NOP switch with AOB scanning.
pub fn new_nop_switch_aob(
name: impl Into<String>,
pattern: &str,
byte_count: usize,
) -> Result<Box<dyn ModifierHandler>, String> {
Self::new_bytes_switch_aob(name, pattern, byte_count, vec![0x90; byte_count])
}
/// Create a BytesSwitchHandler with AOB scanning and custom range.
///
/// Same as `new_bytes_switch_aob()` but allows specifying a memory range for faster scanning.
/// Use this when you know the approximate location of the target code.
///
/// # Arguments
/// * `name` - Switch name
/// * `pattern` - AOB pattern string
/// * `byte_count` - Number of bytes to switch
/// * `patch_bytes` - Bytes to write when enabled
/// * `start_address` - Starting address for the scan (0 = from beginning)
/// * `length` - Length of the scan range (0 = entire process memory)
///
/// # Example
/// ```no_run
/// use win_auto_utils::memory_manager::builtin::BytesSwitchHandler;
///
/// // Scan only within a specific module range (much faster!)
/// let switch = BytesSwitchHandler::new_bytes_switch_aob_with_range(
/// "nop_patch",
/// "90 90 90 90 90",
/// 2,
/// vec![0x90, 0x90],
/// 0x10000000, // Start address (e.g., module base)
/// 0x100000, // Length (e.g., module size)
/// )?;
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
pub fn new_bytes_switch_aob_with_range(
name: impl Into<String>,
pattern: &str,
byte_count: usize,
patch_bytes: Vec<u8>,
start_address: usize,
length: usize,
) -> Result<Box<dyn ModifierHandler>, String> {
Self::new_bytes_switch_aob_with_range_and_offset(
name,
pattern,
byte_count,
patch_bytes,
start_address,
length,
0,
)
}
/// Create a BytesSwitchHandler with AOB scanning and offset.
///
/// Same as `new_bytes_switch_aob()` but supports adding an offset to the scanned address.
/// Useful when the AOB pattern finds a nearby signature, but you need to patch at a different location.
///
/// # Arguments
/// * `name` - Switch name
/// * `pattern` - AOB pattern string
/// * `byte_count` - Number of bytes to switch
/// * `patch_bytes` - Bytes to write when enabled
/// * `offset` - Offset to add to the scanned address (can be negative)
///
/// # Example
/// ```no_run
/// use win_auto_utils::memory_manager::builtin::BytesSwitchHandler;
///
/// // Scan for function prologue, but patch 0x42 bytes later
/// let switch = BytesSwitchHandler::new_bytes_switch_aob_with_offset(
/// "nop_patch",
/// "48 89 5C 24",
/// 2,
/// vec![0x90, 0x90],
/// 0x42,
/// )?;
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
pub fn new_bytes_switch_aob_with_offset(
name: impl Into<String>,
pattern: &str,
byte_count: usize,
patch_bytes: Vec<u8>,
offset: i64,
) -> Result<Box<dyn ModifierHandler>, String> {
let config = BytesSwitchConfig {
name: name.into(),
byte_count,
patch_bytes,
};
Ok(Box::new(Self::new(
config,
AddressStrategy::aob_pattern_with_offset(pattern, offset),
)))
}
/// Create a NOP switch with AOB scanning and offset.
pub fn new_nop_switch_aob_with_offset(
name: impl Into<String>,
pattern: &str,
byte_count: usize,
offset: i64,
) -> Result<Box<dyn ModifierHandler>, String> {
Self::new_bytes_switch_aob_with_offset(
name,
pattern,
byte_count,
vec![0x90; byte_count],
offset,
)
}
/// Create a BytesSwitchHandler with AOB scanning, custom range and offset.
///
/// Combines range-limited scanning with post-scan address correction.
///
/// # Arguments
/// * `name` - Switch name
/// * `pattern` - AOB pattern string
/// * `byte_count` - Number of bytes to switch
/// * `patch_bytes` - Bytes to write when enabled
/// * `start_address` - Starting address for the scan (0 = from beginning)
/// * `length` - Length of the scan range (0 = entire process memory)
/// * `offset` - Offset to add to the scanned address (can be negative)
pub fn new_bytes_switch_aob_with_range_and_offset(
name: impl Into<String>,
pattern: &str,
byte_count: usize,
patch_bytes: Vec<u8>,
start_address: usize,
length: usize,
offset: i64,
) -> Result<Box<dyn ModifierHandler>, String> {
let config = BytesSwitchConfig {
name: name.into(),
byte_count,
patch_bytes,
};
Ok(Box::new(Self::new(
config,
AddressStrategy::aob_pattern_with_range_and_offset(
pattern,
start_address,
length,
offset,
),
)))
}
/// Create a NOP switch with AOB scanning, custom range and offset.
pub fn new_nop_switch_aob_with_range_and_offset(
name: impl Into<String>,
pattern: &str,
byte_count: usize,
start_address: usize,
length: usize,
offset: i64,
) -> Result<Box<dyn ModifierHandler>, String> {
Self::new_bytes_switch_aob_with_range_and_offset(
name,
pattern,
byte_count,
vec![0x90; byte_count],
start_address,
length,
offset,
)
}
}
impl ModifierHandler for BytesSwitchHandler {
fn name(&self) -> &str {
&self.config.name
}
fn activate(
&mut self,
ctx: &crate::memory_manager::manager::ProcessContext,
) -> Result<(), MemoryError> {
// Check if instance exists and if context changed (compare handle from instance)
let context_changed = if let Some(ref switch) = self.instance {
// BytesSwitch wraps HANDLE internally, compare the inner HANDLE value
switch.get_handle() != ctx.handle
} else {
true // No instance, need to create
};
// If context changed, clear address cache to force re-resolution
if context_changed {
self.cached_address = None;
}
// Resolve address (use cache if available and context unchanged)
let target_address = if self.cached_address.is_none() {
// Use unified AddressStrategy to resolve address
let addr = self
.address_strategy
.resolve(ctx.handle, ctx.pid, ctx.architecture)?;
self.cached_address = Some(addr);
addr
} else {
self.cached_address.unwrap()
};
// If instance already exists and is enabled, just return (already active)
if !context_changed && self.instance.is_some() {
if let Some(ref switch) = self.instance {
if switch.is_enabled() {
return Ok(());
}
// Switch exists but disabled, will re-enable below
}
}
// Create new BytesSwitch instance or re-enable existing one
if !context_changed && self.instance.is_some() {
// Reuse existing instance (just re-enable)
if let Some(ref mut switch) = self.instance {
switch.enable()?;
}
} else {
// Context changed or no instance, create new instance
let original_bytes =
read_memory_bytes(ctx.handle, target_address, self.config.byte_count)?;
let mut switch = BytesSwitch::new(
ctx.handle,
target_address,
original_bytes,
self.config.patch_bytes.clone(),
);
switch.enable()?;
self.instance = Some(switch);
}
Ok(())
}
fn deactivate(&mut self) -> Result<(), MemoryError> {
// Disable the switch but KEEP the instance and address cache
// This allows fast re-activation without re-scanning
if let Some(ref mut switch) = self.instance {
if switch.is_enabled() {
switch.disable()?;
}
// Keep the instance (don't take/drop it)
}
// Address cache is preserved for fast re-activation
Ok(())
}
fn is_active(&self) -> bool {
self.instance.is_some()
}
}
impl BytesSwitchHandler {
/// Manually clear the cached address (forces re-scan on next activate)
pub fn clear_cache(&mut self) {
self.cached_address = None;
}
/// Check if this handler has a cached address
pub fn has_cached_address(&self) -> bool {
self.cached_address.is_some()
}
}
unsafe impl Send for BytesSwitchHandler {}