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
//! Implementation of the [`define_events!`] macro.
//!
//! The macro consumes a user-facing DSL that names a flat list of kernel
//! events followed by zero or more grouped module event blocks, and expands
//! to:
//!
//! - A flat enum with fixed derives (`Debug, Clone, Copy, PartialEq, Eq,
//!   Hash`), with module groups flattened into top-level variants.
//! - An `impl ReactorEvent` block exposing `type Module = <M>` and the
//!   per-variant `METADATA` table.
//!
//! [`define_events!`]: super::super::define_events

/// Maps a single token tree to `()`, used to count variants at compile time.
#[doc(hidden)]
#[macro_export]
macro_rules! _private_events_unit {
    ($_t:tt) => {
        ()
    };
}

/// Defines a [`ReactorEvent`] enum for the symbols monitored by a [`Reactor`].
///
/// # Usage
///
/// ```no_run
/// # use vmi_utils::reactor::{define_events, define_modules};
/// # define_modules! {
/// #     pub enum Module {
/// #         #[module(name = "netio.sys")]
/// #         NetioSys,
/// #
/// #         #[module(name = "ncrypt.dll", mode(user, process = "lsass.exe"))]
/// #         Ncrypt,
/// #     }
/// # }
/// define_events! {
///     /// Events monitored by the reactor.
///     pub enum Event in Module {
///         // Kernel events must be listed at the top, before any module group.
///         // The variant ident becomes the symbol name.
///         NtCreateFile,
///         NtWriteFile,
///
///         // `optional` lets the event be absent from the profile.
///         #[event(optional)]
///         NtRetiredSymbol,
///
///         // Module group. Every variant inside is tagged with
///         // `EventMetadata::module = Some(Module::NetioSys)`.
///         NetioSys {
///             KfdClassify,
///
///             /// Some kernels expose this under a slightly different
///             /// name - aliases are tried in declaration order.
///             #[event(alias = "KfdIsLayerEmpty_v2")]
///             KfdIsLayerEmpty,
///         },
///
///         // Multiple aliases and `optional` compose freely.
///         Ncrypt {
///             #[event(
///                 name = "SslGenerateSessionKeys",
///                 alias = ["SslGenerateSessionKeys_v2", "SslGenerateSessionKeysEx"],
///                 optional,
///             )]
///             GenerateSessionKeys,
///         },
///     }
/// }
/// ```
///
/// # Attributes
///
/// `#[event(...)]` on a variant is optional. Arguments are
/// position-independent:
///
/// - `name = "..."`: override the symbol name. Defaults to
///   `stringify!($variant)`.
/// - `alias = "..."` or `alias = ["...", "..."]`: alternate symbol
///   names tried in order when `name` is not present in the profile.
/// - `optional`: the event is allowed to be absent from the profile..
///
/// # Generated code
///
/// - The enum, with `#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]`.
/// - An `impl ReactorEvent for $Enum` block exposing
///   `type Module = $Module` and the per-variant `METADATA` table.
///
/// # Ordering
///
/// All kernel events must precede any module group. A kernel event
/// after a group, or a group between two kernel events, is a compile
/// error.
///
/// [`ReactorEvent`]: super::super::ReactorEvent
/// [`Reactor`]: super::super::Reactor
#[doc(hidden)]
#[macro_export]
macro_rules! _private_define_events {
    //
    // Public entry.
    //
    // Captures the enum and its module reference, then kicks off the body
    // muncher in the `kernels` phase.
    //

    (
        $(#[$enum_attr:meta])*
        $vis:vis enum $name:ident in $module:ident {
            $($body:tt)*
        }
    ) => {
        $crate::_private_define_events! {
            @parse_body
            ctx { [$(#[$enum_attr])*] [$vis] [$name] [$module] }
            phase { kernels }
            remaining { $($body)* }
            events { }
        }
    };

    //
    // @parse_body - base case: empty body.
    //

    (
        @parse_body
        ctx $ctx:tt
        phase $phase:tt
        remaining { }
        events $events:tt
    ) => {
        $crate::_private_define_events! {
            @emit
            ctx $ctx
            events $events
        }
    };

    //
    // @parse_body - module group `Ident { ... },`.
    //
    // Matches before the kernel-event arms because both start with an
    // identifier. The trailing `{ ... }` disambiguates.
    //

    (
        @parse_body
        ctx $ctx:tt
        phase $phase:tt
        remaining {
            $gmod:ident { $($inner:tt)* }
            $(, $($outer_rest:tt)*)?
        }
        events $events:tt
    ) => {
        $crate::_private_define_events! {
            @process_group_inner
            ctx $ctx
            group_module { $gmod }
            inner { $($inner)* }
            outer { $($($outer_rest)*)? }
            events $events
        }
    };

    //
    // @parse_body - kernel event in `groups` phase: forbidden mixing.
    //

    (
        @parse_body
        ctx $ctx:tt
        phase { groups }
        remaining {
            $(#[$($vattr:tt)*])*
            $variant:ident
            $(, $($rest:tt)*)?
        }
        events $events:tt
    ) => {
        compile_error!(concat!(
            "kernel event `",
            stringify!($variant),
            "` cannot appear after a module group. \
             Move all kernel events above the first module group."
        ));
    };

    //
    // @parse_body - kernel event with trailing comma.
    //

    (
        @parse_body
        ctx $ctx:tt
        phase { kernels }
        remaining {
            $(#[$($vattr:tt)*])*
            $variant:ident,
            $($rest:tt)*
        }
        events $events:tt
    ) => {
        $crate::_private_split_reactor_attrs! {
            peel: event
            state: {
                ctx $ctx
                after_body { @parse_body ctx $ctx phase { kernels } remaining { $($rest)* } }
                module { }
                variant { $variant }
                events $events
            }
            pass: { }
            found: { }
            attrs: { $(#[$($vattr)*])* }
        }
    };

    //
    // @parse_body - kernel event with no trailing comma (last in body).
    //

    (
        @parse_body
        ctx $ctx:tt
        phase { kernels }
        remaining {
            $(#[$($vattr:tt)*])*
            $variant:ident
        }
        events $events:tt
    ) => {
        $crate::_private_split_reactor_attrs! {
            peel: event
            state: {
                ctx $ctx
                after_body { @parse_body ctx $ctx phase { kernels } remaining { } }
                module { }
                variant { $variant }
                events $events
            }
            pass: { }
            found: { }
            attrs: { $(#[$($vattr)*])* }
        }
    };

    //
    // @process_group_inner - all inner variants of the group consumed,
    // resume the outer body parser in `groups` phase.
    //

    (
        @process_group_inner
        ctx $ctx:tt
        group_module { $gmod:ident }
        inner { }
        outer { $($outer:tt)* }
        events $events:tt
    ) => {
        $crate::_private_define_events! {
            @parse_body
            ctx $ctx
            phase { groups }
            remaining { $($outer)* }
            events $events
        }
    };

    //
    // @process_group_inner - one variant of the group, with trailing comma.
    //

    (
        @process_group_inner
        ctx $ctx:tt
        group_module { $gmod:ident }
        inner {
            $(#[$($vattr:tt)*])*
            $variant:ident,
            $($rest:tt)*
        }
        outer $outer:tt
        events $events:tt
    ) => {
        $crate::_private_split_reactor_attrs! {
            peel: event
            state: {
                ctx $ctx
                after_body { @process_group_inner ctx $ctx group_module { $gmod } inner { $($rest)* } outer $outer }
                module { group $gmod }
                variant { $variant }
                events $events
            }
            pass: { }
            found: { }
            attrs: { $(#[$($vattr)*])* }
        }
    };

    //
    // @process_group_inner - one variant of the group, no trailing comma.
    //

    (
        @process_group_inner
        ctx $ctx:tt
        group_module { $gmod:ident }
        inner {
            $(#[$($vattr:tt)*])*
            $variant:ident
        }
        outer $outer:tt
        events $events:tt
    ) => {
        $crate::_private_split_reactor_attrs! {
            peel: event
            state: {
                ctx $ctx
                after_body { @process_group_inner ctx $ctx group_module { $gmod } inner { } outer $outer }
                module { group $gmod }
                variant { $variant }
                events $events
            }
            pass: { }
            found: { }
            attrs: { $(#[$($vattr)*])* }
        }
    };

    //
    // @after_split - empty `found:` means no `#[event(...)]` was supplied.
    // The variant ident becomes the symbol name (no alias, not optional).
    // This arm must precede the catch-all `found: { $($eargs:tt)* }` below.
    //
    // `name { }` is used for "no explicit name" - @event_name resolves it
    // to `stringify!($variant)` at emission time.
    //

    (
        @after_split
        state: {
            ctx $ctx:tt
            after_body $after:tt
            module $module:tt
            variant $variant:tt
            events $events:tt
        }
        pass: $pass:tt
        found: { }
    ) => {
        $crate::_private_define_events! {
            @finish_event
            ctx $ctx
            after_body $after
            module $module
            variant $variant
            events $events
            pass $pass
            name { }
            alias { [ ] }
            optional { false }
        }
    };

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

    (
        @after_split
        state: {
            ctx $ctx:tt
            after_body $after:tt
            module $module:tt
            variant $variant:tt
            events $events:tt
        }
        pass: $pass:tt
        found: { $($eargs:tt)* }
    ) => {
        $crate::_private_define_events! {
            @parse_event_args
            ctx $ctx
            after_body $after
            module $module
            variant $variant
            events $events
            pass $pass
            name { }
            alias { [ ] }
            optional { false }
            args { $($eargs)* }
        }
    };

    //
    // @parse_event_args - consume `name = "..."`.
    //

    (
        @parse_event_args
        ctx $ctx:tt
        after_body $after:tt
        module $module:tt
        variant $variant:tt
        events $events:tt
        pass $pass:tt
        name $_old_name:tt
        alias $alias:tt
        optional $optional:tt
        args { name = $name:literal $(, $($rest:tt)*)? }
    ) => {
        $crate::_private_define_events! {
            @parse_event_args
            ctx $ctx
            after_body $after
            module $module
            variant $variant
            events $events
            pass $pass
            name { $name }
            alias $alias
            optional $optional
            args { $($($rest)*)? }
        }
    };

    //
    // @parse_event_args - consume `alias = "x"` (single string).
    //

    (
        @parse_event_args
        ctx $ctx:tt
        after_body $after:tt
        module $module:tt
        variant $variant:tt
        events $events:tt
        pass $pass:tt
        name $name:tt
        alias $_old_alias:tt
        optional $optional:tt
        args { alias = $alias:literal $(, $($rest:tt)*)? }
    ) => {
        $crate::_private_define_events! {
            @parse_event_args
            ctx $ctx
            after_body $after
            module $module
            variant $variant
            events $events
            pass $pass
            name $name
            alias { [ $alias ] }
            optional $optional
            args { $($($rest)*)? }
        }
    };

    //
    // @parse_event_args - consume `alias = ["x", "y", ...]` (array form).
    //

    (
        @parse_event_args
        ctx $ctx:tt
        after_body $after:tt
        module $module:tt
        variant $variant:tt
        events $events:tt
        pass $pass:tt
        name $name:tt
        alias $_old_alias:tt
        optional $optional:tt
        args { alias = [ $($alias:literal),* $(,)? ] $(, $($rest:tt)*)? }
    ) => {
        $crate::_private_define_events! {
            @parse_event_args
            ctx $ctx
            after_body $after
            module $module
            variant $variant
            events $events
            pass $pass
            name $name
            alias { [ $($alias),* ] }
            optional $optional
            args { $($($rest)*)? }
        }
    };

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

    (
        @parse_event_args
        ctx $ctx:tt
        after_body $after:tt
        module $module:tt
        variant $variant:tt
        events $events:tt
        pass $pass:tt
        name $name:tt
        alias $alias:tt
        optional $_old_optional:tt
        args { optional $(, $($rest:tt)*)? }
    ) => {
        $crate::_private_define_events! {
            @parse_event_args
            ctx $ctx
            after_body $after
            module $module
            variant $variant
            events $events
            pass $pass
            name $name
            alias $alias
            optional { true }
            args { $($($rest)*)? }
        }
    };

    //
    // @parse_event_args - empty args, finalize the entry.
    //

    (
        @parse_event_args
        ctx $ctx:tt
        after_body $after:tt
        module $module:tt
        variant $variant:tt
        events $events:tt
        pass $pass:tt
        name $name:tt
        alias $alias:tt
        optional $optional:tt
        args { }
    ) => {
        $crate::_private_define_events! {
            @finish_event
            ctx $ctx
            after_body $after
            module $module
            variant $variant
            events $events
            pass $pass
            name $name
            alias $alias
            optional $optional
        }
    };

    //
    // @finish_event - append the parsed event to the accumulator and resume
    // the appropriate body parser.
    //

    (
        @finish_event
        ctx $ctx:tt
        after_body { $($after:tt)* }
        module $module:tt
        variant { $variant:ident }
        events { $($events:tt)* }
        pass { $($pass:tt)* }
        name $name:tt
        alias $alias:tt
        optional { $optional:tt }
    ) => {
        $crate::_private_define_events! {
            $($after)*
            events {
                $($events)*
                {
                    variant: $variant,
                    pass: [$($pass)*],
                    module: $module,
                    name: $name,
                    alias: $alias,
                    optional: $optional,
                }
            }
        }
    };

    //
    // @emit - all events collected, generate the enum and impl.
    //

    (
        @emit
        ctx { [$($eattr:tt)*] [$vis:vis] [$name:ident] [$module:ident] }
        events {
            $(
                {
                    variant: $variant:ident,
                    pass: [$($pass:tt)*],
                    module: $event_module:tt,
                    name: $event_name:tt,
                    alias: $event_alias:tt,
                    optional: $optional:tt,
                }
            )*
        }
    ) => {
        $($eattr)*
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
        $vis enum $name {
            $(
                $($pass)*
                $variant,
            )*
        }

        impl $crate::reactor::ReactorEvent for $name {
            type Module = $module;

            const METADATA: &'static [$crate::reactor::EventMetadata<Self>] = &[
                $(
                    $crate::reactor::EventMetadata {
                        name: $crate::_private_define_events!(
                            @event_name $event_name $variant
                        ),
                        alias: $crate::_private_define_events!(
                            @event_alias $event_alias
                        ),
                        module: $crate::_private_define_events!(
                            @event_module $event_module $module
                        ),
                        event: Self::$variant,
                        optional: $optional,
                    },
                )*
            ];
        }
    };

    //
    // @event_name helpers - empty `{ }` means no explicit name was given,
    // so derive one from the variant ident. The empty arm must precede the
    // literal arm.
    //

    (@event_name { } $variant:ident) => {
        stringify!($variant)
    };

    (@event_name { $literal:literal } $variant:ident) => {
        $literal
    };

    //
    // @event_alias helper - unwrap `{ [ "x", "y", ... ] }` into `&["x", "y"]`.
    //

    (@event_alias { [ $($alias:literal),* $(,)? ] }) => {
        &[ $($alias),* ]
    };

    //
    // @event_module helpers - convert `module` tag to an Option.
    //

    (@event_module { } $module:ident) => {
        None
    };

    (@event_module { group $gmod:ident } $module:ident) => {
        Some($module::$gmod)
    };
}