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
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
//! Read-only schema for the metadata.

mod asbits;
pub mod model;

use uuid::Uuid;

pub use crate::model::ParameterFlags;
use crate::model::{
    ArchivedBinaryExpression, ArchivedBinaryOperator, ArchivedBuffer, ArchivedBufferDirection,
    ArchivedBufferPhase, ArchivedDatabase, ArchivedExpression, ArchivedFunction, ArchivedInterface,
    ArchivedMetadata, ArchivedParameter, ArchivedType, ArchivedTypeKind, ArchivedUnaryExpression,
    ArchivedUnaryOperator,
};

/// CPU architecture used as the database key.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[expect(missing_docs, reason = "self-explanatory")]
pub enum Architecture {
    X86,
    X64,
}

/// Read-only handle to an archived [`model::Database`].
#[derive(Debug, Clone, Copy)]
pub struct Database<'a> {
    inner: &'a ArchivedDatabase,
}

impl<'a> Database<'a> {
    /// Validates `data` as an rkyv archive and returns a typed handle.
    pub fn from_bytes(data: &'a [u8]) -> Result<Self, rkyv::rancor::Error> {
        let inner = rkyv::access(data)?;
        Ok(Self { inner })
    }

    /// Returns a handle to `data` without validating its archive structure.
    ///
    /// # Safety
    ///
    /// Caller must ensure that `data` is a valid rkyv archive of the expected
    /// format.
    pub unsafe fn from_bytes_unchecked(data: &'a [u8]) -> Self {
        let inner = unsafe { rkyv::access_unchecked(data) };
        Self { inner }
    }

    /// Returns the [`Metadata`] bucket for the requested architecture.
    pub fn bucket(&self, arch: Architecture) -> Metadata<'a> {
        match arch {
            Architecture::X86 => self.x86(),
            Architecture::X64 => self.x64(),
        }
    }

    /// Returns the x86 metadata bucket.
    pub fn x86(&self) -> Metadata<'a> {
        Metadata {
            inner: &self.inner.x86,
        }
    }

    /// Returns the x64 metadata bucket.
    pub fn x64(&self) -> Metadata<'a> {
        Metadata {
            inner: &self.inner.x64,
        }
    }
}

/// Read-only handle to one architecture's metadata.
#[derive(Debug)]
pub struct Metadata<'a> {
    inner: &'a ArchivedMetadata,
}

impl<'a> Metadata<'a> {
    /// Iterates all functions in this bucket, in name-sorted order.
    pub fn functions(&self) -> impl ExactSizeIterator<Item = Function<'a>> {
        self.inner.functions.iter().map(|inner| Function { inner })
    }

    /// Iterates all COM interfaces in this bucket, in name-sorted order.
    pub fn interfaces(&self) -> impl ExactSizeIterator<Item = Interface<'a>> {
        self.inner
            .interfaces
            .iter()
            .map(|inner| Interface { inner })
    }

    /// Looks up a function by name.
    pub fn function(&self, name: impl AsRef<str>) -> Option<Function<'a>> {
        self.inner
            .functions_by_name
            .get(name.as_ref())
            .map(|index| {
                let index = index.to_native() as usize;
                Function {
                    inner: &self.inner.functions[index],
                }
            })
    }

    /// Looks up a COM interface by name.
    pub fn interface(&self, name: impl AsRef<str>) -> Option<Interface<'a>> {
        self.inner
            .interfaces_by_name
            .get(name.as_ref())
            .map(|index| {
                let index = index.to_native() as usize;
                Interface {
                    inner: &self.inner.interfaces[index],
                }
            })
    }

    /// Looks up a COM interface by UUID.
    pub fn interface_by_uuid(&self, uuid: Uuid) -> Option<Interface<'a>> {
        self.inner.interfaces_by_uuid.get(&uuid).map(|index| {
            let index = index.to_native() as usize;
            Interface {
                inner: &self.inner.interfaces[index],
            }
        })
    }
}

