hao 0.0.19

Read, edit, create and write .net assemblies
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
//! Coded indexes (ECMA-335 §II.24.2.6): a row index plus a small tag saying
//! which table it points into, packed into one 2- or 4-byte column.
//!
//! Each kind of coded index is an enum implementing [`CodedTokenTarget`]
//! whose variants are the tables it can point into, in tag order. A column
//! of that kind is read as a [`CodedToken`] of the enum.

use std::fmt::Debug;

use strum::{FromRepr, IntoStaticStr};

use crate::{
    dotnet::md::streams::tables_stream::metadata::TableRowCount,
    error::{HaoError, Result},
    io::ReadData,
};

use super::{TableRows, TablesStreamReader, ValueSize};

/// A decoded coded index: which table (`target`) and which row (`rid`).
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct CodedToken<T: CodedTokenTarget> {
    /// 1-based row in the target table; 0 means null.
    pub rid: u32,
    /// The table the row is in.
    pub target: T,
}

impl<T: CodedTokenTarget> CodedToken<T> {
    /// Points at row `rid` of `target`.
    pub fn new(target: T, rid: u32) -> Self {
        Self { rid, target }
    }

    /// Packs into the stored form: `rid` shifted left by the tag width, with the
    /// tag in the low bits.
    pub fn encode(&self) -> u32 {
        (self.rid << T::BITS) | self.target.tag()
    }

    /// Unpacks a stored value. Errors if the tag isn't one of `T`'s tables.
    pub fn decode(coded_value: u32) -> Result<Self> {
        let offset_mask = 0xFFFFFFFF << T::BITS;
        let target_mask = !offset_mask;

        let table_offset = coded_value >> T::BITS;
        let target = coded_value & target_mask;

        Ok(CodedToken {
            rid: table_offset,
            target: T::from_tag(target).ok_or_else(|| {
                HaoError::InvalidCodedToken(coded_value, std::any::type_name::<T>())
            })?,
        })
    }
}

impl<'a, T: CodedTokenTarget> ReadData<CodedToken<T>> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<CodedToken<T>> {
        let coded_value = match T::token_size(&self.header.coded_token_sizes) {
            ValueSize::Big => self.read()?,
            ValueSize::Small => {
                let small: u16 = self.read()?;
                small as u32
            }
        };

        CodedToken::decode(coded_value)
    }
}

/// Whether each kind of coded index is 2 or 4 bytes in this tables stream. A
/// kind is 4 bytes once a table it can point into has too many rows to fit in
/// the 16 bits left after the tag.
#[derive(Debug, Clone, Copy)]
pub struct CodedTokenSizes {
    /// Width of [`TypeDefOrRefToken`] columns.
    pub type_def_or_ref: ValueSize,
    /// Width of [`HasConstantToken`] columns.
    pub has_constant: ValueSize,
    /// Width of [`HasCustomAttributeToken`] columns.
    pub has_custom_attribute: ValueSize,
    /// Width of [`HasFieldMarshalToken`] columns.
    pub has_field_marshal: ValueSize,
    /// Width of [`HasDeclSecurityToken`] columns.
    pub has_decl_security: ValueSize,
    /// Width of [`MemberRefParentToken`] columns.
    pub member_ref_parent: ValueSize,
    /// Width of [`HasSemanticToken`] columns.
    pub has_semantic: ValueSize,
    /// Width of [`MethodDefOrRefToken`] columns.
    pub method_def_or_ref: ValueSize,
    /// Width of [`MemberForwardedToken`] columns.
    pub member_forwarded: ValueSize,
    /// Width of [`ImplementationToken`] columns.
    pub implementation: ValueSize,
    /// Width of [`CustomAttributeTypeToken`] columns.
    pub custom_attribute_type: ValueSize,
    /// Width of [`ResolutionScopeToken`] columns.
    pub resolution_scope: ValueSize,
    /// Width of [`TypeOrMethodDefToken`] columns.
    pub type_or_method_def: ValueSize,
    /// Width of [`HasCustomDebugInformationToken`] columns.
    pub has_custom_debug_information: ValueSize,
}

