source_sdk_2013 0.1.0-alpha.4

Higher-level bindings for the Source SDK.
Documentation
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
//! A narrowly checked workaround for TF2's Windows `host_timescale` cheat gate.
//!
//! Linux has no corresponding gate. This does not change `sv_cheats`, console
//! flags, or clients' replicated variables. It only bypasses the Windows
//! engine's check immediately before applying a positive `host_timescale`.

use crate::interfaces::Cvar;
use std::marker::PhantomData;
use std::rc::Rc;

/// Owns the single-byte Windows workaround until it is explicitly restored.
///
/// The Windows engine module remains loaded while this guard exists. Unknown
/// instruction sequences are refused. `Drop` attempts restoration, but callers
/// should call [`Self::restore`] to observe and handle errors before unloading.
/// On Linux this is a no-op guard.
#[must_use = "keep the patch guard until the plugin restores normal time scaling"]
pub struct HostTimescalePatch {
	#[cfg(target_os = "windows")]
	patch: windows::Patch,
	_not_thread_safe: PhantomData<Rc<()>>,
}

impl HostTimescalePatch {
	/// Locates the workaround's target in the currently loaded Windows engine.
	/// This validates and retains the image without changing instructions.
	///
	/// The signature was verified in TF2's 64-bit Windows `Host_AccumulateTime`.
	/// Both references to `host_timescale` and the reference to `sv_cheats` must
	/// resolve to the registered variables' actual `m_pParent` fields. The two
	/// rejection branches must lead to the same verified continuation, and the
	/// replacement branch must lead to the float load. Exactly one match is
	/// required across the engine's readable executable sections.
	///
	/// # Safety
	///
	/// The caller must be on the server's main thread in a TF2 dedicated-server
	/// callback, outside execution of `Host_AccumulateTime`. No other thread may
	/// execute or patch that routine during installation or restoration. The
	/// guard must be restored and dropped under the same conditions, before
	/// engine shutdown. `cvar` must belong to that server's engine.
	pub unsafe fn locate(cvar: Cvar<'_>) -> Result<Self, PatchError> {
		#[cfg(target_os = "windows")]
		let patch = {
			// SAFETY: The caller upholds the engine-thread and timing contract.
			unsafe { windows::Patch::locate(cvar) }?
		};
		#[cfg(not(target_os = "windows"))]
		let _ = cvar;

		Ok(Self {
			#[cfg(target_os = "windows")]
			patch,
			_not_thread_safe: PhantomData,
		})
	}

	/// Enables the workaround, retaining restoration ownership on any error.
	///
	/// If a Windows operation fails after writing the byte, this guard still
	/// owns the patch and any pending page-protection or cache cleanup. Call
	/// [`Self::restore`] before releasing it. Calling this again after successful
	/// enabling is idempotent while its installed instruction remains unchanged.
	///
	/// # Safety
	///
	/// As for [`Self::locate`]: run on the server's main thread while nobody
	/// executes or patches `Host_AccumulateTime`.
	pub unsafe fn enable(&mut self) -> Result<(), PatchError> {
		#[cfg(target_os = "windows")]
		{
			// SAFETY: The caller upholds the engine-thread and timing contract.
			unsafe { self.patch.enable() }
		}
		#[cfg(not(target_os = "windows"))]
		Ok(())
	}

	/// Whether this guard has an outstanding installed Windows patch.
	pub fn is_active(&self) -> bool {
		#[cfg(target_os = "windows")]
		return self.patch.active;
		#[cfg(not(target_os = "windows"))]
		false
	}

	/// Restores the original instruction, page protection, and instruction cache.
	///
	/// This is idempotent after successful restoration. If another component
	/// changed the byte, it is left alone and an error is returned. A failed
	/// Windows operation can be retried while the guard remains alive.
	///
	/// # Safety
	///
	/// As for [`Self::locate`]: run on the server's main thread while nobody
	/// executes or patches `Host_AccumulateTime`.
	pub unsafe fn restore(&mut self) -> Result<(), PatchError> {
		#[cfg(target_os = "windows")]
		{
			// SAFETY: The caller upholds the engine-thread and timing contract.
			unsafe { self.patch.restore() }
		}
		#[cfg(not(target_os = "windows"))]
		Ok(())
	}
}

