Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions build.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -1044,9 +1044,10 @@ function Publish-PSTestTools {
Find-Dotnet

$tools = @(
@{Path="${PSScriptRoot}/test/tools/TestExe";Output="testexe"}
@{Path="${PSScriptRoot}/test/tools/WebListener";Output="WebListener"}
@{Path="${PSScriptRoot}/test/tools/TestService";Output="TestService"}
@{ Path="${PSScriptRoot}/test/tools/TestAlc"; Output="library" }
@{ Path="${PSScriptRoot}/test/tools/TestExe"; Output="exe" }
@{ Path="${PSScriptRoot}/test/tools/WebListener"; Output="exe" }
@{ Path="${PSScriptRoot}/test/tools/TestService"; Output="exe" }
)

$Options = Get-PSOptions -DefaultToNew
Expand All @@ -1067,12 +1068,19 @@ function Publish-PSTestTools {
Remove-Item -Path $objPath -Recurse -Force
}

if ($tool.Output -eq 'library') {
## Handle building and publishing assemblies.
dotnet publish --configuration $Options.Configuration --framework $Options.Framework
continue
}

## Handle building and publishing executables.
if (-not $runtime) {
dotnet publish --output bin --configuration $Options.Configuration --framework $Options.Framework --runtime $Options.Runtime
} else {
dotnet publish --output bin --configuration $Options.Configuration --framework $Options.Framework --runtime $runtime
$runtime = $Options.Runtime
Comment thread
daxian-dbw marked this conversation as resolved.
Resolved
}

dotnet publish --output bin --configuration $Options.Configuration --framework $Options.Framework --runtime $runtime --self-contained

if ( -not $env:PATH.Contains($toolPath) ) {
$env:PATH = $toolPath+$TestModulePathSeparator+$($env:PATH)
}
Expand Down
149 changes: 122 additions & 27 deletions src/System.Management.Automation/engine/ExecutionContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1269,55 +1269,150 @@ internal PSTransactionManager TransactionManager

internal PSTransactionManager transactionManager;

internal Assembly AddAssembly(string name, string filename, out Exception error)
{
Assembly loadedAssembly = LoadAssembly(name, filename, out error);

if (loadedAssembly == null)
return null;

if (AssemblyCache.ContainsKey(loadedAssembly.FullName))
/// <summary>
/// This method is used for assembly loading requests stemmed from 'InitialSessionState' binding and module loading.
/// </summary>
/// <param name="source">Source of the assembly loading request, should be a module name when specified.</param>
Comment thread
daxian-dbw marked this conversation as resolved.
Resolved
/// <param name="assemblyName">Name of the assembly to be loaded.</param>
/// <param name="filePath">Path of the assembly to be loaded.</param>
/// <param name="error">Exception that is caught when the loading fails.</param>
internal Assembly AddAssembly(string source, string assemblyName, string filePath, out Exception error)
{
// Search the cache by the path, and return the assembly if we find it.
// It's common to have two loading requests for the same assembly when loading a module -- the first time for
// resolving a binary module path, and the second time for actually processing that module.
//
// That's not a problem when all the module assemblies are loaded into the default ALC. But in a scenario where
// a module tries to hide its nested/root binary modules in a custom ALC, that will become a problem. This is
// because:
// in that scenario, the module will usually setup a handler to load the specific assemblies to the custom ALC,
// and that will be how the first loading request gets served. However, after the module path is resolved with
// the first loading, the path will be used for the second loading upon real module processing. Since we prefer
// loading-by-path over loading-by-name in the 'LoadAssembly' call, we will end up loading the same assembly in
// the default ALC (because we use 'Assembly.LoadFrom' which always loads an assembly to the default ALC) if we
// do not search in the cache first. That will break the scenario, because the module means to isolate all its
// dependencies from the default ALC, and it failed to do so.
//
// Therefore, we need to search the cache first. The reason we use path as the key is to make sure the request
// is for exactly the same assembly. The same assembly file should not be loaded into different ALC's by module
// loading within the same PowerShell session (Runspace).
Comment thread
daxian-dbw marked this conversation as resolved.
Resolved
//
// An example module targeting the abovementioned scenario will likely have the following file structure:
// IsolatedModule
// │ IsolatedModule.psd1 (has 'NestedModules = @('Test.Isolated.Init.dll', 'Test.Isolated.Nested.dll')')
// │ Test.Isolated.Init.dll (contains the custom ALC and code to setup 'Resolving' handler)
// └───Dependencies (folder under module base)
// Newtonsoft.Json.dll (version 10.0.0.0 dependency)
// Test.Isolated.Nested.dll (nested binary module referencing the particular dependency)
//
// In this example, the following events will happen in sequence:
// 1. PowerShell is able to find 'Test.Isolated.Init.dll' under module base folder, so it will be loaded into
// the default ALC as expected and setup the 'Resolving' handler via the 'OnImport' call.
// 2. PowerShell cannot find 'Test.Isolated.Nested.dll' under the module base folder, so it will call the method
// 'FixFileName(.., bool canLoadAssembly)' to resolve the path of this binary module.
// This particular overload will attempt to load the assembly by name, which will be served by the 'Resolving'
// handler that was setup in the step 1. So, the assembly will be loaded into the custom ALC and insert to the
// assembly cache.
// 3. Path of the nested module 'Test.Isolated.Init.dll' now has been resolved by the step 2 (assembly.Location).
// Now it's time to actually load this binary module for processing in the method 'LoadBinaryModule', which
// will make a call to this method with the resolved assembly file path.
// At this poin, we will have to query the cache first, instead of calling 'LoadAssembly' directly, to make sure
// that the assembly instance loaded in the custom ALC in step 2 gets returned back. Otherwise, the same assembly
// file will be loaded in the default ALC because 'Assembly.LoadFrom' is used in 'LoadAssembly' and that API will
// always load an assembly file to the default ALC, and that will break this scenario.
Comment thread
daxian-dbw marked this conversation as resolved.
Resolved
if (TryGetFromAssemblyCache(source, filePath, out Assembly loadedAssembly))
{
// we should ignore this assembly.
error = null;
return loadedAssembly;
}
// We will cache the assembly by both full name and
// file name
AssemblyCache.Add(loadedAssembly.FullName, loadedAssembly);

if (AssemblyCache.ContainsKey(loadedAssembly.GetName().Name))
// Attempt to load the requested assembly, first by path then by name.
loadedAssembly = LoadAssembly(assemblyName, filePath, out error);
if (loadedAssembly is not null)
{
// we should ignore this assembly.
return loadedAssembly;
AddToAssemblyCache(source, loadedAssembly);
}

AssemblyCache.Add(loadedAssembly.GetName().Name, loadedAssembly);
return loadedAssembly;
}

internal void RemoveAssembly(string name)
/// <summary>
/// Add a loaded assembly to the 'AssemblyCache'.
/// The <paramref name="source"/> is used as a prefix for the key to make it easy to remove all associated
/// assemblies from the cache when a module gets unloaded.
/// </summary>
/// <param name="source">The source where the assembly comes from, should be a module name when specified.</param>
/// <param name="assembly">The assembly we try to cache.</param>
internal void AddToAssemblyCache(string source, Assembly assembly)
{
// Try caching the assembly by its location if possible.
// When it's a dynamic assembly, we use it's full name. This could happen with 'Import-Module -Assembly'.
string key = string.IsNullOrEmpty(assembly.Location) ? assembly.FullName : assembly.Location;

// When the assembly is from a module loading, we prefix the key with the source,
// so we can remove it from the cache when the module gets unloaded.
if (!string.IsNullOrEmpty(source))
{
// Both 'source' and 'key' are of the string type, so no need to specify 'InvariantCulture'.
key = $"{source}@{key}";
Comment thread
daxian-dbw marked this conversation as resolved.
Resolved
}

AssemblyCache.TryAdd(key, assembly);
}

/// <summary>
/// Remove all cache entries that are associated with the specified source.
/// </summary>
internal void RemoveFromAssemblyCache(string source)
{
Assembly loadedAssembly;
if (AssemblyCache.TryGetValue(name, out loadedAssembly) && loadedAssembly != null)
if (string.IsNullOrEmpty(source))
{
AssemblyCache.Remove(name);
return;
}

var keysToRemove = new List<string>();
string prefix = $"{source}@";

AssemblyCache.Remove(loadedAssembly.GetName().Name);
foreach (string key in AssemblyCache.Keys)
{
if (key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
keysToRemove.Add(key);
}
}

foreach (string key in keysToRemove)
{
AssemblyCache.Remove(key);
Comment thread
daxian-dbw marked this conversation as resolved.
Resolved
}
}

[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadWithPartialName")]
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom")]
internal static Assembly LoadAssembly(string name, string filename, out Exception error)
/// <summary>
/// Try to get an assembly from the cache.
/// </summary>
private bool TryGetFromAssemblyCache(string source, string filePath, out Assembly assembly)
{
if (string.IsNullOrEmpty(filePath))
{
assembly = null;
return false;
}

// Both 'source' and 'filePath' are of the string type, so no need to specify 'InvariantCulture'.
string key = string.IsNullOrEmpty(source) ? filePath : $"{source}@{filePath}";
return AssemblyCache.TryGetValue(key, out assembly);
}

private static Assembly LoadAssembly(string name, string filePath, out Exception error)
{
// First we try to load the assembly based on the filename
Assembly loadedAssembly = null;
error = null;
if (!string.IsNullOrEmpty(filename))
if (!string.IsNullOrEmpty(filePath))
{
try
{
loadedAssembly = Assembly.LoadFrom(filename);
loadedAssembly = Assembly.LoadFrom(filePath);
return loadedAssembly;
}
catch (FileNotFoundException fileNotFound)
Expand Down Expand Up @@ -1562,7 +1657,7 @@ private void InitializeCommon(AutomationEngine engine, PSHost hostInterface)
EngineHostInterface = hostInterface as InternalHost ?? new InternalHost(hostInterface, this);

// Hook up the assembly cache
AssemblyCache = new Dictionary<string, Assembly>();
AssemblyCache = new Dictionary<string, Assembly>(StringComparer.OrdinalIgnoreCase);
Comment thread
daxian-dbw marked this conversation as resolved.
Resolved

// Initialize the fixed toplevel session state and the current session state
TopLevelSessionState = EngineSessionState = new SessionStateInternal(this);
Expand Down
Loading