-
Notifications
You must be signed in to change notification settings - Fork 4k
/
PEModule.cs
3981 lines (3374 loc) · 157 KB
/
PEModule.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// A set of helpers for extracting elements from metadata.
/// This type is not responsible for managing the underlying storage
/// backing the PE image.
/// </summary>
internal sealed class PEModule : IDisposable
{
/// <summary>
/// We need to store reference to the module metadata to keep the metadata alive while
/// symbols have reference to PEModule.
/// </summary>
private readonly ModuleMetadata _owner;
// Either we have PEReader or we have pointer and size of the metadata blob:
private readonly PEReader _peReaderOpt;
private readonly IntPtr _metadataPointerOpt;
private readonly int _metadataSizeOpt;
private MetadataReader _lazyMetadataReader;
private ImmutableArray<AssemblyIdentity> _lazyAssemblyReferences;
private static readonly Dictionary<string, (int FirstIndex, int SecondIndex)> s_sharedEmptyForwardedTypes = new Dictionary<string, (int FirstIndex, int SecondIndex)>();
private static readonly Dictionary<string, (string OriginalName, int FirstIndex, int SecondIndex)> s_sharedEmptyCaseInsensitiveForwardedTypes = new Dictionary<string, (string OriginalName, int FirstIndex, int SecondIndex)>();
/// <summary>
/// This is a tuple for optimization purposes. In valid cases, we need to store
/// only one assembly index per type. However, if we found more than one, we
/// keep a second one as well to use it for error reporting.
/// We use -1 in case there was no forward.
/// </summary>
private Dictionary<string, (int FirstIndex, int SecondIndex)> _lazyForwardedTypesToAssemblyIndexMap;
/// <summary>
/// Case-insensitive version of <see cref="_lazyForwardedTypesToAssemblyIndexMap"/>, only populated if case-insensitive search is
/// requested. We only keep the first instance of a type name, regardless of case, as this is only used for error recovery purposes
/// in VB.
/// </summary>
private Dictionary<string, (string OriginalName, int FirstIndex, int SecondIndex)> _lazyCaseInsensitiveForwardedTypesToAssemblyIndexMap;
private readonly Lazy<IdentifierCollection> _lazyTypeNameCollection;
private readonly Lazy<IdentifierCollection> _lazyNamespaceNameCollection;
private string _lazyName;
private bool _isDisposed;
/// <summary>
/// Using <see cref="ThreeState"/> as a type for atomicity.
/// </summary>
private ThreeState _lazyContainsNoPiaLocalTypes;
/// <summary>
/// If bitmap is not null, each bit indicates whether a TypeDef
/// with corresponding RowId has been checked if it is a NoPia
/// local type. If the bit is 1, local type will have an entry
/// in m_lazyTypeDefToTypeIdentifierMap.
/// </summary>
private int[] _lazyNoPiaLocalTypeCheckBitMap;
/// <summary>
/// For each TypeDef that has 1 in m_lazyNoPiaLocalTypeCheckBitMap,
/// this map stores corresponding TypeIdentifier AttributeInfo.
/// </summary>
private ConcurrentDictionary<TypeDefinitionHandle, AttributeInfo> _lazyTypeDefToTypeIdentifierMap;
// The module can be used by different compilations or different versions of the "same"
// compilation, which use different hash algorithms. Let's cache result for each distinct
// algorithm.
private readonly CryptographicHashProvider _hashesOpt;
#nullable enable
private delegate bool AttributeValueExtractor<T>(out T value, ref BlobReader sigReader);
private static readonly AttributeValueExtractor<string?> s_attributeStringValueExtractor = CrackStringInAttributeValue;
private static readonly AttributeValueExtractor<(int, int)> s_attributeIntAndIntValueExtractor = CrackIntAndIntInAttributeValue;
private static readonly AttributeValueExtractor<StringAndInt> s_attributeStringAndIntValueExtractor = CrackStringAndIntInAttributeValue;
private static readonly AttributeValueExtractor<(string?, string?)> s_attributeStringAndStringValueExtractor = CrackStringAndStringInAttributeValue;
private static readonly AttributeValueExtractor<bool> s_attributeBooleanValueExtractor = CrackBooleanInAttributeValue;
private static readonly AttributeValueExtractor<byte> s_attributeByteValueExtractor = CrackByteInAttributeValue;
private static readonly AttributeValueExtractor<short> s_attributeShortValueExtractor = CrackShortInAttributeValue;
private static readonly AttributeValueExtractor<int> s_attributeIntValueExtractor = CrackIntInAttributeValue;
private static readonly AttributeValueExtractor<long> s_attributeLongValueExtractor = CrackLongInAttributeValue;
// Note: not a general purpose helper
private static readonly AttributeValueExtractor<decimal> s_decimalValueInDecimalConstantAttributeExtractor = CrackDecimalInDecimalConstantAttribute;
private static readonly AttributeValueExtractor<ImmutableArray<bool>> s_attributeBoolArrayValueExtractor = CrackBoolArrayInAttributeValue;
private static readonly AttributeValueExtractor<ImmutableArray<byte>> s_attributeByteArrayValueExtractor = CrackByteArrayInAttributeValue;
private static readonly AttributeValueExtractor<ImmutableArray<string?>> s_attributeStringArrayValueExtractor = CrackStringArrayInAttributeValue;
private static readonly AttributeValueExtractor<ObsoleteAttributeData?> s_attributeDeprecatedDataExtractor = CrackDeprecatedAttributeData;
private static readonly AttributeValueExtractor<BoolAndStringArrayData> s_attributeBoolAndStringArrayValueExtractor = CrackBoolAndStringArrayInAttributeValue;
private static readonly AttributeValueExtractor<BoolAndStringData> s_attributeBoolAndStringValueExtractor = CrackBoolAndStringInAttributeValue;
internal readonly struct BoolAndStringArrayData
{
public BoolAndStringArrayData(bool sense, ImmutableArray<string?> strings)
{
Sense = sense;
Strings = strings;
}
public readonly bool Sense;
public readonly ImmutableArray<string?> Strings;
}
internal readonly struct BoolAndStringData
{
public BoolAndStringData(bool sense, string? @string)
{
Sense = sense;
String = @string;
}
public readonly bool Sense;
public readonly string? String;
}
#nullable disable
// 'ignoreAssemblyRefs' is used by the EE only, when debugging
// .NET Native, where the corlib may have assembly references
// (see https://github.com/dotnet/roslyn/issues/13275).
internal PEModule(ModuleMetadata owner, PEReader peReader, IntPtr metadataOpt, int metadataSizeOpt, bool includeEmbeddedInteropTypes, bool ignoreAssemblyRefs)
{
// shall not throw
Debug.Assert((peReader == null) ^ (metadataOpt == IntPtr.Zero && metadataSizeOpt == 0));
Debug.Assert(metadataOpt == IntPtr.Zero || metadataSizeOpt > 0);
_owner = owner;
_peReaderOpt = peReader;
_metadataPointerOpt = metadataOpt;
_metadataSizeOpt = metadataSizeOpt;
_lazyTypeNameCollection = new Lazy<IdentifierCollection>(ComputeTypeNameCollection);
_lazyNamespaceNameCollection = new Lazy<IdentifierCollection>(ComputeNamespaceNameCollection);
_hashesOpt = (peReader != null) ? new PEHashProvider(peReader) : null;
_lazyContainsNoPiaLocalTypes = includeEmbeddedInteropTypes ? ThreeState.False : ThreeState.Unknown;
if (ignoreAssemblyRefs)
{
_lazyAssemblyReferences = ImmutableArray<AssemblyIdentity>.Empty;
}
}
private sealed class PEHashProvider : CryptographicHashProvider
{
private readonly PEReader _peReader;
public PEHashProvider(PEReader peReader)
{
Debug.Assert(peReader != null);
_peReader = peReader;
}
internal override unsafe ImmutableArray<byte> ComputeHash(HashAlgorithm algorithm)
{
PEMemoryBlock block = _peReader.GetEntireImage();
byte[] hash;
using (var stream = new ReadOnlyUnmanagedMemoryStream(_peReader, (IntPtr)block.Pointer, block.Length))
{
hash = algorithm.ComputeHash(stream);
}
return ImmutableArray.Create(hash);
}
}
internal bool IsDisposed
{
get
{
return _isDisposed;
}
}
public void Dispose()
{
_isDisposed = true;
_peReaderOpt?.Dispose();
}
// for testing
internal PEReader PEReaderOpt
{
get
{
return _peReaderOpt;
}
}
internal MetadataReader MetadataReader
{
get
{
if (_lazyMetadataReader == null)
{
InitializeMetadataReader();
}
if (_isDisposed)
{
// Without locking, which might be expensive, we can't guarantee that the underlying memory
// won't be accessed after the metadata object is disposed. However we can do a cheap check here that
// handles most cases.
ThrowMetadataDisposed();
}
return _lazyMetadataReader;
}
}
private unsafe void InitializeMetadataReader()
{
MetadataReader newReader;
// PEModule is either created with metadata memory block or a PE reader.
if (_metadataPointerOpt != IntPtr.Zero)
{
newReader = new MetadataReader((byte*)_metadataPointerOpt, _metadataSizeOpt, MetadataReaderOptions.ApplyWindowsRuntimeProjections, StringTableDecoder.Instance);
}
else
{
Debug.Assert(_peReaderOpt != null);
// A workaround for https://github.com/dotnet/corefx/issues/1815
bool hasMetadata;
try
{
hasMetadata = _peReaderOpt.HasMetadata;
}
catch
{
hasMetadata = false;
}
if (!hasMetadata)
{
throw new BadImageFormatException(CodeAnalysisResources.PEImageDoesntContainManagedMetadata);
}
newReader = _peReaderOpt.GetMetadataReader(MetadataReaderOptions.ApplyWindowsRuntimeProjections, StringTableDecoder.Instance);
}
Interlocked.CompareExchange(ref _lazyMetadataReader, newReader, null);
}
private static void ThrowMetadataDisposed()
{
throw new ObjectDisposedException(nameof(ModuleMetadata));
}
#region Module level properties and methods
internal bool IsManifestModule
{
get
{
return MetadataReader.IsAssembly;
}
}
internal bool IsLinkedModule
{
get
{
return !MetadataReader.IsAssembly;
}
}
internal bool IsCOFFOnly
{
get
{
// default value if we only have metadata
if (_peReaderOpt == null)
{
return false;
}
return _peReaderOpt.PEHeaders.IsCoffOnly;
}
}
/// <summary>
/// Target architecture of the machine.
/// </summary>
internal Machine Machine
{
get
{
// platform agnostic if we only have metadata
if (_peReaderOpt == null)
{
return Machine.I386;
}
return _peReaderOpt.PEHeaders.CoffHeader.Machine;
}
}
/// <summary>
/// Indicates that this PE file makes Win32 calls. See CorPEKind.pe32BitRequired for more information (http://msdn.microsoft.com/en-us/library/ms230275.aspx).
/// </summary>
internal bool Bit32Required
{
get
{
// platform agnostic if we only have metadata
if (_peReaderOpt == null)
{
return false;
}
return (_peReaderOpt.PEHeaders.CorHeader.Flags & CorFlags.Requires32Bit) != 0;
}
}
internal ImmutableArray<byte> GetHash(AssemblyHashAlgorithm algorithmId)
{
Debug.Assert(_hashesOpt != null);
return _hashesOpt.GetHash(algorithmId);
}
#endregion
#region ModuleDef helpers
internal string Name
{
get
{
if (_lazyName == null)
{
_lazyName = MetadataReader.GetString(MetadataReader.GetModuleDefinition().Name);
}
return _lazyName;
}
}
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
internal Guid GetModuleVersionIdOrThrow()
{
return MetadataReader.GetModuleVersionIdOrThrow();
}
#endregion
#region ModuleRef, File helpers
/// <summary>
/// Returns the names of linked managed modules.
/// </summary>
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
internal ImmutableArray<string> GetMetadataModuleNamesOrThrow()
{
var builder = ArrayBuilder<string>.GetInstance();
try
{
foreach (var fileHandle in MetadataReader.AssemblyFiles)
{
var file = MetadataReader.GetAssemblyFile(fileHandle);
if (!file.ContainsMetadata)
{
continue;
}
string moduleName = MetadataReader.GetString(file.Name);
if (!MetadataHelpers.IsValidMetadataFileName(moduleName))
{
throw new BadImageFormatException(string.Format(CodeAnalysisResources.InvalidModuleName, this.Name, moduleName));
}
builder.Add(moduleName);
}
return builder.ToImmutable();
}
finally
{
builder.Free();
}
}
/// <summary>
/// Returns names of referenced modules.
/// </summary>
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
internal IEnumerable<string> GetReferencedManagedModulesOrThrow()
{
HashSet<EntityHandle> nameTokens = new HashSet<EntityHandle>();
foreach (var handle in MetadataReader.TypeReferences)
{
TypeReference typeRef = MetadataReader.GetTypeReference(handle);
EntityHandle scope = typeRef.ResolutionScope;
if (scope.Kind == HandleKind.ModuleReference)
{
nameTokens.Add(scope);
}
}
foreach (var token in nameTokens)
{
yield return this.GetModuleRefNameOrThrow((ModuleReferenceHandle)token);
}
}
internal ImmutableArray<EmbeddedResource> GetEmbeddedResourcesOrThrow()
{
if (MetadataReader.ManifestResources.Count == 0)
{
return ImmutableArray<EmbeddedResource>.Empty;
}
var builder = ImmutableArray.CreateBuilder<EmbeddedResource>();
foreach (var handle in MetadataReader.ManifestResources)
{
var resource = MetadataReader.GetManifestResource(handle);
if (resource.Implementation.IsNil)
{
string resourceName = MetadataReader.GetString(resource.Name);
builder.Add(new EmbeddedResource((uint)resource.Offset, resource.Attributes, resourceName));
}
}
return builder.ToImmutable();
}
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
public string GetModuleRefNameOrThrow(ModuleReferenceHandle moduleRef)
{
return MetadataReader.GetString(MetadataReader.GetModuleReference(moduleRef).Name);
}
#endregion
#region AssemblyRef helpers
// The array is sorted by AssemblyRef RowId, starting with RowId=1 and doesn't have any RowId gaps.
public ImmutableArray<AssemblyIdentity> ReferencedAssemblies
{
get
{
if (_lazyAssemblyReferences == null)
{
_lazyAssemblyReferences = this.MetadataReader.GetReferencedAssembliesOrThrow();
}
return _lazyAssemblyReferences;
}
}
#endregion
#region PE Header helpers
internal string MetadataVersion
{
get { return MetadataReader.MetadataVersion; }
}
#endregion
#region Heaps
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
internal BlobReader GetMemoryReaderOrThrow(BlobHandle blob)
{
return MetadataReader.GetBlobReader(blob);
}
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
internal string GetFullNameOrThrow(StringHandle namespaceHandle, StringHandle nameHandle)
{
var attributeTypeName = MetadataReader.GetString(nameHandle);
var attributeTypeNamespaceName = MetadataReader.GetString(namespaceHandle);
return MetadataHelpers.BuildQualifiedName(attributeTypeNamespaceName, attributeTypeName);
}
#endregion
#region AssemblyDef helpers
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
internal AssemblyIdentity ReadAssemblyIdentityOrThrow()
{
return MetadataReader.ReadAssemblyIdentityOrThrow();
}
#endregion
#region TypeDef helpers
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
public TypeDefinitionHandle GetContainingTypeOrThrow(TypeDefinitionHandle typeDef)
{
return MetadataReader.GetTypeDefinition(typeDef).GetDeclaringType();
}
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
public string GetTypeDefNameOrThrow(TypeDefinitionHandle typeDef)
{
TypeDefinition typeDefinition = MetadataReader.GetTypeDefinition(typeDef);
string name = MetadataReader.GetString(typeDefinition.Name);
Debug.Assert(name.Length == 0 || MetadataHelpers.IsValidMetadataIdentifier(name)); // Obfuscated assemblies can have types with empty names.
// The problem is that the mangled name for a static machine type looks like
// "<" + methodName + ">d__" + uniqueId.However, methodName will have dots in
// it for explicit interface implementations (e.g. "<I.F>d__0"). Unfortunately,
// the native compiler emits such names in a very strange way: everything before
// the last dot goes in the namespace (!!) field of the typedef.Since state
// machine types are always nested types and since nested types never have
// explicit namespaces (since they are in the same namespaces as their containing
// types), it should be safe to check for a non-empty namespace name on a nested
// type and prepend the namespace name and a dot to the type name. After that,
// debugging support falls out.
if (IsNestedTypeDefOrThrow(typeDef))
{
string namespaceName = MetadataReader.GetString(typeDefinition.Namespace);
if (namespaceName.Length > 0)
{
// As explained above, this is not really the qualified name - the namespace
// name is actually the part of the name that preceded the last dot (in bad
// metadata).
name = namespaceName + "." + name;
}
}
return name;
}
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
public string GetTypeDefNamespaceOrThrow(TypeDefinitionHandle typeDef)
{
return MetadataReader.GetString(MetadataReader.GetTypeDefinition(typeDef).Namespace);
}
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
public EntityHandle GetTypeDefExtendsOrThrow(TypeDefinitionHandle typeDef)
{
return MetadataReader.GetTypeDefinition(typeDef).BaseType;
}
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
public TypeAttributes GetTypeDefFlagsOrThrow(TypeDefinitionHandle typeDef)
{
return MetadataReader.GetTypeDefinition(typeDef).Attributes;
}
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
public GenericParameterHandleCollection GetTypeDefGenericParamsOrThrow(TypeDefinitionHandle typeDef)
{
return MetadataReader.GetTypeDefinition(typeDef).GetGenericParameters();
}
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
public bool HasGenericParametersOrThrow(TypeDefinitionHandle typeDef)
{
return MetadataReader.GetTypeDefinition(typeDef).GetGenericParameters().Count > 0;
}
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
public void GetTypeDefPropsOrThrow(
TypeDefinitionHandle typeDef,
out string name,
out string @namespace,
out TypeAttributes flags,
out EntityHandle extends)
{
TypeDefinition row = MetadataReader.GetTypeDefinition(typeDef);
name = MetadataReader.GetString(row.Name);
@namespace = MetadataReader.GetString(row.Namespace);
flags = row.Attributes;
extends = row.BaseType;
}
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
internal bool IsNestedTypeDefOrThrow(TypeDefinitionHandle typeDef)
{
return IsNestedTypeDefOrThrow(MetadataReader, typeDef);
}
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
private static bool IsNestedTypeDefOrThrow(MetadataReader metadataReader, TypeDefinitionHandle typeDef)
{
return IsNested(metadataReader.GetTypeDefinition(typeDef).Attributes);
}
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
internal bool IsInterfaceOrThrow(TypeDefinitionHandle typeDef)
{
return MetadataReader.GetTypeDefinition(typeDef).Attributes.IsInterface();
}
private readonly struct TypeDefToNamespace
{
internal readonly TypeDefinitionHandle TypeDef;
internal readonly NamespaceDefinitionHandle NamespaceHandle;
internal TypeDefToNamespace(TypeDefinitionHandle typeDef, NamespaceDefinitionHandle namespaceHandle)
{
TypeDef = typeDef;
NamespaceHandle = namespaceHandle;
}
}
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
private IEnumerable<TypeDefToNamespace> GetTypeDefsOrThrow(bool topLevelOnly)
{
foreach (var typeDef in MetadataReader.TypeDefinitions)
{
var row = MetadataReader.GetTypeDefinition(typeDef);
if (topLevelOnly && IsNested(row.Attributes))
{
continue;
}
yield return new TypeDefToNamespace(typeDef, row.NamespaceDefinition);
}
}
/// <summary>
/// The function groups types defined in the module by their fully-qualified namespace name.
/// The case-sensitivity of the grouping depends upon the provided StringComparer.
///
/// The sequence is sorted by name by using provided comparer. Therefore, if there are multiple
/// groups for a namespace name (e.g. because they differ in case), the groups are going to be
/// adjacent to each other.
///
/// Empty string is used as namespace name for types in the Global namespace. Therefore, all types
/// in the Global namespace, if any, should be in the first group (assuming a reasonable StringComparer).
/// </summary>
/// Comparer to sort the groups.
/// <param name="nameComparer">
/// </param>
/// <returns>A sorted list of TypeDef row ids, grouped by fully-qualified namespace name.</returns>
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
internal IEnumerable<IGrouping<string, TypeDefinitionHandle>> GroupTypesByNamespaceOrThrow(StringComparer nameComparer)
{
// TODO: Consider if we should cache the result (not the IEnumerable, but the actual values).
// NOTE: Rather than use a sorted dictionary, we accumulate the groupings in a normal dictionary
// and then sort the list. We do this so that namespaces with distinct names are not
// merged, even if they are equal according to the provided comparer. This improves the error
// experience because types retain their exact namespaces.
Dictionary<string, ArrayBuilder<TypeDefinitionHandle>> namespaces = new Dictionary<string, ArrayBuilder<TypeDefinitionHandle>>();
GetTypeNamespaceNamesOrThrow(namespaces);
GetForwardedTypeNamespaceNamesOrThrow(namespaces);
var result = new ArrayBuilder<IGrouping<string, TypeDefinitionHandle>>(namespaces.Count);
foreach (var pair in namespaces)
{
result.Add(new Grouping<string, TypeDefinitionHandle>(pair.Key, pair.Value ?? SpecializedCollections.EmptyEnumerable<TypeDefinitionHandle>()));
}
result.Sort(new TypesByNamespaceSortComparer(nameComparer));
return result;
}
internal class TypesByNamespaceSortComparer : IComparer<IGrouping<string, TypeDefinitionHandle>>
{
private readonly StringComparer _nameComparer;
public TypesByNamespaceSortComparer(StringComparer nameComparer)
{
_nameComparer = nameComparer;
}
public int Compare(IGrouping<string, TypeDefinitionHandle> left, IGrouping<string, TypeDefinitionHandle> right)
{
if (left == right)
{
return 0;
}
int result = _nameComparer.Compare(left.Key, right.Key);
if (result == 0)
{
var fLeft = left.FirstOrDefault();
var fRight = right.FirstOrDefault();
if (fLeft.IsNil ^ fRight.IsNil)
{
result = fLeft.IsNil ? +1 : -1;
}
else
{
result = HandleComparer.Default.Compare(fLeft, fRight);
}
if (result == 0)
{
// This can only happen when both are for forwarded types.
Debug.Assert(left.IsEmpty() && right.IsEmpty());
result = string.CompareOrdinal(left.Key, right.Key);
}
}
Debug.Assert(result != 0);
return result;
}
}
/// <summary>
/// Groups together the RowIds of types in a given namespaces. The types considered are
/// those defined in this module.
/// </summary>
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
private void GetTypeNamespaceNamesOrThrow(Dictionary<string, ArrayBuilder<TypeDefinitionHandle>> namespaces)
{
// PERF: Group by namespace handle so we only have to allocate one string for every namespace
var namespaceHandles = new Dictionary<NamespaceDefinitionHandle, ArrayBuilder<TypeDefinitionHandle>>(NamespaceHandleEqualityComparer.Singleton);
foreach (TypeDefToNamespace pair in GetTypeDefsOrThrow(topLevelOnly: true))
{
NamespaceDefinitionHandle nsHandle = pair.NamespaceHandle;
TypeDefinitionHandle typeDef = pair.TypeDef;
ArrayBuilder<TypeDefinitionHandle> builder;
if (namespaceHandles.TryGetValue(nsHandle, out builder))
{
builder.Add(typeDef);
}
else
{
namespaceHandles.Add(nsHandle, new ArrayBuilder<TypeDefinitionHandle> { typeDef });
}
}
foreach (var kvp in namespaceHandles)
{
string @namespace = MetadataReader.GetString(kvp.Key);
ArrayBuilder<TypeDefinitionHandle> builder;
if (namespaces.TryGetValue(@namespace, out builder))
{
builder.AddRange(kvp.Value);
}
else
{
namespaces.Add(@namespace, kvp.Value);
}
}
}
private class NamespaceHandleEqualityComparer : IEqualityComparer<NamespaceDefinitionHandle>
{
public static readonly NamespaceHandleEqualityComparer Singleton = new NamespaceHandleEqualityComparer();
private NamespaceHandleEqualityComparer()
{
}
public bool Equals(NamespaceDefinitionHandle x, NamespaceDefinitionHandle y)
{
return x == y;
}
public int GetHashCode(NamespaceDefinitionHandle obj)
{
return obj.GetHashCode();
}
}
/// <summary>
/// Supplements the namespace-to-RowIDs map with the namespaces of forwarded types.
/// These types will not have associated row IDs (represented as null, for efficiency).
/// These namespaces are important because we want lookups of missing forwarded types
/// to succeed far enough that we can actually find the type forwarder and provide
/// information about the target assembly.
///
/// For example, consider the following forwarded type:
///
/// .class extern forwarder Namespace.Type {}
///
/// If this type is referenced in source as "Namespace.Type", then dev10 reports
///
/// error CS1070: The type name 'Namespace.Name' could not be found. This type has been
/// forwarded to assembly 'pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
/// Consider adding a reference to that assembly.
///
/// If we did not include "Namespace" as a child of the global namespace of this module
/// (the forwarding module), then Roslyn would report that the type "Namespace" was not
/// found and say nothing about "Name" (because of the diagnostic already attached to
/// the qualifier).
/// </summary>
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
private void GetForwardedTypeNamespaceNamesOrThrow(Dictionary<string, ArrayBuilder<TypeDefinitionHandle>> namespaces)
{
EnsureForwardTypeToAssemblyMap();
foreach (var typeName in _lazyForwardedTypesToAssemblyIndexMap.Keys)
{
int index = typeName.LastIndexOf('.');
string namespaceName = index >= 0 ? typeName.Substring(0, index) : "";
if (!namespaces.ContainsKey(namespaceName))
{
namespaces.Add(namespaceName, null);
}
}
}
private IdentifierCollection ComputeTypeNameCollection()
{
try
{
var allTypeDefs = GetTypeDefsOrThrow(topLevelOnly: false);
var typeNames =
from typeDef in allTypeDefs
let metadataName = GetTypeDefNameOrThrow(typeDef.TypeDef)
let backtickIndex = metadataName.IndexOf('`')
select backtickIndex < 0 ? metadataName : metadataName.Substring(0, backtickIndex);
return new IdentifierCollection(typeNames);
}
catch (BadImageFormatException)
{
return new IdentifierCollection();
}
}
private IdentifierCollection ComputeNamespaceNameCollection()
{
try
{
var allTypeIds = GetTypeDefsOrThrow(topLevelOnly: true);
var fullNamespaceNames =
from id in allTypeIds
where !id.NamespaceHandle.IsNil
select MetadataReader.GetString(id.NamespaceHandle);
var namespaceNames =
from fullName in fullNamespaceNames.Distinct()
from name in fullName.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries)
select name;
return new IdentifierCollection(namespaceNames);
}
catch (BadImageFormatException)
{
return new IdentifierCollection();
}
}
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
internal ImmutableArray<TypeDefinitionHandle> GetNestedTypeDefsOrThrow(TypeDefinitionHandle container)
{
return MetadataReader.GetTypeDefinition(container).GetNestedTypes();
}
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
internal MethodImplementationHandleCollection GetMethodImplementationsOrThrow(TypeDefinitionHandle typeDef)
{
return MetadataReader.GetTypeDefinition(typeDef).GetMethodImplementations();
}
/// <summary>
/// Returns a collection of interfaces implemented by given type.
/// </summary>
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
internal InterfaceImplementationHandleCollection GetInterfaceImplementationsOrThrow(TypeDefinitionHandle typeDef)
{
return MetadataReader.GetTypeDefinition(typeDef).GetInterfaceImplementations();
}
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
internal MethodDefinitionHandleCollection GetMethodsOfTypeOrThrow(TypeDefinitionHandle typeDef)
{
return MetadataReader.GetTypeDefinition(typeDef).GetMethods();
}
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
internal PropertyDefinitionHandleCollection GetPropertiesOfTypeOrThrow(TypeDefinitionHandle typeDef)
{
return MetadataReader.GetTypeDefinition(typeDef).GetProperties();
}
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
internal EventDefinitionHandleCollection GetEventsOfTypeOrThrow(TypeDefinitionHandle typeDef)
{
return MetadataReader.GetTypeDefinition(typeDef).GetEvents();
}
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
internal FieldDefinitionHandleCollection GetFieldsOfTypeOrThrow(TypeDefinitionHandle typeDef)
{
return MetadataReader.GetTypeDefinition(typeDef).GetFields();
}
/// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
internal EntityHandle GetBaseTypeOfTypeOrThrow(TypeDefinitionHandle typeDef)
{
return MetadataReader.GetTypeDefinition(typeDef).BaseType;
}
internal TypeLayout GetTypeLayout(TypeDefinitionHandle typeDef)
{
try
{
// CLI Spec 22.8.3:
// The Class or ValueType indexed by Parent shall be SequentialLayout or ExplicitLayout.
// That is, AutoLayout types shall not own any rows in the ClassLayout table.
var def = MetadataReader.GetTypeDefinition(typeDef);
LayoutKind kind;
switch (def.Attributes & TypeAttributes.LayoutMask)
{
case TypeAttributes.SequentialLayout:
kind = LayoutKind.Sequential;
break;
case TypeAttributes.ExplicitLayout:
kind = LayoutKind.Explicit;
break;
case TypeAttributes.AutoLayout:
return default(TypeLayout);
default:
// TODO (tomat) report error:
return default(TypeLayout);
}
var layout = def.GetLayout();
int size = layout.Size;
int packingSize = layout.PackingSize;
if (packingSize > byte.MaxValue)
{
// TODO (tomat) report error:
packingSize = 0;
}
if (size < 0)
{
// TODO (tomat) report error:
size = 0;
}
return new TypeLayout(kind, size, (byte)packingSize);
}
catch (BadImageFormatException)
{
return default(TypeLayout);
}
}
internal bool IsNoPiaLocalType(TypeDefinitionHandle typeDef)
{
AttributeInfo attributeInfo;
return IsNoPiaLocalType(typeDef, out attributeInfo);
}
internal bool HasParamArrayAttribute(EntityHandle token)
{
return FindTargetAttribute(token, AttributeDescription.ParamArrayAttribute).HasValue;
}
internal bool HasParamCollectionAttribute(EntityHandle token)
{
return FindTargetAttribute(token, AttributeDescription.ParamCollectionAttribute).HasValue;
}
internal bool HasIsReadOnlyAttribute(EntityHandle token)
{
return FindTargetAttribute(token, AttributeDescription.IsReadOnlyAttribute).HasValue;
}
internal bool HasDoesNotReturnAttribute(EntityHandle token)