/// Why the engine's time-scale workaround could not be installed or restored.
#[derive(Debug, thiserror::Error)]
pub enum PatchError {
	#[error("the engine does not register `{0}`")]
	MissingVariable(&'static str),

	#[error("engine.dll has an unsupported or inaccessible PE image")]
	InvalidImage,

	#[error("engine.dll does not contain the verified TF2 time-scale gate")]
	UnsupportedEngine,

	#[error("engine.dll contains more than one verified TF2 time-scale gate")]
	AmbiguousGate,

	#[error("another component changed the time-scale gate's instruction")]
	InstructionChanged,

	#[error("{operation} failed: {source}")]
	Windows {
		operation: &'static str,
		#[source]
		source: std::io::Error,
	},
}

#[cfg(any(target_os = "windows", test))]
mod scan {
	use super::PatchError;
	use crate::sigscan;
	use std::ops::Range;

	pub(super) const ORIGINAL: u8 = 0x75;
	pub(super) const PATCH_OFFSET: usize = 28;

	// Host_AccumulateTime, TF2 Windows x64. Relocation-dependent displacements
	// are masked, then checked semantically below. The patch changes the jnz
	// into jmp with its existing +0x1c destination (the final movss).
	const PATTERN: [Option<u8>; 63] = [
		Some(0x48),
		Some(0x8b),
		Some(0x0d),
		None,
		None,
		None,
		None,
		Some(0x0f),
		Some(0x2f),
		Some(0x71),
		Some(0x54),
		Some(0x0f),
		Some(0x83),
		None,
		None,
		None,
		None,
		Some(0x48),
		Some(0x8b),
		Some(0x05),
		None,
		None,
		None,
		None,
		Some(0x83),
		Some(0x78),
		Some(0x58),
		Some(0x00),
		Some(ORIGINAL),
		Some(0x1c),
		Some(0x48),
		Some(0x8b),
		Some(0x0d),
		None,
		None,
		None,
		None,
		Some(0x48),
		Some(0x8b),
		Some(0x01),
		Some(0xff),
		Some(0x50),
		Some(0x30),
		Some(0x84),
		Some(0xc0),
		Some(0x0f),
		Some(0x84),
		None,
		None,
		None,
		None,
		Some(0x48),
		Some(0x8b),
		Some(0x0d),
		None,
		None,
		None,
		None,
		Some(0xf3),
		Some(0x0f),
		Some(0x10),
		Some(0x71),
		Some(0x54),
	];

	pub(super) const REPLACEMENT: u8 = 0xeb;

	/// An owned snapshot, so scanning never borrows mutable engine memory.
	pub(super) struct CodeSection {
		pub offset: usize,
		pub bytes: Vec<u8>,
	}

	pub(super) fn find_gate(
		base: usize,
		code: &[CodeSection],
		data: &[Range<usize>],
		timescale_parent: usize,
		cheats_parent: usize,
	) -> Result<usize, PatchError> {
		let mut found = None;
		for section in code {
			for index in sigscan::find_all(&section.bytes, &PATTERN) {
				let bytes = &section.bytes[index..index + PATTERN.len()];
				let Some(offset) = section.offset.checked_add(index) else {
					continue;
				};
				let Some(address) = base.checked_add(offset) else {
					continue;
				};
				let Some(reject) = address.checked_add(198) else {
					continue;
				};
				let Some(section_start) = base.checked_add(section.offset) else {
					continue;
				};
				let Some(section_end) = section_start.checked_add(section.bytes.len()) else {
					continue;
				};
				if !(section_start..section_end).contains(&reject)
					|| relative_target(address, 7, bytes, 3) != Some(timescale_parent)
					|| relative_target(address, 24, bytes, 20) != Some(cheats_parent)
					|| relative_target(address, 58, bytes, 54) != Some(timescale_parent)
					|| relative_target(address, 17, bytes, 13) != Some(reject)
					|| relative_target(address, 51, bytes, 47) != Some(reject)
				{
					continue;
				}
				let Some(demo) = relative_target(address, 37, bytes, 33) else {
					continue;
				};
				let Some(demo_end) = demo.checked_add(size_of::<usize>()) else {
					continue;
				};
				if !data
					.iter()
					.any(|range| range.start <= demo && demo_end <= range.end)
				{
					continue;
				}
				if found.replace(offset + PATCH_OFFSET).is_some() {
					return Err(PatchError::AmbiguousGate);
				}
			}
		}
		found.ok_or(PatchError::UnsupportedEngine)
	}

