sigmd 0.1.0

Windows API signature metadata
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
//! Persisted data types for the metadata bundle.

use std::collections::HashMap;

use bon::Builder;
use rkyv::{Archive, Deserialize, Serialize};
use uuid::Uuid;

/// Top-level metadata bundle, one entry per architecture.
#[derive(Debug, Default, Builder, Archive, Serialize, Deserialize)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[rkyv(derive(Debug))]
pub struct Database {
    /// Metadata for the x86 architecture.
    pub x86: Metadata,

    /// Metadata for the x64 architecture.
    pub x64: Metadata,
}

/// Metadata for one architecture. Vecs are sorted by `name` after the
/// build's merge step.
#[derive(Debug, Default, Builder, Archive, Serialize, Deserialize)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[rkyv(derive(Debug))]
#[builder(finish_fn(name = build_impl, vis = ""))]
pub struct Metadata {
    /// Monitored functions, sorted by name.
    #[builder(default, with = FromIterator::from_iter)]
    pub functions: Vec<Function>,

    /// COM interfaces, sorted by name.
    #[builder(default, with = FromIterator::from_iter)]
    pub interfaces: Vec<Interface>,

    /// Lookup index from function name to position in `functions`.
    #[cfg_attr(feature = "serde", serde(skip))]
    #[builder(skip)]
    pub functions_by_name: HashMap<String, usize>,

    /// Lookup index from interface name to position in `interfaces`.
    #[cfg_attr(feature = "serde", serde(skip))]
    #[builder(skip)]
    pub interfaces_by_name: HashMap<String, usize>,

    /// Lookup index from interface UUID to position in `interfaces`.
    #[cfg_attr(feature = "serde", serde(skip))]
    #[builder(skip)]
    pub interfaces_by_uuid: HashMap<Uuid, usize>,
}

impl<S: metadata_builder::State> MetadataBuilder<S>
where
    S: metadata_builder::IsComplete,
{
    /// Finishes the builder. Sorts the function and interface vecs by
    /// name and computes the runtime lookup indices.
    pub fn build(self) -> Metadata {
        let mut metadata = self.build_impl();

        metadata.functions.sort_by(|a, b| a.name.cmp(&b.name));
        metadata.interfaces.sort_by(|a, b| a.name.cmp(&b.name));

        metadata.functions_by_name = metadata
            .functions
            .iter()
            .enumerate()
            .map(|(index, function)| (function.name.clone(), index))
            .collect();

        metadata.interfaces_by_name = metadata
            .interfaces
            .iter()
            .enumerate()
            .map(|(index, interface)| (interface.name.clone(), index))
            .collect();

        metadata.interfaces_by_uuid = metadata
            .interfaces
            .iter()
            .enumerate()
            .map(|(index, interface)| (interface.uuid, index))
            .collect();

        metadata
    }
}

/// A monitored function (free or method).
///
/// Use `Function::builder()` to construct. The terminal `build()` pre-bakes
/// `output_parameter_indices`, `input_buffer_indices`, and
/// `output_buffer_indices` from `parameters` and `buffers`, so the on-disk
/// archive carries the partitions and the runtime never re-scans.
#[derive(Debug, Builder, Archive, Serialize, Deserialize)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[rkyv(derive(Debug))]
#[builder(finish_fn(name = build_impl, vis = ""))]
pub struct Function {
    /// Function name.
    #[builder(into)]
    pub name: String,

    /// Parameters in declaration order.
    #[builder(default)]
    pub parameters: Vec<Parameter>,

    /// Buffer descriptions referenced by the parameters.
    #[builder(default)]
    pub buffers: Vec<Buffer>,

    /// Return type.
    pub return_ty: Type,

    /// Indices into `parameters` of params with `HAS_OUT_ATTRIBUTE`.
    /// Computed at build time from `parameters`.
    #[cfg_attr(feature = "serde", serde(skip))]
    #[builder(skip)]
    pub output_parameter_indices: Vec<u8>,

    /// Indices into `buffers` of buffers with input direction.
    /// Computed at build time from `buffers`.
    #[cfg_attr(feature = "serde", serde(skip))]
    #[builder(skip)]
    pub input_buffer_indices: Vec<u8>,

    /// Indices into `buffers` of buffers with output direction.
    /// Computed at build time from `buffers`.
    #[cfg_attr(feature = "serde", serde(skip))]
    #[builder(skip)]
    pub output_buffer_indices: Vec<u8>,
}

