| |
| |
|
|
| using System.Collections; |
| using System.Collections.Generic; |
| using System.Diagnostics; |
| using System.IO; |
| using System.Linq; |
| using System.Management.Automation.Language; |
| using System.Net.NetworkInformation; |
| using System.Runtime.CompilerServices; |
| using System.Runtime.InteropServices; |
| using System.Text; |
| using System.Xml; |
|
|
| namespace System.Management.Automation |
| { |
| |
| |
| |
| internal static class PsUtils |
| { |
| |
| private static int? s_currentParentProcessId; |
| private static readonly int s_currentProcessId = Environment.ProcessId; |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| internal static Process GetParentProcess(Process current) |
| { |
| var processId = current.Id; |
|
|
| |
| |
| var parentProcessId = processId == s_currentProcessId && s_currentParentProcessId.HasValue ? |
| s_currentParentProcessId.Value : |
| Microsoft.PowerShell.ProcessCodeMethods.GetParentPid(current); |
|
|
| |
| if (processId == s_currentProcessId && !s_currentParentProcessId.HasValue) |
| { |
| s_currentParentProcessId = parentProcessId; |
| } |
|
|
| if (parentProcessId == 0) |
| return null; |
|
|
| try |
| { |
| Process returnProcess = Process.GetProcessById(parentProcessId); |
|
|
| |
| |
| |
| if (returnProcess.StartTime <= current.StartTime) |
| return returnProcess; |
| else |
| return null; |
| } |
| catch (ArgumentException) |
| { |
| |
| |
| |
| return null; |
| } |
| } |
|
|
| |
| |
| |
| |
| internal static bool IsRunningOnProcessArchitectureARM() |
| { |
| Architecture arch = RuntimeInformation.ProcessArchitecture; |
| return arch == Architecture.Arm || arch == Architecture.Arm64; |
| } |
|
|
| internal static string GetHostName() |
| { |
| IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties(); |
|
|
| string hostname = ipProperties.HostName; |
| string domainName = ipProperties.DomainName; |
|
|
| |
| |
| if (!string.IsNullOrEmpty(domainName) && !domainName.Equals("(none)", StringComparison.Ordinal)) |
| { |
| hostname = hostname + "." + domainName; |
| } |
|
|
| return hostname; |
| } |
|
|
| internal static uint GetNativeThreadId() |
| { |
| #if UNIX |
| return Platform.NonWindowsGetThreadId(); |
| #else |
| return Interop.Windows.GetCurrentThreadId(); |
| #endif |
| } |
|
|
| #region ASTUtils |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| internal static string GetUsingExpressionKey(Language.UsingExpressionAst usingAst) |
| { |
| Diagnostics.Assert(usingAst != null, "Caller makes sure the parameter is not null"); |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| string usingAstText = usingAst.ToString(); |
| if (usingAst.SubExpression is Language.VariableExpressionAst) |
| { |
| usingAstText = usingAstText.ToLowerInvariant(); |
| } |
|
|
| return StringToBase64Converter.StringToBase64String(usingAstText); |
| } |
|
|
| #endregion ASTUtils |
|
|
| #region EvaluatePowerShellDataFile |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| internal static Hashtable EvaluatePowerShellDataFileAsModuleManifest( |
| string parameterName, |
| string psDataFilePath, |
| ExecutionContext context, |
| bool skipPathValidation) |
| { |
| |
| |
| return EvaluatePowerShellDataFile( |
| parameterName, |
| psDataFilePath, |
| context, |
| Microsoft.PowerShell.Commands.ModuleCmdletBase.PermittedCmdlets, |
| new[] { "PSScriptRoot" }, |
| allowEnvironmentVariables: true, |
| skipPathValidation: skipPathValidation); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| internal static Hashtable EvaluatePowerShellDataFile( |
| string parameterName, |
| string psDataFilePath, |
| ExecutionContext context, |
| IEnumerable<string> allowedCommands, |
| IEnumerable<string> allowedVariables, |
| bool allowEnvironmentVariables, |
| bool skipPathValidation) |
| { |
| if (!skipPathValidation && string.IsNullOrEmpty(parameterName)) |
| { |
| throw PSTraceSource.NewArgumentNullException(nameof(parameterName)); |
| } |
|
|
| if (string.IsNullOrEmpty(psDataFilePath)) |
| { |
| throw PSTraceSource.NewArgumentNullException(nameof(psDataFilePath)); |
| } |
|
|
| if (context == null) |
| { |
| throw PSTraceSource.NewArgumentNullException(nameof(context)); |
| } |
|
|
| string resolvedPath; |
| if (skipPathValidation) |
| { |
| resolvedPath = psDataFilePath; |
| } |
| else |
| { |
| #region "ValidatePowerShellDataFilePath" |
|
|
| bool isPathValid = true; |
|
|
| |
| string pathExt = Path.GetExtension(psDataFilePath); |
| if (string.IsNullOrEmpty(pathExt) || |
| !StringLiterals.PowerShellDataFileExtension.Equals(pathExt, StringComparison.OrdinalIgnoreCase)) |
| { |
| isPathValid = false; |
| } |
|
|
| ProviderInfo provider; |
| var resolvedPaths = context.SessionState.Path.GetResolvedProviderPathFromPSPath(psDataFilePath, out provider); |
|
|
| |
| if (provider == null || !Microsoft.PowerShell.Commands.FileSystemProvider.ProviderName.Equals(provider.Name, StringComparison.OrdinalIgnoreCase)) |
| { |
| isPathValid = false; |
| } |
|
|
| |
| if (resolvedPaths.Count != 1) |
| { |
| isPathValid = false; |
| } |
|
|
| if (!isPathValid) |
| { |
| throw PSTraceSource.NewArgumentException( |
| parameterName, |
| ParserStrings.CannotResolvePowerShellDataFilePath, |
| psDataFilePath); |
| } |
|
|
| resolvedPath = resolvedPaths[0]; |
|
|
| #endregion "ValidatePowerShellDataFilePath" |
| } |
|
|
| #region "LoadAndEvaluatePowerShellDataFile" |
|
|
| object evaluationResult; |
| try |
| { |
| |
| string dataFileName = Path.GetFileName(resolvedPath); |
| var dataFileScriptInfo = new ExternalScriptInfo(dataFileName, resolvedPath, context); |
| ScriptBlock scriptBlock = dataFileScriptInfo.ScriptBlock; |
|
|
| |
| scriptBlock.CheckRestrictedLanguage(allowedCommands, allowedVariables, allowEnvironmentVariables); |
|
|
| |
| object oldPsScriptRoot = context.GetVariableValue(SpecialVariables.PSScriptRootVarPath); |
| try |
| { |
| |
| context.SetVariable(SpecialVariables.PSScriptRootVarPath, Path.GetDirectoryName(resolvedPath)); |
| evaluationResult = PSObject.Base(scriptBlock.InvokeReturnAsIs()); |
| } |
| finally |
| { |
| context.SetVariable(SpecialVariables.PSScriptRootVarPath, oldPsScriptRoot); |
| } |
| } |
| catch (RuntimeException ex) |
| { |
| throw PSTraceSource.NewInvalidOperationException( |
| ex, |
| ParserStrings.CannotLoadPowerShellDataFile, |
| psDataFilePath, |
| ex.Message); |
| } |
|
|
| if (evaluationResult is not Hashtable retResult) |
| { |
| throw PSTraceSource.NewInvalidOperationException( |
| ParserStrings.InvalidPowerShellDataFile, |
| psDataFilePath); |
| } |
|
|
| #endregion "LoadAndEvaluatePowerShellDataFile" |
|
|
| return retResult; |
| } |
|
|
| #endregion EvaluatePowerShellDataFile |
|
|
| internal static readonly string[] ManifestModuleVersionPropertyName = new[] { "ModuleVersion" }; |
| internal static readonly string[] ManifestGuidPropertyName = new[] { "GUID" }; |
| internal static readonly string[] ManifestPrivateDataPropertyName = new[] { "PrivateData" }; |
|
|
| internal static readonly string[] FastModuleManifestAnalysisPropertyNames = new[] |
| { |
| "AliasesToExport", |
| "CmdletsToExport", |
| "CompatiblePSEditions", |
| "FunctionsToExport", |
| "NestedModules", |
| "RootModule", |
| "ModuleToProcess", |
| "ModuleVersion" |
| }; |
|
|
| internal static Hashtable GetModuleManifestProperties(string psDataFilePath, string[] keys) |
| { |
| string dataFileContents = File.ReadAllText(psDataFilePath, Encoding.Default); |
| ParseError[] parseErrors; |
| var ast = (new Parser()).Parse(psDataFilePath, dataFileContents, null, out parseErrors, ParseMode.ModuleAnalysis); |
| if (parseErrors.Length > 0) |
| { |
| var pe = new ParseException(parseErrors); |
| throw PSTraceSource.NewInvalidOperationException( |
| pe, |
| ParserStrings.CannotLoadPowerShellDataFile, |
| psDataFilePath, |
| pe.Message); |
| } |
|
|
| var pipeline = ast.GetSimplePipeline(false, out _, out _); |
| if (pipeline?.GetPureExpression() is HashtableAst hashtableAst) |
| { |
| var result = new Hashtable(StringComparer.OrdinalIgnoreCase); |
| foreach (var pair in hashtableAst.KeyValuePairs) |
| { |
| if (pair.Item1 is StringConstantExpressionAst key && keys.Contains(key.Value, StringComparer.OrdinalIgnoreCase)) |
| { |
| try |
| { |
| var val = pair.Item2.SafeGetValue(); |
| result[key.Value] = val; |
| } |
| catch |
| { |
| throw PSTraceSource.NewInvalidOperationException( |
| ParserStrings.InvalidPowerShellDataFile, |
| psDataFilePath); |
| } |
| } |
| } |
|
|
| return result; |
| } |
|
|
| throw PSTraceSource.NewInvalidOperationException( |
| ParserStrings.InvalidPowerShellDataFile, |
| psDataFilePath); |
| } |
| } |
|
|
| |
| |
| |
| |
| internal static class StringToBase64Converter |
| { |
| |
| |
| |
| |
| |
| internal static string StringToBase64String(string input) |
| { |
| |
| |
| if (input == null) |
| { |
| throw PSTraceSource.NewArgumentNullException(nameof(input)); |
| } |
|
|
| string base64 = Convert.ToBase64String |
| ( |
| Encoding.Unicode.GetBytes(input.ToCharArray()) |
| ); |
| return base64; |
| } |
|
|
| |
| |
| |
| |
| |
| internal static string Base64ToString(string base64) |
| { |
| if (string.IsNullOrEmpty(base64)) |
| { |
| throw PSTraceSource.NewArgumentNullException(nameof(base64)); |
| } |
|
|
| string output = new string(Encoding.Unicode.GetChars(Convert.FromBase64String(base64))); |
| return output; |
| } |
|
|
| |
| |
| |
| |
| |
| internal static object[] Base64ToArgsConverter(string base64) |
| { |
| if (string.IsNullOrEmpty(base64)) |
| { |
| throw PSTraceSource.NewArgumentNullException(nameof(base64)); |
| } |
|
|
| string decoded = new string(Encoding.Unicode.GetChars(Convert.FromBase64String(base64))); |
|
|
| |
| XmlReader reader = XmlReader.Create(new StringReader(decoded), InternalDeserializer.XmlReaderSettingsForCliXml); |
| object dso; |
| Deserializer deserializer = new Deserializer(reader); |
| dso = deserializer.Deserialize(); |
| if (!deserializer.Done()) |
| { |
| |
| |
| throw PSTraceSource.NewArgumentException(MinishellParameterBinderController.ArgsParameter); |
| } |
|
|
| if (dso is not PSObject mo) |
| { |
| |
| |
| throw PSTraceSource.NewArgumentException(MinishellParameterBinderController.ArgsParameter); |
| } |
|
|
| if (mo.BaseObject is not ArrayList argsList) |
| { |
| |
| |
| throw PSTraceSource.NewArgumentException(MinishellParameterBinderController.ArgsParameter); |
| } |
|
|
| return argsList.ToArray(); |
| } |
| } |
|
|
| |
| |
| |
| |
| internal static class CRC32Hash |
| { |
| |
| private const uint polynomial = 0x1EDC6F41; |
|
|
| private static readonly uint[] table; |
|
|
| static CRC32Hash() |
| { |
| uint temp = 0; |
| table = new uint[256]; |
|
|
| for (int i = 0; i < table.Length; i++) |
| { |
| temp = (uint)i; |
| for (int j = 0; j < 8; j++) |
| { |
| if ((temp & 1) == 1) |
| { |
| temp = (temp >> 1) ^ polynomial; |
| } |
| else |
| { |
| temp >>= 1; |
| } |
| } |
|
|
| table[i] = temp; |
| } |
| } |
|
|
| private static uint Compute(byte[] buffer) |
| { |
| uint crc = 0xFFFFFFFF; |
| for (int i = 0; i < buffer.Length; ++i) |
| { |
| var index = (byte)(crc ^ buffer[i] & 0xff); |
| crc = (crc >> 8) ^ table[index]; |
| } |
|
|
| return ~crc; |
| } |
|
|
| internal static byte[] ComputeHash(byte[] buffer) |
| { |
| uint crcResult = Compute(buffer); |
| return BitConverter.GetBytes(crcResult); |
| } |
|
|
| internal static string ComputeHash(string input) |
| { |
| byte[] hashBytes = ComputeHash(Encoding.UTF8.GetBytes(input)); |
| return Convert.ToHexString(hashBytes); |
| } |
| } |
|
|
| #region ReferenceEqualityComparer |
|
|
| |
| |
| |
| internal class ReferenceEqualityComparer : IEqualityComparer |
| { |
| bool IEqualityComparer.Equals(object x, object y) |
| { |
| return Object.ReferenceEquals(x, y); |
| } |
|
|
| int IEqualityComparer.GetHashCode(object obj) |
| { |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| return RuntimeHelpers.GetHashCode(obj); |
| } |
| } |
|
|
| #endregion |
| } |
|
|