/// Read-only handle to a monitored function or COM method.
#[derive(Debug, Clone, Copy)]
pub struct Function<'a> {
    inner: &'a ArchivedFunction,
}

impl<'a> Function<'a> {
    /// Returns the function name.
    pub fn name(&self) -> &'a str {
        &self.inner.name
    }

    /// Iterates over all parameters in declaration order.
    pub fn parameters(&self) -> impl ExactSizeIterator<Item = Parameter<'a>> {
        self.inner
            .parameters
            .iter()
            .enumerate()
            .map(|(index, inner)| Parameter {
                index,
                inner,
                ty: Type {
                    repr: TypeRepr::Archived(&inner.ty),
                },
            })
    }

    /// Iterates over the parameters as seen at function entry.
    ///
    /// Output-only parameters (`HAS_OUT && !HAS_IN`) get a synthetic
    /// `void *` type so the consumer records the pointer value without
    /// dereferencing the uninitialized pointee.
    pub fn input_parameters(&self) -> impl ExactSizeIterator<Item = Parameter<'a>> {
        self.inner
            .parameters
            .iter()
            .enumerate()
            .map(|(index, inner)| {
                let flags = ParameterFlags::from_bits_retain(inner.flags);
                let is_output_only = flags.contains(ParameterFlags::HAS_OUT_ATTRIBUTE)
                    && !flags.contains(ParameterFlags::HAS_IN_ATTRIBUTE);

                Parameter {
                    index,
                    inner,
                    ty: Type {
                        repr: if is_output_only {
                            TypeRepr::VoidPointer
                        }
                        else {
                            TypeRepr::Archived(&inner.ty)
                        },
                    },
                }
            })
    }

    /// Iterates over parameters with `HAS_OUT_ATTRIBUTE`.
    pub fn output_parameters(&self) -> impl ExactSizeIterator<Item = Parameter<'a>> {
        let inner = self.inner;
        inner.output_parameter_indices.iter().map(move |index| {
            let index = *index as usize;
            let archived = &inner.parameters[index];
            Parameter {
                index,
                inner: archived,
                ty: Type {
                    repr: TypeRepr::Archived(&archived.ty),
                },
            }
        })
    }

    /// Iterates over all buffer descriptions.
    pub fn buffers(&self) -> impl ExactSizeIterator<Item = Buffer<'a>> {
        self.inner.buffers.iter().map(|inner| Buffer { inner })
    }

    /// Iterates over input-direction buffers.
    pub fn input_buffers(&self) -> impl ExactSizeIterator<Item = Buffer<'a>> {
        let inner = self.inner;
        inner.input_buffer_indices.iter().map(move |index| {
            let index = *index as usize;
            Buffer {
                inner: &inner.buffers[index],
            }
        })
    }

    /// Iterates over output-direction buffers.
    pub fn output_buffers(&self) -> impl ExactSizeIterator<Item = Buffer<'a>> {
        let inner = self.inner;
        inner.output_buffer_indices.iter().map(move |index| {
            let index = *index as usize;
            Buffer {
                inner: &inner.buffers[index],
            }
        })
    }

    /// Returns the function's return type.
    pub fn return_ty(&self) -> Type<'a> {
        Type {
            repr: TypeRepr::Archived(&self.inner.return_ty),
        }
    }
}

/// Read-only handle to a COM interface.
#[derive(Debug, Clone, Copy)]
pub struct Interface<'a> {
    inner: &'a ArchivedInterface,
}

impl<'a> Interface<'a> {
    /// Returns the interface name.
    pub fn name(&self) -> &'a str {
        &self.inner.name
    }

    /// Returns the interface UUID.
    pub fn uuid(&self) -> Uuid {
        self.inner.uuid
    }

    /// Returns the base interface name, if any.
    pub fn base(&self) -> Option<&'a str> {
        self.inner.base.as_deref()
    }

    /// Iterates over the interface's methods.
    pub fn methods(&self) -> impl ExactSizeIterator<Item = Function<'a>> {
        self.inner.methods.iter().map(|inner| Function { inner })
    }
}