impl<S: function_builder::State> FunctionBuilder<S>
where
    S: function_builder::IsComplete,
{
    /// Finishes the builder. Pre-bakes the partition indices used by
    /// runtime accessors.
    pub fn build(self) -> Function {
        let mut function = self.build_impl();

        function.output_parameter_indices = function
            .parameters
            .iter()
            .enumerate()
            .filter_map(|(index, parameter)| {
                parameter
                    .flags
                    .contains(ParameterFlags::HAS_OUT_ATTRIBUTE)
                    .then_some(index as u8)
            })
            .collect();

        for buffer in &mut function.buffers {
            buffer.position = match buffer.direction {
                BufferDirection::Input => buffer.parameter,
                BufferDirection::Output => function
                    .output_parameter_indices
                    .iter()
                    .copied()
                    .position(|index| index == buffer.parameter)
                    .expect("output buffer references parameter without HAS_OUT_ATTRIBUTE")
                    as u8,
            };
        }

        function.input_buffer_indices = function
            .buffers
            .iter()
            .enumerate()
            .filter_map(|(index, buffer)| {
                matches!(buffer.direction, BufferDirection::Input).then_some(index as u8)
            })
            .collect();

        function.output_buffer_indices = function
            .buffers
            .iter()
            .enumerate()
            .filter_map(|(index, buffer)| {
                matches!(buffer.direction, BufferDirection::Output).then_some(index as u8)
            })
            .collect();

        function
    }
}

/// A COM interface (struct or class with `DECLSPEC_UUID`).
#[derive(Debug, Builder, Archive, Serialize, Deserialize)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[rkyv(derive(Debug))]
pub struct Interface {
    /// Interface name.
    #[builder(into)]
    pub name: String,

    /// Interface UUID from `DECLSPEC_UUID`.
    pub uuid: Uuid,

    /// Base interface name, if any.
    #[builder(into)]
    pub base: Option<String>,

    /// Methods declared on this interface.
    #[builder(default)]
    pub methods: Vec<Function>,
}

/// One function/method parameter.
#[derive(Debug, Builder, Archive, Serialize, Deserialize)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[rkyv(derive(Debug))]
pub struct Parameter {
    /// Parameter name, if declared.
    #[builder(into)]
    pub name: Option<String>,

    /// SAL-derived directionality flags.
    #[rkyv(with = crate::asbits::AsBits)]
    #[builder(default = ParameterFlags::empty())]
    pub flags: ParameterFlags,

    /// Parameter type.
    pub ty: Type,
}

bitflags::bitflags! {
    /// SAL-derived parameter directionality flags.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    #[cfg_attr(feature = "serde", derive(serde::Serialize))]
    pub struct ParameterFlags: u8 {
        /// `_In_` (or `_Inout_`, `__in`, `__RPC__in`, etc.) was present.
        const HAS_IN_ATTRIBUTE  = 0x01;

        /// `_Out_` (or `_Inout_`, `_COM_Out`, `__out`, etc.) was present.
        const HAS_OUT_ATTRIBUTE = 0x02;

        /// `_COM_Outptr_*` was present.
        const HAS_COM_ATTRIBUTE = 0x04;
    }
}

/// Type signature for a parameter or return value.
#[derive(Debug, Builder, Archive, Serialize, Deserialize)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[rkyv(derive(Debug))]
pub struct Type {
    /// Pointer or reference depth. Zero for non-pointer types.
    #[builder(default)]
    pub indirections: u8,

    /// Source-spelling of the leaf type with C++ keyword prefixes
    /// (`const`, `struct`, `enum`, `union`, `class`) stripped, for
    /// example "DWORD" or "_UNICODE_STRING".
    #[builder(into)]
    pub name: String,

    /// Primitive kind of the leaf. Pointers are structural via
    /// `indirections`, so this never represents a pointer.
    pub kind: TypeKind,
}

impl Type {
    /// `void *`. Used for the synthetic `This` parameter on COM methods.
    pub fn void_pointer() -> Self {
        Self {
            indirections: 1,
            name: String::from("void"),
            kind: TypeKind::Void,
        }
    }
}

/// Primitive kind of a leaf type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Archive, Serialize, Deserialize)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[rkyv(derive(Debug))]
#[expect(missing_docs, reason = "self-explanatory")]
pub enum TypeKind {
    Unknown,
    Void,
    Bool,
    Char8,
    Char16,
    I8,
    I16,
    I32,
    I64,
    U8,
    U16,
    U32,
    U64,
    F32,
    F64,
    Custom(u8),
}

