Skip to content

About

Header-only C++20 bit-parallel Thompson NFA for Windows kernel wildcard matching (WCHAR/CHAR). Evaluates thousands of rules in a single O(N) pass using pure 64-bit GPR SWAR (no SSE/AVX), stack-resident fast paths, path-segment scoping, and lock-free readers for minifilters and EDR drivers.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

8 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

High-Performance Bit-Parallel Thompson NFA for Kernel Wildcard Matching

Platform: Windows Kernel (x64 / ARM64) Language: C++20 (MSVC 2026) Environment: Kernel Mode

  • Single-Pass $O(N)$ Multi-Pattern Matching: Evaluates all $K$ registered rules simultaneously in a single pass of $O(N)$ steps in input length $N$ for a fixed compiled automaton, avoiding $O(K)$ rule loops and backtracking blowups.
  • 64-Bit GPR SWAR Acceleration (No SSE/AVX): Vectorizes ASCII case-folding, 2-character digraph / 16-byte nibble-LUT wildcard skipping, and literal-run verification in general-purpose registers—no SSE/AVX context-save penalties.
  • Compile-Time Partitioning, Leading-? Stripping & Radix Compression: Separates mixed anchored and leading-* rule sets, strips leading ? prefixes behind a 128-bit ASCII prefilter, and collapses deterministic literal chains into single NFA states.
  • Stack Fast-Path & Concurrent Immutable Readers: Executes on the kernel stack with zero pool allocations up to 4,096 states (tiered at 16 and 64 state words) and supports concurrent immutable readers with caller-managed RCU-style replacement (EX_RUNDOWN_REF / KmSharedPtr).
  • Kernel-Safe by Design: Strictly non-recursive, no C++ heap allocation (all runtime buffers use ExAllocatePool2 / ExFreePoolWithTag directly), native path-segment scoping (SCOPE_PATH_SEGMENT), and DISPATCH_LEVEL execution for CHAR, case-sensitive WCHAR, and ASCII-only ($\le \text{0x7F}$) case-insensitive WCHAR.
  • User-Mode WDK Test Harness: Includes a correctness and benchmark suite compilable in user space for rapid debugging without VM deployment.

Table of Contents

  1. Overview
  2. Architecture & Algorithms
  3. Quick Start API Overview
  4. Benchmarks & Scaling Performance
  5. Project Layout
  6. Building Instructions
  7. Conclusion
  8. License

Overview

KmWildcardNfa is a bit-parallel Thompson Non-Deterministic Finite Automaton (NFA) engine designed for Windows kernel-mode drivers, file system minifilters, and security telemetry. Unlike single-pattern kernel routines such as FsRtlIsNameInExpression—which require sequential $O(K)$ loops over $K$ registered rules—and unlike backtracking wildcard matchers that degrade to exponential or $O(N^2)$ time on multi-wildcard expressions, KmWildcardNfa compiles wildcard patterns into a prefix-deduplicated state graph and evaluates all $K$ patterns simultaneously in a single pass over an input string of length $N$.

To support file system filtering, the engine natively implements path segment scoping (SCOPE_PATH_SEGMENT), halting wildcard expansion (* and ?) upon encountering native directory separator boundaries (\).

Operational Guarantees & Constraints

  • Concurrent Immutable Readers with Caller-Managed RCU-Style Replacement: After Compile() completes, MatchFirst() and MatchAll() are const and safe for simultaneous execution across arbitrary CPU cores without locks. Mutating methods (AddPattern(), Compile(), Clear()) are not thread-safe with respect to each other or concurrent readers. Atomic pointer publication (e.g., via InterlockedExchangePointer) and reader lifetime management / reclamation (e.g., via EX_RUNDOWN_REF or KmSharedPtr) are caller responsibilities.
  • No C++ Heap Allocation & Non-Recursive Execution: All internal buffers are allocated explicitly from Windows kernel pools (ExAllocatePool2 / ExFreePoolWithTag) with no operator new or operator delete. Matching is strictly iterative, avoiding kernel stack exhaustion regardless of input length $N$ or wildcard complexity.
  • State & Pattern Capacity: Each compiled NFA_ENGINE_DATA block supports up to 262,144 deduplicated states (4,096 64-bit state words), with up to 4,096 states (64 state words) served by the stack-only fast-path (Path A). Maximum pattern count is bounded by this state budget rather than a fixed pattern cap: disjoint non-deterministic patterns fit roughly $\lfloor 262{,}144 / L_{\text{avg}} \rfloor$ rules, while shared-prefix kernel path and registry rulesets—aided by Trie prefix merging and deterministic Radix compression—scale to tens of thousands of patterns.
  • IRQL Compatibility:
    • AddPattern() & Compile(): Allocate staging and transient build structures from pool and require IRQL <= APC_LEVEL.
    • Clear(): Releases Non-Paged Pool buffers and supports execution up to IRQL <= DISPATCH_LEVEL.
    • MatchFirst() & MatchAll() (CHAR): Both case-sensitive and case-insensitive 8-bit CHAR matching operate on non-paged state tables and branchless ASCII arithmetic, supporting IRQL <= DISPATCH_LEVEL when the KmWildcardNfa instance and caller buffers are resident/non-paged.
    • MatchFirst() & MatchAll() (WCHAR — Case-Sensitive): Supports IRQL <= DISPATCH_LEVEL across the full 16-bit Unicode range (0x0000..0xFFFF) when the instance and caller buffers are resident/non-paged; evaluating paged WCHAR buffers requires IRQL < DISPATCH_LEVEL.
    • MatchFirst() & MatchAll() (WCHAR — Case-Insensitive): Requires IRQL == PASSIVE_LEVEL for non-ASCII Unicode code points ($\ge \text{0x80}$), because RtlUpcaseUnicodeChar accesses paged system NLS tables. ASCII code points ($\le \text{0x7F}$) are pre-folded into non-paged tables and SWAR masks; if invoked at DISPATCH_LEVEL in release builds, non-ASCII code points degrade to direct comparison to avoid page faults.

Architecture & Algorithms

High-Level Lifecycle