impl CodedTokenSizes {
    /// Works out every width from the tables' row counts.
    pub fn from_header(rows: &TableRows) -> Self {
        fn size_from_rows(bits: usize, rows: &[TableRowCount]) -> ValueSize {
            let max_row = rows.iter().map(|i| i.0).max().unwrap_or(0);
            if (max_row << bits) > u16::MAX as u32 {
                ValueSize::Big
            } else {
                ValueSize::Small
            }
        }

        Self {
            type_def_or_ref: size_from_rows(
                TypeDefOrRefToken::BITS,
                &[rows.type_def, rows.type_ref, rows.type_spec],
            ),

            has_constant: size_from_rows(
                HasConstantToken::BITS,
                &[rows.field, rows.param, rows.property],
            ),

            has_custom_attribute: size_from_rows(
                HasCustomAttributeToken::BITS,
                &[
                    rows.method,
                    rows.field,
                    rows.type_ref,
                    rows.type_def,
                    rows.param,
                    rows.interface_impl,
                    rows.member_ref,
                    rows.module,
                    rows.decl_security,
                    rows.property,
                    rows.event,
                    rows.stand_alone_sig,
                    rows.module_ref,
                    rows.type_spec,
                    rows.assembly,
                    rows.assembly_ref,
                    rows.file,
                    rows.exported_type,
                    rows.manifest_resource,
                    rows.generic_param,
                    rows.generic_param_constraint,
                    rows.method_spec,
                    rows.module,
                    rows.module,
                ],
            ),

            has_field_marshal: size_from_rows(
                HasFieldMarshalToken::BITS,
                &[rows.field, rows.param],
            ),

            has_decl_security: size_from_rows(
                HasDeclSecurityToken::BITS,
                &[rows.type_def, rows.method, rows.assembly],
            ),

            member_ref_parent: size_from_rows(
                MemberRefParentToken::BITS,
                &[
                    rows.type_def,
                    rows.type_ref,
                    rows.module_ref,
                    rows.method,
                    rows.type_spec,
                ],
            ),

            has_semantic: size_from_rows(HasSemanticToken::BITS, &[rows.event, rows.property]),

            method_def_or_ref: size_from_rows(
                MethodDefOrRefToken::BITS,
                &[rows.method, rows.member_ref],
            ),

            member_forwarded: size_from_rows(
                MemberForwardedToken::BITS,
                &[rows.field, rows.method],
            ),

            implementation: size_from_rows(
                ImplementationToken::BITS,
                &[rows.file, rows.assembly_ref, rows.exported_type],
            ),

            custom_attribute_type: size_from_rows(
                CustomAttributeTypeToken::BITS,
                &[
                    rows.module,
                    rows.module,
                    rows.method,
                    rows.member_ref,
                    rows.module,
                ],
            ),

            resolution_scope: size_from_rows(
                ResolutionScopeToken::BITS,
                &[
                    rows.module,
                    rows.module_ref,
                    rows.assembly_ref,
                    rows.type_ref,
                ],
            ),

            type_or_method_def: size_from_rows(
                TypeOrMethodDefToken::BITS,
                &[rows.type_def, rows.method],
            ),

            has_custom_debug_information: size_from_rows(
                HasCustomDebugInformationToken::BITS,
                &[
                    rows.method,
                    rows.field,
                    rows.type_ref,
                    rows.type_def,
                    rows.param,
                    rows.interface_impl,
                    rows.member_ref,
                    rows.module,
                    rows.decl_security,
                    rows.property,
                    rows.event,
                    rows.stand_alone_sig,
                    rows.module_ref,
                    rows.type_spec,
                    rows.assembly,
                    rows.assembly_ref,
                    rows.file,
                    rows.exported_type,
                    rows.manifest_resource,
                    rows.generic_param,
                    rows.generic_param_constraint,
                    rows.method_spec,
                    rows.document,
                    rows.local_scope,
                    rows.local_variable,
                    rows.local_constant,
                    rows.import_scope,
                ],
            ),
        }
    }
}

