forked from jbevain/cecil
-
Notifications
You must be signed in to change notification settings - Fork 44
/
AssemblyReader.cs
3883 lines (2996 loc) · 101 KB
/
AssemblyReader.cs
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
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text;
using Mono.Collections.Generic;
using Mono.Cecil.Cil;
using Mono.Cecil.Metadata;
using Mono.Cecil.PE;
using RVA = System.UInt32;
namespace Mono.Cecil {
abstract class ModuleReader {
readonly protected ModuleDefinition module;
protected ModuleReader (Image image, ReadingMode mode)
{
this.module = new ModuleDefinition (image);
this.module.ReadingMode = mode;
}
protected abstract void ReadModule ();
public abstract void ReadSymbols (ModuleDefinition module);
protected void ReadModuleManifest (MetadataReader reader)
{
reader.Populate (module);
ReadAssembly (reader);
}
void ReadAssembly (MetadataReader reader)
{
var name = reader.ReadAssemblyNameDefinition ();
if (name == null) {
module.kind = ModuleKind.NetModule;
return;
}
var assembly = new AssemblyDefinition ();
assembly.Name = name;
module.assembly = assembly;
assembly.main_module = module;
}
public static ModuleDefinition CreateModule (Image image, ReaderParameters parameters)
{
var reader = CreateModuleReader (image, parameters.ReadingMode);
var module = reader.module;
if (parameters.assembly_resolver != null)
module.assembly_resolver = Disposable.NotOwned (parameters.assembly_resolver);
if (parameters.metadata_resolver != null)
module.metadata_resolver = parameters.metadata_resolver;
if (parameters.metadata_importer_provider != null)
module.metadata_importer = parameters.metadata_importer_provider.GetMetadataImporter (module);
if (parameters.reflection_importer_provider != null)
module.reflection_importer = parameters.reflection_importer_provider.GetReflectionImporter (module);
GetMetadataKind (module, parameters);
reader.ReadModule ();
ReadSymbols (module, parameters);
reader.ReadSymbols (module);
if (parameters.ReadingMode == ReadingMode.Immediate)
module.MetadataSystem.Clear ();
return module;
}
static void ReadSymbols (ModuleDefinition module, ReaderParameters parameters)
{
var symbol_reader_provider = parameters.SymbolReaderProvider;
if (symbol_reader_provider == null && parameters.ReadSymbols)
symbol_reader_provider = new DefaultSymbolReaderProvider ();
if (symbol_reader_provider != null) {
module.SymbolReaderProvider = symbol_reader_provider;
var reader = parameters.SymbolStream != null
? symbol_reader_provider.GetSymbolReader (module, parameters.SymbolStream)
: symbol_reader_provider.GetSymbolReader (module, module.FileName);
if (reader != null) {
try {
module.ReadSymbols (reader, parameters.ThrowIfSymbolsAreNotMatching);
} catch (Exception) {
reader.Dispose ();
throw;
}
}
}
if (module.Image.HasDebugTables ())
module.ReadSymbols (new PortablePdbReader (module.Image, module));
}
static void GetMetadataKind (ModuleDefinition module, ReaderParameters parameters)
{
if (!parameters.ApplyWindowsRuntimeProjections) {
module.MetadataKind = MetadataKind.Ecma335;
return;
}
var runtime_version = module.RuntimeVersion;
if (!runtime_version.Contains ("WindowsRuntime"))
module.MetadataKind = MetadataKind.Ecma335;
else if (runtime_version.Contains ("CLR"))
module.MetadataKind = MetadataKind.ManagedWindowsMetadata;
else
module.MetadataKind = MetadataKind.WindowsMetadata;
}
static ModuleReader CreateModuleReader (Image image, ReadingMode mode)
{
switch (mode) {
case ReadingMode.Immediate:
return new ImmediateModuleReader (image);
case ReadingMode.Deferred:
return new DeferredModuleReader (image);
default:
throw new ArgumentException ();
}
}
}
sealed class ImmediateModuleReader : ModuleReader {
bool resolve_attributes;
public ImmediateModuleReader (Image image)
: base (image, ReadingMode.Immediate)
{
}
protected override void ReadModule ()
{
this.module.Read (this.module, (module, reader) => {
ReadModuleManifest (reader);
ReadModule (module, resolve_attributes: true);
});
}
public void ReadModule (ModuleDefinition module, bool resolve_attributes)
{
this.resolve_attributes = resolve_attributes;
if (module.HasAssemblyReferences)
Mixin.Read (module.AssemblyReferences);
if (module.HasResources)
Mixin.Read (module.Resources);
if (module.HasModuleReferences)
Mixin.Read (module.ModuleReferences);
if (module.HasTypes)
ReadTypes (module.Types);
if (module.HasExportedTypes)
Mixin.Read (module.ExportedTypes);
ReadCustomAttributes (module);
var assembly = module.Assembly;
if (module.kind == ModuleKind.NetModule || assembly == null)
return;
ReadCustomAttributes (assembly);
ReadSecurityDeclarations (assembly);
}
void ReadTypes (Collection<TypeDefinition> types)
{
for (int i = 0; i < types.Count; i++)
ReadType (types [i]);
}
void ReadType (TypeDefinition type)
{
ReadGenericParameters (type);
if (type.HasInterfaces)
ReadInterfaces (type);
if (type.HasNestedTypes)
ReadTypes (type.NestedTypes);
if (type.HasLayoutInfo)
Mixin.Read (type.ClassSize);
if (type.HasFields)
ReadFields (type);
if (type.HasMethods)
ReadMethods (type);
if (type.HasProperties)
ReadProperties (type);
if (type.HasEvents)
ReadEvents (type);
ReadSecurityDeclarations (type);
ReadCustomAttributes (type);
}
void ReadInterfaces (TypeDefinition type)
{
var interfaces = type.Interfaces;
for (int i = 0; i < interfaces.Count; i++)
ReadCustomAttributes (interfaces [i]);
}
void ReadGenericParameters (IGenericParameterProvider provider)
{
if (!provider.HasGenericParameters)
return;
var parameters = provider.GenericParameters;
for (int i = 0; i < parameters.Count; i++) {
var parameter = parameters [i];
if (parameter.HasConstraints)
ReadGenericParameterConstraints (parameter);
ReadCustomAttributes (parameter);
}
}
void ReadGenericParameterConstraints (GenericParameter parameter)
{
var constraints = parameter.Constraints;
for (int i = 0; i < constraints.Count; i++)
ReadCustomAttributes (constraints [i]);
}
void ReadSecurityDeclarations (ISecurityDeclarationProvider provider)
{
if (!provider.HasSecurityDeclarations)
return;
var security_declarations = provider.SecurityDeclarations;
if (!resolve_attributes)
return;
for (int i = 0; i < security_declarations.Count; i++) {
var security_declaration = security_declarations [i];
Mixin.Read (security_declaration.SecurityAttributes);
}
}
void ReadCustomAttributes (ICustomAttributeProvider provider)
{
if (!provider.HasCustomAttributes)
return;
var custom_attributes = provider.CustomAttributes;
if (!resolve_attributes)
return;
for (int i = 0; i < custom_attributes.Count; i++) {
var custom_attribute = custom_attributes [i];
Mixin.Read (custom_attribute.ConstructorArguments);
}
}
void ReadFields (TypeDefinition type)
{
var fields = type.Fields;
for (int i = 0; i < fields.Count; i++) {
var field = fields [i];
if (field.HasConstant)
Mixin.Read (field.Constant);
if (field.HasLayoutInfo)
Mixin.Read (field.Offset);
if (field.RVA > 0)
Mixin.Read (field.InitialValue);
if (field.HasMarshalInfo)
Mixin.Read (field.MarshalInfo);
ReadCustomAttributes (field);
}
}
void ReadMethods (TypeDefinition type)
{
var methods = type.Methods;
for (int i = 0; i < methods.Count; i++) {
var method = methods [i];
ReadGenericParameters (method);
if (method.HasParameters)
ReadParameters (method);
if (method.HasOverrides)
Mixin.Read (method.Overrides);
if (method.IsPInvokeImpl)
Mixin.Read (method.PInvokeInfo);
ReadSecurityDeclarations (method);
ReadCustomAttributes (method);
var return_type = method.MethodReturnType;
if (return_type.HasConstant)
Mixin.Read (return_type.Constant);
if (return_type.HasMarshalInfo)
Mixin.Read (return_type.MarshalInfo);
ReadCustomAttributes (return_type);
}
}
void ReadParameters (MethodDefinition method)
{
var parameters = method.Parameters;
for (int i = 0; i < parameters.Count; i++) {
var parameter = parameters [i];
if (parameter.HasConstant)
Mixin.Read (parameter.Constant);
if (parameter.HasMarshalInfo)
Mixin.Read (parameter.MarshalInfo);
ReadCustomAttributes (parameter);
}
}
void ReadProperties (TypeDefinition type)
{
var properties = type.Properties;
for (int i = 0; i < properties.Count; i++) {
var property = properties [i];
Mixin.Read (property.GetMethod);
if (property.HasConstant)
Mixin.Read (property.Constant);
ReadCustomAttributes (property);
}
}
void ReadEvents (TypeDefinition type)
{
var events = type.Events;
for (int i = 0; i < events.Count; i++) {
var @event = events [i];
Mixin.Read (@event.AddMethod);
ReadCustomAttributes (@event);
}
}
public override void ReadSymbols (ModuleDefinition module)
{
if (module.symbol_reader == null)
return;
ReadTypesSymbols (module.Types, module.symbol_reader);
}
void ReadTypesSymbols (Collection<TypeDefinition> types, ISymbolReader symbol_reader)
{
for (int i = 0; i < types.Count; i++) {
var type = types [i];
if (type.HasNestedTypes)
ReadTypesSymbols (type.NestedTypes, symbol_reader);
if (type.HasMethods)
ReadMethodsSymbols (type, symbol_reader);
}
}
void ReadMethodsSymbols (TypeDefinition type, ISymbolReader symbol_reader)
{
var methods = type.Methods;
for (int i = 0; i < methods.Count; i++) {
var method = methods [i];
if (method.HasBody && method.token.RID != 0 && method.debug_info == null)
method.debug_info = symbol_reader.Read (method);
}
}
}
sealed class DeferredModuleReader : ModuleReader {
public DeferredModuleReader (Image image)
: base (image, ReadingMode.Deferred)
{
}
protected override void ReadModule ()
{
this.module.Read (this.module, (_, reader) => ReadModuleManifest (reader));
}
public override void ReadSymbols (ModuleDefinition module)
{
}
}
sealed class MetadataReader : ByteBuffer {
readonly internal Image image;
readonly internal ModuleDefinition module;
readonly internal MetadataSystem metadata;
internal CodeReader code;
internal IGenericContext context;
readonly MetadataReader metadata_reader;
public MetadataReader (ModuleDefinition module)
: base (module.Image.TableHeap.data)
{
this.image = module.Image;
this.module = module;
this.metadata = module.MetadataSystem;
this.code = new CodeReader (this);
}
public MetadataReader (Image image, ModuleDefinition module, MetadataReader metadata_reader)
: base (image.TableHeap.data)
{
this.image = image;
this.module = module;
this.metadata = module.MetadataSystem;
this.metadata_reader = metadata_reader;
}
int GetCodedIndexSize (CodedIndex index)
{
return image.GetCodedIndexSize (index);
}
uint ReadByIndexSize (int size)
{
if (size == 4)
return ReadUInt32 ();
else
return ReadUInt16 ();
}
byte [] ReadBlob ()
{
var blob_heap = image.BlobHeap;
if (blob_heap == null) {
position += 2;
return Empty<byte>.Array;
}
return blob_heap.Read (ReadBlobIndex ());
}
byte [] ReadBlob (uint signature)
{
var blob_heap = image.BlobHeap;
if (blob_heap == null)
return Empty<byte>.Array;
return blob_heap.Read (signature);
}
uint ReadBlobIndex ()
{
var blob_heap = image.BlobHeap;
return ReadByIndexSize (blob_heap != null ? blob_heap.IndexSize : 2);
}
void GetBlobView (uint signature, out byte [] blob, out int index, out int count)
{
var blob_heap = image.BlobHeap;
if (blob_heap == null) {
blob = null;
index = count = 0;
return;
}
blob_heap.GetView (signature, out blob, out index, out count);
}
string ReadString ()
{
return image.StringHeap.Read (ReadByIndexSize (image.StringHeap.IndexSize));
}
uint ReadStringIndex ()
{
return ReadByIndexSize (image.StringHeap.IndexSize);
}
Guid ReadGuid ()
{
return image.GuidHeap.Read (ReadByIndexSize (image.GuidHeap.IndexSize));
}
uint ReadTableIndex (Table table)
{
return ReadByIndexSize (image.GetTableIndexSize (table));
}
MetadataToken ReadMetadataToken (CodedIndex index)
{
return index.GetMetadataToken (ReadByIndexSize (GetCodedIndexSize (index)));
}
int MoveTo (Table table)
{
var info = image.TableHeap [table];
if (info.Length != 0)
this.position = (int) info.Offset;
return (int) info.Length;
}
bool MoveTo (Table table, uint row)
{
var info = image.TableHeap [table];
var length = info.Length;
if (length == 0 || row > length)
return false;
this.position = (int) (info.Offset + (info.RowSize * (row - 1)));
return true;
}
public AssemblyNameDefinition ReadAssemblyNameDefinition ()
{
if (MoveTo (Table.Assembly) == 0)
return null;
var name = new AssemblyNameDefinition ();
name.HashAlgorithm = (AssemblyHashAlgorithm) ReadUInt32 ();
PopulateVersionAndFlags (name);
name.PublicKey = ReadBlob ();
PopulateNameAndCulture (name);
return name;
}
public ModuleDefinition Populate (ModuleDefinition module)
{
if (MoveTo (Table.Module) == 0)
return module;
Advance (2); // Generation
module.Name = ReadString ();
module.Mvid = ReadGuid ();
return module;
}
void InitializeAssemblyReferences ()
{
if (metadata.AssemblyReferences != null)
return;
int length = MoveTo (Table.AssemblyRef);
var references = metadata.AssemblyReferences = new AssemblyNameReference [length];
for (uint i = 0; i < length; i++) {
var reference = new AssemblyNameReference ();
reference.token = new MetadataToken (TokenType.AssemblyRef, i + 1);
PopulateVersionAndFlags (reference);
var key_or_token = ReadBlob ();
if (reference.HasPublicKey)
reference.PublicKey = key_or_token;
else
reference.PublicKeyToken = key_or_token;
PopulateNameAndCulture (reference);
reference.Hash = ReadBlob ();
references [i] = reference;
}
}
public Collection<AssemblyNameReference> ReadAssemblyReferences ()
{
InitializeAssemblyReferences ();
var references = new Collection<AssemblyNameReference> (metadata.AssemblyReferences);
if (module.IsWindowsMetadata ())
module.Projections.AddVirtualReferences (references);
return references;
}
public MethodDefinition ReadEntryPoint ()
{
if (module.Image.EntryPointToken == 0)
return null;
var token = new MetadataToken (module.Image.EntryPointToken);
return GetMethodDefinition (token.RID);
}
public Collection<ModuleDefinition> ReadModules ()
{
var modules = new Collection<ModuleDefinition> (1);
modules.Add (this.module);
int length = MoveTo (Table.File);
for (uint i = 1; i <= length; i++) {
var attributes = (FileAttributes) ReadUInt32 ();
var name = ReadString ();
ReadBlobIndex ();
if (attributes != FileAttributes.ContainsMetaData)
continue;
var parameters = new ReaderParameters {
ReadingMode = module.ReadingMode,
SymbolReaderProvider = module.SymbolReaderProvider,
AssemblyResolver = module.AssemblyResolver
};
var netmodule = ModuleDefinition.ReadModule (GetModuleFileName (name), parameters);
netmodule.assembly = this.module.assembly;
modules.Add (netmodule);
}
return modules;
}
string GetModuleFileName (string name)
{
if (module.FileName == null)
throw new NotSupportedException ();
var path = Path.GetDirectoryName (module.FileName);
return Path.Combine (path, name);
}
void InitializeModuleReferences ()
{
if (metadata.ModuleReferences != null)
return;
int length = MoveTo (Table.ModuleRef);
var references = metadata.ModuleReferences = new ModuleReference [length];
for (uint i = 0; i < length; i++) {
var reference = new ModuleReference (ReadString ());
reference.token = new MetadataToken (TokenType.ModuleRef, i + 1);
references [i] = reference;
}
}
public Collection<ModuleReference> ReadModuleReferences ()
{
InitializeModuleReferences ();
return new Collection<ModuleReference> (metadata.ModuleReferences);
}
public bool HasFileResource ()
{
int length = MoveTo (Table.File);
if (length == 0)
return false;
for (uint i = 1; i <= length; i++)
if (ReadFileRecord (i).Col1 == FileAttributes.ContainsNoMetaData)
return true;
return false;
}
public Collection<Resource> ReadResources ()
{
int length = MoveTo (Table.ManifestResource);
var resources = new Collection<Resource> (length);
for (int i = 1; i <= length; i++) {
var offset = ReadUInt32 ();
var flags = (ManifestResourceAttributes) ReadUInt32 ();
var name = ReadString ();
var implementation = ReadMetadataToken (CodedIndex.Implementation);
Resource resource;
if (implementation.RID == 0) {
resource = new EmbeddedResource (name, flags, offset, this);
} else if (implementation.TokenType == TokenType.AssemblyRef) {
resource = new AssemblyLinkedResource (name, flags) {
Assembly = (AssemblyNameReference) GetTypeReferenceScope (implementation),
};
} else if (implementation.TokenType == TokenType.File) {
var file_record = ReadFileRecord (implementation.RID);
resource = new LinkedResource (name, flags) {
File = file_record.Col2,
hash = ReadBlob (file_record.Col3)
};
} else
continue;
resources.Add (resource);
}
return resources;
}
Row<FileAttributes, string, uint> ReadFileRecord (uint rid)
{
var position = this.position;
if (!MoveTo (Table.File, rid))
throw new ArgumentException ();
var record = new Row<FileAttributes, string, uint> (
(FileAttributes) ReadUInt32 (),
ReadString (),
ReadBlobIndex ());
this.position = position;
return record;
}
public byte [] GetManagedResource (uint offset)
{
return image.GetReaderAt (image.Resources.VirtualAddress, offset, (o, reader) => {
reader.Advance ((int) o);
return reader.ReadBytes (reader.ReadInt32 ());
}) ?? Empty<byte>.Array;
}
void PopulateVersionAndFlags (AssemblyNameReference name)
{
name.Version = new Version (
ReadUInt16 (),
ReadUInt16 (),
ReadUInt16 (),
ReadUInt16 ());
name.Attributes = (AssemblyAttributes) ReadUInt32 ();
}
void PopulateNameAndCulture (AssemblyNameReference name)
{
name.Name = ReadString ();
name.Culture = ReadString ();
}
public TypeDefinitionCollection ReadTypes ()
{
InitializeTypeDefinitions ();
var mtypes = metadata.Types;
var type_count = mtypes.Length - metadata.NestedTypes.Count;
var types = new TypeDefinitionCollection (module, type_count);
for (int i = 0; i < mtypes.Length; i++) {
var type = mtypes [i];
if (IsNested (type.Attributes))
continue;
types.Add (type);
}
if (image.HasTable (Table.MethodPtr) || image.HasTable (Table.FieldPtr))
CompleteTypes ();
return types;
}
void CompleteTypes ()
{
var types = metadata.Types;
for (int i = 0; i < types.Length; i++) {
var type = types [i];
Mixin.Read (type.Fields);
Mixin.Read (type.Methods);
}
}
void InitializeTypeDefinitions ()
{
if (metadata.Types != null)
return;
InitializeNestedTypes ();
InitializeFields ();
InitializeMethods ();
int length = MoveTo (Table.TypeDef);
var types = metadata.Types = new TypeDefinition [length];
for (uint i = 0; i < length; i++) {
if (types [i] != null)
continue;
types [i] = ReadType (i + 1);
}
if (module.IsWindowsMetadata ()) {
for (uint i = 0; i < length; i++) {
WindowsRuntimeProjections.Project (types [i]);
}
}
}
static bool IsNested (TypeAttributes attributes)
{
switch (attributes & TypeAttributes.VisibilityMask) {
case TypeAttributes.NestedAssembly:
case TypeAttributes.NestedFamANDAssem:
case TypeAttributes.NestedFamily:
case TypeAttributes.NestedFamORAssem:
case TypeAttributes.NestedPrivate:
case TypeAttributes.NestedPublic:
return true;
default:
return false;
}
}
public bool HasNestedTypes (TypeDefinition type)
{
Collection<uint> mapping;
InitializeNestedTypes ();
if (!metadata.TryGetNestedTypeMapping (type, out mapping))
return false;
return mapping.Count > 0;
}
public Collection<TypeDefinition> ReadNestedTypes (TypeDefinition type)
{
InitializeNestedTypes ();
Collection<uint> mapping;
if (!metadata.TryGetNestedTypeMapping (type, out mapping))
return new MemberDefinitionCollection<TypeDefinition> (type);
var nested_types = new MemberDefinitionCollection<TypeDefinition> (type, mapping.Count);
for (int i = 0; i < mapping.Count; i++) {
var nested_type = GetTypeDefinition (mapping [i]);
if (nested_type != null)
nested_types.Add (nested_type);
}
return nested_types;
}
void InitializeNestedTypes ()
{
if (metadata.NestedTypes != null)
return;
var length = MoveTo (Table.NestedClass);
metadata.NestedTypes = new Dictionary<uint, Collection<uint>> (length);
metadata.ReverseNestedTypes = new Dictionary<uint, uint> (length);
if (length == 0)
return;
for (int i = 1; i <= length; i++) {
var nested = ReadTableIndex (Table.TypeDef);
var declaring = ReadTableIndex (Table.TypeDef);
AddNestedMapping (declaring, nested);
}
}
void AddNestedMapping (uint declaring, uint nested)
{
metadata.SetNestedTypeMapping (declaring, AddMapping (metadata.NestedTypes, declaring, nested));
metadata.SetReverseNestedTypeMapping (nested, declaring);
}
static Collection<TValue> AddMapping<TKey, TValue> (Dictionary<TKey, Collection<TValue>> cache, TKey key, TValue value)
{
Collection<TValue> mapped;
if (!cache.TryGetValue (key, out mapped)) {
mapped = new Collection<TValue> ();
}
mapped.Add (value);
return mapped;
}
TypeDefinition ReadType (uint rid)
{
if (!MoveTo (Table.TypeDef, rid))
return null;
var attributes = (TypeAttributes) ReadUInt32 ();
var name = ReadString ();
var @namespace = ReadString ();
var type = new TypeDefinition (@namespace, name, attributes);
type.token = new MetadataToken (TokenType.TypeDef, rid);
type.scope = module;
type.module = module;
metadata.AddTypeDefinition (type);
this.context = type;
type.BaseType = GetTypeDefOrRef (ReadMetadataToken (CodedIndex.TypeDefOrRef));
type.fields_range = ReadListRange (rid, Table.TypeDef, Table.Field);
type.methods_range = ReadListRange (rid, Table.TypeDef, Table.Method);
if (IsNested (attributes))
type.DeclaringType = GetNestedTypeDeclaringType (type);
return type;
}
TypeDefinition GetNestedTypeDeclaringType (TypeDefinition type)
{
uint declaring_rid;
if (!metadata.TryGetReverseNestedTypeMapping (type, out declaring_rid))
return null;
return GetTypeDefinition (declaring_rid);
}
Range ReadListRange (uint current_index, Table current, Table target)
{
var list = new Range ();
var start = ReadTableIndex (target);
if (start == 0)
return list;
uint next_index;
var current_table = image.TableHeap [current];
if (current_index == current_table.Length)
next_index = image.TableHeap [target].Length + 1;
else {
var position = this.position;
this.position += (int) (current_table.RowSize - image.GetTableIndexSize (target));
next_index = ReadTableIndex (target);
this.position = position;
}
list.Start = start;
list.Length = next_index - start;