/// Per-call buffer description for one parameter.
#[derive(Debug, Builder, Archive, Serialize, Deserialize)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[rkyv(derive(Debug))]
pub struct Buffer {
    /// Index into the enclosing function's `parameters` vec.
    pub parameter: u8,

    /// Position of this buffer's parameter in the directional argument vec.
    /// For Input: position in `input_arguments`. For Output: position in
    /// `output_arguments`. Computed by `FunctionBuilder::build`.
    #[cfg_attr(feature = "serde", serde(skip))]
    #[builder(skip)]
    pub position: u8,

    /// Expression for the buffer's length in bytes.
    pub length: Expression,

    /// Data flow direction for this buffer parameter.
    pub direction: BufferDirection,

    /// Whether the length expression is evaluable from input arguments (Pre)
    /// or output arguments (Post).
    pub phase: BufferPhase,
}

/// Data flow direction for a buffer parameter.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Archive, Serialize, Deserialize)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[rkyv(derive(Debug, PartialEq, Eq))]
pub enum BufferDirection {
    /// Buffer is consumed by the call.
    Input,

    /// Buffer is produced by the call.
    Output,
}

/// When the buffer's length expression is evaluable.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Archive, Serialize, Deserialize)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[rkyv(derive(Debug, PartialEq, Eq))]
pub enum BufferPhase {
    /// Length is known from input arguments (before the call).
    Pre,

    /// Length is known from output arguments (after the call).
    Post,
}

/// Arithmetic expression evaluated against the call's arguments at trace
/// time to compute a buffer's length in bytes.
#[derive(Debug, PartialEq, Eq, Archive, Serialize, Deserialize)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[rkyv(
    derive(Debug, PartialEq, Eq),
    serialize_bounds(
        __S: rkyv::ser::Writer + rkyv::ser::Allocator,
        __S::Error: rkyv::rancor::Source,
    ),
    deserialize_bounds(
        __D::Error: rkyv::rancor::Source
    ),
    bytecheck(bounds(
        __C: rkyv::validation::ArchiveContext,
        __C::Error: rkyv::rancor::Source,
    )
))]
pub enum Expression {
    /// The function's return value, interpreted as `u64`.
    Return,

    /// A literal numeric constant in bytes.
    Constant(u64),

    /// Reference to a parameter by its index in the enclosing function.
    Parameter(u8),

    /// Unary operator applied to one operand.
    UnaryExpression(#[rkyv(omit_bounds)] Box<UnaryExpression>),

    /// Binary operator applied to two operands.
    BinaryExpression(#[rkyv(omit_bounds)] Box<BinaryExpression>),
}

/// Unary operator applied to one operand.
#[derive(Debug, PartialEq, Eq, Builder, Archive, Serialize, Deserialize)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[rkyv(
    derive(Debug, PartialEq, Eq),
    serialize_bounds(
        __S: rkyv::ser::Writer + rkyv::ser::Allocator,
        __S::Error: rkyv::rancor::Source,
    ),
    deserialize_bounds(
        __D::Error: rkyv::rancor::Source
    ),
    bytecheck(bounds(
        __C: rkyv::validation::ArchiveContext,
        __C::Error: rkyv::rancor::Source,
    ))
)]
pub struct UnaryExpression {
    /// Operator applied to the operand.
    pub operator: UnaryOperator,

    /// Operand expression.
    #[rkyv(omit_bounds)]
    pub expression: Expression,
}

/// Binary operator applied to two operands.
#[derive(Debug, PartialEq, Eq, Builder, Archive, Serialize, Deserialize)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[rkyv(
    derive(Debug, PartialEq, Eq),
    serialize_bounds(
        __S: rkyv::ser::Writer + rkyv::ser::Allocator,
        __S::Error: rkyv::rancor::Source,
    ),
    deserialize_bounds(
        __D::Error: rkyv::rancor::Source
    ),
    bytecheck(bounds(
        __C: rkyv::validation::ArchiveContext,
        __C::Error: rkyv::rancor::Source,
    ))
)]
pub struct BinaryExpression {
    /// Operator applied to the operands.
    pub operator: BinaryOperator,

    /// Left-hand operand.
    #[rkyv(omit_bounds)]
    pub lhs: Expression,