	fn relative_target(
		address: usize,
		instruction_end: usize,
		bytes: &[u8],
		displacement: usize,
	) -> Option<usize> {
		let value = i32::from_le_bytes(bytes.get(displacement..displacement + 4)?.try_into().ok()?);
		address
			.checked_add(instruction_end)?
			.checked_add_signed(value as isize)
	}

	#[cfg(test)]
	mod tests {
		use super::*;

		const BASE: usize = 0x180000000;
		const CHEATS: usize = BASE + 0x2100;
		const DEMO: usize = BASE + 0x2200;
		const TIMESCALE: usize = BASE + 0x2000;

		#[test]
		fn candidates_at_nonzero_section_offsets_are_found() {
			let mut code = CodeSection {
				offset: 0x100,
				bytes: vec![0x90; 0x80],
			};
			code.bytes.extend(section(0x180).bytes);
			assert_eq!(find(&[code]).unwrap(), 0x180 + PATCH_OFFSET);
		}

		#[test]
		fn every_candidate_in_a_section_is_validated() {
			let mut code = section(0x100);
			code.bytes.extend(section(0x200).bytes);
			assert!(matches!(
				find(std::slice::from_ref(&code)),
				Err(PatchError::AmbiguousGate)
			));

			// A signature match with the wrong variable must not hide the valid
			// candidate later in the same section or make it ambiguous.
			put_relative(&mut code.bytes, 3, 7, CHEATS, BASE + code.offset);
			assert_eq!(find(&[code]).unwrap(), 0x200 + PATCH_OFFSET);
		}

		fn find(code: &[CodeSection]) -> Result<usize, PatchError> {
			find_gate(
				BASE,
				code,
				&[BASE + 0x2000..BASE + 0x3000],
				TIMESCALE,
				CHEATS,
			)
		}

		fn put_relative(bytes: &mut [u8], at: usize, end: usize, target: usize, address: usize) {
			let delta = i32::try_from(target as i128 - (address + end) as i128).unwrap();
			bytes[at..at + 4].copy_from_slice(&delta.to_le_bytes());
		}

		#[test]
		fn rejection_branches_and_replacement_destination_are_checked() {
			for (at, end) in [(13, 17), (47, 51)] {
				let mut code = section(0x100);
				put_relative(
					&mut code.bytes,
					at,
					end,
					BASE + code.offset + 199,
					BASE + code.offset,
				);
				assert!(matches!(find(&[code]), Err(PatchError::UnsupportedEngine)));
			}
			let mut code = section(0x100);
			code.bytes[PATCH_OFFSET + 1] = 0x1d;
			assert!(matches!(find(&[code]), Err(PatchError::UnsupportedEngine)));
		}

		#[test]
		fn relocation_targets_must_be_the_registered_variables() {
			for (at, end, wrong) in [
				(3, 7, CHEATS),
				(20, 24, TIMESCALE),
				(54, 58, CHEATS),
				(33, 37, BASE + 0x100),
			] {
				let mut code = section(0x100);
				put_relative(&mut code.bytes, at, end, wrong, BASE + code.offset);
				assert!(matches!(find(&[code]), Err(PatchError::UnsupportedEngine)));
			}
		}

