File size: 27,575 Bytes
8c763fb | 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 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Runtime.Loader;
using Microsoft.PowerShell.Telemetry;
namespace System.Management.Automation
{
/// <summary>
/// The powershell custom AssemblyLoadContext implementation.
/// </summary>
internal sealed partial class PowerShellAssemblyLoadContext
{
#region Resource_Strings
// We cannot use a satellite resources.dll to store resource strings for Microsoft.PowerShell.CoreCLR.AssemblyLoadContext.dll. This is because when retrieving resource strings, ResourceManager
// tries to load the satellite resources.dll using a probing approach, which will cause an infinite loop to PowerShellAssemblyLoadContext.Load(AssemblyName).
// Take the 'en-US' culture as an example. When retrieving resource string to construct an exception, ResourceManager calls Assembly.Load(..) in the following order to load the resource dll:
// 1. Load assembly with culture 'en-US' (Microsoft.PowerShell.CoreCLR.AssemblyLoadContext.resources, Version=3.0.0.0, Culture=en-US, PublicKeyToken=31bf3856ad364e35)
// 2. Load assembly with culture 'en' (Microsoft.PowerShell.CoreCLR.AssemblyLoadContext.resources, Version=3.0.0.0, Culture=en, PublicKeyToken=31bf3856ad364e35)
// When the first attempt fails, we again need to retrieve the resource string to construct another exception, which ends up with an infinite loop.
private const string BaseFolderDoesNotExist = "The base directory '{0}' does not exist.";
private const string ManifestDefinitionDoesNotMatch = "Could not load file or assembly '{0}' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference.";
private const string SingletonAlreadyInitialized = "The singleton of PowerShellAssemblyLoadContext has already been initialized.";
#endregion Resource_Strings
#region Constructor
/// <summary>
/// Initialize a singleton of PowerShellAssemblyLoadContext.
/// </summary>
internal static PowerShellAssemblyLoadContext InitializeSingleton(string basePaths, bool throwOnReentry)
{
lock (s_syncObj)
{
if (Instance is null)
{
Instance = new PowerShellAssemblyLoadContext(basePaths);
}
else if (throwOnReentry)
{
throw new InvalidOperationException(SingletonAlreadyInitialized);
}
return Instance;
}
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="basePaths">
/// Base directory paths that are separated by semicolon ';'. They will be the default paths to probe assemblies.
/// The passed-in argument could be null or an empty string, in which case there is no default paths to probe assemblies.
/// </param>
private PowerShellAssemblyLoadContext(string basePaths)
{
#if !UNIX
// Set GAC related member variables to null
_winDir = _gacPath32 = _gacPath64 = _gacPathMSIL = null;
#endif
// FIRST: Validate and populate probing paths
if (string.IsNullOrEmpty(basePaths))
{
_probingPaths = Array.Empty<string>();
}
else
{
_probingPaths = basePaths.Split(';', StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < _probingPaths.Length; i++)
{
string basePath = _probingPaths[i];
if (!Directory.Exists(basePath))
{
string message = string.Format(CultureInfo.CurrentCulture, BaseFolderDoesNotExist, basePath);
throw new ArgumentException(message, nameof(basePaths));
}
_probingPaths[i] = basePath.Trim();
}
}
// NEXT: Initialize the CoreCLR type catalog dictionary [OrdinalIgnoreCase]
_coreClrTypeCatalog = InitializeTypeCatalog();
_availableDotNetAssemblyNames = new Lazy<HashSet<string>>(
() => new HashSet<string>(_coreClrTypeCatalog.Values, StringComparer.Ordinal));
// LAST: Register the 'Resolving' handler and 'ResolvingUnmanagedDll' handler on the default load context.
AssemblyLoadContext.Default.Resolving += Resolve;
// Add last resort native dll resolver.
// Default order:
// 1. System.Runtime.InteropServices.DllImportResolver callbacks
// 2. AssemblyLoadContext.LoadUnmanagedDll()
// 3. AssemblyLoadContext.Default.ResolvingUnmanagedDll handlers
AssemblyLoadContext.Default.ResolvingUnmanagedDll += NativeDllHandler;
}
#endregion Constructor
#region Fields
private static readonly object s_syncObj = new();
private readonly string[] _probingPaths;
private readonly string[] _extensions = new string[] { ".ni.dll", ".dll" };
// CoreCLR type catalog dictionary
// - Key: namespace qualified type name (FullName)
// - Value: strong name of the TPA that contains the type represented by Key.
private readonly Dictionary<string, string> _coreClrTypeCatalog;
private readonly Lazy<HashSet<string>> _availableDotNetAssemblyNames;
private readonly HashSet<string> _denyListedAssemblies =
new(StringComparer.OrdinalIgnoreCase) { "System.Windows.Forms" };
#if !UNIX
private string _winDir;
private string _gacPathMSIL;
private string _gacPath32;
private string _gacPath64;
#endif
/// <summary>
/// Assembly cache across the AppDomain.
/// </summary>
/// <remarks>
/// We user the assembly short name (AssemblyName.Name) as the key.
/// According to the Spec of AssemblyLoadContext, "in the context of a given instance of AssemblyLoadContext, only one assembly with
/// a given name can be loaded. Attempt to load a second assembly with the same name and different MVID will result in an exception."
///
/// MVID is Module Version Identifier, which is a guid. Its purpose is solely to be unique for each time the module is compiled, and
/// it gets regenerated for every compilation. That means AssemblyLoadContext cannot handle loading two assemblies with the same name
/// but different versions, not even two assemblies with the exactly same code and version but built by two separate compilations.
///
/// Therefore, there is no need to use the full assembly name as the key. Short assembly name is sufficient.
/// </remarks>
private static readonly ConcurrentDictionary<string, Assembly> s_assemblyCache =
new(StringComparer.OrdinalIgnoreCase);
#endregion Fields
#region Properties
/// <summary>
/// Singleton instance of PowerShellAssemblyLoadContext.
/// </summary>
internal static PowerShellAssemblyLoadContext Instance
{
get; private set;
}
/// <summary>
/// Get the namespace-qualified type names of all available .NET Core types shipped with PowerShell.
/// This is used for type name auto-completion in PS engine.
/// </summary>
internal IEnumerable<string> AvailableDotNetTypeNames
{
get { return _coreClrTypeCatalog.Keys; }
}
/// <summary>
/// Get the assembly names of all available .NET Core assemblies shipped with PowerShell.
/// This is used for type name auto-completion in PS engine.
/// </summary>
internal HashSet<string> AvailableDotNetAssemblyNames
{
get { return _availableDotNetAssemblyNames.Value; }
}
#endregion Properties
#region Internal_Methods
/// <summary>
/// Get the current loaded assemblies.
/// </summary>
internal IEnumerable<Assembly> GetAssembly(string namespaceQualifiedTypeName)
{
// If 'namespaceQualifiedTypeName' is specified and it's a CoreCLR framework type,
// then we only return that specific TPA assembly.
if (!string.IsNullOrEmpty(namespaceQualifiedTypeName))
{
if (_coreClrTypeCatalog.TryGetValue(namespaceQualifiedTypeName, out string tpaStrongName))
{
try
{
return new Assembly[] { GetTrustedPlatformAssembly(tpaStrongName) };
}
catch (FileNotFoundException) { }
}
}
// Otherwise, we return null
return null;
}
/// <summary>
/// If a managed dll has native dependencies the handler will try to find these native dlls.
/// 1. Gets the managed.dll location (folder)
/// 2. Based on OS name and architecture name builds subfolder name where it is expected the native dll resides:
/// 3. Loads the native dll
///
/// managed.dll folder
/// |
/// |--- 'win-x64' subfolder
/// | |--- native.dll
/// |
/// |--- 'win-x86' subfolder
/// | |--- native.dll
/// |
/// |--- 'win-arm' subfolder
/// | |--- native.dll
/// |
/// |--- 'win-arm64' subfolder
/// | |--- native.dll
/// |
/// |--- 'linux-x64' subfolder
/// | |--- native.so
/// |
/// |--- 'linux-x86' subfolder
/// | |--- native.so
/// |
/// |--- 'linux-arm' subfolder
/// | |--- native.so
/// |
/// |--- 'linux-arm64' subfolder
/// | |--- native.so
/// |
/// |--- 'osx-x64' subfolder
/// | |--- native.dylib
/// |
/// |--- 'osx-arm64' subfolder
/// | |--- native.dylib
/// </summary>
internal static IntPtr NativeDllHandler(Assembly assembly, string libraryName)
{
s_nativeDllSubFolder ??= GetNativeDllSubFolderName(out s_nativeDllExtension);
string folder = Path.GetDirectoryName(assembly.Location);
string fullName = Path.Combine(folder, s_nativeDllSubFolder, libraryName) + s_nativeDllExtension;
return NativeLibrary.TryLoad(fullName, out IntPtr pointer) ? pointer : IntPtr.Zero;
}
#endregion Internal_Methods
#region Private_Methods
/// <summary>
/// The handler for the Resolving event.
/// </summary>
private Assembly Resolve(AssemblyLoadContext loadContext, AssemblyName assemblyName)
{
// Probe the assembly cache
Assembly asmLoaded;
if (TryGetAssemblyFromCache(assemblyName, out asmLoaded))
return asmLoaded;
// Prepare to load the assembly
lock (s_syncObj)
{
// Probe the cache again in case it's already loaded
if (TryGetAssemblyFromCache(assemblyName, out asmLoaded))
return asmLoaded;
// Search the specified assembly in probing paths, and load it through 'LoadFromAssemblyPath' if the file exists and matches the requested AssemblyName.
// If the CultureName of the requested assembly is not NullOrEmpty, then it's a resources.dll and we need to search corresponding culture sub-folder.
bool isAssemblyFileFound = false, isAssemblyFileMatching = false;
string asmCultureName = assemblyName.CultureName ?? string.Empty;
string asmFilePath = null;
for (int i = 0; i < _probingPaths.Length; i++)
{
string probingPath = _probingPaths[i];
string asmCulturePath = Path.Combine(probingPath, asmCultureName);
for (int k = 0; k < _extensions.Length; k++)
{
string asmFileName = assemblyName.Name + _extensions[k];
asmFilePath = Path.Combine(asmCulturePath, asmFileName);
if (File.Exists(asmFilePath))
{
isAssemblyFileFound = true;
AssemblyName asmNameFound = AssemblyLoadContext.GetAssemblyName(asmFilePath);
if (IsAssemblyMatching(assemblyName, asmNameFound))
{
isAssemblyFileMatching = true;
break;
}
}
}
if (isAssemblyFileFound && isAssemblyFileMatching)
{
break;
}
}
// We failed to find the assembly file; or we found the file, but the assembly file doesn't match the request.
// In this case, return null so that other Resolving event handlers can kick in to resolve the request.
if (!isAssemblyFileFound || !isAssemblyFileMatching)
{
#if !UNIX
// Try loading from GAC
if (!TryFindInGAC(assemblyName, out asmFilePath))
{
return null;
}
#else
return null;
#endif
}
asmLoaded = asmFilePath.EndsWith(".ni.dll", StringComparison.OrdinalIgnoreCase)
? loadContext.LoadFromNativeImagePath(asmFilePath, null)
: loadContext.LoadFromAssemblyPath(asmFilePath);
if (asmLoaded != null)
{
// Add the loaded assembly to the cache
s_assemblyCache.TryAdd(assemblyName.Name, asmLoaded);
}
}
return asmLoaded;
}
#if !UNIX
// Try to find the assembly in GAC by looking up the directories in well know locations.
// First try to find in GAC_MSIL, then depending on process bitness; GAC_64 or GAC32.
// If there are multiple version of the assembly, load the latest.
private bool TryFindInGAC(AssemblyName assemblyName, out string assemblyFilePath)
{
assemblyFilePath = null;
if (_denyListedAssemblies.Contains(assemblyName.Name))
{
// DotNet catches and throws a new exception with no inner exception
// We cannot change the message DotNet returns.
return false;
}
if (Internal.InternalTestHooks.DisableGACLoading)
{
return false;
}
if (string.IsNullOrEmpty(_winDir))
{
// cache value of '_winDir' folder in member variable.
_winDir = Environment.GetEnvironmentVariable("winDir");
}
if (string.IsNullOrEmpty(_gacPathMSIL))
{
// cache value of '_gacPathMSIL' folder in member variable.
_gacPathMSIL = Path.Join(_winDir, "Microsoft.NET", "assembly", "GAC_MSIL");
}
bool assemblyFound = FindInGac(_gacPathMSIL, assemblyName, out assemblyFilePath);
if (!assemblyFound)
{
string gacBitnessAwarePath;
if (Environment.Is64BitProcess)
{
if (string.IsNullOrEmpty(_gacPath64))
{
var gacName = RuntimeInformation.ProcessArchitecture == Architecture.Arm64 ? "GAC_Arm64" : "GAC_64";
_gacPath64 = Path.Join(_winDir, "Microsoft.NET", "assembly", gacName);
}
gacBitnessAwarePath = _gacPath64;
}
else
{
if (string.IsNullOrEmpty(_gacPath32))
{
_gacPath32 = Path.Join(_winDir, "Microsoft.NET", "assembly", "GAC_32");
}
gacBitnessAwarePath = _gacPath32;
}
assemblyFound = FindInGac(gacBitnessAwarePath, assemblyName, out assemblyFilePath);
}
return assemblyFound;
}
// Find the assembly under 'gacRoot' and select the latest version.
private static bool FindInGac(string gacRoot, AssemblyName assemblyName, out string assemblyPath)
{
bool assemblyFound = false;
assemblyPath = null;
string tempAssemblyDirPath = Path.Join(gacRoot, assemblyName.Name);
if (Directory.Exists(tempAssemblyDirPath))
{
// Enumerate all directories, sort by name and select the last. This selects the latest version.
var chosenVersionDirectory = Directory.EnumerateDirectories(tempAssemblyDirPath).Order().LastOrDefault();
if (!string.IsNullOrEmpty(chosenVersionDirectory))
{
// Select first or default as the directory will contain only one assembly. If nothing then default is null;
var foundAssemblyPath = Directory.EnumerateFiles(chosenVersionDirectory, $"{assemblyName.Name}*").FirstOrDefault();
if (!string.IsNullOrEmpty(foundAssemblyPath))
{
AssemblyName asmNameFound = AssemblyLoadContext.GetAssemblyName(foundAssemblyPath);
if (IsAssemblyMatching(assemblyName, asmNameFound))
{
assemblyPath = foundAssemblyPath;
assemblyFound = true;
}
}
}
}
return assemblyFound;
}
#endif
/// <summary>
/// Try to get the specified assembly from cache.
/// </summary>
private static bool TryGetAssemblyFromCache(AssemblyName assemblyName, out Assembly asmLoaded)
{
if (s_assemblyCache.TryGetValue(assemblyName.Name, out asmLoaded))
{
// Check if loaded assembly matches the request
if (IsAssemblyMatching(assemblyName, asmLoaded.GetName()))
return true;
// In the context of a given instance of AssemblyLoadContext, only one assembly with the
// same name can be loaded. So we throw exception if assembly doesn't match the request.
ThrowFileLoadException(
ManifestDefinitionDoesNotMatch,
assemblyName.FullName);
}
return false;
}
/// <summary>
/// Check if the loaded assembly matches the request.
/// </summary>
/// <param name="requestedAssembly">AssemblyName of the requested assembly.</param>
/// <param name="loadedAssembly">AssemblyName of the loaded assembly.</param>
/// <returns></returns>
private static bool IsAssemblyMatching(AssemblyName requestedAssembly, AssemblyName loadedAssembly)
{
//
// We use the same rules as CoreCLR loader to compare the requested assembly and loaded assembly:
// 1. If 'Version' of the requested assembly is specified, then the requested version should be less or equal to the loaded version;
// 2. If 'CultureName' of the requested assembly is specified (not NullOrEmpty), then the CultureName of the loaded assembly should be the same;
// 3. If 'PublicKeyToken' of the requested assembly is specified (not Null or EmptyArray), then the PublicKenToken of the loaded assembly should be the same.
//
// Version of the requested assembly should be the same or before the version of loaded assembly
if (requestedAssembly.Version != null && requestedAssembly.Version.CompareTo(loadedAssembly.Version) > 0)
{
return false;
}
// CultureName of requested assembly and loaded assembly should be the same
string requestedCultureName = requestedAssembly.CultureName;
if (!string.IsNullOrEmpty(requestedCultureName) && !requestedCultureName.Equals(loadedAssembly.CultureName, StringComparison.OrdinalIgnoreCase))
{
return false;
}
// PublicKeyToken should be the same, unless it's not specified in the requested assembly
byte[] requestedPublicKeyToken = requestedAssembly.GetPublicKeyToken();
byte[] loadedPublicKeyToken = loadedAssembly.GetPublicKeyToken();
if (requestedPublicKeyToken != null && requestedPublicKeyToken.Length > 0)
{
if (loadedPublicKeyToken == null || requestedPublicKeyToken.Length != loadedPublicKeyToken.Length)
return false;
for (int i = 0; i < requestedPublicKeyToken.Length; i++)
{
if (requestedPublicKeyToken[i] != loadedPublicKeyToken[i])
return false;
}
}
return true;
}
/// <summary>
/// Get the TPA that is represented by the specified assembly strong name.
/// </summary>
/// <param name="tpaStrongName">
/// The assembly strong name of a CoreCLR Trusted_Platform_Assembly
/// </param>
private static Assembly GetTrustedPlatformAssembly(string tpaStrongName)
{
// We always depend on the default context to load the TPAs that are recorded in
// the type catalog.
// - If the requested TPA is already loaded, then 'Assembly.Load' will just get
// it back from the cache of default context.
// - If the requested TPA is not loaded yet, then 'Assembly.Load' will make the
// default context to load it
AssemblyName assemblyName = new(tpaStrongName);
Assembly asmLoaded = Assembly.Load(assemblyName);
return asmLoaded;
}
/// <summary>
/// Throw FileLoadException.
/// </summary>
private static void ThrowFileLoadException(string errorTemplate, params object[] args)
{
string message = string.Format(CultureInfo.CurrentCulture, errorTemplate, args);
throw new FileLoadException(message);
}
/// <summary>
/// Throw FileNotFoundException.
/// </summary>
private static void ThrowFileNotFoundException(string errorTemplate, params object[] args)
{
string message = string.Format(CultureInfo.CurrentCulture, errorTemplate, args);
throw new FileNotFoundException(message);
}
private static string s_nativeDllSubFolder;
private static string s_nativeDllExtension;
private static string GetNativeDllSubFolderName(out string ext)
{
string folderName = string.Empty;
ext = string.Empty;
var processArch = RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant();
if (Platform.IsWindows)
{
folderName = "win-" + processArch;
ext = ".dll";
}
else if (Platform.IsLinux)
{
folderName = "linux-" + processArch;
ext = ".so";
}
else if (Platform.IsMacOS)
{
folderName = "osx-" + processArch;
ext = ".dylib";
}
return folderName;
}
#endregion Private_Methods
}
/// <summary>
/// This is the managed entry point for Microsoft.PowerShell.CoreCLR.AssemblyLoadContext.dll.
/// </summary>
public static class PowerShellAssemblyLoadContextInitializer
{
/// <summary>
/// Create a singleton of PowerShellAssemblyLoadContext.
/// Then register to the Resolving event of the load context that loads this assembly.
/// </summary>
/// <remarks>
/// This method is to be used by native host whose TPA list doesn't include PS assemblies, such as the
/// in-box Nano powershell, the PS remote WinRM plugin, in-box Nano DSC and in-box Nano SCOM agent.
/// </remarks>
/// <param name="basePaths">
/// Base directory paths that are separated by semicolon ';'.
/// They will be the default paths to probe assemblies.
/// </param>
public static void SetPowerShellAssemblyLoadContext([MarshalAs(UnmanagedType.LPWStr)] string basePaths)
{
ArgumentException.ThrowIfNullOrEmpty(basePaths);
// Disallow calling this method from native code for more than once.
PowerShellAssemblyLoadContext.InitializeSingleton(basePaths, throwOnReentry: true);
}
}
/// <summary>
/// Provides helper functions to facilitate calling managed code from a native PowerShell host.
/// </summary>
public static unsafe class PowerShellUnsafeAssemblyLoad
{
/// <summary>
/// Load an assembly in memory from unmanaged code.
/// </summary>
/// <remarks>
/// This API is covered by the experimental feature 'PSLoadAssemblyFromNativeCode',
/// and it may be deprecated and removed in future.
/// </remarks>
/// <param name="data">Unmanaged pointer to assembly data buffer.</param>
/// <param name="size">Size in bytes of the assembly data buffer.</param>
/// <returns>Returns zero on success and non-zero on failure.</returns>
[UnmanagedCallersOnly]
public static int LoadAssemblyFromNativeMemory(IntPtr data, int size)
{
int result = 0;
try
{
using var stream = new UnmanagedMemoryStream((byte*)data, size);
AssemblyLoadContext.Default.LoadFromStream(stream);
}
catch
{
result = -1;
}
ApplicationInsightsTelemetry.SendUseTelemetry("PowerShellUnsafeAssemblyLoad", result == 0 ? "1" : "0");
return result;
}
}
}
|