-
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/ExFreePoolWithTagdirectly), native path-segment scoping (SCOPE_PATH_SEGMENT), andDISPATCH_LEVELexecution forCHAR, case-sensitiveWCHAR, and ASCII-only ($\le \text{0x7F}$ ) case-insensitiveWCHAR. - User-Mode WDK Test Harness: Includes a correctness and benchmark suite compilable in user space for rapid debugging without VM deployment.
- Overview
- Architecture & Algorithms
- Quick Start API Overview
- Benchmarks & Scaling Performance
- Project Layout
- Building Instructions
- Conclusion
- License
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 KmWildcardNfa compiles wildcard patterns into a prefix-deduplicated state graph and evaluates all
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 (\).
-
Concurrent Immutable Readers with Caller-Managed RCU-Style Replacement: After
Compile()completes,MatchFirst()andMatchAll()areconstand 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., viaInterlockedExchangePointer) and reader lifetime management / reclamation (e.g., viaEX_RUNDOWN_REForKmSharedPtr) are caller responsibilities. -
No C++ Heap Allocation & Non-Recursive Execution: All internal buffers are allocated explicitly from Windows kernel pools (
ExAllocatePool2/ExFreePoolWithTag) with nooperator neworoperator delete. Matching is strictly iterative, avoiding kernel stack exhaustion regardless of input length$N$ or wildcard complexity. -
State & Pattern Capacity: Each compiled
NFA_ENGINE_DATAblock supports up to 262,144 deduplicated states (4,09664-bit state words), with up to 4,096 states (64state 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 requireIRQL <= APC_LEVEL. -
Clear(): Releases Non-Paged Pool buffers and supports execution up toIRQL <= DISPATCH_LEVEL. -
MatchFirst()&MatchAll()(CHAR): Both case-sensitive and case-insensitive 8-bitCHARmatching operate on non-paged state tables and branchless ASCII arithmetic, supportingIRQL <= DISPATCH_LEVELwhen theKmWildcardNfainstance and caller buffers are resident/non-paged. -
MatchFirst()&MatchAll()(WCHAR— Case-Sensitive): SupportsIRQL <= DISPATCH_LEVELacross the full 16-bit Unicode range (0x0000..0xFFFF) when the instance and caller buffers are resident/non-paged; evaluating pagedWCHARbuffers requiresIRQL < DISPATCH_LEVEL. -
MatchFirst()&MatchAll()(WCHAR— Case-Insensitive): RequiresIRQL == PASSIVE_LEVELfor non-ASCII Unicode code points ($\ge \text{0x80}$ ), becauseRtlUpcaseUnicodeCharaccesses paged system NLS tables. ASCII code points ($\le \text{0x7F}$ ) are pre-folded into non-paged tables and SWAR masks; if invoked atDISPATCH_LEVELin release builds, non-ASCII code points degrade to direct comparison to avoid page faults.
-
KmWildcardNfa separates pattern preprocessing from runtime evaluation through three stages:
-
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). WhenbCaseInsensitiveis enabled, pattern characters are pre-normalized to uppercase during insertion via 64-bit SWAR (SwarUpcaseBuffer). -
Compilation (
Compile&CompilePatternSubset):-
Anchored / Leading-
*Partitioning: When both anchored and unescaped leading-*patterns are present,Compile()allocates a trivialNFA_ENGINE_DATAsub-engine (m_pStarEngine) from Non-Paged Pool viaExAllocatePool2and 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 singleOp::Starstates, resolving|escapes, appending terminalOp::Acceptstates 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_QUADviaFindSharedRootLiteralPrefix), 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-byteNFA_INSTRUCTION, spills multi-word closures toEXTRA_TARGET_WORD, builds 128-entry ASCII compatibility masks (WORD_SWAR_FILTER) with pre-folded lowercase slots ('a'..'z'), computes nearest post-dominating Word-0SCOPE_DEFAULTOp::Starbits (ucDomWord0StarBit) in reverse topological order, and consolidatesInitialStates,AcceptStates, andInitialWordsMaskinto one Non-Paged Pool allocation. -
Literal-Run Descriptors & Root
*Configuration (BuildLiteralRunsAndDescriptors&ConfigureStarSteadyStateSkip): Allocates exact-sizedpszLiteralRunsand front-loaded 24-byteLITERAL_RUN_DESCtables (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, orSwarFilter).m_bCompiledis published viaWriteBooleanReleaseso all runtime tables are visible on ARM64 and x64 before readers observeTRUE.
-
Anchored / Leading-
-
Execution (
ExecuteVm<bCaseInsensitive>): Dispatches at compile time onbCaseInsensitive, 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.
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 (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
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_BitScanForward64andx &= (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.
- Dispatches to a 16-word stack frame (
-
Path B (
$> 64$ State Words / up to$262,144$ States — 3-LevelulSuperMaskHierarchy):-
Normal Execution Path (Uncontended): Tracks up to
$64 \times 64 = 4,096$ state words via a top-level 64-bitulSuperMaskregister.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 viaInterlockedCompareExchangeAcquire(&pEngine->lScratchBufferInUse, 1, 0) == 0, sparsely initializes active words fromulInitialSuperMask, and zeroes dirty words in a single structured cleanup epilogue before releasing the latch withWriteRelease(&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), returningFALSEif pool exhaustion occurs.
-
Normal Execution Path (Uncontended): Tracks up to
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): ChecksIsAsciiSwar((ullQuad & SWAR_ASCII_HIGH_MASK) == 0) and folds all ASCII lanes branchlessly viaullGeA & ~ullGtZandullQuad ^ (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.
-
2-Character Digraph (
-
Stack-Cached Dynamic Word-0
*Skipping,ucDomWord0StarBitPruning & 1-Branch ASCII Quad Filter (TrySkipWord0SteadyStateSwar/TryProbeQuadsSwar): When Word 0 is the sole active state word and is self-sustained bySCOPE_DEFAULTOp::Starstates (ullWord0DefaultStarMask),ClassifyWord0DynamicSteadyStatecaches 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-0SCOPE_DEFAULTOp::Star(ucDomWord0StarBit) are pruned; absorbing states jump straight tocchLen, 1–2 literal exits useDualBroadcast, and 3+ literal orOp::Anyexits useTryProbeQuadsSwar, which OR-combines all 4 or 8ullAsciiMatchMaskloads per ASCII quad into a single miss branch. -
Permanent Accepting State Early-Exit (
CheckWord0PermanentAccept): PrecomputesullWord0PermanentAcceptMaskfor terminal Word-0SCOPE_DEFAULTOp::Staraccepting states (pre-filtered byFilterPermAcceptMaskForStartwhen leading-?stripping is active) and guards the Word-0 load onullPermAcceptMask != 0. -
Radix-Compressed & Unbranched Literal-Run Verification (
VerifyLiteralRunSwar/TryAdvanceLiteralRunSwar): Verifies shared root literal prefixes and unbranched mid-TrieOp::Literalchains 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-byteLITERAL_RUN_DESC. -
64-Way Bit-Parallel State Filtering (
FilterActiveStatesSwar): Pre-folds lowercase'a'..'z'slots intoWORD_SWAR_FILTER::ullAsciiMatchMask[128]at compile time so all 64 states in a word are filtered with a single bitwiseANDand zero per-character ASCII upcasing instructions.
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: PacksullTargetBits(8B),ulExtraOffset(4B, bit 31 =NFA_INST_LITERAL_RUN_FLAG),usTargetWord(2B), andusExtraCount(2B)—4 instructions per 64-byte cache line. - Compact 24-Byte
LITERAL_RUN_DESC: Inlines the chain end state's outgoingNFA_INSTRUCTIONalongsideulRunOffsetandulRunLength, avoidingpStateMetadataandpInstructions[endState]lookups on literal-run fast-forwards. - Compact 8-Byte
NFA_STATE_METADATA: StoresulFirstMatchIdx(4B),chLiteral(1–2B),eOp(1B), anducDomWord0StarBit(1B)—8 entries per 64-byte cache line. - Inlined Context Links (
MATCH_LINK_NODE): InlinesTContextdirectly into the accepting state's singly-linked match list, eliminating secondary pointer chases during match harvesting.
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.
*(Zero or More Characters): Matches zero or more characters within the configuredWILD_CARD_SCOPE. Adjacent asterisks (e.g.,**) collapse into a single self-loopingOp::Starstate duringBuildPrefixTrie().?(Single Character): Matches any single character within the configuredWILD_CARD_SCOPE.
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.
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\*.tmpwill not match nested subdirectories).
Security policy warning:
MatchFirst()does not implement global registration-order or security-priority resolution. Terminal unrestricted*rules may preempt more specific matches. UseMatchAll()when matching rules can have conflicting actions.
When multiple registered patterns match an input string, MatchFirst() and MatchAll() follow these resolution rules:
- 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:- Anchored start-0 patterns (
m_PrimaryEngineat offset0). - Stripped leading-
?patterns (m_PrimaryEngineat ascending start offsetskin1..63). - Partitioned leading-
*patterns (m_pStarEngineat offset0).
- Anchored start-0 patterns (
- In mixed sets, anchored patterns therefore resolve before leading-
*patterns inMatchFirst()and appear before leading-*patterns inMatchAll(). Identical patterns always reside in the same engine and start offset, preserving their FIFO order.
- When mixed anchored and leading-
- Permanent-Accept Mid-String Early Termination (
MatchFirst()Only):- Any pattern ending in an unrestricted
*(Op::StarwithSCOPE_DEFAULT) whose compiled state resides in Word 0 (ulStateIdx < 64) is recorded inullWord0PermanentAcceptMask(pre-filtered byFilterPermAcceptMaskForStartfor the active start offset when leading-?stripping is enabled). - During
MatchFirst(), activating any valid bit inullPermAcceptMaskterminates immediately viaCheckWord0PermanentAccept()without scanning the remainder of the string. Within a pass, a broadSCOPE_DEFAULTrule ending in*(e.g.,\Device\HarddiskVolume1\*with actionAUDIT) preempts a more specific rule (e.g.,\Device\HarddiskVolume1\Temp\*.tmpwith actionBLOCK) 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 FIFOMATCH_LINK_NODEchain.
- Any pattern ending in an unrestricted
- End-of-Input Resolution & FIFO Ordering (
MatchFirst()andMatchAll()):- When no Word-0 permanent-accepting state triggers early exit (always true in
MatchAll(), and true inMatchFirst()when only non-permanent states are active), evaluation proceeds tocchOffset == cchLen. - At end-of-input,
HarvestWordMatches()scans surviving accepting state bits in ascending BFSulStateIdxorder and walks each accepting state'sMATCH_LINK_NODElist in FIFO registration order (filtered bypMatchStartReqswhen 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 BFSulStateIdx.
- When no Word-0 permanent-accepting state triggers early exit (always true in
- 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.,BLOCKvs.ALLOWoverrides) so your driver can apply explicit policy priority over all matched contexts.
- Use
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 viastatic_assert(__is_trivially_copyable(TContext))andstatic_assert(alignof(TContext) <= MEMORY_ALLOCATION_ALIGNMENT).TChar: Character type (WCHARfor 16-bit Unicode orCHARfor 8-bit ANSI/ASCII). Enforced at compile time viastatic_assert(sizeof(TChar) == 1 || sizeof(TChar) == 2). Convenience type aliasesKmWildcardNfaW<TContext>andKmWildcardNfaA<TContext>are provided.
explicit KmWildcardNfa(_In_ BOOLEAN bCaseInsensitive = TRUE) noexcept;- Constructs an empty NFA instance. When
bCaseInsensitiveisTRUE(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
TContextpayload 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 inCompile()). Invalidates any previously compiled runtime tables if called afterCompile(). ReturnsSTATUS_INVALID_PARAMETERon invalid arguments orSTATUS_INSUFFICIENT_RESOURCESon capacity overflow or allocation failure. -
pszPattern/cchLen: Pointer to the pattern buffer and its character count (excluding any null terminator).pszPatternmay beNULLonly whencchLen == 0. -
eScope:WILD_CARD_SCOPE::SCOPE_DEFAULTorWILD_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. ReturnsSTATUS_SUCCESSon completion orSTATUS_INSUFFICIENT_RESOURCESif pool allocation fails or the deduplicated state count exceedsMAX_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
pszTextagainst all compiled patterns simultaneously and returnsTRUEupon resolving a match (populating*pOutContextif non-NULL), orFALSEif 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—useMatchAll()when matching rules can have conflicting actions. SupportsIRQL <= DISPATCH_LEVELforCHAR, case-sensitiveWCHAR, and ASCII-only ($\le \text{0x7F}$ ) case-insensitiveWCHARwhen the instance and caller buffers are resident/non-paged; non-ASCII case-insensitiveWCHARmatching requiresPASSIVE_LEVEL(and paged buffers requireIRQL < 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
pszTextto end-of-input against all compiled patterns without mid-string early exit, writing up toulMaxMatchesmatching contexts intopOutContextsand storing the total match count in*pulMatchCount(if non-NULL). ReturnsTRUEif at least one pattern matched. Shares the same IRQL and memory-residency requirements asMatchFirst().
_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.
#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;
}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.
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+ 67CHAR) covering exact literals, prefix/suffix/middle wildcards,SCOPE_DEFAULTvs.SCOPE_PATH_SEGMENT,|escape sequences, SWAR boundary characters, unaligned tails,Clear()lifecycle resets, anchored / leading-*partitioning (includingulMaxMatchessaturation 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 &ucDomWord0StarBitpruning, Radix compression alongsideOp::Acceptand sole?segments, the 64-word Path A Word-63 boundary & Path B combined suite, andWCHARnon-ASCII case folding (U+00E4). Inside every performance loop, the worker thread assertsbRet == bExpectMatchon every single iteration, immediately settingg_lAbortTestsand aborting the run if any discrepancy occurs. -
Processor Topology & P-Core Affinity Pinning: To avoid thread migration and asymmetric E-core throttling,
GetPCoreLogicalThreads()queriesKeQueryLogicalProcessorRelationship(..., RelationProcessorCore, ...)to identify the highestEfficiencyClassphysical Performance cores (excluding E-cores/LP-cores), unpacks logical SMT threads, pins each benchmark worker thread (StartThreads(pMgr, ulThreadCount, ...)) viaKeSetSystemGroupAffinityThread, 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
lStartFlagspin barrier (YieldProcessor()), capturing high-resolution timestamps viaKeQueryPerformanceCounterimmediately 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 repeatedMatchFirst()/MatchAll()calls without injecting a hardwaredmb ishfence on every iteration; inter-thread synchronization is handled explicitly via Acquire/Release primitives.
(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).)
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 |
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 |
Evaluation cost depends on input length
-
Rule-Count Scaling: Per-call latency stays flat from
10to10,000exact literals and from1,000to10,000realistic orVolume-?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/sWCHARat85 ns,7,149 MB/sCHARat68 ns), while the TDP-limited mobile i7-1165G7 reaches ~2.3x (6,950 MB/sWCHAR,4,579 MB/sCHAR) due to all-core turbo throttling. -
Known Limits: Automata exceeding 4,096 states enter Path B, where concurrent threads sharing one instance contend on
lScratchBufferInUseand 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 at349–352 MB/s(WCHAR) and163–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
CHARandWCHARengines evaluating saturated overlapping*A%dB*rules across10(512 chars),100(10,240 chars), and1,000(102,400 chars) tiers inMatchAllmode.
Figure 1: Bare-Metal Kernel Mode on x64 Windows 11 (Intel Core i7-1165G7) |
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
CHARandWCHARengines evaluating 100 multi-wildcard prose rules (*allocation*%u*) across1 KB(1,024 chars),10 KB(10,240 chars), and100 KB(102,400 chars) buffers inMatchAllmode.
Figure 3: Bare-Metal Kernel Mode on x64 Windows 11 (Intel Core i7-1165G7) |
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
CHARandWCHARengines evaluating 128-character exact literal patterns across 10, 100, 1,000, and 10,000 pattern sets inMatchFirstmode.
Figure 5: Bare-Metal Kernel Mode on x64 Windows 11 (Intel Core i7-1165G7) |
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
CHARandWCHARengines 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 inMatchFirstmode.
Figure 7: Bare-Metal Kernel Mode on x64 Windows 11 (Intel Core i7-1165G7) |
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).
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 executesKmWildcardNfa.handTestKmWildcardNfa.hin user space for rapid iteration and debugging. Includes MSVC 2026.slnxand.vcxprojfiles.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 viaDbgPrintExand persisting results to\SystemRoot\Temp\KmWildcardNfaPerf.txt. Includes MSVC 2026.slnxand.vcxprojfiles.
The project targets C++20 and the Microsoft Visual Studio 2026 toolchain with the Windows Driver Kit (WDK):
- Open the
.slnxsolution file in/TestUm(for user-mode testing) or/TestKm(for native kernel-mode driver compilation). - Select your target architecture (
x64orARM64) and configuration (Releaseis recommended for accurate throughput and latency measurements). - Ensure the Windows Driver Kit (WDK) Visual Studio extensions are installed when building
/TestKmto generate the.sysdriver binary. - Build the solution (
Ctrl+Shift+B).
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 WCHAR on non-paged buffers; PASSIVE_LEVEL required for non-ASCII case-insensitive WCHAR matching and paged buffers).
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.







