/
MetadataWriter.cs
4154 lines (3495 loc) · 167 KB
/
MetadataWriter.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
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Microsoft.DiaSymReader;
using Roslyn.Utilities;
namespace Microsoft.Cci
{
internal abstract partial class MetadataWriter
{
internal static readonly Encoding s_utf8Encoding = Encoding.UTF8;
/// <summary>
/// This is the maximum length of a type or member name in metadata, assuming
/// the name is in UTF-8 format and not (yet) null-terminated.
/// </summary>
/// <remarks>
/// Source names may have to be shorter still to accommodate mangling.
/// Used for event names, field names, property names, field names, method def names,
/// member ref names, type def (full) names, type ref (full) names, exported type
/// (full) names, parameter names, manifest resource names, and unmanaged method names
/// (ImplMap table).
///
/// See CLI Part II, section 22.
/// </remarks>
internal const int NameLengthLimit = 1024 - 1; //MAX_CLASS_NAME = 1024 in dev11
/// <summary>
/// This is the maximum length of a path in metadata, assuming the path is in UTF-8
/// format and not (yet) null-terminated.
/// </summary>
/// <remarks>
/// Used for file names, module names, and module ref names.
///
/// See CLI Part II, section 22.
/// </remarks>
internal const int PathLengthLimit = 260 - 1; //MAX_PATH = 1024 in dev11
/// <summary>
/// This is the maximum length of a string in the PDB, assuming it is in UTF-8 format
/// and not (yet) null-terminated.
/// </summary>
/// <remarks>
/// Used for import strings, locals, and local constants.
/// </remarks>
internal const int PdbLengthLimit = 2046; // Empirical, based on when ISymUnmanagedWriter2 methods start throwing.
private readonly int _numTypeDefsEstimate;
private readonly bool _deterministic;
internal readonly bool MetadataOnly;
internal readonly bool EmitTestCoverageData;
// A map of method body before token translation to RVA. Used for deduplication of small bodies.
private readonly Dictionary<(ImmutableArray<byte>, bool), int> _smallMethodBodies;
private const byte TinyFormat = 2;
private const int ThrowNullCodeSize = 2;
private static readonly ImmutableArray<byte> ThrowNullEncodedBody =
ImmutableArray.Create(
(byte)((ThrowNullCodeSize << 2) | TinyFormat),
(byte)ILOpCode.Ldnull,
(byte)ILOpCode.Throw);
protected MetadataWriter(
MetadataBuilder metadata,
MetadataBuilder debugMetadataOpt,
DynamicAnalysisDataWriter dynamicAnalysisDataWriterOpt,
EmitContext context,
CommonMessageProvider messageProvider,
bool metadataOnly,
bool deterministic,
bool emitTestCoverageData,
CancellationToken cancellationToken)
{
Debug.Assert(metadata != debugMetadataOpt);
this.module = context.Module;
_deterministic = deterministic;
this.MetadataOnly = metadataOnly;
this.EmitTestCoverageData = emitTestCoverageData;
// EDMAURER provide some reasonable size estimates for these that will avoid
// much of the reallocation that would occur when growing these from empty.
_signatureIndex = new Dictionary<ISignature, KeyValuePair<BlobHandle, ImmutableArray<byte>>>(module.HintNumberOfMethodDefinitions); //ignores field signatures
_numTypeDefsEstimate = module.HintNumberOfMethodDefinitions / 6;
_exportedTypeList = new List<ITypeReference>(_numTypeDefsEstimate);
this.Context = context;
this.messageProvider = messageProvider;
_cancellationToken = cancellationToken;
this.metadata = metadata;
_debugMetadataOpt = debugMetadataOpt;
_dynamicAnalysisDataWriterOpt = dynamicAnalysisDataWriterOpt;
_smallMethodBodies = new Dictionary<(ImmutableArray<byte>, bool), int>(ByteSequenceBoolTupleComparer.Instance);
}
private int NumberOfTypeDefsEstimate { get { return _numTypeDefsEstimate; } }
/// <summary>
/// Returns true if writing full metadata, false if writing delta.
/// </summary>
internal bool IsFullMetadata
{
get { return this.Generation == 0; }
}
/// <summary>
/// True if writing delta metadata in a minimal format.
/// </summary>
private bool IsMinimalDelta
{
get { return !IsFullMetadata; }
}
/// <summary>
/// NetModules and EnC deltas don't have AssemblyDef record.
/// We don't emit it for EnC deltas since assembly identity has to be preserved across generations (CLR/debugger get confused otherwise).
/// </summary>
private bool EmitAssemblyDefinition => module.OutputKind != OutputKind.NetModule && !IsMinimalDelta;
/// <summary>
/// Returns metadata generation ordinal. Zero for
/// full metadata and non-zero for delta.
/// </summary>
protected abstract ushort Generation { get; }
/// <summary>
/// Returns unique Guid for this delta, or default(Guid)
/// if full metadata.
/// </summary>
protected abstract Guid EncId { get; }
/// <summary>
/// Returns Guid of previous delta, or default(Guid)
/// if full metadata or generation 1 delta.
/// </summary>
protected abstract Guid EncBaseId { get; }
/// <summary>
/// Returns true and full metadata handle of the type definition
/// if the type definition is recognized. Otherwise returns false.
/// </summary>
protected abstract bool TryGetTypeDefinitionHandle(ITypeDefinition def, out TypeDefinitionHandle handle);
/// <summary>
/// Get full metadata handle of the type definition.
/// </summary>
protected abstract TypeDefinitionHandle GetTypeDefinitionHandle(ITypeDefinition def);
/// <summary>
/// The type definition corresponding to full metadata type handle.
/// Deltas are only required to support indexing into current generation.
/// </summary>
protected abstract ITypeDefinition GetTypeDef(TypeDefinitionHandle handle);
/// <summary>
/// The type definitions to be emitted, in row order. These
/// are just the type definitions from the current generation.
/// </summary>
protected abstract IReadOnlyList<ITypeDefinition> GetTypeDefs();
/// <summary>
/// Get full metadata handle of the event definition.
/// </summary>
protected abstract EventDefinitionHandle GetEventDefinitionHandle(IEventDefinition def);
/// <summary>
/// The event definitions to be emitted, in row order. These
/// are just the event definitions from the current generation.
/// </summary>
protected abstract IReadOnlyList<IEventDefinition> GetEventDefs();
/// <summary>
/// Get full metadata handle of the field definition.
/// </summary>
protected abstract FieldDefinitionHandle GetFieldDefinitionHandle(IFieldDefinition def);
/// <summary>
/// The field definitions to be emitted, in row order. These
/// are just the field definitions from the current generation.
/// </summary>
protected abstract IReadOnlyList<IFieldDefinition> GetFieldDefs();
/// <summary>
/// Returns true and handle of the method definition
/// if the method definition is recognized. Otherwise returns false.
/// The index is into the full metadata.
/// </summary>
protected abstract bool TryGetMethodDefinitionHandle(IMethodDefinition def, out MethodDefinitionHandle handle);
/// <summary>
/// Get full metadata handle of the method definition.
/// </summary>
protected abstract MethodDefinitionHandle GetMethodDefinitionHandle(IMethodDefinition def);
/// <summary>
/// The method definition corresponding to full metadata method handle.
/// Deltas are only required to support indexing into current generation.
/// </summary>
protected abstract IMethodDefinition GetMethodDef(MethodDefinitionHandle handle);
/// <summary>
/// The method definitions to be emitted, in row order. These
/// are just the method definitions from the current generation.
/// </summary>
protected abstract IReadOnlyList<IMethodDefinition> GetMethodDefs();
/// <summary>
/// Get full metadata handle of the property definition.
/// </summary>
protected abstract PropertyDefinitionHandle GetPropertyDefIndex(IPropertyDefinition def);
/// <summary>
/// The property definitions to be emitted, in row order. These
/// are just the property definitions from the current generation.
/// </summary>
protected abstract IReadOnlyList<IPropertyDefinition> GetPropertyDefs();
/// <summary>
/// The full metadata handle of the parameter definition.
/// </summary>
protected abstract ParameterHandle GetParameterHandle(IParameterDefinition def);
/// <summary>
/// The parameter definitions to be emitted, in row order. These
/// are just the parameter definitions from the current generation.
/// </summary>
protected abstract IReadOnlyList<IParameterDefinition> GetParameterDefs();
/// <summary>
/// The generic parameter definitions to be emitted, in row order. These
/// are just the generic parameter definitions from the current generation.
/// </summary>
protected abstract IReadOnlyList<IGenericParameter> GetGenericParameters();
/// <summary>
/// The handle of the first field of the type.
/// </summary>
protected abstract FieldDefinitionHandle GetFirstFieldDefinitionHandle(INamedTypeDefinition typeDef);
/// <summary>
/// The handle of the first method of the type.
/// </summary>
protected abstract MethodDefinitionHandle GetFirstMethodDefinitionHandle(INamedTypeDefinition typeDef);
/// <summary>
/// The handle of the first parameter of the method.
/// </summary>
protected abstract ParameterHandle GetFirstParameterHandle(IMethodDefinition methodDef);
/// <summary>
/// Return full metadata handle of the assembly reference, adding
/// the reference to the index for this generation if missing.
/// Deltas are not required to return rows from previous generations.
/// </summary>
protected abstract AssemblyReferenceHandle GetOrAddAssemblyReferenceHandle(IAssemblyReference reference);
/// <summary>
/// The assembly references to be emitted, in row order. These
/// are just the assembly references from the current generation.
/// </summary>
protected abstract IReadOnlyList<AssemblyIdentity> GetAssemblyRefs();
// ModuleRef table contains module names for TypeRefs that target types in netmodules (represented by IModuleReference),
// and module names specified by P/Invokes (plain strings). Names in the table must be unique and are case sensitive.
//
// Spec 22.31 (ModuleRef : 0x1A)
// "Name should match an entry in the Name column of the File table. Moreover, that entry shall enable the
// CLI to locate the target module (typically it might name the file used to hold the module)"
//
// This is not how the Dev10 compilers and ILASM work. An entry is added to File table only for resources and netmodules.
// Entries aren't added for P/Invoked modules.
/// <summary>
/// Return full metadata handle of the module reference, adding
/// the reference to the index for this generation if missing.
/// Deltas are not required to return rows from previous generations.
/// </summary>
protected abstract ModuleReferenceHandle GetOrAddModuleReferenceHandle(string reference);
/// <summary>
/// The module references to be emitted, in row order. These
/// are just the module references from the current generation.
/// </summary>
protected abstract IReadOnlyList<string> GetModuleRefs();
/// <summary>
/// Return full metadata handle of the member reference, adding
/// the reference to the index for this generation if missing.
/// Deltas are not required to return rows from previous generations.
/// </summary>
protected abstract MemberReferenceHandle GetOrAddMemberReferenceHandle(ITypeMemberReference reference);
/// <summary>
/// The member references to be emitted, in row order. These
/// are just the member references from the current generation.
/// </summary>
protected abstract IReadOnlyList<ITypeMemberReference> GetMemberRefs();
/// <summary>
/// Return full metadata handle of the method spec, adding
/// the spec to the index for this generation if missing.
/// Deltas are not required to return rows from previous generations.
/// </summary>
protected abstract MethodSpecificationHandle GetOrAddMethodSpecificationHandle(IGenericMethodInstanceReference reference);
/// <summary>
/// The method specs to be emitted, in row order. These
/// are just the method specs from the current generation.
/// </summary>
protected abstract IReadOnlyList<IGenericMethodInstanceReference> GetMethodSpecs();
/// <summary>
/// The greatest index given to any method definition.
/// </summary>
protected abstract int GreatestMethodDefIndex { get; }
/// <summary>
/// Return true and full metadata handle of the type reference
/// if the reference is available in the current generation.
/// Deltas are not required to return rows from previous generations.
/// </summary>
protected abstract bool TryGetTypeReferenceHandle(ITypeReference reference, out TypeReferenceHandle handle);
/// <summary>
/// Return full metadata handle of the type reference, adding
/// the reference to the index for this generation if missing.
/// Deltas are not required to return rows from previous generations.
/// </summary>
protected abstract TypeReferenceHandle GetOrAddTypeReferenceHandle(ITypeReference reference);
/// <summary>
/// The type references to be emitted, in row order. These
/// are just the type references from the current generation.
/// </summary>
protected abstract IReadOnlyList<ITypeReference> GetTypeRefs();
/// <summary>
/// Returns full metadata handle of the type spec, adding
/// the spec to the index for this generation if missing.
/// Deltas are not required to return rows from previous generations.
/// </summary>
protected abstract TypeSpecificationHandle GetOrAddTypeSpecificationHandle(ITypeReference reference);
/// <summary>
/// The type specs to be emitted, in row order. These
/// are just the type specs from the current generation.
/// </summary>
protected abstract IReadOnlyList<ITypeReference> GetTypeSpecs();
/// <summary>
/// Returns full metadata handle the standalone signature, adding
/// the signature to the index for this generation if missing.
/// Deltas are not required to return rows from previous generations.
/// </summary>
protected abstract StandaloneSignatureHandle GetOrAddStandaloneSignatureHandle(BlobHandle handle);
/// <summary>
/// The signature blob handles to be emitted, in row order. These
/// are just the signature indices from the current generation.
/// </summary>
protected abstract IReadOnlyList<BlobHandle> GetStandaloneSignatureBlobHandles();
protected abstract void CreateIndicesForNonTypeMembers(ITypeDefinition typeDef);
/// <summary>
/// Return a visitor for traversing all references to be emitted.
/// </summary>
protected abstract ReferenceIndexer CreateReferenceVisitor();
/// <summary>
/// Populate EventMap table.
/// </summary>
protected abstract void PopulateEventMapTableRows();
/// <summary>
/// Populate PropertyMap table.
/// </summary>
protected abstract void PopulatePropertyMapTableRows();
/// <summary>
/// Populate EncLog table.
/// </summary>
protected abstract void PopulateEncLogTableRows(ImmutableArray<int> rowCounts);
/// <summary>
/// Populate EncMap table.
/// </summary>
protected abstract void PopulateEncMapTableRows(ImmutableArray<int> rowCounts);
protected abstract void ReportReferencesToAddedSymbols();
// If true, it is allowed to have methods not have bodies (for emitting metadata-only
// assembly)
private readonly CancellationToken _cancellationToken;
protected readonly CommonPEModuleBuilder module;
public readonly EmitContext Context;
protected readonly CommonMessageProvider messageProvider;
// progress:
private bool _tableIndicesAreComplete;
private EntityHandle[] _pseudoSymbolTokenToTokenMap;
private IReference[] _pseudoSymbolTokenToReferenceMap;
private UserStringHandle[] _pseudoStringTokenToTokenMap;
private bool _userStringTokenOverflow;
private List<string> _pseudoStringTokenToStringMap;
private ReferenceIndexer _referenceVisitor;
protected readonly MetadataBuilder metadata;
// A builder for Portable or Embedded PDB metadata, or null if we are not emitting Portable/Embedded PDB.
protected readonly MetadataBuilder _debugMetadataOpt;
internal bool EmitPortableDebugMetadata => _debugMetadataOpt != null;
private readonly DynamicAnalysisDataWriter _dynamicAnalysisDataWriterOpt;
private readonly Dictionary<ICustomAttribute, BlobHandle> _customAttributeSignatureIndex = new Dictionary<ICustomAttribute, BlobHandle>();
private readonly Dictionary<ITypeReference, BlobHandle> _typeSpecSignatureIndex = new Dictionary<ITypeReference, BlobHandle>();
private readonly List<ITypeReference> _exportedTypeList;
private readonly Dictionary<string, int> _fileRefIndex = new Dictionary<string, int>(32); // more than enough in most cases, value is a RowId
private readonly List<IFileReference> _fileRefList = new List<IFileReference>(32);
private readonly Dictionary<IFieldReference, BlobHandle> _fieldSignatureIndex = new Dictionary<IFieldReference, BlobHandle>();
// We need to keep track of both the index of the signature and the actual blob to support VB static local naming scheme.
private readonly Dictionary<ISignature, KeyValuePair<BlobHandle, ImmutableArray<byte>>> _signatureIndex;
private readonly Dictionary<IMarshallingInformation, BlobHandle> _marshallingDescriptorIndex = new Dictionary<IMarshallingInformation, BlobHandle>();
protected readonly List<MethodImplementation> methodImplList = new List<MethodImplementation>();
private readonly Dictionary<IGenericMethodInstanceReference, BlobHandle> _methodInstanceSignatureIndex = new Dictionary<IGenericMethodInstanceReference, BlobHandle>();
// Well known dummy cor library types whose refs are used for attaching assembly attributes off within net modules
// There is no guarantee the types actually exist in a cor library
internal const string dummyAssemblyAttributeParentNamespace = "System.Runtime.CompilerServices";
internal const string dummyAssemblyAttributeParentName = "AssemblyAttributesGoHere";
internal static readonly string[,] dummyAssemblyAttributeParentQualifier = { { "", "M" }, { "S", "SM" } };
private readonly TypeReferenceHandle[,] _dummyAssemblyAttributeParent = { { default(TypeReferenceHandle), default(TypeReferenceHandle) }, { default(TypeReferenceHandle), default(TypeReferenceHandle) } };
internal CommonPEModuleBuilder Module => module;
private void CreateMethodBodyReferenceIndex()
{
int count;
var referencesInIL = module.ReferencesInIL(out count);
_pseudoSymbolTokenToTokenMap = new EntityHandle[count];
_pseudoSymbolTokenToReferenceMap = new IReference[count];
int cur = 0;
foreach (IReference o in referencesInIL)
{
_pseudoSymbolTokenToReferenceMap[cur] = o;
cur++;
}
}
private void CreateIndices()
{
_cancellationToken.ThrowIfCancellationRequested();
this.CreateUserStringIndices();
this.CreateInitialAssemblyRefIndex();
this.CreateInitialFileRefIndex();
this.CreateIndicesForModule();
// Find all references and assign tokens.
_referenceVisitor = this.CreateReferenceVisitor();
_referenceVisitor.Visit(module);
this.CreateMethodBodyReferenceIndex();
this.OnIndicesCreated();
}
private void CreateUserStringIndices()
{
_pseudoStringTokenToStringMap = new List<string>();
foreach (string str in this.module.GetStrings())
{
_pseudoStringTokenToStringMap.Add(str);
}
_pseudoStringTokenToTokenMap = new UserStringHandle[_pseudoStringTokenToStringMap.Count];
}
private void CreateIndicesForModule()
{
var nestedTypes = new Queue<INestedTypeDefinition>();
foreach (INamespaceTypeDefinition typeDef in module.GetTopLevelTypeDefinitions(Context))
{
this.CreateIndicesFor(typeDef, nestedTypes);
}
while (nestedTypes.Count > 0)
{
var nestedType = nestedTypes.Dequeue();
this.CreateIndicesFor(nestedType, nestedTypes);
}
}
protected virtual void OnIndicesCreated()
{
}
private void CreateIndicesFor(ITypeDefinition typeDef, Queue<INestedTypeDefinition> nestedTypes)
{
_cancellationToken.ThrowIfCancellationRequested();
this.CreateIndicesForNonTypeMembers(typeDef);
// Metadata spec:
// The TypeDef table has a special ordering constraint:
// the definition of an enclosing class shall precede the definition of all classes it encloses.
foreach (var nestedType in typeDef.GetNestedTypes(Context))
{
nestedTypes.Enqueue(nestedType);
}
}
protected IEnumerable<IGenericTypeParameter> GetConsolidatedTypeParameters(ITypeDefinition typeDef)
{
INestedTypeDefinition nestedTypeDef = typeDef.AsNestedTypeDefinition(Context);
if (nestedTypeDef == null)
{
if (typeDef.IsGeneric)
{
return typeDef.GenericParameters;
}
return null;
}
return this.GetConsolidatedTypeParameters(typeDef, typeDef);
}
private List<IGenericTypeParameter> GetConsolidatedTypeParameters(ITypeDefinition typeDef, ITypeDefinition owner)
{
List<IGenericTypeParameter> result = null;
INestedTypeDefinition nestedTypeDef = typeDef.AsNestedTypeDefinition(Context);
if (nestedTypeDef != null)
{
result = this.GetConsolidatedTypeParameters(nestedTypeDef.ContainingTypeDefinition, owner);
}
if (typeDef.GenericParameterCount > 0)
{
ushort index = 0;
if (result == null)
{
result = new List<IGenericTypeParameter>();
}
else
{
index = (ushort)result.Count;
}
if (typeDef == owner && index == 0)
{
result.AddRange(typeDef.GenericParameters);
}
else
{
foreach (IGenericTypeParameter genericParameter in typeDef.GenericParameters)
{
result.Add(new InheritedTypeParameter(index++, owner, genericParameter));
}
}
}
return result;
}
protected ImmutableArray<IParameterDefinition> GetParametersToEmit(IMethodDefinition methodDef)
{
if (methodDef.ParameterCount == 0 && !(methodDef.ReturnValueIsMarshalledExplicitly || IteratorHelper.EnumerableIsNotEmpty(methodDef.GetReturnValueAttributes(Context))))
{
return ImmutableArray<IParameterDefinition>.Empty;
}
return GetParametersToEmitCore(methodDef);
}
private ImmutableArray<IParameterDefinition> GetParametersToEmitCore(IMethodDefinition methodDef)
{
ArrayBuilder<IParameterDefinition> builder = null;
var parameters = methodDef.Parameters;
if (methodDef.ReturnValueIsMarshalledExplicitly || IteratorHelper.EnumerableIsNotEmpty(methodDef.GetReturnValueAttributes(Context)))
{
builder = ArrayBuilder<IParameterDefinition>.GetInstance(parameters.Length + 1);
builder.Add(new ReturnValueParameter(methodDef));
}
for (int i = 0; i < parameters.Length; i++)
{
IParameterDefinition parDef = parameters[i];
// No explicit param row is needed if param has no flags (other than optionally IN),
// no name and no references to the param row, such as CustomAttribute, Constant, or FieldMarshal
if (parDef.Name != String.Empty ||
parDef.HasDefaultValue || parDef.IsOptional || parDef.IsOut || parDef.IsMarshalledExplicitly ||
IteratorHelper.EnumerableIsNotEmpty(parDef.GetAttributes(Context)))
{
if (builder != null)
{
builder.Add(parDef);
}
}
else
{
// we have a parameter that does not need to be emitted (not common)
if (builder == null)
{
builder = ArrayBuilder<IParameterDefinition>.GetInstance(parameters.Length);
builder.AddRange(parameters, i);
}
}
}
return builder?.ToImmutableAndFree() ?? parameters;
}
/// <summary>
/// Returns a reference to the unit that defines the given referenced type. If the referenced type is a structural type, such as a pointer or a generic type instance,
/// then the result is null.
/// </summary>
public static IUnitReference GetDefiningUnitReference(ITypeReference typeReference, EmitContext context)
{
INestedTypeReference nestedTypeReference = typeReference.AsNestedTypeReference;
while (nestedTypeReference != null)
{
if (nestedTypeReference.AsGenericTypeInstanceReference != null)
{
return null;
}
typeReference = nestedTypeReference.GetContainingType(context);
nestedTypeReference = typeReference.AsNestedTypeReference;
}
INamespaceTypeReference namespaceTypeReference = typeReference.AsNamespaceTypeReference;
if (namespaceTypeReference == null)
{
return null;
}
Debug.Assert(namespaceTypeReference.AsGenericTypeInstanceReference == null);
return namespaceTypeReference.GetUnit(context);
}
private void CreateInitialAssemblyRefIndex()
{
Debug.Assert(!_tableIndicesAreComplete);
foreach (IAssemblyReference assemblyRef in this.module.GetAssemblyReferences(Context))
{
this.GetOrAddAssemblyReferenceHandle(assemblyRef);
}
}
private void CreateInitialFileRefIndex()
{
Debug.Assert(!_tableIndicesAreComplete);
foreach (IFileReference fileRef in module.GetFiles(Context))
{
string key = fileRef.FileName;
if (!_fileRefIndex.ContainsKey(key))
{
_fileRefList.Add(fileRef);
_fileRefIndex.Add(key, _fileRefList.Count);
}
}
}
internal AssemblyReferenceHandle GetAssemblyReferenceHandle(IAssemblyReference assemblyReference)
{
var containingAssembly = this.module.GetContainingAssembly(Context);
if (containingAssembly != null && ReferenceEquals(assemblyReference, containingAssembly))
{
return default(AssemblyReferenceHandle);
}
return this.GetOrAddAssemblyReferenceHandle(assemblyReference);
}
internal ModuleReferenceHandle GetModuleReferenceHandle(string moduleName)
{
return this.GetOrAddModuleReferenceHandle(moduleName);
}
private BlobHandle GetCustomAttributeSignatureIndex(ICustomAttribute customAttribute)
{
BlobHandle result;
if (_customAttributeSignatureIndex.TryGetValue(customAttribute, out result))
{
return result;
}
var writer = PooledBlobBuilder.GetInstance();
this.SerializeCustomAttributeSignature(customAttribute, writer);
result = metadata.GetOrAddBlob(writer);
_customAttributeSignatureIndex.Add(customAttribute, result);
writer.Free();
return result;
}
private EntityHandle GetCustomAttributeTypeCodedIndex(IMethodReference methodReference)
{
IMethodDefinition methodDef = null;
IUnitReference definingUnit = GetDefiningUnitReference(methodReference.GetContainingType(Context), Context);
if (definingUnit != null && ReferenceEquals(definingUnit, this.module))
{
methodDef = methodReference.GetResolvedMethod(Context);
}
return methodDef != null
? (EntityHandle)GetMethodDefinitionHandle(methodDef)
: GetMemberReferenceHandle(methodReference);
}
public static EventAttributes GetEventAttributes(IEventDefinition eventDef)
{
EventAttributes result = 0;
if (eventDef.IsSpecialName)
{
result |= EventAttributes.SpecialName;
}
if (eventDef.IsRuntimeSpecial)
{
result |= EventAttributes.RTSpecialName;
}
return result;
}
public static FieldAttributes GetFieldAttributes(IFieldDefinition fieldDef)
{
var result = (FieldAttributes)fieldDef.Visibility;
if (fieldDef.IsStatic)
{
result |= FieldAttributes.Static;
}
if (fieldDef.IsReadOnly)
{
result |= FieldAttributes.InitOnly;
}
if (fieldDef.IsCompileTimeConstant)
{
result |= FieldAttributes.Literal;
}
if (fieldDef.IsNotSerialized)
{
result |= FieldAttributes.NotSerialized;
}
if (!fieldDef.MappedData.IsDefault)
{
result |= FieldAttributes.HasFieldRVA;
}
if (fieldDef.IsSpecialName)
{
result |= FieldAttributes.SpecialName;
}
if (fieldDef.IsRuntimeSpecial)
{
result |= FieldAttributes.RTSpecialName;
}
if (fieldDef.IsMarshalledExplicitly)
{
result |= FieldAttributes.HasFieldMarshal;
}
if (fieldDef.IsCompileTimeConstant)
{
result |= FieldAttributes.HasDefault;
}
return result;
}
internal BlobHandle GetFieldSignatureIndex(IFieldReference fieldReference)
{
BlobHandle result;
ISpecializedFieldReference specializedFieldReference = fieldReference.AsSpecializedFieldReference;
if (specializedFieldReference != null)
{
fieldReference = specializedFieldReference.UnspecializedVersion;
}
if (_fieldSignatureIndex.TryGetValue(fieldReference, out result))
{
return result;
}
var writer = PooledBlobBuilder.GetInstance();
this.SerializeFieldSignature(fieldReference, writer);
result = metadata.GetOrAddBlob(writer);
_fieldSignatureIndex.Add(fieldReference, result);
writer.Free();
return result;
}
internal EntityHandle GetFieldHandle(IFieldReference fieldReference)
{
IFieldDefinition fieldDef = null;
IUnitReference definingUnit = GetDefiningUnitReference(fieldReference.GetContainingType(Context), Context);
if (definingUnit != null && ReferenceEquals(definingUnit, this.module))
{
fieldDef = fieldReference.GetResolvedField(Context);
}
return fieldDef != null
? (EntityHandle)GetFieldDefinitionHandle(fieldDef)
: GetMemberReferenceHandle(fieldReference);
}
internal AssemblyFileHandle GetAssemblyFileHandle(IFileReference fileReference)
{
string key = fileReference.FileName;
int index;
if (!_fileRefIndex.TryGetValue(key, out index))
{
Debug.Assert(!_tableIndicesAreComplete);
_fileRefList.Add(fileReference);
_fileRefIndex.Add(key, index = _fileRefList.Count);
}
return MetadataTokens.AssemblyFileHandle(index);
}
private AssemblyFileHandle GetAssemblyFileHandle(IModuleReference mref)
{
return MetadataTokens.AssemblyFileHandle(_fileRefIndex[mref.Name]);
}
private static GenericParameterAttributes GetGenericParameterAttributes(IGenericParameter genPar)
{
GenericParameterAttributes result = 0;
switch (genPar.Variance)
{
case TypeParameterVariance.Covariant:
result |= GenericParameterAttributes.Covariant;
break;
case TypeParameterVariance.Contravariant:
result |= GenericParameterAttributes.Contravariant;
break;
}
if (genPar.MustBeReferenceType)
{
result |= GenericParameterAttributes.ReferenceTypeConstraint;
}
if (genPar.MustBeValueType)
{
result |= GenericParameterAttributes.NotNullableValueTypeConstraint;
}
if (genPar.MustHaveDefaultConstructor)
{
result |= GenericParameterAttributes.DefaultConstructorConstraint;
}
return result;
}
private EntityHandle GetExportedTypeImplementation(INamespaceTypeReference namespaceRef)
{
IUnitReference uref = namespaceRef.GetUnit(Context);
if (uref is IAssemblyReference aref)
{
return GetAssemblyReferenceHandle(aref);
}
var mref = (IModuleReference)uref;
aref = mref.GetContainingAssembly(Context);
return aref == null || ReferenceEquals(aref, this.module.GetContainingAssembly(Context))
? (EntityHandle)GetAssemblyFileHandle(mref)
: GetAssemblyReferenceHandle(aref);
}
private static uint GetManagedResourceOffset(ManagedResource resource, BlobBuilder resourceWriter)
{
if (resource.ExternalFile != null)
{
return resource.Offset;
}
int result = resourceWriter.Count;
resource.WriteData(resourceWriter);
return (uint)result;
}
private static uint GetManagedResourceOffset(BlobBuilder resource, BlobBuilder resourceWriter)
{
int result = resourceWriter.Count;
resourceWriter.WriteInt32(resource.Count);
resource.WriteContentTo(resourceWriter);
resourceWriter.Align(8);
return (uint)result;
}
public static string GetMangledName(INamedTypeReference namedType)
{
string unmangledName = namedType.Name;
return namedType.MangleName
? MetadataHelpers.ComposeAritySuffixedMetadataName(unmangledName, namedType.GenericParameterCount)
: unmangledName;
}
internal MemberReferenceHandle GetMemberReferenceHandle(ITypeMemberReference memberRef)
{
return this.GetOrAddMemberReferenceHandle(memberRef);
}
internal EntityHandle GetMemberReferenceParent(ITypeMemberReference memberRef)
{
ITypeDefinition parentTypeDef = memberRef.GetContainingType(Context).AsTypeDefinition(Context);
if (parentTypeDef != null)
{
TypeDefinitionHandle parentTypeDefHandle;
TryGetTypeDefinitionHandle(parentTypeDef, out parentTypeDefHandle);
if (!parentTypeDefHandle.IsNil)
{
if (memberRef is IFieldReference)
{
return parentTypeDefHandle;
}
if (memberRef is IMethodReference methodRef)
{
if (methodRef.AcceptsExtraArguments)
{
MethodDefinitionHandle methodHandle;
if (this.TryGetMethodDefinitionHandle(methodRef.GetResolvedMethod(Context), out methodHandle))
{
return methodHandle;
}
}
return parentTypeDefHandle;
}
// TODO: error
}
}
// TODO: special treatment for global fields and methods. Object model support would be nice.
var containingType = memberRef.GetContainingType(Context);
return containingType.IsTypeSpecification()
? (EntityHandle)GetTypeSpecificationHandle(containingType)
: GetTypeReferenceHandle(containingType);
}
internal EntityHandle GetMethodDefinitionOrReferenceHandle(IMethodReference methodReference)
{
IMethodDefinition methodDef = null;
IUnitReference definingUnit = GetDefiningUnitReference(methodReference.GetContainingType(Context), Context);
if (definingUnit != null && ReferenceEquals(definingUnit, this.module))
{
methodDef = methodReference.GetResolvedMethod(Context);
}
return methodDef != null