/// A kind of coded index: the set of tables it can point into, as an enum
/// whose discriminants are the tags.
pub trait CodedTokenTarget: Sized + Copy {
    /// Number of low bits that hold the tag.
    const BITS: usize;
    /// Width of this kind of column, looked up in `sizes`.
    fn token_size(sizes: &CodedTokenSizes) -> ValueSize;
    /// The table for `tag`, or `None` if the tag is out of range.
    fn from_tag(tag: u32) -> Option<Self>;
    /// The tag of this table.
    fn tag(self) -> u32;
}

/// A coded index to a type: defined here, referenced, or constructed. Used for
/// base types, interfaces, constraints and event types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)]
#[repr(u32)]
pub enum TypeDefOrRefToken {
    /// A type defined in this module.
    TypeDef,
    /// A type from another module or assembly.
    TypeRef,
    /// A constructed type (generic instance, array, pointer).
    TypeSpec,
}
impl CodedTokenTarget for TypeDefOrRefToken {
    fn from_tag(tag: u32) -> Option<Self> {
        Self::from_repr(tag)
    }
    fn tag(self) -> u32 {
        self as u32
    }
    const BITS: usize = 2;
    fn token_size(sizes: &CodedTokenSizes) -> ValueSize {
        sizes.type_def_or_ref
    }
}

/// A coded index to what a Constant row is the default value of.
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)]
#[repr(u32)]
pub enum HasConstantToken {
    /// A field: a `const` or a field with a default.
    Field,
    /// A parameter with a default value.
    Param,
    /// A property with a default value.
    Property,
}
impl CodedTokenTarget for HasConstantToken {
    fn from_tag(tag: u32) -> Option<Self> {
        Self::from_repr(tag)
    }
    fn tag(self) -> u32 {
        self as u32
    }
    const BITS: usize = 2;
    fn token_size(sizes: &CodedTokenSizes) -> ValueSize {
        sizes.has_constant
    }
}

/// A coded index to what a custom attribute is applied to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr, IntoStaticStr)]
#[repr(u32)]
pub enum HasCustomAttributeToken {
    /// A method.
    Method,
    /// A field.
    Field,
    /// A type from another module or assembly.
    TypeRef,
    /// A type defined in this module.
    TypeDef,
    /// A parameter or return value.
    Param,
    /// A type's implementation of an interface.
    InterfaceImpl,
    /// A referenced method or field.
    MemberRef,
    /// This module.
    Module,
    /// A security declaration.
    DeclSecurity,
    /// A property.
    Property,
    /// An event.
    Event,
    /// A standalone signature.
    StandAloneSig,
    /// A referenced module.
    ModuleRef,
    /// A constructed type.
    TypeSpec,
    /// This assembly.
    Assembly,
    /// A referenced assembly.
    AssemblyRef,
    /// A file of this assembly.
    File,
    /// An exported type.
    ExportedType,
    /// A resource.
    ManifestResource,
    /// A generic parameter.
    GenericParam,
    /// A generic parameter constraint.
    GenericParamConstraint,
    /// A generic method instance.
    MethodSpec,
    /// Tag 22, which no table uses.
    Unused1,
    /// Tag 23, which no table uses.
    Unused2,
}
impl CodedTokenTarget for HasCustomAttributeToken {
    fn from_tag(tag: u32) -> Option<Self> {
        Self::from_repr(tag)
    }
    fn tag(self) -> u32 {
        self as u32
    }
    const BITS: usize = 5;
    fn token_size(sizes: &CodedTokenSizes) -> ValueSize {
        sizes.has_custom_attribute
    }
}

/// A coded index to what a FieldMarshal row describes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)]
#[repr(u32)]
pub enum HasFieldMarshalToken {
    /// A field.
    Field,
    /// A parameter or return value.
    Param,
}
impl CodedTokenTarget for HasFieldMarshalToken {
    fn from_tag(tag: u32) -> Option<Self> {
        Self::from_repr(tag)
    }
    fn tag(self) -> u32 {
        self as u32
    }
    const BITS: usize = 1;
    fn token_size(sizes: &CodedTokenSizes) -> ValueSize {
        sizes.has_field_marshal
    }
}

