vmi-utils 0.7.0

Utilities for VMI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
//! Implementation of the [`define_modules!`] macro.
//!
//! The macro consumes a user-facing DSL describing a module enum and
//! optional resolver / cache wrapper structs, and expands to:
//!
//! - The enum with fixed derives (`Debug, Clone, Copy, PartialEq, Eq, Hash`).
//! - A blanket `impl<__Os: VmiOs + 'static> ReactorModule<__Os>` block
//!   with `METADATA`, `KERNEL_SLOT`, `slot`.
//! - If `#[resolver]` is present, a resolver wrapper parameterized over
//!   `Os` with `with_kernel`, `with_module`, `into_events`.
//! - If `#[resolver]` and `#[cache]` are both present, a symbol cache
//!   struct plus a `resolve` method on the resolver, available only when
//!   `Os = WindowsOs<Driver>`.
//!
//! [`define_modules!`]: super::super::define_modules

/// Maps a single token tree to `()`. Used to count repetitions at compile time
/// by emitting `<[()]>::len(&[ () , () , ... ])`.
#[doc(hidden)]
#[macro_export]
macro_rules! _private_modules_unit {
    ($_t:tt) => {
        ()
    };
}

/// Defines a [`ReactorModule`] enum for the modules monitored by a [`Reactor`].
///
/// # Usage
///
/// ```no_run
/// # use vmi_core::{VmiError, driver::VmiRead};
/// # use vmi_os_windows::{ArchAdapter, WindowsOs, WindowsProcess};
/// # use vmi_utils::reactor::define_modules;
/// #
/// # fn in_lsass<Driver>(_p: &WindowsProcess<Driver>) -> Result<bool, VmiError>
/// # where
/// #     Driver: VmiRead,
/// #     Driver::Architecture: ArchAdapter<Driver>,
/// # { Ok(true) }
/// #
/// define_modules! {
///     /// Modules monitored by the reactor.
///     #[os(<Driver: VmiRead> WindowsOs<Driver> where Driver::Architecture: ArchAdapter<Driver>)]
///     pub enum Module {
///         // Kernel-mode driver. `mode(kernel)` is the default.
///         #[module(name = "netio.sys")]
///         NetioSys,
///
///         // User-mode DLL with no process filter. The resolver picks
///         // the first process that maps the image.
///         #[module(name = "ntdll.dll", mode(user))]
///         NtDll,
///
///         // User-mode DLL pinned to a process by exact image name
///         // (case-insensitive).
///         #[module(name = "ncrypt.dll", mode(user, process = "lsass.exe"))]
///         NcryptInLsass,
///
///         // User-mode DLL pinned by a caller-supplied predicate.
///         #[module(name = "user32.dll", mode(user, process = in_lsass))]
///         User32InLsass,
///
///         // `optional` lets the module be absent from the guest.
///         // The corresponding events resolve to `Ok(None)` and are
///         // dropped from the event vector.
///         #[module(name = "msmpeng.exe", mode(user), optional)]
///         Defender,
///     }
///
///     // Emit `ModuleResolver` - a typed resolver wrapper.
///     #[resolver]
///     pub struct ModuleResolver;
///
///     // Emit `SymbolCache` - a profile cache backing `.resolve(...)`.
///     // Requires `#[resolver]`. The two markers may appear in either
///     // order.
///     #[cache]
///     pub struct SymbolCache;
/// }
/// ```
///
/// # Attributes
///
/// - `#[os(...)]` on the enum: anchors the generated `ReactorModule`
///   impl to a specific OS family. Two shapes are accepted:
///
///   - `#[os(<G...> $os_ty where $bounds)]` - generics and where-bounds
///     spelled by the caller and emitted verbatim, e.g.
///     `#[os(<Driver: VmiRead> WindowsOs<Driver> where Driver::Architecture: ArchAdapter<Driver>)]`.
///   - `#[os($os_ty)]` - no generic parameters, the impl binds to a
///     concrete type or alias, e.g. `#[os(WindowsOs<VmiXenDriver<Amd64>>)]`.
///
///   Omitting `#[os(...)]` emits a blanket
///   `impl<Os: VmiOs + 'static> ReactorModule<Os>` covering every OS
///   family. Predicates passed to `mode(user, process = ...)` must
///   then be `Os`-generic.
///
/// - `#[module(...)]` on each variant: required. Arguments are
///   position-independent.
///
///   - `name = "..."` (required): image filename, e.g. `"ntdll.dll"`.
///   - `mode(kernel)` (default): kernel address space.
///   - `mode(user)`: user-mode, no process filter.
///   - `mode(user, process = "literal")`: user-mode pinned by exact,
///     case-insensitive image name.
///   - `mode(user, process = path)`: user-mode pinned by a predicate.
///     `path` can be a bare ident or a fully qualified path. Signature:
///     `fn(&Os::Process<'_>) -> Result<bool, VmiError>`.
///   - `optional`: the module is allowed to be absent from the guest.
///
/// - `#[resolver] $vis struct $Name;` (optional): emit the resolver
///   wrapper named `$Name`. Rustdoc and other attributes on the marker
///   struct are not permitted.
///
/// - `#[cache] $vis struct $Name;` (optional): emit a profile cache
///   named `$Name`. Requires `#[resolver]`. Backs the resolver's
///   Windows-anchored `.resolve(...)`.
///
/// # Generated code
///
/// - The enum, with `#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]`.
/// - One `impl ReactorModule<Os> for $Enum` block, blanket or anchored
///   depending on `#[os(...)]`.
/// - If `#[resolver]` is present: a `$Resolver<'a, Os>` struct with
///   `default()`, `with_kernel`, `with_module`, `with_module_in_process`,
///   and `into_events()`.
/// - If `#[resolver]` and `#[cache]` are both present: a `$Cache` struct
///   (an array of profiles) and a
///   `.resolve(session, isr, &mut cache) -> Result<Self, VmiError>`.
///
/// [`ReactorModule`]: super::super::ReactorModule
/// [`Reactor`]: super::super::Reactor
#[doc(hidden)]
#[macro_export]
macro_rules! _private_define_modules {
    //
    // Public entry.
    //
    // Captures the enum and its trailing resolver / cache markers as tt streams
    // so the optional `#[os(...)]` attribute (which carries a non-literal type
    // and so cannot match `:meta`) can be peeled by `@walk_enum_attrs` before
    // variant processing begins.
    //

    (
        $(#[$($enum_attr:tt)*])*
        $vis:vis enum $name:ident {
            $(
                $(#[$($vattr:tt)*])*
                $variant:ident
            ),* $(,)?
        }
        $($trailing:tt)*
    ) => {
        $crate::_private_define_modules! {
            @walk_enum_attrs
            attrs: { $( #[$($enum_attr)*] )* }
            pass:  { }
            os:    { }
            tail:  {
                vis: [$vis]
                name: [$name]
                trailing: [$($trailing)*]
                variants: [ $( { [$(#[$($vattr)*])*] $variant } )* ]
            }
        }
    };

    //
    // @walk_enum_attrs - peel a single `#[os(...)]` and pass everything else
    // through unchanged. A second `#[os(...)]` is a compile_error!.
    //

    (
        @walk_enum_attrs
        attrs: { #[os($($args:tt)*)] $($more:tt)* }
        pass:  $pass:tt
        os:    { }
        tail:  $tail:tt
    ) => {
        $crate::_private_define_modules! {
            @walk_enum_attrs
            attrs: { $($more)* }
            pass:  $pass
            os:    { $($args)* }
            tail:  $tail
        }
    };

    (
        @walk_enum_attrs
        attrs: { #[os($($args:tt)*)] $($more:tt)* }
        pass:  $pass:tt
        os:    { $($_old:tt)+ }
        tail:  $tail:tt
    ) => {
        compile_error!("`#[os(...)]` may only appear once on the enum");
    };

    (
        @walk_enum_attrs
        attrs: { #[$($other:tt)*] $($more:tt)* }
        pass:  { $($pass:tt)* }
        os:    $os:tt
        tail:  $tail:tt
    ) => {
        $crate::_private_define_modules! {
            @walk_enum_attrs
            attrs: { $($more)* }
            pass:  { $($pass)* #[$($other)*] }
            os:    $os
            tail:  $tail
        }
    };

    (
        @walk_enum_attrs
        attrs: { }
        pass:  { $($pass:tt)* }
        os:    $os:tt
        tail:  {
            vis: [$vis:vis]
            name: [$name:ident]
            trailing: [$($trailing:tt)*]
            variants: [ $({ [$($vattr:tt)*] $variant:ident })* ]
        }
    ) => {
        $crate::_private_define_modules! {
            @process_variants
            ctx { [$($pass)*] [$vis] [$name] [$($trailing)*] [$os] }
            input { $( { [$($vattr)*] $variant } )* }
            output { }
        }
    };

    //
    // @process_variants - base case: no more input variants.
    //

    (
        @process_variants
        ctx $ctx:tt
        input { }
        output $output:tt
    ) => {
        $crate::_private_define_modules! {
            @finalize
            ctx $ctx
            output $output
        }
    };

    //
    // @process_variants - recursive: pull the next variant and hand its
    // attributes to the shared splitter.
    //

    (
        @process_variants
        ctx $ctx:tt
        input { { [ $($attrs:tt)* ] $variant:ident } $($rest:tt)* }
        output $output:tt
    ) => {
        // `found:` starts empty - the splitter fills it in when it
        // encounters `#[module(...)]`. An empty `found:` after the walk
        // therefore means "no module attribute was supplied."
        $crate::_private_split_reactor_attrs! {
            peel: module
            state: {
                ctx $ctx
                input { $($rest)* }
                output $output
                variant { $variant }
            }
            pass: { }
            found: { }
            attrs: { $($attrs)* }
        }
    };

    //
    // @after_split - empty `found:` means no `#[module(...)]` was supplied.
    // This arm must precede the catch-all `found: { $($margs:tt)* }` arm
    // below so the empty case is preferred.
    //

    (
        @after_split
        state: {
            ctx $ctx:tt
            input $input:tt
            output $output:tt
            variant { $variant:ident }
        }
        pass: $pass:tt
        found: { }
    ) => {
        compile_error!(concat!(
            "module variant `", stringify!($variant), "` is missing `#[module(name = \"...\")]`"
        ));
    };

    //
    // @after_split - non-empty `found:` carries the captured
    // `#[module(...)]` arguments. Dispatch to the per-arg parser.
    //

    (
        @after_split
        state: {
            ctx $ctx:tt
            input $input:tt
            output $output:tt
            variant $variant:tt
        }
        pass: $pass:tt
        found: { $($margs:tt)* }
    ) => {
        // `name { }` starts empty for the same reason as `found:` above
        // - an empty `name {}` after parsing means the caller forgot
        // `name = "..."`.
        //
        // `mode { kernel }` is the default when no `mode(...)` is given.
        $crate::_private_define_modules! {
            @parse_module_args
            ctx $ctx
            input $input
            output $output
            variant $variant
            pass $pass
            name { }
            mode { kernel }
            optional { false }
            args { $($margs)* }
        }
    };

    //
    // @parse_module_args - consume `name = "..."` (optionally followed by `, ...`).
    //

    (
        @parse_module_args
        ctx $ctx:tt
        input $input:tt
        output $output:tt
        variant $variant:tt
        pass $pass:tt
        name $_old_name:tt
        mode $mode:tt
        optional $opt:tt
        args { name = $name:literal $(, $($rest:tt)*)? }
    ) => {
        $crate::_private_define_modules! {
            @parse_module_args
            ctx $ctx
            input $input
            output $output
            variant $variant
            pass $pass
            name { $name }
            mode $mode
            optional $opt
            args { $($($rest)*)? }
        }
    };

    //
    // @parse_module_args - consume `mode(...)`.
    //

    (
        @parse_module_args
        ctx $ctx:tt
        input $input:tt
        output $output:tt
        variant $variant:tt
        pass $pass:tt
        name $name:tt
        mode $_old_mode:tt
        optional $opt:tt
        args { mode($($mode_args:tt)*) $(, $($rest:tt)*)? }
    ) => {
        $crate::_private_define_modules! {
            @parse_module_args
            ctx $ctx
            input $input
            output $output
            variant $variant
            pass $pass
            name $name
            mode { $($mode_args)* }
            optional $opt
            args { $($($rest)*)? }
        }
    };

    //
    // @parse_module_args - consume `optional` flag.
    //

    (
        @parse_module_args
        ctx $ctx:tt
        input $input:tt
        output $output:tt
        variant $variant:tt
        pass $pass:tt
        name $name:tt
        mode $mode:tt
        optional $_old_opt:tt
        args { optional $(, $($rest:tt)*)? }
    ) => {
        $crate::_private_define_modules! {
            @parse_module_args
            ctx $ctx
            input $input
            output $output
            variant $variant
            pass $pass
            name $name
            mode $mode
            optional { true }
            args { $($($rest)*)? }
        }
    };

    //
    // @parse_module_args - done with no `name = "..."` ever consumed:
    // the `name { }` slot is still empty. This arm must precede the
    // success arm below.
    //

    (
        @parse_module_args
        ctx $ctx:tt
        input $input:tt
        output $output:tt
        variant { $variant:ident }
        pass $pass:tt
        name { }
        mode $mode:tt
        optional $opt:tt
        args { }
    ) => {
        compile_error!(concat!(
            "module variant `", stringify!($variant), "` is missing `name = \"...\"` in `#[module(...)]`"
        ));
    };

    //
    // @parse_module_args - done, append the variant to the output.
    //

    (
        @parse_module_args
        ctx $ctx:tt
        input $input:tt
        output { $($out:tt)* }
        variant { $variant:ident }
        pass { $($pass:tt)* }
        name { $mod_name:literal }
        mode { $($mode_args:tt)* }
        optional { $opt:tt }
        args { }
    ) => {
        $crate::_private_define_modules! {
            @process_variants
            ctx $ctx
            input $input
            output {
                $($out)*
                {
                    variant: $variant,
                    pass: [$($pass)*],
                    name: $mod_name,
                    mode: { $($mode_args)* },
                    optional: $opt,
                }
            }
        }
    };

    //
    // @finalize - all variants are processed. Dispatch on the trailing markers.
    //

    // `#[resolver] ...; #[cache] ...;`
    (
        @finalize
        ctx {
            [$($eattr:tt)*]
            [$vis:vis]
            [$name:ident]
            [
                #[resolver] $rvis:vis struct $resolver:ident;
                #[cache]    $cvis:vis struct $cache:ident;
            ]
            [$os:tt]
        }
        output $variants:tt
    ) => {
        $crate::_private_define_modules! {
            @emit
            attrs: [$($eattr)*] vis: [$vis] name: [$name] os: $os
            variants: $variants
            resolver: { yes $rvis $resolver }
            cache:    { yes $cvis $cache }
        }
    };

    // `#[cache] ...; #[resolver] ...;`
    (
        @finalize
        ctx {
            [$($eattr:tt)*]
            [$vis:vis]
            [$name:ident]
            [
                #[cache]    $cvis:vis struct $cache:ident;
                #[resolver] $rvis:vis struct $resolver:ident;
            ]
            [$os:tt]
        }
        output $variants:tt
    ) => {
        $crate::_private_define_modules! {
            @emit
            attrs: [$($eattr)*] vis: [$vis] name: [$name] os: $os
            variants: $variants
            resolver: { yes $rvis $resolver }
            cache:    { yes $cvis $cache }
        }
    };

    // `#[resolver] ...;` only.
    (
        @finalize
        ctx {
            [$($eattr:tt)*]
            [$vis:vis]
            [$name:ident]
            [
                #[resolver] $rvis:vis struct $resolver:ident;
            ]
            [$os:tt]
        }
        output $variants:tt
    ) => {
        $crate::_private_define_modules! {
            @emit
            attrs: [$($eattr)*] vis: [$vis] name: [$name] os: $os
            variants: $variants
            resolver: { yes $rvis $resolver }
            cache:    { no }
        }
    };

    // `#[cache] ...;` only - error.
    (
        @finalize
        ctx {
            [$($eattr:tt)*]
            [$vis:vis]
            [$name:ident]
            [
                #[cache] $cvis:vis struct $cache:ident;
            ]
            [$os:tt]
        }
        output $variants:tt
    ) => {
        compile_error!("`#[cache]` requires `#[resolver]`");
    };

    // No trailing markers.
    (
        @finalize
        ctx {
            [$($eattr:tt)*]
            [$vis:vis]
            [$name:ident]
            [ ]
            [$os:tt]
        }
        output $variants:tt
    ) => {
        $crate::_private_define_modules! {
            @emit
            attrs: [$($eattr)*] vis: [$vis] name: [$name] os: $os
            variants: $variants
            resolver: { no }
            cache:    { no }
        }
    };

    //
    // @emit - generate the enum and dispatch to the appropriate impl emitter
    // based on whether `#[os(...)]` was provided.
    //

    (
        @emit
        attrs: [$($eattr:tt)*]
        vis:   [$vis:vis]
        name:  [$name:ident]
        os:    $os:tt
        variants: {
            $(
                {
                    variant: $variant:ident,
                    pass: [$($pass:tt)*],
                    name: $mod_name:literal,
                    mode: { $($mode_args:tt)* },
                    optional: $opt:tt,
                }
            )*
        }
        resolver: $resolver:tt
        cache:    $cache:tt
    ) => {
        $($eattr)*
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
        $vis enum $name {
            $(
                $($pass)*
                $variant,
            )*
        }

        $crate::_private_define_modules! {
            @emit_impl
            name: [$name]
            os:   $os
            variants: {
                $(
                    {
                        variant: $variant,
                        name: $mod_name,
                        mode: { $($mode_args)* },
                        optional: $opt,
                    }
                )*
            }
        }

        $crate::_private_define_modules! {
            @emit_resolver
            name: [$name]
            variants: { $( { variant: $variant, name: $mod_name, optional: $opt } )* }
            resolver: $resolver
            cache:    $cache
        }
    };

    //
    // @emit_impl - blanket case: `#[os(...)]` was omitted. Emits one impl over
    // `__Os: VmiOs + 'static`, so the enum serves every OS. Predicates passed
    // to `mode(user, process = ...)` must therefore be Os-generic.
    //
    // Predicates are turbofished with `__Os` because Rust cannot normalize the
    // abstract `__Os::Process<'_>` projection during dyn-Fn coercion, so it
    // cannot infer the predicate's generic from the expected type alone.
    //

    (
        @emit_impl
        name: [$name:ident]
        os:   { }
        variants: {
            $(
                {
                    variant: $variant:ident,
                    name: $mod_name:literal,
                    mode: { $($mode_args:tt)* },
                    optional: $opt:tt,
                }
            )*
        }
    ) => {
        impl<__Os> $crate::reactor::ReactorModule<__Os> for $name
        where
            __Os: $crate::reactor::macros::__private::vmi_core::VmiOs + 'static,
        {
            const METADATA: &'static [$crate::reactor::ModuleMetadata<Self, __Os>] = &[
                $crate::reactor::ModuleMetadata {
                    name: "kernel",
                    module: ::std::option::Option::None,
                    mode: $crate::reactor::ModuleMode::Kernel,
                    optional: true,
                },
                $(
                    $crate::reactor::ModuleMetadata {
                        name: $mod_name,
                        module: ::std::option::Option::Some(Self::$variant),
                        mode: $crate::_private_define_modules!(
                            @mode_expr { $($mode_args)* } turbofish: { ::<__Os> }
                        ),
                        optional: $opt,
                    },
                )*
            ];

            const KERNEL_SLOT: usize = 0;

            fn slot(self) -> usize {
                self as usize + 1
            }
        }
    };

    //
    // @emit_impl - os-anchored case, with generic params. The impl signature is
    // spelled by the user via `#[os(<G...> OsTy where bounds...)]` and emitted
    // verbatim, anchoring the impl to a specific OS family.
    //
    // Generics are parsed structurally (per-param `:ident` with an optional
    // single-`:ident` bound) so angle brackets do not cause local ambiguity.
    // Complex bounds (`VmiRead<X>`, `Driver::Architecture: ArchAdapter<Driver>`)
    // belong in the `where` clause.
    //
    // This arm must precede the no-generics arm below - an input that begins
    // with `<` would otherwise be ambiguous between starting a generics list
    // and starting an HRTB-like `:ty` in the no-generics arm.
    //

    (
        @emit_impl
        name: [$name:ident]
        os:   {
            < $( $g_param:ident $( : $g_bound:ident )? ),+ >
            $os_ty:ty
            $( where $($bounds:tt)* )?
        }
        variants: $variants:tt
    ) => {
        $crate::_private_define_modules! {
            @emit_impl_anchored
            name: [$name]
            impl_generics: [ $( $g_param $( : $g_bound )? ),+ ]
            os_ty: [$os_ty]
            where_bounds: [ $( $($bounds)* )? ]
            variants: $variants
        }
    };

    //
    // @emit_impl - os-anchored case, no generic params. The impl is bound to a
    // concrete OS type (e.g. `WindowsOs<VmiXenDriver<Amd64>>`) or a type alias.
    //

    (
        @emit_impl
        name: [$name:ident]
        os:   {
            $os_ty:ty
            $( where $($bounds:tt)* )?
        }
        variants: $variants:tt
    ) => {
        $crate::_private_define_modules! {
            @emit_impl_anchored
            name: [$name]
            impl_generics: [ ]
            os_ty: [$os_ty]
            where_bounds: [ $( $($bounds)* )? ]
            variants: $variants
        }
    };

    //
    // @emit_impl_anchored - shared emit for both anchored arms above. Receives
    // already-extracted generics, os type, and where bounds, and writes one
    // `impl ... ReactorModule<OsTy> for $name { ... }` block.
    //

    (
        @emit_impl_anchored
        name: [$name:ident]
        impl_generics: [ $($impl_generics:tt)* ]
        os_ty: [$os_ty:ty]
        where_bounds: [ $($bounds:tt)* ]
        variants: {
            $(
                {
                    variant: $variant:ident,
                    name: $mod_name:literal,
                    mode: { $($mode_args:tt)* },
                    optional: $opt:tt,
                }
            )*
        }
    ) => {
        impl<$($impl_generics)*> $crate::reactor::ReactorModule<$os_ty> for $name
        where
            $($bounds)*
        {
            const METADATA: &'static [$crate::reactor::ModuleMetadata<Self, $os_ty>] = &[
                $crate::reactor::ModuleMetadata {
                    name: "kernel",
                    module: ::std::option::Option::None,
                    mode: $crate::reactor::ModuleMode::Kernel,
                    optional: true,
                },
                $(
                    $crate::reactor::ModuleMetadata {
                        name: $mod_name,
                        module: ::std::option::Option::Some(Self::$variant),
                        mode: $crate::_private_define_modules!(
                            @mode_expr { $($mode_args)* } turbofish: { }
                        ),
                        optional: $opt,
                    },
                )*
            ];

            const KERNEL_SLOT: usize = 0;

            fn slot(self) -> usize {
                self as usize + 1
            }
        }
    };

    //
    // @mode_expr - render a `ModuleMode<Os>` expression from captured
    // `mode(...)` args. Invoked from `@emit_impl` / `@emit_impl_anchored`,
    // where the impl's Os type is in scope.
    //
    // The `turbofish` parameter is appended verbatim after the predicate path
    // so the blanket emitter can pass `::<__Os>` to make the predicate's
    // generic explicit (needed because Rust cannot normalize the abstract
    // `__Os::Process<'_>` projection during dyn-Fn coercion). Anchored
    // emitters pass an empty turbofish - the impl's concrete bounds let
    // inference resolve the predicate's generic.
    //
    // Arm order: literal `process = "..."` precedes the path arm because
    // `:literal` is the narrower matcher.
    //

    (@mode_expr { kernel } turbofish: $tf:tt) => {
        $crate::reactor::ModuleMode::Kernel
    };

    (@mode_expr { user } turbofish: $tf:tt) => {
        $crate::reactor::ModuleMode::User {
            process: ::std::option::Option::None,
        }
    };

    (@mode_expr { user, process = $name:literal } turbofish: $tf:tt) => {
        $crate::reactor::ModuleMode::User {
            process: ::std::option::Option::Some(
                $crate::reactor::ModuleProcessFilter::Name($name),
            ),
        }
    };

    (@mode_expr { user, process = $($path:tt)+ } turbofish: { $($tf:tt)* }) => {
        $crate::reactor::ModuleMode::User {
            process: ::std::option::Option::Some(
                $crate::reactor::ModuleProcessFilter::Predicate(&$($path)+ $($tf)*),
            ),
        }
    };

    //
    // @emit_resolver - nothing when no `#[resolver]` is requested.
    //

    (
        @emit_resolver
        name: [$name:ident]
        variants: $variants:tt
        resolver: { no }
        cache:    { no }
    ) => { };

    //
    // @emit_resolver - resolver only (no cache).
    //

    (
        @emit_resolver
        name: [$name:ident]
        variants: {
            $( { variant: $variant:ident, name: $mod_name:literal, optional: $opt:tt } )*
        }
        resolver: { yes $rvis:vis $resolver:ident }
        cache:    { no }
    ) => {
        $crate::_private_define_modules! {
            @emit_resolver_struct
            name: [$name]
            variants: { $( { variant: $variant, name: $mod_name, optional: $opt } )* }
            resolver: { $rvis $resolver }
        }
    };

    //
    // @emit_resolver - resolver and cache.
    //

    (
        @emit_resolver
        name: [$name:ident]
        variants: {
            $( { variant: $variant:ident, name: $mod_name:literal, optional: $opt:tt } )*
        }
        resolver: { yes $rvis:vis $resolver:ident }
        cache:    { yes $cvis:vis $cache:ident }
    ) => {
        $crate::_private_define_modules! {
            @emit_resolver_struct
            name: [$name]
            variants: { $( { variant: $variant, name: $mod_name, optional: $opt } )* }
            resolver: { $rvis $resolver }
        }

        #[doc = concat!(
            "Cache for resolved symbol entries of `", stringify!($name), "`.\n\n",
            "Slot 0 is reserved for the kernel. The remaining slots correspond to ",
            "the modules of the enum, indexed by `slot()`."
        )]
        $cvis struct $cache {
            __inner: [
                ::std::option::Option<
                    $crate::reactor::macros::__private::isr_cache::Entry
                >;
                1 + <[()]>::len(&[ $( $crate::_private_modules_unit!($variant) ),* ])
            ],
        }

        impl ::std::default::Default for $cache {
            fn default() -> Self {
                Self {
                    __inner: [
                        const { ::std::option::Option::None };
                        1 + <[()]>::len(&[ $( $crate::_private_modules_unit!($variant) ),* ])
                    ],
                }
            }
        }

        #[allow(dead_code)]
        impl<'a, __Driver> $resolver<'a, $crate::reactor::macros::__private::vmi_os_windows::WindowsOs<__Driver>>
        where
            __Driver: $crate::reactor::macros::__private::vmi_core::driver::VmiFullDriver,
            __Driver::Architecture:
                $crate::reactor::macros::__private::vmi_os_windows::ArchAdapter<__Driver> +
                $crate::resolver::ArchAdapter<__Driver>,
        {
            /// Resolves the kernel and every module that has not been pre-populated.
            pub fn resolve(
                mut self,
                session: &$crate::reactor::macros::__private::vmi_core::VmiSession<
                    $crate::reactor::macros::__private::vmi_os_windows::WindowsOs<__Driver>
                >,
                isr: &$crate::reactor::macros::__private::isr_cache::IsrCache,
                entries: &'a mut $cache,
            ) -> ::std::result::Result<
                Self,
                $crate::reactor::macros::__private::vmi_core::VmiError,
            > {
                $crate::reactor::macros::__private::resolve_modules::<__Driver, $name>(
                    session,
                    isr,
                    entries.__inner.as_mut_slice(),
                    self.__inner.as_mut_slice(),
                )?;

                ::std::result::Result::Ok(self)
            }
        }
    };

    //
    // @emit_resolver_struct - shared resolver struct + Default + builder methods.
    //

    (
        @emit_resolver_struct
        name: [$name:ident]
        variants: {
            $( { variant: $variant:ident, name: $mod_name:literal, optional: $opt:tt } )*
        }
        resolver: { $rvis:vis $resolver:ident }
    ) => {
        #[doc = concat!(
            "Table of resolved modules for `", stringify!($name), "`.\n\n",
            "Slot 0 is reserved for the kernel; the remaining slots correspond to ",
            "the variants of the enum, indexed by `slot()`.\n\n",
            "The `Os` parameter is locked when `.resolve(...)` is called against a ",
            "concrete `VmiSession<Os>`; before that point inference will leave it open."
        )]
        $rvis struct $resolver<'a, __Os>
        where
            __Os: $crate::reactor::macros::__private::vmi_core::VmiOs + 'static,
        {
            __inner: [
                ::std::option::Option<$crate::reactor::ResolvedModule<'a>>;
                1 + <[()]>::len(&[ $( $crate::_private_modules_unit!($variant) ),* ])
            ],
            __marker: ::std::marker::PhantomData<fn() -> __Os>,
        }

        impl<'a, __Os> ::std::default::Default for $resolver<'a, __Os>
        where
            __Os: $crate::reactor::macros::__private::vmi_core::VmiOs + 'static,
        {
            fn default() -> Self {
                Self {
                    __inner: [
                        const { ::std::option::Option::None };
                        1 + <[()]>::len(&[ $( $crate::_private_modules_unit!($variant) ),* ])
                    ],
                    __marker: ::std::marker::PhantomData,
                }
            }
        }

        #[allow(dead_code)]
        impl<'a, __Os> $resolver<'a, __Os>
        where
            __Os: $crate::reactor::macros::__private::vmi_core::VmiOs + 'static,
            $name: $crate::reactor::ReactorModule<__Os>,
        {
            /// Stores a pre-resolved kernel entry.
            pub fn with_kernel(
                mut self,
                base_address: $crate::reactor::macros::__private::vmi_core::Va,
                profile: impl ::std::convert::Into<$crate::reactor::ProfileRef<'a>>,
            ) -> Self {
                let profile = profile.into();
                self.__inner[<$name as $crate::reactor::ReactorModule<__Os>>::KERNEL_SLOT] =
                    ::std::option::Option::Some(
                        $crate::reactor::ResolvedModule { process: None, base_address, profile },
                    );
                self
            }

            /// Stores a pre-resolved entry for a module.
            pub fn with_module(
                mut self,
                module: $name,
                base_address: $crate::reactor::macros::__private::vmi_core::Va,
                profile: impl ::std::convert::Into<$crate::reactor::ProfileRef<'a>>,
            ) -> Self {
                let profile = profile.into();
                let slot = <$name as $crate::reactor::ReactorModule<__Os>>::slot(module);
                self.__inner[slot] = ::std::option::Option::Some(
                    $crate::reactor::ResolvedModule { process: None, base_address, profile },
                );
                self
            }

            /// Stores a pre-resolved entry for a module in a specific process.
            pub fn with_module_in_process(
                mut self,
                module: $name,
                process: $crate::reactor::macros::__private::vmi_core::os::ProcessObject,
                base_address: $crate::reactor::macros::__private::vmi_core::Va,
                profile: impl ::std::convert::Into<$crate::reactor::ProfileRef<'a>>,
            ) -> Self {
                let profile = profile.into();
                let slot = <$name as $crate::reactor::ReactorModule<__Os>>::slot(module);
                self.__inner[slot] = ::std::option::Option::Some(
                    $crate::reactor::ResolvedModule { process: Some(process), base_address, profile },
                );
                self
            }

            /// Resolves the events declared against this module enum.
            pub fn into_events<Event>(
                self,
            ) -> ::std::result::Result<
                ::std::vec::Vec<$crate::reactor::ResolvedEvent<Event>>,
                $crate::reactor::macros::__private::vmi_core::VmiError,
            >
            where
                Event: $crate::reactor::ReactorEvent<Module = $name>,
            {
                $crate::reactor::macros::__private::resolve_events::<Event, __Os>(
                    self.__inner.as_slice(),
                )
            }
        }
    };
}