KmWildcardNfa separates pattern preprocessing from runtime evaluation through three stages:

  1. Registration (AddPattern): Validates arguments and appends patterns into a geometrically grown Non-Paged Pool staging array (PATTERN_ENTRY, starting at 16 entries and doubling up to $2^{31}$ entries subject to pool availability). When bCaseInsensitive is enabled, pattern characters are pre-normalized to uppercase during insertion via 64-bit SWAR (SwarUpcaseBuffer).
  2. Compilation (Compile & CompilePatternSubset):
    • Anchored / Leading-* Partitioning: When both anchored and unescaped leading-* patterns are present, Compile() allocates a trivial NFA_ENGINE_DATA sub-engine (m_pStarEngine) from Non-Paged Pool via ExAllocatePool2 and compiles leading-* rules separately from anchored rules (m_PrimaryEngine) without copying pattern strings.
    • Leading-? Stripping (AnalyzeAndConfigureLeadingAnyStripping): Detects uniform leading-? prefixes (1..63 ? characters, including ?*...) or mixed deterministic sets ($\le 8$ distinct depths without root *), emitting 128-bit pre-folded ASCII first-character masks (STRIPPED_START_INFO) and per-match start/scope requirement bytes (pMatchStartReqs).
    • Prefix Trie Deduplication (BuildPrefixTrie): Inserts patterns (starting past any stripped leading ?) into a transient Paged Pool prefix Trie (TRIE_NODE), collapsing consecutive * operators into single Op::Star states, resolving | escapes, appending terminal Op::Accept states for patterns not ending in *, and chaining caller contexts (MATCH_LINK_NODE) in FIFO order per accepting state. Enforces the 262,144-state limit (MAX_INSTRUCTIONS) post-deduplication.
    • Deterministic Radix Compression & Chain-Contiguous Sibling BFS (CompressDeterministicLiteralChains & AssignStateIndicesBfs): Hoists shared anchored root literal prefixes ($\ge$ CHARS_PER_QUAD via FindSharedRootLiteralPrefix), marks strictly single-active deterministic literal chains (including chains beneath sole-child ? wildcards such as \Device\HarddiskVolume?\...) for 1-state Radix compression, and assigns state indices starting from the post-prefix anchor so live states begin in Word 0.
    • Runtime Table & SWAR Filter Generation (AllocateRuntimeTables & PopulateInstructionsAndFilters): Computes epsilon-closures (ComputeNodeTransitionClosure), packs each state's primary target word into a 16-byte NFA_INSTRUCTION, spills multi-word closures to EXTRA_TARGET_WORD, builds 128-entry ASCII compatibility masks (WORD_SWAR_FILTER) with pre-folded lowercase slots ('a'..'z'), computes nearest post-dominating Word-0 SCOPE_DEFAULT Op::Star bits (ucDomWord0StarBit) in reverse topological order, and consolidates InitialStates, AcceptStates, and InitialWordsMask into one Non-Paged Pool allocation.
    • Literal-Run Descriptors & Root * Configuration (BuildLiteralRunsAndDescriptors & ConfigureStarSteadyStateSkip): Allocates exact-sized pszLiteralRuns and front-loaded 24-byte LITERAL_RUN_DESC tables (chain heads first, sparse post-\ / 64-char mid-chain restart checkpoints at the tail), computes initial closure masks from the anchor node, and configures root * steady-state skipping (SingleExitWithNextChar, SingleExitWithNextLut, DualBroadcast, or SwarFilter). m_bCompiled is published via WriteBooleanRelease so all runtime tables are visible on ARM64 and x64 before readers observe TRUE.
  3. Execution (ExecuteVm<bCaseInsensitive>): Dispatches at compile time on bCaseInsensitive, selects standard vs. extended execution via a single Cache-Line-0 flag (m_bUseExtendedDispatch, avoiding indirect-call kCFG overhead), verifies any shared anchored root prefix 8 bytes at a time, and steps through the bit-parallel NFA.

1. Trie Prefix Merging, Radix Compression & Chain-Contiguous Sibling BFS

BuildPrefixTrie collapses shared directory and registry prefixes into a single Trie path. CompressDeterministicLiteralChains then walks strictly deterministic subtrees (parents with no Op::Star or co-active Op::Any sibling, or a sole Op::Any child) and collapses unbranched literal chains ($\ge$ CHARS_PER_QUAD) into 1 NFA state backed by LITERAL_RUN_DESC.

During state numbering, AssignStateIndicesBfs keeps sibling branches contiguous so a single 64-bit word filter evaluates forks together, while packing single-child chains into the same 64-bit state word. Radix-compressed chains consume 1 state bit instead of $L$ bits, reducing Non-Paged Pool usage and keeping larger anchored rule sets inside Path A's 4,096-state stack fast-path.

2. Hierarchical Bitset State Tracking & Scratch Buffer Lifecycle

Depending on compiled state count, ExecuteVmRunForStart selects one of two execution tiers:

  • Path A ($\le 64$ State Words / $\le 4,096$ States — Tiered Stack Fast-Path):
    • Dispatches to a 16-word stack frame (STACK_SMALL_FAST_PATH_WORDS, $\le 1,024$ states, 256-byte buffers) or a 64-word stack frame (STACK_FAST_PATH_WORDS, $\le 4,096$ states, 1,024-byte buffers). Ping-pong state buffers (StatesBufferA / StatesBufferB) reside on the kernel stack and active words are tracked in a single 64-bit register (ulCurrentWordsMask), scanned via _BitScanForward64 and x &= (x - 1).
    • Since Path A performs zero pool allocations and touches no shared mutable state, Path A execution is unconditionally lock-free and wait-free across concurrent threads.
  • Path B ($&gt; 64$ State Words / up to $262,144$ States — 3-Level ulSuperMask Hierarchy):
    • Normal Execution Path (Uncontended): Tracks up to $64 \times 64 = 4,096$ state words via a top-level 64-bit ulSuperMask register. Compile() pre-allocates a pre-zeroed Non-Paged Pool scratch buffer (pulScratchStateBuffer) with an interleaved layout ([WordsMask0 | States0] [WordsMask1 | States1]) so L2 masks and low L1 state words share the first 4 KB page and buffer swaps rotate 2 pointers instead of 4. An entering thread acquires this buffer via InterlockedCompareExchangeAcquire(&pEngine->lScratchBufferInUse, 1, 0) == 0, sparsely initializes active words from ulInitialSuperMask, and zeroes dirty words in a single structured cleanup epilogue before releasing the latch with WriteRelease(&pEngine->lScratchBufferInUse, 0). Uncontended Path B calls perform zero runtime pool allocations.
    • Contention Fallback: If multiple threads concurrently evaluate the same Path B engine while lScratchBufferInUse == 1, the compare-exchange fails immediately without spinning and the contending thread allocates a temporary per-call Non-Paged Pool scratch buffer (ExAllocatePool2 / ExFreePoolWithTag), returning FALSE if pool exhaustion occurs.

3. 64-Bit GPR SWAR Acceleration Suite (No SSE/AVX)

All vectorization operates on 8 CHARs or 4 WCHARs per 64-bit general-purpose register load without touching SSE/AVX state:

  • Parallel ASCII Case-Folding (SwarUpcaseQuad / ToUpperSwar): Checks IsAsciiSwar ((ullQuad & SWAR_ASCII_HIGH_MASK) == 0) and folds all ASCII lanes branchlessly via ullGeA & ~ullGtZ and ullQuad ^ (ullIsLower >> 2). Quads containing non-ASCII code points ($\ge \text{0x80}$) branch to an out-of-line __declspec(noinline) SwarUpcaseQuadFallback.
  • 2-Character Digraph & 16-Byte Next-Char LUT Root * Skipping (SkipBroadcastSwar): Uses single-op bit-5 ASCII case masking (ComputeAsciiCaseMaskAndTarget) and Mycroft zero-lane detection (SwarHasZeroLane64) across 64-bit loads:
    • 2-Character Digraph (SingleExitWithNextChar): For a single non-accepting literal exit with one literal child (e.g., *allocation*, *random*), evaluates two overlapping 64-bit loads ((q0 | m1) ^ t1) | ((q1 | m2) ^ t2) so single-character false hits do not wake the scalar NFA.
    • 16-Byte Next-Char Nibble LUT (SingleExitWithNextLut): For a single non-accepting literal exit with multiple literal children (e.g., *A%dB* or *.exe / *.dll / *.sys), filters the 2nd character against a 16-byte ASCII nibble LUT inside the SWAR loop.
    • Dual Broadcast (DualBroadcast): Scans 1 or 2 distinct literal exits simultaneously in-register.
  • Stack-Cached Dynamic Word-0 * Skipping, ucDomWord0StarBit Pruning & 1-Branch ASCII Quad Filter (TrySkipWord0SteadyStateSwar / TryProbeQuadsSwar): When Word 0 is the sole active state word and is self-sustained by SCOPE_DEFAULT Op::Star states (ullWord0DefaultStarMask), ClassifyWord0DynamicSteadyState caches the exit classification on the stack (WORD0_DYNAMIC_SKIP_CACHE, zeroing only its two sentinel keys on VM entry). Exits whose unbranched non-accepting subtrees lead exclusively into an already-active Word-0 SCOPE_DEFAULT Op::Star (ucDomWord0StarBit) are pruned; absorbing states jump straight to cchLen, 1–2 literal exits use DualBroadcast, and 3+ literal or Op::Any exits use TryProbeQuadsSwar, which OR-combines all 4 or 8 ullAsciiMatchMask loads per ASCII quad into a single miss branch.
  • Permanent Accepting State Early-Exit (CheckWord0PermanentAccept): Precomputes ullWord0PermanentAcceptMask for terminal Word-0 SCOPE_DEFAULT Op::Star accepting states (pre-filtered by FilterPermAcceptMaskForStart when leading-? stripping is active) and guards the Word-0 load on ullPermAcceptMask != 0.
  • Radix-Compressed & Unbranched Literal-Run Verification (VerifyLiteralRunSwar / TryAdvanceLiteralRunSwar): Verifies shared root literal prefixes and unbranched mid-Trie Op::Literal chains 8 bytes at a time (with an overlapping 64-bit tail load for unaligned lengths), resolving both the run slice and post-run transition from a single 24-byte LITERAL_RUN_DESC.
  • 64-Way Bit-Parallel State Filtering (FilterActiveStatesSwar): Pre-folds lowercase 'a'..'z' slots into WORD_SWAR_FILTER::ullAsciiMatchMask[128] at compile time so all 64 states in a word are filtered with a single bitwise AND and zero per-character ASCII upcasing instructions.