/// A coded index to what a DeclSecurity row applies to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)]
#[repr(u32)]
pub enum HasDeclSecurityToken {
    /// A type defined in this module.
    TypeDef,
    /// A method.
    Method,
    /// This assembly.
    Assembly,
}
impl CodedTokenTarget for HasDeclSecurityToken {
    fn from_tag(tag: u32) -> Option<Self> {
        Self::from_repr(tag)
    }
    fn tag(self) -> u32 {
        self as u32
    }
    const BITS: usize = 2;
    fn token_size(sizes: &CodedTokenSizes) -> ValueSize {
        sizes.has_decl_security
    }
}

/// A coded index to where a MemberRef's member is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)]
#[repr(u32)]
pub enum MemberRefParentToken {
    /// A type defined in this module.
    TypeDef,
    /// A type from another module or assembly.
    TypeRef,
    /// Another module, for its global members.
    ModuleRef,
    /// A vararg method defined here, for a call site that passes extra
    /// arguments.
    Method,
    /// A constructed type, such as a generic instance.
    TypeSpec,
}
impl CodedTokenTarget for MemberRefParentToken {
    fn from_tag(tag: u32) -> Option<Self> {
        Self::from_repr(tag)
    }
    fn tag(self) -> u32 {
        self as u32
    }
    const BITS: usize = 3;
    fn token_size(sizes: &CodedTokenSizes) -> ValueSize {
        sizes.member_ref_parent
    }
}

/// A coded index to the event or property of a MethodSemantics row.
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)]
#[repr(u32)]
pub enum HasSemanticToken {
    /// An event.
    Event,
    /// A property.
    Property,
}
impl CodedTokenTarget for HasSemanticToken {
    fn from_tag(tag: u32) -> Option<Self> {
        Self::from_repr(tag)
    }
    fn tag(self) -> u32 {
        self as u32
    }
    const BITS: usize = 1;
    fn token_size(sizes: &CodedTokenSizes) -> ValueSize {
        sizes.has_semantic
    }
}

/// A coded index to a method: defined here or referenced.
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)]
#[repr(u32)]
pub enum MethodDefOrRefToken {
    /// A method defined in this module.
    Method,
    /// A referenced method.
    MemberRef,
}
impl CodedTokenTarget for MethodDefOrRefToken {
    fn from_tag(tag: u32) -> Option<Self> {
        Self::from_repr(tag)
    }
    fn tag(self) -> u32 {
        self as u32
    }
    const BITS: usize = 1;
    fn token_size(sizes: &CodedTokenSizes) -> ValueSize {
        sizes.method_def_or_ref
    }
}

/// A coded index to the member an ImplMap (P/Invoke) row describes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)]
#[repr(u32)]
pub enum MemberForwardedToken {
    /// A field. The encoding allows it, but only methods are P/Invoke.
    Field,
    /// A method.
    Method,
}
impl CodedTokenTarget for MemberForwardedToken {
    fn from_tag(tag: u32) -> Option<Self> {
        Self::from_repr(tag)
    }
    fn tag(self) -> u32 {
        self as u32
    }
    const BITS: usize = 1;
    fn token_size(sizes: &CodedTokenSizes) -> ValueSize {
        sizes.member_forwarded
    }
}

/// A coded index to where an exported type or resource actually is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)]
#[repr(u32)]
pub enum ImplementationToken {
    /// Another file of this assembly.
    File,
    /// Another assembly.
    AssemblyRef,
    /// The enclosing exported type, for a nested exported type.
    ExportedType,
}
impl CodedTokenTarget for ImplementationToken {
    fn from_tag(tag: u32) -> Option<Self> {
        Self::from_repr(tag)
    }
    fn tag(self) -> u32 {
        self as u32
    }
    const BITS: usize = 2;
    fn token_size(sizes: &CodedTokenSizes) -> ValueSize {
        sizes.implementation
    }
}

