/
mod.rs
1640 lines (1546 loc) · 64 KB
/
mod.rs
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
mod blob;
mod codes;
mod file;
mod guid;
mod row;
mod tree;
mod r#type;
mod type_name;
use super::*;
pub use blob::*;
pub use codes::*;
pub use file::*;
pub use guid::*;
pub use r#type::*;
pub use row::*;
pub use tree::*;
pub use type_name::*;
macro_rules! tables {
($($name:ident,)*) => ($(
#[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub struct $name(pub Row);
)*)
}
tables! {
Attribute,
ClassLayout,
Constant,
Field,
GenericParam,
ImplMap,
InterfaceImpl,
MemberRef,
MethodDef,
ModuleRef,
Param,
TypeDef,
TypeRef,
TypeSpec,
}
#[derive(Copy, Clone, Eq, PartialEq)]
pub enum ArrayInfo {
Fixed(usize),
RelativeLen(usize),
RelativeByteLen(usize),
RelativePtr(usize),
None,
Removed,
}
#[derive(Clone, PartialEq, PartialOrd, Eq, Ord)]
pub struct Interface {
pub ty: Type,
pub kind: InterfaceKind,
}
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq, Ord)]
pub enum InterfaceKind {
None,
Default,
Overridable,
Static,
Composable,
Base,
}
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct QueryPosition {
pub object: usize,
pub guid: usize,
}
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum SignatureKind {
Query(QueryPosition),
QueryOptional(QueryPosition),
ResultValue,
ResultVoid,
ReturnStruct,
ReturnVoid,
PreserveSig,
}
#[derive(PartialEq, Eq)]
pub enum AsyncKind {
None,
Action,
ActionWithProgress,
Operation,
OperationWithProgress,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, PartialOrd, Ord)]
pub enum TypeKind {
Interface,
Class,
Enum,
Struct,
Delegate,
}
pub enum Value {
Bool(bool),
U8(u8),
I8(i8),
U16(u16),
I16(i16),
U32(u32),
I32(i32),
U64(u64),
I64(i64),
F32(f32),
F64(f64),
String(String),
TypeDef(TypeDef),
}
pub struct Signature {
pub def: MethodDef,
pub params: Vec<SignatureParam>,
pub return_type: Option<Type>,
}
pub struct SignatureParam {
pub def: Param,
pub ty: Type,
pub array_info: ArrayInfo,
}
#[derive(Default, Clone)]
pub struct Cfg<'a> {
pub types: BTreeMap<&'a str, BTreeSet<TypeDef>>,
pub arches: BTreeSet<&'static str>,
}
impl<'a> Cfg<'a> {
pub fn add_feature(&mut self, feature: &'a str) {
self.types.entry(feature).or_default();
}
pub fn union(&self, other: &Self) -> Self {
let mut union = Self::default();
self.types.keys().for_each(|feature| {
union.types.entry(feature).or_default();
});
other.types.keys().for_each(|feature| {
union.types.entry(feature).or_default();
});
self.arches.iter().for_each(|arch| {
union.arches.insert(arch);
});
other.arches.iter().for_each(|arch| {
union.arches.insert(arch);
});
union
}
}
pub struct Reader<'a> {
files: &'a [File],
types: HashMap<&'a str, BTreeMap<&'a str, Vec<TypeDef>>>,
nested: HashMap<TypeDef, BTreeMap<&'a str, TypeDef>>,
}
impl<'a> Reader<'a> {
pub fn new(files: &'a [File]) -> Self {
let mut types = HashMap::<&'a str, BTreeMap<&'a str, Vec<TypeDef>>>::new();
let mut nested = HashMap::<TypeDef, BTreeMap<&'a str, TypeDef>>::new();
for (file_index, file) in files.iter().enumerate() {
for row in 0..file.tables[TABLE_TYPEDEF].len {
let key = Row::new(row, TABLE_TYPEDEF, file_index);
let namespace = file.str(key.row as _, key.table as _, 2);
let name = trim_tick(file.str(key.row as _, key.table as _, 1));
types.entry(namespace).or_default().entry(name).or_default().push(TypeDef(key));
}
for row in 0..file.tables[TABLE_NESTEDCLASS].len {
let key = Row::new(row, TABLE_NESTEDCLASS, file_index);
let inner = Row::new(file.usize(key.row as _, key.table as _, 0) - 1, TABLE_TYPEDEF, file_index);
let outer = Row::new(file.usize(key.row as _, key.table as _, 1) - 1, TABLE_TYPEDEF, file_index);
let name = file.str(inner.row as _, inner.table as _, 1);
nested.entry(TypeDef(outer)).or_default().insert(name, TypeDef(inner));
}
}
Self { files, types, nested }
}
pub fn tree(&'a self, root: &'a str, exclude: &[&str]) -> Option<Tree> {
let mut tree = Tree::from_namespace("");
for ns in self.types.keys() {
if !exclude.iter().any(|x| ns.starts_with(x)) {
tree.insert_namespace(ns, 0);
}
}
tree.seek(root)
}
//
// Hash functions for fast type lookup
//
pub fn namespace_types(&self, namespace: &str) -> impl Iterator<Item = TypeDef> + '_ {
self.types.get(namespace).map(|types| types.values().flatten().copied()).into_iter().flatten()
}
pub fn nested_types(&self, type_def: TypeDef) -> impl Iterator<Item = TypeDef> + '_ {
self.nested.get(&type_def).map(|map| map.values().copied()).into_iter().flatten()
}
pub fn get(&self, type_name: TypeName) -> impl Iterator<Item = TypeDef> + '_ {
if let Some(types) = self.types.get(type_name.namespace) {
if let Some(definitions) = types.get(type_name.name) {
return Some(definitions.iter().copied()).into_iter().flatten();
}
}
None.into_iter().flatten()
}
//
// Row functions providing low-level file access
//
fn row_usize(&self, key: Row, column: usize) -> usize {
self.files[key.file as usize].usize(key.row as _, key.table as _, column)
}
fn row_str(&self, key: Row, column: usize) -> &str {
self.files[key.file as usize].str(key.row as _, key.table as _, column)
}
pub fn row_blob(&self, key: Row, column: usize) -> Blob {
let file = key.file as usize;
Blob::new(file, self.files[file].blob(key.row as _, key.table as _, column))
}
fn row_equal_range(&self, key: Row, table: usize, column: usize, value: usize) -> impl Iterator<Item = Row> {
let (first, last) = self.files[key.file as usize].equal_range(table, column, value);
(first..last).map(move |row| Row::new(row, table, key.file as _))
}
fn row_attributes(&self, key: Row, source: HasAttribute) -> impl Iterator<Item = Attribute> {
self.row_equal_range(key, TABLE_CUSTOMATTRIBUTE, 0, source.encode()).map(Attribute)
}
fn row_list(&self, key: Row, table: usize, column: usize) -> impl Iterator<Item = Row> {
let file = key.file as usize;
let first = self.row_usize(key, column) - 1;
let last = if key.row + 1 < self.files[file].tables[key.table as usize].len as _ { self.row_usize(key.next(), column) - 1 } else { self.files[file].tables[table].len };
(first..last).map(move |row| Row::new(row, table, file))
}
fn row_decode<T: Decode>(&self, key: Row, column: usize) -> T {
T::decode(key.file as _, self.row_usize(key, column))
}
//
// Attribute table queries
//
pub fn attribute_name(&self, row: Attribute) -> &str {
let AttributeType::MemberRef(row) = self.row_decode(row.0, 1);
let MemberRefParent::TypeRef(row) = self.row_decode(row.0, 0);
self.type_ref_name(row)
}
pub fn attribute_args(&self, row: Attribute) -> Vec<(String, Value)> {
let AttributeType::MemberRef(member) = self.row_decode(row.0, 1);
let mut sig = self.member_ref_signature(member);
let mut values = self.row_blob(row.0, 2);
let _prolog = values.read_u16();
let _this_and_gen_param_count = sig.read_usize();
let fixed_arg_count = sig.read_usize();
let _ret_type = sig.read_usize();
let mut args: Vec<(String, Value)> = Vec::with_capacity(fixed_arg_count as usize);
for _ in 0..fixed_arg_count {
let arg = match self.type_from_blob(&mut sig, None, &[]).expect("Type not found") {
Type::I8 => Value::I8(values.read_i8()),
Type::U8 => Value::U8(values.read_u8()),
Type::I16 => Value::I16(values.read_i16()),
Type::U16 => Value::U16(values.read_u16()),
Type::I32 => Value::I32(values.read_i32()),
Type::U32 => Value::U32(values.read_u32()),
Type::I64 => Value::I64(values.read_i64()),
Type::U64 => Value::U64(values.read_u64()),
Type::String => Value::String(values.read_str().to_string()),
Type::TypeName => Value::TypeDef(self.get(TypeName::parse(values.read_str())).next().expect("Type not found")),
Type::TypeDef((def, _)) => match self.type_def_underlying_type(def) {
Type::I8 => Value::I8(values.read_i8()),
Type::U8 => Value::U8(values.read_u8()),
Type::I16 => Value::I16(values.read_i16()),
Type::U16 => Value::U16(values.read_u16()),
Type::I32 => Value::I32(values.read_i32()),
Type::U32 => Value::U32(values.read_u32()),
Type::I64 => Value::I64(values.read_i64()),
Type::U64 => Value::U64(values.read_u64()),
_ => unimplemented!(),
},
_ => unimplemented!(),
};
args.push((String::new(), arg));
}
let named_arg_count = values.read_u16();
args.reserve(named_arg_count as usize);
for _ in 0..named_arg_count {
let _id = values.read_u8();
let arg_type = values.read_u8();
let name = values.read_str().to_string();
let arg = match arg_type {
0x02 => Value::Bool(values.read_u8() != 0),
0x06 => Value::I16(values.read_i16()),
0x08 => Value::I32(values.read_i32()),
0x09 => Value::U32(values.read_u32()),
0x0E => Value::String(values.read_str().to_string()),
0x50 => Value::TypeDef(self.get(TypeName::parse(values.read_str())).next().expect("Type not found")),
_ => unimplemented!(),
};
args.push((name, arg));
}
args
}
//
// ClassLayout table queries
//
pub fn class_layout_packing_size(&self, row: ClassLayout) -> usize {
self.row_usize(row.0, 0)
}
//
// Constant table queries
//
pub fn constant_type(&self, row: Constant) -> Type {
let code = self.row_usize(row.0, 0);
Type::from_code(code).expect("Type not found")
}
pub fn constant_value(&self, row: Constant) -> Value {
let mut blob = self.row_blob(row.0, 2);
match self.constant_type(row) {
Type::I8 => Value::I8(blob.read_i8()),
Type::U8 => Value::U8(blob.read_u8()),
Type::I16 => Value::I16(blob.read_i16()),
Type::U16 => Value::U16(blob.read_u16()),
Type::I32 => Value::I32(blob.read_i32()),
Type::U32 => Value::U32(blob.read_u32()),
Type::I64 => Value::I64(blob.read_i64()),
Type::U64 => Value::U64(blob.read_u64()),
Type::F32 => Value::F32(blob.read_f32()),
Type::F64 => Value::F64(blob.read_f64()),
Type::String => Value::String(blob.read_string()),
_ => unimplemented!(),
}
}
//
// Field table queries
//
pub fn field_flags(&self, row: Field) -> FieldAttributes {
FieldAttributes(self.row_usize(row.0, 0))
}
pub fn field_name(&self, row: Field) -> &str {
self.row_str(row.0, 1)
}
pub fn field_constant(&self, row: Field) -> Option<Constant> {
self.row_equal_range(row.0, TABLE_CONSTANT, 1, HasConstant::Field(row).encode()).map(Constant).next()
}
pub fn field_attributes(&self, row: Field) -> impl Iterator<Item = Attribute> {
self.row_attributes(row.0, HasAttribute::Field(row))
}
pub fn field_is_const(&self, row: Field) -> bool {
self.field_attributes(row).any(|attribute| self.attribute_name(attribute) == "ConstAttribute")
}
pub fn field_type(&self, row: Field, enclosing: Option<TypeDef>) -> Type {
let mut blob = self.row_blob(row.0, 2);
blob.read_usize();
blob.read_modifiers();
let def = self.type_from_blob(&mut blob, enclosing, &[]).expect("Type not found");
if self.field_is_const(row) {
def.to_const()
} else {
def
}
}
pub fn field_is_blittable(&self, row: Field, enclosing: TypeDef) -> bool {
self.type_is_blittable(&self.field_type(row, Some(enclosing)))
}
pub fn field_guid(&self, row: Field) -> Option<GUID> {
for attribute in self.field_attributes(row) {
if self.attribute_name(attribute) == "GuidAttribute" {
return Some(GUID::from_args(&self.attribute_args(attribute)));
}
}
None
}
pub fn field_cfg(&self, row: Field) -> Cfg {
let mut cfg = Cfg::default();
self.field_cfg_combine(row, None, &mut cfg);
self.cfg_add_attributes(&mut cfg, self.field_attributes(row));
cfg
}
fn field_cfg_combine(&'a self, row: Field, enclosing: Option<TypeDef>, cfg: &mut Cfg<'a>) {
self.type_cfg_combine(&self.field_type(row, enclosing), cfg)
}
//
// GenericParam table queries
//
pub fn generic_param_name(&self, row: GenericParam) -> &str {
self.row_str(row.0, 3)
}
//
// ImplMap table queries
//
pub fn impl_map_flags(&self, row: ImplMap) -> PInvokeAttributes {
PInvokeAttributes(self.row_usize(row.0, 0))
}
pub fn impl_map_scope(&self, row: ImplMap) -> ModuleRef {
ModuleRef(Row::new(self.row_usize(row.0, 3) - 1, TABLE_MODULEREF, row.0.file as _))
}
//
// InterfaceImpl table queries
//
pub fn interface_impl_attributes(&self, row: InterfaceImpl) -> impl Iterator<Item = Attribute> {
self.row_attributes(row.0, HasAttribute::InterfaceImpl(row))
}
pub fn interface_impl_is_default(&self, row: InterfaceImpl) -> bool {
self.interface_impl_attributes(row).any(|attribute| self.attribute_name(attribute) == "DefaultAttribute")
}
pub fn interface_impl_is_overridable(&self, row: InterfaceImpl) -> bool {
self.interface_impl_attributes(row).any(|attribute| self.attribute_name(attribute) == "OverridableAttribute")
}
pub fn interface_impl_type(&self, row: InterfaceImpl, generics: &[Type]) -> Interface {
let mut kind = InterfaceKind::None;
for attribute in self.interface_impl_attributes(row) {
match self.attribute_name(attribute) {
"DefaultAttribute" => kind = InterfaceKind::Default,
"OverridableAttribute" => kind = InterfaceKind::Overridable,
_ => {}
}
}
Interface { ty: self.type_from_ref(self.row_decode(row.0, 1), None, generics), kind }
}
//
// MemberRef table queries
//
pub fn member_ref_parent(&self, row: MemberRef) -> MemberRefParent {
self.row_decode(row.0, 0)
}
pub fn member_ref_signature(&self, row: MemberRef) -> Blob {
self.row_blob(row.0, 2)
}
//
// MethodDef table queries
//
pub fn method_def_impl_flags(&self, row: MethodDef) -> MethodImplAttributes {
MethodImplAttributes(self.row_usize(row.0, 1))
}
pub fn method_def_flags(&self, row: MethodDef) -> MethodAttributes {
MethodAttributes(self.row_usize(row.0, 2))
}
pub fn method_def_name(&self, row: MethodDef) -> &str {
self.row_str(row.0, 3)
}
pub fn method_def_params(&self, row: MethodDef) -> impl Iterator<Item = Param> {
self.row_list(row.0, TABLE_PARAM, 5).map(Param)
}
pub fn method_def_attributes(&self, row: MethodDef) -> impl Iterator<Item = Attribute> {
self.row_attributes(row.0, HasAttribute::MethodDef(row))
}
pub fn method_def_is_deprecated(&self, row: MethodDef) -> bool {
self.method_def_attributes(row).any(|attribute| self.attribute_name(attribute) == "DeprecatedAttribute")
}
pub fn method_def_does_not_return(&self, row: MethodDef) -> bool {
self.method_def_attributes(row).any(|attribute| self.attribute_name(attribute) == "DoesNotReturnAttribute")
}
pub fn method_def_special_name(&self, row: MethodDef) -> String {
let name = self.method_def_name(row);
if self.method_def_flags(row).special() {
if name.starts_with("get") {
name[4..].to_string()
} else if name.starts_with("put") {
format!("Set{}", &name[4..])
} else if name.starts_with("add") {
name[4..].to_string()
} else if name.starts_with("remove") {
format!("Remove{}", &name[7..])
} else {
name.to_string()
}
} else {
for attribute in self.method_def_attributes(row) {
if self.attribute_name(attribute) == "OverloadAttribute" {
for (_, arg) in self.attribute_args(attribute) {
if let Value::String(name) = arg {
return name;
}
}
}
}
name.to_string()
}
}
pub fn method_def_static_lib(&self, row: MethodDef) -> Option<String> {
for attribute in self.method_def_attributes(row) {
if self.attribute_name(attribute) == "StaticLibraryAttribute" {
let args = self.attribute_args(attribute);
if let Value::String(value) = &args[0].1 {
return Some(value.clone());
}
}
}
None
}
pub fn method_def_impl_map(&self, row: MethodDef) -> Option<ImplMap> {
self.row_equal_range(row.0, TABLE_IMPLMAP, 1, MemberForwarded::MethodDef(row).encode()).map(ImplMap).next()
}
pub fn method_def_signature(&self, row: MethodDef, generics: &[Type]) -> Signature {
let mut blob = self.row_blob(row.0, 4);
blob.read_usize();
blob.read_usize();
let return_type = self.type_from_blob(&mut blob, None, generics);
let mut params: Vec<SignatureParam> = self
.method_def_params(row)
.filter_map(|param| {
if self.param_sequence(param) == 0 {
None
} else {
let ty = self.type_from_blob(&mut blob, None, generics).expect("Parameter type not found");
let ty = if !self.param_flags(param).output() { ty.to_const() } else { ty };
let array_info = self.param_array_info(param);
Some(SignatureParam { def: param, ty, array_info })
}
})
.collect();
for position in 0..params.len() {
// Point len params back to the corresponding ptr params.
match params[position].array_info {
ArrayInfo::RelativeLen(relative) | ArrayInfo::RelativeByteLen(relative) => {
// The len params must be input only.
if !self.param_flags(params[relative].def).output() && position != relative && !params[relative].ty.is_pointer() {
params[relative].array_info = ArrayInfo::RelativePtr(position);
} else {
params[position].array_info = ArrayInfo::Removed;
}
}
_ => {}
}
}
let mut sets = BTreeMap::<usize, Vec<usize>>::new();
// Finds sets of ptr params pointing at the same len param.
for (position, param) in params.iter().enumerate() {
match param.array_info {
ArrayInfo::RelativeLen(relative) | ArrayInfo::RelativeByteLen(relative) => {
sets.entry(relative).or_default().push(position);
}
_ => {}
}
}
// Remove all sets.
for (len, ptrs) in sets {
if ptrs.len() > 1 {
params[len].array_info = ArrayInfo::Removed;
for ptr in ptrs {
params[ptr].array_info = ArrayInfo::Removed;
}
}
}
Signature { def: row, params, return_type }
}
pub fn method_def_extern_abi(&self, def: MethodDef) -> &'static str {
let impl_map = self.method_def_impl_map(def).expect("ImplMap not found");
let flags = self.impl_map_flags(impl_map);
if flags.conv_platform() {
"system"
} else if flags.conv_cdecl() {
"cdecl"
} else {
unimplemented!()
}
}
pub fn method_def_size(&self, method: MethodDef) -> usize {
let signature = self.method_def_signature(method, &[]);
signature.params.iter().fold(0, |sum, param| sum + std::cmp::max(4, self.type_size(¶m.ty)))
}
pub fn type_def_size(&self, def: TypeDef) -> usize {
match self.type_def_kind(def) {
TypeKind::Struct => {
if self.type_def_flags(def).explicit_layout() {
self.type_def_fields(def).map(|field| self.type_size(&self.field_type(field, Some(def)))).max().unwrap_or(1)
} else {
let mut sum = 0;
for field in self.type_def_fields(def) {
let size = self.type_size(&self.field_type(field, Some(def)));
let align = self.type_align(&self.field_type(field, Some(def)));
sum = (sum + (align - 1)) & !(align - 1);
sum += size;
}
sum
}
}
TypeKind::Enum => self.type_size(&self.type_def_underlying_type(def)),
_ => 4,
}
}
fn type_size(&self, ty: &Type) -> usize {
match ty {
Type::I8 | Type::U8 => 1,
Type::I16 | Type::U16 => 2,
Type::I64 | Type::U64 | Type::F64 => 8,
Type::GUID => 16,
Type::TypeDef((def, _)) => self.type_def_size(*def),
Type::Win32Array((ty, len)) => self.type_size(ty) * len,
_ => 4,
}
}
fn type_def_align(&self, def: TypeDef) -> usize {
match self.type_def_kind(def) {
TypeKind::Struct => self.type_def_fields(def).map(|field| self.type_align(&self.field_type(field, Some(def)))).max().unwrap_or(1),
TypeKind::Enum => self.type_align(&self.type_def_underlying_type(def)),
_ => 4,
}
}
fn type_align(&self, ty: &Type) -> usize {
match ty {
Type::I8 | Type::U8 => 1,
Type::I16 | Type::U16 => 2,
Type::I64 | Type::U64 | Type::F64 => 8,
Type::GUID => 4,
Type::TypeDef((def, _)) => self.type_def_align(*def),
Type::Win32Array((ty, len)) => self.type_align(ty) * len,
_ => 4,
}
}
//
// ModuleRef table queries
//
pub fn module_ref_name(&self, row: ModuleRef) -> &str {
self.row_str(row.0, 0)
}
//
// Param table queries
//
pub fn param_flags(&self, row: Param) -> ParamAttributes {
ParamAttributes(self.row_usize(row.0, 0))
}
pub fn param_sequence(&self, row: Param) -> usize {
self.row_usize(row.0, 1)
}
pub fn param_name(&self, row: Param) -> &str {
self.row_str(row.0, 2)
}
pub fn param_attributes(&self, row: Param) -> impl Iterator<Item = Attribute> {
self.row_attributes(row.0, HasAttribute::Param(row))
}
pub fn param_is_com_out_ptr(&self, row: Param) -> bool {
self.param_attributes(row).any(|attribute| self.attribute_name(attribute) == "ComOutPtrAttribute")
}
pub fn param_array_info(&self, row: Param) -> ArrayInfo {
for attribute in self.param_attributes(row) {
match self.attribute_name(attribute) {
"NativeArrayInfoAttribute" => {
for (_, value) in self.attribute_args(attribute) {
match value {
Value::I16(value) => return ArrayInfo::RelativeLen(value as _),
Value::I32(value) => return ArrayInfo::Fixed(value as _),
_ => {}
}
}
}
"MemorySizeAttribute" => {
for (_, value) in self.attribute_args(attribute) {
if let Value::I16(value) = value {
return ArrayInfo::RelativeByteLen(value as _);
}
}
}
_ => {}
}
}
ArrayInfo::None
}
pub fn param_is_retval(&self, row: Param) -> bool {
self.param_attributes(row).any(|attribute| self.attribute_name(attribute) == "RetValAttribute")
}
pub fn param_free_with(&self, row: Param) -> Option<String> {
for attribute in self.param_attributes(row) {
if self.attribute_name(attribute) == "FreeWithAttribute" {
for (_, arg) in self.attribute_args(attribute) {
if let Value::String(name) = arg {
return Some(name);
}
}
}
}
None
}
//
// TypeDef table queries
//
pub fn type_def_flags(&self, row: TypeDef) -> TypeAttributes {
TypeAttributes(self.row_usize(row.0, 0))
}
pub fn type_def_name(&self, row: TypeDef) -> &str {
self.row_str(row.0, 1)
}
pub fn type_def_namespace(&self, row: TypeDef) -> &str {
self.row_str(row.0, 2)
}
pub fn type_def_type_name(&self, row: TypeDef) -> TypeName {
TypeName::new(self.type_def_namespace(row), self.type_def_name(row))
}
pub fn type_def_extends(&self, row: TypeDef) -> TypeName {
self.type_def_or_ref(self.row_decode(row.0, 3))
}
pub fn type_def_fields(&self, row: TypeDef) -> impl Iterator<Item = Field> {
self.row_list(row.0, TABLE_FIELD, 4).map(Field)
}
pub fn type_def_methods(&self, row: TypeDef) -> impl Iterator<Item = MethodDef> {
self.row_list(row.0, TABLE_METHODDEF, 5).map(MethodDef)
}
pub fn type_def_attributes(&self, row: TypeDef) -> impl Iterator<Item = Attribute> {
self.row_attributes(row.0, HasAttribute::TypeDef(row))
}
pub fn type_def_generics(&self, row: TypeDef) -> impl Iterator<Item = Type> {
self.row_equal_range(row.0, TABLE_GENERICPARAM, 2, TypeOrMethodDef::TypeDef(row).encode()).map(|row| Type::GenericParam(GenericParam(row)))
}
pub fn type_def_interface_impls(&self, row: TypeDef) -> impl Iterator<Item = InterfaceImpl> {
self.row_equal_range(row.0, TABLE_INTERFACEIMPL, 0, (row.0.row + 1) as _).map(InterfaceImpl)
}
pub fn type_def_enclosing_type(&self, row: TypeDef) -> Option<TypeDef> {
self.row_equal_range(row.0, TABLE_NESTEDCLASS, 0, (row.0.row + 1) as _).next().map(|row| TypeDef(Row::new(self.files[row.file as usize].usize(row.row as _, row.table as _, 1) - 1, TABLE_TYPEDEF, row.file as _)))
}
pub fn type_def_class_layout(&self, row: TypeDef) -> Option<ClassLayout> {
self.row_equal_range(row.0, TABLE_CLASSLAYOUT, 2, (row.0.row + 1) as _).map(ClassLayout).next()
}
pub fn type_def_underlying_type(&self, row: TypeDef) -> Type {
let field = self.type_def_fields(row).next().expect("Field not found");
if let Some(constant) = self.field_constant(field) {
self.constant_type(constant)
} else {
self.field_type(field, Some(row))
}
}
pub fn type_def_kind(&self, row: TypeDef) -> TypeKind {
if self.type_def_flags(row).interface() {
TypeKind::Interface
} else {
match self.type_def_extends(row) {
TypeName::Enum => TypeKind::Enum,
TypeName::Delegate => TypeKind::Delegate,
TypeName::Struct => TypeKind::Struct,
_ => TypeKind::Class,
}
}
}
pub fn type_def_stdcall(&self, row: TypeDef) -> usize {
if self.type_def_kind(row) == TypeKind::Struct {
if self.type_def_flags(row).explicit_layout() {
self.type_def_fields(row).map(|field| self.type_stdcall(&self.field_type(field, Some(row)))).max().unwrap_or(1)
} else {
self.type_def_fields(row).fold(0, |sum, field| sum + self.type_stdcall(&self.field_type(field, Some(row))))
}
} else {
4
}
}
pub fn type_def_is_blittable(&self, row: TypeDef) -> bool {
match self.type_def_kind(row) {
TypeKind::Struct => self.type_def_fields(row).all(|field| self.field_is_blittable(field, row)),
TypeKind::Enum => true,
TypeKind::Delegate => !self.type_def_flags(row).winrt(),
_ => false,
}
}
pub fn type_def_is_callback(&self, row: TypeDef) -> bool {
!self.type_def_flags(row).winrt() && self.type_def_kind(row) == TypeKind::Delegate
}
pub fn type_def_has_default_constructor(&self, row: TypeDef) -> bool {
for attribute in self.type_def_attributes(row) {
if self.attribute_name(attribute) == "ActivatableAttribute" {
if self.attribute_args(attribute).iter().any(|arg| matches!(arg.1, Value::TypeDef(_))) {
continue;
} else {
return true;
}
}
}
false
}
// TODO: consider removing all the expects and just return Option<T> and let the bindgen crate expect it
// that way the metadata reader is a little more schema-agnostic...
pub fn type_def_invoke_method(&self, row: TypeDef) -> MethodDef {
self.type_def_methods(row).find(|method| self.method_def_name(*method) == "Invoke").expect("`Invoke` method not found")
}
pub fn type_def_interfaces(&'a self, row: TypeDef, generics: &'a [Type]) -> impl Iterator<Item = Interface> + '_ {
self.type_def_interface_impls(row).map(move |row| self.interface_impl_type(row, generics))
}
pub fn type_def_default_interface(&self, row: TypeDef) -> Option<Type> {
self.type_def_interfaces(row, &[]).find(|interface| interface.kind == InterfaceKind::Default).map(|interface| interface.ty)
}
pub fn type_def_has_default_interface(&self, row: TypeDef) -> bool {
self.type_def_interface_impls(row).any(|imp| self.interface_impl_is_default(imp))
}
pub fn type_def_is_deprecated(&self, row: TypeDef) -> bool {
self.type_def_attributes(row).any(|attribute| self.attribute_name(attribute) == "DeprecatedAttribute")
}
pub fn type_def_is_handle(&self, row: TypeDef) -> bool {
self.type_def_attributes(row).any(|attribute| self.attribute_name(attribute) == "NativeTypedefAttribute")
}
pub fn type_def_is_exclusive(&self, row: TypeDef) -> bool {
self.type_def_attributes(row).any(|attribute| self.attribute_name(attribute) == "ExclusiveToAttribute")
}
pub fn type_def_is_scoped(&self, row: TypeDef) -> bool {
self.type_def_flags(row).winrt() || self.type_def_attributes(row).any(|attribute| self.attribute_name(attribute) == "ScopedEnumAttribute")
}
pub fn type_def_is_contract(&self, row: TypeDef) -> bool {
self.type_def_attributes(row).any(|attribute| self.attribute_name(attribute) == "ApiContractAttribute")
}
pub fn type_def_is_udt(&self, row: TypeDef) -> bool {
// TODO: should this just check whether the struct has > 1 fields rather than type_def_is_handle?
self.type_def_kind(row) == TypeKind::Struct && !self.type_def_is_handle(row)
}
pub fn type_def_is_borrowed(&self, row: TypeDef) -> bool {
match self.type_def_kind(row) {
TypeKind::Class => true,
TypeKind::Delegate => self.type_def_flags(row).winrt(),
_ => !self.type_def_is_blittable(row),
}
}
pub fn type_def_is_trivially_convertible(&self, row: TypeDef) -> bool {
match self.type_def_kind(row) {
TypeKind::Struct => self.type_def_is_handle(row),
_ => false,
}
}
pub fn type_def_is_primitive(&self, row: TypeDef) -> bool {
match self.type_def_kind(row) {
TypeKind::Enum => true,
TypeKind::Struct => self.type_def_is_handle(row),
_ => false,
}
}
pub fn type_def_has_explicit_layout(&self, row: TypeDef) -> bool {
if self.type_def_kind(row) != TypeKind::Struct {
return false;
}
fn check(reader: &Reader, row: TypeDef) -> bool {
if reader.type_def_flags(row).explicit_layout() {
return true;
}
if reader.type_def_fields(row).any(|field| reader.type_has_explicit_layout(&reader.field_type(field, Some(row)))) {
return true;
}
false
}
let type_name = self.type_def_type_name(row);
if type_name.namespace.is_empty() {
check(self, row)
} else {
for row in self.get(type_name) {
if check(self, row) {
return true;
}
}
false
}
}
pub fn type_def_has_packing(&self, row: TypeDef) -> bool {
if self.type_def_kind(row) != TypeKind::Struct {
return false;
}
fn check(reader: &Reader, row: TypeDef) -> bool {
if reader.type_def_class_layout(row).is_some() {
return true;
}
if reader.type_def_fields(row).any(|field| reader.type_has_packing(&reader.field_type(field, Some(row)))) {
return true;
}
false
}
let type_name = self.type_def_type_name(row);
if type_name.namespace.is_empty() {
check(self, row)
} else {
for row in self.get(type_name) {
if check(self, row) {
return true;
}
}
false
}
}
pub fn type_def_guid(&self, row: TypeDef) -> Option<GUID> {
for attribute in self.type_def_attributes(row) {
if self.attribute_name(attribute) == "GuidAttribute" {
return Some(GUID::from_args(&self.attribute_args(attribute)));
}
}
None
}
pub fn type_def_bases(&self, mut row: TypeDef) -> Vec<TypeDef> {
// TODO: maybe return Vec<Type>
let mut bases = Vec::new();
loop {
let extends = self.type_def_extends(row);
if extends == TypeName::Object {
break;
} else {
row = self.get(extends).next().expect("Type not found");
bases.push(row);
}
}
bases
}
pub fn type_def_is_flags(&self, row: TypeDef) -> bool {
// Win32 enums use the Flags attribute. WinRT enums don't have the Flags attribute but are paritioned merely based
// on whether they are signed.
self.type_def_attributes(row).any(|attribute| self.attribute_name(attribute) == "FlagsAttribute") || (self.type_def_flags(row).winrt() && self.type_def_underlying_type(row) == Type::U32)
}
pub fn type_def_is_agile(&self, row: TypeDef) -> bool {
for attribute in self.type_def_attributes(row) {
match self.attribute_name(attribute) {
"AgileAttribute" => return true,
"MarshalingBehaviorAttribute" => {
if let Some((_, Value::I32(2))) = self.attribute_args(attribute).get(0) {
return true;
}
}
_ => {}
}
}
matches!(self.type_def_type_name(row), TypeName::IAsyncAction | TypeName::IAsyncActionWithProgress | TypeName::IAsyncOperation | TypeName::IAsyncOperationWithProgress)
}
pub fn type_def_invalid_values(&self, row: TypeDef) -> Vec<i64> {
let mut values = Vec::new();
for attribute in self.type_def_attributes(row) {
if self.attribute_name(attribute) == "InvalidHandleValueAttribute" {
if let Some((_, Value::I64(value))) = self.attribute_args(attribute).get(0) {
values.push(*value);
}
}
}
values
}
pub fn type_def_usable_for(&self, row: TypeDef) -> Option<TypeDef> {
for attribute in self.type_def_attributes(row) {
if self.attribute_name(attribute) == "AlsoUsableForAttribute" {
if let Some((_, Value::String(name))) = self.attribute_args(attribute).get(0) {
return self.get(TypeName::new(self.type_def_namespace(row), name.as_str())).next();
}
}
}
None
}
pub fn type_def_is_nullable(&self, row: TypeDef) -> bool {
match self.type_def_kind(row) {
TypeKind::Interface | TypeKind::Class => true,
// TODO: win32 callbacks should be nullable...
TypeKind::Delegate => self.type_def_flags(row).winrt(),
_ => false,
}
}
pub fn type_def_can_implement(&self, row: TypeDef) -> bool {
for attribute in self.type_def_attributes(row) {
if self.attribute_name(attribute) == "ExclusiveToAttribute" {
for (_, arg) in self.attribute_args(attribute) {
if let Value::TypeDef(def) = arg {
for child in self.type_def_interfaces(def, &[]) {
if child.kind == InterfaceKind::Overridable {
if let Type::TypeDef((def, _)) = child.ty {
if self.type_def_type_name(def) == self.type_def_type_name(row) {
return true;
}
}
}
}
}
}
return false;