		fn section(offset: usize) -> CodeSection {
			let address = BASE + offset;
			let mut bytes = vec![0x90; 256];
			for (out, input) in bytes.iter_mut().zip(PATTERN) {
				*out = input.unwrap_or_default();
			}
			put_relative(&mut bytes, 3, 7, TIMESCALE, address);
			put_relative(&mut bytes, 20, 24, CHEATS, address);
			put_relative(&mut bytes, 54, 58, TIMESCALE, address);
			put_relative(&mut bytes, 33, 37, DEMO, address);
			put_relative(&mut bytes, 13, 17, address + 198, address);
			put_relative(&mut bytes, 47, 51, address + 198, address);
			CodeSection { offset, bytes }
		}

		#[test]
		fn selects_only_the_verified_gate() {
			assert_eq!(find(&[section(0x100)]).unwrap(), 0x100 + PATCH_OFFSET);
			assert!(matches!(
				find(&[section(0x100), section(0x500)]),
				Err(PatchError::AmbiguousGate)
			));
		}

		#[test]
		fn truncated_or_already_patched_code_is_refused() {
			let mut code = section(0x100);
			code.bytes.truncate(63);
			assert!(matches!(find(&[code]), Err(PatchError::UnsupportedEngine)));
			let mut code = section(0x100);
			code.bytes[PATCH_OFFSET] = REPLACEMENT;
			assert!(matches!(find(&[code]), Err(PatchError::UnsupportedEngine)));
		}
	}
}

#[cfg(target_os = "windows")]
mod windows {
	use super::{PatchError, scan};
	use crate::interfaces::Cvar;
	use std::ffi::c_void;
	use std::mem::{MaybeUninit, offset_of};
	use std::ops::Range;
	use std::ptr::{self, NonNull};

	const _: () = assert!(offset_of!(MemoryInformation, region_size) == 24);
	const _: () = assert!(offset_of!(sys::ConVar, m_fValue) == 0x54);
	const _: () = assert!(offset_of!(sys::ConVar, m_nValue) == 0x58);
	const _: () = assert!(offset_of!(sys::ConVar, m_pParent) == 56);
	const _: () = assert!(size_of::<MemoryInformation>() == 48);
	const IMAGE_SCN_MEM_EXECUTE: u32 = 0x20000000;
	const IMAGE_SCN_MEM_READ: u32 = 0x40000000;
	const MEM_COMMIT: u32 = 0x1000;
	const MEM_IMAGE: u32 = 0x1000000;
	const PAGE_EXECUTE_READWRITE: u32 = 0x40;

	#[repr(C)]
	struct MemoryInformation {
		base: *mut c_void,
		allocation_base: *mut c_void,
		allocation_protection: u32,
		partition_id: u16,
		region_size: usize,
		state: u32,
		protection: u32,
		kind: u32,
	}

	struct Module(NonNull<c_void>);

	impl Module {
		fn engine() -> Result<Self, PatchError> {
			const NAME: [u16; 11] = [101, 110, 103, 105, 110, 101, 46, 100, 108, 108, 0];
			let mut module = ptr::null_mut();
			// SAFETY: Both pointers are valid; flags zero acquires a loader
			// reference to an already loaded named module without loading a DLL.
			if unsafe { GetModuleHandleExW(0, NAME.as_ptr(), &mut module) } == 0 {
				return Err(os_error("GetModuleHandleExW(engine.dll)"));
			}
			NonNull::new(module)
				.map(Self)
				.ok_or(PatchError::InvalidImage)
		}

		fn base(&self) -> usize {
			self.0.as_ptr() as usize
		}