/// A coded index to the constructor a custom attribute calls.
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)]
#[repr(u32)]
pub enum CustomAttributeTypeToken {
    /// Tag 0, which no table uses.
    Unused1,
    /// Tag 1, which no table uses.
    Unused2,
    /// A constructor defined in this module.
    Method,
    /// A referenced constructor.
    MemberRef,
    /// Tag 4, which no table uses.
    Unused3,
}
impl CodedTokenTarget for CustomAttributeTypeToken {
    fn from_tag(tag: u32) -> Option<Self> {
        Self::from_repr(tag)
    }
    fn tag(self) -> u32 {
        self as u32
    }
    const BITS: usize = 3;
    fn token_size(sizes: &CodedTokenSizes) -> ValueSize {
        sizes.custom_attribute_type
    }
}

/// A coded index to where a TypeRef's type is defined.
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)]
#[repr(u32)]
pub enum ResolutionScopeToken {
    /// This module.
    Module,
    /// Another module of this assembly.
    ModuleRef,
    /// Another assembly.
    AssemblyRef,
    /// The enclosing type, for a nested type.
    TypeRef,
}
impl CodedTokenTarget for ResolutionScopeToken {
    fn from_tag(tag: u32) -> Option<Self> {
        Self::from_repr(tag)
    }
    fn tag(self) -> u32 {
        self as u32
    }
    const BITS: usize = 2;
    #[inline(always)]
    fn token_size(sizes: &CodedTokenSizes) -> ValueSize {
        sizes.resolution_scope
    }
}

/// A coded index to the owner of a generic parameter.
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)]
#[repr(u32)]
pub enum TypeOrMethodDefToken {
    /// A generic type.
    TypeDef,
    /// A generic method.
    Method,
}
impl CodedTokenTarget for TypeOrMethodDefToken {
    fn from_tag(tag: u32) -> Option<Self> {
        Self::from_repr(tag)
    }
    fn tag(self) -> u32 {
        self as u32
    }
    const BITS: usize = 1;
    fn token_size(sizes: &CodedTokenSizes) -> ValueSize {
        sizes.type_or_method_def
    }
}

/// A coded index to what a Portable PDB CustomDebugInformation row is attached
/// to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)]
#[repr(u32)]
pub enum HasCustomDebugInformationToken {
    /// A method.
    Method,
    /// A field.
    Field,
    /// A type from another module or assembly.
    TypeRef,
    /// A type defined in this module.
    TypeDef,
    /// A parameter or return value.
    Param,
    /// A type's implementation of an interface.
    InterfaceImpl,
    /// A referenced method or field.
    MemberRef,
    /// This module.
    Module,
    /// A security declaration.
    DeclSecurity,
    /// A property.
    Property,
    /// An event.
    Event,
    /// A standalone signature.
    StandAloneSig,
    /// A referenced module.
    ModuleRef,
    /// A constructed type.
    TypeSpec,
    /// This assembly.
    Assembly,
    /// A referenced assembly.
    AssemblyRef,
    /// A file of this assembly.
    File,
    /// An exported type.
    ExportedType,
    /// A resource.
    ManifestResource,
    /// A generic parameter.
    GenericParam,
    /// A generic parameter constraint.
    GenericParamConstraint,
    /// A generic method instance.
    MethodSpec,
    /// A source document.
    Document,
    /// A local scope.
    LocalScope,
    /// A local variable.
    LocalVariable,
    /// A local constant.
    LocalConstant,
    /// An import scope.
    ImportScope,
}
impl CodedTokenTarget for HasCustomDebugInformationToken {
    fn from_tag(tag: u32) -> Option<Self> {
        Self::from_repr(tag)
    }
    fn tag(self) -> u32 {
        self as u32
    }
    const BITS: usize = 5;
    fn token_size(sizes: &CodedTokenSizes) -> ValueSize {
        sizes.has_custom_debug_information
    }
}