4. Cache-Line-Engineered Data Layout

Hot read-only fields pack into the leading cache lines of NFA_ENGINE_DATA, while lScratchBufferInUse is separated by SYSTEM_CACHE_ALIGNMENT_SIZE bytes (64 B on x64, 128 B on ARM64) without raising alignof(KmWildcardNfa) above MEMORY_ALLOCATION_ALIGNMENT:

KmWildcardNfa Top-Level Layout (x64)
+---------------------------------------------------------------------------------------------------+
| Top-Level Dispatch Header (24 Bytes): Read-Only Flags & Extended Dispatch Pointers                |
+-----------------------------------+-------------------------------+-------------------------------+
| Bytes 0..7 (8B)                   | Bytes 8..15 (8B)              | Bytes 16..23 (8B)             |
| bCaseInsensitive (1B)             | m_pStarEngine*                | m_pStrippedStarts*            |
| bCompiled (1B), bUseExtDisp (1B)  | (Trivial NFA_ENGINE_DATA*,    | (STRIPPED_START_INFO*,        |
| bHasStart0 (1B), ucStripCnt (1B)  |  NULL unless mixed *+anchored)|  NULL unless leading-? strip) |
| [3B Align Pad]                    |                               |                               |
+-----------------------------------+-------------------------------+-------------------------------+
| m_PrimaryEngine (NFA_ENGINE_DATA: 224 Bytes on x64 / 288 Bytes on ARM64)                          |
+---------------------------------------------------------------------------------------------------+
|   Engine Cache Line 0 (Bytes 0..63): Hottest Path A & Path B VM Execution Fields                  |
|   ulStateWords64 (4B) | ulPrefixLength (4B) | pInstructions* (8B) | pWordFilters* (8B)            |
|   pExtraTargets* (8B) | pulInitialStates* (8B) | pulScratchStateBuffer* (8B)                      |
|   ulInitialSuperMask (8B) | pszLiteralRuns* (8B)                                                  |
+---------------------------------------------------------------------------------------------------+
|   Engine Cache Line 1 (Bytes 64..127): Literal-Run Descriptors, Metadata & Word-0 SWAR Masks      |
|   pLiteralRunDescs* (8B) | pStateMetadata* (8B) | pMatchLinks* (8B) | pMatchStartReqs* (8B)       |
|   ullSteadyStateWord0 (8B) | ullWord0DefaultStarMask (8B) | ullWord0PermanentAcceptMask (8B)      |
|   ullStarExitBroadcast1 (8B)                                                                      |
+---------------------------------------------------------------------------------------------------+
|   Engine Cache Line 2+ (Cold + Isolated Latch):                                                   |
|   ullStarExitBroadcast2 (8B) | ucRootStarNextLut[16] (16B) | eRootSteadyStateKind (1B)            |
|   bRootStarNextStopOnNonAscii (1B) | ucScratchLatchPad[SYSTEM_CACHE_ALIGNMENT_SIZE]               |
|   [2B Pad] | lScratchBufferInUse (LONG, 4B)                                                       |
+---------------------------------------------------------------------------------------------------+
| Cold Pattern-Staging Tail (16 Bytes, Never Read During MatchFirst / MatchAll)                     |
| m_pPatterns* (8B) | m_ulPatternCount (4B) | m_ulPatternCapacity (4B)                              |
+---------------------------------------------------------------------------------------------------+

Hot Compiled State Descriptor: NFA_INSTRUCTION (16 Bytes -> 4 Instructions per 64-Byte Cache Line)
+-----------------------------------+-----------------------+-------------------+-------------------+
| Bytes 0..7 (8B)                   | Bytes 8..11 (4B)      | Bytes 12..13 (2B) | Bytes 14..15 (2B) |
| ullTargetBits (Primary 64b mask)  | ulExtraOffset         | usTargetWord      | usExtraCount      |
|                                   | [Bit 31: LitRunFlag]  | (or MAXUSHORT)    | (Overflow count)  |
+-----------------------------------+-----------------------+-------------------+-------------------+

Literal-Run Descriptor: LITERAL_RUN_DESC (24 Bytes, Front-Loaded Chain Heads + Sparse Checkpoints)
+---------------------------------------------------+-----------------------+-----------------------+
| Bytes 0..15 (16B)                                 | Bytes 16..19 (4B)     | Bytes 20..23 (4B)     |
| EndInst (Inlined NFA_INSTRUCTION of chain end)    | ulRunOffset           | ulRunLength           |
+---------------------------------------------------+-----------------------+-----------------------+
  • Hot 16-Byte NFA_INSTRUCTION: Packs ullTargetBits (8B), ulExtraOffset (4B, bit 31 = NFA_INST_LITERAL_RUN_FLAG), usTargetWord (2B), and usExtraCount (2B)—4 instructions per 64-byte cache line.
  • Compact 24-Byte LITERAL_RUN_DESC: Inlines the chain end state's outgoing NFA_INSTRUCTION alongside ulRunOffset and ulRunLength, avoiding pStateMetadata and pInstructions[endState] lookups on literal-run fast-forwards.
  • Compact 8-Byte NFA_STATE_METADATA: Stores ulFirstMatchIdx (4B), chLiteral (1–2B), eOp (1B), and ucDomWord0StarBit (1B)—8 entries per 64-byte cache line.
  • Inlined Context Links (MATCH_LINK_NODE): Inlines TContext directly into the accepting state's singly-linked match list, eliminating secondary pointer chases during match harvesting.

Quick Start API Overview

KmWildcardNfa is header-only (KmWildcardNfa.h) and requires only standard WDK headers. Copy construction and copy assignment are explicitly deleted to prevent shallow copies of Non-Paged Pool tables.

Pattern Syntax & Wildcard Scoping

1. Supported Wildcard Operators

  • * (Zero or More Characters): Matches zero or more characters within the configured WILD_CARD_SCOPE. Adjacent asterisks (e.g., **) collapse into a single self-looping Op::Star state during BuildPrefixTrie().
  • ? (Single Character): Matches any single character within the configured WILD_CARD_SCOPE.

2. Literal Escaping (|)