		fn copy(&self, offset: usize, len: usize) -> Result<Vec<u8>, PatchError> {
			self.readable(offset, len)?;
			let mut bytes = vec![0; len];
			// SAFETY: readable verified all source pages belong to the held
			// image and are readable; the owned destination does not overlap.
			// Installation's contract excludes concurrent code modification.
			unsafe {
				ptr::copy_nonoverlapping(
					(self.base() + offset) as *const u8,
					bytes.as_mut_ptr(),
					len,
				)
			};
			Ok(bytes)
		}

		/// Checks every page before copying memory out of the mapped image.
		fn readable(&self, offset: usize, len: usize) -> Result<(), PatchError> {
			let mut address = self
				.base()
				.checked_add(offset)
				.ok_or(PatchError::InvalidImage)?;
			let end = address.checked_add(len).ok_or(PatchError::InvalidImage)?;
			while address < end {
				let mut information = MaybeUninit::uninit();
				// SAFETY: VirtualQuery validates the address; the output buffer
				// has the Windows x64 MEMORY_BASIC_INFORMATION layout asserted above.
				if unsafe {
					VirtualQuery(
						address as *const c_void,
						information.as_mut_ptr(),
						size_of::<MemoryInformation>(),
					)
				} != size_of::<MemoryInformation>()
				{
					return Err(PatchError::InvalidImage);
				}
				// SAFETY: VirtualQuery initialized the complete structure.
				let information = unsafe { information.assume_init() };
				if information.allocation_base != self.0.as_ptr()
					|| information.state != MEM_COMMIT
					|| information.kind != MEM_IMAGE
					|| information.protection & 0x101 != 0
					|| information.protection & 0xee == 0
				{
					return Err(PatchError::InvalidImage);
				}
				let next = (information.base as usize)
					.checked_add(information.region_size)
					.ok_or(PatchError::InvalidImage)?;
				if next <= address {
					return Err(PatchError::InvalidImage);
				}
				address = next.min(end);
			}
			Ok(())
		}

		fn sections(&self) -> Result<(Vec<scan::CodeSection>, Vec<Range<usize>>), PatchError> {
			let dos = self.copy(0, 64)?;
			if dos[..2] != *b"MZ" {
				return Err(PatchError::InvalidImage);
			}
			let pe = usize::try_from(i32::from_le_bytes(dos[60..64].try_into().unwrap()))
				.map_err(|_| PatchError::InvalidImage)?;
			if !(64..=0x100000).contains(&pe) {
				return Err(PatchError::InvalidImage);
			}
			let coff = self.copy(pe, 24)?;
			if coff[..4] != *b"PE\0\0"
				|| u16::from_le_bytes(coff[4..6].try_into().unwrap()) != 0x8664
			{
				return Err(PatchError::InvalidImage);
			}
			let count = u16::from_le_bytes(coff[6..8].try_into().unwrap()) as usize;
			let optional_size = u16::from_le_bytes(coff[20..22].try_into().unwrap()) as usize;
			if !(1..=96).contains(&count) || !(112..=4096).contains(&optional_size) {
				return Err(PatchError::InvalidImage);
			}
			let optional = self.copy(pe + 24, optional_size)?;
			if u16::from_le_bytes(optional[..2].try_into().unwrap()) != 0x20b {
				return Err(PatchError::InvalidImage);
			}
			let image_size = u32::from_le_bytes(optional[56..60].try_into().unwrap()) as usize;
			let table = pe + 24 + optional_size;
			if !(table + count * 40..=0x40000000).contains(&image_size) {
				return Err(PatchError::InvalidImage);
			}
			let sections = self.copy(table, count * 40)?;
			let mut code = Vec::new();
			let mut data = Vec::new();
			for section in sections.chunks_exact(40) {
				let size = u32::from_le_bytes(section[8..12].try_into().unwrap()) as usize;
				let offset = u32::from_le_bytes(section[12..16].try_into().unwrap()) as usize;
				let flags = u32::from_le_bytes(section[36..40].try_into().unwrap());
				let end = offset.checked_add(size).ok_or(PatchError::InvalidImage)?;
				if offset > image_size || end > image_size {
					return Err(PatchError::InvalidImage);
				}
				if size == 0 || flags & IMAGE_SCN_MEM_READ == 0 {
					continue;
				}
				if flags & IMAGE_SCN_MEM_EXECUTE != 0 {
					code.push(scan::CodeSection {
						offset,
						bytes: self.copy(offset, size)?,
					});
				} else {
					self.readable(offset, size)?;
					data.push(self.base() + offset..self.base() + end);
				}
			}
			Ok((code, data))
		}
	}