/// Read-only handle to one function or method parameter.
#[derive(Debug, Clone, Copy)]
pub struct Parameter<'a> {
    index: usize,
    inner: &'a ArchivedParameter,
    ty: Type<'a>,
}

impl<'a> Parameter<'a> {
    /// Returns the parameter's position in the enclosing function.
    pub fn index(&self) -> usize {
        self.index
    }

    /// Returns the parameter name, if declared.
    pub fn name(&self) -> Option<&'a str> {
        self.inner.name.as_deref()
    }

    /// Returns the SAL-derived directionality flags.
    pub fn flags(&self) -> ParameterFlags {
        ParameterFlags::from_bits_retain(self.inner.flags)
    }

    /// Returns the parameter's type.
    pub fn ty(&self) -> Type<'a> {
        self.ty
    }
}

/// Storage backing for [`Type`].
#[derive(Debug, Clone, Copy)]
enum TypeRepr<'a> {
    /// Real type from the archive.
    Archived(&'a ArchivedType),

    /// Synthetic `void *` substituted for output-only parameters.
    VoidPointer,
}

/// Read-only type signature for a parameter or return value.
#[derive(Debug, Clone, Copy)]
pub struct Type<'a> {
    repr: TypeRepr<'a>,
}

impl<'a> Type<'a> {
    /// Returns the pointer or reference depth.
    pub fn indirections(&self) -> usize {
        match self.repr {
            TypeRepr::Archived(inner) => inner.indirections as usize,
            TypeRepr::VoidPointer => 1,
        }
    }

    /// Returns the leaf type's source-spelling.
    pub fn name(&self) -> &'a str {
        match self.repr {
            TypeRepr::Archived(inner) => &inner.name,
            TypeRepr::VoidPointer => "void",
        }
    }

    /// Returns the leaf primitive kind.
    pub fn kind(&self) -> TypeKind {
        match self.repr {
            TypeRepr::Archived(inner) => TypeKind::from_archived(&inner.kind),
            TypeRepr::VoidPointer => TypeKind::Void,
        }
    }
}

/// Primitive kind of a leaf type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[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),
}

impl TypeKind {
    fn from_archived(value: &ArchivedTypeKind) -> Self {
        match value {
            ArchivedTypeKind::Unknown => Self::Unknown,
            ArchivedTypeKind::Void => Self::Void,
            ArchivedTypeKind::Bool => Self::Bool,
            ArchivedTypeKind::Char8 => Self::Char8,
            ArchivedTypeKind::Char16 => Self::Char16,
            ArchivedTypeKind::I8 => Self::I8,
            ArchivedTypeKind::I16 => Self::I16,
            ArchivedTypeKind::I32 => Self::I32,
            ArchivedTypeKind::I64 => Self::I64,
            ArchivedTypeKind::U8 => Self::U8,
            ArchivedTypeKind::U16 => Self::U16,
            ArchivedTypeKind::U32 => Self::U32,
            ArchivedTypeKind::U64 => Self::U64,
            ArchivedTypeKind::F32 => Self::F32,
            ArchivedTypeKind::F64 => Self::F64,
            ArchivedTypeKind::Custom(inner) => Self::Custom(*inner),
        }
    }
}

/// Read-only handle to a per-call buffer description.
#[derive(Debug, Clone, Copy)]
pub struct Buffer<'a> {
    inner: &'a ArchivedBuffer,
}

impl<'a> Buffer<'a> {
    /// Returns the index of the parameter that holds this buffer.
    pub fn parameter(&self) -> usize {
        self.inner.parameter as usize
    }

    /// Returns the buffer's position in the directional argument vec.
    pub fn position(&self) -> usize {
        self.inner.position as usize
    }