The pipe character (|) acts as an escape prefix so reserved wildcard symbols can be matched literally:

  • |*: Matches a literal asterisk (*).
  • |?: Matches a literal question mark (?).
  • ||: Matches a literal pipe (|).
  • Unrecognized or Dangling Escapes: If | is followed by any other character, or appears at the very end of a pattern, it is treated as a verbatim literal character without buffer overreads.

3. Path Boundary Scoping (WILD_CARD_SCOPE)

  • SCOPE_DEFAULT (0): Unrestricted wildcard expansion across all characters, including native path separators (\). Suitable for rules spanning arbitrary directory depths (e.g., \Device\*\Confidential\*.dat).
  • SCOPE_PATH_SEGMENT (1): Confines * and ? to a single path segment by blocking expansion across \ boundaries (e.g., \Device\HarddiskVolume1\Temp\*.tmp will not match nested subdirectories).

Resolution Precedence & Ordering Semantics

Security policy warning: MatchFirst() does not implement global registration-order or security-priority resolution. Terminal unrestricted * rules may preempt more specific matches. Use MatchAll() when matching rules can have conflicting actions.

When multiple registered patterns match an input string, MatchFirst() and MatchAll() follow these resolution rules:

  1. Partitioned & Stripped-Start Evaluation Order (ExecuteVmExtended):
    • When mixed anchored and leading-* patterns are partitioned (m_pStarEngine != NULL) and/or leading-? stripping is active (m_ucStrippedStartCount > 0), evaluation proceeds in deterministic pass order:
      1. Anchored start-0 patterns (m_PrimaryEngine at offset 0).
      2. Stripped leading-? patterns (m_PrimaryEngine at ascending start offsets k in 1..63).
      3. Partitioned leading-* patterns (m_pStarEngine at offset 0).
    • In mixed sets, anchored patterns therefore resolve before leading-* patterns in MatchFirst() and appear before leading-* patterns in MatchAll(). Identical patterns always reside in the same engine and start offset, preserving their FIFO order.
  2. Permanent-Accept Mid-String Early Termination (MatchFirst() Only):
    • Any pattern ending in an unrestricted * (Op::Star with SCOPE_DEFAULT) whose compiled state resides in Word 0 (ulStateIdx < 64) is recorded in ullWord0PermanentAcceptMask (pre-filtered by FilterPermAcceptMaskForStart for the active start offset when leading-? stripping is enabled).
    • During MatchFirst(), activating any valid bit in ullPermAcceptMask terminates immediately via CheckWord0PermanentAccept() without scanning the remainder of the string. Within a pass, a broad SCOPE_DEFAULT rule ending in * (e.g., \Device\HarddiskVolume1\* with action AUDIT) preempts a more specific rule (e.g., \Device\HarddiskVolume1\Temp\*.tmp with action BLOCK) regardless of registration order. If multiple Word-0 permanent-accepting states activate on the same step, the lowest state index (_BitScanForward64) wins and resolves the head of its FIFO MATCH_LINK_NODE chain.
  3. End-of-Input Resolution & FIFO Ordering (MatchFirst() and MatchAll()):
    • When no Word-0 permanent-accepting state triggers early exit (always true in MatchAll(), and true in MatchFirst() when only non-permanent states are active), evaluation proceeds to cchOffset == cchLen.
    • At end-of-input, HarvestWordMatches() scans surviving accepting state bits in ascending BFS ulStateIdx order and walks each accepting state's MATCH_LINK_NODE list in FIFO registration order (filtered by pMatchStartReqs when leading-? stripping is active). FIFO ordering is therefore guaranteed among patterns sharing the same accepting Trie state; across distinct accepting Trie nodes, order follows pass order and ascending BFS ulStateIdx.
  4. Usage Guidance:
    • Use MatchFirst() when all rules share a uniform action (e.g., indicator/IOC detection where any match triggers telemetry) or when rules cannot carry conflicting policy actions.
    • Use MatchAll() whenever rules encode conflicting security actions (e.g., BLOCK vs. ALLOW overrides) so your driver can apply explicit policy priority over all matched contexts.

Template Parameters

template <typename TContext, typename TChar = WCHAR>

  • TContext: Caller-supplied context payload type associated with each pattern (e.g., rule ID, flags struct, or pointer). Enforced at compile time via static_assert(__is_trivially_copyable(TContext)) and static_assert(alignof(TContext) <= MEMORY_ALLOCATION_ALIGNMENT).
  • TChar: Character type (WCHAR for 16-bit Unicode or CHAR for 8-bit ANSI/ASCII). Enforced at compile time via static_assert(sizeof(TChar) == 1 || sizeof(TChar) == 2). Convenience type aliases KmWildcardNfaW<TContext> and KmWildcardNfaA<TContext> are provided.

Public API Methods

explicit KmWildcardNfa(_In_ BOOLEAN bCaseInsensitive = TRUE) noexcept;
  • Constructs an empty NFA instance. When bCaseInsensitive is TRUE (default), pattern registration and string evaluation normalize ASCII (a-z $\rightarrow$ A-Z) and Unicode code points.
_IRQL_requires_max_(APC_LEVEL)
NTSTATUS AddPattern(_In_reads_opt_(cchLen) const TChar* __restrict    pszPattern,
                    _In_                   size_t                     cchLen,
                    _In_                   WILD_CARD_SCOPE            eScope,
                    _In_                   const TContext& __restrict rContext) noexcept;
  • Stages a wildcard pattern and its associated TContext payload into a geometrically grown Non-Paged Pool array (up to $2^{31}$ staged entries, bounded by available pool and the 262,144 post-deduplication compiled state limit in Compile()). Invalidates any previously compiled runtime tables if called after Compile(). Returns STATUS_INVALID_PARAMETER on invalid arguments or STATUS_INSUFFICIENT_RESOURCES on capacity overflow or allocation failure.
  • pszPattern / cchLen: Pointer to the pattern buffer and its character count (excluding any null terminator). pszPattern may be NULL only when cchLen == 0.
  • eScope: WILD_CARD_SCOPE::SCOPE_DEFAULT or WILD_CARD_SCOPE::SCOPE_PATH_SEGMENT.
  • rContext: Caller payload copied into the pattern entry.
_IRQL_requires_max_(APC_LEVEL)
NTSTATUS Compile() noexcept;
  • Compiles all staged patterns into a prefix-deduplicated, Radix-compressed Trie NFA (applying anchored / leading-* partitioning and leading-? stripping where applicable) and populates all SWAR acceleration tables. Returns STATUS_SUCCESS on completion or STATUS_INSUFFICIENT_RESOURCES if pool allocation fails or the deduplicated state count exceeds MAX_INSTRUCTIONS (262,144 states).
_IRQL_requires_max_(DISPATCH_LEVEL)
BOOLEAN MatchFirst(_In_reads_opt_(cchLen) const TChar* __restrict pszText,
                   _In_                   size_t                  cchLen,
                   _Out_opt_              TContext* __restrict    pOutContext) const noexcept;
  • Evaluates pszText against all compiled patterns simultaneously and returns TRUE upon resolving a match (populating *pOutContext if non-NULL), or FALSE if no pattern matches. Security policy warning: MatchFirst() does not implement global registration-order or security-priority resolution; terminal unrestricted * rules may preempt more specific matches—use MatchAll() when matching rules can have conflicting actions. Supports IRQL <= DISPATCH_LEVEL for CHAR, case-sensitive WCHAR, and ASCII-only ($\le \text{0x7F}$) case-insensitive WCHAR when the instance and caller buffers are resident/non-paged; non-ASCII case-insensitive WCHAR matching requires PASSIVE_LEVEL (and paged buffers require IRQL < DISPATCH_LEVEL).