	impl Drop for Module {
		fn drop(&mut self) {
			// SAFETY: This releases only the reference acquired by engine().
			unsafe { FreeLibrary(self.0.as_ptr()) };
		}
	}

	pub(super) struct Patch {
		_module: Module,
		location: NonNull<u8>,
		original_block: [u8; 63],
		pub active: bool,
		cache_dirty: bool,
		protection: Option<u32>,
	}

	impl Patch {
		pub(super) unsafe fn locate(cvar: Cvar<'_>) -> Result<Self, PatchError> {
			let timescale = cvar
				.find_var(c"host_timescale")
				.ok_or(PatchError::MissingVariable("host_timescale"))?;
			let cheats = cvar
				.find_var(c"sv_cheats")
				.ok_or(PatchError::MissingVariable("sv_cheats"))?;
			let module = Module::engine()?;
			let (code, data) = module.sections()?;
			let timescale_parent = (timescale.as_ptr() as usize)
				.checked_add(offset_of!(sys::ConVar, m_pParent))
				.ok_or(PatchError::InvalidImage)?;
			let cheats_parent = (cheats.as_ptr() as usize)
				.checked_add(offset_of!(sys::ConVar, m_pParent))
				.ok_or(PatchError::InvalidImage)?;
			if ![timescale_parent, cheats_parent].iter().all(|address| {
				data.iter().any(|range| {
					range.start <= *address
						&& address.checked_add(8).is_some_and(|end| end <= range.end)
				})
			}) {
				return Err(PatchError::UnsupportedEngine);
			}
			let offset =
				scan::find_gate(module.base(), &code, &data, timescale_parent, cheats_parent)?;
			let location = NonNull::new((module.base() + offset) as *mut u8)
				.ok_or(PatchError::InvalidImage)?;
			let original_block = module
				.copy(offset - scan::PATCH_OFFSET, 63)?
				.try_into()
				.map_err(|_| PatchError::InvalidImage)?;
			Ok(Self {
				_module: module,
				location,
				original_block,
				active: false,
				cache_dirty: false,
				protection: None,
			})
		}

		pub(super) unsafe fn enable(&mut self) -> Result<(), PatchError> {
			// SAFETY: locate validated all 63 bytes and keeps the module loaded;
			// the caller excludes concurrent execution and modification.
			if !unsafe {
				self.matches_block(if self.active {
					scan::REPLACEMENT
				} else {
					scan::ORIGINAL
				})
			} {
				return Err(PatchError::InstructionChanged);
			}
			if self.active {
				self.finish_write()
			} else {
				// SAFETY: The caller excludes execution and concurrent patching.
				unsafe { self.replace(scan::ORIGINAL, scan::REPLACEMENT, true) }
			}
		}

		fn finish_write(&mut self) -> Result<(), PatchError> {
			let cache_error = if self.cache_dirty {
				// SAFETY: The process pseudo-handle and the held image byte are
				// valid; this publishes the instruction change to execution.
				if unsafe {
					FlushInstructionCache(GetCurrentProcess(), self.location.as_ptr().cast(), 1)
				} == 0
				{
					Some(os_error("FlushInstructionCache(time-scale gate)"))
				} else {
					self.cache_dirty = false;
					None
				}
			} else {
				None
			};
			let protection_error = if let Some(protection) = self.protection {
				let mut old = 0;
				// SAFETY: This restores the protection Windows reported for the
				// live byte's page. Save the pending restoration on failure.
				if unsafe { VirtualProtect(self.location.as_ptr().cast(), 1, protection, &mut old) }
					== 0
				{
					Some(os_error(
						"VirtualProtect(time-scale gate, original protection)",
					))
				} else {
					self.protection = None;
					None
				}
			} else {
				None
			};
			match cache_error.or(protection_error) {
				Some(error) => Err(error),
				None => Ok(()),
			}
		}