    /// Returns the buffer's length expression.
    pub fn length(&self) -> Expression<'a> {
        Expression::from_archived(&self.inner.length)
    }

    /// Returns the buffer's data flow direction.
    pub fn direction(&self) -> BufferDirection {
        BufferDirection::from_archived(&self.inner.direction)
    }

    /// Returns when the length expression is evaluable.
    pub fn phase(&self) -> BufferPhase {
        BufferPhase::from_archived(&self.inner.phase)
    }
}

/// Data flow direction for a buffer parameter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BufferDirection {
    /// Buffer is consumed by the call.
    Input,

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

impl BufferDirection {
    fn from_archived(value: &ArchivedBufferDirection) -> Self {
        match value {
            ArchivedBufferDirection::Input => Self::Input,
            ArchivedBufferDirection::Output => Self::Output,
        }
    }
}

/// When a buffer's length expression becomes evaluable.
#[derive(Debug, Clone, Copy, 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,
}

impl BufferPhase {
    fn from_archived(value: &ArchivedBufferPhase) -> Self {
        match value {
            ArchivedBufferPhase::Pre => Self::Pre,
            ArchivedBufferPhase::Post => Self::Post,
        }
    }
}

/// Arithmetic expression evaluated at trace time to compute a buffer's
/// length in bytes.
#[derive(Debug, Clone, Copy)]
pub enum Expression<'a> {
    /// 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(usize),

    /// Unary operator applied to one operand.
    UnaryExpression(UnaryExpression<'a>),

    /// Binary operator applied to two operands.
    BinaryExpression(BinaryExpression<'a>),
}

impl<'a> Expression<'a> {
    fn from_archived(value: &'a ArchivedExpression) -> Self {
        match value {
            ArchivedExpression::Return => Self::Return,
            ArchivedExpression::Constant(inner) => Self::Constant(inner.to_native()),
            ArchivedExpression::Parameter(inner) => Self::Parameter(*inner as usize),
            ArchivedExpression::UnaryExpression(inner) => {
                Self::UnaryExpression(UnaryExpression { inner })
            }
            ArchivedExpression::BinaryExpression(inner) => {
                Self::BinaryExpression(BinaryExpression { inner })
            }
        }
    }
}

/// Read-only handle to a unary operator and its operand.
#[derive(Debug, Clone, Copy)]
pub struct UnaryExpression<'a> {
    inner: &'a ArchivedUnaryExpression,
}

impl<'a> UnaryExpression<'a> {
    /// Returns the unary operator.
    pub fn operator(&self) -> UnaryOperator {
        UnaryOperator::from_archived(&self.inner.operator)
    }

    /// Returns the operand expression.
    pub fn expression(&self) -> Expression<'a> {
        Expression::from_archived(&self.inner.expression)
    }
}

/// Read-only handle to a binary operator and its two operands.
#[derive(Debug, Clone, Copy)]
pub struct BinaryExpression<'a> {
    inner: &'a ArchivedBinaryExpression,
}

impl<'a> BinaryExpression<'a> {
    /// Returns the binary operator.
    pub fn operator(&self) -> BinaryOperator {
        BinaryOperator::from_archived(&self.inner.operator)
    }

    /// Returns the left-hand operand.
    pub fn lhs(&self) -> Expression<'a> {
        Expression::from_archived(&self.inner.lhs)
    }

    /// Returns the right-hand operand.
    pub fn rhs(&self) -> Expression<'a> {
        Expression::from_archived(&self.inner.rhs)
    }
}

/// Wire-format unary operator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnaryOperator {
    /// Pointer dereference.
    Dereference,
}

impl UnaryOperator {
    fn from_archived(value: &ArchivedUnaryOperator) -> Self {
        match value {
            ArchivedUnaryOperator::Dereference => Self::Dereference,
        }
    }
}

/// Wire-format binary operator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinaryOperator {
    /// Addition.
    Add,

    /// Subtraction.
    Subtract,

    /// Multiplication.
    Multiply,

    /// Division.
    Divide,
}