_IRQL_requires_max_(DISPATCH_LEVEL)
BOOLEAN MatchAll(_In_reads_opt_(cchLen)         const TChar* __restrict pszText,
                 _In_                           size_t                  cchLen,
                 _Out_writes_opt_(ulMaxMatches) TContext* __restrict    pOutContexts,
                 _In_                           ULONG                   ulMaxMatches,
                 _Out_opt_                      ULONG* __restrict       pulMatchCount) const noexcept;
  • Evaluates pszText to end-of-input against all compiled patterns without mid-string early exit, writing up to ulMaxMatches matching contexts into pOutContexts and storing the total match count in *pulMatchCount (if non-NULL). Returns TRUE if at least one pattern matched. Shares the same IRQL and memory-residency requirements as MatchFirst().
_IRQL_requires_max_(DISPATCH_LEVEL)
VOID Clear() noexcept;
  • Releases all staged pattern strings and compiled NFA tables, resetting the instance to a clean empty state without requiring destruction.

Example Implementation

#include <ntddk.h>
#include "KmWildcardNfa.h"

// 1. Define a trivially copyable payload to associate with patterns
enum class RuleAction : ULONG
{
    Allow = 0,
    Block = 1,
    Audit = 2
};

struct RuleContext
{
    ULONG      RuleId;
    RuleAction Action;
};

// Main execution routine (must be called at IRQL == PASSIVE_LEVEL for non-ASCII CI WCHAR matching)
_IRQL_requires_(PASSIVE_LEVEL)
NTSTATUS RunWildcardNfaExample()
{
    PAGED_CODE();

    // 2. Initialize the WCHAR NFA engine in case-insensitive mode (TRUE)
    KmWildcardNfaW<RuleContext> nfa(TRUE);

    // 3. Register Patterns
    // Block all '.tmp' files inside a specific directory without crossing '\' boundaries.
    static constexpr WCHAR kRule1[] = L"\\Device\\HarddiskVolume1\\Temp\\*.tmp";
    RuleContext rule1 = { 1001, RuleAction::Block };
    NTSTATUS status = nfa.AddPattern(kRule1,
                                     RTL_NUMBER_OF(kRule1) - 1,
                                     KmWildcardNfaW<RuleContext>::SCOPE_PATH_SEGMENT,
                                     rule1);
    if (!NT_SUCCESS(status))
    {
        return status;
    }

    // Match sensitive '.dat' files across arbitrary subdirectory depths.
    static constexpr WCHAR kRule2[] = L"\\Device\\*\\Confidential\\*.dat";
    RuleContext rule2 = { 1002, RuleAction::Block };
    status = nfa.AddPattern(kRule2,
                            RTL_NUMBER_OF(kRule2) - 1,
                            KmWildcardNfaW<RuleContext>::SCOPE_DEFAULT,
                            rule2);
    if (!NT_SUCCESS(status))
    {
        return status;
    }

    // Broad volume-level audit rule ending in SCOPE_DEFAULT '*' (permanent-accept state).
    static constexpr WCHAR kRule3[] = L"\\Device\\HarddiskVolume1\\*";
    RuleContext rule3 = { 1003, RuleAction::Audit };
    status = nfa.AddPattern(kRule3,
                            RTL_NUMBER_OF(kRule3) - 1,
                            KmWildcardNfaW<RuleContext>::SCOPE_DEFAULT,
                            rule3);
    if (!NT_SUCCESS(status))
    {
        return status;
    }

    // 4. Compile all staged patterns into the bit-parallel NFA
    status = nfa.Compile();
    if (!NT_SUCCESS(status))
    {
        return status;
    }

    // 5. Evaluate Input Text (Executed at PASSIVE_LEVEL here due to case-insensitive WCHAR;
    // case-sensitive WCHAR, ASCII-only WCHAR, and CHAR also support IRQL <= DISPATCH_LEVEL
    // when target and output buffers are non-paged).
    // Note: For hot-reloading rules in production, build and Compile() a new
    // KmWildcardNfaW instance out-of-band, atomically swap the active pointer
    // via InterlockedExchangePointer, and retire the old instance after readers
    // drain (e.g., via EX_RUNDOWN_REF or KmSharedPtr: https://github.com/adanil-code/KmSharedPtr).
    static constexpr WCHAR kTargetPath[] = L"\\Device\\HarddiskVolume1\\Temp\\cache.tmp";
    constexpr size_t targetLen = RTL_NUMBER_OF(kTargetPath) - 1;

    // MatchFirst triggers immediate mid-string early exit once kRule3's permanent-accept '*'
    // state activates after "\Device\HarddiskVolume1\", returning RuleId 1003 (Audit).
    RuleContext matchedContext = { 0 };
    if (nfa.MatchFirst(kTargetPath, targetLen, &matchedContext))
    {
        DbgPrint("MatchFirst resolved Rule ID: %lu (Action: %lu)\n",
                 matchedContext.RuleId,
                 static_cast<ULONG>(matchedContext.Action));
    }

    // MatchAll evaluates to end-of-input without permanent-accept early termination,
    // collecting both kRule1 (1001, Block) and kRule3 (1003, Audit) for policy resolution.
    RuleContext allMatches[8] = { 0 };
    ULONG       matchCount    = 0;

    if (nfa.MatchAll(kTargetPath,
                     targetLen,
                     allMatches,
                     static_cast<ULONG>(RTL_NUMBER_OF(allMatches)),
                     &matchCount))
    {
        const ULONG collectedCount = (matchCount < static_cast<ULONG>(RTL_NUMBER_OF(allMatches)))
            ? matchCount
            : static_cast<ULONG>(RTL_NUMBER_OF(allMatches));

        for (ULONG i = 0; i < collectedCount; i++)
        {
            DbgPrint("MatchAll resolved Rule ID: %lu (Action: %lu)\n",
                     allMatches[i].RuleId,
                     static_cast<ULONG>(allMatches[i].Action));
        }
    }

    // 6. Cleanup
    nfa.Clear();
    return STATUS_SUCCESS;
}

Benchmarks & Scaling Performance

All functional correctness tests (135 tests) and performance benchmark tiers (78 tiers: 39 WCHAR + 39 CHAR) were executed on x64 Windows 11 using the unified C++20 test suite (TestKmWildcardNfa.h) included in the repository.

To streamline development and debugging, the project supports compiling and executing the exact kernel NFA header in both native kernel mode and user mode. Using lightweight WDK API stubs (ntddk.h), developers can step through state transitions, verify SWAR bitmasks, and run the full correctness suite in user space before deploying the native .sys test driver for bare-metal kernel telemetry.

Test Methodology & Benchmark Architecture