    /// Right-hand operand.
    #[rkyv(omit_bounds)]
    pub rhs: Expression,
}

/// Wire-format unary operators. `SizeOf` is intentionally absent - the SAL
/// analyzer resolves `sizeof(IDENT)` to a `Constant` at build time using
/// the architecture-keyed sizeof table, so the wire never sees `SizeOf`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Archive, Serialize, Deserialize)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[rkyv(derive(Debug, PartialEq, Eq))]
pub enum UnaryOperator {
    /// Pointer dereference.
    Dereference,
}

/// Wire-format binary operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Archive, Serialize, Deserialize)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[rkyv(derive(Debug, PartialEq, Eq))]
pub enum BinaryOperator {
    /// Addition.
    Add,

    /// Subtraction.
    Subtract,

    /// Multiplication.
    Multiply,

    /// Division.
    Divide,
}

#[cfg(test)]
mod tests {
    use rkyv::rancor::Error as RkyvError;

    use super::*;

    fn sample_database() -> Database {
        let func = Function::builder()
            .name("ReadFile")
            .parameters(vec![
                Parameter::builder()
                    .name("hFile")
                    .flags(ParameterFlags::HAS_IN_ATTRIBUTE)
                    .ty(Type::builder().name("HANDLE").kind(TypeKind::U64).build())
                    .build(),
                Parameter::builder()
                    .name("lpBuffer")
                    .flags(ParameterFlags::HAS_OUT_ATTRIBUTE)
                    .ty(Type::builder()
                        .indirections(1)
                        .name("BYTE")
                        .kind(TypeKind::U8)
                        .build())
                    .build(),
                Parameter::builder()
                    .name("nBytes")
                    .flags(ParameterFlags::HAS_IN_ATTRIBUTE)
                    .ty(Type::builder().name("DWORD").kind(TypeKind::U32).build())
                    .build(),
                Parameter::builder()
                    .name("lpRead")
                    .flags(ParameterFlags::HAS_OUT_ATTRIBUTE)
                    .ty(Type::builder()
                        .indirections(1)
                        .name("DWORD")
                        .kind(TypeKind::U32)
                        .build())
                    .build(),
            ])
            .buffers(vec![
                Buffer::builder()
                    .parameter(1)
                    .length(Expression::Parameter(2))
                    .direction(BufferDirection::Output)
                    .phase(BufferPhase::Post)
                    .build(),
                Buffer::builder()
                    .parameter(2)
                    .length(Expression::Constant(4))
                    .direction(BufferDirection::Input)
                    .phase(BufferPhase::Pre)
                    .build(),
            ])
            .return_ty(Type::builder().name("BOOL").kind(TypeKind::I32).build())
            .build();

        Database::builder()
            .x86(Metadata::builder().functions(vec![func]).build())
            .x64(Metadata::default())
            .build()
    }

    #[test]
    fn rkyv_round_trip() {
        let db = sample_database();
        let bytes = rkyv::to_bytes::<RkyvError>(&db).expect("serialize");
        let restored = rkyv::from_bytes::<Database, RkyvError>(&bytes).expect("deserialize");
        assert_eq!(restored.x86.functions.len(), 1);
        assert_eq!(restored.x86.functions[0].name, "ReadFile");
        assert_eq!(
            restored.x86.functions[0].parameters[0].name.as_deref(),
            Some("hFile")
        );
        assert!(
            restored.x86.functions[0].parameters[0]
                .flags
                .contains(ParameterFlags::HAS_IN_ATTRIBUTE)
        );
    }

    #[test]
    fn function_builder_bakes_indices() {
        let db = sample_database();
        let func = &db.x86.functions[0];
        assert_eq!(func.output_parameter_indices, vec![1, 3]);
        assert_eq!(func.input_buffer_indices, vec![1]);
        assert_eq!(func.output_buffer_indices, vec![0]);
    }

    #[test]
    fn baked_indices_survive_rkyv_round_trip() {
        let db = sample_database();
        let bytes = rkyv::to_bytes::<RkyvError>(&db).expect("serialize");
        let restored = rkyv::from_bytes::<Database, RkyvError>(&bytes).expect("deserialize");
        let func = &restored.x86.functions[0];
        assert_eq!(func.output_parameter_indices, vec![1, 3]);
        assert_eq!(func.input_buffer_indices, vec![1]);
        assert_eq!(func.output_buffer_indices, vec![0]);
    }
}