impl BinaryOperator {
    fn from_archived(value: &ArchivedBinaryOperator) -> Self {
        match value {
            ArchivedBinaryOperator::Add => Self::Add,
            ArchivedBinaryOperator::Subtract => Self::Subtract,
            ArchivedBinaryOperator::Multiply => Self::Multiply,
            ArchivedBinaryOperator::Divide => Self::Divide,
        }
    }
}

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

    use super::*;
    use crate::model;

    fn archive_with_function(function: model::Function) -> Vec<u8> {
        let db = model::Database::builder()
            .x86(model::Metadata::builder().functions(vec![function]).build())
            .x64(model::Metadata::default())
            .build();
        rkyv::to_bytes::<RkyvError>(&db)
            .expect("serialize")
            .to_vec()
    }

    fn sample_function() -> model::Function {
        model::Function::builder()
            .name("Func")
            .parameters(vec![
                model::Parameter::builder()
                    .name("p_in")
                    .flags(model::ParameterFlags::HAS_IN_ATTRIBUTE)
                    .ty(model::Type::builder()
                        .indirections(1)
                        .name("DWORD")
                        .kind(model::TypeKind::U32)
                        .build())
                    .build(),
                model::Parameter::builder()
                    .name("p_out")
                    .flags(model::ParameterFlags::HAS_OUT_ATTRIBUTE)
                    .ty(model::Type::builder()
                        .indirections(1)
                        .name("DWORD")
                        .kind(model::TypeKind::U32)
                        .build())
                    .build(),
                model::Parameter::builder()
                    .name("p_inout")
                    .flags(
                        model::ParameterFlags::HAS_IN_ATTRIBUTE
                            | model::ParameterFlags::HAS_OUT_ATTRIBUTE,
                    )
                    .ty(model::Type::builder()
                        .indirections(1)
                        .name("DWORD")
                        .kind(model::TypeKind::U32)
                        .build())
                    .build(),
            ])
            .return_ty(
                model::Type::builder()
                    .name("BOOL")
                    .kind(model::TypeKind::I32)
                    .build(),
            )
            .build()
    }

    #[test]
    fn input_parameters_substitutes_void_pointer_for_output_only() {
        let bytes = archive_with_function(sample_function());
        let db = Database::from_bytes(&bytes).expect("open");
        let func = db.x86().function("Func").expect("Func");

        let params = func.input_parameters().collect::<Vec<_>>();
        assert_eq!(params.len(), 3);

        // p_in: input, real type preserved.
        assert_eq!(params[0].name(), Some("p_in"));
        assert_eq!(params[0].ty().name(), "DWORD");
        assert_eq!(params[0].ty().kind(), TypeKind::U32);
        assert_eq!(params[0].ty().indirections(), 1);

        // p_out: output-only, substituted to `void *`.
        assert_eq!(params[1].name(), Some("p_out"));
        assert_eq!(params[1].ty().name(), "void");
        assert_eq!(params[1].ty().kind(), TypeKind::Void);
        assert_eq!(params[1].ty().indirections(), 1);

        // p_inout: HAS_IN suppresses substitution. Real type preserved.
        assert_eq!(params[2].name(), Some("p_inout"));
        assert_eq!(params[2].ty().name(), "DWORD");
        assert_eq!(params[2].ty().kind(), TypeKind::U32);
        assert_eq!(params[2].ty().indirections(), 1);
    }

    #[test]
    fn parameters_keeps_original_type_for_output_only() {
        let bytes = archive_with_function(sample_function());
        let db = Database::from_bytes(&bytes).expect("open");
        let func = db.x86().function("Func").expect("Func");

        let params = func.parameters().collect::<Vec<_>>();
        assert_eq!(params.len(), 3);

        // p_out: parameters() does not substitute - real type is exposed.
        assert_eq!(params[1].name(), Some("p_out"));
        assert_eq!(params[1].ty().name(), "DWORD");
        assert_eq!(params[1].ty().kind(), TypeKind::U32);
        assert_eq!(params[1].ty().indirections(), 1);
    }
}