|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT license. See LICENSE file in the project root for full license information. |
| 3 | + |
| 4 | +using System.Reflection.Metadata; |
| 5 | +using System.Reflection.PortableExecutable; |
| 6 | +using System.Security; |
| 7 | +#if NET && !WINDOWS_UWP |
| 8 | +using System.Runtime.Loader; |
| 9 | +#endif |
| 10 | + |
| 11 | +using Microsoft.VisualStudio.TestTools.UnitTesting; |
| 12 | + |
| 13 | +namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution; |
| 14 | + |
| 15 | +internal sealed partial class TypeCache |
| 16 | +{ |
| 17 | + private static bool TryReadProviderMetadata(string path, out bool hasMarker, out AssemblyName[] references) |
| 18 | + { |
| 19 | + hasMarker = false; |
| 20 | + references = []; |
| 21 | + try |
| 22 | + { |
| 23 | + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); |
| 24 | + using var peReader = new PEReader(stream, PEStreamOptions.PrefetchMetadata); |
| 25 | + MetadataReader reader = peReader.GetMetadataReader(); |
| 26 | + AssemblyDefinition definition = reader.GetAssemblyDefinition(); |
| 27 | + foreach (CustomAttributeHandle handle in definition.GetCustomAttributes()) |
| 28 | + { |
| 29 | + EntityHandle constructor = reader.GetCustomAttribute(handle).Constructor; |
| 30 | + EntityHandle type = constructor.Kind switch |
| 31 | + { |
| 32 | + HandleKind.MemberReference => reader.GetMemberReference((MemberReferenceHandle)constructor).Parent, |
| 33 | + HandleKind.MethodDefinition => reader.GetMethodDefinition((MethodDefinitionHandle)constructor).GetDeclaringType(), |
| 34 | + _ => default, |
| 35 | + }; |
| 36 | + if (type.Kind == HandleKind.TypeReference) |
| 37 | + { |
| 38 | + TypeReference attribute = reader.GetTypeReference((TypeReferenceHandle)type); |
| 39 | + hasMarker = reader.StringComparer.Equals(attribute.Name, nameof(AssemblyFixtureProviderAttribute)) |
| 40 | + && reader.StringComparer.Equals(attribute.Namespace, typeof(AssemblyFixtureProviderAttribute).Namespace!); |
| 41 | + } |
| 42 | + else if (type.Kind == HandleKind.TypeDefinition) |
| 43 | + { |
| 44 | + TypeDefinition attribute = reader.GetTypeDefinition((TypeDefinitionHandle)type); |
| 45 | + hasMarker = reader.StringComparer.Equals(attribute.Name, nameof(AssemblyFixtureProviderAttribute)) |
| 46 | + && reader.StringComparer.Equals(attribute.Namespace, typeof(AssemblyFixtureProviderAttribute).Namespace!); |
| 47 | + } |
| 48 | + |
| 49 | + if (hasMarker) |
| 50 | + { |
| 51 | + break; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + references = reader.AssemblyReferences.Select(handle => reader.GetAssemblyReference(handle).GetAssemblyName()).ToArray(); |
| 56 | + return true; |
| 57 | + } |
| 58 | + catch (Exception ex) when (ex is IOException or BadImageFormatException or UnauthorizedAccessException or SecurityException) |
| 59 | + { |
| 60 | + if (PlatformServiceProvider.Instance.AdapterTraceLogger.IsWarningEnabled) |
| 61 | + { |
| 62 | + PlatformServiceProvider.Instance.AdapterTraceLogger.Warning( |
| 63 | + "TypeCache: Could not read assembly metadata from {0}; using runtime resolution for AssemblyFixtureProvider discovery. {1}", |
| 64 | + path, |
| 65 | + ex); |
| 66 | + } |
| 67 | + |
| 68 | + return false; |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + private sealed class ProviderDiscoveryMetadataResolver |
| 73 | + { |
| 74 | +#if NET && !WINDOWS_UWP |
| 75 | + private Dictionary<string, string?>? _trustedAssemblyPaths; |
| 76 | +#endif |
| 77 | +#if NETFRAMEWORK |
| 78 | + private bool? _hasCodeBaseOverrides; |
| 79 | +#endif |
| 80 | + |
| 81 | + [SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "The resolver caches runtime-specific metadata paths on other target frameworks.")] |
| 82 | + public string? Resolve(Assembly referrer, AssemblyName referenceName) |
| 83 | + { |
| 84 | + try |
| 85 | + { |
| 86 | +#if NET && !WINDOWS_UWP |
| 87 | + AssemblyLoadContext context = AssemblyLoadContext.GetLoadContext(referrer) ?? AssemblyLoadContext.Default; |
| 88 | + // A component's deps/adjacent files do not describe Default's binding policy. |
| 89 | + // A later-loaded consumer may instead bind through Default.Resolving. |
| 90 | + if (context != AssemblyLoadContext.Default || context.Assemblies.Any(assembly => |
| 91 | + string.Equals(assembly.GetName().Name, referenceName.Name, StringComparison.OrdinalIgnoreCase))) |
| 92 | + { |
| 93 | + return null; |
| 94 | + } |
| 95 | + |
| 96 | + _trustedAssemblyPaths ??= ReadTrustedAssemblyPaths(); |
| 97 | + return _trustedAssemblyPaths.TryGetValue(referenceName.Name!, out string? path) |
| 98 | + && path is not null |
| 99 | + && HasMatchingProviderDiscoveryIdentity(referenceName, path) ? path : null; |
| 100 | +#elif NETFRAMEWORK |
| 101 | + _ = referrer; |
| 102 | + AppDomain domain = AppDomain.CurrentDomain; |
| 103 | + AppDomainSetup setup = domain.SetupInformation; |
| 104 | + // Fusion can select a loaded image or the GAC before probing the application base. |
| 105 | + // Keep those bindings, culture probing, redirects and host overrides authoritative. |
| 106 | + if (domain.GetAssemblies().Any(assembly => |
| 107 | + string.Equals(assembly.GetName().Name, referenceName.Name, StringComparison.OrdinalIgnoreCase)) |
| 108 | + || referenceName.GetPublicKeyToken() is { Length: > 0 } |
| 109 | + || !string.IsNullOrEmpty(referenceName.CultureName) |
| 110 | + || setup.DisallowApplicationBaseProbing |
| 111 | + || setup.PrivateBinPathProbe is not null |
| 112 | + || setup.GetConfigurationBytes() is { Length: > 0 } |
| 113 | + || !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("DEVPATH")) |
| 114 | + || !string.Equals(domain.ApplyPolicy(referenceName.FullName), referenceName.FullName, StringComparison.Ordinal) |
| 115 | + || (_hasCodeBaseOverrides ??= HasCodeBaseOverrides())) |
| 116 | + { |
| 117 | + return null; |
| 118 | + } |
| 119 | + |
| 120 | + foreach (string extension in new[] { ".dll", ".exe" }) |
| 121 | + { |
| 122 | + string path = Path.Combine(domain.BaseDirectory, referenceName.Name + extension); |
| 123 | + if (File.Exists(path)) |
| 124 | + { |
| 125 | + return HasMatchingProviderDiscoveryIdentity(referenceName, path) ? path : null; |
| 126 | + } |
| 127 | + } |
| 128 | +#else |
| 129 | + _ = referrer; |
| 130 | + _ = referenceName; |
| 131 | +#endif |
| 132 | + } |
| 133 | + catch (Exception ex) when (ex is IOException or BadImageFormatException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or SecurityException or XmlException) |
| 134 | + { |
| 135 | + if (PlatformServiceProvider.Instance.AdapterTraceLogger.IsWarningEnabled) |
| 136 | + { |
| 137 | + PlatformServiceProvider.Instance.AdapterTraceLogger.Warning( |
| 138 | + "TypeCache: Could not resolve a metadata path for {0}; using runtime resolution for AssemblyFixtureProvider discovery. {1}", |
| 139 | + referenceName.FullName, |
| 140 | + ex); |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + return null; |
| 145 | + } |
| 146 | + |
| 147 | +#if NET && !WINDOWS_UWP |
| 148 | + private static Dictionary<string, string?> ReadTrustedAssemblyPaths() |
| 149 | + { |
| 150 | + Dictionary<string, string?> paths = [with(StringComparer.OrdinalIgnoreCase)]; |
| 151 | + if (AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") is not string trustedPaths) |
| 152 | + { |
| 153 | + return paths; |
| 154 | + } |
| 155 | + |
| 156 | + foreach (string path in trustedPaths.Split(Path.PathSeparator)) |
| 157 | + { |
| 158 | + if (string.IsNullOrEmpty(path)) |
| 159 | + { |
| 160 | + continue; |
| 161 | + } |
| 162 | + |
| 163 | + string name = Path.GetFileNameWithoutExtension(path); |
| 164 | + paths[name] = paths.TryGetValue(name, out string? previous) |
| 165 | + && !string.Equals(previous, path, StringComparison.Ordinal) ? null : path; |
| 166 | + } |
| 167 | + |
| 168 | + return paths; |
| 169 | + } |
| 170 | +#endif |
| 171 | + |
| 172 | +#if NETFRAMEWORK || (NET && !WINDOWS_UWP) |
| 173 | + private static bool HasMatchingProviderDiscoveryIdentity(AssemblyName referenceName, string path) |
| 174 | + => string.Equals(referenceName.FullName, AssemblyName.GetAssemblyName(path).FullName, StringComparison.Ordinal); |
| 175 | +#endif |
| 176 | + |
| 177 | +#if NETFRAMEWORK |
| 178 | + private static bool HasCodeBaseOverrides() |
| 179 | + { |
| 180 | + string configurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; |
| 181 | + if (!File.Exists(configurationFile)) |
| 182 | + { |
| 183 | + return false; |
| 184 | + } |
| 185 | + |
| 186 | + using var reader = XmlReader.Create(configurationFile, new XmlReaderSettings { XmlResolver = null, DtdProcessing = DtdProcessing.Prohibit }); |
| 187 | + while (reader.Read()) |
| 188 | + { |
| 189 | + if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "codeBase") |
| 190 | + { |
| 191 | + return true; |
| 192 | + } |
| 193 | + } |
| 194 | + |
| 195 | + return false; |
| 196 | + } |
| 197 | +#endif |
| 198 | + } |
| 199 | +} |
0 commit comments