13 std::vector<PatternByte> bytes;
14 std::istringstream stream(pattern);
17 while (stream >> token)
19 if (token ==
"?" || token ==
"??")
21 bytes.push_back({.Wildcard =
true});
27 const char* end = token.data() + token.size();
28 auto [stop, ec] = std::from_chars(token.data(), end, value, 16);
29 if (ec != std::errc{} || stop != end || value > 0xFF)
31 Log::Error(
"Signature pattern has an invalid byte '{}'; ignoring the pattern.", token);
34 bytes.push_back({.Value =
static_cast<uint8_t
>(value)});
41 for (
size_t i = 0; i < size; ++i)
49 size_t anchor = pattern.size();
50 size_t rarest = SIZE_MAX;
52 for (
size_t i = 0; i < pattern.size(); ++i)
54 if (pattern[i].Wildcard)
58 if (
const size_t count = frequencies[pattern[i].Value]; count < rarest)
68static bool Matches(
const uint8_t* at,
const std::vector<PatternByte>& pattern)
70 for (
size_t i = 0; i < pattern.size(); ++i)
72 if (!pattern[i].Wildcard && at[i] != pattern[i].Value)
80const uint8_t*
FindFirst(
const uint8_t* base,
size_t size,
const std::vector<PatternByte>& pattern,
size_t anchor)
82 if (!base || pattern.empty() || size < pattern.size())
87 const size_t lastStart = size - pattern.size();
90 if (anchor >= pattern.size())
95 const uint8_t wanted = pattern[anchor].Value;
96 for (
size_t at = 0; at <= lastStart;)
100 const auto* found =
static_cast<const uint8_t*
>(std::memchr(base + at + anchor, wanted, lastStart - at + 1));
106 at =
static_cast<size_t>(found - base) - anchor;
107 if (
Matches(base + at, pattern))
Parsing and searching byte patterns, with no notion of a loaded module.
void Error(std::format_string< Args... > fmt, Args &&... args)
std::vector< PatternByte > ParsePattern(const std::string &pattern)
size_t Anchor(const std::vector< PatternByte > &pattern, const ByteHistogram &frequencies)
const uint8_t * FindFirst(const uint8_t *base, size_t size, const std::vector< PatternByte > &pattern, size_t anchor)
std::array< size_t, 256 > ByteHistogram
static bool Matches(const uint8_t *at, const std::vector< PatternByte > &pattern)
void CountBytes(const uint8_t *base, size_t size, ByteHistogram &counts)