The test harness (TestKmWildcardNfa.h) isolates execution and measures physical ingestion bandwidth using the following principles:

  • Kernel Logging & Persistent Telemetry Capture: When running as a kernel driver, the test suite streams real-time progress via DbgPrintEx(DPFLTR_IHVDRIVER_ID, ...) and flushes the complete benchmark report to \SystemRoot\Temp\KmWildcardNfaPerf.txt.
  • Correctness-First Execution Gating: Prior to running any performance tier, the harness executes 135 functional unit tests (68 WCHAR + 67 CHAR) covering exact literals, prefix/suffix/middle wildcards, SCOPE_DEFAULT vs. SCOPE_PATH_SEGMENT, | escape sequences, SWAR boundary characters, unaligned tails, Clear() lifecycle resets, anchored / leading-* partitioning (including ulMaxMatches saturation and (NULL, 0)), uniform and mixed leading-? stripping with permanent-accept cross-start filtering, 2-char SWAR digraph quad boundaries, 16-byte next-char LUT skipping, 3+ leading-* parallel SWAR filtering, dynamic Word-0 skip caching & ucDomWord0StarBit pruning, Radix compression alongside Op::Accept and sole ? segments, the 64-word Path A Word-63 boundary & Path B combined suite, and WCHAR non-ASCII case folding (U+00E4). Inside every performance loop, the worker thread asserts bRet == bExpectMatch on every single iteration, immediately setting g_lAbortTests and aborting the run if any discrepancy occurs.
  • Processor Topology & P-Core Affinity Pinning: To avoid thread migration and asymmetric E-core throttling, GetPCoreLogicalThreads() queries KeQueryLogicalProcessorRelationship(..., RelationProcessorCore, ...) to identify the highest EfficiencyClass physical Performance cores (excluding E-cores/LP-cores), unpacks logical SMT threads, pins each benchmark worker thread (StartThreads(pMgr, ulThreadCount, ...)) via KeSetSystemGroupAffinityThread, and elevates thread priority to time-critical levels (15). Single-thread tiers pin 1 worker thread; the multi-threaded Radix contention tier pins 4 worker threads.
  • Per-Thread Throughput Aggregation & OS Isolation: Worker threads synchronize on a shared start event and atomic lStartFlag spin barrier (YieldProcessor()), capturing high-resolution timestamps via KeQueryPerformanceCounter immediately before and after the inner evaluation loop. OS thread creation and teardown overhead are completely excluded from timing measurements.
  • Physical Stream Ingestion Bandwidth: Throughput reflects actual input string bytes ingested per second: $$\text{BytesPerOp} = \text{TargetTextLength} \times \text{sizeof(TChar)}$$ $$\text{Throughput (MB/s)} = \frac{\text{Ops/sec} \times \text{BytesPerOp}}{1{,}048{,}576}$$
  • Concurrency-Scaled Latency: Latency per operation is computed in picoseconds and scaled by active worker thread count: $$\text{Latency (ps)} = \frac{10^{12} \times \text{ThreadCount}}{\text{Ops/sec}}$$
  • Compiler Barrier Rigor: Inside the hot measurement loop, KmReadWriteBarrier() emits a compiler-only _ReadWriteBarrier() on both x64 and ARM64 so the compiler cannot hoist or elide repeated MatchFirst() / MatchAll() calls without injecting a hardware dmb ish fence on every iteration; inter-thread synchronization is handled explicitly via Acquire/Release primitives.

Performance Results

(Note: All benchmarks below were performed in native x64 Windows 11 kernel mode (TestKm driver). For positive Meaningful Prose (*allocation*%u*), the summary tables report MatchAll so full-buffer ingestion bandwidth (MB/s) is directly comparable; in the full test logs, MatchFirst() exits early upon matching *allocation* within the first ~120 characters and is reported as N/A (EarlyExit) for full-buffer MB/s (~7.4M–7.6M Ops/sec for WCHAR and ~8.7M–9.0M Ops/sec for CHAR on the 10 KB tier).)

Bare-Metal x64 Windows 11 (Intel Core i7-1165G7)

Environment: Native x64 Windows 11 kernel-mode driver execution on physical Intel Core i7-1165G7 (KmWildcardNfaPerf-1165G7.txt, 135 correctness tests passed, 78 performance tiers).

Workload Profile Pattern Count Target Text Length String Type Engine Mode Throughput Operations/sec Latency/Op
Realistic File Paths 1,000 56 Characters CHAR MatchFirst 239 MB/s 4.49 Million 223 ns
Realistic File Paths 1,000 56 Characters WCHAR MatchFirst 509 MB/s 4.77 Million 209 ns
Negative File Paths 1,000 59 Characters CHAR MatchFirst 1,134 MB/s 20.2 Million 50 ns
Negative File Paths 1,000 59 Characters WCHAR MatchFirst 2,041 MB/s 18.1 Million 55 ns
Mixed Anchored + * 1,020 56 Characters CHAR MatchFirst 235 MB/s 4.40 Million 227 ns
Mixed Anchored + * 1,020 56 Characters WCHAR MatchFirst 481 MB/s 4.51 Million 222 ns
Uniform Leading-? Paths 1,000 35 Characters CHAR MatchFirst 132 MB/s 3.97 Million 252 ns
Uniform Leading-? Paths 1,000 35 Characters WCHAR MatchFirst 289 MB/s 4.33 Million 231 ns
Mixed Anchored + ? (Neg) 1,008 59 Characters CHAR MatchFirst 572 MB/s 10.2 Million 98 ns
Mixed Anchored + ? (Neg) 1,008 59 Characters WCHAR MatchFirst 1,068 MB/s 9.50 Million 105 ns
Volume-? Radix Paths 10,000 56 Characters CHAR MatchFirst 216 MB/s 4.06 Million 246 ns
Volume-? Radix Paths 10,000 56 Characters WCHAR MatchFirst 454 MB/s 4.25 Million 235 ns
Exact Match (No Wildcards) 100 128 Characters CHAR MatchFirst 2,190 MB/s 17.9 Million 56 ns
Exact Match (No Wildcards) 100 128 Characters WCHAR MatchFirst 3,562 MB/s 14.6 Million 69 ns
Distinct Exact (1T / 4T) 1,000 128 Characters CHAR MatchFirst 1,984 / 4,579 MB/s 16.3M / 37.5M 62 / 107 ns
Distinct Exact (1T / 4T) 1,000 128 Characters WCHAR MatchFirst 2,978 / 6,950 MB/s 12.2M / 28.5M 82 / 140 ns
Exact Match Negative 100 256 Characters CHAR MatchFirst 12,538 MB/s 51.4 Million 19 ns
Exact Match Negative 100 256 Characters WCHAR MatchFirst 11,443 MB/s 23.4 Million 43 ns
Meaningful Prose (*xxx*) 100 10,240 Characters CHAR MatchAll 2,926 MB/s 299,703 3.3 µs
Meaningful Prose (*xxx*) 100 10,240 Characters WCHAR MatchAll 5,375 MB/s 275,217 3.6 µs
Meaningful Negative (*xxx*) 100 102,400 Characters CHAR MatchFirst 8,360 MB/s 85,610 11.7 µs
Meaningful Negative (*xxx*) 100 102,400 Characters WCHAR MatchFirst 7,386 MB/s 37,821 26.4 µs
Diverse Multi-Keyword (Neg) 32 (16 letters) 102,400 Characters CHAR MatchFirst 167 MB/s 1,711 584 µs
Diverse Multi-Keyword (Neg) 32 (16 letters) 102,400 Characters WCHAR MatchFirst 352 MB/s 1,803 555 µs
Heavy Pathological (*A%dB*) 1,000 102,400 Characters CHAR MatchAll 4,053 MB/s 41.5 K 24.1 µs
Heavy Pathological (*A%dB*) 1,000 102,400 Characters WCHAR MatchAll 5,228 MB/s 26.8 K 37.4 µs

Native Kernel Mode on x64 Windows 11 (Intel Core i7-8086K)

Environment: Native x64 Windows 11 kernel-mode driver execution on Intel Core i7-8086K (KmWildcardNfaPerf-8086K.txt, 135 correctness tests passed, 78 performance tiers).

