forked from dotnet/msbuild
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAssemblyInformation.cs
More file actions
1205 lines (1058 loc) · 46.2 KB
/
Copy pathAssemblyInformation.cs
File metadata and controls
1205 lines (1058 loc) · 46.2 KB
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.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
#if !FEATURE_ASSEMBLYLOADCONTEXT
using System.Linq;
using System.Runtime.InteropServices;
#endif
using System.Reflection;
using System.Runtime.Versioning;
using System.Text;
using Microsoft.Build.Shared;
using Microsoft.Build.Shared.FileSystem;
#if FEATURE_ASSEMBLYLOADCONTEXT
using System.Reflection.PortableExecutable;
using System.Reflection.Metadata;
#endif
using Microsoft.Build.Tasks.AssemblyDependency;
#nullable disable
using Microsoft.Build.Framework;
namespace Microsoft.Build.Tasks
{
/// <summary>
/// Collection of methods used to discover assembly metadata.
/// Primarily stolen from manifestutility.cs AssemblyMetaDataImport class.
/// </summary>
internal class AssemblyInformation : DisposableBase
{
private AssemblyNameExtension[] _assemblyDependencies;
private string[] _assemblyFiles;
#if !FEATURE_ASSEMBLYLOADCONTEXT
private readonly IMetaDataDispenser _metadataDispenser;
private readonly IMetaDataAssemblyImport _assemblyImport;
private static Guid s_importerGuid = new Guid(((GuidAttribute)Attribute.GetCustomAttribute(typeof(IMetaDataImport), typeof(GuidAttribute), false)).Value);
private readonly Assembly _assembly;
#endif
private readonly string _sourceFile;
private FrameworkName _frameworkName;
#if FEATURE_ASSEMBLYLOADCONTEXT
private bool _metadataRead;
#endif
#if !FEATURE_ASSEMBLYLOADCONTEXT
private const string s_targetFrameworkAttribute = "System.Runtime.Versioning.TargetFrameworkAttribute";
#endif
#if !FEATURE_ASSEMBLYLOADCONTEXT
// Borrowed from genman.
private const int GENMAN_STRING_BUF_SIZE = 1024;
private const int GENMAN_LOCALE_BUF_SIZE = 64;
private const int GENMAN_ENUM_TOKEN_BUF_SIZE = 16; // 128 from genman seems too big.
static AssemblyInformation()
{
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += ReflectionOnlyAssemblyResolve;
}
#endif // FEATURE_ASSEMBLY_LOADFROM
/// <summary>
/// Construct an instance for a source file.
/// </summary>
/// <param name="sourceFile">The assembly.</param>
internal AssemblyInformation(string sourceFile)
{
// Extra checks for PInvoke-destined data.
ErrorUtilities.VerifyThrowArgumentNull(sourceFile);
_sourceFile = sourceFile;
#if !FEATURE_ASSEMBLYLOADCONTEXT
if (NativeMethodsShared.IsWindows)
{
// Create the metadata dispenser and open scope on the source file.
_metadataDispenser = (IMetaDataDispenser)new CorMetaDataDispenser();
_assemblyImport = (IMetaDataAssemblyImport)_metadataDispenser.OpenScope(sourceFile, 0, ref s_importerGuid);
}
else
{
_assembly = Assembly.ReflectionOnlyLoadFrom(sourceFile);
}
#endif
}
#if !FEATURE_ASSEMBLYLOADCONTEXT
private static Assembly ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args)
{
string[] nameParts = args.Name.Split(MSBuildConstants.CommaChar);
Assembly assembly = null;
if (args.RequestingAssembly != null && !string.IsNullOrEmpty(args.RequestingAssembly.Location) && nameParts.Length > 0)
{
var location = args.RequestingAssembly.Location;
var newLocation = Path.Combine(Path.GetDirectoryName(location), nameParts[0].Trim() + ".dll");
try
{
if (FileSystems.Default.FileExists(newLocation))
{
assembly = Assembly.ReflectionOnlyLoadFrom(newLocation);
}
}
catch
{
}
}
// Let's try to automatically load it
if (assembly == null)
{
try
{
assembly = Assembly.ReflectionOnlyLoad(args.Name);
}
catch
{
}
}
return assembly;
}
#endif
/// <summary>
/// Get the dependencies.
/// </summary>
/// <value></value>
public AssemblyNameExtension[] Dependencies
{
get
{
if (_assemblyDependencies == null)
{
lock (this)
{
if (_assemblyDependencies == null)
{
_assemblyDependencies = ImportAssemblyDependencies();
}
}
}
return _assemblyDependencies;
}
}
/// <summary>
/// Get the scatter files from the assembly metadata.
/// </summary>
public string[] Files
{
get
{
if (_assemblyFiles == null)
{
lock (this)
{
if (_assemblyFiles == null)
{
_assemblyFiles = ImportFiles();
}
}
}
return _assemblyFiles;
}
}
/// <summary>
/// What was the framework name that the assembly was built against.
/// </summary>
public FrameworkName FrameworkNameAttribute
{
get
{
if (_frameworkName == null)
{
lock (this)
{
if (_frameworkName == null)
{
_frameworkName = GetFrameworkName();
}
}
}
return _frameworkName;
}
}
/// <summary>
/// Given an assembly name, crack it open and retrieve the list of dependent
/// assemblies and the list of scatter files.
/// </summary>
/// <param name="path">Path to the assembly.</param>
/// <param name="assemblyMetadataCache">Cache of pre-extracted assembly metadata.</param>
/// <param name="dependencies">Receives the list of dependencies.</param>
/// <param name="scatterFiles">Receives the list of associated scatter files.</param>
/// <param name="frameworkName">Gets the assembly name.</param>
internal static void GetAssemblyMetadata(
string path,
ConcurrentDictionary<string, AssemblyMetadata> assemblyMetadataCache,
out AssemblyNameExtension[] dependencies,
out string[] scatterFiles,
out FrameworkName frameworkName)
{
var import = assemblyMetadataCache?.GetOrAdd(path, p => new AssemblyMetadata(p))
?? new AssemblyMetadata(path);
dependencies = import.Dependencies;
frameworkName = import.FrameworkName;
scatterFiles = import.ScatterFiles;
}
/// <summary>
/// Given an assembly name, crack it open and retrieve the TargetFrameworkAttribute
/// assemblies and the list of scatter files.
/// </summary>
internal static FrameworkName GetTargetFrameworkAttribute(string path)
{
using (var import = new AssemblyInformation(path))
{
return import.FrameworkNameAttribute;
}
}
/// <summary>
/// Determine if an file is a winmd file or not.
/// </summary>
internal static bool IsWinMDFile(
string fullPath,
GetAssemblyRuntimeVersion getAssemblyRuntimeVersion,
FileExists fileExists,
out string imageRuntimeVersion,
out bool isManagedWinmd)
{
imageRuntimeVersion = String.Empty;
isManagedWinmd = false;
if (!NativeMethodsShared.IsWindows)
{
return false;
}
// May be null or empty is the file was never resolved to a path on disk.
if (!String.IsNullOrEmpty(fullPath) && fileExists(fullPath))
{
imageRuntimeVersion = getAssemblyRuntimeVersion(fullPath);
if (!String.IsNullOrEmpty(imageRuntimeVersion))
{
bool containsWindowsRuntime = imageRuntimeVersion.IndexOf(
"WindowsRuntime",
StringComparison.OrdinalIgnoreCase) >= 0;
if (containsWindowsRuntime)
{
isManagedWinmd = imageRuntimeVersion.IndexOf("CLR", StringComparison.OrdinalIgnoreCase) >= 0;
return true;
}
}
}
return false;
}
#if !FEATURE_ASSEMBLYLOADCONTEXT
/// <summary>
/// Collects the metadata and attributes for specified assembly.
/// The requested properties are used by legacy project system.
/// </summary>
internal AssemblyAttributes GetAssemblyMetadata()
{
IntPtr asmMetaPtr = IntPtr.Zero;
ASSEMBLYMETADATA asmMeta = new();
try
{
IMetaDataImport2 import2 = (IMetaDataImport2)_assemblyImport;
_assemblyImport.GetAssemblyFromScope(out uint assemblyScope);
// get the assembly, if there is no assembly, it is a module reference
if (assemblyScope == 0)
{
return null;
}
AssemblyAttributes assemblyAttributes = new()
{
AssemblyFullPath = _sourceFile,
IsAssembly = true,
};
// will be populated with the assembly name
char[] defaultCharArray = new char[GENMAN_STRING_BUF_SIZE];
asmMetaPtr = AllocAsmMeta();
_assemblyImport.GetAssemblyProps(
assemblyScope,
out IntPtr publicKeyPtr,
out uint publicKeyLength,
out uint hashAlgorithmId,
defaultCharArray,
// the default buffer size is taken from csproj call
GENMAN_STRING_BUF_SIZE,
out uint nameLength,
asmMetaPtr,
out uint flags);
assemblyAttributes.AssemblyName = new string(defaultCharArray, 0, (int)nameLength - 1);
assemblyAttributes.DefaultAlias = assemblyAttributes.AssemblyName;
asmMeta = (ASSEMBLYMETADATA)Marshal.PtrToStructure(asmMetaPtr, typeof(ASSEMBLYMETADATA));
assemblyAttributes.MajorVersion = asmMeta.usMajorVersion;
assemblyAttributes.MinorVersion = asmMeta.usMinorVersion;
assemblyAttributes.RevisionNumber = asmMeta.usRevisionNumber;
assemblyAttributes.BuildNumber = asmMeta.usBuildNumber;
assemblyAttributes.Culture = Marshal.PtrToStringUni(asmMeta.rpLocale);
byte[] publicKey = new byte[publicKeyLength];
Marshal.Copy(publicKeyPtr, publicKey, 0, (int)publicKeyLength);
assemblyAttributes.PublicHexKey = BitConverter.ToString(publicKey).Replace("-", string.Empty);
if (import2 != null)
{
assemblyAttributes.Description = GetStringCustomAttribute(import2, assemblyScope, "System.Reflection.AssemblyDescriptionAttribute");
assemblyAttributes.TargetFrameworkMoniker = GetStringCustomAttribute(import2, assemblyScope, "System.Runtime.Versioning.TargetFrameworkAttribute");
var guid = GetStringCustomAttribute(import2, assemblyScope, "System.Runtime.InteropServices.GuidAttribute");
if (!string.IsNullOrEmpty(guid))
{
string importedFromTypeLibString = GetStringCustomAttribute(import2, assemblyScope, "System.Runtime.InteropServices.ImportedFromTypeLibAttribute");
if (!string.IsNullOrEmpty(importedFromTypeLibString))
{
assemblyAttributes.IsImportedFromTypeLib = true;
}
else
{
string primaryInteropAssemblyString = GetStringCustomAttribute(import2, assemblyScope, "System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute");
assemblyAttributes.IsImportedFromTypeLib = !string.IsNullOrEmpty(primaryInteropAssemblyString);
}
}
}
assemblyAttributes.RuntimeVersion = GetRuntimeVersion(_sourceFile);
import2.GetPEKind(out uint peKind, out _);
assemblyAttributes.PeKind = peKind;
return assemblyAttributes;
}
finally
{
FreeAsmMeta(asmMetaPtr, ref asmMeta);
}
}
private string GetStringCustomAttribute(IMetaDataImport2 import2, uint assemblyScope, string attributeName)
{
int hr = import2.GetCustomAttributeByName(assemblyScope, attributeName, out IntPtr data, out uint valueLen);
if (hr == NativeMethodsShared.S_OK)
{
// if an custom attribute exists, parse the contents of the blob
if (NativeMethods.TryReadMetadataString(_sourceFile, data, valueLen, out string propertyValue))
{
return propertyValue;
}
}
return string.Empty;
}
#endif
/// <summary>
/// Get the framework name from the assembly.
/// </summary>
private FrameworkName GetFrameworkName()
{
#if !FEATURE_ASSEMBLYLOADCONTEXT
if (!NativeMethodsShared.IsWindows)
{
CustomAttributeData attr = null;
foreach (CustomAttributeData a in _assembly.GetCustomAttributesData())
{
try
{
if (a.AttributeType == typeof(TargetFrameworkAttribute))
{
attr = a;
break;
}
}
catch
{
}
}
string name = null;
if (attr != null)
{
name = (string)attr.ConstructorArguments[0].Value;
}
return name == null ? null : new FrameworkName(name);
}
FrameworkName frameworkAttribute = null;
try
{
var import2 = (IMetaDataImport2)_assemblyImport;
_assemblyImport.GetAssemblyFromScope(out uint assemblyScope);
string frameworkNameAttribute = GetStringCustomAttribute(import2, assemblyScope, s_targetFrameworkAttribute);
if (!string.IsNullOrEmpty(frameworkNameAttribute))
{
frameworkAttribute = new FrameworkName(frameworkNameAttribute);
}
}
catch (Exception e) when (!ExceptionHandling.IsCriticalException(e))
{
}
return frameworkAttribute;
#else
CorePopulateMetadata();
return _frameworkName;
#endif
}
#if FEATURE_ASSEMBLYLOADCONTEXT
/// <summary>
/// Read everything from the assembly in a single stream.
/// </summary>
/// <returns></returns>
private void CorePopulateMetadata()
{
if (_metadataRead)
{
return;
}
lock (this)
{
if (_metadataRead)
{
return;
}
using (var stream = File.OpenRead(_sourceFile))
using (var peFile = new PEReader(stream))
{
bool hasMetadata = false;
try
{
// This can throw if the stream is too small, which means
// the assembly doesn't have metadata.
hasMetadata = peFile.HasMetadata;
}
finally
{
// If the file does not contain PE metadata, throw BadImageFormatException to preserve
// behavior from AssemblyName.GetAssemblyName(). RAR will deal with this correctly.
if (!hasMetadata)
{
throw new BadImageFormatException(string.Format(CultureInfo.CurrentCulture,
AssemblyResources.GetString("ResolveAssemblyReference.AssemblyDoesNotContainPEMetadata"),
_sourceFile));
}
}
var metadataReader = peFile.GetMetadataReader();
var assemblyReferences = metadataReader.AssemblyReferences;
List<AssemblyNameExtension> ret = new List<AssemblyNameExtension>(assemblyReferences.Count);
foreach (var handle in assemblyReferences)
{
var assemblyName = GetAssemblyName(metadataReader, handle);
ret.Add(new AssemblyNameExtension(assemblyName));
}
_assemblyDependencies = ret.ToArray();
foreach (var attrHandle in metadataReader.GetAssemblyDefinition().GetCustomAttributes())
{
var attr = metadataReader.GetCustomAttribute(attrHandle);
var ctorHandle = attr.Constructor;
if (ctorHandle.Kind != HandleKind.MemberReference)
{
continue;
}
var container = metadataReader.GetMemberReference((MemberReferenceHandle)ctorHandle).Parent;
if (container.Kind != HandleKind.TypeReference)
{
continue;
}
var name = metadataReader.GetTypeReference((TypeReferenceHandle)container).Name;
if (!string.Equals(metadataReader.GetString(name), "TargetFrameworkAttribute"))
{
continue;
}
var arguments = GetFixedStringArguments(metadataReader, attr);
if (arguments.Count == 1)
{
_frameworkName = new FrameworkName(arguments[0]);
}
}
var assemblyFilesCollection = metadataReader.AssemblyFiles;
List<string> assemblyFiles = new List<string>(assemblyFilesCollection.Count);
foreach (var fileHandle in assemblyFilesCollection)
{
assemblyFiles.Add(metadataReader.GetString(metadataReader.GetAssemblyFile(fileHandle).Name));
}
_assemblyFiles = assemblyFiles.ToArray();
}
_metadataRead = true;
}
}
// https://github.com/dotnet/msbuild/issues/4002
// https://github.com/dotnet/corefx/issues/34008
//
// We do not use AssemblyReference.GetAssemblyName() here because its behavior
// is different from other code paths with respect to neutral culture. We will
// get unspecified culture instead of explicitly neutral culture. This in turn
// leads string comparisons of assembly-name-modulo-version in RAR to false
// negatives that break its conflict resolution and binding redirect generation.
private static AssemblyName GetAssemblyName(MetadataReader metadataReader, AssemblyReferenceHandle handle)
{
var entry = metadataReader.GetAssemblyReference(handle);
var assemblyName = new AssemblyName
{
Name = metadataReader.GetString(entry.Name),
Version = entry.Version,
CultureName = metadataReader.GetString(entry.Culture)
};
var publicKeyOrToken = metadataReader.GetBlobBytes(entry.PublicKeyOrToken);
if (publicKeyOrToken != null)
{
if (publicKeyOrToken.Length <= 8)
{
assemblyName.SetPublicKeyToken(publicKeyOrToken);
}
else
{
assemblyName.SetPublicKey(publicKeyOrToken);
}
}
assemblyName.Flags = (AssemblyNameFlags)(int)entry.Flags;
return assemblyName;
}
#endif
#if FEATURE_ASSEMBLYLOADCONTEXT
// This method copied from DNX source: https://github.com/aspnet/dnx/blob/e0726f769aead073af2d8cd9db47b89e1745d574/src/Microsoft.Dnx.Tooling/Utils/LockFileUtils.cs#L385
// System.Reflection.Metadata 1.1 is expected to have an API that helps with this.
/// <summary>
/// Gets the fixed (required) string arguments of a custom attribute.
/// Only attributes that have only fixed string arguments.
/// </summary>
private static List<string> GetFixedStringArguments(MetadataReader reader, CustomAttribute attribute)
{
// TODO: Nick Guerrera (Nick.Guerrera@microsoft.com) hacked this method for temporary use.
// There is a blob decoder feature in progress but it won't ship in time for our milestone.
// Replace this method with the blob decoder feature when later it is availale.
var signature = reader.GetMemberReference((MemberReferenceHandle)attribute.Constructor).Signature;
var signatureReader = reader.GetBlobReader(signature);
var valueReader = reader.GetBlobReader(attribute.Value);
var arguments = new List<string>();
var prolog = valueReader.ReadUInt16();
if (prolog != 1)
{
// Invalid custom attribute prolog
return arguments;
}
var header = signatureReader.ReadSignatureHeader();
if (header.Kind != SignatureKind.Method || header.IsGeneric)
{
// Invalid custom attribute constructor signature
return arguments;
}
int parameterCount;
if (!signatureReader.TryReadCompressedInteger(out parameterCount))
{
// Invalid custom attribute constructor signature
return arguments;
}
var returnType = signatureReader.ReadSignatureTypeCode();
if (returnType != SignatureTypeCode.Void)
{
// Invalid custom attribute constructor signature
return arguments;
}
for (int i = 0; i < parameterCount; i++)
{
var signatureTypeCode = signatureReader.ReadSignatureTypeCode();
if (signatureTypeCode == SignatureTypeCode.String)
{
// Custom attribute constructor must take only strings
arguments.Add(valueReader.ReadSerializedString());
}
}
return arguments;
}
#endif
#if !FEATURE_ASSEMBLYLOADCONTEXT
/// <summary>
/// Release interface pointers on Dispose().
/// </summary>
protected override void DisposeUnmanagedResources()
{
if (NativeMethodsShared.IsWindows)
{
if (_assemblyImport != null)
{
Marshal.ReleaseComObject(_assemblyImport);
}
if (_metadataDispenser != null)
{
Marshal.ReleaseComObject(_metadataDispenser);
}
}
}
#endif
/// <summary>
/// Given a path get the CLR runtime version of the file
/// </summary>
/// <param name="path">path to the file</param>
/// <returns>The CLR runtime version or empty if the path does not exist.</returns>
internal static string GetRuntimeVersion(string path)
{
#if FEATURE_MSCOREE
if (NativeMethodsShared.IsWindows)
{
#if DEBUG
// Just to make sure and exercise the code that uses dwLength to allocate the buffer
// when GetRequestedRuntimeInfo fails due to insufficient buffer size.
int bufferLength = 1;
#else
int bufferLength = 11; // 11 is the length of a runtime version and null terminator v2.0.50727/0
#endif
unsafe
{
// Allocate an initial buffer
char* runtimeVersion = stackalloc char[bufferLength];
// Run GetFileVersion, this should succeed using the initial buffer.
// It also returns the dwLength which is used if there is insufficient buffer.
uint hresult = NativeMethods.GetFileVersion(path, runtimeVersion, bufferLength, out int dwLength);
if (hresult == NativeMethodsShared.ERROR_INSUFFICIENT_BUFFER)
{
// Allocate new buffer based on the returned length.
char* runtimeVersion2 = stackalloc char[dwLength];
runtimeVersion = runtimeVersion2;
// Get the RuntimeVersion in this second call.
bufferLength = dwLength;
hresult = NativeMethods.GetFileVersion(path, runtimeVersion, bufferLength, out dwLength);
}
return hresult == NativeMethodsShared.S_OK ? new string(runtimeVersion, 0, dwLength - 1) : string.Empty;
}
}
else
{
return ManagedRuntimeVersionReader.GetRuntimeVersion(path);
}
#else
return ManagedRuntimeVersionReader.GetRuntimeVersion(path);
#endif
}
/// <summary>
/// Import assembly dependencies.
/// </summary>
/// <returns>The array of assembly dependencies.</returns>
private AssemblyNameExtension[] ImportAssemblyDependencies()
{
#if !FEATURE_ASSEMBLYLOADCONTEXT
var asmRefs = new List<AssemblyNameExtension>();
if (!NativeMethodsShared.IsWindows)
{
return _assembly.GetReferencedAssemblies().Select(a => new AssemblyNameExtension(a)).ToArray();
}
IntPtr asmRefEnum = IntPtr.Zero;
var asmRefTokens = new UInt32[GENMAN_ENUM_TOKEN_BUF_SIZE];
// Ensure the enum handle is closed.
try
{
// Enum chunks of refs in 16-ref blocks until we run out.
UInt32 fetched;
do
{
_assemblyImport.EnumAssemblyRefs(
ref asmRefEnum,
asmRefTokens,
(uint)asmRefTokens.Length,
out fetched);
for (uint i = 0; i < fetched; i++)
{
// Determine the length of the string to contain the name first.
_assemblyImport.GetAssemblyRefProps(
asmRefTokens[i],
out IntPtr pubKeyPtr,
out uint pubKeyBytes,
null,
0,
out uint asmNameLength,
IntPtr.Zero,
out _,
out _,
out uint flags);
// Allocate assembly name buffer.
var asmNameBuf = new char[asmNameLength + 1];
IntPtr asmMetaPtr = IntPtr.Zero;
// Ensure metadata structure is freed.
try
{
// Allocate metadata structure.
asmMetaPtr = AllocAsmMeta();
// Retrieve the assembly reference properties.
_assemblyImport.GetAssemblyRefProps(
asmRefTokens[i],
out pubKeyPtr,
out pubKeyBytes,
asmNameBuf,
(uint)asmNameBuf.Length,
out asmNameLength,
asmMetaPtr,
out _,
out _,
out flags);
// Construct the assembly name and free metadata structure.
AssemblyNameExtension asmName = ConstructAssemblyName(
asmMetaPtr,
asmNameBuf,
asmNameLength,
pubKeyPtr,
pubKeyBytes,
flags);
// Add the assembly name to the reference list.
asmRefs.Add(asmName);
}
finally
{
FreeAsmMeta(asmMetaPtr);
}
}
} while (fetched > 0);
}
finally
{
if (asmRefEnum != IntPtr.Zero)
{
_assemblyImport.CloseEnum(asmRefEnum);
}
}
return asmRefs.ToArray();
#else
CorePopulateMetadata();
return _assemblyDependencies;
#endif
}
/// <summary>
/// Import extra files. These are usually consituent members of a scatter assembly.
/// </summary>
/// <returns>The extra files of assembly dependencies.</returns>
private string[] ImportFiles()
{
#if !FEATURE_ASSEMBLYLOADCONTEXT
var files = new List<string>();
IntPtr fileEnum = IntPtr.Zero;
var fileTokens = new UInt32[GENMAN_ENUM_TOKEN_BUF_SIZE];
var fileNameBuf = new char[GENMAN_STRING_BUF_SIZE];
// Ensure the enum handle is closed.
try
{
// Enum chunks of files until we run out.
UInt32 fetched;
do
{
_assemblyImport.EnumFiles(ref fileEnum, fileTokens, (uint)fileTokens.Length, out fetched);
for (uint i = 0; i < fetched; i++)
{
// Retrieve file properties.
_assemblyImport.GetFileProps(fileTokens[i],
fileNameBuf, (uint)fileNameBuf.Length, out uint fileNameLength,
out _, out _, out _);
// Add file to file list.
string file = new string(fileNameBuf, 0, (int)(fileNameLength - 1));
files.Add(file);
}
} while (fetched > 0);
}
finally
{
if (fileEnum != IntPtr.Zero)
{
_assemblyImport.CloseEnum(fileEnum);
}
}
return files.ToArray();
#else
CorePopulateMetadata();
return _assemblyFiles;
#endif
}
#if !FEATURE_ASSEMBLYLOADCONTEXT
/// <summary>
/// Allocate assembly metadata structure buffer.
/// </summary>
/// <returns>Pointer to structure</returns>
private static IntPtr AllocAsmMeta()
{
ASSEMBLYMETADATA asmMeta;
asmMeta.usMajorVersion = asmMeta.usMinorVersion = asmMeta.usBuildNumber = asmMeta.usRevisionNumber = 0;
asmMeta.cOses = asmMeta.cProcessors = 0;
asmMeta.rOses = asmMeta.rpProcessors = IntPtr.Zero;
// Allocate buffer for locale.
asmMeta.rpLocale = Marshal.AllocCoTaskMem(GENMAN_LOCALE_BUF_SIZE * 2);
asmMeta.cchLocale = GENMAN_LOCALE_BUF_SIZE;
// Convert to unmanaged structure.
int size = Marshal.SizeOf<ASSEMBLYMETADATA>();
IntPtr asmMetaPtr = Marshal.AllocCoTaskMem(size);
Marshal.StructureToPtr(asmMeta, asmMetaPtr, false);
return asmMetaPtr;
}
/// <summary>
/// Construct assembly name.
/// </summary>
/// <param name="asmMetaPtr">Assembly metadata structure</param>
/// <param name="asmNameBuf">Buffer containing the name</param>
/// <param name="asmNameLength">Length of that buffer</param>
/// <param name="pubKeyPtr">Pointer to public key</param>
/// <param name="pubKeyBytes">Count of bytes in public key.</param>
/// <param name="flags">Extra flags</param>
/// <returns>The assembly name.</returns>
private static AssemblyNameExtension ConstructAssemblyName(IntPtr asmMetaPtr, char[] asmNameBuf, UInt32 asmNameLength, IntPtr pubKeyPtr, UInt32 pubKeyBytes, UInt32 flags)
{
// Marshal the assembly metadata back to a managed type.
ASSEMBLYMETADATA asmMeta = (ASSEMBLYMETADATA)Marshal.PtrToStructure(asmMetaPtr, typeof(ASSEMBLYMETADATA));
// Construct the assembly name. (Note asmNameLength should/must be > 0.)
var assemblyName = new AssemblyName
{
Name = new string(asmNameBuf, 0, (int)asmNameLength - 1),
Version = new Version(
asmMeta.usMajorVersion,
asmMeta.usMinorVersion,
asmMeta.usBuildNumber,
asmMeta.usRevisionNumber)
};
// Set culture info.
string locale = Marshal.PtrToStringUni(asmMeta.rpLocale);
if (locale.Length > 0)
{
assemblyName.CultureInfo = CultureInfo.CreateSpecificCulture(locale);
}
else
{
assemblyName.CultureInfo = CultureInfo.CreateSpecificCulture(String.Empty);
}
// Set public key or PKT.
var publicKey = new byte[pubKeyBytes];
Marshal.Copy(pubKeyPtr, publicKey, 0, (int)pubKeyBytes);
if ((flags & (uint)CorAssemblyFlags.afPublicKey) != 0)
{
assemblyName.SetPublicKey(publicKey);
}
else
{
assemblyName.SetPublicKeyToken(publicKey);
}
assemblyName.Flags = (AssemblyNameFlags)flags;
return new AssemblyNameExtension(assemblyName);
}
/// <summary>
/// Free the assembly metadata structure.
/// </summary>
/// <param name="asmMetaPtr">The pointer.</param>
private static void FreeAsmMeta(IntPtr asmMetaPtr)
{
if (asmMetaPtr != IntPtr.Zero)
{
// Marshal the assembly metadata back to a managed type.
var asmMeta = (ASSEMBLYMETADATA)Marshal.PtrToStructure(asmMetaPtr, typeof(ASSEMBLYMETADATA));
FreeAsmMeta(asmMetaPtr, ref asmMeta);
}
}
/// <summary>
/// Free the assembly metadata structure.
/// </summary>
/// <param name="asmMetaPtr">The pointer.</param>
/// <param name="asmMeta">Marshaled assembly metadata to the managed type.</param>
private static void FreeAsmMeta(IntPtr asmMetaPtr, ref ASSEMBLYMETADATA asmMeta)
{
if (asmMetaPtr != IntPtr.Zero)
{
// Free unmanaged memory.
Marshal.FreeCoTaskMem(asmMeta.rpLocale);
asmMeta.rpLocale = IntPtr.Zero;
Marshal.DestroyStructure(asmMetaPtr, typeof(ASSEMBLYMETADATA));
Marshal.FreeCoTaskMem(asmMetaPtr);
}
}
#endif
}
/// <summary>
/// Managed implementation of a reader for getting the runtime version of an assembly
/// </summary>
internal static class ManagedRuntimeVersionReader
{
private class HeaderInfo
{
public uint VirtualAddress;
public uint Size;
public uint FileOffset;
}
/// <summary>
/// Given a path get the CLR runtime version of the file.
/// </summary>
/// <param name="path">path to the file</param>
/// <returns>The CLR runtime version or empty if the path does not exist or the file is not an assembly.</returns>
public static string GetRuntimeVersion(string path)
{
if (!FileSystems.Default.FileExists(path))
{
return string.Empty;
}
using Stream stream = File.OpenRead(path);
using BinaryReader reader = new BinaryReader(stream);
return GetRuntimeVersion(reader);
}
/// <summary>
/// Given a <see cref="BinaryReader"/> get the CLR runtime version of the underlying file.
/// </summary>
/// <param name="sr">A <see cref="BinaryReader"/> positioned at the first byte of the file.</param>
/// <returns>The CLR runtime version or empty if the data does not represent an assembly.</returns>
internal static string GetRuntimeVersion(BinaryReader sr)
{
// This algorithm for getting the runtime version is based on
// the ECMA Standard 335: The Common Language Infrastructure (CLI)
// http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-335.pdf
try
{
const uint PEHeaderPointerOffset = 0x3c;
const uint PEHeaderSize = 20;
const uint OptionalPEHeaderSize = 224;
const uint OptionalPEPlusHeaderSize = 240;
const uint SectionHeaderSize = 40;