aob_common/needle.rs
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
use crate::{
parsing,
pattern::{
DynamicPattern,
Method,
PatternRef,
StaticPattern,
},
prefilter::{
CompiledPrefilter,
PrefilterError,
},
Error,
RawPrefilter,
Sealed,
};
use chumsky::{
primitive::end,
Parser as _,
};
use std::ops::Range;
/// Represents a matching [`Needle`] found in the haystack.
#[derive(Clone, Copy, Debug)]
pub struct Match<'haystack> {
range: (usize, usize),
haystack: &'haystack [u8],
}
impl<'haystack> Match<'haystack> {
/// The position of the first byte in the matching needle, relative to the haystack.
///
/// ```
/// # use aob_common::{DynamicNeedle, Needle as _};
/// let needle = DynamicNeedle::from_ida("63 ? 74").unwrap();
/// let haystack = "a_cat_tries";
/// let matched = needle.find(haystack.as_bytes()).unwrap();
/// assert_eq!(matched.start(), 2);
/// ```
#[must_use]
pub fn start(&self) -> usize {
self.range.0
}
/// The position of the last byte past the end of the matching needle, relative to the haystack.
///
/// ```
/// # use aob_common::{DynamicNeedle, Needle as _};
/// let needle = DynamicNeedle::from_ida("63 ? 74").unwrap();
/// let haystack = "a_cat_tries";
/// let matched = needle.find(haystack.as_bytes()).unwrap();
/// assert_eq!(matched.end(), 5);
/// ```
#[must_use]
pub fn end(&self) -> usize {
self.range.1
}
/// The range of the matching needle, relative to the haystack.
///
/// ```
/// # use aob_common::{DynamicNeedle, Needle as _};
/// let needle = DynamicNeedle::from_ida("63 ? 74").unwrap();
/// let haystack = "a_cat_tries";
/// let matched = needle.find(haystack.as_bytes()).unwrap();
/// assert_eq!(matched.range(), 2..5);
/// ```
#[must_use]
pub fn range(&self) -> Range<usize> {
self.start()..self.end()
}
/// The actual matched bytes, from the haystack.
///
/// ```
/// # use aob_common::{DynamicNeedle, Needle as _};
/// let needle = DynamicNeedle::from_ida("63 ? 74").unwrap();
/// let haystack = "a_cat_tries";
/// let matched = needle.find(haystack.as_bytes()).unwrap();
/// assert_eq!(matched.as_bytes(), &b"cat"[..]);
/// ```
#[must_use]
pub fn as_bytes(&self) -> &'haystack [u8] {
&self.haystack[self.range()]
}
}
/// The common interface for searching haystacks with needles.
///
/// A successful search will yield a [`Match`] in the haystack, whose length is equal to the [length](Needle::len) of the needle. Matches may overlap.
///
/// ```
/// # use aob_common::{DynamicNeedle, Needle as _};
/// let needle = DynamicNeedle::from_ida("12 23 ? 12").unwrap();
/// let haystack = [0x32, 0x21, 0x12, 0x23, 0xAB, 0x12, 0x23, 0xCD, 0x12];
/// let mut iter = needle.find_iter(&haystack);
/// assert_eq!(&haystack[iter.next().unwrap().start()..], [0x12, 0x23, 0xAB, 0x12, 0x23, 0xCD, 0x12]);
/// assert_eq!(&haystack[iter.next().unwrap().start()..], [0x12, 0x23, 0xCD, 0x12]);
/// assert!(iter.next().is_none());
/// ```
#[expect(clippy::len_without_is_empty)]
pub trait Needle: Sealed {
/// A convenience method for getting only the first match.
#[must_use]
fn find<'haystack>(&self, haystack: &'haystack [u8]) -> Option<Match<'haystack>> {
self.find_iter(haystack).next()
}
/// Finds all matching subsequences, iteratively.
#[must_use]
fn find_iter<'needle, 'haystack>(
&'needle self,
haystack: &'haystack [u8],
) -> Find<'needle, 'haystack>;
/// The length of the needle itself.
///
/// ```
/// # use aob_common::{DynamicNeedle, Needle as _};
/// let needle = DynamicNeedle::from_ida("12 ? 56 ? 9A BC").unwrap();
/// assert_eq!(needle.len(), 6);
/// ```
#[must_use]
fn len(&self) -> usize;
}
/// An [`Iterator`] for finding subsequent matches of a [`Needle`] in a haystack.
pub struct Find<'needle, 'haystack> {
prefilter: CompiledPrefilter,
pattern: PatternRef<'needle>,
haystack: &'haystack [u8],
last_offset: usize,
}
impl Find<'_, '_> {
/// Yields the [`Method`] chosen for quick string comparison of the [`Needle`] against strings in the haystack.
#[must_use]
pub fn search_method(&self) -> Method {
self.pattern.method()
}
}
impl<'haystack> Iterator for Find<'_, 'haystack> {
type Item = Match<'haystack>;
fn next(&mut self) -> Option<Self::Item> {
macro_rules! failure {
() => {{
self.last_offset = self.haystack.len();
return None;
}};
}
macro_rules! success {
($start:ident, $end:ident) => {{
self.last_offset = $start + 1;
return Some(Match {
range: ($start, $end),
haystack: self.haystack,
});
}};
}
let mut prefilter_iter = self.prefilter.find_iter(&self.haystack[self.last_offset..]);
loop {
let prefilter_offset = match prefilter_iter.next() {
Some(Ok(offset)) => offset,
Some(Err(PrefilterError::HaystackTooSmall { offset })) => {
self.last_offset += offset;
break;
}
None => failure!(),
};
let start = self.last_offset + prefilter_offset;
let end = start + self.pattern.len();
let Some(haystack) = &self.haystack.get(start..end) else {
failure!();
};
// SAFETY: `haystack` has the same length as `self.pattern`
if unsafe { self.pattern.cmpeq_unchecked(haystack) } {
success!(start, end);
}
}
for (window_offset, window) in self.haystack[self.last_offset..]
.windows(self.pattern.len())
.enumerate()
{
// SAFETY: `window` has the same length as `self.pattern`
if unsafe { self.pattern.cmpeq_unchecked(window) } {
let start = self.last_offset + window_offset;
let end = start + self.pattern.len();
success!(start, end);
}
}
failure!();
}
}
/// The compile-time variant of a [`Needle`].
///
/// [`StaticNeedle`] is intended for embedding into executables at compile-time,
/// such that no allocations or validation is needed to perform a match on a
/// haystack at run-time.
///
/// You should never need to name this type directly:
/// * If you need to instantiate one, please use the `aob!` macro instead.
/// * If you need to use one in an api, please use the [`Needle`] trait instead.
#[derive(Clone, Debug)]
pub struct StaticNeedle<const NEEDLE_LEN: usize, const BUFFER_LEN: usize> {
prefilter: RawPrefilter,
pattern: StaticPattern<NEEDLE_LEN, BUFFER_LEN>,
}
impl<const NEEDLE_LEN: usize, const BUFFER_LEN: usize> StaticNeedle<NEEDLE_LEN, BUFFER_LEN> {
/// I will german suplex you if you use this hidden method.
#[doc(hidden)]
#[must_use]
pub const fn new(
prefilter: RawPrefilter,
word: [u8; BUFFER_LEN],
mask: [u8; BUFFER_LEN],
) -> Self {
Self {
prefilter,
pattern: StaticPattern::from_components(word, mask),
}
}
}
impl<const NEEDLE_LEN: usize, const BUFFER_LEN: usize> Sealed
for StaticNeedle<NEEDLE_LEN, BUFFER_LEN>
{
}
impl<const NEEDLE_LEN: usize, const BUFFER_LEN: usize> Needle
for StaticNeedle<NEEDLE_LEN, BUFFER_LEN>
{
fn find_iter<'needle, 'haystack>(
&'needle self,
haystack: &'haystack [u8],
) -> Find<'needle, 'haystack> {
let pattern: PatternRef<'_> = (&self.pattern).into();
let prefilter = match self.prefilter {
RawPrefilter::Length { len } => CompiledPrefilter::from_length(len),
RawPrefilter::Prefix {
prefix,
prefix_offset,
} => CompiledPrefilter::from_prefix(prefix, prefix_offset),
RawPrefilter::PrefixPostfix {
prefix: _,
prefix_offset,
postfix: _,
postfix_offset,
} => CompiledPrefilter::from_prefix_postfix(
pattern.word_slice(),
prefix_offset.into(),
postfix_offset.into(),
),
};
Find {
prefilter,
pattern,
haystack,
last_offset: 0,
}
}
fn len(&self) -> usize {
NEEDLE_LEN
}
}
/// The run-time variant of a [`Needle`].
#[derive(Clone, Debug)]
pub struct DynamicNeedle {
prefilter: CompiledPrefilter,
pattern: DynamicPattern,
}
impl DynamicNeedle {
/// Construct a [`DynamicNeedle`] using an Ida style pattern.
///
/// # Syntax
/// Expects a sequence of `byte` or `wildcard` separated by whitespace, where:
/// * `byte` is exactly 2 hexadecimals (uppercase or lowercase), indicating an exact match
/// * `wildcard` is one or two `?` characters, indicating a fuzzy match
///
/// # Example
/// ```
/// # use aob_common::{DynamicNeedle, Needle as _};
/// let needle = DynamicNeedle::from_ida("78 ? BC").unwrap();
/// let haystack = [0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE];
/// let matched = needle.find(&haystack).unwrap();
/// assert_eq!(&haystack[matched.start()..], [0x78, 0x9A, 0xBC, 0xDE]);
/// ```
pub fn from_ida(pattern: &str) -> Result<Self, Error<'_>> {
let parser = parsing::ida_pattern().then_ignore(end());
match parser.parse(pattern) {
Ok(ok) => Ok(Self::from_bytes(&ok)),
Err(mut errors) => {
let error = errors
.drain(..)
.next()
.expect("failure to parse should produce at least one error");
Err(Error {
source: pattern,
inner: error,
})
}
}
}
/// Contruct a [`DynamicNeedle`] using raw bytes, in plain Rust.
///
/// # Syntax
/// Expects an array of `Option<u8>`, where:
/// * `Some(_)` indicates an exact match
/// * `None` indicates a fuzzy match
///
/// # Example
/// ```
/// # use aob_common::{DynamicNeedle, Needle as _};
/// let needle = DynamicNeedle::from_bytes(&[Some(0x78), None, Some(0xBC)]);
/// let haystack = [0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE];
/// let matched = needle.find(&haystack).unwrap();
/// assert_eq!(&haystack[matched.start()..], [0x78, 0x9A, 0xBC, 0xDE]);
/// ```
#[must_use]
pub fn from_bytes(bytes: &[Option<u8>]) -> Self {
let pattern = DynamicPattern::from_bytes(bytes);
Self {
prefilter: CompiledPrefilter::from_bytes((&pattern).into()),
pattern,
}
}
#[doc(hidden)]
#[must_use]
pub fn serialize_word(&self) -> &[u8] {
self.pattern.word_slice_padded()
}
#[doc(hidden)]
#[must_use]
pub fn serialize_mask(&self) -> &[u8] {
self.pattern.mask_slice_padded()
}
#[doc(hidden)]
#[must_use]
pub fn serialize_prefilter(&self) -> RawPrefilter {
(&self.prefilter).into()
}
#[cfg(test)]
#[must_use]
pub(crate) fn prefilter(&self) -> &CompiledPrefilter {
&self.prefilter
}
}
impl Sealed for DynamicNeedle {}
impl Needle for DynamicNeedle {
fn find_iter<'needle, 'haystack>(
&'needle self,
haystack: &'haystack [u8],
) -> Find<'needle, 'haystack> {
Find {
prefilter: self.prefilter.clone(),
pattern: (&self.pattern).into(),
haystack,
last_offset: 0,
}
}
fn len(&self) -> usize {
self.pattern.len()
}
}
#[cfg(test)]
mod tests {
use super::{
DynamicNeedle,
Needle as _,
};
#[test]
fn test_from_ida() {
assert!(DynamicNeedle::from_ida("4_ 42 41 43 41 42 41 42 43").is_err());
assert!(DynamicNeedle::from_ida("11 ??? 22").is_err());
macro_rules! test_success {
($pattern:literal, $length:literal) => {
let needle = DynamicNeedle::from_ida($pattern);
assert!(needle.is_ok(), "\"{}\"", $pattern);
let needle = needle.unwrap();
assert_eq!(needle.len(), $length, "\"{}\"", $pattern);
};
}
test_success!("41 42 41 43 41 42 41 42 43", 9);
test_success!("41 42 41 43 41 42 41 42 41", 9);
test_success!(
"50 41 52 54 49 43 49 50 41 54 45 20 49 4E 20 50 41 52 41 43 48 55 54 45",
24
);
test_success!("11 ? ? 22 ? 33 44 ?", 8);
test_success!("aA Bb 1d", 3);
test_success!("11 ? 33 ?? 55 ? ?? 88", 8);
}
}