Workload Profile Pattern Count Target Text Length String Type Engine Mode Throughput Operations/sec Latency/Op
Realistic File Paths 1,000 56 Characters CHAR MatchFirst 250 MB/s 4.69 Million 213 ns
Realistic File Paths 1,000 56 Characters WCHAR MatchFirst 511 MB/s 4.79 Million 209 ns
Negative File Paths 1,000 59 Characters CHAR MatchFirst 1,072 MB/s 19.1 Million 52 ns
Negative File Paths 1,000 59 Characters WCHAR MatchFirst 1,921 MB/s 17.1 Million 59 ns
Mixed Anchored + * 1,020 56 Characters CHAR MatchFirst 241 MB/s 4.53 Million 221 ns
Mixed Anchored + * 1,020 56 Characters WCHAR MatchFirst 483 MB/s 4.53 Million 221 ns
Uniform Leading-? Paths 1,000 35 Characters CHAR MatchFirst 138 MB/s 4.15 Million 241 ns
Uniform Leading-? Paths 1,000 35 Characters WCHAR MatchFirst 258 MB/s 3.87 Million 259 ns
Mixed Anchored + ? (Neg) 1,008 59 Characters CHAR MatchFirst 571 MB/s 10.2 Million 98 ns
Mixed Anchored + ? (Neg) 1,008 59 Characters WCHAR MatchFirst 1,025 MB/s 9.11 Million 110 ns
Volume-? Radix Paths 10,000 56 Characters CHAR MatchFirst 219 MB/s 4.10 Million 244 ns
Volume-? Radix Paths 10,000 56 Characters WCHAR MatchFirst 463 MB/s 4.34 Million 231 ns
Exact Match (No Wildcards) 100 128 Characters CHAR MatchFirst 2,063 MB/s 16.9 Million 59 ns
Exact Match (No Wildcards) 100 128 Characters WCHAR MatchFirst 3,088 MB/s 12.6 Million 79 ns
Distinct Exact (1T / 4T) 1,000 128 Characters CHAR MatchFirst 1,772 / 7,149 MB/s 14.5M / 58.6M 69 / 68 ns
Distinct Exact (1T / 4T) 1,000 128 Characters WCHAR MatchFirst 2,788 / 11,504 MB/s 11.4M / 47.1M 88 / 85 ns
Exact Match Negative 100 256 Characters CHAR MatchFirst 12,591 MB/s 51.6 Million 19 ns
Exact Match Negative 100 256 Characters WCHAR MatchFirst 12,474 MB/s 25.5 Million 39 ns
Meaningful Prose (*xxx*) 100 10,240 Characters CHAR MatchAll 2,895 MB/s 296,526 3.4 µs
Meaningful Prose (*xxx*) 100 10,240 Characters WCHAR MatchAll 4,997 MB/s 255,873 3.9 µs
Meaningful Negative (*xxx*) 100 102,400 Characters CHAR MatchFirst 8,772 MB/s 89,827 11.1 µs
Meaningful Negative (*xxx*) 100 102,400 Characters WCHAR MatchFirst 6,931 MB/s 35,487 28.2 µs
Diverse Multi-Keyword (Neg) 32 (16 letters) 102,400 Characters CHAR MatchFirst 163 MB/s 1,674 597 µs
Diverse Multi-Keyword (Neg) 32 (16 letters) 102,400 Characters WCHAR MatchFirst 349 MB/s 1,790 559 µs
Heavy Pathological (*A%dB*) 1,000 102,400 Characters CHAR MatchAll 4,541 MB/s 46.5 K 21.5 µs
Heavy Pathological (*A%dB*) 1,000 102,400 Characters WCHAR MatchAll 4,928 MB/s 25.2 K 39.6 µs

Scaling Characteristics Across Pattern Densities & Concurrency

Evaluation cost depends on input length $N$ and concurrently active state words rather than total rule count $K$:

  • Rule-Count Scaling: Per-call latency stays flat from 10 to 10,000 exact literals and from 1,000 to 10,000 realistic or Volume-? file paths once the automaton settles in Path A or Path B.
  • Radix Path A Retention & Multi-Core Scaling: Deterministic Radix compression collapses 1,000 distinct 128-character literals from ~58,000 raw states to ~3,100 states, keeping execution in Path A ($\le 4,096$ states) without shared mutable state. Across 4 threads (Distinct Exact (4T Contention)), the desktop i7-8086K scales ~4.0x–4.1x (11,504 MB/s WCHAR at 85 ns, 7,149 MB/s CHAR at 68 ns), while the TDP-limited mobile i7-1165G7 reaches ~2.3x (6,950 MB/s WCHAR, 4,579 MB/s CHAR) due to all-core turbo throttling.
  • Known Limits: Automata exceeding 4,096 states enter Path B, where concurrent threads sharing one instance contend on lScratchBufferInUse and fall back to per-call Non-Paged Pool allocations. On dense multi-letter leading-* sets (Diverse Multi-Keyword Negative, 16 common first letters matching ~43% of prose), frequent NFA wakeups cap scalar SWAR throughput at 349–352 MB/s (WCHAR) and 163–167 MB/s (CHAR).

Since WCHAR characters occupy 2 bytes while CHAR characters occupy 1 byte, each scaling graph below pairs physical byte throughput (MB/s) with character or operation evaluation rate (MChars/s or Ops/sec) to reflect both memory bus bandwidth and algorithmic transition efficiency across both string types on x64 Windows 11.

Pathological Multi-Wildcard Scaling Performance — comparison between CHAR and WCHAR engines evaluating saturated overlapping *A%dB* rules across 10 (512 chars), 100 (10,240 chars), and 1,000 (102,400 chars) tiers in MatchAll mode.

Intel Core i7-1165G7 Pathological Scaling Performance
Figure 1: Bare-Metal Kernel Mode on x64 Windows 11 (Intel Core i7-1165G7)
Intel Core i7-8086K Pathological Scaling Performance
Figure 2: Native Kernel Mode on x64 Windows 11 (Intel Core i7-8086K)

Unlike backtracking wildcard matchers that degrade on multi-wildcard expressions, KmWildcardNfa tracks active states in bit-parallel registers and accelerates *A%dB* with SingleExitWithNextLut (matching 'A' via bit-5 SWAR masking and rejecting non-digit 2nd characters in a 16-byte nibble LUT without waking the scalar VM). Scaling from 10 to 1,000 overlapping *A%dB* patterns across a 102,400-character payload increases sustained throughput—reaching 5,228 MB/s (2,741 MChars/s) for WCHAR and 4,053 MB/s (4,250 MChars/s) for CHAR on Intel Core i7-1165G7, and 4,928 MB/s (2,584 MChars/s) for WCHAR / 4,541 MB/s (4,762 MChars/s) for CHAR on Intel Core i7-8086K—as longer buffers amortize setup across extended 64-bit SWAR scanning runs.

Meaningful Prose Full-Buffer Scaling Performance — comparison between CHAR and WCHAR engines evaluating 100 multi-wildcard prose rules (*allocation*%u*) across 1 KB (1,024 chars), 10 KB (10,240 chars), and 100 KB (102,400 chars) buffers in MatchAll mode.

Intel Core i7-1165G7 Meaningful Prose Scaling Performance
Figure 3: Bare-Metal Kernel Mode on x64 Windows 11 (Intel Core i7-1165G7)
Intel Core i7-8086K Meaningful Prose Scaling Performance
Figure 4: Native Kernel Mode on x64 Windows 11 (Intel Core i7-8086K)

