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
//! # pe-sigscan
//!
//! Fast in-process byte-pattern ("signature") scanning over the executable
//! sections of a loaded PE (Portable Executable) module on Windows.
//!
//! This crate is a building block for game mods, hookers, debuggers, and any
//! other in-process tool that needs to locate non-exported, non-vtable-
//! accessible code by its byte signature. It mirrors the workflow common
//! across the reverse-engineering ecosystem — derive a pattern from a
//! disassembler (IDA, Ghidra, Binary Ninja, Cutter), then scan the live
//! process's mapped image for it at runtime.
//!
//! ## Quick start
//!
//! ```no_run
//! use pe_sigscan::{find_in_text, Pattern};
//!
//! // Get a module base via your preferred means (GetModuleHandleW,
//! // PEB walk, etc.). For demonstration we assume a known base.
//! # let module_base = 0usize;
//!
//! // Build a pattern from an IDA-style hex string. `?` and `??` are
//! // wildcards; whitespace between bytes is ignored.
//! let pat = Pattern::from_ida("48 8B 05 ?? ?? ?? ?? 48 89 41 08").unwrap();
//!
//! if let Some(addr) = find_in_text(module_base, pat.as_slice()) {
//! println!("matched at {addr:#x}");
//! }
//! ```
//!
//! Or with the `pattern!` macro (no allocation, fully `const`-eligible):
//!
//! ```
//! use pe_sigscan::pattern;
//!
//! const SIG: &[Option<u8>] = pattern![0x48, 0x8B, _, _, 0x48, 0x89];
//! assert_eq!(SIG.len(), 6);
//! assert_eq!(SIG[0], Some(0x48));
//! assert_eq!(SIG[2], None);
//! ```
//!
//! ## Two scanning modes
//!
//! - [`find_in_text`] / [`count_in_text`] / [`iter_in_text`] — walk only
//! the section literally named `.text`. The simplest case, suitable for
//! MSVC-built DLLs that put everything in one code section.
//! - [`find_in_exec_sections`] / [`count_in_exec_sections`] /
//! [`iter_in_exec_sections`] — walk every section whose
//! `IMAGE_SCN_MEM_EXECUTE` characteristic is set. Required when the
//! function you're scanning for might live in a companion section like
//! `.text$mn`, `.textbss`, a jump-table arena, or any of the
//! optimized-layout code sections that some compilers and linkers emit.
//!
//! Both modes have [`find_in_slice`] / [`count_in_slice`] / [`iter_in_slice`]
//! companions that work on a `&[u8]` instead of a loaded PE — useful for
//! offline analysis, unit testing, and scanning extracted bytes.
//!
//! ## Resolving rel32 displacements
//!
//! Real signature workflows almost always end with "match the
//! instruction, then follow its `rel32` displacement to the actual target
//! address". The [`resolve_rel32`] / [`resolve_rel32_at`] helpers package
//! that arithmetic so callers don't reinvent the off-by-one-prone
//! `next_ip + disp32` calculation:
//!
//! ```no_run
//! use pe_sigscan::{find_in_text, pattern, resolve_rel32_at};
//! # let module_base = 0usize;
//!
//! // mov rax, [rip+disp32]: 48 8B 05 ?? ?? ?? ?? (7 bytes total).
//! const SIG: &[Option<u8>] = pattern![0x48, 0x8B, 0x05, _, _, _, _];
//! if let Some(addr) = find_in_text(module_base, SIG) {
//! let target = unsafe { resolve_rel32_at(addr, 3, 7) };
//! println!("global at {target:#x}");
//! }
//! ```
//!
//! ## Why direct memory reads?
//!
//! The `.text` section of a loaded DLL is page-aligned, RX-protected, and
//! stays committed for the lifetime of the module. There is no TOCTOU
//! concern; bytes don't change between reads. A typical scan walks tens of
//! megabytes of bytes — routing every probe through `ReadProcessMemory`
//! would cost tens of millions of syscalls (minutes of wall time). This
//! crate reads directly via raw pointer dereference, bounded to PE-declared
//! section ranges.
//!
//! ## Safety
//!
//! Public functions take a `module_base: usize` you must obtain from the OS
//! (e.g. `GetModuleHandleW`). The implementation parses the PE headers at
//! that base before any other access, so a non-PE pointer is rejected
//! cleanly. Inside the validated section ranges, the unsafe pointer reads
//! are bounded by the `VirtualSize` field from the section header — outside
//! the loader handing us a malformed PE (which the loader itself would have
//! rejected), there is no path to an out-of-bounds read.
//!
//! The slice variants are safe by Rust's slice invariants and need no
//! further trust from the caller.
//!
//! ## Platform
//!
//! Windows / PE only.
//!
//! The crate compiles on every platform — the parsing is pure compute —
//! but the in-process function signatures assume a `module_base` that came
//! from the Windows loader. On non-Windows targets, the slice variants
//! still work for analysing PE bytes you have mapped manually.
//!
//! ## License
//!
//! MIT OR Apache-2.0.
extern crate alloc;
pub use crate;
pub use crate;
pub use crate;
pub use crate;
// Section-targeted scanners (feature `section-info`).
//
// `find_in_section` / `count_in_section` / `iter_in_section` live in
// `scan.rs` alongside the always-available scanners; they're the
// same shape as `find_in_text` etc. but take a section name as a
// parameter, letting callers scan inside `.rdata`, `.pdata`,
// `.text$mn`, etc. Internally they delegate to `crate::pe::find_section`.
//
// The feature also re-exports the section-lookup helpers from
// `crate::pe` so that advanced users can implement their own
// section-specific logic if needed.
pub use crate;
// `module_size` is a standalone reader for
// `IMAGE_OPTIONAL_HEADER.SizeOfImage` — useful for cross-module
// rel32 disambiguation (pairs naturally with the always-available
// `resolve_rel32*` helpers). It is exported unconditionally.
pub use cratemodule_size;
// ---------------------------------------------------------------------------
// pattern! macro
// ---------------------------------------------------------------------------
//
// Macros must be defined at the crate root (or re-exported with
// `#[macro_export]`) to be reachable as `pe_sigscan::pattern!`. We keep the
// definition here rather than in a `macros` submodule so the public macro
// path is the natural `crate::pattern!`.
/// Build a `&'static [Option<u8>; N]` at compile time from a list of byte
/// literals and `_` wildcards.
///
/// # Examples
///
/// ```
/// use pe_sigscan::pattern;
///
/// // `_` is the wildcard token. Use byte literals (0xNN) for fixed bytes.
/// const SIG: &[Option<u8>] = pattern![0x48, 0x8B, _, _, 0x48, 0x89];
/// assert_eq!(SIG, &[Some(0x48), Some(0x8B), None, None, Some(0x48), Some(0x89)]);
/// ```
///
/// This is the zero-cost / no-allocation alternative to
/// [`Pattern::from_ida`]. Use it when the pattern is known at compile time
/// (the common case for hard-coded signatures); use `Pattern::from_ida`
/// when the pattern is loaded from config, a dump file, or user input at
/// runtime.
;
}
/// Helper for [`pattern!`] — converts a single token into `Some(byte)` or
/// `None`. Hidden from the public surface; users should not call this
/// directly.
// ---------------------------------------------------------------------------
// Crate-level integration tests
// ---------------------------------------------------------------------------