		unsafe fn matches_block(&self, opcode: u8) -> bool {
			self.original_block
				.iter()
				.enumerate()
				.all(|(index, expected)| {
					let expected = if index == scan::PATCH_OFFSET {
						opcode
					} else {
						*expected
					};
					// SAFETY: The complete validated block is live in the held image,
					// and the caller excludes concurrent instruction modification.
					(unsafe {
						self.location
							.as_ptr()
							.sub(scan::PATCH_OFFSET)
							.add(index)
							.read_volatile()
					}) == expected
				})
		}

		unsafe fn replace(
			&mut self,
			expected: u8,
			value: u8,
			active: bool,
		) -> Result<(), PatchError> {
			// SAFETY: The held module keeps this validated executable byte live;
			// the caller excludes simultaneous execution and modification.
			if unsafe { self.location.as_ptr().read_volatile() } != expected {
				return Err(PatchError::InstructionChanged);
			}
			let mut old = 0;
			// SAFETY: This is one live image byte; Windows changes its page's
			// protection and initializes old before the byte is written.
			if unsafe {
				VirtualProtect(
					self.location.as_ptr().cast(),
					1,
					PAGE_EXECUTE_READWRITE,
					&mut old,
				)
			} == 0
			{
				return Err(os_error("VirtualProtect(time-scale gate, writable)"));
			}
			self.protection.get_or_insert(old);
			// SAFETY: The byte is writable and nobody executes or modifies it.
			unsafe { self.location.as_ptr().write_volatile(value) };
			self.active = active;
			self.cache_dirty = true;
			self.finish_write()
		}

		pub(super) unsafe fn restore(&mut self) -> Result<(), PatchError> {
			if self.active {
				// SAFETY: The held module keeps the checked instruction live.
				// If another component already restored the original byte, there
				// is nothing left to overwrite; pending OS cleanup still runs.
				if unsafe { self.location.as_ptr().read_volatile() } == scan::ORIGINAL {
					self.active = false;
					return self.finish_write();
				}
				// SAFETY: As for the checked instruction; refuse to change its
				// branch if another component modified the surrounding block.
				if !unsafe { self.matches_block(scan::REPLACEMENT) } {
					return Err(PatchError::InstructionChanged);
				}
				// SAFETY: The caller upholds the same contract as installation.
				unsafe { self.replace(scan::REPLACEMENT, scan::ORIGINAL, false) }
			} else {
				self.finish_write()
			}
		}
	}

	impl Drop for Patch {
		fn drop(&mut self) {
			// SAFETY: locate's caller promises the timing/main-thread contract
			// also holds for destruction. Module is released only after this.
			let _ = unsafe { self.restore() };
		}
	}

	#[link(name = "kernel32")]
	unsafe extern "system" {
		fn FlushInstructionCache(process: *mut c_void, address: *const c_void, size: usize) -> i32;
		fn FreeLibrary(module: *mut c_void) -> i32;
		fn GetCurrentProcess() -> *mut c_void;
		fn GetModuleHandleExW(flags: u32, name: *const u16, module: *mut *mut c_void) -> i32;

		fn VirtualProtect(
			address: *const c_void,
			size: usize,
			protection: u32,
			old: *mut u32,
		) -> i32;

		fn VirtualQuery(
			address: *const c_void,
			information: *mut MemoryInformation,
			length: usize,
		) -> usize;
	}

	fn os_error(operation: &'static str) -> PatchError {
		PatchError::Windows {
			operation,
			source: std::io::Error::last_os_error(),
		}
	}
}