When scanning real-world prose in MatchAll mode, SingleExitWithNextChar scans for the 2-character digraph ('a', 'l') in overlapping 64-bit loads until the first "allocation" activates the downstream Word-0 Op::Star states; thereafter, WORD0_DYNAMIC_SKIP_CACHE and ucDomWord0StarBit prune redundant 'a' re-entry exits and skip across the remaining buffer. Sustained bandwidth rises from 1 KB to 100 KB, reaching 3,878–5,472 MB/s (2,033–2,869 MChars/s) for WCHAR and 1,996–3,019 MB/s (2,094–3,166 MChars/s) for CHAR on i7-1165G7, and 3,723–5,234 MB/s (1,952–2,744 MChars/s) for WCHAR / 2,055–3,013 MB/s (2,156–3,160 MChars/s) for CHAR on i7-8086K. On negative prose (*random*notfound*%u*), 2-character digraph skipping sustains 7,386 MB/s WCHAR / 8,360 MB/s CHAR on i7-1165G7 and 6,931 MB/s WCHAR / 8,772 MB/s CHAR on i7-8086K.

Exact String Search Scaling Performance — comparison between CHAR and WCHAR engines evaluating 128-character exact literal patterns across 10, 100, 1,000, and 10,000 pattern sets in MatchFirst mode.

Intel Core i7-1165G7 Exact String Scaling Performance
Figure 5: Bare-Metal Kernel Mode on x64 Windows 11 (Intel Core i7-1165G7)
Intel Core i7-8086K Exact String Scaling Performance
Figure 6: Native Kernel Mode on x64 Windows 11 (Intel Core i7-8086K)

For exact literal workloads, BuildPrefixTrie collapses shared prefixes and BuildLiteralRunsAndDescriptors vectorizes both the root prefix and Radix-compressed suffixes into 64-bit SWAR comparisons (VerifyLiteralRunSwar). From 10 to 10,000 registered rules, evaluation throughput remains invariant: 17.64M–17.94M Ops/sec (2,153–2,190 MB/s) for CHAR and 14.52M–14.59M Ops/sec (3,545–3,562 MB/s) for WCHAR on i7-1165G7, and 16.90M–16.96M Ops/sec (2,063–2,070 MB/s) for CHAR and 12.63M–12.66M Ops/sec (3,083–3,090 MB/s) for WCHAR on i7-8086K. On 256-character exact literals, longer SWAR runs amortize fixed WDK kernel mitigation overhead (/Qspectre and /GS), reaching 4,291–4,304 MB/s (WCHAR) / 3,243–3,301 MB/s (CHAR) on i7-1165G7 and 4,081–4,220 MB/s (WCHAR) / 3,142–3,148 MB/s (CHAR) on i7-8086K.

Kernel File Paths Scaling Performance — comparison between CHAR and WCHAR engines evaluating realistic kernel file path rules (e.g., \Device\HarddiskVolume2\Program Files\App%u\*\crypt.exe) across 10, 100, 1,000, and 10,000 pattern sets in MatchFirst mode.

Intel Core i7-1165G7 Kernel File Paths Scaling Performance
Figure 7: Bare-Metal Kernel Mode on x64 Windows 11 (Intel Core i7-1165G7)
Intel Core i7-8086K Kernel File Paths Scaling Performance
Figure 8: Native Kernel Mode on x64 Windows 11 (Intel Core i7-8086K)

Evaluating realistic kernel file paths exercises simultaneous prefix-Trie branching, deterministic Radix compression, and active interior * wildcards (\Device\HarddiskVolume2\Program Files\App%u\*\crypt.exe and \Users\*\AppData\...). Between 10 and 100 patterns, the compiled automaton fits within Path A's 16-word stack-resident bitset, sustaining 6.39M–6.41M Ops/sec (156 ns) for CHAR and 6.42M–6.44M Ops/sec (155–156 ns / 686–687 MB/s) for WCHAR on i7-1165G7 (and 6.77M–6.86M Ops/sec CHAR / 6.30M–6.39M Ops/sec WCHAR on i7-8086K). Scaling to 1,000 and 10,000 patterns transitions the engine into Path B's interleaved 3-level ulSuperMask hierarchy, stabilizing at 4.46M–4.49M Ops/sec (223–224 ns / 238–239 MB/s) for CHAR and 4.77M Ops/sec (209 ns / 509 MB/s) for WCHAR on i7-1165G7 (and 4.53M–4.69M Ops/sec CHAR / 4.71M–4.79M Ops/sec WCHAR on i7-8086K) with flat throughput from 1,000 to 10,000 rules. Similar flat scaling holds on Volume-? paths (\Device\HarddiskVolume?\...), which sustain 4.25M–4.27M Ops/sec (WCHAR) on i7-1165G7 and 4.34M–4.35M Ops/sec (WCHAR) on i7-8086K across 1,000 and 10,000 rules, as well as mixed anchored + 20 leading-* rules (4.51M–4.53M Ops/sec WCHAR MatchFirst on both CPUs).


Project Layout

The repository is structured to separate the standalone kernel NFA engine from the shared test suite and platform harnesses:

  • /KmWildcardNfa/: Core header-only kernel implementation.
    • KmWildcardNfa.h: Complete bit-parallel Thompson NFA compiler and SWAR virtual machine.
  • /Shared/:
    • TestKmWildcardNfa.h: Unified correctness (135 tests) and performance (78 tiers) test suite shared natively between kernel-mode and user-mode builds.
  • /TestUm/: User-mode matching engine test harness.
    • KmWildcardNfaUm.cpp: Compiles and executes KmWildcardNfa.h and TestKmWildcardNfa.h in user space for rapid iteration and debugging. Includes MSVC 2026 .slnx and .vcxproj files.
    • ntddk.h: Lightweight WDK API stubs intercepting kernel pool, IRQL, synchronization, and processor topology routines for user-mode execution.
  • /TestKm/: Native kernel-mode test driver.
    • KmWildcardNfaDrv.cpp & .inf: Deploys the unified test suite as a Windows kernel driver (WDM) for bare-metal performance validation, logging via DbgPrintEx and persisting results to \SystemRoot\Temp\KmWildcardNfaPerf.txt. Includes MSVC 2026 .slnx and .vcxproj files.

Building Instructions

The project targets C++20 and the Microsoft Visual Studio 2026 toolchain with the Windows Driver Kit (WDK):

  1. Open the .slnx solution file in /TestUm (for user-mode testing) or /TestKm (for native kernel-mode driver compilation).
  2. Select your target architecture (x64 or ARM64) and configuration (Release is recommended for accurate throughput and latency measurements).
  3. Ensure the Windows Driver Kit (WDK) Visual Studio extensions are installed when building /TestKm to generate the .sys driver binary.
  4. Build the solution (Ctrl+Shift+B).

Conclusion

KmWildcardNfa provides deterministic, single-pass multi-pattern wildcard matching for Windows kernel drivers without recursion, C++ heap allocation, or SSE/AVX state management. Its operating envelope is bounded by 262,144 compiled states per NFA_ENGINE_DATA engine, with stack-resident lock-free execution up to 4,096 states (Path A) and interleaved scratch-buffer execution above 4,096 states (Path B, falling back to per-call Non-Paged Pool allocation under concurrent contention).

For safe deployment, callers must pair MatchAll() with explicit policy precedence when rules carry conflicting actions, manage atomic pointer replacement and reader draining externally during rule reloads, and observe the IRQL contract (DISPATCH_LEVEL supported for CHAR, case-sensitive WCHAR, and ASCII-only $\le \text{0x7F}$ case-insensitive WCHAR on non-paged buffers; PASSIVE_LEVEL required for non-ASCII case-insensitive WCHAR matching and paged buffers).


License

This project is licensed under the Apache License, Version 2.0.

You may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations.

About

Header-only C++20 bit-parallel Thompson NFA for Windows kernel wildcard matching (WCHAR/CHAR). Evaluates thousands of rules in a single O(N) pass using pure 64-bit GPR SWAR (no SSE/AVX), stack-resident fast paths, path-segment scoping, and lock-free readers for minifilters and EDR drivers.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages