Merge pull request #1120 from PowerShell/andschwa/merge-sd

Merge SD changeset 715912
This commit is contained in:
Andy Schwartzmeyer authored and GitHub committed 2016-06-16 00:15:58 -07:00
commit acf2f58f26
76 files changed
+1405 -1336

No files matched your search

@@ -1620,7 +1620,7 @@ namespace System.Management.Automation
namespace Microsoft.PowerShell.CoreCLR
{
using System;
using System.IO;
using System.Management.Automation;
/// <summary>
@@ -1629,18 +1629,23 @@ namespace Microsoft.PowerShell.CoreCLR
public static class AssemblyExtensions
{
/// <summary>
/// Loads an assembly given its file path.
/// Load an assembly given its file path.
/// </summary>
/// <param name="assemblyFile">The path of the file that contains the manifest of the assembly.</param>
/// <param name="assemblyPath">The path of the file that contains the manifest of the assembly.</param>
/// <returns>The loaded assembly.</returns>
public static Assembly LoadFrom(string assemblyFile)
public static Assembly LoadFrom(string assemblyPath)
{
if (string.IsNullOrEmpty(assemblyFile))
{
throw new ArgumentNullException("assemblyFile");
return ClrFacade.LoadFrom(assemblyPath);
}
return ClrFacade.LoadFrom(assemblyFile);
/// <summary>
/// Load an assembly given its byte stream
/// </summary>
/// <param name="assembly">The byte stream of assembly</param>
/// <returns>The loaded assembly</returns>
public static Assembly LoadFrom(Stream assembly)
{
return ClrFacade.LoadFrom(assembly);
}
}
}
@@ -537,8 +537,7 @@ namespace System.Management.Automation.Runspaces
.AddHeader(Alignment.Right, label: "NPM(K)", width: 7)
.AddHeader(Alignment.Right, label: "PM(K)", width: 8)
.AddHeader(Alignment.Right, label: "WS(K)", width: 10)
.AddHeader(Alignment.Right, label: "VM(M)", width: 5)
.AddHeader(Alignment.Right, label: "CPU(s)", width: 8)
.AddHeader(Alignment.Right, label: "CPU(s)", width: 10)
.AddHeader(Alignment.Right, width: 6)
.AddHeader(Alignment.Right, width: 3)
.AddHeader()
@@ -547,13 +546,7 @@ namespace System.Management.Automation.Runspaces
.AddScriptBlockColumn("[long]($_.NPM / 1024)")
.AddScriptBlockColumn("[long]($_.PM / 1024)")
.AddScriptBlockColumn("[long]($_.WS / 1024)")
.AddScriptBlockColumn("[long]($_.VM / 1048576)")
.AddScriptBlockColumn(@"
if ($_.CPU -ne $())
{
$_.CPU.ToString(""N"")
}
")
.AddScriptBlockColumn(@"if ($_.CPU -ne $()) { $_.CPU.ToString(""N"") }")
.AddPropertyColumn("Id")
.AddPropertyColumn("SI")
.AddPropertyColumn("ProcessName")
@@ -600,21 +593,14 @@ if ($_.CPU -ne $())
TableControl.Create()
.AddHeader(Alignment.Right, label: "Handles", width: 7)
.AddHeader(Alignment.Right, label: "WS(K)", width: 10)
.AddHeader(Alignment.Right, label: "VM(M)", width: 5)
.AddHeader(Alignment.Right, label: "CPU(s)", width: 8)
.AddHeader(Alignment.Right, width: 6)
.AddHeader(width: 17)
.AddHeader(width: 22)
.AddHeader()
.StartRowDefinition()
.AddPropertyColumn("HandleCount")
.AddScriptBlockColumn("[long]($_.WS / 1024)")
.AddScriptBlockColumn("[long]($_.VM / 1048576)")
.AddScriptBlockColumn(@"
if ($_.CPU -ne $())
{
$_.CPU.ToString(""N"")
}
")
.AddScriptBlockColumn(@"if ($_.CPU -ne $()) { $_.CPU.ToString(""N"") }")
.AddPropertyColumn("Id")
.AddPropertyColumn("UserName")
.AddPropertyColumn("ProcessName")
@@ -196,6 +196,7 @@ namespace System.Management.Automation
/// </summary>
/// <param name="typeinfo">reference to ITypeInfo from which to get TypeAttr</param>
/// <returns></returns>
[ArchitectureSensitive]
internal static COM.TYPEATTR GetTypeAttr(COM.ITypeInfo typeinfo)
{
IntPtr pTypeAttr;
@@ -211,6 +212,7 @@ namespace System.Management.Automation
/// <param name="typeinfo"></param>
/// <param name="index"></param>
/// <returns></returns>
[ArchitectureSensitive]
internal static COM.FUNCDESC GetFuncDesc(COM.ITypeInfo typeinfo, int index)
{
IntPtr pFuncDesc;
@@ -103,7 +103,7 @@ namespace System.Management.Automation.ComInterop {
i.ToString(CultureInfo.InvariantCulture),
method.Name,
temps,
initTemps), curArgument.Restrictions, curArgument.Value);
initTemps), curArgument.Restrictions);
}
else
{
@@ -508,6 +508,20 @@ namespace System.Management.Automation.ComInterop {
}
}
if (typeAttr.typekind == ComTypes.TYPEKIND.TKIND_INTERFACE)
{
//We have typeinfo for custom interface. Get typeinfo for Dispatch interface.
typeInfo = ComTypeInfo.GetDispatchTypeInfoFromCustomInterfaceTypeInfo(typeInfo);
typeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(typeInfo);
}
if (typeAttr.typekind == ComTypes.TYPEKIND.TKIND_COCLASS)
{
//We have typeinfo for the COClass. Find the default interface and get typeinfo for default interface.
typeInfo = ComTypeInfo.GetDispatchTypeInfoFromCoClassTypeInfo(typeInfo);
typeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(typeInfo);
}
ComTypeDesc typeDesc = ComTypeDesc.FromITypeInfo(typeInfo, typeAttr);
ComMethodDesc getItem = null;
@@ -1068,7 +1068,7 @@ namespace System.Management.Automation
var configAst = Ast.GetAncestorAst<ConfigurationDefinitionAst>(keywordAst);
if (configAst != null)
{
var namedBlockAst = keywordAst.Parent as NamedBlockAst;
var namedBlockAst = Ast.GetAncestorAst<NamedBlockAst>(keywordAst);
if (namedBlockAst != null)
{
List<string> allResources = new List<string>();
@@ -1297,9 +1297,6 @@ namespace System.Management.Automation
//Get Target object
object targetObject = RemotingDecoder.GetPropertyValue<object>(serializedErrorRecord, "TargetObject");
//Get InvocationInfo
PSObject invocationInfo = RemotingDecoder.GetPropertyValue<PSObject>(serializedErrorRecord, "InvocationInfo");
string exceptionMessage = null;
if (serializedException != null)
{
@@ -1324,6 +1321,12 @@ namespace System.Management.Automation
string errorCategory_TargetType = RemotingDecoder.GetPropertyValue<string>(serializedErrorRecord, "ErrorCategory_TargetType");
string errorCategory_Message = RemotingDecoder.GetPropertyValue<string>(serializedErrorRecord, "ErrorCategory_Message");
//Get InvocationInfo (optional property)
PSObject invocationInfo = Microsoft.PowerShell.DeserializingTypeConverter.GetPropertyValue<PSObject>(
serializedErrorRecord,
"InvocationInfo",
Microsoft.PowerShell.DeserializingTypeConverter.RehydrationFlags.MissingPropertyOk);
//Get Error Detail (these note properties are optional, so can't right now use RemotingDecoder...)
string errorDetails_Message =
GetNoteValue(serializedErrorRecord, "ErrorDetails_Message") as string;
@@ -5474,7 +5474,12 @@ end
internal const string DefaultMoreFunctionText = @"
param([string[]]$paths)
$OutputEncoding = [System.Console]::OutputEncoding
# Nano needs to use Unicode, but Windows and Linux need the default
$OutputEncoding = if ($IsWindows -and $IsCore) {
[System.Text.Encoding]::Unicode
} else {
[System.Console]::OutputEncoding
}
# Respect PAGER, use more on Windows, and use less on Linux
if (Test-Path env:PAGER) {
@@ -7,6 +7,7 @@ using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
using System.Text;
@@ -104,6 +105,17 @@ namespace System.Management.Automation
var moduleManifestProperties = PsUtils.GetModuleManifestProperties(modulePath, PsUtils.FastModuleManifestAnalysisPropertyNames);
if (moduleManifestProperties != null)
{
Version version;
if (ModuleUtils.IsModuleInVersionSubdirectory(modulePath, out version))
{
var versionInManifest = LanguagePrimitives.ConvertTo<Version>(moduleManifestProperties["ModuleVersion"]);
if (version != versionInManifest)
{
ModuleIntrinsics.Tracer.WriteLine("ModuleVersion in manifest does not match versioned module directory, skipping module: {0}", modulePath);
return null;
}
}
result = new ConcurrentDictionary<string, CommandTypes>(3, moduleManifestProperties.Count, StringComparer.OrdinalIgnoreCase);
var sawWildcard = false;
@@ -1190,10 +1190,15 @@ namespace Microsoft.PowerShell.Commands
if (module != null)
{
Version directoryVersion;
if (!ModuleUtils.IsModuleInVersionSubdirectory(file, out directoryVersion)
|| directoryVersion == module.Version)
{
availableModules.Add(module);
}
}
}
}
ClearAnalysisCaches();
@@ -4982,7 +4987,7 @@ namespace Microsoft.PowerShell.Commands
/// <returns></returns>
internal string GetAbsolutePath(string moduleBase, string path)
{
if (!IsRooted(path) && (path.Contains('/') || path.Contains('\\')) && !path.Contains('$'))
if (!IsRooted(path) && (path.Contains('/') || path.Contains('\\')))
{
return Path.Combine(moduleBase, path);
}
@@ -797,6 +797,15 @@ namespace System.Management.Automation
int psHomePosition = PathContainsSubstring(currentProcessModulePath, psHomeModulePath); // index of $PSHome\Modules in currentProcessModulePath
if (psHomePosition >= 0) // if $PSHome\Modules IS found - insert <Program Files> location before $PSHome\Modules
{
#if !CORECLR
// for bug 6678623, if we are running wow64 process (x86 32-bit process on 64-bit (amd64) OS), then ensure that <SpecialFolder.MyDocuments> exists in currentProcessModulePath / return value
if (Environment.Is64BitOperatingSystem && !Environment.Is64BitProcess)
{
string userModulePath = GetPersonalModulePath();
currentProcessModulePath = AddToPath(currentProcessModulePath, userModulePath, psHomePosition);
psHomePosition = PathContainsSubstring(currentProcessModulePath, psHomeModulePath);
}
#endif
return AddToPath(currentProcessModulePath, programFilesModulePath, psHomePosition);
} // if $PSHome\Modules NOT found = <scenario 4> = 'PSModulePath has been constrained by a user to create a sand boxed environment without including System Modules'
@@ -905,27 +914,27 @@ namespace System.Management.Automation
/// <summary>
/// Get the current module path setting.
///
/// 'preferSystemModulePath' should only be used for internal functions - by default,
/// user modules should be able to override system modules.
/// </summary>
/// <param name="includeSystemModulePath">
/// Include The system wide module path ($PSHOME\Modules) even if it's not in PSModulePath.
/// In V3-V5, we prepended this path during module auto-discovery which incorrectly preferred
/// $PSHOME\Modules over user installed modules that might have a command that overrides
/// a product-supplied command.
/// For 5.1, we append $PSHOME\Modules in this case to avoid the rare case where PSModulePath
/// does not contain the path, but a script depends on previous behavior.
/// Note that appending is still a potential breaking change, but necessary to update in-box
/// modules long term - e.g. when open sourcing a module and installing from the gallery.
/// </param>
/// <param name="context"></param>
/// <returns>The module path as an array of strings</returns>
internal static IEnumerable<string> GetModulePath(bool preferSystemModulePath, ExecutionContext context)
internal static IEnumerable<string> GetModulePath(bool includeSystemModulePath, ExecutionContext context)
{
string modulePathString = Environment.GetEnvironmentVariable("PSMODULEPATH") ?? SetModulePath();
HashSet<string> processedPathSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
// If we should prefer the system-wide module path, prepend that to what gets returned.
if (preferSystemModulePath)
if (!string.IsNullOrWhiteSpace(modulePathString))
{
yield return ProcessOneModulePath(context, GetSystemwideModulePath(), processedPathSet);
}
// If the path is just whitespace, return an empty collection.
if (string.IsNullOrWhiteSpace(modulePathString))
yield break;
foreach (string envPath in modulePathString.Split(Utils.Separators.Semicolon, StringSplitOptions.RemoveEmptyEntries))
{
var processedPath = ProcessOneModulePath(context, envPath, processedPathSet);
@@ -934,6 +943,14 @@ namespace System.Management.Automation
}
}
if (includeSystemModulePath)
{
var processedPath = ProcessOneModulePath(context, GetSystemwideModulePath(), processedPathSet);
if (processedPath != null)
yield return processedPath;
}
}
static private string ProcessOneModulePath(ExecutionContext context, string envPath, HashSet<string> processedPathSet)
{
string trimmedenvPath = envPath.Trim();
@@ -226,12 +226,8 @@ namespace System.Management.Automation.Internal
string manifestPath = qualifiedPathWithVersion + StringLiterals.PowerShellDataFileExtension;
if (File.Exists(manifestPath))
{
var isValidModuleVersion = version.Equals(ModuleIntrinsics.GetManifestModuleVersion(manifestPath));
if (isValidModuleVersion)
{
isModuleDirectory = true;
yield return manifestPath;
}
isModuleDirectory = true;
yield return manifestPath;
}
}
@@ -309,6 +305,18 @@ namespace System.Management.Automation.Internal
}
}
internal static bool IsModuleInVersionSubdirectory(string modulePath, out Version version)
{
version = null;
var folderName = Path.GetDirectoryName(modulePath);
if (folderName != null)
{
folderName = Path.GetFileName(folderName);
return Version.TryParse(folderName, out version);
}
return false;
}
/// <summary>
/// Gets a list of matching commands
/// </summary>
@@ -978,9 +978,9 @@ namespace Microsoft.PowerShell.Commands
BuildModuleManifest(result, "PowerShellHostVersion", Modules.PowerShellHostVersion, _PowerShellHostVersion != null && !string.IsNullOrEmpty(_PowerShellHostVersion.ToString()), () => QuoteName(_PowerShellHostVersion), streamWriter);
BuildModuleManifest(result, "DotNetFrameworkVersion", Modules.DotNetFrameworkVersion, _DotNetFrameworkVersion != null && !string.IsNullOrEmpty(_DotNetFrameworkVersion.ToString()), () => QuoteName(_DotNetFrameworkVersion), streamWriter);
BuildModuleManifest(result, "DotNetFrameworkVersion", StringUtil.Format(Modules.DotNetFrameworkVersion, Modules.PrerequisiteForDesktopEditionOnly), _DotNetFrameworkVersion != null && !string.IsNullOrEmpty(_DotNetFrameworkVersion.ToString()), () => QuoteName(_DotNetFrameworkVersion), streamWriter);
BuildModuleManifest(result, "CLRVersion", Modules.CLRVersion, _ClrVersion != null && !string.IsNullOrEmpty(_ClrVersion.ToString()), () => QuoteName(_ClrVersion), streamWriter);
BuildModuleManifest(result, "CLRVersion", StringUtil.Format(Modules.CLRVersion, Modules.PrerequisiteForDesktopEditionOnly), _ClrVersion != null && !string.IsNullOrEmpty(_ClrVersion.ToString()), () => QuoteName(_ClrVersion), streamWriter);
BuildModuleManifest(result, "ProcessorArchitecture", Modules.ProcessorArchitecture, _processorArchitecture.HasValue, () => QuoteName(_processorArchitecture), streamWriter);
@@ -848,6 +848,7 @@ namespace System.Management.Automation
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
[ArchitectureSensitive]
static bool IsWindowsApplication(string fileName)
{
#if CORECLR
@@ -1250,6 +1251,7 @@ namespace System.Management.Automation
private static extern IntPtr FindExecutableW(
string fileName, string directoryPath, StringBuilder pathFound);
[ArchitectureSensitive]
private static string FindExecutable(string filename)
{
// Preallocate a
@@ -164,6 +164,7 @@ namespace System.Management.Automation
}
}
[ArchitectureSensitive]
internal static string GetStringFromSecureString(SecureString ss)
{
IntPtr p = IntPtr.Zero;
@@ -878,7 +878,7 @@ namespace System.Management.Automation.Runspaces
PSHostUserInterface host = executionContext.EngineHostInterface.UI;
if (host != null)
{
host.StopAllTranscribing();
host.StopAllTranscribing(executionContext.CurrentRunspace.InstanceId);
}
}
}
@@ -420,12 +420,13 @@ namespace System.Management.Automation.Host
}
}
internal void StartTranscribing(string path, System.Management.Automation.Remoting.PSSenderInfo senderInfo, bool includeInvocationHeader)
{
internal void StartTranscribing(string path, System.Management.Automation.Remoting.PSSenderInfo senderInfo, bool includeInvocationHeader, Guid runspaceInstanceId)
{
TranscriptionOption transcript = new TranscriptionOption();
transcript.Path = path;
transcript.IncludeInvocationHeader = includeInvocationHeader;
TranscriptionData.Transcripts.Add(transcript);
transcript.RunspaceInstanceId = runspaceInstanceId;
TranscriptionData.Transcripts.Add(transcript);
LogTranscriptHeader(senderInfo, transcript);
}
@@ -476,7 +477,7 @@ namespace System.Management.Automation.Host
TranscribeCommandComplete(null);
}
internal string StopTranscribing()
internal string StopTranscribing(Guid runspaceInstanceId)
{
if (TranscriptionData.Transcripts.Count == 0)
{
@@ -484,11 +485,17 @@ namespace System.Management.Automation.Host
}
TranscriptionOption stoppedTranscript = TranscriptionData.Transcripts[TranscriptionData.Transcripts.Count - 1];
LogTranscriptFooter(stoppedTranscript);
stoppedTranscript.Dispose();
TranscriptionData.Transcripts.Remove(stoppedTranscript);
return stoppedTranscript.Path;
if (stoppedTranscript.RunspaceInstanceId == runspaceInstanceId)
{
LogTranscriptFooter(stoppedTranscript);
stoppedTranscript.Dispose();
TranscriptionData.Transcripts.Remove(stoppedTranscript);
return stoppedTranscript.Path;
}
return null;
}
private void LogTranscriptFooter(TranscriptionOption stoppedTranscript)
@@ -514,13 +521,13 @@ namespace System.Management.Automation.Host
}
}
internal void StopAllTranscribing()
internal void StopAllTranscribing(Guid runspaceInstanceId)
{
TranscribeCommandComplete(null);
while (TranscriptionData.Transcripts.Count > 0)
foreach(var transcription in TranscriptionData.Transcripts)
{
StopTranscribing();
StopTranscribing(runspaceInstanceId);
}
lock (TranscriptionData)
@@ -999,7 +1006,7 @@ namespace System.Management.Automation.Host
internal TranscriptionOption SystemTranscript { get; set; }
internal string CommandBeingIgnored { get; set; }
internal bool IsHelperCommand { get; set; }
internal string PromptText { get; set; }
internal string PromptText { get; set; }
}
@@ -1059,6 +1066,12 @@ namespace System.Management.Automation.Host
/// </summary>
internal Encoding Encoding { get; private set; }
/// <summary>
/// RunspaceInstanceId of the transcription session.
/// This is used to choose which transcriptions are closed when runspace is disposed.
/// </summary>
internal Guid RunspaceInstanceId { get; set; }
/// <summary>
/// Logs buffered content to disk. We use this instead of File.AppendAllLines
/// so that we don't need to pay seek penalties all the time, and so that we
@@ -11,9 +11,8 @@ using System.Runtime.CompilerServices;
using System.Reflection;
using System.Text;
using Microsoft.PowerShell;
#if !CORECLR // Configuration Keyword Not Supported On CSS
using Microsoft.PowerShell.DesiredStateConfiguration.Internal;
#endif
namespace System.Management.Automation.Language
{
@@ -1091,8 +1090,6 @@ namespace System.Management.Automation.Language
return AstVisitAction.Continue;
}
#if !CORECLR // Configuration Keyword Not Supported On CSS
public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst)
{
ConfigurationDefinitionAst configAst = Ast.GetAncestorAst<ConfigurationDefinitionAst>(scriptBlockExpressionAst);
@@ -1172,7 +1169,7 @@ namespace System.Management.Automation.Language
}
return AstVisitAction.Continue;
}
}
public override AstVisitAction VisitConfigurationDefinition(ConfigurationDefinitionAst configurationDefinitionAst)
{
@@ -1197,7 +1194,6 @@ namespace System.Management.Automation.Language
return AstVisitAction.Continue;
}
public override AstVisitAction VisitDynamicKeywordStatement(DynamicKeywordStatementAst dynamicKeywordStatementAst)
{
//////////////////////////////////////////////////////////////////////////////////
@@ -1269,7 +1265,7 @@ namespace System.Management.Automation.Language
return AstVisitAction.Continue;
}
#endif //!CORECLR
public override AstVisitAction VisitPropertyMember(PropertyMemberAst propertyMemberAst)
{
@@ -1299,7 +1295,10 @@ namespace System.Management.Automation.Language
}
_scopeStack.Pop();
scriptBlockAst.PostParseChecksPerformed = true;
scriptBlockAst.HadErrors = _parser.ErrorList.Count > 0;
// at this moment, we could use different parser for the initial syntax check
// and this _parser for semantic check.
// that's why '|=' instead of just '='.
scriptBlockAst.HadErrors |= _parser.ErrorList.Count > 0;
}
else if (ast is MemberAst)
{
@@ -261,7 +261,7 @@ namespace System.Management.Automation.Language
// - Assemblies added by 'using assembly'.
// For this case, we REPORT ambiguity, since user explicitly specifies the set of assemblies.
// * All other loaded assemblies (excluding dynamic assemblies created for PS defined types).
// On FullCLR, IGNORE ambiguity. It mimics PS v4. There are two reasons:
// IGNORE ambiguity. It mimics PS v4. There are two reasons:
// 1) If we report ambiguity, we need to fix our caching logic accordingly.
// Consider this code
// Add-Type 'public class Q {}' # ok
@@ -280,7 +280,8 @@ namespace System.Management.Automation.Language
// So [NuGet.VisualStudio.IVsPackageInstallerServices] can be resolved to several different assemblies and it's ok.
// * User defined type accelerators (rare - interface was never public)
//
// If nothing is found, we search again, this time applying any 'using namespace ...' declarations including the implicit 'using namespace System'. We must search all using aliases and REPORT an error if there is an ambiguity.
// If nothing is found, we search again, this time applying any 'using namespace ...' declarations including the implicit 'using namespace System'.
// We must search all using aliases and REPORT an error if there is an ambiguity.
var assemList = assemblies ?? ClrFacade.GetAssemblies(typeResolutionState, typeName);
@@ -301,15 +302,10 @@ namespace System.Management.Automation.Language
return typeName._typeDefinitionAst.Type;
}
#if CORECLR
bool reportAmbigousException = true;
#else
bool reportAmbigousException = false;
#endif
result = ResolveTypeNameWorker(typeName, currentScope, typeResolutionState.assemblies, typeResolutionState, /* reportAmbigousException */ true, out exception);
if (exception == null && result == null)
{
result = ResolveTypeNameWorker(typeName, currentScope, assemList, typeResolutionState, reportAmbigousException, out exception);
result = ResolveTypeNameWorker(typeName, currentScope, assemList, typeResolutionState, /* reportAmbigousException */ false, out exception);
}
if (result != null)
@@ -337,7 +333,7 @@ namespace System.Management.Automation.Language
var newResult = ResolveTypeNameWorker(newTypeName, currentScope, typeResolutionState.assemblies, typeResolutionState, /* reportAmbigousException */ true, out exception);
if (exception == null && newResult == null)
{
newResult = ResolveTypeNameWorker(newTypeName, currentScope, assemList, typeResolutionState, reportAmbigousException, out exception);
newResult = ResolveTypeNameWorker(newTypeName, currentScope, assemList, typeResolutionState, /* reportAmbigousException */ false, out exception);
}
if (exception != null)
@@ -1131,12 +1131,17 @@ namespace System.Management.Automation.Language
if (!PostParseChecksPerformed)
{
Parser parser = new Parser();
PerformPostParseChecks(parser);
// we call PerformPostParseChecks on root ScriptBlockAst, to obey contract of SymbolResolver.
// It needs to be run from the top of the tree.
// It's ok to report an error from a different part of AST in this case.
var root = GetRootScriptBlockAst();
root.PerformPostParseChecks(parser);
if (parser.ErrorList.Any())
{
throw new ParseException(parser.ErrorList.ToArray());
}
}
if (HadErrors)
{
throw new PSInvalidOperationException();
@@ -1145,6 +1150,18 @@ namespace System.Management.Automation.Language
return new ScriptBlock(this, isFilter: false);
}
private ScriptBlockAst GetRootScriptBlockAst()
{
ScriptBlockAst rootScriptBlockAst = this;
ScriptBlockAst parent;
while ((parent = Ast.GetAncestorAst<ScriptBlockAst>(rootScriptBlockAst.Parent)) != null)
{
rootScriptBlockAst = parent;
}
return rootScriptBlockAst;
}
/// <summary>
/// Copy the ScriptBlockAst instance
/// </summary>
@@ -85,24 +85,6 @@ namespace System.Management.Automation.Runspaces
}
}
/// <summary>
/// Name of the container target
/// </summary>
public String ContainerName
{
get
{
if (ComputerType == TargetMachineType.Container)
{
return remoteRunspace.ConnectionInfo.ComputerName;
}
else
{
return string.Empty;
}
}
}
/// <summary>
/// Id of the container target
/// </summary>
@@ -360,17 +360,6 @@ namespace Microsoft.PowerShell.Commands
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
public override string[] ContainerName
{
get
{
return null;
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
@@ -143,17 +143,6 @@ namespace Microsoft.PowerShell.Commands
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
public override string[] ContainerName
{
get
{
return null;
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
@@ -281,16 +281,12 @@ namespace Microsoft.PowerShell.Commands
ParameterSetName = InvokeCommandCommand.FilePathUriParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.ContainerIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.ContainerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.VMIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.VMNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.FilePathContainerIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.FilePathContainerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.FilePathVMIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
@@ -343,11 +339,9 @@ namespace Microsoft.PowerShell.Commands
[Parameter(ParameterSetName = InvokeCommandCommand.VMIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.VMNameParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.ContainerIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.ContainerNameParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathVMIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathVMNameParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathContainerIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathContainerNameParameterSet)]
public override Int32 ThrottleLimit
{
set
@@ -394,11 +388,9 @@ namespace Microsoft.PowerShell.Commands
[Parameter(ParameterSetName = InvokeCommandCommand.VMIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.VMNameParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.ContainerIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.ContainerNameParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathVMIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathVMNameParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathContainerIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathContainerNameParameterSet)]
public SwitchParameter AsJob
{
get
@@ -453,11 +445,9 @@ namespace Microsoft.PowerShell.Commands
[Parameter(ParameterSetName = InvokeCommandCommand.VMIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.VMNameParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.ContainerIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.ContainerNameParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathVMIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathVMNameParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathContainerIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathContainerNameParameterSet)]
[Alias("HCN")]
public SwitchParameter HideComputerName
{
@@ -476,9 +466,7 @@ namespace Microsoft.PowerShell.Commands
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathSessionParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathUriParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.ContainerIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.ContainerNameParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathContainerIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathContainerNameParameterSet)]
public String JobName
{
get
@@ -522,9 +510,6 @@ namespace Microsoft.PowerShell.Commands
[Parameter(Position = 1,
Mandatory = true,
ParameterSetName = InvokeCommandCommand.ContainerIdParameterSet)]
[Parameter(Position = 1,
Mandatory = true,
ParameterSetName = InvokeCommandCommand.ContainerNameParameterSet)]
[ValidateNotNull]
[Alias("Command")]
public override ScriptBlock ScriptBlock
@@ -568,9 +553,6 @@ namespace Microsoft.PowerShell.Commands
[Parameter(Position = 1,
Mandatory = true,
ParameterSetName = FilePathContainerIdParameterSet)]
[Parameter(Position = 1,
Mandatory = true,
ParameterSetName = FilePathContainerNameParameterSet)]
[ValidateNotNull]
[Alias("PSPath")]
public override string FilePath
@@ -666,8 +648,6 @@ namespace Microsoft.PowerShell.Commands
/// </summary>
[Parameter(ParameterSetName = InvokeCommandCommand.ContainerIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathContainerIdParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.ContainerNameParameterSet)]
[Parameter(ParameterSetName = InvokeCommandCommand.FilePathContainerNameParameterSet)]
public override SwitchParameter RunAsAdministrator
{
get { return base.RunAsAdministrator; }
@@ -938,11 +918,9 @@ namespace Microsoft.PowerShell.Commands
case InvokeCommandCommand.VMIdParameterSet:
case InvokeCommandCommand.VMNameParameterSet:
case InvokeCommandCommand.ContainerIdParameterSet:
case InvokeCommandCommand.ContainerNameParameterSet:
case InvokeCommandCommand.FilePathVMIdParameterSet:
case InvokeCommandCommand.FilePathVMNameParameterSet:
case InvokeCommandCommand.FilePathContainerIdParameterSet:
case InvokeCommandCommand.FilePathContainerNameParameterSet:
{
if (ResolvedComputerNames.Length != 0 && Operations.Count > 0)
{
@@ -30,7 +30,7 @@ namespace Microsoft.PowerShell.Commands
private int? _processIdleTimeoutSec = null;
internal const string AttribMaxIdleTimeout = "MaxIdleTimeoutms";
internal static readonly int? DefaultMaxIdleTimeout = 43200; // 12 hours in seconds
internal static readonly int? DefaultMaxIdleTimeout = int.MaxValue;
private int? _maxIdleTimeoutSec = null;
internal const string AttribIdleTimeout = "IdleTimeoutms";
@@ -38,27 +38,27 @@ namespace Microsoft.PowerShell.Commands
private int? _idleTimeoutSec = null;
private const string AttribMaxConcurrentUsers = "MaxConcurrentUsers";
internal static readonly int? DefaultMaxConcurrentUsers = 5;
internal static readonly int? DefaultMaxConcurrentUsers = int.MaxValue;
private int? maxConcurrentUsers = null;
private const string AttribMaxProcessesPerSession = "MaxProcessesPerShell";
internal static readonly int? DefaultMaxProcessesPerSession = 15;
internal static readonly int? DefaultMaxProcessesPerSession = int.MaxValue;
private int? maxProcessesPerSession = null;
private const string AttribMaxMemoryPerSessionMB = "MaxMemoryPerShellMB";
internal static readonly int? DefaultMaxMemoryPerSessionMB = 1024;
internal static readonly int? DefaultMaxMemoryPerSessionMB = int.MaxValue;
private int? maxMemoryPerSessionMB = null;
private const string AttribMaxSessions = "MaxShells";
internal static readonly int? DefaultMaxSessions = 25;
internal static readonly int? DefaultMaxSessions = int.MaxValue;
private int? maxSessions = null;
private const string AttribMaxSessionsPerUser = "MaxShellsPerUser";
internal static readonly int? DefaultMaxSessionsPerUser = 25;
internal static readonly int? DefaultMaxSessionsPerUser = int.MaxValue;
private int? maxSessionsPerUser = null;
private const string AttribMaxConcurrentCommandsPerSession = "MaxConcurrentCommandsPerShell";
internal static readonly int? DefaultMaxConcurrentCommandsPerSession = 1000;
internal static readonly int? DefaultMaxConcurrentCommandsPerSession = int.MaxValue;
private int? maxConcurrentCommandsPerSession = null;
/// <summary>
@@ -350,7 +350,9 @@ namespace Microsoft.PowerShell.Commands
}
if (_maxIdleTimeoutSec.HasValue)
{
sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxIdleTimeout, 1000 * _maxIdleTimeoutSec));
// Special case max int value for unbounded default.
sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxIdleTimeout,
(_maxIdleTimeoutSec == int.MaxValue) ? _maxIdleTimeoutSec : (1000 * _maxIdleTimeoutSec)));
}
return sb.Length > 0
@@ -167,11 +167,6 @@ namespace Microsoft.PowerShell.Commands
/// </summary>
protected const string ContainerIdParameterSet = "ContainerId";
/// <summary>
/// Container name parameter set
/// </summary>
protected const string ContainerNameParameterSet = "ContainerName";
/// <summary>
/// VM guid parameter set
/// </summary>
@@ -601,28 +596,6 @@ namespace Microsoft.PowerShell.Commands
}
private string[] containerId;
/// <summary>
/// Name of target container.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Justification = "This is by spec.")]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.ContainerNameParameterSet)]
[ValidateNotNullOrEmpty]
public virtual string[] ContainerName
{
get
{
return containerName;
}
set
{
containerName = value;
}
}
private string[] containerName;
/// <summary>
/// When set, PowerShell process inside container will be launched with
/// high privileged account.
@@ -630,7 +603,6 @@ namespace Microsoft.PowerShell.Commands
/// with low privileged account.
/// </summary>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.ContainerIdParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.ContainerNameParameterSet)]
public virtual SwitchParameter RunAsAdministrator
{
get
@@ -723,7 +695,6 @@ namespace Microsoft.PowerShell.Commands
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.SessionParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.UriParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.ContainerIdParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.ContainerNameParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.VMIdParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.VMNameParameterSet)]
public virtual Int32 ThrottleLimit
@@ -1031,11 +1002,6 @@ namespace Microsoft.PowerShell.Commands
/// </summary>
protected const string FilePathContainerIdParameterSet = "FilePathContainerId";
/// <summary>
/// Container name file path parameter set.
/// </summary>
protected const string FilePathContainerNameParameterSet = "FilePathContainerName";
#endregion
#region Parameters
@@ -1225,25 +1191,6 @@ namespace Microsoft.PowerShell.Commands
}
private string[] containerId;
/// <summary>
/// Name of target container.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Justification = "This is by spec.")]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.ContainerNameParameterSet)]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.FilePathContainerNameParameterSet)]
[ValidateNotNullOrEmpty]
public override string[] ContainerName
{
get { return containerName; }
set { containerName = value; }
}
private string[] containerName;
/// <summary>
/// For WSMan session:
/// If this parameter is not specified then the value specified in
@@ -1263,16 +1210,12 @@ namespace Microsoft.PowerShell.Commands
ParameterSetName = InvokeCommandCommand.FilePathUriParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.ContainerIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.ContainerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.VMIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.VMNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.FilePathContainerIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.FilePathContainerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = InvokeCommandCommand.FilePathVMIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
@@ -1664,26 +1607,13 @@ namespace Microsoft.PowerShell.Commands
/// </summary>
protected virtual void CreateHelpersForSpecifiedContainerSession()
{
string[] inputArray;
bool isContainerIdSet = false;
List<string> resolvedNameList = new List<string>();
Dbg.Assert((ParameterSetName == PSExecutionCmdlet.ContainerIdParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.FilePathContainerIdParameterSet),
"Expected ParameterSetName == ContainerId or FilePathContainerId");
if ((ParameterSetName == PSExecutionCmdlet.ContainerIdParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.FilePathContainerIdParameterSet))
{
inputArray = ContainerId;
isContainerIdSet = true;
}
else
{
Dbg.Assert((ParameterSetName == PSExecutionCmdlet.ContainerNameParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.FilePathContainerNameParameterSet),
"Expected ParameterSetName == ContainerId, ContainerName, FilePathContainerId or FilePathContainerName");
inputArray = ContainerName;
}
foreach (var input in inputArray)
foreach (var input in ContainerId)
{
//
// Create helper objects for container ID or name.
@@ -1697,14 +1627,7 @@ namespace Microsoft.PowerShell.Commands
// Hyper-V container uses Hype-V socket as transport.
// Windows Server container uses named pipe as transport.
//
if (isContainerIdSet)
{
connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfoById(input, RunAsAdministrator.IsPresent, this.ConfigurationName);
}
else
{
connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfoByName(input, RunAsAdministrator.IsPresent, this.ConfigurationName);
}
connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfo(input, RunAsAdministrator.IsPresent, this.ConfigurationName);
resolvedNameList.Add(connectionInfo.ComputerName);
@@ -1975,11 +1898,9 @@ namespace Microsoft.PowerShell.Commands
if ((ParameterSetName == PSExecutionCmdlet.VMIdParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.VMNameParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.ContainerIdParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.ContainerNameParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.FilePathVMIdParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.FilePathVMNameParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.FilePathContainerIdParameterSet) ||
(ParameterSetName == PSExecutionCmdlet.FilePathContainerNameParameterSet))
(ParameterSetName == PSExecutionCmdlet.FilePathContainerIdParameterSet))
{
SkipWinRMCheck = true;
}
@@ -2031,9 +1952,7 @@ namespace Microsoft.PowerShell.Commands
break;
case PSExecutionCmdlet.ContainerIdParameterSet:
case PSExecutionCmdlet.ContainerNameParameterSet:
case PSExecutionCmdlet.FilePathContainerIdParameterSet:
case PSExecutionCmdlet.FilePathContainerNameParameterSet:
{
CreateHelpersForSpecifiedContainerSession();
}
@@ -2360,11 +2279,6 @@ private string GetConvertedScript(out List<string> newParameterNames, out List<o
/// </summary>
protected const string ContainerIdInstanceIdParameterSet = "ContainerIdInstanceId";
/// <summary>
/// ContainerNameInstanceId parameter set: container name + session instance id
/// </summary>
protected const string ContainerNameInstanceIdParameterSet = "ContainerNameInstanceId";
/// <summary>
/// VMIdInstanceId parameter set: vm id + session instance id
/// </summary>
@@ -2483,25 +2397,6 @@ private string GetConvertedScript(out List<string> newParameterNames, out List<o
}
private string[] containerId;
/// <summary>
/// Name of target container.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Justification = "This is by spec.")]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRunspaceCmdlet.ContainerNameParameterSet)]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRunspaceCmdlet.ContainerNameInstanceIdParameterSet)]
[ValidateNotNullOrEmpty]
public virtual string[] ContainerName
{
get { return containerName; }
set { containerName = value; }
}
private string[] containerName;
/// <summary>
/// Guid of target virtual machine.
/// </summary>
@@ -2606,25 +2501,13 @@ private string GetConvertedScript(out List<string> newParameterNames, out List<o
// container id + optional session name
case PSRunspaceCmdlet.ContainerIdParameterSet:
{
return GetMatchingRunspacesByContainerVMNameContainerId(writeobject, filterState, configurationName, true, true);
return GetMatchingRunspacesByVMNameContainerId(writeobject, filterState, configurationName, true);
}
// container id + session instanceid
case PSRunspaceCmdlet.ContainerIdInstanceIdParameterSet:
{
return GetMatchingRunspacesByContainerVMNameContainerIdSessionInstanceId(writeobject, filterState, configurationName, true, true);
}
// container name + optional session name
case PSRunspaceCmdlet.ContainerNameParameterSet:
{
return GetMatchingRunspacesByContainerVMNameContainerId(writeobject, filterState, configurationName, true, false);
}
// container name + session instanceid
case PSRunspaceCmdlet.ContainerNameInstanceIdParameterSet:
{
return GetMatchingRunspacesByContainerVMNameContainerIdSessionInstanceId(writeobject, filterState, configurationName, true, false);
return GetMatchingRunspacesByVMNameContainerIdSessionInstanceId(writeobject, filterState, configurationName, true);
}
// vm Guid + optional session name
@@ -2642,13 +2525,13 @@ private string GetConvertedScript(out List<string> newParameterNames, out List<o
// vm name + optional session name
case PSRunspaceCmdlet.VMNameParameterSet:
{
return GetMatchingRunspacesByContainerVMNameContainerId(writeobject, filterState, configurationName, false, false);
return GetMatchingRunspacesByVMNameContainerId(writeobject, filterState, configurationName, false);
}
// vm name + session instanceid
case PSRunspaceCmdlet.VMNameInstanceIdParameterSet:
{
return GetMatchingRunspacesByContainerVMNameContainerIdSessionInstanceId(writeobject, filterState, configurationName, false, false);
return GetMatchingRunspacesByVMNameContainerIdSessionInstanceId(writeobject, filterState, configurationName, false);
}
}
@@ -2911,44 +2794,34 @@ private string GetConvertedScript(out List<string> newParameterNames, out List<o
}
/// <summary>
/// Gets the matching runspaces by container name, vm name or container id with optional session name
/// Gets the matching runspaces by vm name or container id with optional session name
/// </summary>
/// <param name="writeobject">if true write the object down the pipeline</param>
/// <param name="filterState">Runspace state filter value.</param>
/// <param name="configurationName">Runspace configuration name filter value.</param>
/// <param name="isContainer">if true the target is a container instead of virtual machine</param>
/// <param name="useContainerId">if true the input is container id</param>
/// <returns>list of matching runspaces</returns>
private Dictionary<Guid, PSSession> GetMatchingRunspacesByContainerVMNameContainerId(bool writeobject,
private Dictionary<Guid, PSSession> GetMatchingRunspacesByVMNameContainerId(bool writeobject,
SessionFilterState filterState,
String configurationName,
bool isContainer,
bool useContainerId)
bool isContainer)
{
String[] inputNames;
TargetMachineType computerType;
bool supportWildChar = false;
bool supportWildChar;
String[] sessionNames = { "*" };
WildcardPattern configurationNamePattern =
String.IsNullOrEmpty(configurationName) ? null : WildcardPattern.Get(configurationName, WildcardOptions.IgnoreCase);
Dictionary<Guid, PSSession> matches = new Dictionary<Guid, PSSession>();
List<PSSession> remoteRunspaceInfos = this.RunspaceRepository.Runspaces;
// container name and vm name support wild characters, while container id does not.
// vm name support wild characters, while container id does not.
// vm id does not apply in this method, which does not support wild characters either.
if (isContainer)
{
if (useContainerId)
{
inputNames = ContainerId;
}
else
{
inputNames = ContainerName;
supportWildChar = true;
}
inputNames = ContainerId;
computerType = TargetMachineType.Container;
supportWildChar = false;
}
else
{
@@ -2973,7 +2846,7 @@ private string GetConvertedScript(out List<string> newParameterNames, out List<o
String.IsNullOrEmpty(sessionName) ? null : WildcardPattern.Get(sessionName, WildcardOptions.IgnoreCase);
var matchingRunspaceInfos = remoteRunspaceInfos
.Where<PSSession>(session => (supportWildChar ? inputNamePattern.IsMatch(isContainer ? session.ContainerName : session.VMName)
.Where<PSSession>(session => (supportWildChar ? inputNamePattern.IsMatch(session.VMName)
: inputName.Equals(session.ContainerId)) &&
((sessionNamePattern == null) ? true : sessionNamePattern.IsMatch(session.Name)) &&
QueryRunspaces.TestRunspaceState(session.Runspace, filterState) &&
@@ -2989,43 +2862,33 @@ private string GetConvertedScript(out List<string> newParameterNames, out List<o
}
/// <summary>
/// Gets the matching runspaces by container name, vm name or container id with session instanceid
/// Gets the matching runspaces by vm name or container id with session instanceid
/// </summary>
/// <param name="writeobject">if true write the object down the pipeline</param>
/// <param name="filterState">Runspace state filter value.</param>
/// <param name="configurationName">Runspace configuration name filter value.</param>
/// <param name="isContainer">if true the target is a container instead of virtual machine</param>
/// <param name="useContainerId">if true the input is container id</param>
/// <returns>list of matching runspaces</returns>
private Dictionary<Guid, PSSession> GetMatchingRunspacesByContainerVMNameContainerIdSessionInstanceId(bool writeobject,
private Dictionary<Guid, PSSession> GetMatchingRunspacesByVMNameContainerIdSessionInstanceId(bool writeobject,
SessionFilterState filterState,
String configurationName,
bool isContainer,
bool useContainerId)
bool isContainer)
{
String[] inputNames;
TargetMachineType computerType;
bool supportWildChar = false;
bool supportWildChar;
WildcardPattern configurationNamePattern =
String.IsNullOrEmpty(configurationName) ? null : WildcardPattern.Get(configurationName, WildcardOptions.IgnoreCase);
Dictionary<Guid, PSSession> matches = new Dictionary<Guid, PSSession>();
List<PSSession> remoteRunspaceInfos = this.RunspaceRepository.Runspaces;
// container name and vm name support wild characters, while container id does not.
// vm name support wild characters, while container id does not.
// vm id does not apply in this method, which does not support wild characters either.
if (isContainer)
{
if (useContainerId)
{
inputNames = ContainerId;
}
else
{
inputNames = ContainerName;
supportWildChar = true;
}
inputNames = ContainerId;
computerType = TargetMachineType.Container;
supportWildChar = false;
}
else
{
@@ -3041,7 +2904,7 @@ private string GetConvertedScript(out List<string> newParameterNames, out List<o
foreach (Guid sessionInstanceId in InstanceId)
{
var matchingRunspaceInfos = remoteRunspaceInfos
.Where<PSSession>(session => (supportWildChar ? inputNamePattern.IsMatch(isContainer ? session.ContainerName : session.VMName)
.Where<PSSession>(session => (supportWildChar ? inputNamePattern.IsMatch(session.VMName)
: inputName.Equals(session.ContainerId)) &&
sessionInstanceId.Equals(session.InstanceId) &&
QueryRunspaces.TestRunspaceState(session.Runspace, filterState) &&
@@ -206,19 +206,6 @@ namespace Microsoft.PowerShell.Commands
}
private string containerId;
/// <summary>
/// The name of the target container.
/// </summary>
[ValidateNotNullOrEmpty]
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true, ParameterSetName = ContainerNameParameterSet)]
public new string ContainerName
{
get { return containerName; }
set { containerName = value; }
}
private string containerName;
/// <summary>
/// For WSMan sessions:
/// If this parameter is not specified then the value specified in
@@ -234,8 +221,6 @@ namespace Microsoft.PowerShell.Commands
ParameterSetName = EnterPSSessionCommand.UriParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = EnterPSSessionCommand.ContainerIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = EnterPSSessionCommand.ContainerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = EnterPSSessionCommand.VMIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
@@ -377,7 +362,6 @@ namespace Microsoft.PowerShell.Commands
break;
case ContainerIdParameterSet:
case ContainerNameParameterSet:
remoteRunspace = GetRunspaceForContainerSession();
break;
}
@@ -923,8 +907,7 @@ namespace Microsoft.PowerShell.Commands
private bool IsParameterSetForContainer()
{
return ((ParameterSetName == ContainerIdParameterSet) ||
(ParameterSetName == ContainerNameParameterSet));
return (ParameterSetName == ContainerIdParameterSet);
}
/// <summary>
@@ -1196,8 +1179,8 @@ namespace Microsoft.PowerShell.Commands
break;
case ContainerIdParameterSet:
case ContainerNameParameterSet:
targetName = this.ContainerName;
targetName = (this.ContainerId.Length <= 15) ? this.ContainerId
: this.ContainerId.Remove(12) + "...";
break;
case SessionParameterSet:
@@ -1254,24 +1237,16 @@ namespace Microsoft.PowerShell.Commands
try
{
Dbg.Assert(!String.IsNullOrEmpty(ContainerId), "ContainerId has to be set.");
ContainerConnectionInfo connectionInfo = null;
//
// Hyper-V container uses Hype-V socket as transport.
// Windows Server container uses named pipe as transport.
//
if (!String.IsNullOrEmpty(ContainerId))
{
connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfoById(ContainerId, RunAsAdministrator.IsPresent, this.ConfigurationName);
}
else
{
Dbg.Assert(!String.IsNullOrEmpty(ContainerName), "Either ContainerId or ContainerName has to be set.");
connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfo(ContainerId, RunAsAdministrator.IsPresent, this.ConfigurationName);
connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfoByName(ContainerName, RunAsAdministrator.IsPresent, this.ConfigurationName);
}
this.ContainerName = connectionInfo.ComputerName;
connectionInfo.CreateContainerProcess();
remoteRunspace = CreateTemporaryRemoteRunspaceForPowerShellDirect(this.Host, connectionInfo);
}
@@ -357,17 +357,6 @@ namespace Microsoft.PowerShell.Commands
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
public override string[] ContainerName
{
get
{
return null;
}
}
/// <summary>
/// Overriding to suppress this parameter
/// </summary>
@@ -137,10 +137,6 @@ namespace Microsoft.PowerShell.Commands
ParameterSetName = GetPSSessionCommand.ContainerIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = GetPSSessionCommand.ContainerIdInstanceIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = GetPSSessionCommand.ContainerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = GetPSSessionCommand.ContainerNameInstanceIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = GetPSSessionCommand.VMIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
@@ -176,7 +172,6 @@ namespace Microsoft.PowerShell.Commands
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRunspaceCmdlet.NameParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ContainerIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ContainerNameParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.VMIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.VMNameParameterSet)]
[ValidateNotNullOrEmpty()]
@@ -197,8 +192,6 @@ namespace Microsoft.PowerShell.Commands
ParameterSetName = PSRunspaceCmdlet.InstanceIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ContainerIdInstanceIdParameterSet,
Mandatory = true)]
[Parameter(ParameterSetName = GetPSSessionCommand.ContainerNameInstanceIdParameterSet,
Mandatory = true)]
[Parameter(ParameterSetName = GetPSSessionCommand.VMIdInstanceIdParameterSet,
Mandatory = true)]
[Parameter(ParameterSetName = GetPSSessionCommand.VMNameInstanceIdParameterSet,
@@ -352,8 +345,6 @@ namespace Microsoft.PowerShell.Commands
[Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriInstanceIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ContainerIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ContainerIdInstanceIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ContainerNameParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.ContainerNameInstanceIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.VMIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.VMIdInstanceIdParameterSet)]
[Parameter(ParameterSetName = GetPSSessionCommand.VMNameParameterSet)]
@@ -183,8 +183,6 @@ namespace Microsoft.PowerShell.Commands
ParameterSetName = NewPSSessionCommand.UriParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = NewPSSessionCommand.ContainerIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = NewPSSessionCommand.ContainerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = NewPSSessionCommand.VMIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
@@ -273,7 +271,6 @@ namespace Microsoft.PowerShell.Commands
break;
case NewPSSessionCommand.ContainerIdParameterSet:
case NewPSSessionCommand.ContainerNameParameterSet:
{
remoteRunspaces = CreateRunspacesWhenContainerParameterSpecified();
}
@@ -1023,31 +1020,18 @@ namespace Microsoft.PowerShell.Commands
}// CreateRunspacesWhenVMParameterSpecified
/// <summary>
/// Creates the remote runspace objects when the ContainerId or ContainerName parameter
/// is specified
/// Creates the remote runspace objects when the ContainerId parameter is specified
/// </summary>
private List<RemoteRunspace> CreateRunspacesWhenContainerParameterSpecified()
{
string[] inputArray;
bool isContainerIdSet = false;
int index = 0;
List<string> resolvedNameList = new List<string>();
List<RemoteRunspace> remoteRunspaces = new List<RemoteRunspace>();
Dbg.Assert((ParameterSetName == PSExecutionCmdlet.ContainerIdParameterSet),
"Expected ParameterSetName == ContainerId");
if (ParameterSetName == PSExecutionCmdlet.ContainerIdParameterSet)
{
inputArray = ContainerId;
isContainerIdSet = true;
}
else
{
Dbg.Assert((ParameterSetName == PSExecutionCmdlet.ContainerNameParameterSet),
"Expected ParameterSetName == ContainerId or ContainerName");
inputArray = ContainerName;
}
foreach (var input in inputArray)
foreach (var input in ContainerId)
{
//
// Create helper objects for container ID or name.
@@ -1064,14 +1048,7 @@ namespace Microsoft.PowerShell.Commands
// Hyper-V container uses Hype-V socket as transport.
// Windows Server container uses named pipe as transport.
//
if (isContainerIdSet)
{
connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfoById(input, RunAsAdministrator.IsPresent, this.ConfigurationName);
}
else
{
connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfoByName(input, RunAsAdministrator.IsPresent, this.ConfigurationName);
}
connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfo(input, RunAsAdministrator.IsPresent, this.ConfigurationName);
resolvedNameList.Add(connectionInfo.ComputerName);
@@ -78,22 +78,6 @@ namespace Microsoft.PowerShell.Commands
}
private string[] containerId;
/// <summary>
/// Name of target container.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Justification = "This is by spec.")]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRunspaceCmdlet.ContainerNameParameterSet)]
[ValidateNotNullOrEmpty]
public override string[] ContainerName
{
get { return containerName; }
set { containerName = value; }
}
private string[] containerName;
/// <summary>
/// Guid of target virtual machine.
/// </summary>
@@ -149,7 +133,6 @@ namespace Microsoft.PowerShell.Commands
case RemovePSSessionCommand.InstanceIdParameterSet:
case RemovePSSessionCommand.IdParameterSet:
case RemovePSSessionCommand.ContainerIdParameterSet:
case RemovePSSessionCommand.ContainerNameParameterSet:
case RemovePSSessionCommand.VMIdParameterSet:
case RemovePSSessionCommand.VMNameParameterSet:
{
@@ -247,7 +247,7 @@ namespace System.Management.Automation.Runspaces
/// The duration (in ms) for which PowerShell should wait before it times out on cancel operations
/// (close runspace or stop powershell). For instance, when the user hits ctrl-C,
/// New-PSSession cmdlet tries to call a stop on all remote runspaces which are in the Opening state.
/// The administrator wouldn’t mind waiting for 15 seconds, but this should be time bound and of a shorter duration.
/// The administrator wouldn�t mind waiting for 15 seconds, but this should be time bound and of a shorter duration.
/// A high timeout here like 3 minutes will give the administrator a feeling that the PowerShell client has hung.
/// </summary>
public int CancelTimeout
@@ -2181,7 +2181,7 @@ namespace System.Management.Automation.Runspaces
/// </summary>
public override string ComputerName
{
get { return _containerProc.ContainerName; }
get { return _containerProc.ContainerId; }
set { throw new PSNotSupportedException(); }
}
@@ -2235,25 +2235,12 @@ namespace System.Management.Automation.Runspaces
/// <summary>
/// Create ContainerConnectionInfo object based on container id.
/// </summary>
public static ContainerConnectionInfo CreateContainerConnectionInfoById(
public static ContainerConnectionInfo CreateContainerConnectionInfo(
string containerId,
bool runAsAdmin,
string configurationName)
{
ContainerProcess containerProc = new ContainerProcess(containerId, null, null, 0, runAsAdmin, configurationName);
return new ContainerConnectionInfo(containerProc);
}
/// <summary>
/// Create ContainerConnectionInfo object based on container name.
/// </summary>
public static ContainerConnectionInfo CreateContainerConnectionInfoByName(
string containerName,
bool runAsAdmin,
string configurationName)
{
ContainerProcess containerProc = new ContainerProcess(null, containerName, null, 0, runAsAdmin, configurationName);
ContainerProcess containerProc = new ContainerProcess(containerId, null, 0, runAsAdmin, configurationName);
return new ContainerConnectionInfo(containerProc);
}
@@ -2290,7 +2277,6 @@ namespace System.Management.Automation.Runspaces
private Guid runtimeId;
private string containerObRoot;
private string containerId;
private string containerName;
private int processId;
private bool runAsAdmin = false;
private string configurationName;
@@ -2301,8 +2287,6 @@ namespace System.Management.Automation.Runspaces
private const uint NoError = 0;
private const uint InvalidContainerId = 1;
private const uint ContainersFeatureNotEnabled = 2;
private const uint InvalidContainerNameMultiple = 3;
private const uint InvalidContainerNameNotExist = 4;
private const uint OtherError = 9999;
#endregion
@@ -2337,15 +2321,6 @@ namespace System.Management.Automation.Runspaces
set { containerId = value; }
}
/// <summary>
/// Name of the container.
/// </summary>
public string ContainerName
{
get { return containerName; }
set { containerName = value; }
}
/// <summary>
/// Process ID of the process created in container.
/// </summary>
@@ -2405,16 +2380,67 @@ namespace System.Management.Automation.Runspaces
#region Native HCS (i.e., host compute service) methods
[StructLayout(LayoutKind.Sequential)]
internal struct HCS_PROCESS_INFORMATION
{
/// <summary>
/// The process id.
/// </summary>
public uint ProcessId;
/// <summary>
/// Reserved.
/// </summary>
public uint Reserved;
/// <summary>
/// If created, standard input handle of the process.
/// </summary>
public IntPtr StdInput;
/// <summary>
/// If created, standard output handle of the process.
/// </summary>
public IntPtr StdOutput;
/// <summary>
/// If created, standard error handle of the process.
/// </summary>
public IntPtr StdError;
}
[DllImport(PinvokeDllNames.CreateProcessInComputeSystemDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern uint CreateProcessInComputeSystem(
string id,
string ProcessParameters,
ref int processId);
internal static extern uint HcsOpenComputeSystem(
string id,
ref IntPtr computeSystem,
ref string result);
[DllImport(PinvokeDllNames.CreateProcessInComputeSystemDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern uint TerminateProcessInComputeSystem(
string id,
int processId);
internal static extern uint HcsGetComputeSystemProperties(
IntPtr computeSystem,
string propertyQuery,
ref string properties,
ref string result);
[DllImport(PinvokeDllNames.CreateProcessInComputeSystemDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern uint HcsCreateProcess(
IntPtr computeSystem,
string processParameters,
ref HCS_PROCESS_INFORMATION processInformation,
ref IntPtr process,
ref string reslt);
[DllImport(PinvokeDllNames.CreateProcessInComputeSystemDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern uint HcsOpenProcess(
IntPtr computeSystem,
int processId,
ref IntPtr process,
ref string result);
[DllImport(PinvokeDllNames.CreateProcessInComputeSystemDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern uint HcsTerminateProcess(
IntPtr process,
ref string result);
#endregion
@@ -2423,30 +2449,17 @@ namespace System.Management.Automation.Runspaces
/// <summary>
/// Creates an instance used for PowerShell Direct for container.
/// </summary>
public ContainerProcess(string containerId, string containerName, string containerObRoot, int processId, bool runAsAdmin, string configurationName)
public ContainerProcess(string containerId, string containerObRoot, int processId, bool runAsAdmin, string configurationName)
{
this.ContainerId = containerId;
this.ContainerName = containerName;
this.ContainerObRoot = containerObRoot;
this.ProcessId = processId;
this.RunAsAdmin = runAsAdmin;
this.ConfigurationName = configurationName;
if (!String.IsNullOrEmpty(containerId))
{
if (String.IsNullOrEmpty(containerName))
{
GetContainerPropertiesFromContainerId();
}
}
else if (!String.IsNullOrEmpty(containerName))
{
GetContainerPropertiesFromContainerName();
}
else
{
Dbg.Assert(false, "containerId and containerName inputs cannot be empty at the same time.");
}
Dbg.Assert(!String.IsNullOrEmpty(containerId), "containerId input cannot be empty.");
GetContainerProperties();
}
#endregion
@@ -2497,11 +2510,11 @@ namespace System.Management.Automation.Runspaces
}
/// <summary>
/// Get container name and object root based on given container id.
/// Get object root based on given container id.
/// </summary>
public void GetContainerPropertiesFromContainerId()
public void GetContainerProperties()
{
RunOnMTAThread(GetContainerPropertiesFromContainerIdInternal);
RunOnMTAThread(GetContainerPropertiesInternal);
//
// Report error.
@@ -2519,37 +2532,6 @@ namespace System.Management.Automation.Runspaces
}
}
/// <summary>
/// Get container id and object root based on given container name.
/// </summary>
public void GetContainerPropertiesFromContainerName()
{
RunOnMTAThread(GetContainerPropertiesFromContainerNameInternal);
//
// Report error.
//
switch (ErrorCode)
{
case NoError:
break;
case ContainersFeatureNotEnabled:
throw new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.ContainersFeatureNotEnabled));
case InvalidContainerNameMultiple:
throw new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.InvalidContainerNameMultiple,
ContainerName));
case InvalidContainerNameNotExist:
throw new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.InvalidContainerNameNotExist,
ContainerName));
case OtherError:
throw new PSInvalidOperationException(ErrorMessage);
}
}
#endregion
#region Private methods
@@ -2583,14 +2565,11 @@ namespace System.Management.Automation.Runspaces
//
try
{
Type computeSystemPropertiesType;
Type hostComputeInteropType;
GetHostComputeInteropTypes(out computeSystemPropertiesType, out hostComputeInteropType);
MethodInfo computeSystemExistsInfo = hostComputeInteropType.GetMethod("ComputeSystemExists");
if (!(bool)computeSystemExistsInfo.Invoke(null, new object[]{ ContainerId }))
IntPtr ComputeSystem = IntPtr.Zero;
string resultString = String.Empty;
result = HcsOpenComputeSystem(ContainerId, ref ComputeSystem, ref resultString);
if (result != 0)
{
processId = 0;
error = InvalidContainerId;
@@ -2606,19 +2585,23 @@ namespace System.Management.Automation.Runspaces
(RuntimeId != Guid.Empty) ? "-so -NoProfile" : "-NamedPipeServerMode",
String.IsNullOrEmpty(ConfigurationName) ? String.Empty : String.Concat("-Config ", ConfigurationName),
(RunAsAdmin) ? "false" : "true");
HCS_PROCESS_INFORMATION ProcessInformation = new HCS_PROCESS_INFORMATION();
IntPtr Process = IntPtr.Zero;
//
// Create PowerShell process inside the container.
//
result = CreateProcessInComputeSystem(
ContainerId,
cmd,
ref processId);
result = HcsCreateProcess(ComputeSystem, cmd, ref ProcessInformation, ref Process, ref resultString);
if (result != 0)
{
processId = 0;
error = result;
}
else
{
processId = Convert.ToInt32(ProcessInformation.ProcessId);
}
}
}
catch (Exception e)
@@ -2654,35 +2637,54 @@ namespace System.Management.Automation.Runspaces
/// </summary>
private void TerminateContainerProcessInternal()
{
ProcessTerminated =
(TerminateProcessInComputeSystem(ContainerId, ProcessId) == 0);
IntPtr ComputeSystem = IntPtr.Zero;
string resultString = String.Empty;
IntPtr process = IntPtr.Zero;
ProcessTerminated = false;
if (HcsOpenComputeSystem(ContainerId, ref ComputeSystem, ref resultString) == 0)
{
if (HcsOpenProcess(ComputeSystem, ProcessId, ref process, ref resultString) == 0)
{
if (HcsTerminateProcess(process, ref resultString) == 0)
{
ProcessTerminated = true;
}
}
}
}
/// <summary>
/// Get container name and object root based on given container id.
/// Get object root based on given container id.
/// </summary>
private void GetContainerPropertiesFromContainerIdInternal()
private void GetContainerPropertiesInternal()
{
try
{
Type computeSystemPropertiesType;
Type hostComputeInteropType;
GetHostComputeInteropTypes(out computeSystemPropertiesType, out hostComputeInteropType);
IntPtr ComputeSystem = IntPtr.Zero;
string resultString = String.Empty;
MethodInfo getComputeSystemPropertiesInfo = hostComputeInteropType.GetMethod("GetComputeSystemProperties");
var computeSystemPropertiesHandle = getComputeSystemPropertiesInfo.Invoke(null, new object[]{ ContainerId });
ContainerName = (string)computeSystemPropertiesType.GetProperty("Name").GetValue(computeSystemPropertiesHandle);
RuntimeId = (Guid)computeSystemPropertiesType.GetProperty("RuntimeId").GetValue(computeSystemPropertiesHandle);
//
// Get container object root for Windows Server container.
//
if (RuntimeId == Guid.Empty)
if (HcsOpenComputeSystem(ContainerId, ref ComputeSystem, ref resultString) == 0)
{
ContainerObRoot = (string)computeSystemPropertiesType.GetProperty("ObRoot").GetValue(computeSystemPropertiesHandle);
Type computeSystemPropertiesType;
Type hostComputeInteropType;
GetHostComputeInteropTypes(out computeSystemPropertiesType, out hostComputeInteropType);
MethodInfo getComputeSystemPropertiesInfo = hostComputeInteropType.GetMethod("HcsGetComputeSystemProperties");
var computeSystemPropertiesHandle = getComputeSystemPropertiesInfo.Invoke(null, new object[]{ ComputeSystem });
RuntimeId = (Guid)computeSystemPropertiesType.GetProperty("RuntimeId").GetValue(computeSystemPropertiesHandle);
//
// Get container object root for Windows Server container.
//
if (RuntimeId == Guid.Empty)
{
ContainerObRoot = (string)computeSystemPropertiesType.GetProperty("ObRoot").GetValue(computeSystemPropertiesHandle);
}
}
}
catch (FileNotFoundException)
@@ -2712,77 +2714,6 @@ namespace System.Management.Automation.Runspaces
}
}
/// <summary>
/// Get container id and object root based on given container name.
/// </summary>
private void GetContainerPropertiesFromContainerNameInternal()
{
try
{
Type computeSystemPropertiesType;
Type hostComputeInteropType;
object computeSystemPropertiesHandle = null;
int computeSystemPropertiesHandlesCount = 0;
var wildCardPattern = WildcardPattern.Get(ContainerName, WildcardOptions.IgnoreCase);
GetHostComputeInteropTypes(out computeSystemPropertiesType, out hostComputeInteropType);
MethodInfo enumerateComputeSystemsInfo = hostComputeInteropType.GetMethod("EnumerateComputeSystems");
var computeSystemPropertiesHandles = (IEnumerable)enumerateComputeSystemsInfo.Invoke(null, new object[] { null, null, null, null });
foreach (var currentComputeSystemPropertiesHandle in computeSystemPropertiesHandles)
{
string name = (string)computeSystemPropertiesType.GetProperty("Name").GetValue(currentComputeSystemPropertiesHandle);
if (wildCardPattern.IsMatch(name))
{
computeSystemPropertiesHandle = currentComputeSystemPropertiesHandle;
computeSystemPropertiesHandlesCount++;
if (computeSystemPropertiesHandlesCount > 1)
{
ErrorCode = InvalidContainerNameMultiple;
return;
}
}
}
if (computeSystemPropertiesHandle == null)
{
ErrorCode = InvalidContainerNameNotExist;
return;
}
ContainerId = (string)computeSystemPropertiesType.GetProperty("Id").GetValue(computeSystemPropertiesHandle);
ContainerName = (string)computeSystemPropertiesType.GetProperty("Name").GetValue(computeSystemPropertiesHandle);
RuntimeId = (Guid)computeSystemPropertiesType.GetProperty("RuntimeId").GetValue(computeSystemPropertiesHandle);
//
// Get container object root for Windows Server container.
//
if (RuntimeId == Guid.Empty)
{
ContainerObRoot = (string)computeSystemPropertiesType.GetProperty("ObRoot").GetValue(computeSystemPropertiesHandle);
}
}
catch (FileNotFoundException)
{
ErrorCode = ContainersFeatureNotEnabled;
}
catch (FileLoadException)
{
ErrorCode = ContainersFeatureNotEnabled;
}
catch (Exception e)
{
CommandProcessorBase.CheckForSevereException(e);
ErrorCode = OtherError;
ErrorMessage = GetErrorMessageFromException(e);
}
}
/// <summary>
/// Run some tasks on MTA thread if needed.
/// </summary>
@@ -228,8 +228,6 @@ namespace System.Management.Automation.Remoting
CannotTerminateProcessInContainer = 968,
ContainersFeatureNotEnabled = 969,
RemoteSessionHyperVSocketServerConstructorFailure = 970,
InvalidContainerNameMultiple = 971,
InvalidContainerNameNotExist = 972,
ContainerSessionConnectFailed = 973,
RemoteSessionHyperVSocketClientConstructorSetSocketOptionFailure = 974,
InvalidVMState = 975,
@@ -459,7 +459,28 @@ namespace System.Management.Automation.Remoting
{
return WSManPluginConstants.ExitCodeFailure;
}
#if !CORECLR
// For long-path support, Full .NET requires some AppContext switches;
// (for CoreCLR this is Not needed, because CoreCLR supports long paths by default)
// internally in .NET they are cached once retrieved and are typically hit very early during an application run;
// so per .NET team's recommendation, we are setting them as soon as we enter managed code.
// We build against CLR4.5 so we can run on Win7/Win8, but we want to use apis added to CLR 4.6, so we use reflection
try
{
Type appContextType = Type.GetType("System.AppContext"); // type is in mscorlib, so it is sufficient to supply the type name qualified by its namespace
object[] blockLongPathsSwitch = new object[] { "Switch.System.IO.BlockLongPaths", false };
object[] useLegacyPathHandlingSwitch = new object[] { "Switch.System.IO.UseLegacyPathHandling", false };
appContextType.InvokeMember("SetSwitch", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.InvokeMethod, null, null, blockLongPathsSwitch);
appContextType.InvokeMember("SetSwitch", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.InvokeMethod, null, null, useLegacyPathHandlingSwitch);
}
catch (Exception e)
{
// If there are any non-critical exceptions (e.g. we are running on CLR prior to 4.6.2), we won't be able to use long paths
CommandProcessorBase.CheckForSevereException(e);
}
#endif
ClrFacade.StructureToPtr<WSManPluginEntryDelegates.WSManPluginEntryDelegatesInternal>(workerPtrs.UnmanagedStruct, wkrPtrs, false);
return WSManPluginConstants.ExitCodeSuccess;
}
@@ -596,9 +596,11 @@ namespace System.Management.Automation.Language
// function wouldn't work properly. Instead, we'll fix things up after the binding decisions are made, see
// EnumerableOps.NonEnumerableObjectEnumerator for more comments on how this works.
var bindingRestrictions = BindingRestrictions.GetExpressionRestriction(
Expression.Call(typeof(PSEnumerableBinder).GetMethod("IsComObject", BindingFlags.Static | BindingFlags.NonPublic),
target.Expression));
return new DynamicMetaObject(
Expression.Call(CachedReflectionInfo.EnumerableOps_GetCOMEnumerator, target.Expression),
GetRestrictions(target)).WriteToDebugLog(this);
Expression.Call(CachedReflectionInfo.EnumerableOps_GetCOMEnumerator, target.Expression), bindingRestrictions).WriteToDebugLog(this);
}
var enumerable = targetValue as IEnumerable;
@@ -687,8 +689,8 @@ namespace System.Management.Automation.Language
internal static bool IsComObject(object obj)
{
// Platform notes: We can't use System.Runtime.InteropServices.Marshal.IsComObject(obj)
// since it doesn't work in partial trust
// we can't use System.Runtime.InteropServices.Marshal.IsComObject(obj) since it doesn't work in partial trust
obj = PSObject.Base(obj);
return obj != null && ComObjectTypeInfo != null && ComObjectTypeInfo.IsAssignableFrom(obj.GetType().GetTypeInfo());
}
@@ -701,7 +703,7 @@ namespace System.Management.Automation.Language
private static IEnumerator NotEnumerableRule(CallSite site, object obj)
{
if (!(obj is PSObject) && !(obj is IEnumerable) && !(obj is IEnumerator) && !(obj is DataTable))
if (!(obj is PSObject) && !(obj is IEnumerable) && !(obj is IEnumerator) && !(obj is DataTable) && !IsComObject(obj))
{
return null;
}
@@ -9,9 +9,137 @@ using System.Reflection;
using System.Reflection.Emit;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Management.Automation.Language;
using System.Threading;
namespace System.Management.Automation
// These APIs are not part of the public contract.
// They are implementation details and intendent to be called from generated assemlbies for PS classes.
//
// Because they are called from other assemblies, we have to make them public.
// We put them in Internal namespace to emphasise that despite the fact that they are public, it's not part of API contract.
namespace System.Management.Automation.Internal
{
/// <summary>
/// Every Runspace in one process contains SessionStateInternal per module (module SessionState).
/// Every RuntimeType is associated to only one SessionState in the Runspace, which creates it:
/// it's ever global state or a module state.
/// In the former case, module can be imported from the different runspaces in the same process.
/// And so runspaces will share RuntimeType. But in every runspace, Type is associated with just one SessionState.
/// We want type methods to be able access $script: variables and module-specific methods.
/// To achive it, we preserve reference to SessionState that creates type in the private field 'SessionStateFieldName'.
/// Later, we use it to call scriptBlocks captured in ScriptBlockMemberMethodWrapper with the right sessionState.
/// </summary>
public class SessionStateKeeper
{
// We use ConditionalWeakTable, because if GC already collect Runspace,
// then there is no way to call a ctor on the type in this Runspace.
private readonly ConditionalWeakTable<Runspace, SessionStateInternal> _stateMap;
internal SessionStateKeeper()
{
_stateMap = new ConditionalWeakTable<Runspace, SessionStateInternal>();
}
internal void RegisterRunspace()
{
// it's not get, but really 'Add' value.
// ConditionalWeakTable.Add throw exception, when you are trying to add a value with the same key.
_stateMap.GetValue(Runspace.DefaultRunspace, runspace => runspace.ExecutionContext.EngineSessionState);
}
/// <summary>
/// This method should be called only from generated ctors for PowerShell classes.
/// It's not intended to be a public API, but because we generate type in a different assembly it has to be public.
/// Return type should be SessionStateInternal, but it violates accessibility consistency, so we use object.
/// </summary>
/// <returns>SessionStateInternal</returns>
public object GetSessionState()
{
SessionStateInternal ss = null;
bool found = _stateMap.TryGetValue(Runspace.DefaultRunspace, out ss);
Diagnostics.Assert(found, "We always should be able to find corresponding SessionState");
return ss;
}
}
/// <summary/>
public class ScriptBlockMemberMethodWrapper
{
/// <summary>Used in codegen</summary>
public static readonly object[] _emptyArgumentArray = Utils.EmptyArray<object>(); // See TypeDefiner.DefineTypeHelper.DefineMethodBody
// we use this _scriptBlock instance for static methods.
private Lazy<ScriptBlock> _scriptBlock;
private IParameterMetadataProvider _ast;
/// <summary>
/// We use ThreadLocal boundScriptBlock to allow multi-thread execution of instance methods.
/// </summary>
private ThreadLocal<ScriptBlock> _boundScriptBlock;
internal ScriptBlockMemberMethodWrapper(IParameterMetadataProvider ast)
{
_ast = ast;
_scriptBlock = new Lazy<ScriptBlock>(() => new ScriptBlock(_ast, isFilter: false));
_boundScriptBlock = new ThreadLocal<ScriptBlock>(
() =>
{
var sb = _scriptBlock.Value.Clone();
return sb;
});
}
internal void InitAtRuntime()
{
var context = Runspace.DefaultRunspace.ExecutionContext;
_scriptBlock.Value.SessionStateInternal = context.EngineSessionState;
}
/// <summary>
/// </summary>
/// <param name="instance">target object or null for static call</param>
/// <param name="sessionStateInternal">sessionStateInternal from private field of instance or null for static call</param>
/// <param name="args"></param>
public void InvokeHelper(object instance, object sessionStateInternal, object[] args)
{
ScriptBlock sb;
if (instance != null)
{
_boundScriptBlock.Value.SessionStateInternal = (SessionStateInternal)sessionStateInternal;
sb = _boundScriptBlock.Value;
}
else
{
sb = _scriptBlock.Value;
}
sb.InvokeAsMemberFunction(instance, args);
}
/// <summary>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="instance">target object or null for static call</param>
/// <param name="sessionStateInternal">sessionStateInternal from private field of instance or null for static call</param>
/// <param name="args"></param>
/// <returns></returns>
public T InvokeHelperT<T>(object instance, object sessionStateInternal, object[] args)
{
ScriptBlock sb;
if (instance != null)
{
_boundScriptBlock.Value.SessionStateInternal = (SessionStateInternal)sessionStateInternal;
sb = _boundScriptBlock.Value;
}
else
{
sb = _scriptBlock.Value;
}
return sb.InvokeAsMemberFunctionT<T>(instance, args);
}
}
/// <summary>
/// Support methods for PowerShell classes.
/// </summary>
@@ -17,10 +17,6 @@ using System.Management.Automation.Runspaces;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading;
#if !CORECLR
using Microsoft.CodeAnalysis;
#endif
using Microsoft.PowerShell.Commands;
// ReSharper disable UnusedMember.Global
@@ -1183,127 +1179,6 @@ namespace System.Management.Automation
}
}
/// <summary>
/// Every Runspace in one process contains SessionStateInternal per module (module SessionState).
/// Every RuntimeType is associated to only one SessionState in the Runspace, which creates it:
/// it's ever global state or a module state.
/// In the former case, module can be imported from the different runspaces in the same process.
/// And so runspaces will share RuntimeType. But in every runspace, Type is associated with just one SessionState.
/// We want type methods to be able access $script: variables and module-specific methods.
/// To achive it, we preserve reference to SessionState that creates type in the private field 'SessionStateFieldName'.
/// Later, we use it to call scriptBlocks captured in ScriptBlockMemberMethodWrapper with the right sessionState.
/// </summary>
public class SessionStateKeeper
{
// We use ConditionalWeakTable, because if GC already collect Runspace,
// then there is no way to call a ctor on the type in this Runspace.
private readonly ConditionalWeakTable<Runspace, SessionStateInternal> _stateMap;
internal SessionStateKeeper()
{
_stateMap = new ConditionalWeakTable<Runspace, SessionStateInternal>();
}
internal void RegisterRunspace()
{
// it's not get, but really 'Add' value.
// ConditionalWeakTable.Add throw exception, when you are trying to add a value with the same key.
_stateMap.GetValue(Runspace.DefaultRunspace, runspace => runspace.ExecutionContext.EngineSessionState);
}
/// <summary>
/// This method should be called only from generated ctors for PowerShell classes.
/// It's not intended to be a public API, but because we generate type in a different assembly it has to be public.
/// Return type should be SessionStateInternal, but it violates accessibility consistency, so we use object.
/// </summary>
/// <returns>SessionStateInternal</returns>
public object GetSessionState()
{
SessionStateInternal ss = null;
bool found = _stateMap.TryGetValue(Runspace.DefaultRunspace, out ss);
Diagnostics.Assert(found, "We always should be able to find corresponding SessionState");
return ss;
}
}
/// <summary/>
public class ScriptBlockMemberMethodWrapper
{
/// <summary>Used in codegen</summary>
public static readonly object[] _emptyArgumentArray = Utils.EmptyArray<object>(); // See TypeDefiner.DefineTypeHelper.DefineMethodBody
// we use this _scriptBlock instance for static methods.
private Lazy<ScriptBlock> _scriptBlock;
private IParameterMetadataProvider _ast;
/// <summary>
/// We use ThreadLocal boundScriptBlock to allow multi-thread execution of instance methods.
/// </summary>
private ThreadLocal<ScriptBlock> _boundScriptBlock;
internal ScriptBlockMemberMethodWrapper(IParameterMetadataProvider ast)
{
_ast = ast;
_scriptBlock = new Lazy<ScriptBlock>(() => new ScriptBlock(_ast, isFilter: false));
_boundScriptBlock = new ThreadLocal<ScriptBlock>(
() =>
{
var sb = _scriptBlock.Value.Clone();
return sb;
});
}
internal void InitAtRuntime()
{
var context = Runspace.DefaultRunspace.ExecutionContext;
_scriptBlock.Value.SessionStateInternal = context.EngineSessionState;
}
/// <summary>
/// </summary>
/// <param name="instance">target object or null for static call</param>
/// <param name="sessionStateInternal">sessionStateInternal from private field of instance or null for static call</param>
/// <param name="args"></param>
public void InvokeHelper(object instance, object sessionStateInternal, object[] args)
{
ScriptBlock sb;
if (instance != null)
{
_boundScriptBlock.Value.SessionStateInternal = (SessionStateInternal)sessionStateInternal;
sb = _boundScriptBlock.Value;
}
else
{
sb = _scriptBlock.Value;
}
sb.InvokeAsMemberFunction(instance, args);
}
/// <summary>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="instance">target object or null for static call</param>
/// <param name="sessionStateInternal">sessionStateInternal from private field of instance or null for static call</param>
/// <param name="args"></param>
/// <returns></returns>
public T InvokeHelperT<T>(object instance, object sessionStateInternal, object[] args)
{
ScriptBlock sb;
if (instance != null)
{
_boundScriptBlock.Value.SessionStateInternal = (SessionStateInternal)sessionStateInternal;
sb = _boundScriptBlock.Value;
}
else
{
sb = _scriptBlock.Value;
}
return sb.InvokeAsMemberFunctionT<T>(instance, args);
}
}
static class HashtableOps
{
internal static void AddKeyValuePair(IDictionary hashtable, object key, object value, IScriptExtent errorExtent)
@@ -250,22 +250,22 @@ namespace System.Management.Automation
private void GetModuleNameAndVersion(string psmodulePathRoot, string filePath, out string moduleName, out Version moduleVersion)
{
Version returnVersion = null;
string returnModuleName = null;
moduleVersion = null;
moduleName = null;
if (filePath.StartsWith(psmodulePathRoot))
if (filePath.StartsWith(psmodulePathRoot, StringComparison.OrdinalIgnoreCase))
{
var moduleRootSubPath = filePath.Remove(0, psmodulePathRoot.Length).TrimStart(Utils.Separators.Directory);
var pathParts = moduleRootSubPath.Split(Utils.Separators.Directory, StringSplitOptions.RemoveEmptyEntries);
//returnModuleRootPath = Path.Combine(psmodulePathRoot, pathParts[0]);
returnModuleName = pathParts[0];
moduleName = pathParts[0];
var potentialVersion = pathParts[1];
Version.TryParse(potentialVersion, out returnVersion);
Version result;
if (Version.TryParse(potentialVersion, out result))
{
moduleVersion = result;
}
}
moduleVersion = returnVersion;
moduleName = returnModuleName;
}
/// <summary>
@@ -472,6 +472,7 @@
"monad/src/engine/resources/Authenticode.resx": "resources/Authenticode.resx",
"monad/src/engine/COM/ComUtil.cs": "engine/COM/ComUtil.cs",
"monad/src/engine/hostifaces/MshHostUserInterface.cs": "engine/hostifaces/MshHostUserInterface.cs",
"monad/src/utils/ArchitectureSensitiveAttribute.cs": "utils/ArchitectureSensitiveAttribute.cs",
"monad/src/engine/DriveInterfaces.cs": "engine/DriveInterfaces.cs",
"monad/src/engine/ComInterop/Errors.cs": "engine/ComInterop/Errors.cs",
"monad/src/singleshell/config/MshConsoleInfo.cs": "singleshell/config/MshConsoleInfo.cs",
@@ -392,7 +392,7 @@
<value>Minimum version of the Windows PowerShell engine required by this module</value>
</data>
<data name="CLRVersion" xml:space="preserve">
<value>Minimum version of the common language runtime (CLR) required by this module</value>
<value>Minimum version of the common language runtime (CLR) required by this module. {0}</value>
</data>
<data name="RequiredModules" xml:space="preserve">
<value>Modules that must be imported into the global environment prior to importing this module</value>
@@ -473,7 +473,7 @@
<value>List of all modules packaged with this module</value>
</data>
<data name="DotNetFrameworkVersion" xml:space="preserve">
<value>Minimum version of Microsoft .NET Framework required by this module</value>
<value>Minimum version of Microsoft .NET Framework required by this module. {0}</value>
</data>
<data name="PowerShellHostName" xml:space="preserve">
<value>Name of the Windows PowerShell host required by this module</value>
@@ -634,4 +634,7 @@
<data name="ManifestMemberNotValid" xml:space="preserve">
<value>The module to process '{0}', listed in field '{1}' of module manifest '{2}' was not processed. {3}</value>
</data>
</root>
<data name="PrerequisiteForDesktopEditionOnly" xml:space="preserve">
<value>This prerequisite is valid for the PowerShell Desktop edition only.</value>
</data>
</root>
@@ -1204,12 +1204,6 @@ All WinRM sessions connected to Windows PowerShell session configurations, such
<data name="InvalidContainerId" xml:space="preserve">
<value>The input ContainerId {0} does not exist, or the corresponding container is not running.</value>
</data>
<data name="InvalidContainerNameMultiple" xml:space="preserve">
<value>The input ContainerName {0} does not resolve to a single running container.</value>
</data>
<data name="InvalidContainerNameNotExist" xml:space="preserve">
<value>The input ContainerName {0} does not exist, or the corresponding container is not running.</value>
</data>
<data name="InvalidVMId" xml:space="preserve">
<value>The input VMId parameter does not resolve to a single virtual machine.</value>
</data>
@@ -121,6 +121,7 @@ namespace System.Management.Automation
///
/// <remarks> </remarks>
///
[ArchitectureSensitive]
internal static Signature SignFile(SigningOption option,
string fileName,
X509Certificate2 certificate,
@@ -312,6 +313,7 @@ namespace System.Management.Automation
///
/// <remarks> </remarks>
///
[ArchitectureSensitive]
internal static Signature GetSignature(string fileName, string fileContent)
{
Signature signature = null;
@@ -503,6 +505,7 @@ namespace System.Management.Automation
return signature;
}
[ArchitectureSensitive]
private static DWORD GetWinTrustData(string fileName, string fileContent,
out NativeMethods.WINTRUST_DATA wtData)
{
@@ -559,6 +562,7 @@ namespace System.Management.Automation
return dwResult;
}
[ArchitectureSensitive]
private static X509Certificate2 GetCertFromChain(IntPtr pSigner)
{
X509Certificate2 signerCert = null;
@@ -581,6 +585,7 @@ namespace System.Management.Automation
return signerCert;
}
[ArchitectureSensitive]
private static Signature GetSignatureFromWintrustData(
string filePath,
DWORD error,
@@ -653,6 +658,7 @@ namespace System.Management.Automation
return signature;
}
[ArchitectureSensitive]
private static DWORD GetLastWin32Error()
{
int error = Marshal.GetLastWin32Error();
@@ -76,6 +76,7 @@ namespace Microsoft.PowerShell
///
/// <returns> contents of s (char[]) converted to byte[] </returns>
///
[ArchitectureSensitive]
internal static byte[] GetData(SecureString s)
{
//
@@ -466,6 +466,7 @@ namespace System.Management.Automation
///
/// <param name="path">The path to the file in question</param>
/// <param name="handle">A file handle to the file in question, if available.</param>
[ArchitectureSensitive]
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")]
internal static SaferPolicy GetSaferPolicy(string path, SafeHandle handle)
{
@@ -758,6 +759,7 @@ namespace System.Management.Automation
///
/// <remarks> </remarks>
///
[ArchitectureSensitive]
internal static Collection<string> GetCertEKU(X509Certificate2 cert)
{
Collection<string> ekus = new Collection<string>();
@@ -587,6 +587,7 @@ namespace System.Management.Automation.Security
internal IntPtr psUnauthenticatedNotUsed; // PCRYPT_ATTRIBUTES
};
[ArchitectureSensitive]
internal static CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO
InitSignInfoExtendedStruct(string description,
string moreInfoUrl,
@@ -692,6 +693,7 @@ namespace System.Management.Automation.Security
uint dwGroupId);
[ArchitectureSensitive]
internal static DWORD GetCertChoiceFromSigningOption(
SigningOption option)
{
@@ -719,6 +721,7 @@ namespace System.Management.Automation.Security
return cc;
}
[ArchitectureSensitive]
internal static CRYPTUI_WIZ_DIGITAL_SIGN_INFO
InitSignInfoStruct(string fileName,
X509Certificate2 signingCert,
@@ -815,6 +818,7 @@ namespace System.Management.Automation.Security
internal byte[] Data4;
}
[ArchitectureSensitive]
internal static WINTRUST_FILE_INFO InitWintrustFileInfoStruct(string fileName)
{
WINTRUST_FILE_INFO fi = new WINTRUST_FILE_INFO();
@@ -827,6 +831,7 @@ namespace System.Management.Automation.Security
return fi;
}
[ArchitectureSensitive]
internal static WINTRUST_BLOB_INFO InitWintrustBlobInfoStruct(string fileName, string content)
{
WINTRUST_BLOB_INFO bi = new WINTRUST_BLOB_INFO();
@@ -959,6 +964,7 @@ namespace System.Management.Automation.Security
internal uint dwUIContext;
}
[ArchitectureSensitive]
internal static WINTRUST_DATA InitWintrustDataStructFromFile(WINTRUST_FILE_INFO wfi)
{
WINTRUST_DATA wtd = new WINTRUST_DATA();
@@ -982,6 +988,7 @@ namespace System.Management.Automation.Security
return wtd;
}
[ArchitectureSensitive]
internal static WINTRUST_DATA InitWintrustDataStructFromBlob(WINTRUST_BLOB_INFO wbi)
{
WINTRUST_DATA wtd = new WINTRUST_DATA();
@@ -1005,6 +1012,7 @@ namespace System.Management.Automation.Security
return wtd;
}
[ArchitectureSensitive]
internal static DWORD DestroyWintrustDataStruct(WINTRUST_DATA wtd)
{
DWORD dwResult = Win32Errors.E_FAIL;
@@ -0,0 +1,28 @@
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Reflection;
namespace System.Management.Automation.Internal
{
/// <summary>
/// This attribute is used for Design For Testability.
/// It should be placed on any method containing code
/// which is likely to be sensitive to X86/X64/IA64 issues,
/// primarily code which calls DllImports or otherwise uses
/// NativeMethods. This allows us to generate code coverage
/// data specific to architecture sensitive code.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple=false)]
internal class ArchitectureSensitiveAttribute : Attribute
{
/// <summary>
/// Constructor for the ArchitectureSensitiveAttribute class.
/// </summary>
internal ArchitectureSensitiveAttribute ()
{
}
}
}
@@ -95,7 +95,17 @@ namespace System.Management.Automation
internal static IntPtr GetRawProcessHandle(Process process)
{
#if CORECLR
try
{
return process.SafeHandle.DangerousGetHandle();
}
catch (InvalidOperationException)
{
// It's possible that the process has already exited when we try to get its handle.
// In that case, InvalidOperationException will be thrown from Process.SafeHandle,
// and we return the invalid zero pointer.
return IntPtr.Zero;
}
#else
return process.Handle;
#endif
@@ -866,7 +866,7 @@ namespace System.Management.Automation
internal static readonly string[] ManifestModuleVersionPropertyName = new[] {"ModuleVersion"};
internal static readonly string[] ManifestGuidPropertyName = new[] { "GUID" };
internal static readonly string[] FastModuleManifestAnalysisPropertyNames = new[] {"AliasesToExport", "CmdletsToExport", "FunctionsToExport", "NestedModules", "RootModule", "ModuleToProcess"};
internal static readonly string[] FastModuleManifestAnalysisPropertyNames = new[] {"AliasesToExport", "CmdletsToExport", "FunctionsToExport", "NestedModules", "RootModule", "ModuleToProcess", "ModuleVersion"};
internal static Hashtable GetModuleManifestProperties(string psDataFilePath, string[] keys)
{