From 45140c57520890b9bc7e0b4357faad14f7edf52b Mon Sep 17 00:00:00 2001 From: PowerShell Team Date: Wed, 30 Mar 2016 14:26:05 -0700 Subject: [PATCH] Move files from psl-monad submodule to super-project This commit uses master branch 860eb5d --- .../management/ClearRecycleBinCommand.cs | 6 +- .../management/CommitTransactionCommand.cs | 3 + .../commands/management/Computer.cs | 3 + .../commands/management/Eventlog.cs | 3 + .../management/GetClipboardCommand.cs | 6 +- .../management/GetTransactionCommand.cs | 3 + .../management/GetWMIObjectCommand.cs | 3 + .../commands/management/Hotfix.cs | 3 + .../management/InvokeWMIMethodCommand.cs | 3 + .../commands/management/ParsePathCommand.cs | 14 +- .../commands/management/Process.cs | 161 +++- .../management/RegisterWMIEventCommand.cs | 3 + .../management/RemoveWMIObjectCommand.cs | 3 + .../management/RollbackTransactionCommand.cs | 3 + .../management/SetClipboardCommand.cs | 6 +- .../management/SetWMIInstanceCommand.cs | 3 + .../management/StartTransactionCommand.cs | 3 + .../management/UseTransactionCommand.cs | 3 + .../commands/management/WMIHelper.cs | 3 + .../commands/management/WebServiceProxy.cs | 3 + .../installer/MshManagementMshSnapin.cs | 3 + .../commands/utility/AddType.cs | 10 +- .../FormatAndOutput/OutGridView/ColumnInfo.cs | 4 +- .../OutGridView/ExpressionColumnInfo.cs | 4 +- .../FormatAndOutput/OutGridView/HeaderInfo.cs | 4 +- .../OutGridView/OriginalColumnInfo.cs | 3 + .../OutGridView/OutGridViewCommand.cs | 3 + .../OutGridView/OutWindowProxy.cs | 3 + .../OutGridView/ScalarTypeColumnInfo.cs | 4 +- .../FormatAndOutput/OutGridView/TableView.cs | 3 + .../out-printer/PrinterLineOutput.cs | 3 + .../out-printer/out-printer.cs | 3 + .../utility/ImplicitRemotingCommands.cs | 25 +- .../commands/utility/Import-LocalizedData.cs | 24 +- .../commands/utility/Measure-Object.cs | 2 +- .../commands/utility/Send-MailMessage.cs | 4 +- .../commands/utility/SetDateCommand.cs | 29 +- .../utility/ShowCommand/ShowCommand.cs | 7 +- .../ShowCommand/ShowCommandCommandInfo.cs | 8 +- .../ShowCommand/ShowCommandModuleInfo.cs | 6 +- .../ShowCommand/ShowCommandParameterInfo.cs | 6 +- .../ShowCommandParameterSetInfo.cs | 8 +- .../ShowCommand/ShowCommandParameterType.cs | 8 +- .../utility/ShowCommand/ShowCommandProxy.cs | 7 +- .../WebCmdlet/BasicHtmlWebResponseObject.cs | 5 +- .../utility/WebCmdlet/ContentHelper.cs | 5 +- .../WebCmdlet/HtmlWebResponseObject.cs | 5 +- .../WebCmdlet/InvokeRestMethodCommand.cs | 7 +- .../WebCmdlet/InvokeWebRequestCommand.cs | 5 +- .../WebCmdlet/JsonObjectTypeResolver.cs | 5 +- .../commands/utility/WebCmdlet/PSUserAgent.cs | 5 +- .../utility/WebCmdlet/StreamHelper.cs | 5 +- .../utility/WebCmdlet/WebRequestPSCmdlet.cs | 5 +- .../utility/WebCmdlet/WebRequestSession.cs | 5 +- .../utility/WebCmdlet/WebResponseHelper.cs | 5 +- .../utility/WebCmdlet/WebResponseObject.cs | 5 +- .../WebCmdlet/WebResponseObjectFactory.cs | 5 +- .../commands/utility/WriteConsoleCmdlet.cs | 5 + .../commands/utility/convert-HTML.cs | 3 + .../utility/trace/GetTracerCommand.cs | 3 + .../utility/trace/MshHostTraceListener.cs | 3 + .../utility/trace/SetTracerCommand.cs | 3 + .../utility/trace/TraceCommandBase.cs | 3 + .../utility/trace/TraceExpressionCommand.cs | 3 + .../utility/trace/TraceListenerCommandBase.cs | 3 + .../commands/utility/update-list.cs | 3 + .../installer/MshUtilityMshSnapin.cs | 3 + .../CoreCLR/CorePsAssemblyLoadContext.cs | 52 +- .../security/CertificateCommands.cs | 3 + .../security/CmsCommands.cs | 3 + .../installer/MshSecurityMshSnapin.cs | 3 + .../CoreCLR/CorePsExtensions.cs | 208 +++-- .../CoreCLR/CorePsPlatform.cs | 719 ++++++++++++++++++ .../CoreCLR/CorePsStub.cs | 365 ++++++++- ...mdlets-over-objects.objectModel.autogen.cs | 5 +- ...lets-over-objects.xmlSerializer.autogen.cs | 5 +- ...mdlets-over-objects.objectModel.autogen.cs | 5 +- ...lets-over-objects.xmlSerializer.autogen.cs | 5 +- .../common/DisplayDatabase/FormatTable.cs | 16 +- .../displayResourceManagerCache.cs | 4 + .../DisplayDatabase/typeDataXmlLoader.cs | 3 +- .../engine/CodeMethods.cs | 3 + .../engine/ComInterop/ArgBuilder.cs | 3 + .../engine/ComInterop/BoolArgBuilder.cs | 3 + .../engine/ComInterop/BoundDispEvent.cs | 3 + .../engine/ComInterop/CollectionExtensions.cs | 3 + .../engine/ComInterop/ComBinder.cs | 3 + .../engine/ComInterop/ComBinderHelpers.cs | 3 + .../engine/ComInterop/ComClassMetaObject.cs | 3 + .../engine/ComInterop/ComDispIds.cs | 3 + .../engine/ComInterop/ComEventDesc.cs | 3 + .../engine/ComInterop/ComEventSink.cs | 3 + .../engine/ComInterop/ComEventSinkProxy.cs | 3 + .../ComInterop/ComEventSinksContainer.cs | 3 + .../ComInterop/ComFallbackMetaObject.cs | 3 + .../engine/ComInterop/ComHresults.cs | 3 + .../engine/ComInterop/ComInterop.cs | 3 + .../engine/ComInterop/ComInvokeAction.cs | 3 + .../engine/ComInterop/ComInvokeBinder.cs | 3 + .../engine/ComInterop/ComMetaObject.cs | 3 + .../engine/ComInterop/ComMethodDesc.cs | 3 + .../engine/ComInterop/ComObject.cs | 3 + .../engine/ComInterop/ComParamDesc.cs | 3 + .../engine/ComInterop/ComRuntimeHelpers.cs | 3 + .../engine/ComInterop/ComType.cs | 3 + .../engine/ComInterop/ComTypeClassDesc.cs | 3 + .../engine/ComInterop/ComTypeDesc.cs | 3 + .../engine/ComInterop/ComTypeEnumDesc.cs | 3 + .../engine/ComInterop/ComTypeLibDesc.cs | 3 + .../engine/ComInterop/ComTypeLibInfo.cs | 3 + .../engine/ComInterop/ComTypeLibMemberDesc.cs | 3 + .../engine/ComInterop/ConversionArgBuilder.cs | 3 + .../engine/ComInterop/ConvertArgBuilder.cs | 3 + .../ComInterop/ConvertibleArgBuilder.cs | 3 + .../engine/ComInterop/CurrencyArgBuilder.cs | 3 + .../engine/ComInterop/DateTimeArgBuilder.cs | 3 + .../engine/ComInterop/DispCallable.cs | 3 + .../ComInterop/DispCallableMetaObject.cs | 3 + .../engine/ComInterop/DispatchArgBuilder.cs | 3 + .../engine/ComInterop/ErrorArgBuilder.cs | 3 + .../engine/ComInterop/Errors.cs | 3 + .../engine/ComInterop/ExcepInfo.cs | 3 + .../engine/ComInterop/Helpers.cs | 3 + .../engine/ComInterop/IDispatchComObject.cs | 3 + .../engine/ComInterop/IDispatchMetaObject.cs | 3 + .../engine/ComInterop/IPseudoComObject.cs | 3 + .../engine/ComInterop/NullArgBuilder.cs | 3 + .../engine/ComInterop/SimpleArgBuilder.cs | 3 + .../engine/ComInterop/SplatCallSite.cs | 3 + .../engine/ComInterop/StringArgBuilder.cs | 3 + .../engine/ComInterop/TypeEnumMetaObject.cs | 3 + .../ComInterop/TypeLibInfoMetaObject.cs | 3 + .../engine/ComInterop/TypeLibMetaObject.cs | 3 + .../engine/ComInterop/TypeUtils.cs | 3 + .../engine/ComInterop/UnknownArgBuilder.cs | 3 + .../engine/ComInterop/VarEnumSelector.cs | 3 + .../engine/ComInterop/Variant.cs | 3 + .../engine/ComInterop/VariantArgBuilder.cs | 3 + .../engine/ComInterop/VariantArray.cs | 3 + .../engine/ComInterop/VariantBuilder.cs | 3 + .../CommandCompletion/CompletionCompleters.cs | 11 +- .../engine/CommandDiscovery.cs | 15 +- .../engine/CommandPathSearch.cs | 23 +- .../engine/DataStoreAdapter.cs | 52 ++ .../engine/DataStoreAdapterProvider.cs | 22 + .../engine/ExecutionContext.cs | 2 +- .../engine/ExtraAdapter.cs | 5 +- .../engine/InformationRecord.cs | 12 +- .../engine/InitialSessionState.cs | 106 ++- .../engine/LanguagePrimitives.cs | 6 + .../engine/ManagementObjectAdapter.cs | 3 + .../engine/Modules/ModuleIntrinsics.cs | 38 +- .../engine/MshObjectTypeDescriptor.cs | 3 + .../engine/NativeCommandParameterBinder.cs | 2 +- .../engine/NativeCommandProcessor.cs | 6 +- .../engine/PSMI/PSNegotiationData.cs | 6 +- .../engine/PSMI/PSPowerShellPipeline.cs | 6 +- .../Serialization/InternalMISerializer.cs | 6 +- .../engine/PSMI/Serialization/KnownMITypes.cs | 6 +- .../engine/PSMI/Serialization/MISerializer.cs | 6 +- .../Serialization/MITypeSerializationInfo.cs | 6 +- .../PSMI/Serialization/PSMISerializer.cs | 6 +- .../engine/PSVersionInfo.cs | 7 +- .../engine/SecurityManagerBase.cs | 9 + .../engine/SessionStateDriveAPIs.cs | 3 +- .../engine/SessionStateNavigation.cs | 34 +- .../engine/SessionStateStrings.cs | 8 +- .../engine/TransactedString.cs | 3 + .../engine/TransactionManager.cs | 3 + .../engine/Utils.cs | 261 ++++++- .../engine/hostifaces/History.cs | 35 +- .../hostifaces/NativeCultureResolver.cs | 4 +- .../engine/hostifaces/RunspaceInvoke.cs | 3 + .../remoting/commands/remotingcommandutil.cs | 59 +- .../remoting/common/RemoteSessionNamedPipe.cs | 8 +- .../fanin/InitialSessionStateProvider.cs | 2 +- .../engine/remoting/fanin/WSManNativeAPI.cs | 38 +- .../engine/remoting/fanin/WSManPlugin.cs | 72 +- .../remoting/fanin/WSManPluginFacade.cs | 60 +- .../remoting/fanin/WSManPluginShellSession.cs | 2 +- .../fanin/WSManPluginTransportManager.cs | 30 +- .../remoting/server/ServerPowerShellDriver.cs | 25 +- .../remoting/server/serverremotesession.cs | 7 +- .../engine/runtime/Binding/Binders.cs | 23 +- .../help/HelpSystem.cs | 2 +- .../logging/MshLog.cs | 4 +- .../logging/eventlog/EventLogLogProvider.cs | 5 +- .../namespaces/FileSystemContentStream.cs | 6 +- .../namespaces/FileSystemProvider.cs | 477 ++++++++++-- .../namespaces/LocationGlobber.cs | 209 +++-- .../namespaces/RegistryProvider.cs | 6 + .../namespaces/SafeRegistryHandle.cs | 4 + .../namespaces/SafeTransactionHandle.cs | 7 +- .../namespaces/TransactedRegistry.cs | 3 + .../namespaces/TransactedRegistryKey.cs | 12 +- .../namespaces/TransactedRegistrySecurity.cs | 3 + .../security/SecurityManager.cs | 5 +- .../security/SecuritySupport.cs | 68 +- .../security/wldpNativeMethods.cs | 4 +- .../singleshell/Commands/ConsoleCommands.cs | 3 + .../singleshell/Commands/MshSnapinCommands.cs | 3 + .../singleshell/config/MshSnapinInfo.cs | 28 +- .../config/RegistryStringResourceIndirect.cs | 3 + .../config/RunspaceConfigForSingleShell.cs | 3 +- .../singleshell/installer/CustomMshSnapin.cs | 3 + .../singleshell/installer/MshCoreMshSnapin.cs | 3 + .../singleshell/installer/MshInstaller.cs | 3 + .../singleshell/installer/MshSnapin.cs | 3 + .../installer/MshSnapinInstaller.cs | 3 + .../utils/BackgroundDispatcher.cs | 5 +- .../utils/ClrFacade.cs | 73 +- .../utils/ExtensionMethods.cs | 8 + .../utils/GraphicalHostReflectionWrapper.cs | 5 +- .../utils/PowerShellETWTracer.cs | 7 +- .../utils/PsUtils.cs | 25 + .../utils/WindowsErrorReporting.cs | 7 +- .../perfCounters/CounterSetInstanceBase.cs | 5 +- .../perfCounters/CounterSetRegistrarBase.cs | 5 +- .../utils/perfCounters/PSPerfCountersMgr.cs | 5 +- .../utils/tracing/EtwActivity.cs | 4 + .../utils/tracing/EtwActivityReverter.cs | 6 +- .../EtwActivityReverterMethodInvoker.cs | 6 +- .../utils/tracing/EtwEventCorrelator.cs | 6 +- .../utils/tracing/IMethodInvoker.cs | 6 +- .../utils/tracing/PSEtwLog.cs | 4 + .../utils/tracing/PSEtwLogProvider.cs | 5 +- .../utils/tracing/Tracing.cs | 5 +- .../utils/tracing/TracingGen.cs | 3 + src/TypeCatalogGen/TypeCatalogGen.cs | 12 +- .../pwrshcommon/ConfigFileReader.cpp | 2 +- 230 files changed, 3494 insertions(+), 715 deletions(-) create mode 100644 src/System.Management.Automation/CoreCLR/CorePsPlatform.cs diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs index 60653a6de..5c67e1899 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs @@ -1,4 +1,5 @@ -using System; +#if !CORECLR +using System; using System.Management.Automation; using System.Runtime.InteropServices; using System.IO; @@ -251,4 +252,5 @@ namespace Microsoft.PowerShell.Commands [DllImport("Shell32.dll", CharSet = CharSet.Unicode)] internal static extern uint SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath, RecycleFlags dwFlags); } -} \ No newline at end of file +} +#endif diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/CommitTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/CommitTransactionCommand.cs index 63669c7e5..6c77912b9 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/CommitTransactionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/CommitTransactionCommand.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -32,3 +33,5 @@ namespace Microsoft.PowerShell.Commands } // namespace Microsoft.PowerShell.Commands + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs index 88a2ee2b1..978a492d9 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -7384,3 +7385,5 @@ $result #endregion }//End namespace + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs index 15059f3e7..4473fb52f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -1631,3 +1632,5 @@ namespace Microsoft.PowerShell.Commands }//Microsoft.PowerShell.Commands + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs index 9db034e2c..99ab75198 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs @@ -1,4 +1,5 @@ -using System; +#if !CORECLR +using System; using System.Management.Automation; using System.Collections.Generic; using System.Windows.Forms; @@ -200,4 +201,5 @@ namespace Microsoft.PowerShell.Commands return result; } } -} \ No newline at end of file +} +#endif diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetTransactionCommand.cs index 366b6274d..aedba2dbd 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetTransactionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetTransactionCommand.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -26,3 +27,5 @@ namespace Microsoft.PowerShell.Commands } // namespace Microsoft.PowerShell.Commands + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs index c2e6736f1..e3aad4779 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -468,3 +469,5 @@ namespace Microsoft.PowerShell.Commands } // namespace Microsoft.PowerShell.Commands + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs index e693b0f69..8af70ed1c 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -276,3 +277,5 @@ namespace Microsoft.PowerShell.Commands #endregion }//Microsoft.Powershell.commands + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs index 904d4a909..68206ef9a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs @@ -1,3 +1,4 @@ +#if !CORECLR // // Copyright (C) Microsoft. All rights reserved. // @@ -298,3 +299,5 @@ namespace Microsoft.PowerShell.Commands #endregion Command code }//InvokeWMIObject } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs index 4f137484d..341d713ac 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs @@ -272,6 +272,7 @@ namespace Microsoft.PowerShell.Commands #region Command code + private static string volumeSeparatorCharAsString = System.IO.Path.VolumeSeparatorChar.ToString(); /// /// Parses the specified path and returns the portion determined by the /// boolean parameters. @@ -395,7 +396,7 @@ namespace Microsoft.PowerShell.Commands continue; case qualifierSet : - int separatorIndex = pathsToParse[index].IndexOf(":", StringComparison.CurrentCulture); + int separatorIndex = pathsToParse[index].IndexOf(volumeSeparatorCharAsString, StringComparison.CurrentCulture); if (separatorIndex < 0) { @@ -537,10 +538,15 @@ namespace Microsoft.PowerShell.Commands string result = path; - if (SessionState.Path.IsProviderQualified(path)) + // Platform notes: On single root fileystems, there is no such thing + // as a drive qualifier, and so this is a noop + if (Platform.HasSingleRootFilesystem()) + { + } + else if (SessionState.Path.IsProviderQualified(path)) { int index = path.IndexOf("::", StringComparison.CurrentCulture); - + if (index != -1) { // remove the qualifier @@ -553,8 +559,8 @@ namespace Microsoft.PowerShell.Commands if (SessionState.Path.IsPSAbsolute(path, out driveName)) { - // Remove the drive name and colon + // Remove the drive name and colon result = path.Substring(driveName.Length + 1); } } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs index b4664a5d5..5d9fe6800 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -1362,7 +1362,7 @@ namespace Microsoft.PowerShell.Commands continue; } - if (!Force) + if (Platform.IsWindows() && !Force) { // Check if the process is owned by current user if (!IsProcessOwnedByCurrentUser(process)) @@ -2001,6 +2001,9 @@ namespace Microsoft.PowerShell.Commands } private SwitchParameter _UseNewEnvironment; + private StreamWriter OutputWriter; + private StreamWriter ErrorWriter; + #endregion #region overrides @@ -2094,7 +2097,10 @@ namespace Microsoft.PowerShell.Commands } //LoadUserProfile. - startInfo.LoadUserProfile = _loaduserprofile; + if (Platform.IsWindows()) + { + startInfo.LoadUserProfile = _loaduserprofile; + } if (_credential != null) { @@ -2186,8 +2192,30 @@ namespace Microsoft.PowerShell.Commands } #endif //Starts the Process - Process process = start(startInfo); - + Process process; + if (Platform.IsWindows()) + { + process = start(startInfo); + } + else + { + process = new Process(); + process.StartInfo = startInfo; + SetupInputOutputRedirection(process); + process.Start(); + if (process.StartInfo.RedirectStandardOutput) + { + process.BeginOutputReadLine(); + } + if (process.StartInfo.RedirectStandardError) + { + process.BeginErrorReadLine(); + } + if (process.StartInfo.RedirectStandardInput) + { + WriteToStandardInput(process); + } + } //Wait and Passthru Implementation. if (_passthru.IsPresent) @@ -2210,20 +2238,27 @@ namespace Microsoft.PowerShell.Commands { if (!process.HasExited) { - waithandle = new ManualResetEvent(false); - - // Create and start the job object - ProcessCollection jobObject = new ProcessCollection(); - if (jobObject.AssignProcessToJobObject(process)) + if (Platform.IsWindows()) { - // Wait for the job object to finish - jobObject.WaitOne(waithandle); + waithandle = new ManualResetEvent(false); + + // Create and start the job object + ProcessCollection jobObject = new ProcessCollection(); + if (jobObject.AssignProcessToJobObject(process)) + { + // Wait for the job object to finish + jobObject.WaitOne(waithandle); + } + else + { + // WinBlue: 27537 Start-Process -Wait doesn't work in a remote session on Windows 7 or lower. + process.Exited += new EventHandler(myProcess_Exited); + process.EnableRaisingEvents = true; + process.WaitForExit(); + } } else { - // WinBlue: 27537 Start-Process -Wait doesn't work in a remote session on Windows 7 or lower. - process.Exited += new EventHandler(myProcess_Exited); - process.EnableRaisingEvents = true; process.WaitForExit(); } } @@ -2282,6 +2317,104 @@ namespace Microsoft.PowerShell.Commands } } + private void StdOutputHandler(object sendingProcess, DataReceivedEventArgs outLine) + { + if (!String.IsNullOrEmpty(outLine.Data)) + { + OutputWriter.WriteLine(outLine.Data); + OutputWriter.Flush(); + } + } + + private void StdErrorHandler(object sendingProcess, DataReceivedEventArgs outLine) + { + if (!String.IsNullOrEmpty(outLine.Data)) + { + ErrorWriter.WriteLine(outLine.Data); + ErrorWriter.Flush(); + } + } + + private void ExitHandler(object sendingProcess, System.EventArgs e) + { + // To avoid a race condition with Std*Handler, let's wait a bit before closing the streams + // System.Timer is not supported in CoreCLR, so let's spawn a new thread to do the wait + + Thread delayedStreamClosing = new Thread(StreamClosing); + delayedStreamClosing.Start(); + } + + private void StreamClosing() + { + Thread.Sleep(1000); + + if (OutputWriter != null) + { + OutputWriter.Dispose(); + } + if (ErrorWriter != null) + { + ErrorWriter.Dispose(); + } + } + + private void SetupInputOutputRedirection(Process p) + { + if (_redirectstandardinput != null) + { + p.StartInfo.RedirectStandardInput = true; + _redirectstandardinput = ResolveFilePath(_redirectstandardinput); + } + else + { + p.StartInfo.RedirectStandardInput = false; + } + + if (_redirectstandardoutput != null) + { + p.StartInfo.RedirectStandardOutput = true; + _redirectstandardoutput = ResolveFilePath(_redirectstandardoutput); + p.OutputDataReceived += new DataReceivedEventHandler(StdOutputHandler); + + // Can't do StreamWriter(string) in coreCLR + OutputWriter = new StreamWriter(new FileStream(_redirectstandardoutput, FileMode.Create)); + } + else + { + p.StartInfo.RedirectStandardOutput = false; + OutputWriter = null; + } + + if (_redirectstandarderror != null) + { + p.StartInfo.RedirectStandardError = true; + _redirectstandarderror = ResolveFilePath(_redirectstandarderror); + p.ErrorDataReceived += new DataReceivedEventHandler(StdErrorHandler); + + // Can't do StreamWriter(string) in coreCLR + ErrorWriter = new StreamWriter(new FileStream(_redirectstandarderror, FileMode.Create)); + } + else + { + p.StartInfo.RedirectStandardError = false; + ErrorWriter = null; + } + + p.EnableRaisingEvents = true; + p.Exited += new EventHandler(ExitHandler); + } + + private void WriteToStandardInput(Process p) + { + StreamWriter writer = p.StandardInput; + using (StreamReader reader = new StreamReader(new FileStream(_redirectstandardinput, FileMode.Open))) + { + string line = reader.ReadToEnd(); + writer.WriteLine(line); + } + writer.Dispose(); + } + private Process StartWithCreateProcess(ProcessStartInfo startinfo) { diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs index a3be5e099..80d9f0235 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs @@ -1,3 +1,4 @@ +#if !CORECLR // // Copyright (C) Microsoft. All rights reserved. // @@ -216,3 +217,5 @@ namespace Microsoft.PowerShell.Commands } } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs index 706196dc6..b135fbc2f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs @@ -1,3 +1,4 @@ +#if !CORECLR // // Copyright (C) Microsoft. All rights reserved. // @@ -171,3 +172,5 @@ namespace Microsoft.PowerShell.Commands #endregion Command code } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RollbackTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RollbackTransactionCommand.cs index b5ae078fb..b8ab72dae 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RollbackTransactionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/RollbackTransactionCommand.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -32,3 +33,5 @@ namespace Microsoft.PowerShell.Commands } // namespace Microsoft.PowerShell.Commands + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs index d83d4b870..8dcd5e72b 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs @@ -1,4 +1,5 @@ -using System; +#if !CORECLR +using System; using System.Management.Automation; using System.Collections.Generic; using System.Globalization; @@ -418,4 +419,5 @@ EndSelection:<<<<<<<<4"; } } -} \ No newline at end of file +} +#endif diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs index f43d604c7..84317267a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs @@ -1,3 +1,4 @@ +#if !CORECLR // // Copyright (C) Microsoft. All rights reserved. // @@ -193,3 +194,5 @@ namespace Microsoft.PowerShell.Commands #endregion Command code } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs index 3754775dc..bf1c14d2b 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -103,3 +104,5 @@ namespace Microsoft.PowerShell.Commands } // namespace Microsoft.PowerShell.Commands + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs index b0b105dc0..229d8a201 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -93,3 +94,5 @@ namespace Microsoft.PowerShell.Commands } // namespace Microsoft.PowerShell.Commands + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs index 21f4c6e7d..af5295934 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs @@ -1,3 +1,4 @@ +#if !CORECLR // // Copyright (C) Microsoft. All rights reserved. // @@ -2111,3 +2112,5 @@ namespace Microsoft.PowerShell.Commands } // HandleThrottleComplete } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs index 3f300bea7..d5c16a2f2 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************-- Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -477,3 +478,5 @@ namespace Microsoft.PowerShell.Commands #endregion }//Microsoft.Powershell.commands + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Management/singleshell/installer/MshManagementMshSnapin.cs b/src/Microsoft.PowerShell.Commands.Management/singleshell/installer/MshManagementMshSnapin.cs index 49166075b..526fb6ebe 100644 --- a/src/Microsoft.PowerShell.Commands.Management/singleshell/installer/MshManagementMshSnapin.cs +++ b/src/Microsoft.PowerShell.Commands.Management/singleshell/installer/MshManagementMshSnapin.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -91,3 +92,5 @@ namespace Microsoft.PowerShell } } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs index cc74cf431..fc1fb2da4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs @@ -1137,7 +1137,7 @@ namespace Microsoft.PowerShell.Commands // First try by strong name try { - loadedAssembly = System.Reflection.Assembly.Load(new AssemblyName(assemblyName)); + loadedAssembly = ClrFacade.Load(new AssemblyName(assemblyName)); } // Generates a FileNotFoundException if you can't load the strong type. // So we'll try from the short name. @@ -1912,7 +1912,7 @@ namespace Microsoft.PowerShell.Commands { foreach(string path in paths) { - generatedTypes.AddRange(System.Reflection.Assembly.LoadFrom(path).GetTypes()); + generatedTypes.AddRange(ClrFacade.LoadFrom(path).GetTypes()); } } // Load the assembly by name @@ -2030,7 +2030,7 @@ namespace Microsoft.PowerShell.Commands // First try by strong name try { - loadedAssembly = System.Reflection.Assembly.Load(assemblyName); + loadedAssembly = ClrFacade.Load(assemblyName); } // Generates a FileNotFoundException if you can't load the strong type. // So we'll try from the short name. @@ -2042,7 +2042,7 @@ namespace Microsoft.PowerShell.Commands // Next, try an exact match if (StrongNames.Value.ContainsKey(assemblyName)) { - return System.Reflection.Assembly.Load(StrongNames.Value[assemblyName]); + return ClrFacade.Load(StrongNames.Value[assemblyName]); } // If the assembly name doesn't contain wildcards, return null. The caller generates an error here. @@ -2085,7 +2085,7 @@ namespace Microsoft.PowerShell.Commands return null; // Otherwise, load the assembly. - return System.Reflection.Assembly.Load(matchedStrongName); + return ClrFacade.Load(matchedStrongName); } private static ConcurrentDictionary InitializeStrongNameDictionary() diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs index 03cd917ed..c46519159 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs @@ -1,3 +1,4 @@ +#if !CORECLR // // Copyright (C) Microsoft. All rights reserved. // @@ -56,4 +57,5 @@ namespace Microsoft.PowerShell.Commands return HostUtilities.GetMaxLines(srcString, 10); } } -} \ No newline at end of file +} +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ExpressionColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ExpressionColumnInfo.cs index 093cd12df..95d49653f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ExpressionColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ExpressionColumnInfo.cs @@ -1,3 +1,4 @@ +#if !CORECLR // // Copyright (C) Microsoft. All rights reserved. // @@ -38,4 +39,5 @@ namespace Microsoft.PowerShell.Commands return objectResult == null ? String.Empty : ColumnInfo.LimitString(objectResult.ToString()); } } -} \ No newline at end of file +} +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs index b51748868..968aa94da 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs @@ -1,3 +1,4 @@ +#if !CORECLR // // Copyright (C) Microsoft. All rights reserved. // @@ -59,4 +60,5 @@ namespace Microsoft.PowerShell.Commands return staleObject; } } -} \ No newline at end of file +} +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs index 5e89c754c..de3982895 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs @@ -1,3 +1,4 @@ +#if !CORECLR // // Copyright (C) Microsoft. All rights reserved. // @@ -71,3 +72,5 @@ namespace Microsoft.PowerShell.Commands } } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs index bfc3a5396..1d6ce8830 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs @@ -1,3 +1,4 @@ +#if !CORECLR // // Copyright (C) Microsoft. All rights reserved. // @@ -529,3 +530,5 @@ namespace Microsoft.PowerShell.Commands } } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs index 635af783b..5d8cd0802 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs @@ -1,3 +1,4 @@ +#if !CORECLR // // Copyright (C) Microsoft. All rights reserved. // @@ -307,3 +308,5 @@ namespace Microsoft.PowerShell.Commands } } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs index 2ee294cca..989116e5e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs @@ -1,3 +1,4 @@ +#if !CORECLR // // Copyright (C) Microsoft. All rights reserved. // @@ -76,4 +77,5 @@ namespace Microsoft.PowerShell.Commands return index++; } } -} \ No newline at end of file +} +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs index 7822caf5c..a05506e32 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs @@ -1,3 +1,4 @@ +#if !CORECLR // // Copyright (C) Microsoft. All rights reserved. // @@ -281,3 +282,5 @@ namespace Microsoft.PowerShell.Commands } } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs index 018f907f9..97393fa21 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -331,3 +332,5 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/out-printer.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/out-printer.cs index 11c537537..77f0093fb 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/out-printer.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/out-printer.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -74,3 +75,5 @@ namespace Microsoft.PowerShell.Commands + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index 2b68bb0b6..59107f1a8 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -2031,9 +2032,7 @@ namespace Microsoft.PowerShell.Commands return result.ToString(); } - private const string SectionSeparator = @" -############################################################################## -"; + private const string SectionSeparator = "\r\n##############################################################################\r\n"; private void GenerateSectionSeparator(TextWriter writer) { @@ -2080,14 +2079,7 @@ namespace Microsoft.PowerShell.Commands #region Generating header of a proxy module - private const string TopCommentTemplate = @" -<# - # {0} - # {1} - # {2} - # {3} - #> - "; + private const string TopCommentTemplate = "\r\n<#\r\n # {0}\r\n # {1}\r\n # {2}\r\n # {3}\r\n #>\r\n"; private void GenerateTopComment(TextWriter writer) { @@ -2403,8 +2395,7 @@ function Get-PSImplicitRemotingSession -ErrorAction SilentlyContinue ) }} if (($script:PSSession -ne $null) -and ($script:PSSession.Runspace.RunspaceStateInfo.State -eq 'Disconnected')) - {{ - # If we are handed a disconnected session, try re-connecting it before creating a new session. + {{ # If we are handed a disconnected session, try re-connecting it before creating a new session. Set-PSImplicitRemotingSession ` (& $script:ConnectPSSession ` -Session $script:PSSession ` @@ -2848,12 +2839,7 @@ function Get-PSImplicitRemotingClientSideParameters }} Process {{ {6} }} End {{ {7} }} - - # .ForwardHelpTargetName {1} - # .ForwardHelpCategory {5} - # .RemoteHelpRunspace PSSession -}} - "; +" + "\r\n # .ForwardHelpTargetName {1}\r\n # .ForwardHelpCategory {5}\r\n # .RemoteHelpRunspace PSSession\r\n}}\r\n "; private void GenerateCommandProxy(TextWriter writer, CommandMetadata commandMetadata) { @@ -3149,3 +3135,4 @@ function Get-PSImplicitRemotingClientSideParameters } } +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs index a568cd6b8..c2c65f557 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs @@ -294,18 +294,11 @@ namespace Microsoft.PowerShell.Commands } CultureInfo currentCulture = culture; - StringBuilder stringBuilder; string filePath; + string fullFileName = fileName + ".psd1"; while (currentCulture != null && !String.IsNullOrEmpty(currentCulture.Name)) { - stringBuilder = new StringBuilder(dir); - stringBuilder.Append("\\"); - stringBuilder.Append(currentCulture.Name); - stringBuilder.Append("\\"); - stringBuilder.Append(fileName); - stringBuilder.Append(".psd1"); - - filePath = stringBuilder.ToString(); + filePath = Path.Combine(dir, currentCulture.Name, fullFileName); if (File.Exists(filePath)) { @@ -315,12 +308,7 @@ namespace Microsoft.PowerShell.Commands currentCulture = currentCulture.Parent; } - stringBuilder = new StringBuilder(dir); - stringBuilder.Append("\\"); - stringBuilder.Append(fileName); - stringBuilder.Append(".psd1"); - - filePath = stringBuilder.ToString(); + filePath = Path.Combine(dir, fullFileName); if (File.Exists(filePath)) { @@ -330,11 +318,11 @@ namespace Microsoft.PowerShell.Commands InvalidOperationException ioe = PSTraceSource.NewInvalidOperationException( ImportLocalizedDataStrings.CannotFindPsd1File, - fileName + ".psd1", - dir + "\\" + culture.Name + "\\" + fullFileName, + Path.Combine(dir, culture.Name) ); WriteError(new ErrorRecord(ioe, "ImportLocalizedData", ErrorCategory.ObjectNotFound, - dir + "\\" + culture.Name + "\\" + fileName + ".psd1")); + Path.Combine(dir, culture.Name, fullFileName))); return null; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs index 7bc100225..015c7a4e8 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs @@ -548,7 +548,7 @@ namespace Microsoft.PowerShell.Commands // properties... foreach (string p in Property) { - MshExpression expression = new MshExpression(p); + MshExpression expression = new MshExpression(p, true); List resolvedNames = expression.ResolveNames(inObj); if (resolvedNames == null || resolvedNames.Count == 0) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs index 1e691675d..d7aa65d82 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -548,4 +549,5 @@ namespace Microsoft.PowerShell.Commands } #endregion -} \ No newline at end of file +} +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs index 5abd52537..1cd50f686 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs @@ -117,21 +117,28 @@ namespace Microsoft.PowerShell.Commands if ( ShouldProcess( dateToUse.ToString() ) ) { - #pragma warning disable 56523 - - if (!NativeMethods.SetLocalTime(ref systemTime)) + if (Platform.IsWindows()) { - throw new Win32Exception(Marshal.GetLastWin32Error()); - } + #pragma warning disable 56523 - // MSDN says to call this twice to account for changes - // between DST - if (!NativeMethods.SetLocalTime(ref systemTime)) + if (!NativeMethods.SetLocalTime(ref systemTime)) + { + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + + // MSDN says to call this twice to account for changes + // between DST + if (!NativeMethods.SetLocalTime(ref systemTime)) + { + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + + #pragma warning restore 56523 + } + else { - throw new Win32Exception(Marshal.GetLastWin32Error()); + Platform.NonWindowsSetDate(dateToUse); } - - #pragma warning restore 56523 } //output DateTime object wrapped in an PSObject with DisplayHint attached diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs index 2614de1d0..162cfd3ae 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs @@ -1,6 +1,7 @@ -//----------------------------------------------------------------------- +#if !CORECLR +//----------------------------------------------------------------------- // -// Copyright © Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------- namespace Microsoft.PowerShell.Commands @@ -693,3 +694,5 @@ namespace Microsoft.PowerShell.Commands } } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs index 577d805f9..260165cc3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs @@ -1,6 +1,7 @@ -//----------------------------------------------------------------------- +#if !CORECLR +//----------------------------------------------------------------------- // -// Copyright © Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------- namespace Microsoft.PowerShell.Commands.ShowCommandExtension @@ -152,4 +153,5 @@ namespace Microsoft.PowerShell.Commands.ShowCommandExtension /// public ICollection ParameterSets { get; private set; } } -} \ No newline at end of file +} +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs index 81dd4e572..bc028672b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs @@ -1,6 +1,7 @@ +#if !CORECLR //----------------------------------------------------------------------- // -// Copyright © Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------- namespace Microsoft.PowerShell.Commands.ShowCommandExtension @@ -58,4 +59,5 @@ namespace Microsoft.PowerShell.Commands.ShowCommandExtension /// public string Name { get; private set; } } -} \ No newline at end of file +} +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs index 50961f1c0..a5638ae8c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs @@ -1,6 +1,7 @@ +#if !CORECLR //----------------------------------------------------------------------- // -// Copyright © Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------- namespace Microsoft.PowerShell.Commands.ShowCommandExtension @@ -110,4 +111,5 @@ namespace Microsoft.PowerShell.Commands.ShowCommandExtension /// public int Position { get; private set; } } -} \ No newline at end of file +} +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs index 4a61dac7b..0f0be2b54 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs @@ -1,6 +1,7 @@ -//----------------------------------------------------------------------- +#if !CORECLR +//----------------------------------------------------------------------- // -// Copyright © Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------- namespace Microsoft.PowerShell.Commands.ShowCommandExtension @@ -74,4 +75,5 @@ namespace Microsoft.PowerShell.Commands.ShowCommandExtension /// public ICollection Parameters { get; private set; } } -} \ No newline at end of file +} +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs index af40834a2..7ee008bab 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs @@ -1,6 +1,7 @@ -//----------------------------------------------------------------------- +#if !CORECLR +//----------------------------------------------------------------------- // -// Copyright © Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------- namespace Microsoft.PowerShell.Commands.ShowCommandExtension @@ -161,4 +162,5 @@ namespace Microsoft.PowerShell.Commands.ShowCommandExtension /// public ArrayList EnumValues { get; private set; } } -} \ No newline at end of file +} +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandProxy.cs index 3e5acfa98..c3b4b0a2d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandProxy.cs @@ -1,6 +1,7 @@ -//----------------------------------------------------------------------- +#if !CORECLR +//----------------------------------------------------------------------- // -// Copyright © Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------- namespace Microsoft.PowerShell.Commands @@ -195,3 +196,5 @@ namespace Microsoft.PowerShell.Commands } } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/BasicHtmlWebResponseObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/BasicHtmlWebResponseObject.cs index d5b3d1cd8..5d48a73e2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/BasicHtmlWebResponseObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/BasicHtmlWebResponseObject.cs @@ -1,4 +1,5 @@ -/********************************************************************++ +#if !CORECLR +/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -269,3 +270,5 @@ namespace Microsoft.PowerShell.Commands #endregion Methods } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ContentHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ContentHelper.cs index e2b0f76f1..42da7742d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ContentHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ContentHelper.cs @@ -1,4 +1,5 @@ -/********************************************************************++ +#if !CORECLR +/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -206,3 +207,5 @@ namespace Microsoft.PowerShell.Commands #endregion Internal Helper Methods } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/HtmlWebResponseObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/HtmlWebResponseObject.cs index ee5e174a8..6267602de 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/HtmlWebResponseObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/HtmlWebResponseObject.cs @@ -1,4 +1,5 @@ -/********************************************************************++ +#if !CORECLR +/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -550,3 +551,5 @@ namespace Microsoft.PowerShell.Commands } } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/InvokeRestMethodCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/InvokeRestMethodCommand.cs index 31c2748b2..b4765f0ba 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/InvokeRestMethodCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/InvokeRestMethodCommand.cs @@ -1,4 +1,5 @@ -/********************************************************************++ +#if !CORECLR +/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -16,7 +17,7 @@ namespace Microsoft.PowerShell.Commands /// The Invoke-RestMethod command /// This command makes an HTTP or HTTPS request to a web service, /// and returns the response in an appropriate way. - /// Intended to work against the wide spectrum of “RESTful” web services + /// Intended to work against the wide spectrum of "RESTful" web services /// currently deployed across the web. /// [Cmdlet(VerbsLifecycle.Invoke, "RestMethod", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=217034")] @@ -372,3 +373,5 @@ namespace Microsoft.PowerShell.Commands } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/InvokeWebRequestCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/InvokeWebRequestCommand.cs index beb9819c2..37c210882 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/InvokeWebRequestCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/InvokeWebRequestCommand.cs @@ -1,4 +1,5 @@ -/********************************************************************++ +#if !CORECLR +/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -61,3 +62,5 @@ namespace Microsoft.PowerShell.Commands #endregion Virtual Method Overrides } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObjectTypeResolver.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObjectTypeResolver.cs index a279a6df1..070033082 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObjectTypeResolver.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObjectTypeResolver.cs @@ -1,4 +1,5 @@ -/********************************************************************++ +#if !CORECLR +/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -27,3 +28,5 @@ namespace Microsoft.PowerShell.Commands } } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs index e513f1216..4bafc0599 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs @@ -1,4 +1,5 @@ -/********************************************************************++ +#if !CORECLR +/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -174,3 +175,5 @@ namespace Microsoft.PowerShell.Commands } } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs index edd1ff6af..5c7bcd515 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -1,4 +1,5 @@ -/********************************************************************++ +#if !CORECLR +/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -492,3 +493,5 @@ namespace Microsoft.PowerShell.Commands #endregion Static Methods } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestPSCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestPSCmdlet.cs index 041147285..0111bc81d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestPSCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestPSCmdlet.cs @@ -1,4 +1,5 @@ -/********************************************************************++ +#if !CORECLR +/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -1356,3 +1357,5 @@ namespace Microsoft.PowerShell.Commands #endregion private State class } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs index a8a87eeee..c82b71552 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs @@ -1,4 +1,5 @@ -/********************************************************************++ +#if !CORECLR +/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -98,3 +99,5 @@ namespace Microsoft.PowerShell.Commands } } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebResponseHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebResponseHelper.cs index d8afb0a7c..e413d27ce 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebResponseHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebResponseHelper.cs @@ -1,4 +1,5 @@ -/********************************************************************++ +#if !CORECLR +/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -71,3 +72,5 @@ namespace Microsoft.PowerShell.Commands } } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebResponseObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebResponseObject.cs index 7791ad00c..2e896419a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebResponseObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebResponseObject.cs @@ -1,4 +1,5 @@ -/********************************************************************++ +#if !CORECLR +/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -190,3 +191,5 @@ namespace Microsoft.PowerShell.Commands #endregion Methods } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebResponseObjectFactory.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebResponseObjectFactory.cs index e2019ae76..68c791266 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebResponseObjectFactory.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebResponseObjectFactory.cs @@ -1,4 +1,5 @@ -/********************************************************************++ +#if !CORECLR +/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -38,3 +39,5 @@ namespace Microsoft.PowerShell.Commands } } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs index 23a7754fe..1b9283221 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs @@ -170,6 +170,11 @@ namespace Microsoft.PowerShell.Commands // Expected if the host is not interactive, or doesn't have Foreground / Background // colours. } + catch (System.PlatformNotSupportedException) + { + // TODO:PSL Support setting these colors. Expected + // exception on non-windows CoreCLR for now. + } this.WriteInformation(informationMessage, new string[] { "PSHOST" }); this.Host.UI.TranscribeResult(result); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/convert-HTML.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/convert-HTML.cs index c992b38e4..15c6a95d4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/convert-HTML.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/convert-HTML.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -623,3 +624,5 @@ namespace Microsoft.PowerShell.Commands } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs index ce47c25bb..b9ad3e7d4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -59,3 +60,5 @@ namespace Microsoft.PowerShell.Commands } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs index 5cafcba4f..30b6050e9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -144,3 +145,5 @@ namespace Microsoft.PowerShell.Commands } // class PSHostTraceListener } // namespace System.Management.Automation + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs index c6f08afe8..6f6a04450 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -186,3 +187,5 @@ namespace Microsoft.PowerShell.Commands } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceCommandBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceCommandBase.cs index 995754330..e9b13f9a0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceCommandBase.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -134,3 +135,5 @@ namespace Microsoft.PowerShell.Commands } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs index 29e6de6da..3f48f6796 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -573,3 +574,5 @@ namespace Microsoft.PowerShell.Commands } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs index 186f40f97..6af1f02b6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -632,3 +633,5 @@ namespace Microsoft.PowerShell.Commands } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/update-list.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/update-list.cs index 5e8a72a53..2fc2a113f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/update-list.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/update-list.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -214,3 +215,5 @@ namespace Microsoft.PowerShell.Commands } } } + +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs b/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs index 9920e6b9c..c52f0e7a7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -91,3 +92,5 @@ namespace Microsoft.PowerShell } } } + +#endif diff --git a/src/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext/CoreCLR/CorePsAssemblyLoadContext.cs b/src/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext/CoreCLR/CorePsAssemblyLoadContext.cs index c7a51fde0..922565574 100644 --- a/src/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext/CoreCLR/CorePsAssemblyLoadContext.cs +++ b/src/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext/CoreCLR/CorePsAssemblyLoadContext.cs @@ -54,11 +54,6 @@ namespace System.Management.Automation internal PowerShellAssemblyLoadContext(string basePaths) { #region Validation - if (string.IsNullOrEmpty(basePaths)) - { - throw new ArgumentNullException("basePaths"); - } - this.basePaths = basePaths.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < this.basePaths.Length; i++) { @@ -189,9 +184,19 @@ namespace System.Management.Automation assemblyName.FullName); } - asmLoaded = asmFilePath.EndsWith(".ni.dll", StringComparison.OrdinalIgnoreCase) - ? LoadFromNativeImagePath(asmFilePath, null) - : LoadFromAssemblyPath(asmFilePath); + // Try loading it from the TPA list. All PowerShell dependencies are in the + // TPA list when published with dotnet-cli. + asmLoaded = Assembly.Load(assemblyName); + + // If it wasn't there, try loading from path + if (asmLoaded == null) + { + asmLoaded = asmFilePath.EndsWith(".ni.dll", StringComparison.OrdinalIgnoreCase) + ? LoadFromNativeImagePath(asmFilePath, null) + : LoadFromAssemblyPath(asmFilePath); + } + + // If it loaded, add it to the cache if (asmLoaded != null) { // Add the loaded assembly to the cache @@ -243,10 +248,17 @@ namespace System.Management.Automation if (TryGetAssemblyFromCache(assemblyName, out asmLoaded)) return asmLoaded; - // Load the assembly through 'LoadFromNativeImagePath' or 'LoadFromAssemblyPath' - asmLoaded = assemblyPath.EndsWith(".ni.dll", StringComparison.OrdinalIgnoreCase) - ? LoadFromNativeImagePath(assemblyPath, null) - : LoadFromAssemblyPath(assemblyPath); + // Try loading it from the TPA list. All PowerShell dependencies are in the + // TPA list when published with dotnet-cli. + asmLoaded = Assembly.Load(assemblyName); + + if (asmLoaded == null) + { + // Load the assembly through 'LoadFromNativeImagePath' or 'LoadFromAssemblyPath' + asmLoaded = assemblyPath.EndsWith(".ni.dll", StringComparison.OrdinalIgnoreCase) + ? LoadFromNativeImagePath(assemblyPath, null) + : LoadFromAssemblyPath(assemblyPath); + } if (asmLoaded != null) { @@ -484,16 +496,20 @@ namespace System.Management.Automation { private static bool IsInitialized = false; + // Porting note: it's much easier to send an LPStr on Linux + private const UnmanagedType stringType = +#if LINUX + UnmanagedType.LPStr +#else + UnmanagedType.LPWStr +#endif + ; + /// /// Set the default Assembly Load Context /// - public static void SetPowerShellAssemblyLoadContext([MarshalAs(UnmanagedType.LPWStr)]string basePaths) + public static void SetPowerShellAssemblyLoadContext([MarshalAs(stringType)]string basePaths) { - if (string.IsNullOrEmpty(basePaths)) - { - throw new ArgumentNullException("basePaths"); - } - if (!IsInitialized) { var psAsmLoadContext = new PowerShellAssemblyLoadContext(basePaths); diff --git a/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs b/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs index e40496766..994cb634b 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -239,3 +240,5 @@ namespace Microsoft.PowerShell.Commands } } + +#endif diff --git a/src/Microsoft.PowerShell.Security/security/CmsCommands.cs b/src/Microsoft.PowerShell.Security/security/CmsCommands.cs index 48df4fc3c..0fce7622f 100644 --- a/src/Microsoft.PowerShell.Security/security/CmsCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CmsCommands.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -587,3 +588,5 @@ namespace Microsoft.PowerShell.Commands } } + +#endif diff --git a/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs b/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs index ca07bc89a..2721d2d6f 100644 --- a/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs +++ b/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -91,3 +92,5 @@ namespace Microsoft.PowerShell } } } + +#endif diff --git a/src/System.Management.Automation/CoreCLR/CorePsExtensions.cs b/src/System.Management.Automation/CoreCLR/CorePsExtensions.cs index fee97847a..f6fb21d0b 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsExtensions.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsExtensions.cs @@ -1,3 +1,4 @@ +#if CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -825,7 +826,37 @@ namespace System.Management.Automation public static string GetEnvironmentVariable(string variable) { - return System.Environment.GetEnvironmentVariable(variable); + string value = System.Environment.GetEnvironmentVariable(variable); + + // Porting note: if not otherwise defined, map Windows environment + // variables to their corresponding Linux counterparts + if (Platform.IsLinux() && String.IsNullOrEmpty(value)) + { + switch (variable) + { + case "OS": + return "Linux"; + + case "COMPUTERNAME": + return System.Environment.GetEnvironmentVariable("HOSTNAME"); + + case "USERNAME": + return System.Environment.GetEnvironmentVariable("USER"); + + case "HOMEPATH": + case "USERPROFILE": + return System.Environment.GetEnvironmentVariable("HOME"); + + case "TMP": + case "TEMP": + return System.Environment.GetEnvironmentVariable("TMPDIR"); + + default: + break; + } + } + + return value; } public static IDictionary GetEnvironmentVariables() @@ -863,6 +894,13 @@ namespace System.Management.Automation { return GetEnvironmentVariables(); } + + if (!Platform.HasRegistrySupport()) + { + // Porting note: Does not throw a PlatformUnsupported because + // GetEnvironmentVariable cannot throw, and we want the same interface. + return null; + } if( target == EnvironmentVariableTarget.Machine) { @@ -920,6 +958,14 @@ namespace System.Management.Automation return System.Environment.GetEnvironmentVariable(variable); } + if (!Platform.HasRegistrySupport()) + { + // Porting note: This cannot throw since it would otherwise throw while + // creating a runspace. Returning null is appropriate to signal that there + // is no value for a registry key with no registry. + return null; + } + if (target == EnvironmentVariableTarget.Machine) { using (RegistryKey environmentKey = @@ -947,6 +993,31 @@ namespace System.Management.Automation #region Property_Extensions + internal static string WinGetUserDomainName() + { + StringBuilder domainName = new StringBuilder(1024); + uint domainNameLen = (uint)domainName.Capacity; + + byte ret = Win32Native.GetUserNameEx(Win32Native.NameSamCompatible, domainName, ref domainNameLen); + if (ret == 1) + { + string samName = domainName.ToString(); + int index = samName.IndexOf('\\'); + if (index != -1) + { + return samName.Substring(0, index); + } + } + else + { + int errorCode = Marshal.GetLastWin32Error(); + throw new InvalidOperationException(Win32Native.GetMessage(errorCode)); + } + + // Cannot use LookupAccountNameW to get DomainName because 'GetUserName' is not available in CSS and thus we cannot get the account. + throw new InvalidOperationException(CoreClrStubResources.CannotGetDomainName); + } + /// /// UserDomainName /// @@ -954,29 +1025,34 @@ namespace System.Management.Automation { get { - StringBuilder domainName = new StringBuilder(1024); - uint domainNameLen = (uint)domainName.Capacity; - - byte ret = Win32Native.GetUserNameEx(Win32Native.NameSamCompatible, domainName, ref domainNameLen); - if (ret == 1) + if (Platform.IsWindows()) { - string samName = domainName.ToString(); - int index = samName.IndexOf('\\'); - if (index != -1) - { - return samName.Substring(0, index); - } + return WinGetUserDomainName(); } else { - int errorCode = Marshal.GetLastWin32Error(); - throw new InvalidOperationException(Win32Native.GetMessage(errorCode)); + return Platform.NonWindowsGetDomainName(); } - - // Cannot use LookupAccountNameW to get DomainName because 'GetUserName' is not available in CSS and thus we cannot get the account. - throw new InvalidOperationException(CoreClrStubResources.CannotGetDomainName); } } + + internal static string WinGetUserName() + { + StringBuilder domainName = new StringBuilder(1024); + uint domainNameLen = (uint)domainName.Capacity; + + byte ret = Win32Native.GetUserNameEx(Win32Native.NameSamCompatible, domainName, ref domainNameLen); + if (ret == 1) + { + string samName = domainName.ToString(); + int index = samName.IndexOf('\\'); + if (index != -1) + { + return samName.Substring(index + 1); + } + } + return string.Empty; + } /// /// UserName @@ -985,23 +1061,28 @@ namespace System.Management.Automation { get { - StringBuilder domainName = new StringBuilder(1024); - uint domainNameLen = (uint)domainName.Capacity; - - byte ret = Win32Native.GetUserNameEx(Win32Native.NameSamCompatible, domainName, ref domainNameLen); - if (ret == 1) + if (Platform.IsWindows()) { - string samName = domainName.ToString(); - int index = samName.IndexOf('\\'); - if (index != -1) - { - return samName.Substring(index + 1); - } + return WinGetUserName(); + } + else + { + return Platform.NonWindowsGetUserName(); } - return string.Empty; } } + internal static string WinGetMachineName() + { + // In future release of operating systems, you might be able to rename a machine without + // rebooting. Therefore, don't cache this machine name. + StringBuilder buf = new StringBuilder(MaxMachineNameLength); + int len = MaxMachineNameLength; + if (Win32Native.GetComputerName(buf, ref len) == 0) + throw new InvalidOperationException(CoreClrStubResources.CannotGetComputerName); + return buf.ToString(); + } + /// /// MachineName /// @@ -1009,13 +1090,14 @@ namespace System.Management.Automation { get { - // In future release of operating systems, you might be able to rename a machine without - // rebooting. Therefore, don't cache this machine name. - StringBuilder buf = new StringBuilder(MaxMachineNameLength); - int len = MaxMachineNameLength; - if (Win32Native.GetComputerName(buf, ref len) == 0) - throw new InvalidOperationException(CoreClrStubResources.CannotGetComputerName); - return buf.ToString(); + if (Platform.IsWindows()) + { + return WinGetMachineName(); + } + else + { + return Platform.NonWindowsGetMachineName(); + } } } @@ -1028,22 +1110,45 @@ namespace System.Management.Automation { if (m_os == null) { - Win32Native.OSVERSIONINFOEX osviex = new Win32Native.OSVERSIONINFOEX(); - osviex.OSVersionInfoSize = Marshal.SizeOf(osviex); - if (!Win32Native.GetVersionEx(ref osviex)) + if (Platform.IsWindows()) { - int errorCode = Marshal.GetLastWin32Error(); - throw new Win32Exception(errorCode); + m_os = WinOSVersion; } + else + { + // TODO:PSL use P/Invoke to provide proper version - Version v = new Version(osviex.MajorVersion, osviex.MinorVersion, osviex.BuildNumber, (osviex.ServicePackMajor << 16) | osviex.ServicePackMinor); - m_os = new OperatingSystem(v, osviex.CSDVersion); + // Porting note: cannot put this in CorePsPlatform since + // System.Management.Automation.Environment only exists in CoreCLR + // builds of monad. + m_os = new Environment.OperatingSystem(new Version(1,0,0,0),""); + } } return m_os; } } private static volatile OperatingSystem m_os; + /// + /// Windows OSVersion implementation + /// + private static OperatingSystem WinOSVersion + { + get + { + Win32Native.OSVERSIONINFOEX osviex = new Win32Native.OSVERSIONINFOEX(); + osviex.OSVersionInfoSize = Marshal.SizeOf(osviex); + if (!Win32Native.GetVersionEx(ref osviex)) + { + int errorCode = Marshal.GetLastWin32Error(); + throw new Win32Exception(errorCode); + } + + Version v = new Version(osviex.MajorVersion, osviex.MinorVersion, osviex.BuildNumber, (osviex.ServicePackMajor << 16) | osviex.ServicePackMinor); + return new OperatingSystem(v, osviex.CSDVersion); + } + } + //TODO:CORECLR Need to decide what to do with 'requestedClrVersion' and 'requestedDotNetFrameworkVersion' in ModuleCmdletBase.cs [LoadModuleManifest] public static Version Version { @@ -1076,6 +1181,11 @@ namespace System.Management.Automation /// private static string InternalGetFolderPath(SpecialFolder folder) { + if (!Platform.IsWindows()) + { + return Platform.NonWindowsGetFolderPath(folder); + } + // The API 'SHGetFolderPath' is not available on OneCore, so we have to rely on environment variables string folderPath = null; string systemRoot = null; @@ -1156,7 +1266,7 @@ namespace System.Management.Automation /// DllImport uses the ApiSet dll that is available on CSS, since this code /// will only be included when building targeting CoreCLR. /// - private static class Win32Native + internal static class Win32Native { internal const int NameSamCompatible = 2; // EXTENDED_NAME_FORMAT - NameSamCompatible @@ -1223,13 +1333,17 @@ namespace System.Management.Automation #region NestedTypes + // Porting note: MyDocuments does not exist on .NET Core, but Personal does, and + // they both point to your "documents repository," which on linux, is just the + // home directory. + /// /// It only contains the values that get used in powershell /// internal enum SpecialFolder { - MyDocuments = 5, - Personal = 5, + Personal = 0x05, + MyDocuments = 0x05, LocalApplicationData = 0x1c, ProgramFiles = 0x26, ProgramFilesX86 = 0x2a, @@ -1565,3 +1679,5 @@ namespace Microsoft.PowerShell.CoreCLR } #endif + +#endif diff --git a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs new file mode 100644 index 000000000..51fc33d68 --- /dev/null +++ b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs @@ -0,0 +1,719 @@ +/********************************************************************++ +Copyright (c) Microsoft Corporation. All rights reserved. +--********************************************************************/ + +using System.Globalization; +using System.Linq; +using System.Reflection; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Microsoft.Win32; +using Microsoft.Win32.SafeHandles; +using System.IO; + +#if CORECLR +// SMA.Environment is only available on CoreCLR +using SpecialFolder = System.Management.Automation.Environment.SpecialFolder; +#endif + +namespace System.Management.Automation +{ + + /// + /// These are platform abstractions and platform specific implementations + /// + /// All these properties are calling into platform specific static classes, to make + /// sure the platform implementations are switched at runtime (including pinvokes). + /// + internal static class Platform + { + // this queries specifically for Linux or OS X because they are very similar + internal static bool IsLinux() + { +#if CORECLR + return RuntimeInformation.IsOSPlatform(OSPlatform.Linux) + || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); +#else + // FullCLR doesn't have a Linux version + return false; +#endif + } + + // this is specifically to query for Windows, everything else is considered to be non-Windows + internal static bool IsWindows() + { +#if CORECLR + return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); +#else + // FullCLR has only Windows version + return true; +#endif + } + + // true if cross-platform (always for this project) + internal static bool IsX() + { +#if CORECLR + // CoreCLR version is cross-platform + return true; +#else + // FullCLR is not cross-platform + return false; +#endif + } + + // format files + internal static List FormatFileNames = new List + { + "Certificate.format.ps1xml", + "Diagnostics.format.ps1xml", + "DotNetTypes.format.ps1xml", + "Event.format.ps1xml", + "FileSystem.format.ps1xml", + "Help.format.ps1xml", + "HelpV3.format.ps1xml", + "PowerShellCore.format.ps1xml", + "PowerShellTrace.format.ps1xml", + "Registry.format.ps1xml", + "WSMan.format.ps1xml" + }; + + // directory location of PowerShell for profile loading + public static string ProductNameForDirectory = ".powershell"; + + // ComObjectType is null on CoreCLR for Linux since there is + // no COM support on Linux + internal static bool HasCom() + { + // TODO: catch exception from Type.IsComObject + return IsWindows(); + } + + // The Antimalware Scan Interface is not supported on Linux + internal static bool HasAmsi() + { + return IsWindows(); + } + + internal static bool UsesCodeSignedAssemblies() + { + return !Platform.IsX(); + } + + // This is mainly with respect to the auto-mounting of + // disconnected network drives on Windows + internal static bool HasDriveAutoMounting() + { + return IsWindows(); + } + + // Linux does not have a registry + internal static bool HasRegistrySupport() + { + return IsWindows(); + } + + // Linux does not have PowerShell execution policies + internal static bool HasExecutionPolicy() + { + return IsWindows(); + } + + // Linux has a single rooted file system + internal static bool HasSingleRootFilesystem() + { + return !IsWindows(); + } + + // Linux has no notion of file shares. It has mount points + // instead, which are subdirectories of its single-root + // filesystem. + internal static bool HasFileShares() + { + return !HasSingleRootFilesystem(); + } + + // Linux has no support for UNC, just mounts in a single rooted hierarchy + // the UNC equivalent of a "network drive" aka mount would be the mount itself + internal static bool HasUNCSupport() + { + return IsWindows(); + } + + // Linux uses .net to query file attributes + internal static bool UseDotNetToQueryFileAttributes() + { + return true; + } + + // Linux does not have group policy support + internal static bool HasGroupPolicySupport() + { + return IsWindows(); + } + + // non-windows does not have network drive support + internal static bool HasNetworkDriveSupport() + { + return IsWindows(); + } + + // non-windows does not have reparse points + internal static bool SupportsReparsePoints() + { + return IsWindows(); + } + + // non-windows does not support removing drives + internal static bool SupportsRemoveDrive() + { + return IsWindows(); + } + + // Platform methods prefixed NonWindows are: + // - non-windows by the definition of the IsWindows method above + // - here, because porting to Linux and other operating systems + // should not move the original Windows code out of the module + // it belongs to, so this way the windows code can remain in it's + // original source file and only the non-windows code has been moved + // out here + // - only to be used with the IsWindows feature query, and only if + // no other more specific feature query makes sense + + internal static bool NonWindowsIsHardLink(ref IntPtr handle) + { + return LinuxPlatform.IsHardLink(ref handle); + } + + internal static bool NonWindowsIsHardLink(FileSystemInfo fileInfo) + { + if (IsLinux()) + { + return LinuxPlatform.IsHardLink(fileInfo); + } + + throw new PlatformNotSupportedException(); + } + + internal static bool NonWindowsIsSymLink(FileSystemInfo fileInfo) + { + if (IsLinux()) + { + return LinuxPlatform.IsSymLink(fileInfo); + } + + throw new PlatformNotSupportedException(); + } + + internal static string NonWindowsInternalGetTarget(SafeFileHandle handle) + { + // SafeHandle is a Windows concept. Use the string version instead. + throw new PlatformNotSupportedException(); + } + + internal static string NonWindowsInternalGetTarget(string path) + { + if (IsLinux()) + { + return LinuxPlatform.FollowSymLink(path); + } + else + { + throw new PlatformNotSupportedException(); + } + } + +#if CORECLR + internal static string NonWindowsGetFolderPath(SpecialFolder folder) + { + if (IsLinux()) + { + return LinuxPlatform.GetFolderPath(folder); + } + else + { + throw new PlatformNotSupportedException(); + } + } +#endif + + internal static string NonWindowsInternalGetLinkType(FileSystemInfo fileInfo) + { + if (IsLinux()) + { + if (NonWindowsIsSymLink(fileInfo)) + { + return "SymbolicLink"; + } + if (NonWindowsIsHardLink(fileInfo)) + { + return "HardLink"; + } + return null; + } + else + { + throw new PlatformNotSupportedException(); + } + + } + + internal static bool NonWindowsCreateSymbolicLink(string path, string strTargetPath, bool isDirectory) + { + if (IsLinux()) + { + // Linux doesn't care if target is a directory or not + return LinuxPlatform.CreateSymbolicLink(path, strTargetPath); + } + else + { + throw new PlatformNotSupportedException(); + } + } + + internal static bool NonWindowsCreateHardLink(string path, string strTargetPath) + { + if (IsLinux()) + { + return LinuxPlatform.CreateHardLink(path, strTargetPath); + } + else + { + throw new PlatformNotSupportedException(); + } + } + + internal static void NonWindowsSetDate(DateTime dateToUse) + { + if (IsLinux()) + { + LinuxPlatform.SetDateInfoInternal date = new LinuxPlatform.SetDateInfoInternal(dateToUse); + LinuxPlatform.SetDate(date); + } + else + { + throw new PlatformNotSupportedException(); + } + } + + internal static string NonWindowsGetDomainName() + { + if (IsLinux()) + { + string fullyQualifiedName = LinuxPlatform.Native.GetFullyQualifiedName(); + if (string.IsNullOrEmpty(fullyQualifiedName)) + { + int lastError = Marshal.GetLastWin32Error(); + throw new InvalidOperationException("LinuxPlatform.NonWindowsGetDomainName error: " + lastError); + } + + int index = fullyQualifiedName.IndexOf('.'); + if (index >= 0) + { + return fullyQualifiedName.Substring(index + 1); + } + + return ""; + } + else + { + throw new PlatformNotSupportedException(); + } + } + + internal static string NonWindowsGetUserName() + { + if (IsLinux()) + { + return LinuxPlatform.UserName; + } + else + { + throw new PlatformNotSupportedException(); + } + } + + internal static string NonWindowsGetMachineName() + { + if (IsLinux()) + { + return LinuxPlatform.HostName; + } + else + { + throw new PlatformNotSupportedException(); + } + } + + // Hostname in this context seems to be the FQDN + internal static string NonWindowsGetHostName() + { + if (IsLinux()) + { + string hostName = LinuxPlatform.Native.GetFullyQualifiedName(); + if (string.IsNullOrEmpty(hostName)) + { + int lastError = Marshal.GetLastWin32Error(); + throw new InvalidOperationException("LinuxPlatform.NonWindowsHostName error: " + lastError); + } + return hostName; + + } + else + { + throw new PlatformNotSupportedException(); + } + } + + internal static bool NonWindowsIsExecutable(string path) + { + if (IsLinux()) + { + return LinuxPlatform.IsExecutable(path); + } + + throw new PlatformNotSupportedException(); + } + + internal static uint NonWindowsGetThreadId() + { + // TODO:PSL clean this up + return 0; + } + + /// + /// This exception is meant to be thrown if a code path is not supported due + /// to platform restrictions + /// + internal class PlatformNotSupportedException : System.Exception + { + public PlatformNotSupportedException() : base() {} + } + + /// + /// This models the native call CommandLineToArgvW in managed code. + /// + public static string[] CommandLineToArgv(string command) + { + StringBuilder arguments = new StringBuilder(); + int len = command.Length; + IList returnList = new List(); + bool inquote = false; + char current = '\0'; + + for (int argIndex = 0; argIndex < len; argIndex++) + { + current = command[argIndex]; + + if (current.Equals('"')) + { + // Treat anything in quotes as a single argument + // Because C# treats quotes differently than C++, instead of counting the slashes + // it makes more sense to count the quotes. + inquote = !inquote; + arguments.Append('"'); + continue; + } + + // If we're inside a quote, add the current character and cycle through + if (inquote && !current.Equals('"')) + { + arguments.Append(current.ToString()); + continue; + } + + if (current.Equals("\\")) + { + arguments.Append("\\"); + continue; + } + + if (string.IsNullOrWhiteSpace(current.ToString())) + { + if (arguments.Length > 0) + { + returnList.Add(arguments.ToString()); + arguments.Clear(); + } + continue; + } + + // All other exclusion scenarios being exhausted, append the current character. + arguments.Append(current.ToString()); + } + + // add the final object to the arguments list + returnList.Add(arguments.ToString()); + arguments.Clear(); + + return returnList.ToArray(); + } + } + + internal static class LinuxPlatform + { + public static string HostName + { + get + { + StringBuilder value = new StringBuilder(1024); + uint valueLen = (uint)value.Capacity; + string computerName = Native.GetComputerName(); + if (string.IsNullOrEmpty(computerName)) + { + int lastError = Marshal.GetLastWin32Error(); + throw new InvalidOperationException("LinuxPlatform.HostName error: " + lastError); + } + return computerName; + } + } + + private static string _userName; + public static string UserName + { + get + { + if (string.IsNullOrEmpty(_userName)) + { + _userName = Native.GetUserName(); + if (string.IsNullOrEmpty(_userName)) + { + int lastError = Marshal.GetLastWin32Error(); + throw new InvalidOperationException("LinuxPlatform.UserName error: " + lastError); + } + } + return _userName; + } + } + + public static string TemporaryDirectory + { + get + { + // POSIX temporary directory environment variables + string[] environmentVariables = { "TMPDIR", "TMP", "TEMP", "TEMPDIR" }; + string dir = string.Empty; + foreach (string s in environmentVariables) + { + dir = System.Environment.GetEnvironmentVariable(s); + if (!string.IsNullOrEmpty(dir)) + { + return dir; + } + } + return "/tmp"; + } + } + +#if CORECLR + public static string GetFolderPath(SpecialFolder folder) + { + string s = null; + switch (folder) + { + case SpecialFolder.ProgramFiles: + s = "/bin"; + break; + case SpecialFolder.ProgramFilesX86: + s = "/usr/bin"; + break; + case SpecialFolder.System: + s = "/sbin"; + break; + case SpecialFolder.SystemX86: + s = "/sbin"; + break; + case SpecialFolder.Personal: + s = System.Environment.GetEnvironmentVariable("HOME"); + break; + case SpecialFolder.LocalApplicationData: + s = System.IO.Path.Combine(System.Environment.GetEnvironmentVariable("HOME"), ".config"); + if (!System.IO.Directory.Exists(s)) + { + System.IO.Directory.CreateDirectory(s); + } + break; + default: + throw new NotSupportedException(); + } + return s; + } +#endif + + public static bool IsHardLink(ref IntPtr handle) + { + // TODO:PSL implement using fstat to query inode refcount to see if it is a hard link + return false; + } + + + public static bool IsHardLink(FileSystemInfo fs) + { + if (!fs.Exists || (fs.Attributes & FileAttributes.Directory) == FileAttributes.Directory) + { + return false; + } + + int count; + string filePath = fs.FullName; + int ret = Native.GetLinkCount(filePath, out count); + if (ret == 1) + { + return count > 1; + } + else + { + int lastError = Marshal.GetLastWin32Error(); + throw new InvalidOperationException("LinuxPlatform.IsHardLink error: " + lastError); + } + + } + + public static bool IsSymLink(FileSystemInfo fs) + { + if (!fs.Exists) + { + return false; + } + + string filePath = fs.FullName; + int ret = Native.IsSymLink(filePath); + switch(ret) + { + case 1: + return true; + case 0: + return false; + default: + int lastError = Marshal.GetLastWin32Error(); + throw new InvalidOperationException("LinuxPlatform.IsSymLink error: " + lastError); + } + } + + public static bool IsExecutable(string filePath) + { + if (!File.Exists(filePath)) + { + return false; + } + + int ret = Native.IsExecutable(filePath); + switch(ret) + { + case 1: + return true; + case 0: + return false; + default: + int lastError = Marshal.GetLastWin32Error(); + throw new InvalidOperationException("LinuxPlatform.IsExecutable error: " + lastError); + } + } + + public static void SetDate(SetDateInfoInternal info) + { + int ret = Native.SetDate(info); + if (ret == -1) + { + int lastError = Marshal.GetLastWin32Error(); + throw new InvalidOperationException("LinuxPlatform.NonWindowsSetDate error: " + lastError); + } + } + + public static bool CreateSymbolicLink(string path, string strTargetPath) + { + int ret = Native.CreateSymLink(path, strTargetPath); + return ret == 1 ? true : false; + } + + public static bool CreateHardLink(string path, string strTargetPath) + { + int ret = Native.CreateHardLink(path, strTargetPath); + return ret == 1 ? true : false; + } + + public static string FollowSymLink(string path) + { + return Native.FollowSymLink(path); + } + + [StructLayout(LayoutKind.Sequential)] + internal class SetDateInfoInternal + { + public int Year; + public int Month; + public int Day; + public int Hour; + public int Minute; + public int Second; + public int Millisecond; + public int DST; + + public SetDateInfoInternal(DateTime d) + { + Year = d.Year; + Month = d.Month; + Day = d.Day; + Hour = d.Hour; + Minute = d.Minute; + Second = d.Second; + Millisecond = d.Millisecond; + DST = d.IsDaylightSavingTime() ? 1 : 0; + } + + public override string ToString() + { + string ret = String.Format("Year = {0}; Month = {1}; Day = {2}; Hour = {3}; Minute = {4}; Second = {5}; Millisec = {6}; DST = {7}", Year, Month, Day, Hour, Minute, Second, Millisecond, DST); + return ret; + } + } + + internal static class Native + { + const string psLib = "libpsl-native"; + + // Ansi is a misnomer, it is hardcoded to UTF-8 on Linux and OS X + + [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] + [return: MarshalAs(UnmanagedType.LPStr)] + internal static extern string GetUserName(); + + [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] + [return: MarshalAs(UnmanagedType.LPStr)] + internal static extern string GetComputerName(); + + [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] + internal static extern int GetLinkCount([MarshalAs(UnmanagedType.LPStr)]string filePath, out int linkCount); + + [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] + internal static extern int IsSymLink([MarshalAs(UnmanagedType.LPStr)]string filePath); + + [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] + internal static extern int IsExecutable([MarshalAs(UnmanagedType.LPStr)]string filePath); + + [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] + [return: MarshalAs(UnmanagedType.LPStr)] + internal static extern string GetFullyQualifiedName(); + + [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] + internal static extern int SetDate(SetDateInfoInternal info); + + [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] + internal static extern int CreateSymLink([MarshalAs(UnmanagedType.LPStr)]string filePath, + [MarshalAs(UnmanagedType.LPStr)]string target); + + [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] + internal static extern int CreateHardLink([MarshalAs(UnmanagedType.LPStr)]string filePath, + [MarshalAs(UnmanagedType.LPStr)]string target); + + [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] + [return: MarshalAs(UnmanagedType.LPStr)] + internal static extern string FollowSymLink([MarshalAs(UnmanagedType.LPStr)]string filePath); + + } + } + +} // namespace System.Management.Automation diff --git a/src/System.Management.Automation/CoreCLR/CorePsStub.cs b/src/System.Management.Automation/CoreCLR/CorePsStub.cs index 0269705b5..e17511684 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsStub.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsStub.cs @@ -1,3 +1,4 @@ +#if CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -632,23 +633,6 @@ namespace System } } -// There is no plan to support DataTable in ProjectK -namespace System.Data -{ - internal class DataTable - { - internal DataRowCollection Rows { get; set; } - } - - internal sealed class DataRowCollection : IEnumerable - { - public IEnumerator GetEnumerator() - { - throw new NotImplementedException("You are calling into the stub for 'DataRowCollection.GetEnumerator()'. It's not implemented."); - } - } -} - namespace System.Net { internal class WebClient //: Component @@ -1426,6 +1410,351 @@ namespace System.Management.Automation.Security } } + +#if NOETW || LINUX + +// Porting note: Tracing is absolutely not available on Linux +namespace System.Management.Automation.Tracing +{ + using System.Management.Automation.Internal; + + /// + /// + /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] + public abstract class EtwActivity + { + /// + /// + /// + /// + /// + public static bool SetActivityId(Guid activityId) + { + return false; + } + + /// + /// + /// + /// + public static Guid CreateActivityId() + { + return Guid.Empty; + } + + /// + /// + /// + /// + public static Guid GetActivityId() + { + return Guid.Empty; + } + } + + internal static class PSEtwLog + { + static internal void LogAnalyticError(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { } + static internal void LogAnalyticWarning(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { } + static internal void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, + Int64 objectId, + Int64 fragmentId, + int isStartFragment, + int isEndFragment, + UInt32 fragmentLength, + PSETWBinaryBlob fragmentData) + { } + static internal void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { } + static internal void SetActivityIdForCurrentThread(Guid newActivityId) { } + static internal void LogOperationalVerbose(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args){ } + static internal void LogOperationalWarning(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args){ } + static internal void ReplaceActivityIdForCurrentThread(Guid newActivityId, PSEventId eventForOperationalChannel, PSEventId eventForAnalyticChannel, PSKeyword keyword, PSTask task) { } + static internal void LogOperationalError(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { } + static internal void LogOperationalError(PSEventId id, PSOpcode opcode, PSTask task, LogContext logContext, string payLoad) { } + static internal void LogAnalyticInformational(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args){ } + static internal void LogOperationalInformation(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args){ } + } + + public enum PowerShellTraceTask + { + /// + /// None + /// + None = 0, + + /// + /// CreateRunspace + /// + CreateRunspace = 1, + + /// + /// ExecuteCommand + /// + ExecuteCommand = 2, + + /// + /// Serialization + /// + Serialization = 3, + + /// + /// PowerShellConsoleStartup + /// + PowerShellConsoleStartup = 4, + } + + /// + /// Defines Keywords. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1028")] + [Flags] + public enum PowerShellTraceKeywords : ulong + { + /// + /// None + /// + None = 0, + + /// + /// Runspace + /// + Runspace = 0x1, + + /// + /// Pipeline + /// + Pipeline = 0x2, + + /// + /// Protocol + /// + Protocol = 0x4, + + /// + /// Transport + /// + Transport = 0x8, + + /// + /// Host + /// + Host = 0x10, + + /// + /// Cmdlets + /// + Cmdlets = 0x20, + + /// + /// Serializer + /// + Serializer = 0x40, + + /// + /// Session + /// + Session = 0x80, + + /// + /// ManagedPlugIn + /// + ManagedPlugIn = 0x100, + + /// + /// + /// + UseAlwaysDebug = 0x2000000000000000, + + /// + /// + /// + UseAlwaysOperational = 0x8000000000000000, + + /// + /// + /// + UseAlwaysAnalytic = 0x4000000000000000, + } + + public sealed partial class Tracer : System.Management.Automation.Tracing.EtwActivity + { + static Tracer() {} + + public void EndpointRegistered(string endpointName, string endpointType, string registeredBy) + { + } + + public void EndpointUnregistered(string endpointName, string unregisteredBy) + { + } + + public void EndpointDisabled(string endpointName, string disabledBy) + { + } + + public void EndpointEnabled(string endpointName, string enabledBy) + { + } + + public void EndpointModified(string endpointName, string modifiedBy) + { + } + + public void BeginContainerParentJobExecution(Guid containerParentJobInstanceId) + { + } + + public void BeginProxyJobExecution(Guid proxyJobInstanceId) + { + } + + public void ProxyJobRemoteJobAssociation(Guid proxyJobInstanceId, Guid containerParentJobInstanceId) + { + } + + public void EndProxyJobExecution(Guid proxyJobInstanceId) + { + } + + public void BeginProxyJobEventHandler(Guid proxyJobInstanceId) + { + } + + public void EndProxyJobEventHandler(Guid proxyJobInstanceId) + { + } + + public void BeginProxyChildJobEventHandler(Guid proxyChildJobInstanceId) + { + } + + public void EndContainerParentJobExecution(Guid containerParentJobInstanceId) + { + } + } + + public sealed class PowerShellTraceSource : IDisposable + { + internal PowerShellTraceSource(PowerShellTraceTask task, PowerShellTraceKeywords keywords) + { + } + + public void Dispose() + { + } + + public bool WriteMessage(String message) + { + return false; + } + + /// + /// + /// + /// + /// + /// + public bool WriteMessage(string message1, string message2) + { + return false; + } + + /// + /// + /// + /// + /// + /// + public bool WriteMessage(string message, Guid instanceId) + { + return false; + } + + + /// + /// + /// + /// + /// + /// + /// + /// + /// + public void WriteMessage(string className, string methodName, Guid workflowId, string message, params string[] parameters) + { + return ; + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public void WriteMessage(string className, string methodName, Guid workflowId, Job job, string message, params string[] parameters) + { + return; + } + + public bool TraceException(Exception exception) + { + return false; + } + } + + /// + /// TraceSourceFactory will return an instance of TraceSource every time GetTraceSource method is called. + /// + public static class PowerShellTraceSourceFactory + { + /// + /// Returns an instance of BaseChannelWriter. + /// If the Etw is not supported by the platform it will return NullWriter.Instance + /// + /// A Task and a set of Keywords can be specified in the GetTraceSource method (See overloads). + /// The supplied task and keywords are used to pass to the Etw provider in case they are + /// not defined in the manifest file. + /// + public static PowerShellTraceSource GetTraceSource() + { + return new PowerShellTraceSource(PowerShellTraceTask.None, PowerShellTraceKeywords.None); + } + + /// + /// Returns an instance of BaseChannelWriter. + /// If the Etw is not supported by the platform it will return NullWriter.Instance + /// + /// A Task and a set of Keywords can be specified in the GetTraceSource method (See overloads). + /// The supplied task and keywords are used to pass to the Etw provider in case they are + /// not defined in the manifest file. + /// + public static PowerShellTraceSource GetTraceSource(PowerShellTraceTask task) + { + return new PowerShellTraceSource(task, PowerShellTraceKeywords.None); + } + + /// + /// Returns an instance of BaseChannelWriter. + /// If the Etw is not supported by the platform it will return NullWriter.Instance + /// + /// A Task and a set of Keywords can be specified in the GetTraceSource method (See overloads). + /// The supplied task and keywords are used to pass to the Etw provider in case they are + /// not defined in the manifest file. + /// + public static PowerShellTraceSource GetTraceSource(PowerShellTraceTask task, PowerShellTraceKeywords keywords) + { + return new PowerShellTraceSource(task, keywords); + } + } +} + +#endif + namespace Microsoft.PowerShell.Commands { using System.Management.Automation; @@ -1545,3 +1874,5 @@ namespace System #pragma warning restore 1591, 1572, 1571, 1573, 1587, 1570, 0067 #endif + +#endif diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs index a32b560d8..1a24c5bac 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs @@ -1,4 +1,5 @@ -// THIS FILE IS MANUALLY CHANGED BASED ON THE GENERATED FILE +#if CORECLR +// THIS FILE IS MANUALLY CHANGED BASED ON THE GENERATED FILE // // The original file has been generated by admin\monad\src\cimSupport\cmdletization\xml\generate.ps1 // based on the following input file: d:\bluedev\admin\monad\src\cimSupport\cmdletization\xml\cmdlets-over-objects.xsd @@ -1725,3 +1726,5 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { } #endif + +#endif diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs index 8e351221b..fdbae2d56 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs @@ -1,4 +1,5 @@ -// THIS FILE IS MANUALLY CHANGED BASED ON THE GENERATED FILE +#if CORECLR +// THIS FILE IS MANUALLY CHANGED BASED ON THE GENERATED FILE // // The original file has been generated by admin\monad\src\cimSupport\cmdletization\xml\generate.ps1 // based on the following input file: d:\bluedev\admin\monad\src\cimSupport\cmdletization\xml\cmdlets-over-objects.xsd @@ -5289,3 +5290,5 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { } #endif + +#endif diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.objectModel.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.objectModel.autogen.cs index e013baef1..6bf2ee034 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.objectModel.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.objectModel.autogen.cs @@ -1,4 +1,5 @@ -// PLEASE DO NOT EDIT THIS FILE BY HAND!!! +#if !CORECLR +// PLEASE DO NOT EDIT THIS FILE BY HAND!!! // // This file has been generated // by D:\bluedev\admin\monad\src\cimSupport\cmdletization\xml\generate.ps1 @@ -1795,3 +1796,5 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { } } + +#endif diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs index 213a12e86..a6c5a5e60 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs @@ -1,4 +1,5 @@ -// PLEASE DO NOT EDIT THIS FILE BY HAND!!! +#if !CORECLR +// PLEASE DO NOT EDIT THIS FILE BY HAND!!! // // This file has been generated // by D:\bluedev\admin\monad\src\cimSupport\cmdletization\xml\generate.ps1 @@ -7755,3 +7756,5 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { } } + +#endif diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/FormatTable.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/FormatTable.cs index 46f2c8ee4..9109d5237 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/FormatTable.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/FormatTable.cs @@ -316,23 +316,9 @@ namespace System.Management.Automation.Runspaces string shellId = Utils.DefaultPowerShellShellID; string psHome = Utils.GetApplicationBase(shellId); List defaultFormatFiles = new List(); - List fileList = new List() - { - "Certificate.Format.ps1xml", - "Event.Format.ps1xml", - "Diagnostics.Format.ps1xml", - "DotNetTypes.Format.ps1xml", - "FileSystem.Format.ps1xml", - "Help.Format.ps1xml", - "HelpV3.Format.ps1xml", - "PowerShellCore.format.ps1xml", - "PowerShellTrace.format.ps1xml", - "Registry.format.ps1xml", - "WSMan.Format.ps1xml" - }; if (!string.IsNullOrEmpty(psHome)) { - defaultFormatFiles.AddRange(fileList.Select(file => Path.Combine(psHome, file))); + defaultFormatFiles.AddRange(Platform.FormatFileNames.Select(file => Path.Combine(psHome, file))); } return new FormatTable(defaultFormatFiles); diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs index f2c4b0100..3c7295a6f 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs @@ -165,6 +165,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format retVal = ResolveAssemblyNameInLoadedAssemblies(assemblyName, false); } // NOTE: we cache the result (both for success and failure) + + // Porting note: this won't be hit in normal usage, but can be hit with bad build setup + Diagnostics.Assert(retVal != null, "AssemblyName resolution failed, a resource file might be broken"); + _assemblyReferences.Add(assemblyName, retVal); return retVal; } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs index 21952638e..f37434522 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs @@ -1809,7 +1809,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // optional pre-load and binding verification - if (this.VerifyStringResources) + // Porting Note: DLL.resources are not currently available on Linux + if (!Platform.IsX() && this.VerifyStringResources) { DisplayResourceManagerCache.LoadingResult result; DisplayResourceManagerCache.AssemblyBindingStatus bindingStatus; diff --git a/src/System.Management.Automation/engine/CodeMethods.cs b/src/System.Management.Automation/engine/CodeMethods.cs index 68e29b31e..7c6060009 100644 --- a/src/System.Management.Automation/engine/CodeMethods.cs +++ b/src/System.Management.Automation/engine/CodeMethods.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -131,3 +132,5 @@ namespace Microsoft.PowerShell #endregion } } + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/ArgBuilder.cs index 548fed6d9..f259f1cef 100644 --- a/src/System.Management.Automation/engine/ComInterop/ArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ArgBuilder.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -43,3 +44,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/BoolArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/BoolArgBuilder.cs index d0939bfe9..3057cc896 100644 --- a/src/System.Management.Automation/engine/ComInterop/BoolArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/BoolArgBuilder.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -46,3 +47,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/BoundDispEvent.cs b/src/System.Management.Automation/engine/ComInterop/BoundDispEvent.cs index b36efe37f..535dd0fb6 100644 --- a/src/System.Management.Automation/engine/ComInterop/BoundDispEvent.cs +++ b/src/System.Management.Automation/engine/ComInterop/BoundDispEvent.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -99,3 +100,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/CollectionExtensions.cs b/src/System.Management.Automation/engine/ComInterop/CollectionExtensions.cs index 1be7f3a41..13f6aca2e 100644 --- a/src/System.Management.Automation/engine/ComInterop/CollectionExtensions.cs +++ b/src/System.Management.Automation/engine/ComInterop/CollectionExtensions.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -38,3 +39,5 @@ namespace System.Management.Automation.ComInterop { } } + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComBinder.cs b/src/System.Management.Automation/engine/ComInterop/ComBinder.cs index adedd7928..0ab529f53 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComBinder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComBinder.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -373,3 +374,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComBinderHelpers.cs b/src/System.Management.Automation/engine/ComInterop/ComBinderHelpers.cs index f5a1ca3ae..19d736281 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComBinderHelpers.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComBinderHelpers.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -131,3 +132,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComClassMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/ComClassMetaObject.cs index 86849c11d..939358b2c 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComClassMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComClassMetaObject.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -38,3 +39,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComDispIds.cs b/src/System.Management.Automation/engine/ComInterop/ComDispIds.cs index c1332c0e7..55825e0be 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComDispIds.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComDispIds.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -14,3 +15,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComEventDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComEventDesc.cs index 3c1238e06..7f8653ca4 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComEventDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComEventDesc.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -15,3 +16,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComEventSink.cs b/src/System.Management.Automation/engine/ComInterop/ComEventSink.cs index 5e2eb2530..d5ddcb533 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComEventSink.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComEventSink.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -318,3 +319,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComEventSinkProxy.cs b/src/System.Management.Automation/engine/ComInterop/ComEventSinkProxy.cs index 93e433ee2..c5c515422 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComEventSinkProxy.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComEventSinkProxy.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -116,3 +117,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComEventSinksContainer.cs b/src/System.Management.Automation/engine/ComInterop/ComEventSinksContainer.cs index ee74a3a6c..4a4ea0ecc 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComEventSinksContainer.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComEventSinksContainer.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -69,3 +70,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComFallbackMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/ComFallbackMetaObject.cs index 1e2b0f41e..437c5332b 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComFallbackMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComFallbackMetaObject.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -69,3 +70,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComHresults.cs b/src/System.Management.Automation/engine/ComInterop/ComHresults.cs index 951364f03..1ca681678 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComHresults.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComHresults.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -36,3 +37,5 @@ namespace System.Management.Automation.ComInterop { } #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComInterop.cs b/src/System.Management.Automation/engine/ComInterop/ComInterop.cs index 2d5b445a5..ff5ee3ce3 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComInterop.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComInterop.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -82,3 +83,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComInvokeAction.cs b/src/System.Management.Automation/engine/ComInterop/ComInvokeAction.cs index 2e9ad0143..884ab803e 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComInvokeAction.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComInvokeAction.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -94,3 +95,5 @@ namespace System.Management.Automation.ComInterop { } #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs b/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs index f5588edb6..27fda6001 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -528,3 +529,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/ComMetaObject.cs index 09be6a229..1e29f549c 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComMetaObject.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -63,3 +64,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComMethodDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComMethodDesc.cs index 3433e3a82..731e806c6 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComMethodDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComMethodDesc.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -121,3 +122,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComObject.cs b/src/System.Management.Automation/engine/ComInterop/ComObject.cs index 72feba2a6..fda5efb0f 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComObject.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -125,3 +126,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComParamDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComParamDesc.cs index 097ab7c1e..13b57ec1a 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComParamDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComParamDesc.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -154,3 +155,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComRuntimeHelpers.cs b/src/System.Management.Automation/engine/ComInterop/ComRuntimeHelpers.cs index c43e5fe94..59c2b0dbe 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComRuntimeHelpers.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComRuntimeHelpers.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -765,3 +766,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComType.cs b/src/System.Management.Automation/engine/ComInterop/ComType.cs index 916e59373..bd6bb75de 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComType.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComType.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -15,3 +16,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeClassDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeClassDesc.cs index 62e56f7a2..9f30a3de9 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeClassDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeClassDesc.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -82,3 +83,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs index a76b00180..8928119fa 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -220,3 +221,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeEnumDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeEnumDesc.cs index a2db280bd..d14290050 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeEnumDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeEnumDesc.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -91,3 +92,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs index 8313529a3..d56a0d430 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -225,3 +226,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeLibInfo.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeLibInfo.cs index 39ea1e7b7..d43893de2 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeLibInfo.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeLibInfo.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -55,3 +56,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeLibMemberDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeLibMemberDesc.cs index 5bca5cbb7..5fff34b71 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeLibMemberDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeLibMemberDesc.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -22,3 +23,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ConversionArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/ConversionArgBuilder.cs index e40f25476..59cd849db 100644 --- a/src/System.Management.Automation/engine/ComInterop/ConversionArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ConversionArgBuilder.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -39,3 +40,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ConvertArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/ConvertArgBuilder.cs index 7a881108e..180d956c9 100644 --- a/src/System.Management.Automation/engine/ComInterop/ConvertArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ConvertArgBuilder.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -34,3 +35,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ConvertibleArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/ConvertibleArgBuilder.cs index 351610caa..0ccac5030 100644 --- a/src/System.Management.Automation/engine/ComInterop/ConvertibleArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ConvertibleArgBuilder.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -34,3 +35,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/CurrencyArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/CurrencyArgBuilder.cs index f3ecb9f5f..54deed6d2 100644 --- a/src/System.Management.Automation/engine/ComInterop/CurrencyArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/CurrencyArgBuilder.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -53,3 +54,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/DateTimeArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/DateTimeArgBuilder.cs index e36b60db5..392b328c3 100644 --- a/src/System.Management.Automation/engine/ComInterop/DateTimeArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/DateTimeArgBuilder.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -44,3 +45,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/DispCallable.cs b/src/System.Management.Automation/engine/ComInterop/DispCallable.cs index dfe8e615f..729a0e6a0 100644 --- a/src/System.Management.Automation/engine/ComInterop/DispCallable.cs +++ b/src/System.Management.Automation/engine/ComInterop/DispCallable.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -67,3 +68,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/DispCallableMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/DispCallableMetaObject.cs index f2280c79c..0bc092256 100644 --- a/src/System.Management.Automation/engine/ComInterop/DispCallableMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/DispCallableMetaObject.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -138,3 +139,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/DispatchArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/DispatchArgBuilder.cs index ae543f809..de8eae0ea 100644 --- a/src/System.Management.Automation/engine/ComInterop/DispatchArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/DispatchArgBuilder.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -79,3 +80,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ErrorArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/ErrorArgBuilder.cs index fdcf32f9c..92231dec8 100644 --- a/src/System.Management.Automation/engine/ComInterop/ErrorArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ErrorArgBuilder.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -45,3 +46,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/Errors.cs b/src/System.Management.Automation/engine/ComInterop/Errors.cs index 072311322..93346edf9 100644 --- a/src/System.Management.Automation/engine/ComInterop/Errors.cs +++ b/src/System.Management.Automation/engine/ComInterop/Errors.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -241,3 +242,5 @@ namespace System.Management.Automation.ComInterop { } + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs b/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs index 4a7f97ad3..81d0744e1 100644 --- a/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs +++ b/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -100,3 +101,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/Helpers.cs b/src/System.Management.Automation/engine/ComInterop/Helpers.cs index 20d903ef3..462ce1169 100644 --- a/src/System.Management.Automation/engine/ComInterop/Helpers.cs +++ b/src/System.Management.Automation/engine/ComInterop/Helpers.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -24,3 +25,5 @@ namespace System.Management.Automation.ComInterop { } } + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs b/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs index 7b41bfc59..9bfc8b4da 100644 --- a/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -629,3 +630,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs index 3aef3cb4f..8f1df754d 100644 --- a/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -318,3 +319,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/IPseudoComObject.cs b/src/System.Management.Automation/engine/ComInterop/IPseudoComObject.cs index be7cce088..294b01b42 100644 --- a/src/System.Management.Automation/engine/ComInterop/IPseudoComObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/IPseudoComObject.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -17,3 +18,5 @@ namespace System.Management.Automation.ComInterop { } } + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/NullArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/NullArgBuilder.cs index 08d7771e1..e4ecf2088 100644 --- a/src/System.Management.Automation/engine/ComInterop/NullArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/NullArgBuilder.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -28,3 +29,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/SimpleArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/SimpleArgBuilder.cs index 065dcce1d..f86b9b729 100644 --- a/src/System.Management.Automation/engine/ComInterop/SimpleArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/SimpleArgBuilder.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -44,3 +45,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/SplatCallSite.cs b/src/System.Management.Automation/engine/ComInterop/SplatCallSite.cs index 1b28e7fe8..c34a6c8af 100644 --- a/src/System.Management.Automation/engine/ComInterop/SplatCallSite.cs +++ b/src/System.Management.Automation/engine/ComInterop/SplatCallSite.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -50,3 +51,5 @@ namespace System.Management.Automation.ComInterop { } #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/StringArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/StringArgBuilder.cs index b42e04213..51e9630ca 100644 --- a/src/System.Management.Automation/engine/ComInterop/StringArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/StringArgBuilder.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -78,3 +79,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/TypeEnumMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/TypeEnumMetaObject.cs index 08b485e62..85ab23159 100644 --- a/src/System.Management.Automation/engine/ComInterop/TypeEnumMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/TypeEnumMetaObject.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -74,3 +75,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/TypeLibInfoMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/TypeLibInfoMetaObject.cs index 74fcd7c82..b75f50fb4 100644 --- a/src/System.Management.Automation/engine/ComInterop/TypeLibInfoMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/TypeLibInfoMetaObject.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -62,3 +63,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/TypeLibMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/TypeLibMetaObject.cs index 0c976abb8..39a10f83f 100644 --- a/src/System.Management.Automation/engine/ComInterop/TypeLibMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/TypeLibMetaObject.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -75,3 +76,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/TypeUtils.cs b/src/System.Management.Automation/engine/ComInterop/TypeUtils.cs index 374c48dd9..b24f896da 100644 --- a/src/System.Management.Automation/engine/ComInterop/TypeUtils.cs +++ b/src/System.Management.Automation/engine/ComInterop/TypeUtils.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -244,3 +245,5 @@ namespace System.Management.Automation.ComInterop { } } + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/UnknownArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/UnknownArgBuilder.cs index 6b429462f..66295226a 100644 --- a/src/System.Management.Automation/engine/ComInterop/UnknownArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/UnknownArgBuilder.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -79,3 +80,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs b/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs index 9f727d4a0..88c4feb43 100644 --- a/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs +++ b/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -515,3 +516,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/Variant.cs b/src/System.Management.Automation/engine/ComInterop/Variant.cs index 586bdfc3e..4791083e4 100644 --- a/src/System.Management.Automation/engine/ComInterop/Variant.cs +++ b/src/System.Management.Automation/engine/ComInterop/Variant.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -841,3 +842,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/VariantArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/VariantArgBuilder.cs index 69ab54d8c..6dae9f984 100644 --- a/src/System.Management.Automation/engine/ComInterop/VariantArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/VariantArgBuilder.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -70,3 +71,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/VariantArray.cs b/src/System.Management.Automation/engine/ComInterop/VariantArray.cs index 63e593475..02cd757bd 100644 --- a/src/System.Management.Automation/engine/ComInterop/VariantArray.cs +++ b/src/System.Management.Automation/engine/ComInterop/VariantArray.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -97,3 +98,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/ComInterop/VariantBuilder.cs b/src/System.Management.Automation/engine/ComInterop/VariantBuilder.cs index 9a5cadef1..eb7df589b 100644 --- a/src/System.Management.Automation/engine/ComInterop/VariantBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/VariantBuilder.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -161,3 +162,5 @@ namespace System.Management.Automation.ComInterop { #endif + +#endif diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 05465a111..9b6b1735a 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -4309,8 +4309,9 @@ namespace System.Management.Automation { var sessionStateInternal = executionContext.EngineSessionState; completionText = sessionStateInternal.NormalizeRelativePath(path, sessionStateInternal.CurrentLocation.ProviderPath); - if (!completionText.StartsWith("..\\", StringComparison.Ordinal)) - completionText = ".\\" + completionText; + string parentDirectory = ".." + Path.DirectorySeparatorChar; + if (!completionText.StartsWith(parentDirectory, StringComparison.Ordinal)) + completionText = Path.Combine(".", completionText); } catch (Exception e) { @@ -4448,6 +4449,12 @@ namespace System.Management.Automation internal static List GetFileShares(string machine, bool ignoreHidden) { + // Platform notes: don't throw an exception since this is being used in auto-completion + if (!Platform.HasFileShares()) + { + return new List(); + } + IntPtr shBuf; uint numEntries; uint totalEntries; diff --git a/src/System.Management.Automation/engine/CommandDiscovery.cs b/src/System.Management.Automation/engine/CommandDiscovery.cs index 620826472..548de11b6 100644 --- a/src/System.Management.Automation/engine/CommandDiscovery.cs +++ b/src/System.Management.Automation/engine/CommandDiscovery.cs @@ -1302,7 +1302,8 @@ namespace System.Management.Automation } // Close the progress pane that may have popped up from analyzing UNC paths. - if (context.CurrentCommandProcessor != null) + // Porting note: we don't like this message + if (!Platform.IsX() && context.CurrentCommandProcessor != null) { ProgressRecord analysisProgress = new ProgressRecord(0, Modules.ScriptAnalysisPreparing, " "); analysisProgress.RecordType = ProgressRecordType.Completed; @@ -1495,8 +1496,7 @@ namespace System.Management.Automation /// /// /// - /// The contents of the PATH environment variable split using a semi-colon - /// as a delimiter. + /// The contents of the PATH environment variable split on System.IO.Path.PathSeparator. /// /// /// @@ -1529,7 +1529,7 @@ namespace System.Management.Automation if (pathCacheKey != null) { - string[] tokenizedPath = pathCacheKey.Split(Utils.Separators.Semicolon, StringSplitOptions.RemoveEmptyEntries); + string[] tokenizedPath = pathCacheKey.Split(new char[] { System.IO.Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries); cachedPath = new Collection(); foreach (string directory in tokenizedPath) @@ -1620,7 +1620,7 @@ namespace System.Management.Automation lock (lockObject) { cachedPathExtCollection = pathExt != null - ? pathExt.Split(Utils.Separators.Semicolon, StringSplitOptions.RemoveEmptyEntries) + ? pathExt.Split(new char[] { System.IO.Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries) : Utils.EmptyArray(); cachedPathExtCollectionWithPs1 = new string[cachedPathExtCollection.Length + 1]; cachedPathExtCollectionWithPs1[0] = StringLiterals.PowerShellScriptFileExtension; @@ -1883,6 +1883,11 @@ namespace System.Management.Automation /// internal static string GetShellPathFromRegistry(string shellID) { + if (!Platform.HasRegistrySupport()) + { + return null; + } + string result = null; try diff --git a/src/System.Management.Automation/engine/CommandPathSearch.cs b/src/System.Management.Automation/engine/CommandPathSearch.cs index 7e6302cd2..0c4edaf8f 100644 --- a/src/System.Management.Automation/engine/CommandPathSearch.cs +++ b/src/System.Management.Automation/engine/CommandPathSearch.cs @@ -55,7 +55,11 @@ namespace System.Management.Automation // The name passed in is not a pattern. To minimize enumerating the file system, we // turn the command name into a pattern and then match against extensions in PATHEXT. // The old code would enumerate the file system many more times, once per possible extension. - commandName = commandName + ".*"; + // Porting note: this is wrong on Linux, where we don't depend on extensions + if (Platform.IsWindows()) + { + commandName = commandName + ".*"; + } this.postProcessEnumeratedFiles = CheckAgainstAcceptableCommandNames; this.acceptableCommandNames = acceptableCommandNames; } @@ -461,8 +465,10 @@ namespace System.Management.Automation { var baseNames = fileNames.Select(Path.GetFileName).ToArray(); - // Result must be ordered by PATHEXT order of precdence. - // accpetableCommandNames is in this order, so + // Result must be ordered by PATHEXT order of precedence. + // acceptableCommandNames is in this order, so + + // Porting note: allow files with executable bit on non-Windows platforms Collection result = null; if (baseNames.Length > 0) @@ -471,7 +477,8 @@ namespace System.Management.Automation { for (int i = 0; i < baseNames.Length; i++) { - if (name.Equals(baseNames[i], StringComparison.OrdinalIgnoreCase)) + if (name.Equals(baseNames[i], StringComparison.OrdinalIgnoreCase) + || (!Platform.IsWindows() && Platform.NonWindowsIsExecutable(name))) { if (result == null) result = new Collection(); @@ -487,14 +494,18 @@ namespace System.Management.Automation private IEnumerable JustCheckExtensions(string[] fileNames) { - // Result must be ordered by PATHEXT order of precdence. + // Warning: pretty duplicated code + // Result must be ordered by PATHEXT order of precedence. + + // Porting note: allow files with executable bit on non-Windows platforms Collection result = null; foreach (var allowedExt in orderedPathExt) { foreach (var fileName in fileNames) { - if (fileName.EndsWith(allowedExt, StringComparison.OrdinalIgnoreCase)) + if (fileName.EndsWith(allowedExt, StringComparison.OrdinalIgnoreCase) + || (!Platform.IsWindows() && Platform.NonWindowsIsExecutable(fileName))) { if (result == null) result = new Collection(); diff --git a/src/System.Management.Automation/engine/DataStoreAdapter.cs b/src/System.Management.Automation/engine/DataStoreAdapter.cs index 4c796937b..e6f926e2c 100644 --- a/src/System.Management.Automation/engine/DataStoreAdapter.cs +++ b/src/System.Management.Automation/engine/DataStoreAdapter.cs @@ -299,6 +299,58 @@ namespace System.Management.Automation } private string displayRoot = null; + /// + /// Gets or sets if the drive-root relative paths on this drive are separated by a + /// colon or not. + /// + /// This is true for all PSDrives on all platforms, except for filesystems on + /// non-Windows platforms. + /// + /// This is not a path separator in the sense of separating paths in a single + /// string. + /// + /// The biggest difference in filesystem handling between PS internally, and Unix + /// style systems is, that paths on Windows separate the drive letter from the + /// actual path by a colon. The second difference is, that a path that starts with + /// a \ or / on Windows is considered to be a relative path (drive-relative in + /// that case) where a similar path on a Unix style filesystem would be + /// root-relative, which is basically drive-relative for the filesystem, as there + /// is only one filesystem drive. + /// + /// This property indicates, that a path can be checked for that drive-relativity + /// by checking for a colon. The main reason for this can be seen in all the + /// places that use this property, where PowerShell's code checks/splits/string + /// manipulates paths according to the colon character. This happens in many + /// places. + /// + /// The idea here was to introduce a property that allows a code to query if a + /// PSDrive expects colon to be such a separator or not. I talked to Jim back then + /// about the problem, and this seemed to be a reasonable solution, given that + /// there is no other way to know for a PSDrive if paths can be qualified only in + /// a certain windows way on all platforms, or need special treatment on platforms + /// where colon does not exist as drive separator (regular filesystems on Unix + /// platforms are the only exception). + /// + /// Globally this property can also be only true for one single PSDrive, because + /// if there is no drive separator, there is also no drive, and because there is + /// no drive there is no way to match against multiple such drives. + /// + /// Additional data: + /// It seems that on single rooted filesystems, only the default + /// drive of "/" needs to set this VolumeSeparatedByColon to false + /// otherwise, creating new drives from the filesystem should actually + /// have this set to true as all the drives will have : except + /// for "/" + /// + /// + public bool VolumeSeparatedByColon + { + get { return _volumeSeparatedByColon; } + internal set { _volumeSeparatedByColon = value; } + } + private bool _volumeSeparatedByColon = true; + + #region ctor /// diff --git a/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs b/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs index 74e9115ba..12d63374d 100644 --- a/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs +++ b/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs @@ -301,6 +301,20 @@ namespace System.Management.Automation Thread.AllocateDataSlot(); #endif + /// + /// Gets or sets if the drive-root relative paths on drives of this provider + /// are separated by a colon or not. + /// + /// This is true for all PSDrives on all platforms, except for filesystems on + /// non-windows platforms + /// + public bool VolumeSeparatedByColon + { + get { return volumeSeparatedByColon; } + internal set { volumeSeparatedByColon = value; } + } + private bool volumeSeparatedByColon = true; + /// /// Constructs an instance of the class using an existing reference /// as a template. @@ -336,6 +350,7 @@ namespace System.Management.Automation this.helpFile = providerInfo.helpFile; this.pssnapin = providerInfo.pssnapin; this.sessionState = providerInfo.sessionState; + this.volumeSeparatedByColon = providerInfo.volumeSeparatedByColon; } /// @@ -481,6 +496,13 @@ namespace System.Management.Automation null); hiddenDrive.Hidden = true; + + // TODO:PSL + // this is probably not right here + if (implementingType == typeof(Microsoft.PowerShell.Commands.FileSystemProvider) && !Platform.IsWindows()) + { + volumeSeparatedByColon = false; + } } #if SUPPORTS_CMDLETPROVIDER_FILE diff --git a/src/System.Management.Automation/engine/ExecutionContext.cs b/src/System.Management.Automation/engine/ExecutionContext.cs index 5920cad06..c0db81346 100644 --- a/src/System.Management.Automation/engine/ExecutionContext.cs +++ b/src/System.Management.Automation/engine/ExecutionContext.cs @@ -1559,7 +1559,7 @@ namespace System.Management.Automation try { - loadedAssembly = Assembly.Load(new AssemblyName(assemblyString)); + loadedAssembly = ClrFacade.Load(new AssemblyName(assemblyString)); } catch (FileNotFoundException fileNotFound) { diff --git a/src/System.Management.Automation/engine/ExtraAdapter.cs b/src/System.Management.Automation/engine/ExtraAdapter.cs index cf84d41de..0982ff8ad 100644 --- a/src/System.Management.Automation/engine/ExtraAdapter.cs +++ b/src/System.Management.Automation/engine/ExtraAdapter.cs @@ -1,4 +1,5 @@ -/********************************************************************++ +#if !CORECLR +/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -596,3 +597,5 @@ namespace System.Management.Automation #endregion method } } + +#endif diff --git a/src/System.Management.Automation/engine/InformationRecord.cs b/src/System.Management.Automation/engine/InformationRecord.cs index e3e373a16..b698501db 100644 --- a/src/System.Management.Automation/engine/InformationRecord.cs +++ b/src/System.Management.Automation/engine/InformationRecord.cs @@ -38,7 +38,15 @@ namespace System.Management.Automation this.TimeGenerated = DateTime.Now; this.Tags = new List(); - this.User = System.Security.Principal.WindowsIdentity.GetCurrent().Name; + if (Platform.IsWindows()) + { + this.User = System.Security.Principal.WindowsIdentity.GetCurrent().Name; + } + else + { + this.User = Platform.NonWindowsGetUserName(); + } + // Porting note: PsUtils.GetHostName() already handles platform specifics this.Computer = PsUtils.GetHostName(); this.ProcessId = (uint) System.Diagnostics.Process.GetCurrentProcess().Id; this.NativeThreadId = PsUtils.GetNativeThreadId(); @@ -225,4 +233,4 @@ namespace System.Management.Automation return Message; } } -} \ No newline at end of file +} diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 9e63b70db..b7e4829a3 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -1673,19 +1673,9 @@ namespace System.Management.Automation.Runspaces return iss; } - private static string[] PSCoreFormatFileNames = { - "Certificate.format.ps1xml", - "Diagnostics.Format.ps1xml", - "DotNetTypes.format.ps1xml", - "Event.Format.ps1xml", - "FileSystem.format.ps1xml", - "Help.format.ps1xml", - "HelpV3.format.ps1xml", - "PowerShellCore.format.ps1xml", - "PowerShellTrace.format.ps1xml", - "Registry.format.ps1xml", - "WSMan.Format.ps1xml" - }; + // Porting note: moved to Platform so we have one list to maintain + private static string[] PSCoreFormatFileNames = Platform.FormatFileNames.ToArray(); + private static void IncludePowerShellCoreFormats(InitialSessionState iss) { string psHome = Utils.GetApplicationBase(Utils.DefaultPowerShellShellID); @@ -1785,25 +1775,14 @@ namespace System.Management.Automation.Runspaces } } - List allowedFormats = new List - { - "Certificate.Format.ps1xml", - "Event.format.ps1xml", - "Diagnostics.format.ps1xml", - "DotNetTypes.Format.ps1xml", - "FileSystem.Format.ps1xml", - "Help.Format.ps1xml", - "HelpV3.format.ps1xml", - "PowerShellCore.format.ps1xml", - "PowerShellTrace.format.ps1xml", - "Registry.format.ps1xml", - "WSMan.format.ps1xml" - }; + // Porting note: copy so it can be modified + List allowedFormats = new List(Platform.FormatFileNames); RemoveDisallowedEntries( iss.Formats, allowedFormats, formatEntry => IO.Path.GetFileName(formatEntry.FileName)); + // Porting note: type files were deprecated List allowedTypes = new List(); allowedTypes.AddRange(DefaultTypeFiles); RemoveDisallowedEntries( @@ -1871,25 +1850,14 @@ namespace System.Management.Automation.Runspaces } } - List allowedFormats = new List - { - "Certificate.Format.ps1xml", - "Event.format.ps1xml", - "Diagnostics.format.ps1xml", - "DotNetTypes.Format.ps1xml", - "FileSystem.Format.ps1xml", - "Help.Format.ps1xml", - "HelpV3.format.ps1xml", - "PowerShellCore.format.ps1xml", - "PowerShellTrace.format.ps1xml", - "Registry.format.ps1xml", - "WSMan.format.ps1xml" - }; + // Porting note: copy so it can be modified + List allowedFormats = new List(Platform.FormatFileNames); RemoveDisallowedEntries( iss.Formats, allowedFormats, formatEntry => IO.Path.GetFileName(formatEntry.FileName)); + // Porting note: type files were deprecated List allowedTypes = new List(); allowedTypes.AddRange(DefaultTypeFiles); RemoveDisallowedEntries( @@ -4277,6 +4245,7 @@ namespace System.Management.Automation.Runspaces return coreSnapin; } + // WARNING: THIS CODE IS COMPLETELY DUPLICATED IN RunspaceConfigForSingleShell internal PSSnapInInfo ImportPSSnapIn(PSSnapInInfo psSnapInInfo, out PSSnapInException warning) { // See if the snapin is already loaded. If has been then there will be an entry in the @@ -4738,6 +4707,32 @@ End /// private static string ImportSystemModulesText = @""; + /// + /// This is the default function to use for clear-host. On Windows it rewrites the + /// host, and on Linux, it delegates to the native binary, 'clear'. + /// + internal static string GetClearHostFunctionText() + { + if (Platform.IsWindows()) + { + return @" +$RawUI = $Host.UI.RawUI +$RawUI.CursorPosition = @{X=0;Y=0} +$RawUI.SetBufferContents( + @{Top = -1; Bottom = -1; Right = -1; Left = -1}, + @{Character = ' '; ForegroundColor = $rawui.ForegroundColor; BackgroundColor = $rawui.BackgroundColor}) +# .Link +# http://go.microsoft.com/fwlink/?LinkID=225747 +# .ExternalHelp System.Management.Automation.dll-help.xml +"; + } + else + { + // Porting note: non-Windows platforms use `clear` + return "& (Get-Command -CommandType Application clear).Definition | Select-Object -First 1"; + } + } + /// /// This is the default function to use for man/help. It uses /// splatting to pass in the parameters. @@ -5431,28 +5426,18 @@ end # .Link # http://go.microsoft.com/fwlink/?LinkID=225750 # .ExternalHelp System.Management.Automation.dll-help.xml -"; - - internal const string DefaultClearHostFunctionText = @" -$RawUI = $Host.UI.RawUI -$RawUI.CursorPosition = @{X=0;Y=0} -$RawUI.SetBufferContents( - @{Top = -1; Bottom = -1; Right = -1; Left = -1}, - @{Character = ' '; ForegroundColor = $rawui.ForegroundColor; BackgroundColor = $rawui.BackgroundColor}) -# .Link -# http://go.microsoft.com/fwlink/?LinkID=225747 -# .ExternalHelp System.Management.Automation.dll-help.xml "; internal const string DefaultMoreFunctionText = @" param([string[]]$paths) $OutputEncoding = [System.Console]::OutputEncoding +$moreCommand = (Get-Command -CommandType Application more).Definition | Select-Object -First 1 if($paths) { foreach ($file in $paths) { - Get-Content $file | more.com + Get-Content $file | & $moreCommand } -} else { $input | more.com } +} else { $input | & $moreCommand } "; internal const string DefaultSetDriveFunctionText = "Set-Location $MyInvocation.MyCommand.Name"; @@ -5461,10 +5446,9 @@ if($paths) { internal static SessionStateFunctionEntry[] BuiltInFunctions = new SessionStateFunctionEntry[] { // Functions. Only the name and definitions are used - SessionStateFunctionEntry.GetDelayParsedFunctionEntry("prompt", DefaultPromptFunctionText), SessionStateFunctionEntry.GetDelayParsedFunctionEntry("TabExpansion2", TabExpansionFunctionText), - SessionStateFunctionEntry.GetDelayParsedFunctionEntry("Clear-Host", DefaultClearHostFunctionText), + SessionStateFunctionEntry.GetDelayParsedFunctionEntry("Clear-Host", GetClearHostFunctionText()), SessionStateFunctionEntry.GetDelayParsedFunctionEntry("more", DefaultMoreFunctionText), SessionStateFunctionEntry.GetDelayParsedFunctionEntry("help", GetHelpPagingFunctionText()), SessionStateFunctionEntry.GetDelayParsedFunctionEntry("mkdir", GetMkdirFunctionText()), @@ -5625,7 +5609,8 @@ if($paths) { try { - assembly = Assembly.Load(new AssemblyName(psSnapInInfo.AssemblyName)); + // WARNING: DUPLICATE CODE see RunspaceConfigForSingleShell + assembly = ClrFacade.Load(new AssemblyName(psSnapInInfo.AssemblyName)); } catch (BadImageFormatException e) { @@ -5648,7 +5633,12 @@ if($paths) { try { AssemblyName assemblyName = ClrFacade.GetAssemblyName(psSnapInInfo.AbsoluteModulePath); - if (!string.Equals(assemblyName.FullName, psSnapInInfo.AssemblyName, StringComparison.OrdinalIgnoreCase)) + + // Porting note: the snapins still require 'ProcessorArchitecture=MSIL' in + // the strong name, which is not in the strong name of assemblies created + // by dotnet-cli + if (!Platform.IsX() && + !string.Equals(assemblyName.FullName, psSnapInInfo.AssemblyName, StringComparison.OrdinalIgnoreCase)) { string message = StringUtil.Format(ConsoleInfoErrorStrings.PSSnapInAssemblyNameMismatch, psSnapInInfo.AbsoluteModulePath, psSnapInInfo.AssemblyName); _PSSnapInTracer.TraceError(message); diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs index 4aaa79022..dcb967760 100644 --- a/src/System.Management.Automation/engine/LanguagePrimitives.cs +++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs @@ -481,10 +481,13 @@ namespace System.Management.Automation return null; } +#if !CORECLR + // .NET Core does not have a full DataTable type static IEnumerable DataTableEnumerable(object obj) { return (((DataTable)obj).Rows); } +#endif static IEnumerable TypicalEnumerable(object obj) { @@ -522,10 +525,13 @@ namespace System.Management.Automation static GetEnumerableDelegate CalculateGetEnumerable(Type objectType) { +#if !CORECLR + // .NET Core does not have a full DataTable type if (typeof(DataTable).IsAssignableFrom(objectType)) { return LanguagePrimitives.DataTableEnumerable; } +#endif // Don't treat IDictionary or XmlNode as enumerable... if (typeof(IEnumerable).IsAssignableFrom(objectType) diff --git a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs index 7f4284b54..5b24ac797 100644 --- a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs +++ b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -1248,3 +1249,5 @@ namespace System.Management.Automation } } } + +#endif diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index 727b56ea9..ca0afb099 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -531,7 +531,9 @@ namespace System.Management.Automation } /// - /// Gets the personal module path (i.e. C:\Users\lukasza\Documents\WindowsPowerShell\modules) + /// Gets the personal module path + /// (i.e. C:\Users\lukasza\Documents\WindowsPowerShell\modules, or + /// ~/.powershell/Modules on Linux) /// /// personal module path internal static string GetPersonalModulePath() @@ -578,7 +580,12 @@ namespace System.Management.Automation // Because of this, the module that is getting loaded during startup (through LocalRunspace) // is using "SysWow64" in the key. Later, when Import-Module is called, it loads the // module using ""System32" in the key. - psHome = psHome.ToLowerInvariant().Replace("\\syswow64\\", "\\system32\\"); + + // Porting note: psHome cannot be lower-cased on case sensitive file systems + if (Platform.IsWindows()) + { + psHome = psHome.ToLowerInvariant().Replace("\\syswow64\\", "\\system32\\"); + } Interlocked.CompareExchange(ref SystemWideModulePath, Path.Combine(psHome, Utils.ModuleDirectory), null); } @@ -593,6 +600,11 @@ namespace System.Management.Automation /// internal static string GetDscModulePath() { + if (!Platform.IsWindows()) + { + return string.Empty; + } + string dscModulePath = null; string programFilesPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); if (!string.IsNullOrEmpty(programFilesPath)) @@ -726,7 +738,7 @@ namespace System.Management.Automation if (currentProcessModulePath == null) // EVT.Process does Not exist - really corner case { // Handle the default case... - if (hkcuUserModulePath == null) // EVT.User does Not exist -> set to location + if (String.IsNullOrEmpty(hkcuUserModulePath)) // EVT.User does Not exist -> set to location { currentProcessModulePath = GetPersonalModulePath(); // = SpecialFolder.MyDocuments + Utils.ProductNameForDirectory + Utils.ModuleDirectory } @@ -736,7 +748,7 @@ namespace System.Management.Automation } currentProcessModulePath += ';'; - if (hklmMachineModulePath == null) // EVT.Machine does Not exist + if (String.IsNullOrEmpty(hklmMachineModulePath)) // EVT.Machine does Not exist { currentProcessModulePath += CombineSystemModulePaths(); // += (DscModulePath + $PSHome\Modules) } @@ -749,6 +761,13 @@ namespace System.Management.Automation { // Now handle the case where the environment variable is already set. + // Porting note: Open PowerShell has a Modules folder in the the application base path which contains the built-in modules + // It must be in the front of the path no matter what. + if (Platform.IsX()) + { + currentProcessModulePath = AddToPath(currentProcessModulePath, GetSystemwideModulePath(), 0); + } + // If there is no personal path key, then if the env variable doesn't match the system variable, // the user modified it somewhere, else prepend the default personel module path if (hklmMachineModulePath != null) // EVT.Machine exists @@ -858,11 +877,11 @@ namespace System.Management.Automation string newModulePathString = GetModulePath(currentModulePath, systemWideModulePath, personalModulePath); - if(!string.IsNullOrEmpty(newModulePathString)) - { - // Set the environment variable... + if(!string.IsNullOrEmpty(newModulePathString)) + { + // Set the environment variable... Environment.SetEnvironmentVariable("PSMODULEPATH", newModulePathString); - } + } return newModulePathString; } @@ -947,7 +966,8 @@ namespace System.Management.Automation catch (NotSupportedException) { // silently skip invalid path - // NotSupportedException is thrown if path contains a colon (":") that is not part of a volume identifier (for example, "c:\" is Supported but not "c:\temp\Z:\invalidPath") + // NotSupportedException is thrown if path contains a colon (":") that is not part of a + // volume identifier (for example, "c:\" is Supported but not "c:\temp\Z:\invalidPath") } if (provider != null && resolvedPaths != null && provider.NameEquals(context.ProviderNames.FileSystem)) diff --git a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs index 4415995ee..9ee08e260 100644 --- a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs +++ b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -776,3 +777,5 @@ namespace System.Management.Automation } + +#endif diff --git a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs index 067a55caf..b9636c6a0 100644 --- a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs +++ b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs @@ -131,7 +131,7 @@ namespace System.Management.Automation { var rawArgs = arguments.ToString(); - if (tracer.IsEnabled) + if (tracer.IsEnabled && Platform.IsWindows()) { // This tracing really shouldn't be in the property getter... tracer.WriteLine("Raw argument string: {0}", rawArgs); diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index a2385aac0..9fc15982d 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -1024,8 +1024,10 @@ namespace System.Management.Automation ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = this.Path; - // Check the extension list and see if we should try to execute this directly. - if (ValidateExtension(this.Path)) + // On Windows, check the extension list and see if we should try to execute this directly. + // Otherwise, use the platform library to check executability + if ((Platform.IsWindows() && ValidateExtension(this.Path)) + || (!Platform.IsWindows() && Platform.NonWindowsIsExecutable(this.Path))) { startInfo.UseShellExecute = false; if (redirectInput) diff --git a/src/System.Management.Automation/engine/PSMI/PSNegotiationData.cs b/src/System.Management.Automation/engine/PSMI/PSNegotiationData.cs index 23899138e..b5058a6ae 100644 --- a/src/System.Management.Automation/engine/PSMI/PSNegotiationData.cs +++ b/src/System.Management.Automation/engine/PSMI/PSNegotiationData.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +#if !CORECLR +using System.Collections.Generic; using System.Runtime.InteropServices; using Microsoft.Management.Infrastructure; @@ -24,4 +25,5 @@ namespace System.Management.Automation return c; } } -} \ No newline at end of file +} +#endif diff --git a/src/System.Management.Automation/engine/PSMI/PSPowerShellPipeline.cs b/src/System.Management.Automation/engine/PSMI/PSPowerShellPipeline.cs index 21b8a12f3..8194fd372 100644 --- a/src/System.Management.Automation/engine/PSMI/PSPowerShellPipeline.cs +++ b/src/System.Management.Automation/engine/PSMI/PSPowerShellPipeline.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +#if !CORECLR +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; @@ -59,4 +60,5 @@ namespace System.Management.Automation [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr Value; } -} \ No newline at end of file +} +#endif diff --git a/src/System.Management.Automation/engine/PSMI/Serialization/InternalMISerializer.cs b/src/System.Management.Automation/engine/PSMI/Serialization/InternalMISerializer.cs index 8d35a9838..8d9919e1f 100644 --- a/src/System.Management.Automation/engine/PSMI/Serialization/InternalMISerializer.cs +++ b/src/System.Management.Automation/engine/PSMI/Serialization/InternalMISerializer.cs @@ -1,4 +1,5 @@ -/********************************************************************++ +#if !CORECLR +/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -907,4 +908,5 @@ namespace System.Management.Automation #endregion } -} \ No newline at end of file +} +#endif diff --git a/src/System.Management.Automation/engine/PSMI/Serialization/KnownMITypes.cs b/src/System.Management.Automation/engine/PSMI/Serialization/KnownMITypes.cs index 7f1401d4f..50b9ea2f0 100644 --- a/src/System.Management.Automation/engine/PSMI/Serialization/KnownMITypes.cs +++ b/src/System.Management.Automation/engine/PSMI/Serialization/KnownMITypes.cs @@ -1,4 +1,5 @@ -/********************************************************************++ +#if !CORECLR +/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -159,4 +160,5 @@ namespace System.Management.Automation #endregion private_fields } -} \ No newline at end of file +} +#endif diff --git a/src/System.Management.Automation/engine/PSMI/Serialization/MISerializer.cs b/src/System.Management.Automation/engine/PSMI/Serialization/MISerializer.cs index 5b954fd2f..110ade4f3 100644 --- a/src/System.Management.Automation/engine/PSMI/Serialization/MISerializer.cs +++ b/src/System.Management.Automation/engine/PSMI/Serialization/MISerializer.cs @@ -1,4 +1,5 @@ -/********************************************************************++ +#if !CORECLR +/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -40,4 +41,5 @@ namespace System.Management.Automation return internalSerializer.Serialize(source); } } -} \ No newline at end of file +} +#endif diff --git a/src/System.Management.Automation/engine/PSMI/Serialization/MITypeSerializationInfo.cs b/src/System.Management.Automation/engine/PSMI/Serialization/MITypeSerializationInfo.cs index b80fa6e09..5d1a460d5 100644 --- a/src/System.Management.Automation/engine/PSMI/Serialization/MITypeSerializationInfo.cs +++ b/src/System.Management.Automation/engine/PSMI/Serialization/MITypeSerializationInfo.cs @@ -1,4 +1,5 @@ -/********************************************************************++ +#if !CORECLR +/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -127,4 +128,5 @@ namespace System.Management.Automation #endregion private } -} \ No newline at end of file +} +#endif diff --git a/src/System.Management.Automation/engine/PSMI/Serialization/PSMISerializer.cs b/src/System.Management.Automation/engine/PSMI/Serialization/PSMISerializer.cs index 48c21674f..d8c0be05a 100644 --- a/src/System.Management.Automation/engine/PSMI/Serialization/PSMISerializer.cs +++ b/src/System.Management.Automation/engine/PSMI/Serialization/PSMISerializer.cs @@ -1,4 +1,5 @@ -using System.IO; +#if !CORECLR +using System.IO; using System.Linq; using System.Management.Automation.Internal; using System.Management.Automation.Language; @@ -55,4 +56,5 @@ namespace System.Management.Automation return serializer.Serialize(source); } } -} \ No newline at end of file +} +#endif diff --git a/src/System.Management.Automation/engine/PSVersionInfo.cs b/src/System.Management.Automation/engine/PSVersionInfo.cs index 619b7f2d4..d8c8f9b2a 100644 --- a/src/System.Management.Automation/engine/PSVersionInfo.cs +++ b/src/System.Management.Automation/engine/PSVersionInfo.cs @@ -76,7 +76,7 @@ namespace System.Management.Automation static internal Version GetBuildVersion() { - string assemblyPath = ClrFacade.GetAssemblyLocation(typeof(PSVersionInfo).GetTypeInfo().Assembly); + string assemblyPath = typeof(PSVersionInfo).GetTypeInfo().Assembly.Location; string buildVersion = FileVersionInfo.GetVersionInfo(assemblyPath).FileVersion; return new Version(buildVersion); } @@ -86,6 +86,11 @@ namespace System.Management.Automation // Gets the current WSMan stack version from the registry. private static Version GetWSManStackVersion() { + if (!Platform.HasRegistrySupport()) + { + return new Version(1, 0); + } + Version version = null; try diff --git a/src/System.Management.Automation/engine/SecurityManagerBase.cs b/src/System.Management.Automation/engine/SecurityManagerBase.cs index 0f594a7ff..8d89b859b 100644 --- a/src/System.Management.Automation/engine/SecurityManagerBase.cs +++ b/src/System.Management.Automation/engine/SecurityManagerBase.cs @@ -87,6 +87,15 @@ namespace System.Management.Automation CommandOrigin origin, PSHost host) { + // TODO:PSL this is a workaround since the exception below + // hides the internal issue of what's going on in terms of + // execution policy. + if (Platform.IsX()) + { + return; + } + + #if DEBUG // If we are debugging, let the unit tests swap the file from beneath us if(commandInfo.CommandType == CommandTypes.ExternalScript) diff --git a/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs b/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs index f25090481..d7e0f8e38 100644 --- a/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs @@ -1469,7 +1469,8 @@ namespace System.Management.Automation bool driveIsValid = true; // If the drive is auto-mounted, ensure that it still exists, or remove the drive. - if (drive.IsAutoMounted || IsAStaleVhdMountedDrive(drive)) + // note: not all platforms support drive auto-mounting + if (Platform.HasDriveAutoMounting() && (drive.IsAutoMounted || IsAStaleVhdMountedDrive(drive))) { driveIsValid = ValidateOrRemoveAutoMountedDrive(drive, lookupScope); } diff --git a/src/System.Management.Automation/engine/SessionStateNavigation.cs b/src/System.Management.Automation/engine/SessionStateNavigation.cs index 78ea6401c..c6a51d0f5 100644 --- a/src/System.Management.Automation/engine/SessionStateNavigation.cs +++ b/src/System.Management.Automation/engine/SessionStateNavigation.cs @@ -197,13 +197,13 @@ namespace System.Management.Automation bool isProviderQualified = false; bool isDriveQualified = false; string qualifier = null; - string pathNoQualifier = RemoveQualifier(path, out qualifier, out isProviderQualified, out isDriveQualified); + string pathNoQualifier = RemoveQualifier(path, provider, out qualifier, out isProviderQualified, out isDriveQualified); string result = GetParentPath(provider, pathNoQualifier, root, context); if (!String.IsNullOrEmpty(qualifier) && !String.IsNullOrEmpty(result)) { - result = AddQualifier(result, qualifier, isProviderQualified, isDriveQualified); + result = AddQualifier(result, provider, qualifier, isProviderQualified, isDriveQualified); } return result; @@ -214,7 +214,7 @@ namespace System.Management.Automation } } // GetParentPath - private string AddQualifier(string path, string qualifier, bool isProviderQualified, bool isDriveQualified) + private string AddQualifier(string path, ProviderInfo provider, string qualifier, bool isProviderQualified, bool isDriveQualified) { string result = path; @@ -225,7 +225,15 @@ namespace System.Management.Automation } else if (isDriveQualified) { - formatString = "{0}:{1}"; + // Porting note: on non-windows filesystem paths, there should be no colon in the path + if (provider.VolumeSeparatedByColon) + { + formatString = "{0}:{1}"; + } + else + { + formatString = "{0}{1}"; + } } result = @@ -246,6 +254,10 @@ namespace System.Management.Automation /// The path to strip the provider qualifier from. /// /// + /// + /// The provider that should handle the RemoveQualifier call. + /// + /// /// /// Returns the qualifier of the path. /// @@ -262,7 +274,7 @@ namespace System.Management.Automation /// The path without the qualifier. /// /// - private string RemoveQualifier(string path, out string qualifier, out bool isProviderQualified, out bool isDriveQualified) + private string RemoveQualifier(string path, ProviderInfo provider, out string qualifier, out bool isProviderQualified, out bool isDriveQualified) { Dbg.Diagnostics.Assert( path != null, @@ -291,9 +303,17 @@ namespace System.Management.Automation { isDriveQualified = true; - // Remove the drive name and colon + // Remove the drive name and colon, or just the drive name - result = path.Substring(qualifier.Length + 1); + // Porting note: on non-windows there is no colon for qualified paths + if (provider.VolumeSeparatedByColon) + { + result = path.Substring(qualifier.Length + 1); + } + else + { + result = path.Substring(qualifier.Length); + } } } diff --git a/src/System.Management.Automation/engine/SessionStateStrings.cs b/src/System.Management.Automation/engine/SessionStateStrings.cs index 8f6bd46fd..e932264be 100644 --- a/src/System.Management.Automation/engine/SessionStateStrings.cs +++ b/src/System.Management.Automation/engine/SessionStateStrings.cs @@ -28,15 +28,15 @@ namespace System.Management.Automation /// The default path separator used by the base implementation of the providers. /// /// - internal const char DefaultPathSeparator = '\\'; - internal const string DefaultPathSeparatorString = "\\"; + internal static readonly char DefaultPathSeparator = System.IO.Path.DirectorySeparatorChar; + internal static readonly string DefaultPathSeparatorString = DefaultPathSeparator.ToString(); /// /// The alternate path separator used by the base implementation of the providers. /// /// - internal const char AlternatePathSeparator = '/'; - internal const string AlternatePathSeparatorString = "/"; + internal static readonly char AlternatePathSeparator = System.IO.Path.AltDirectorySeparatorChar; + internal static readonly string AlternatePathSeparatorString = AlternatePathSeparator.ToString(); /// /// The default path prefix for remote paths. This is to mimic diff --git a/src/System.Management.Automation/engine/TransactedString.cs b/src/System.Management.Automation/engine/TransactedString.cs index ba4021e8e..fd30e601d 100644 --- a/src/System.Management.Automation/engine/TransactedString.cs +++ b/src/System.Management.Automation/engine/TransactedString.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -205,3 +206,5 @@ namespace Microsoft.PowerShell.Commands.Management } } // namespace Microsoft.Test.Management.Automation + +#endif diff --git a/src/System.Management.Automation/engine/TransactionManager.cs b/src/System.Management.Automation/engine/TransactionManager.cs index 87288e653..731175dc6 100644 --- a/src/System.Management.Automation/engine/TransactionManager.cs +++ b/src/System.Management.Automation/engine/TransactionManager.cs @@ -1,3 +1,4 @@ +#if !CORECLR #pragma warning disable 1634, 1691 /********************************************************************++ @@ -761,3 +762,5 @@ namespace System.Management.Automation.Internal } + +#endif diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index cca779a9c..8484e0bba 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -62,6 +62,15 @@ namespace System.Management.Automation return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7, h8)); } + /// + /// IsWinPEHost indicates if the machine on which PowerShell is hosted is WinPE or not. + /// This is a helper variable used to kep track if the IsWinPE() helper method has + /// already checked for the WinPE specific registry key or not. + /// If the WinPE specific registry key has not yet been checked even + /// once then this variable will point to null. + /// + internal static bool? isWinPEHost = null; + /// /// The existence of the following registry confirms that the host machine is a WinPE /// HKLM\System\CurrentControlSet\Control\MiniNT @@ -191,16 +200,7 @@ namespace System.Management.Automation private static string _pshome = null; - /// - /// Gets the application base for current monad version - /// - /// - /// applicationbase path for current monad version installation - /// - /// - /// if caller doesn't have permission to read the key - /// - internal static string GetApplicationBase(string shellId) + internal static string GetApplicationBaseFromRegistry(string shellId) { bool wantPsHome = (object) shellId == (object) DefaultPowerShellShellID; if (wantPsHome && _pshome != null) @@ -221,6 +221,30 @@ namespace System.Management.Automation } } + return null; + } + + /// + /// Gets the application base for current monad version + /// + /// + /// applicationbase path for current monad version installation + /// + /// + /// if caller doesn't have permission to read the key + /// + internal static string GetApplicationBase(string shellId) + { + if (!Platform.IsX()) + { + // try to get the path from the registry first + string result = GetApplicationBaseFromRegistry(shellId); + if (result != null) + { + return result; + } + } + #if CORECLR // Use the location of SMA.dll as the application base // Assembly.GetEntryAssembly is not in CoreCLR. GAC is not in CoreCLR. Assembly assembly = typeof(PSObject).GetTypeInfo().Assembly; @@ -275,7 +299,16 @@ namespace System.Management.Automation } // And built-in modules - string progFileDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "WindowsPowerShell", "Modules"); + string progFileDir; + if (Platform.IsX()) + { + progFileDir = Path.Combine(appBase, "Modules"); + } + else + { + progFileDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "WindowsPowerShell", "Modules"); + } + if (!string.IsNullOrEmpty(progFileDir)) { baseDirectories.Add(Path.Combine(progFileDir, "PackageManagement")); @@ -330,31 +363,59 @@ namespace System.Management.Automation /// Checks if host machine is WinPE /// internal static bool IsWinPEHost() + { + if (Platform.HasRegistrySupport()) + { + return WinIsWinPEHost(); + } + else + { + return false; + } + } + + internal static bool WinIsWinPEHost() { RegistryKey winPEKey = null; - try + if (!isWinPEHost.HasValue) { - // The existence of the following registry confirms that the host machine is a WinPE - // HKLM\System\CurrentControlSet\Control\MiniNT - winPEKey = Registry.LocalMachine.OpenSubKey(WinPEIdentificationRegKey); - - return winPEKey != null; - } - catch (ArgumentException) { } - catch (SecurityException) { } - catch (ObjectDisposedException) { } - finally - { - if (winPEKey != null) + try { - winPEKey.Dispose(); + // The existence of the following registry confirms that the host machine is a WinPE + // HKLM\System\CurrentControlSet\Control\MiniNT + winPEKey = Registry.LocalMachine.OpenSubKey(WinPEIdentificationRegKey); + + if (null != winPEKey) + { + isWinPEHost = true; + } + else + { + isWinPEHost = false; + } + } + catch (ArgumentException) { } + catch (SecurityException) { } + catch (ObjectDisposedException) { } + finally + { + if (winPEKey != null) + { + winPEKey.Dispose(); + } } } - return false; - } - + if (isWinPEHost.HasValue) + { + return (bool)isWinPEHost; + } + else + { + return false; + } + } #region Versioning related methods @@ -530,7 +591,8 @@ namespace System.Management.Automation /// /// Profile uses this to control profile loading. /// - internal static string ProductNameForDirectory = "WindowsPowerShell"; + internal static string ProductNameForDirectory = + Platform.IsWindows() ? "WindowsPowerShell" : Platform.ProductNameForDirectory; /// /// The name of the subdirectory that contains packages. @@ -540,7 +602,7 @@ namespace System.Management.Automation /// /// The partial path to the DSC module directory /// - internal static string DscModuleDirectory = "WindowsPowerShell\\Modules"; + internal static string DscModuleDirectory = Path.Combine("WindowsPowerShell", "Modules"); internal static string GetRegistryConfigurationPrefix() { @@ -570,8 +632,18 @@ namespace System.Management.Automation return GetGroupPolicySetting(groupPolicyBase, settingName, preferenceOrder); } + // We use a static to avoid creating "extra garbage." + private static Dictionary _emptyDictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); + internal static Dictionary GetGroupPolicySetting(string groupPolicyBase, string settingName, RegistryKey[] preferenceOrder) { + if (!Platform.HasGroupPolicySupport()) + { + // Porting note: No group policy support means we have an empty set of + // policies. + return _emptyDictionary; + } + lock (cachedGroupPolicySettings) { // Return cached information, if we have it @@ -873,10 +945,21 @@ namespace System.Management.Automation internal static bool IsAdministrator() { - System.Security.Principal.WindowsIdentity currentIdentity = System.Security.Principal.WindowsIdentity.GetCurrent(); - System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(currentIdentity); + // Porting note: only Windows supports the + // SecurityPrincipal API of .net for now assume Linux + // users have no concept of "Administrator" for now and + // specifically do not map to a check for root user + if (Platform.IsWindows()) + { + System.Security.Principal.WindowsIdentity currentIdentity = System.Security.Principal.WindowsIdentity.GetCurrent(); + System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(currentIdentity); - return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator); + return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator); + } + else + { + return false; + } } internal static bool NativeItemExists(string path) @@ -887,9 +970,38 @@ namespace System.Management.Automation return NativeItemExists(path, out unusedIsDirectory, out unusedException); } - // This is done through P/Invoke since File.Exists and Directory.Exists pay 13% performance degradation - // through the CAS checks, and are terribly slow for network paths. internal static bool NativeItemExists(string path, out bool isDirectory, out Exception exception) + { + if (Platform.UseDotNetToQueryFileAttributes()) + { + // TODO:PSL replace by System.IO.File.GetAttributes + exception = null; + if (NativeDirectoryExists(path)) + { + isDirectory = true; + return true; + } + else if (NativeFileExists(path)) + { + isDirectory = false; + return true; + } + else + { + isDirectory = false; + return false; + } + } + else + { + // This is done through P/Invoke since File.Exists and Directory.Exists + // pay 13% performance degradation through the CAS checks, and are + // terribly slow for network paths. + return WinNativeItemExists(path,out isDirectory,out exception); + } + } + + internal static bool WinNativeItemExists(string path, out bool isDirectory, out Exception exception) { exception = null; @@ -933,9 +1045,21 @@ namespace System.Management.Automation return true; } - // This is done through P/Invoke since we pay 13% performance degradation - // through the CAS checks required by File.Exists and Directory.Exists internal static bool NativeFileExists(string path) + { + if (Platform.UseDotNetToQueryFileAttributes()) + { + return System.IO.File.Exists(path); + } + else + { + // This is done through P/Invoke since we pay 13% performance degradation + // through the CAS checks required by File.Exists and Directory.Exists + return WinNativeFileExists(path); + } + } + + internal static bool WinNativeFileExists(string path) { bool isDirectory; Exception ioException; @@ -952,6 +1076,18 @@ namespace System.Management.Automation // This is done through P/Invoke since we pay 13% performance degradation // through the CAS checks required by File.Exists and Directory.Exists internal static bool NativeDirectoryExists(string path) + { + if (Platform.UseDotNetToQueryFileAttributes()) + { + return System.IO.Directory.Exists(path); + } + else + { + return WinNativeDirectoryExists(path); + } + } + + internal static bool WinNativeDirectoryExists(string path) { bool isDirectory; Exception ioException; @@ -966,6 +1102,31 @@ namespace System.Management.Automation } internal static void NativeEnumerateDirectory(string directory, out List directories, out List files) + { + if (Platform.UseDotNetToQueryFileAttributes()) + { + IEnumerable fileEnum = System.IO.Directory.EnumerateFiles(directory); + IEnumerable dirEnum = System.IO.Directory.EnumerateDirectories(directory); + + files = new List(); + directories = new List(); + + foreach (string entry in fileEnum) + { + files.Add(directory + "/" + entry); + } + foreach (string entry in dirEnum) + { + directories.Add(directory + "/" + entry); + } + } + else + { + WinNativeEnumerateDirectory(directory, out directories, out files); + } + } + + internal static void WinNativeEnumerateDirectory(string directory, out List directories, out List files) { IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); NativeMethods.WIN32_FIND_DATA findData; @@ -1030,6 +1191,10 @@ namespace System.Management.Automation internal static bool PathIsUnc(string path) { + if (!Platform.HasUNCSupport()) + { + return false; + } Uri uri; return !string.IsNullOrEmpty(path) && Uri.TryCreate(path, UriKind.Absolute, out uri) && uri.IsUnc; } @@ -1083,8 +1248,25 @@ namespace System.Management.Automation public static extern bool FindClose(IntPtr hFindFile); } + // Porting note: PublicKeyToken must be null if code signed + // assemblies aren't supported + private static string strongNamePublicKeyToken + { + get + { + if (Platform.UsesCodeSignedAssemblies()) + { + return "31bf3856ad364e35"; + } + else + { + return "null"; + } + } + } + internal static readonly string PowerShellAssemblyStrongNameFormat = - "{0}, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; + "{0}, Version=3.0.0.0, Culture=neutral, PublicKeyToken={1}"; internal static readonly HashSet PowerShellAssemblies = new HashSet(StringComparer.OrdinalIgnoreCase) @@ -1141,7 +1323,8 @@ namespace System.Management.Automation if ((fixedName != null) && PowerShellAssemblies.Contains(fixedName)) { - return string.Format(CultureInfo.InvariantCulture, PowerShellAssemblyStrongNameFormat, fixedName); + return string.Format(CultureInfo.InvariantCulture, PowerShellAssemblyStrongNameFormat, + fixedName, strongNamePublicKeyToken); } } diff --git a/src/System.Management.Automation/engine/hostifaces/History.cs b/src/System.Management.Automation/engine/hostifaces/History.cs index 167381725..dfeccead5 100644 --- a/src/System.Management.Automation/engine/hostifaces/History.cs +++ b/src/System.Management.Automation/engine/hostifaces/History.cs @@ -1212,38 +1212,11 @@ namespace Microsoft.PowerShell.Commands { ps.AddScript(commandToInvoke); - EventHandler debugAdded = delegate(Object sender, DataAddedEventArgs e) { DebugRecord record = (DebugRecord)((PSDataCollection)sender)[e.Index]; WriteDebug(record.Message); }; - EventHandler errorAdded = delegate(Object sender, DataAddedEventArgs e) { ErrorRecord record = (ErrorRecord)((PSDataCollection)sender)[e.Index]; WriteError(record); }; - EventHandler informationAdded = delegate(Object sender, DataAddedEventArgs e) { InformationRecord record = (InformationRecord)((PSDataCollection)sender)[e.Index]; WriteInformation(record); }; - EventHandler progressAdded = delegate(Object sender, DataAddedEventArgs e) { ProgressRecord record = (ProgressRecord)((PSDataCollection)sender)[e.Index]; WriteProgress(record); }; - EventHandler verboseAdded = delegate(Object sender, DataAddedEventArgs e) { VerboseRecord record = (VerboseRecord)((PSDataCollection)sender)[e.Index]; WriteVerbose(record.Message); }; - EventHandler warningAdded = delegate(Object sender, DataAddedEventArgs e) { WarningRecord record = (WarningRecord)((PSDataCollection)sender)[e.Index]; WriteWarning(record.Message); }; + ps.AddCommand("out-default"); + ps.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); - ps.Streams.Debug.DataAdded += debugAdded; - ps.Streams.Error.DataAdded += errorAdded; - ps.Streams.Information.DataAdded += informationAdded; - ps.Streams.Progress.DataAdded += progressAdded; - ps.Streams.Verbose.DataAdded += verboseAdded; - ps.Streams.Warning.DataAdded += warningAdded; - - try - { - Collection results = ps.Invoke(); - if (results.Count > 0) - { - WriteObject(results, true); - } - pipeline.RemoveFromInvokeHistoryEntryList(entry); - } - finally - { - ps.Streams.Debug.DataAdded -= debugAdded; - ps.Streams.Error.DataAdded -= errorAdded; - ps.Streams.Information.DataAdded -= informationAdded; - ps.Streams.Progress.DataAdded -= progressAdded; - ps.Streams.Verbose.DataAdded -= verboseAdded; - ps.Streams.Warning.DataAdded -= warningAdded; - } + ps.Invoke(); + pipeline.RemoveFromInvokeHistoryEntryList(entry); } } diff --git a/src/System.Management.Automation/engine/hostifaces/NativeCultureResolver.cs b/src/System.Management.Automation/engine/hostifaces/NativeCultureResolver.cs index 74b4f0519..1fea216fd 100644 --- a/src/System.Management.Automation/engine/hostifaces/NativeCultureResolver.cs +++ b/src/System.Management.Automation/engine/hostifaces/NativeCultureResolver.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. @@ -494,4 +495,5 @@ namespace Microsoft.PowerShell #endregion } -} \ No newline at end of file +} +#endif diff --git a/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs b/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs index f0d6d4c77..1e4b2f2bf 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -218,3 +219,5 @@ namespace System.Management.Automation + +#endif diff --git a/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs b/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs index 5d0c392bb..2f0fa35d5 100644 --- a/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs +++ b/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs @@ -46,15 +46,6 @@ namespace Microsoft.PowerShell.Commands /// internal static string WinPEIdentificationRegKey = @"System\CurrentControlSet\Control\MiniNT"; - /// - /// IsWinPEHost indicates if the machine on which PowerShell is hosted is WinPE or not. - /// This is a helper variable used to kep track if the IsWinPE() helper method has - /// already checked for the WinPE specific registry key or not. - /// If the WinPE specific registry key has not yet been checked even - /// once then this variable will point to null. - /// - internal static bool? isWinPEHost = null; - internal static bool HasRepeatingRunspaces(PSSession[] runspaceInfos) { if (runspaceInfos == null) @@ -105,9 +96,15 @@ namespace Microsoft.PowerShell.Commands /// internal static void CheckRemotingCmdletPrerequisites() { + //If the operating system (ie Linux) does not support the registry, simply return to avoid calls to the Windows registry. + if (!Platform.HasRegistrySupport()) + { + return; + } + bool notSupported = true; String WSManKeyPath = "Software\\Microsoft\\Windows\\CurrentVersion\\WSMAN\\"; - + CheckHostRemotingPrerequisites(); try @@ -160,46 +157,6 @@ namespace Microsoft.PowerShell.Commands } } - /// - /// IsWinPEHost is a helper method used to identify if the - /// PowerShell is hosted on a WinPE machine. - /// - internal static bool IsWinPEHost() - { - RegistryKey wsManKey = null; - - if (isWinPEHost == null) - { - try - { - // The existence of the following registry confirms that the host machine is a WinPE - // HKLM\System\CurrentControlSet\Control\MiniNT - wsManKey = Registry.LocalMachine.OpenSubKey(WinPEIdentificationRegKey); - - if (null != wsManKey) - { - isWinPEHost = true; - } - else - { - isWinPEHost = false; - } - } - catch (ArgumentException) { } - catch (System.Security.SecurityException) { } - catch (ObjectDisposedException) { } - finally - { - if (wsManKey != null) - { - wsManKey.Dispose(); - } - } - } - - return isWinPEHost== true? true: false; - } - /// /// Facilitates to check if remoting is supported on the host machine. /// PowerShell remoting is supported on all Windows SQU's except WinPE. @@ -213,7 +170,7 @@ namespace Microsoft.PowerShell.Commands { // A registry key indicates if the SKU is WINPE. If this turns out to be true, // then an InValidOperation exception is thrown. - bool isWinPEHost = IsWinPEHost(); + bool isWinPEHost = Utils.IsWinPEHost(); if (isWinPEHost) { // WSMan is not supported on this platform diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs index b94a180cb..d6b155e47 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs @@ -523,8 +523,12 @@ namespace System.Management.Automation.Remoting SyncObject = new object(); // All PowerShell instances will start with the named pipe - // and listener created and running. - IPCNamedPipeServerEnabled = true; + // and listner created and running. + if (Platform.IsWindows()) + { + IPCNamedPipeServerEnabled = true; + } + CreateIPCNamedPipeServerSingleton(); #if !CORECLR // There is only one AppDomain per application in CoreCLR, which would be the default CreateAppDomainUnloadHandler(); diff --git a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs index ec004948d..886483780 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs @@ -662,7 +662,7 @@ namespace System.Management.Automation.Remoting { try { - result = Assembly.Load(new AssemblyName(assemblyName)); + result = ClrFacade.Load(new AssemblyName(assemblyName)); } catch (FileLoadException e) { diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs index 2ee10a2a7..4e0ac2d1e 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs @@ -2301,7 +2301,11 @@ namespace System.Management.Automation.Remoting.Client #region DllImports ClientAPI +#if !LINUX internal const string WSManApiDll = @"WsmSvc.dll"; +#else + internal const string WSManApiDll = @"libpsrpomiprov"; +#endif /// /// This API is used to initialize the WinRM client; @@ -2541,6 +2545,7 @@ namespace System.Management.Automation.Remoting.Client IntPtr asyncCallback, [In, Out] ref IntPtr shellOperationHandle); + /// /// /// @@ -2899,7 +2904,8 @@ namespace System.Management.Automation.Remoting.Client int flags, int errorCode, [MarshalAs(UnmanagedType.LPWStr)] string extendedInformation); - + + internal enum WSManFlagReceive : int { /// @@ -2963,7 +2969,20 @@ namespace System.Management.Automation.Remoting.Client IntPtr requestDetails, int flags, IntPtr context); - +#if LINUX + /// + /// Registers the shutdown callback. + /// + /// Specifies the resource URI, options, locale, shutdown flag, and handle for the request. + /// Callback to be executed on shutdown + /// + /// + [DllImport(WSManNativeApi.WSManApiDll, SetLastError = false, CharSet = CharSet.Unicode)] + internal static extern void WSManPluginRegisterShutdownCallback( + IntPtr requestDetails, + IntPtr shutdownCallback, + IntPtr shutdownContext); +#endif #endregion } @@ -2999,6 +3018,11 @@ namespace System.Management.Automation.Remoting.Client IntPtr requestDetails, int flags, IntPtr context); + + void WSManPluginRegisterShutdownCallback( + IntPtr requestDetails, + IntPtr shutdownCallback, + IntPtr shutdownContext); } /// @@ -3041,5 +3065,15 @@ namespace System.Management.Automation.Remoting.Client { return WSManNativeApi.WSManPluginReportContext(requestDetails, flags, context); } + + void IWSManNativeApiFacade.WSManPluginRegisterShutdownCallback( + IntPtr requestDetails, + IntPtr shutdownCallback, + IntPtr shutdownContext) + { +#if LINUX + WSManNativeApi.WSManPluginRegisterShutdownCallback(requestDetails, shutdownCallback, shutdownContext); +#endif + } } } diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs index 35199fad2..c9fdc61a2 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs @@ -170,14 +170,14 @@ namespace System.Management.Automation.Remoting #if !CORECLR // Register our remoting handler for crashes AppDomain currentDomain = AppDomain.CurrentDomain; - currentDomain.UnhandledException += + currentDomain.UnhandledException += new UnhandledExceptionEventHandler(WSManPluginInstance.UnhandledExceptionHandler); // Register our Watson handler for crash reports in server mode System.Management.Automation.WindowsErrorReporting.RegisterWindowsErrorReporting(true); #endif } - + #endregion /// @@ -278,10 +278,20 @@ namespace System.Management.Automation.Remoting try { PSSenderInfo senderInfo = GetPSSenderInfo(requestDetails.senderDetails); - + // inbound shell information is already verified by pwrshplugin.dll.. so no need // to verify here. - WSManPluginServerTransportManager serverTransportMgr = new WSManPluginServerTransportManager(BaseTransportManager.DefaultFragmentSize, new PSRemotingCryptoHelperServer()); + WSManPluginServerTransportManager serverTransportMgr; + + if (Platform.IsWindows()) + { + serverTransportMgr = new WSManPluginServerTransportManager(BaseTransportManager.DefaultFragmentSize, new PSRemotingCryptoHelperServer()); + } + + else + { + serverTransportMgr = new WSManPluginServerTransportManager(BaseTransportManager.DefaultFragmentSize, null); + } PSEtwLog.LogAnalyticInformational(PSEventId.ServerCreateRemoteSession, PSOpcode.Connect, PSTask.None, @@ -305,7 +315,7 @@ namespace System.Management.Automation.Remoting { ReportOperationComplete(requestDetails, WSManPluginErrorCodes.OutOfMemory); return; - } + } // Create a shell session wrapper to track and service future interacations. mgdShellSession = new WSManPluginShellSession(requestDetails, serverTransportMgr, remoteShellSession, context); @@ -371,34 +381,53 @@ namespace System.Management.Automation.Remoting } bool isRegisterWaitForSingleObjectSucceeded = true; - - //always synchronize calls to OperationComplete once notification handle is registered.. else duplicate OperationComplete calls are bound to happen - lock (mgdShellSession.shellSyncObject) - { + + //always synchronize calls to OperationComplete once notification handle is registered.. else duplicate OperationComplete calls are bound to happen + lock (mgdShellSession.shellSyncObject) + { mgdShellSession.registeredShutdownNotification = 1; // Wrap the provided handle so it can be passed to the registration function - SafeWaitHandle safeWaitHandle = new SafeWaitHandle(requestDetails.shutdownNotificationHandle, false); // Owned by WinRM EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset); - ClrFacade.SetSafeWaitHandle(eventWaitHandle, safeWaitHandle); + + if (Platform.IsWindows()) + { + SafeWaitHandle safeWaitHandle = new SafeWaitHandle(requestDetails.shutdownNotificationHandle, false); // Owned by WinRM + ClrFacade.SetSafeWaitHandle(eventWaitHandle, safeWaitHandle); + } + else + { + //On non-windows platforms the shutdown notification is done through a callback instead of a windows event handle. + //Register the callback and this will then signal the event. Note, the gch object is deleted in the shell shutdown + //notification that will always come in to shut down the operation. + + GCHandle gch = GCHandle.Alloc(eventWaitHandle); + IntPtr p = GCHandle.ToIntPtr(gch); + + wsmanPinvokeStatic.WSManPluginRegisterShutdownCallback( + requestDetails.unmanagedHandle, + WSManPluginManagedEntryWrapper.workerPtrs.UnmanagedStruct.wsManPluginShutdownCallbackNative, + p); + } + mgdShellSession.registeredShutDownWaitHandle = ThreadPool.RegisterWaitForSingleObject( - eventWaitHandle, - new WaitOrTimerCallback(WSManPluginManagedEntryWrapper.PSPluginOperationShutdownCallback), - context, - -1, // INFINITE - true); // TODO: Do I need to worry not being able to set missing WT_TRANSFER_IMPERSONATION? + eventWaitHandle, + new WaitOrTimerCallback(WSManPluginManagedEntryWrapper.PSPluginOperationShutdownCallback), + context, + -1, // INFINITE + true); // TODO: Do I need to worry not being able to set missing WT_TRANSFER_IMPERSONATION? if (null == mgdShellSession.registeredShutDownWaitHandle) { isRegisterWaitForSingleObjectSucceeded = false; } } - + if (!isRegisterWaitForSingleObjectSucceeded) { mgdShellSession.registeredShutdownNotification = 0; WSManPluginInstance.ReportWSManOperationComplete( - requestDetails, + requestDetails, WSManPluginErrorCodes.ShutdownRegistrationFailed); DeleteFromActiveShellSessions(requestDetails.unmanagedHandle); return; @@ -410,6 +439,7 @@ namespace System.Management.Automation.Remoting { mgdShellSession.SendOneItemToSessionHelper(convertedBase64, WSManPluginConstants.SupportedInputStream); } + } catch(System.Exception e) { @@ -440,12 +470,12 @@ namespace System.Management.Automation.Remoting /// internal void CloseShellOperation( WSManPluginOperationShutdownContext context) - { + { PSEtwLog.LogAnalyticInformational(PSEventId.ServerCloseOperation, PSOpcode.Disconnect, PSTask.None, PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, - ((IntPtr)context.shellContext).ToString(), - ((IntPtr)context.commandContext).ToString(), + ((IntPtr)context.shellContext).ToString(), + ((IntPtr)context.commandContext).ToString(), context.isReceiveOperation.ToString()); WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(context.shellContext); diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs index 9e057da46..cf55c288c 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs @@ -97,6 +97,13 @@ namespace System.Management.Automation.Remoting [MarshalAs(UnmanagedType.LPWStr)] string commandLine, IntPtr arguments); + /// + /// Delegate that is passed to native layer for callback on operation shutdown notifications + /// + /// IntPtr + delegate void WSMPluginOperationShutdownDelegate( + IntPtr shutdownContext); + /// /// /// @@ -171,27 +178,27 @@ namespace System.Management.Automation.Remoting bool timedOut); /// - /// + /// /// /// PVOID delegate void WSMShutdownPluginDelegate( IntPtr pluginContext); /// - /// + /// /// internal sealed class WSManPluginEntryDelegates : IDisposable { #region Private Members - // Holds the delegate pointers in a structure that has identical layout to the native structure. + // Holds the delegate pointers in a structure that has identical layout to the native structure. private WSManPluginEntryDelegatesInternal unmanagedStruct = new WSManPluginEntryDelegatesInternal(); internal WSManPluginEntryDelegatesInternal UnmanagedStruct { get { return unmanagedStruct; } } - // Flag: Has Dispose already been called? + // Flag: Has Dispose already been called? private bool disposed = false; /// @@ -206,6 +213,7 @@ namespace System.Management.Automation.Remoting private GCHandle pluginSignalGCHandle; private GCHandle pluginConnectGCHandle; private GCHandle shutdownPluginGCHandle; + private GCHandle WSMPluginOperationShutdownGCHandle; #endregion @@ -318,10 +326,16 @@ namespace System.Management.Automation.Remoting this.shutdownPluginGCHandle = GCHandle.Alloc(shutdownPlugin); unmanagedStruct.wsManPluginShutdownPluginCallbackNative = Marshal.GetFunctionPointerForDelegate(shutdownPlugin); } + if(!Platform.IsWindows()) + { + WSMPluginOperationShutdownDelegate pluginShutDownDelegate = new WSMPluginOperationShutdownDelegate(WSManPluginManagedEntryWrapper.WSManPSShutdown); + this.WSMPluginOperationShutdownGCHandle = GCHandle.Alloc(pluginShutDownDelegate); + unmanagedStruct.wsManPluginShutdownCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginShutDownDelegate); + } } /// - /// + /// /// private void CleanUpDelegates() { @@ -337,6 +351,10 @@ namespace System.Management.Automation.Remoting this.pluginSignalGCHandle.Free(); this.pluginConnectGCHandle.Free(); this.shutdownPluginGCHandle.Free(); + if(!Platform.IsWindows()) + { + this.WSMPluginOperationShutdownGCHandle.Free(); + } } } @@ -396,11 +414,18 @@ namespace System.Management.Automation.Remoting internal IntPtr wsManPluginSignalCallbackNative; /// - /// WSManPluginConnectCallbackNative + /// WSManPluginConnectCallbackNative /// [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr wsManPluginConnectCallbackNative; - } + + /// + /// WSManPluginCommandCallbackNative + /// + [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] + internal IntPtr wsManPluginShutdownCallbackNative; + + } } /// @@ -417,7 +442,7 @@ namespace System.Management.Automation.Remoting /// /// Immutable container that holds the delegates and their unmanaged pointers. /// - private static WSManPluginEntryDelegates workerPtrs = new WSManPluginEntryDelegates(); + internal static WSManPluginEntryDelegates workerPtrs = new WSManPluginEntryDelegates(); #region Managed Entry Points @@ -578,6 +603,19 @@ namespace System.Management.Automation.Remoting WSManPluginInstance.PerformWSManPluginCommand(pluginContext, requestDetails, flags, shellContext, commandLine, arguments); } + /// + /// Operation shutdown notification that was registered with the native layer for each of the shellCreate operations. + /// + /// IntPtr + public static void WSManPSShutdown( + IntPtr shutdownContext) + { + GCHandle gch = GCHandle.FromIntPtr(shutdownContext); + EventWaitHandle eventHandle = (EventWaitHandle) gch.Target; + eventHandle.Set(); + gch.Free(); + } + /// /// /// @@ -693,9 +731,9 @@ namespace System.Management.Automation.Remoting WSManPluginInstance.PerformWSManPluginSignal(pluginContext, requestDetails, flags, shellContext, commandContext, code); } - + /// - /// Callback used to register with thread pool to notify when a plugin operation shutsdown. + /// Callback used to register with thread pool to notify when a plugin operation shuts down. /// Conforms to: /// public delegate void WaitOrTimerCallback( Object state, bool timedOut ) /// @@ -716,7 +754,7 @@ namespace System.Management.Automation.Remoting WSManPluginInstance.PerformCloseOperation(context); } - + #endregion } diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs index 8a21e1adf..b311c2f39 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs @@ -265,7 +265,7 @@ namespace System.Management.Automation.Remoting //RACE TO BE FIXED - As soon as this API is called, WinRM service will send CommandResponse back and Signal is expected anytime // If Signal comes and executes before registering the notification handle, cleanup will be messed result = WSManNativeApi.WSManPluginReportContext(creationRequestDetails.unmanagedHandle, 0, creationRequestDetails.unmanagedHandle); - if (WSManPluginConstants.ExitCodeSuccess == result) + if (Platform.IsWindows() && (WSManPluginConstants.ExitCodeSuccess == result)) { registeredShutdownNotification = 1; diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs index 757d774a5..9db15cbf3 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs @@ -332,22 +332,24 @@ namespace System.Management.Automation.Remoting isRequestPending = true; this.requestDetails = requestDetails; - // Wrap the provided handle so it can be passed to the registration function - SafeWaitHandle safeWaitHandle = new SafeWaitHandle(requestDetails.shutdownNotificationHandle, false); // Owned by WinRM - EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset); - ClrFacade.SetSafeWaitHandle(eventWaitHandle, safeWaitHandle); - - this.registeredShutDownWaitHandle = ThreadPool.RegisterWaitForSingleObject( - eventWaitHandle, - new WaitOrTimerCallback(WSManPluginManagedEntryWrapper.PSPluginOperationShutdownCallback), - shutDownContext, - -1, // INFINITE - true); // TODO: Do I need to worry not being able to set missing WT_TRANSFER_IMPERSONATION? - if (null == this.registeredShutDownWaitHandle) + if (Platform.IsWindows()) { - isRegisterWaitForSingleObjectSucceeded = false; - } + // Wrap the provided handle so it can be passed to the registration function + SafeWaitHandle safeWaitHandle = new SafeWaitHandle(requestDetails.shutdownNotificationHandle, false); // Owned by WinRM + EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset); + ClrFacade.SetSafeWaitHandle(eventWaitHandle, safeWaitHandle); + this.registeredShutDownWaitHandle = ThreadPool.RegisterWaitForSingleObject( + eventWaitHandle, + new WaitOrTimerCallback(WSManPluginManagedEntryWrapper.PSPluginOperationShutdownCallback), + shutDownContext, + -1, // INFINITE + true); // TODO: Do I need to worry not being able to set missing WT_TRANSFER_IMPERSONATION? + if (null == this.registeredShutDownWaitHandle) + { + isRegisterWaitForSingleObjectSucceeded = false; + } + } // release thread waiting to send data to the client. waitHandle.Set(); } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs index efc2c3658..692aeaf80 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs @@ -336,17 +336,24 @@ namespace System.Management.Automation // Flow the impersonation policy to pipeline execution thread // only if the current thread is impersonated (Delegation is // also a kind of impersonation). - WindowsIdentity currentThreadIdentity = WindowsIdentity.GetCurrent(); - switch (currentThreadIdentity.ImpersonationLevel) + if (Platform.IsWindows()) { + WindowsIdentity currentThreadIdentity = WindowsIdentity.GetCurrent(); + switch (currentThreadIdentity.ImpersonationLevel) + { - case TokenImpersonationLevel.Impersonation: - case TokenImpersonationLevel.Delegation: - settings.FlowImpersonationPolicy = true; - break; - default: - settings.FlowImpersonationPolicy = false; - break; + case TokenImpersonationLevel.Impersonation: + case TokenImpersonationLevel.Delegation: + settings.FlowImpersonationPolicy = true; + break; + default: + settings.FlowImpersonationPolicy = false; + break; + } + } + else + { + settings.FlowImpersonationPolicy = false; } settings.AddToHistory = addToHistory; diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs index 7f9a1e2ff..d1e7d7c41 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs @@ -170,8 +170,11 @@ namespace System.Management.Automation.Remoting _senderInfo = senderInfo; _configProviderId = configurationProviderId; _initParameters = initializationParameters; - _cryptoHelper = (PSRemotingCryptoHelperServer)transportManager.CryptoHelper; - _cryptoHelper.Session = this; + if (Platform.IsWindows()) + { + _cryptoHelper = (PSRemotingCryptoHelperServer)transportManager.CryptoHelper; + _cryptoHelper.Session = this; + } _context = new ServerRemoteSessionContext(); _sessionDSHandler = new ServerRemoteSessionDSHandlerlImpl(this, transportManager); diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index a8e84bc47..9a9ef31e8 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -555,6 +555,8 @@ namespace System.Management.Automation.Language return (errorSuggestion ?? NullResult(target)).WriteToDebugLog(this); } +#if !CORECLR + // .NET Core does not have a full DataTable type if (targetValue is DataTable) { // Generate: @@ -581,6 +583,7 @@ namespace System.Management.Automation.Language target), GetRestrictions(target))).WriteToDebugLog(this); } +#endif if (IsComObject(targetValue)) { @@ -667,12 +670,26 @@ namespace System.Management.Automation.Language return (result == DynamicMetaObjectExtensions.FakeError) ? null : result; } - private static readonly TypeInfo ComObjectTypeInfo = typeof(object).GetTypeInfo().Assembly.GetType("System.__ComObject").GetTypeInfo(); + // This is to reduce the runtime overhead of the feature query + private static readonly TypeInfo ComObjectTypeInfo = GetComObjectType(); + + private static TypeInfo GetComObjectType() + { + if (Platform.HasCom()) + { + return typeof(object).GetTypeInfo().Assembly.GetType("System.__ComObject").GetTypeInfo(); + } + else + { + return null; + } + } internal static bool IsComObject(object obj) { - // we can't use System.Runtime.InteropServices.Marshal.IsComObject(obj) since it doesn't work in partial trust - return obj != null && ComObjectTypeInfo.IsAssignableFrom(obj.GetType().GetTypeInfo()); + // Platform notes: We can't use System.Runtime.InteropServices.Marshal.IsComObject(obj) + // since it doesn't work in partial trust + return obj != null && ComObjectTypeInfo != null && ComObjectTypeInfo.IsAssignableFrom(obj.GetType().GetTypeInfo()); } private static IEnumerator AutomationNullRule(CallSite site, object obj) diff --git a/src/System.Management.Automation/help/HelpSystem.cs b/src/System.Management.Automation/help/HelpSystem.cs index ca87f9c15..84801679e 100644 --- a/src/System.Management.Automation/help/HelpSystem.cs +++ b/src/System.Management.Automation/help/HelpSystem.cs @@ -667,7 +667,7 @@ namespace System.Management.Automation } else { - providerAssembly = Assembly.Load(providerInfo.AssemblyName); + providerAssembly = ClrFacade.Load(providerInfo.AssemblyName); } try diff --git a/src/System.Management.Automation/logging/MshLog.cs b/src/System.Management.Automation/logging/MshLog.cs index cd2c5c1f2..e380c51a3 100644 --- a/src/System.Management.Automation/logging/MshLog.cs +++ b/src/System.Management.Automation/logging/MshLog.cs @@ -171,6 +171,8 @@ namespace System.Management.Automation } #endif Collection providers = new Collection(); + // Porting note: Linux does not support ETW +#if !NOETW && !LINUX try { #if !CORECLR //TODO:CORECLR EventLogLogProvider not handled yet @@ -195,7 +197,7 @@ namespace System.Management.Automation // when running as non-admin user. In that case, we will default // to dummy log. } - +#endif providers.Add(new DummyLogProvider()); return providers; } diff --git a/src/System.Management.Automation/logging/eventlog/EventLogLogProvider.cs b/src/System.Management.Automation/logging/eventlog/EventLogLogProvider.cs index ccd27ac50..458c90ca1 100644 --- a/src/System.Management.Automation/logging/eventlog/EventLogLogProvider.cs +++ b/src/System.Management.Automation/logging/eventlog/EventLogLogProvider.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -40,7 +41,7 @@ namespace System.Management.Automation _eventLog = new EventLog(); _eventLog.Source = source; - _resourceManager = new ResourceManager("Logging", System.Reflection.Assembly.GetExecutingAssembly()); + _resourceManager = new ResourceManager("System.Management.Automation.Logging", System.Reflection.Assembly.GetExecutingAssembly()); } internal string SetupEventSource(string shellId) @@ -690,3 +691,5 @@ namespace System.Management.Automation #endregion Event Message } } + +#endif diff --git a/src/System.Management.Automation/namespaces/FileSystemContentStream.cs b/src/System.Management.Automation/namespaces/FileSystemContentStream.cs index 97cf6ddb1..15df54f65 100644 --- a/src/System.Management.Automation/namespaces/FileSystemContentStream.cs +++ b/src/System.Management.Automation/namespaces/FileSystemContentStream.cs @@ -1192,8 +1192,10 @@ namespace Microsoft.PowerShell.Commands if (_singleByteCharSet != null) return (bool)_singleByteCharSet; - if (_currentEncoding.Equals(_oemEncoding) || - _currentEncoding.Equals(_defaultAnsiEncoding)) + // Porting note: only UTF-8 is supported on Linux, which is not an SBCS + if ((_currentEncoding.Equals(_oemEncoding) || + _currentEncoding.Equals(_defaultAnsiEncoding)) + && !Platform.IsLinux()) { NativeMethods.CPINFO cpInfo; if (NativeMethods.GetCPInfo((uint)_currentEncoding.CodePage, out cpInfo) && diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 91b6ccf54..50bd189a0 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -405,7 +405,7 @@ namespace Microsoft.PowerShell.Commands } // -Persist switch parameter is supported only for Network paths. - if (drive.Persist && !NativeMethods.PathIsNetworkPath(drive.Root)) + if (drive.Persist && !PathIsNetworkPath(drive.Root)) { ErrorRecord er = new ErrorRecord(new NotSupportedException(FileSystemProviderStrings.PersistNotSupported), "DriveRootNotNetworkPath", ErrorCategory.InvalidArgument, drive); ThrowTerminatingError(er); @@ -488,6 +488,19 @@ namespace Microsoft.PowerShell.Commands /// /// The PSDrive infor that would be used to create a new PS drive. private void MapNetworkDrive(PSDriveInfo drive) + { + // Porting note: mapped network drives are only supported on Windows + if (Platform.IsWindows()) + { + WinMapNetworkDrive(drive); + } + else + { + throw new Platform.PlatformNotSupportedException(); + } + } + + private void WinMapNetworkDrive(PSDriveInfo drive) { if (drive != null && !string.IsNullOrEmpty(drive.Root)) { @@ -578,7 +591,7 @@ namespace Microsoft.PowerShell.Commands /// private bool IsNetworkMappedDrive(PSDriveInfo drive) { - bool shouldMapNetworkDrive = (drive != null && !string.IsNullOrEmpty(drive.Root) && NativeMethods.PathIsNetworkPath(drive.Root)) && + bool shouldMapNetworkDrive = (drive != null && !string.IsNullOrEmpty(drive.Root) && PathIsNetworkPath(drive.Root)) && (drive.Persist || (drive.Credential != null && !drive.Credential.Equals(PSCredential.Empty))); return shouldMapNetworkDrive; @@ -593,6 +606,19 @@ namespace Microsoft.PowerShell.Commands /// PSDrive info. /// protected override PSDriveInfo RemoveDrive(PSDriveInfo drive) + { + // if removing the drive is not supported, just return the drive + if (Platform.SupportsRemoveDrive()) + { + return WinRemoveDrive(drive); + } + else + { + return drive; + } + } + + private PSDriveInfo WinRemoveDrive(PSDriveInfo drive) { if (IsNetworkMappedDrive(drive)) { @@ -658,6 +684,19 @@ namespace Microsoft.PowerShell.Commands /// /// internal static string GetUNCForNetworkDrive(string driveName) + { + // Porting note: on systems that do not support UNC paths, the UNC equivalent is the path itself + if (Platform.HasUNCSupport()) + { + return WinGetUNCForNetworkDrive(driveName); + } + else + { + return driveName; + } + } + + private static string WinGetUNCForNetworkDrive(string driveName) { string uncPath = null; if (!string.IsNullOrEmpty(driveName) && driveName.Length == 1) @@ -707,6 +746,18 @@ namespace Microsoft.PowerShell.Commands /// /// internal static string GetSubstitutedPathForNetworkDosDevice(string driveName) + { + if (Platform.HasNetworkDriveSupport()) + { + return WinGetSubstitutedPathForNetworkDosDevice(driveName); + } + else + { + throw new Platform.PlatformNotSupportedException(); + } + } + + private static string WinGetSubstitutedPathForNetworkDosDevice(string driveName) { string associatedPath = null; if (!string.IsNullOrEmpty(driveName) && driveName.Length == 1) @@ -842,39 +893,50 @@ namespace Microsoft.PowerShell.Commands break; } - string newDriveName = newDrive.Name.Substring(0, 1); - - string description = String.Empty; - string root = newDrive.Name; - string displayRoot = null; - - if (newDrive.DriveType == DriveType.Fixed) - { - try - { - description = newDrive.VolumeLabel; - } - // trying to read the volume label may cause an - // IOException or SecurityException. Just default - // to an empty description. - catch (IOException) - { - } - catch (System.Security.SecurityException) - { - } - catch (System.UnauthorizedAccessException) - { - } - } - - if (newDrive.DriveType == DriveType.Network) - { - displayRoot = GetRootPathForNetworkDriveOrDosDevice(newDrive); - } - + // cover everything by the try-catch block, because some of the + // DriveInfo properties may throw exceptions try { + string newDriveName = newDrive.Name.Substring(0, 1); + + string description = String.Empty; + string root = newDrive.Name; + string displayRoot = null; + + if (newDrive.DriveType == DriveType.Fixed) + { + try + { + description = newDrive.VolumeLabel; + } + // trying to read the volume label may cause an + // IOException or SecurityException. Just default + // to an empty description. + catch (IOException) + { + } + catch (System.Security.SecurityException) + { + } + catch (System.UnauthorizedAccessException) + { + } + } + + if (newDrive.DriveType == DriveType.Network) + { + // Platform notes: This is important because certain mount + // points on non-Windows are enumerated as drives by .net, but + // the platform itself then has no real network drive support + // as required by this context. Solution: check for network + // drive support before using it. + if (!Platform.HasNetworkDriveSupport()) + { + continue; + } + displayRoot = GetRootPathForNetworkDriveOrDosDevice(newDrive); + } + if (newDrive.DriveType == DriveType.Fixed) { if (!newDrive.RootDirectory.Exists) @@ -885,6 +947,27 @@ namespace Microsoft.PowerShell.Commands root = newDrive.RootDirectory.FullName; } + // Porting notes: On platforms with single root filesystems, only + // add the filesystem with the root "/" to the initial drive list, + // otherwise path handling will not work correctly because there + // is no : available to separate the filesystems from each other + if (Platform.HasSingleRootFilesystem() && root != "/") + continue; + + // Porting notes: On non-windows platforms .net can report two + // drives with the same root, make sure to only add one of those + bool skipDuplicate = false; + foreach (PSDriveInfo driveInfo in results) + { + if (driveInfo.Root == root) + { + skipDuplicate = true; + break; + } + } + if (skipDuplicate) + continue; + // Create a new VirtualDrive for each logical drive PSDriveInfo newPSDriveInfo = new PSDriveInfo( @@ -906,9 +989,18 @@ namespace Microsoft.PowerShell.Commands { newPSDriveInfo.IsAutoMounted = true; } + + // Porting notes: on the non-Windows platforms, the drive never + // uses : as a separator between drive and path + if (!Platform.IsWindows()) + { + newPSDriveInfo.VolumeSeparatedByColon = false; + } + results.Add(newPSDriveInfo); } - // If we can't access the root itself, don't add the drive + // If there are issues accessing properties of the DriveInfo, do + // not add the drive catch (IOException) { } @@ -1413,6 +1505,13 @@ namespace Microsoft.PowerShell.Commands { DirectoryInfo directory = new DirectoryInfo(path); + if (!Platform.IsWindows() && Platform.NonWindowsIsSymLink(directory)) + { + // For Linux, treat symlink to directories like a file + WriteItemObject(directory, path, false); + return; + } + // Enumerate the directory Dir(directory, recurse, depth, nameOnly, returnContainers); } @@ -1540,7 +1639,10 @@ namespace Microsoft.PowerShell.Commands // Write out the items foreach (IEnumerable childList in target) { - foreach(FileSystemInfo filesystemInfo in childList) + // On some systems, this is already sorted. For consistency, always sort again. + IEnumerable sortedChildList = childList.OrderBy(c => c.Name, StringComparer.CurrentCultureIgnoreCase); + + foreach(FileSystemInfo filesystemInfo in sortedChildList) { // Making sure to obey the StopProcessing. if (Stopping) @@ -1723,7 +1825,10 @@ namespace Microsoft.PowerShell.Commands mode[3] = (fileInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden ? 'h' : '-'; mode[4] = (fileInfo.Attributes & FileAttributes.System) == FileAttributes.System ? 's' : '-'; // Mark the last bit as a "l" if it's a reparsepoint (symbolic link or junction) - mode[5] = (fileInfo.Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint ? 'l' : '-'; + // Porting note: these need to be handled specially + bool isReparsePoint = InternalSymbolicLinkLinkCodeMethods.IsReparsePoint(fileInfo); + bool isHardLink = InternalSymbolicLinkLinkCodeMethods.IsHardLink(fileInfo); + mode[5] = isReparsePoint || isHardLink ? 'l' : '-'; return new string(mode); } @@ -2105,12 +2210,25 @@ namespace Microsoft.PowerShell.Commands if(itemType == ItemType.SymbolicLink) { - int created = NativeMethods.CreateSymbolicLink(path, strTargetPath, (isDirectory ? 1 : 0)); - success = (created == 1) ? true : false; + if (Platform.IsWindows()) + { + success = WinCreateSymbolicLink(path,strTargetPath,isDirectory); + } + else + { + success = Platform.NonWindowsCreateSymbolicLink(path,strTargetPath,isDirectory); + } } else if(itemType == ItemType.HardLink) { - success = NativeMethods.CreateHardLink(path, strTargetPath, IntPtr.Zero); + if (Platform.IsWindows()) + { + success = WinCreateHardLink(path,strTargetPath); + } + else + { + success = Platform.NonWindowsCreateHardLink(path,strTargetPath); + } } if (!success) @@ -2253,7 +2371,7 @@ namespace Microsoft.PowerShell.Commands try { - bool junctionCreated = InternalSymbolicLinkLinkCodeMethods.CreateJunction(path, strTargetPath); + bool junctionCreated = WinCreateJunction(path, strTargetPath); if (junctionCreated) { @@ -2299,6 +2417,25 @@ namespace Microsoft.PowerShell.Commands } } // NewItem + private static bool WinCreateSymbolicLink(string path, string strTargetPath, bool isDirectory) + { + int created = NativeMethods.CreateSymbolicLink(path, strTargetPath, (isDirectory ? 1 : 0)); + bool success = (created == 1) ? true : false; + return success; + } + + private static bool WinCreateHardLink(string path, string strTargetPath) + { + bool success = NativeMethods.CreateHardLink(path, strTargetPath, IntPtr.Zero); + return success; + } + + private static bool WinCreateJunction(string path, string strTargetPath) + { + bool junctionCreated = InternalSymbolicLinkLinkCodeMethods.CreateJunction(path, strTargetPath); + return junctionCreated; + } + /// /// Checks if the item exists and throws exception on access. /// @@ -4542,6 +4679,12 @@ namespace Microsoft.PowerShell.Commands { bool result = false; + // this needs to be done differently on single root filesystems + if (Platform.HasSingleRootFilesystem() && path.StartsWith("/")) + { + return true; + } + // Find the drive separator int index = path.IndexOf(':'); @@ -5006,15 +5149,18 @@ namespace Microsoft.PowerShell.Commands private string RemoveRelativeTokens(string path) { - string testPath = path.Replace('/', '\\'); + string sep = System.IO.Path.DirectorySeparatorChar.ToString(); + string altSep = System.IO.Path.AltDirectorySeparatorChar.ToString(); + + string testPath = path.Replace(altSep,sep); if ( - (testPath.IndexOf("\\", StringComparison.OrdinalIgnoreCase) < 0) || - testPath.StartsWith(".\\", StringComparison.OrdinalIgnoreCase) || - testPath.StartsWith("..\\", StringComparison.OrdinalIgnoreCase) || - testPath.EndsWith("\\.", StringComparison.OrdinalIgnoreCase) || - testPath.EndsWith("\\..", StringComparison.OrdinalIgnoreCase) || - (testPath.IndexOf("\\.\\", StringComparison.OrdinalIgnoreCase) > 0) || - (testPath.IndexOf("\\..\\", StringComparison.OrdinalIgnoreCase) > 0)) + (testPath.IndexOf(sep, StringComparison.OrdinalIgnoreCase) < 0) || + testPath.StartsWith("." + sep, StringComparison.OrdinalIgnoreCase) || + testPath.StartsWith(".." + sep, StringComparison.OrdinalIgnoreCase) || + testPath.EndsWith(sep + ".", StringComparison.OrdinalIgnoreCase) || + testPath.EndsWith(sep + "..", StringComparison.OrdinalIgnoreCase) || + (testPath.IndexOf(sep + "." + sep, StringComparison.OrdinalIgnoreCase) > 0) || + (testPath.IndexOf(sep + ".." + sep, StringComparison.OrdinalIgnoreCase) > 0)) { try { @@ -6729,6 +6875,52 @@ namespace Microsoft.PowerShell.Commands #endregion IContentCmdletProvider internal static int SafeGetFileAttributes(string path) + { + if (Platform.UseDotNetToQueryFileAttributes()) + { + System.IO.FileAttributes attr = System.IO.File.GetAttributes(path); + + int result = 0; + if ((attr & FileAttributes.Archive) == FileAttributes.Archive) + result |= 0x20; + if ((attr & FileAttributes.Compressed) == FileAttributes.Compressed) + result |= 0x800; + if ((attr & FileAttributes.Device) == FileAttributes.Device) + result |= 0x40; + if ((attr & FileAttributes.Directory) == FileAttributes.Directory) + result |= 0x10; + if ((attr & FileAttributes.Encrypted) == FileAttributes.Encrypted) + result |= 0x4000; + if ((attr & FileAttributes.Hidden) == FileAttributes.Hidden) + result |= 0x2; + if ((attr & FileAttributes.IntegrityStream) == FileAttributes.IntegrityStream) + result |= 0x8000; + if ((attr & FileAttributes.Normal) == FileAttributes.Normal) + result |= 0x80; + if ((attr & FileAttributes.NoScrubData) == FileAttributes.NoScrubData) + result |= 0x20000; + if ((attr & FileAttributes.NotContentIndexed) == FileAttributes.NotContentIndexed) + result |= 0x2000; + if ((attr & FileAttributes.Offline) == FileAttributes.Offline) + result |= 0x1000; + if ((attr & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) + result |= 0x1; + if ((attr & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint) + result |= 0x400; + if ((attr & FileAttributes.SparseFile) == FileAttributes.SparseFile) + result |= 0x200; + if ((attr & FileAttributes.System) == FileAttributes.System) + result |= 0x4; + if ((attr & FileAttributes.Temporary) == FileAttributes.Temporary) + result |= 0x100; + + return result; + } + else + return WinSafeGetFileAttributes(path); + } + + internal static int WinSafeGetFileAttributes(string path) { int result = Utils.NativeMethods.GetFileAttributes(path); if (result == -1) @@ -6779,6 +6971,26 @@ namespace Microsoft.PowerShell.Commands } } + /// + /// The API 'PathIsNetworkPath' is not available in CoreSystem. + /// This implementation is based on the 'PathIsNetworkPath' API. + /// + /// + /// + internal static bool PathIsNetworkPath(string path) + { + // no other logic possible for now on linux + if (Platform.HasNetworkDriveSupport()) + return WinPathIsNetworkPath(path); + else + return false; + } + + internal static bool WinPathIsNetworkPath(string path) + { + return NativeMethods.PathIsNetworkPath(path); // call the native method + } + static class NativeMethods { /// @@ -7769,15 +7981,17 @@ namespace Microsoft.PowerShell.Commands if (fileSysInfo != null) { - using (SafeFileHandle handle = OpenReparsePoint(fileSysInfo.FullName, FileDesiredAccess.GenericRead)) + if (Platform.IsWindows()) { - string linkTarget = InternalGetTarget(handle); + using (SafeFileHandle handle = OpenReparsePoint(fileSysInfo.FullName, FileDesiredAccess.GenericRead)) + { + string linkTarget = InternalGetTarget(handle); - if (linkTarget != null) - return (new string[] { linkTarget }); + if (linkTarget != null) + return (new string[] { linkTarget }); + } } - //return InternalGetTarget(fileSysInfo.FullName).ToArray(); return InternalGetTarget(fileSysInfo.FullName); } else @@ -7795,7 +8009,7 @@ namespace Microsoft.PowerShell.Commands if (fileSysInfo != null) { - return InternalGetLinkType(fileSysInfo.FullName); + return InternalGetLinkType(fileSysInfo); } else return null; @@ -7804,6 +8018,15 @@ namespace Microsoft.PowerShell.Commands private static List InternalGetTarget(string filePath) { var links = new List(); + if (!Platform.IsWindows()) + { + string link = Platform.NonWindowsInternalGetTarget(filePath); + if (!String.IsNullOrEmpty(link)) + { + links.Add(link); + } + return links; + } #if !CORECLR //FindFirstFileName, FindNextFileName and FindClose are not available on Core Clr UInt32 linkStringLength = 0; @@ -7867,9 +8090,26 @@ namespace Microsoft.PowerShell.Commands return links; } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] - private static string InternalGetLinkType(string filePath) + private static string InternalGetLinkType(FileSystemInfo fileInfo) { + if (Platform.IsWindows()) + { + return WinInternalGetLinkType(fileInfo.FullName); + } + else + { + return Platform.NonWindowsInternalGetLinkType(fileInfo); + } + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] + private static string WinInternalGetLinkType(string filePath) + { + if (Platform.IsLinux()) + { + throw new Platform.PlatformNotSupportedException(); + } + using (SafeFileHandle handle = OpenReparsePoint(filePath, FileDesiredAccess.GenericRead)) { int outBufferSize = ClrFacade.SizeOf(); @@ -7927,8 +8167,75 @@ namespace Microsoft.PowerShell.Commands } } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] + internal static bool IsHardLink(FileSystemInfo fileInfo) + { + if (Platform.IsWindows()) + return WinIsHardLink(fileInfo); + else + return Platform.NonWindowsIsHardLink(fileInfo); + } + + internal static bool IsReparsePoint(FileSystemInfo fileInfo) + { + if (Platform.IsWindows()) + { + // Note that this class also has a enum called FileAttributes, so use fully qualified name + return (fileInfo.Attributes & System.IO.FileAttributes.ReparsePoint) + == System.IO.FileAttributes.ReparsePoint; + } + else + { + return Platform.NonWindowsIsSymLink(fileInfo); + } + } + + internal static bool WinIsHardLink(FileSystemInfo fileInfo) + { + bool isHardLink = false; + + // only check for hard link if the item is not directory + if (!((fileInfo.Attributes & System.IO.FileAttributes.Directory) == System.IO.FileAttributes.Directory)) + { + IntPtr nativeHandle = InternalSymbolicLinkLinkCodeMethods.CreateFile( + fileInfo.FullName, + InternalSymbolicLinkLinkCodeMethods.FileDesiredAccess.GenericRead, + InternalSymbolicLinkLinkCodeMethods.FileShareMode.Read, + IntPtr.Zero, + InternalSymbolicLinkLinkCodeMethods.FileCreationDisposition.OpenExisting, + InternalSymbolicLinkLinkCodeMethods.FileAttributes.Normal, + IntPtr.Zero); + + using (SafeFileHandle handle = new SafeFileHandle(nativeHandle, true)) + { + bool success = false; + + try + { + handle.DangerousAddRef(ref success); + IntPtr dangerousHandle = handle.DangerousGetHandle(); + isHardLink = InternalSymbolicLinkLinkCodeMethods.IsHardLink(ref dangerousHandle); + } + finally + { + if (success) + handle.DangerousRelease(); + } + } + } + + return isHardLink; + } + internal static bool IsHardLink(ref IntPtr handle) + { + if (Platform.IsWindows()) + return WinIsHardLink(ref handle); + else + return Platform.NonWindowsIsHardLink(ref handle); + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] + internal static bool WinIsHardLink(ref IntPtr handle) { BY_HANDLE_FILE_INFORMATION handleInfo; bool succeeded = InternalSymbolicLinkLinkCodeMethods.GetFileInformationByHandle(handle, out handleInfo); @@ -7947,8 +8254,20 @@ namespace Microsoft.PowerShell.Commands return false; } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] private static string InternalGetTarget(SafeFileHandle handle) + { + if (Platform.IsWindows()) + { + return WinInternalGetTarget(handle); + } + else + { + return Platform.NonWindowsInternalGetTarget(handle); + } + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] + private static string WinInternalGetTarget(SafeFileHandle handle) { int outBufferSize = ClrFacade.SizeOf(); @@ -8013,8 +8332,22 @@ namespace Microsoft.PowerShell.Commands } } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] internal static bool CreateJunction(string path, string target) + { + // this is a purely Windows specific feature, no feature flag + // used for that reason + if (Platform.IsWindows()) + { + return WinCreateJunction(path,target); + } + else + { + return false; + } + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] + private static bool WinCreateJunction(string path, string target) { if (!String.IsNullOrEmpty(path)) { @@ -8087,6 +8420,20 @@ namespace Microsoft.PowerShell.Commands if (!String.IsNullOrEmpty(junctionPath)) { + if (!Platform.IsWindows()) + { + // For non-Windows platform, treat it as a file. Just delete it. + try + { + File.Delete(junctionPath); + return true; + } + catch + { + return false; + } + } + using (SafeHandle handle = OpenReparsePoint(junctionPath, FileDesiredAccess.GenericWrite)) { bool success = false; @@ -8138,6 +8485,18 @@ namespace Microsoft.PowerShell.Commands } private static SafeFileHandle OpenReparsePoint(string reparsePoint, FileDesiredAccess accessMode) + { + if (Platform.SupportsReparsePoints()) + { + return WinOpenReparsePoint(reparsePoint,accessMode); + } + else + { + throw new Platform.PlatformNotSupportedException(); + } + } + + private static SafeFileHandle WinOpenReparsePoint(string reparsePoint, FileDesiredAccess accessMode) { IntPtr nativeHandle = CreateFile(reparsePoint, accessMode, FileShareMode.Read | FileShareMode.Write | FileShareMode.Delete, diff --git a/src/System.Management.Automation/namespaces/LocationGlobber.cs b/src/System.Management.Automation/namespaces/LocationGlobber.cs index 5e3ba3591..4b5441c29 100644 --- a/src/System.Management.Automation/namespaces/LocationGlobber.cs +++ b/src/System.Management.Automation/namespaces/LocationGlobber.cs @@ -1607,7 +1607,9 @@ namespace System.Management.Automation break; } - if (path.StartsWith(@".\", StringComparison.Ordinal)) + // compare both to \ and / here + if (path.StartsWith(@".\", StringComparison.Ordinal) || + path.StartsWith(@"./", StringComparison.Ordinal)) { // The .\ prefix basically escapes anything that follows // so treat it as a relative path no matter what comes @@ -1617,6 +1619,16 @@ namespace System.Management.Automation break; } + // non-windows porting notes: + // this needs to be handled differently on non-windows, paths starting with / are always absolute + // -> still continue with other isAbsolute processing, colons can still happen in drives + // of other providers + if (Platform.HasSingleRootFilesystem() && path.StartsWith("/",StringComparison.Ordinal)) + { + result = true; + break; + } + int index = path.IndexOf(":", StringComparison.Ordinal); if (index == -1) @@ -1704,6 +1716,17 @@ namespace System.Management.Automation break; } + // non-windows porting notes: + // this needs to be handled differently on non-windows, paths starting with / are always absolute + // -> still continue with other isAbsolute processing, colons can still happen in drives + // of other providers + if (Platform.HasSingleRootFilesystem() && path.StartsWith("/",StringComparison.Ordinal)) + { + driveName = "/"; + result = true; + break; + } + int index = path.IndexOf(":", StringComparison.CurrentCulture); if (index == -1) @@ -2016,7 +2039,20 @@ namespace System.Management.Automation // Now hack off the drive component of the path if (!isPathForCurrentDrive) { - path = path.Substring(driveName.Length + 1); + // This functionality needs to respect if a drive uses a colon to separate the path + // + // what happens here is this: + // - path is assumed to be drive root relative, so on Windows it would start with a + // \ + // - on Linux, there is no difference between drive root relative, and absolute, they + // are both the same, so we have to preserve the drive here in order to make + // sure the path will continue being drive root relative + if (workingDriveForPath.VolumeSeparatedByColon) + { + // this is the default behavior for all windows drives, and all non-filesystem + // drives on non-windows + path = path.Substring(driveName.Length + 1); + } } } else @@ -2224,10 +2260,13 @@ namespace System.Management.Automation { // The root relative path was given so empty the current working path. + // Porting notes: This can happen on non-Windows, because the assumption + // is that for file paths a path that is already relative to the drive + // root is the same thing as an absolute path (both start with /). + driveRootRelativeWorkingPath = String.Empty; - // Remove the \ or / from the drive relative - // path + // Remove the \ or / from the drive relative path path = path.Substring(1); @@ -2403,18 +2442,41 @@ namespace System.Management.Automation private bool HasRelativePathTokens(string path) { - string comparePath = path.Replace('/', '\\'); + if (System.IO.Path.DirectorySeparatorChar == '/') + { + string comparePath = path; - return ( - comparePath.Equals(".", StringComparison.OrdinalIgnoreCase) || - comparePath.Equals("..", StringComparison.OrdinalIgnoreCase) || - comparePath.Contains("\\.\\") || - comparePath.Contains("\\..\\") || - comparePath.EndsWith("\\..", StringComparison.OrdinalIgnoreCase) || - comparePath.EndsWith("\\.", StringComparison.OrdinalIgnoreCase) || - comparePath.StartsWith("..\\", StringComparison.OrdinalIgnoreCase) || - comparePath.StartsWith(".\\", StringComparison.OrdinalIgnoreCase) || - comparePath.StartsWith("~", StringComparison.OrdinalIgnoreCase)); + // the next line will only replace something, if the directory separators + // are different on the platform + if (System.IO.Path.DirectorySeparatorChar != System.IO.Path.AltDirectorySeparatorChar) + comparePath = path.Replace(System.IO.Path.AltDirectorySeparatorChar,System.IO.Path.DirectorySeparatorChar); + + return ( + comparePath.Equals(".", StringComparison.OrdinalIgnoreCase) || + comparePath.Equals("..", StringComparison.OrdinalIgnoreCase) || + comparePath.Contains("/./") || + comparePath.Contains("/../") || + comparePath.EndsWith("/..", StringComparison.OrdinalIgnoreCase) || + comparePath.EndsWith("/.", StringComparison.OrdinalIgnoreCase) || + comparePath.StartsWith("../", StringComparison.OrdinalIgnoreCase) || + comparePath.StartsWith("./", StringComparison.OrdinalIgnoreCase) || + comparePath.StartsWith("~", StringComparison.OrdinalIgnoreCase)); + } + else + { + string comparePath = path.Replace('/', '\\'); + + return ( + comparePath.Equals(".", StringComparison.OrdinalIgnoreCase) || + comparePath.Equals("..", StringComparison.OrdinalIgnoreCase) || + comparePath.Contains("\\.\\") || + comparePath.Contains("\\..\\") || + comparePath.EndsWith("\\..", StringComparison.OrdinalIgnoreCase) || + comparePath.EndsWith("\\.", StringComparison.OrdinalIgnoreCase) || + comparePath.StartsWith("..\\", StringComparison.OrdinalIgnoreCase) || + comparePath.StartsWith(".\\", StringComparison.OrdinalIgnoreCase) || + comparePath.StartsWith("~", StringComparison.OrdinalIgnoreCase)); + } } /// @@ -3068,37 +3130,50 @@ namespace System.Management.Automation } else { + // Platform note: + // this needs to be done differently on non-windows platforms + string unescapedPath = context.SuppressWildcardExpansion ? path : RemoveGlobEscaping(path); - string formatString = "{0}:" + StringLiterals.DefaultPathSeparator + "{1}"; + // this is the output of the platform specific code right below + string resolvedPath; - // Check to see if its a hidden provider drive. - if (drive.Hidden) + if (drive.VolumeSeparatedByColon) { - if (IsProviderDirectPath(unescapedPath)) + string formatString = "{0}:" + StringLiterals.DefaultPathSeparator + "{1}"; + + // Check to see if its a hidden provider drive. + if (drive.Hidden) { - formatString = "{1}"; + if (IsProviderDirectPath(unescapedPath)) + { + formatString = "{1}"; + } + else + { + formatString = "{0}::{1}"; + } } else { - formatString = "{0}::{1}"; + if (path.StartsWith(StringLiterals.DefaultPathSeparator.ToString(), StringComparison.Ordinal)) + { + formatString = "{0}:{1}"; + } } + + resolvedPath = + String.Format( + System.Globalization.CultureInfo.InvariantCulture, + formatString, + drive.Name, + unescapedPath); } else { - if (path.StartsWith(StringLiterals.DefaultPathSeparatorString, StringComparison.Ordinal)) - { - formatString = "{0}:{1}"; - } + resolvedPath = drive.Name + unescapedPath; } - string resolvedPath = - String.Format( - System.Globalization.CultureInfo.InvariantCulture, - formatString, - drive.Name, - unescapedPath); - // Since we didn't do globbing, be sure the path exists if (allowNonexistingPaths || provider.ItemExists(GetProviderPath(resolvedPath, context), context)) @@ -3257,45 +3332,59 @@ namespace System.Management.Automation } string result = path; - bool treatAsRelative = true; - // Ensure the drive name is the same as the portion of the path before - // :. If not add the drive name and colon as if it was a relative path - - int index = path.IndexOf(':'); - - if (index != -1) + // platform notes: + // this needs to be implemented differently depending if the drive uses colon to separate paths + if (drive.VolumeSeparatedByColon) { - if (drive.Hidden) + bool treatAsRelative = true; + + // Ensure the drive name is the same as the portion of the path before + // :. If not add the drive name and colon as if it was a relative path + + int index = path.IndexOf(':'); + + if (index != -1) { - treatAsRelative = false; - } - else - { - string possibleDriveName = path.Substring(0, index); - if (String.Equals(possibleDriveName, drive.Name, StringComparison.OrdinalIgnoreCase)) + if (drive.Hidden) { treatAsRelative = false; } + else + { + string possibleDriveName = path.Substring(0, index); + if (String.Equals(possibleDriveName, drive.Name, StringComparison.OrdinalIgnoreCase)) + { + treatAsRelative = false; + } + } } - } - if (treatAsRelative) - { - string formatString = "{0}:" + StringLiterals.DefaultPathSeparator + "{1}"; - - if (path.StartsWith(StringLiterals.DefaultPathSeparatorString, StringComparison.Ordinal)) + if (treatAsRelative) { - formatString = "{0}:{1}"; + string formatString = "{0}:" + StringLiterals.DefaultPathSeparator + "{1}"; + + if (path.StartsWith(StringLiterals.DefaultPathSeparator.ToString(), StringComparison.Ordinal)) + { + formatString = "{0}:{1}"; + } + result = + String.Format( + System.Globalization.CultureInfo.InvariantCulture, + formatString, + drive.Name, + path); } - result = - String.Format( - System.Globalization.CultureInfo.InvariantCulture, - formatString, - drive.Name, - path); + } + else + { + if (path.StartsWith(drive.Name)) + result = path; + else + result = drive.Name + path; } + tracer.WriteLine("result = {0}", result); return result; } // GetDriveQualifiedPath @@ -5004,4 +5093,4 @@ namespace System.Management.Automation #endregion internal methods } // class LocationGlobber -} // namespace System.Management.Automation \ No newline at end of file +} // namespace System.Management.Automation diff --git a/src/System.Management.Automation/namespaces/RegistryProvider.cs b/src/System.Management.Automation/namespaces/RegistryProvider.cs index 8b3a75847..e33492c8f 100644 --- a/src/System.Management.Automation/namespaces/RegistryProvider.cs +++ b/src/System.Management.Automation/namespaces/RegistryProvider.cs @@ -135,6 +135,12 @@ namespace Microsoft.PowerShell.Commands protected override Collection InitializeDefaultDrives() { Collection drives = new Collection(); + + if (!Platform.HasRegistrySupport()) + { + return drives; + } + drives.Add( new PSDriveInfo( "HKLM", diff --git a/src/System.Management.Automation/namespaces/SafeRegistryHandle.cs b/src/System.Management.Automation/namespaces/SafeRegistryHandle.cs index 119cf9724..1e817966b 100644 --- a/src/System.Management.Automation/namespaces/SafeRegistryHandle.cs +++ b/src/System.Management.Automation/namespaces/SafeRegistryHandle.cs @@ -58,6 +58,10 @@ namespace Microsoft.PowerShell.Commands.Internal override protected bool ReleaseHandle() { + if (!Platform.HasRegistrySupport()) + { + return true; + } // Returns a Win32 error code, 0 for success int r = RegCloseKey(handle); return r == 0; diff --git a/src/System.Management.Automation/namespaces/SafeTransactionHandle.cs b/src/System.Management.Automation/namespaces/SafeTransactionHandle.cs index ad5af91bd..db5ca3c85 100644 --- a/src/System.Management.Automation/namespaces/SafeTransactionHandle.cs +++ b/src/System.Management.Automation/namespaces/SafeTransactionHandle.cs @@ -1,3 +1,4 @@ +#if !CORECLR // // Copyright (C) Microsoft. All rights reserved. // @@ -44,8 +45,8 @@ namespace Microsoft.PowerShell.Commands.Internal // CommitableTransaction will use DTC APIs under the covers to get KTM transaction manager interface. // KTM is kernel Transaction Manager to handle file, registry etc and MSDTC provides an integration support // with KTM to handle transaction across kernel resources and MSDTC resources like SQL, MSMQ etc. - // We need KTMRM service as well. WinPE doesn’t have these services installed - if (RemotingCommandUtil.IsWinPEHost() || PsUtils.IsRunningOnProcessorArchitectureARM()) + // We need KTMRM service as well. WinPE doesn?t have these services installed + if (Utils.IsWinPEHost() || PsUtils.IsRunningOnProcessorArchitectureARM()) { throw new NotSupportedException(RegistryProviderStrings.NotSupported_KernelTransactions); } @@ -80,3 +81,5 @@ namespace Microsoft.PowerShell.Commands.Internal } } } + +#endif diff --git a/src/System.Management.Automation/namespaces/TransactedRegistry.cs b/src/System.Management.Automation/namespaces/TransactedRegistry.cs index 87896a7de..b2f7e19b5 100644 --- a/src/System.Management.Automation/namespaces/TransactedRegistry.cs +++ b/src/System.Management.Automation/namespaces/TransactedRegistry.cs @@ -1,3 +1,4 @@ +#if !CORECLR // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. @@ -132,3 +133,5 @@ namespace Microsoft.PowerShell.Commands.Internal internal static readonly TransactedRegistryKey CurrentConfig = TransactedRegistryKey.GetBaseKey(BaseRegistryKeys.HKEY_CURRENT_CONFIG); } } + +#endif diff --git a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs index 11e7de70e..9f1c3edda 100644 --- a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs +++ b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs @@ -1,3 +1,4 @@ +#if !CORECLR // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. @@ -191,7 +192,14 @@ namespace Microsoft.PowerShell.Commands.Internal { SafeRegistryHandle nonTxKey = null; SafeRegistryHandle txKey = null; - error = Win32Native.RegOpenKeyEx(hkey, lpSubKey, ulOptions, samDesired, out nonTxKey); + if (!Platform.HasRegistrySupport()) + { + error = 1; + } + else + { + error = Win32Native.RegOpenKeyEx(hkey, lpSubKey, ulOptions, samDesired, out nonTxKey); + } // If we got some error on this open, just ignore it and continue on with the handle // we got on the original RegOpenKeyTransacted. if (Win32Native.ERROR_SUCCESS == error) @@ -1961,3 +1969,5 @@ namespace Microsoft.PowerShell.Commands.Internal } } + +#endif diff --git a/src/System.Management.Automation/namespaces/TransactedRegistrySecurity.cs b/src/System.Management.Automation/namespaces/TransactedRegistrySecurity.cs index bcb4c4c38..584c3aea2 100644 --- a/src/System.Management.Automation/namespaces/TransactedRegistrySecurity.cs +++ b/src/System.Management.Automation/namespaces/TransactedRegistrySecurity.cs @@ -1,3 +1,4 @@ +#if !CORECLR // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. @@ -466,3 +467,5 @@ namespace Microsoft.PowerShell.Commands.Internal } } } + +#endif diff --git a/src/System.Management.Automation/security/SecurityManager.cs b/src/System.Management.Automation/security/SecurityManager.cs index 7dd6d46f2..80446a297 100644 --- a/src/System.Management.Automation/security/SecurityManager.cs +++ b/src/System.Management.Automation/security/SecurityManager.cs @@ -117,12 +117,13 @@ namespace Microsoft.PowerShell string path = script.Path; string reasonMessage; - if (path.IndexOf('\\') < 0) + // path is assumed to be fully qualified here + if (path.IndexOf(System.IO.Path.DirectorySeparatorChar) < 0) { throw PSTraceSource.NewArgumentException("path"); } - if (path.LastIndexOf('\\') == (path.Length - 1)) + if (path.LastIndexOf(System.IO.Path.DirectorySeparatorChar) == (path.Length - 1)) { throw PSTraceSource.NewArgumentException("path"); } diff --git a/src/System.Management.Automation/security/SecuritySupport.cs b/src/System.Management.Automation/security/SecuritySupport.cs index 8d4dd2afb..1a6b0ff4f 100644 --- a/src/System.Management.Automation/security/SecuritySupport.cs +++ b/src/System.Management.Automation/security/SecuritySupport.cs @@ -138,6 +138,11 @@ namespace System.Management.Automation internal static void SetExecutionPolicy(ExecutionPolicyScope scope, ExecutionPolicy policy, string shellId) { + if (!Platform.HasExecutionPolicy()) + { + throw new PlatformNotSupportedException(); + } + string executionPolicy = "Restricted"; string preferenceKey = Utils.GetRegistryConfigurationPath(shellId); const string PolicyKeyValueName = "ExecutionPolicy"; @@ -278,6 +283,11 @@ namespace System.Management.Automation internal static ExecutionPolicy GetExecutionPolicy(string shellId, ExecutionPolicyScope scope) { + if (!Platform.HasExecutionPolicy()) + { + throw new PlatformNotSupportedException(); + } + switch (scope) { case ExecutionPolicyScope.Process: @@ -421,6 +431,13 @@ namespace System.Management.Automation return false; } + // There is no signature support on non-Windows platforms (yet), when + // execution reaches here, we are sure the file is under product folder + if (Platform.IsX()) + { + return true; + } + // Check the file signature Signature fileSignature = SignatureHelper.GetSignature(file, null); if ((fileSignature != null) && (fileSignature.IsOSBinary)) @@ -1616,6 +1633,18 @@ namespace System.Management.Automation /// Information about the source (filename, etc.) /// AMSI_RESULT_DETECTED if malware was detected in the sample. internal static AmsiNativeMethods.AMSI_RESULT ScanContent(string content, string sourceMetadata) + { + if (Platform.HasAmsi()) + { + return WinScanContent(content,sourceMetadata); + } + else + { + return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; + } + } + + internal static AmsiNativeMethods.AMSI_RESULT WinScanContent(string content, string sourceMetadata) { if (String.IsNullOrEmpty(sourceMetadata)) { @@ -1700,9 +1729,16 @@ namespace System.Management.Automation } } - static void CurrentDomain_ProcessExit(object sender, EventArgs e) + internal static void CurrentDomain_ProcessExit(object sender, EventArgs e) { - VerifyAmsiUninitializeCalled(); + if (Platform.HasAmsi()) + { + VerifyAmsiUninitializeCalled(); + } + else + { + throw new PlatformNotSupportedException(); + } } [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] @@ -1717,6 +1753,20 @@ namespace System.Management.Automation /// Reset the AMSI session (used to track related script invocations) /// internal static void CloseSession() + { + if (Platform.HasAmsi()) + { + WinCloseSession(); + } + else + { + // Porting note: cannot throw here because this is called whether or not + // AMSI was initialized in the first place + return; + } + } + + internal static void WinCloseSession() { if (!amsiInitFailed) { @@ -1739,6 +1789,20 @@ namespace System.Management.Automation /// Uninitialize the AMSI interface /// internal static void Uninitialize() + { + if (Platform.HasAmsi()) + { + WinUninitialize(); + } + else + { + // Porting note: cannot throw here because this is called whether or not + // AMSI was initialized in the first place + return; + } + } + + internal static void WinUninitialize() { AmsiUninitializeCalled = true; if (!amsiInitFailed) diff --git a/src/System.Management.Automation/security/wldpNativeMethods.cs b/src/System.Management.Automation/security/wldpNativeMethods.cs index bbb88befd..801498709 100644 --- a/src/System.Management.Automation/security/wldpNativeMethods.cs +++ b/src/System.Management.Automation/security/wldpNativeMethods.cs @@ -1,3 +1,4 @@ +#if !CORECLR using System; using System.Management.Automation; using System.Management.Automation.Internal; @@ -574,4 +575,5 @@ namespace System.Management.Automation.Security out IntPtr pszPath); } } -} \ No newline at end of file +} +#endif diff --git a/src/System.Management.Automation/singleshell/Commands/ConsoleCommands.cs b/src/System.Management.Automation/singleshell/Commands/ConsoleCommands.cs index 92be0ceb8..c20a84ef2 100644 --- a/src/System.Management.Automation/singleshell/Commands/ConsoleCommands.cs +++ b/src/System.Management.Automation/singleshell/Commands/ConsoleCommands.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -604,3 +605,5 @@ namespace Microsoft.PowerShell.Commands #endregion } + +#endif diff --git a/src/System.Management.Automation/singleshell/Commands/MshSnapinCommands.cs b/src/System.Management.Automation/singleshell/Commands/MshSnapinCommands.cs index cfe5c7721..eb41b43b3 100644 --- a/src/System.Management.Automation/singleshell/Commands/MshSnapinCommands.cs +++ b/src/System.Management.Automation/singleshell/Commands/MshSnapinCommands.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -857,3 +858,5 @@ namespace Microsoft.PowerShell.Commands #endregion } + +#endif diff --git a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs index 0efd0ab7a..7fa604ded 100644 --- a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs +++ b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs @@ -994,7 +994,7 @@ namespace System.Management.Automation return v; } - private static void ReadRegistryInfo(out Version assemblyVersion, out string publicKeyToken, out string culture, out string architecture, out string applicationBase, out Version psVersion) + internal static void ReadRegistryInfo(out Version assemblyVersion, out string publicKeyToken, out string culture, out string architecture, out string applicationBase, out Version psVersion) { applicationBase = Utils.GetApplicationBase(Utils.DefaultPowerShellShellID); Dbg.Assert(!string.IsNullOrEmpty(applicationBase), @@ -1018,9 +1018,21 @@ namespace System.Management.Automation byte[] publicTokens = currentAssembly.GetName().GetPublicKeyToken(); if (publicTokens.Length == 0) { - throw PSTraceSource.NewArgumentException("PublicKeyToken", MshSnapinInfo.PublicKeyTokenAccessFailed); + if (Platform.UsesCodeSignedAssemblies()) + { + throw PSTraceSource.NewArgumentException("PublicKeyToken", MshSnapinInfo.PublicKeyTokenAccessFailed); + } + else + { + // Platform note: set this to null when code signed assemblies are + // unsupported (rather than blank) + publicKeyToken = "null"; + } + } + else + { + publicKeyToken = ConvertByteArrayToString(publicTokens); } - publicKeyToken = ConvertByteArrayToString(publicTokens); // save some cpu cycles by hardcoding the culture to neutral // assembly should never be targeted to a particular culture culture = "neutral"; @@ -1071,6 +1083,12 @@ namespace System.Management.Automation "Help.format.ps1xml","HelpV3.format.ps1xml","PowerShellCore.format.ps1xml","PowerShellTrace.format.ps1xml", "Registry.format.ps1xml"}); + // If code signing is not supported, the token must be set to "null" + if (!Platform.UsesCodeSignedAssemblies()) + { + publicKeyToken = "null"; + } + string strongName = string.Format(CultureInfo.InvariantCulture, "{0}, Version={1}, Culture={2}, PublicKeyToken={3}, ProcessorArchitecture={4}", CoreSnapin.AssemblyName, assemblyVersion, culture, publicKeyToken, architecture); @@ -1130,7 +1148,7 @@ namespace System.Management.Automation StringComparison.OrdinalIgnoreCase)) { types = new Collection(new string[] { "GetEvent.types.ps1xml" }); - formats = new Collection(new string[] { "Event.Format.ps1xml","Diagnostics.Format.ps1xml" }); + formats = new Collection(new string[] { "Event.format.ps1xml","Diagnostics.format.ps1xml" }); } else if (defaultMshSnapinInfo.AssemblyName.Equals("Microsoft.WSMan.Management", StringComparison.OrdinalIgnoreCase)) { @@ -1410,7 +1428,7 @@ namespace System.Management.Automation }; #if !CORECLR //TODO:CORECLR - The 'Microsoft.WSMan.Management' module will be available on OneCore soon - if (!RemotingCommandUtil.IsWinPEHost()) + if (!Utils.IsWinPEHost()) { defaultMshSnapins.Add(new DefaultPSSnapInInformation("Microsoft.WSMan.Management", "Microsoft.WSMan.Management", null, "WsManResources,Description", "WsManResources,Vendor")); diff --git a/src/System.Management.Automation/singleshell/config/RegistryStringResourceIndirect.cs b/src/System.Management.Automation/singleshell/config/RegistryStringResourceIndirect.cs index 0b836a84e..59fc89475 100644 --- a/src/System.Management.Automation/singleshell/config/RegistryStringResourceIndirect.cs +++ b/src/System.Management.Automation/singleshell/config/RegistryStringResourceIndirect.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -615,3 +616,5 @@ namespace System.Management.Automation } + +#endif diff --git a/src/System.Management.Automation/singleshell/config/RunspaceConfigForSingleShell.cs b/src/System.Management.Automation/singleshell/config/RunspaceConfigForSingleShell.cs index 3a8404f24..6a05afde1 100644 --- a/src/System.Management.Automation/singleshell/config/RunspaceConfigForSingleShell.cs +++ b/src/System.Management.Automation/singleshell/config/RunspaceConfigForSingleShell.cs @@ -617,7 +617,8 @@ namespace System.Management.Automation.Runspaces try { - assembly = Assembly.Load(new AssemblyName(mshsnapinInfo.AssemblyName)); + // WARNING: DUPLICATE CODE see InitialSessionState + assembly = ClrFacade.Load(new AssemblyName(mshsnapinInfo.AssemblyName)); } catch (FileLoadException e) { diff --git a/src/System.Management.Automation/singleshell/installer/CustomMshSnapin.cs b/src/System.Management.Automation/singleshell/installer/CustomMshSnapin.cs index 4ca1b6730..7561274ff 100644 --- a/src/System.Management.Automation/singleshell/installer/CustomMshSnapin.cs +++ b/src/System.Management.Automation/singleshell/installer/CustomMshSnapin.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -152,3 +153,5 @@ namespace System.Management.Automation } } } + +#endif diff --git a/src/System.Management.Automation/singleshell/installer/MshCoreMshSnapin.cs b/src/System.Management.Automation/singleshell/installer/MshCoreMshSnapin.cs index ec52d59e3..1505647a4 100644 --- a/src/System.Management.Automation/singleshell/installer/MshCoreMshSnapin.cs +++ b/src/System.Management.Automation/singleshell/installer/MshCoreMshSnapin.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -127,3 +128,5 @@ namespace Microsoft.PowerShell } } } + +#endif diff --git a/src/System.Management.Automation/singleshell/installer/MshInstaller.cs b/src/System.Management.Automation/singleshell/installer/MshInstaller.cs index a20d362b2..029a4afa5 100644 --- a/src/System.Management.Automation/singleshell/installer/MshInstaller.cs +++ b/src/System.Management.Automation/singleshell/installer/MshInstaller.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -218,3 +219,5 @@ namespace System.Management.Automation } } } + +#endif diff --git a/src/System.Management.Automation/singleshell/installer/MshSnapin.cs b/src/System.Management.Automation/singleshell/installer/MshSnapin.cs index 0b80f4318..1a8c227ce 100644 --- a/src/System.Management.Automation/singleshell/installer/MshSnapin.cs +++ b/src/System.Management.Automation/singleshell/installer/MshSnapin.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -86,3 +87,5 @@ namespace System.Management.Automation } } } + +#endif diff --git a/src/System.Management.Automation/singleshell/installer/MshSnapinInstaller.cs b/src/System.Management.Automation/singleshell/installer/MshSnapinInstaller.cs index 94c0185e4..e70cb5641 100644 --- a/src/System.Management.Automation/singleshell/installer/MshSnapinInstaller.cs +++ b/src/System.Management.Automation/singleshell/installer/MshSnapinInstaller.cs @@ -1,3 +1,4 @@ +#if !CORECLR /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -163,3 +164,5 @@ namespace System.Management.Automation } } } + +#endif diff --git a/src/System.Management.Automation/utils/BackgroundDispatcher.cs b/src/System.Management.Automation/utils/BackgroundDispatcher.cs index 00a28e885..4beef2907 100644 --- a/src/System.Management.Automation/utils/BackgroundDispatcher.cs +++ b/src/System.Management.Automation/utils/BackgroundDispatcher.cs @@ -1,4 +1,5 @@ -//----------------------------------------------------------------------- +#if !CORECLR +//----------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved. // @@ -138,3 +139,5 @@ namespace System.Management.Automation #endregion } } + +#endif diff --git a/src/System.Management.Automation/utils/ClrFacade.cs b/src/System.Management.Automation/utils/ClrFacade.cs index bbf4c9805..141fe20e6 100644 --- a/src/System.Management.Automation/utils/ClrFacade.cs +++ b/src/System.Management.Automation/utils/ClrFacade.cs @@ -240,37 +240,8 @@ namespace System.Management.Automation [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static string GetAssemblyLocation(Assembly assembly) { -#if CORECLR // Assembly.Location is not in CoreCLR; Use Assembly.ManifestModule.FullyQualifiedName to substitute it. - // According to MSDN: - // 1. Assembly.Location returns the location of the loaded file that contains the manifest. - // 2. Assembly.ManifestModule returns the module that contains the manifest for the assembly. - // 3. Module.FullyQualifiedName returns a string representing the fully qualified name and path to this module. - // - // When the actual assembly is .ni.dll, 'ManifestModule.FullyQualifiedName' still returns the IL dll name, e.g. System.Collections.dll. - // So we need to check if the path exists before returning it, and try the .ni.dll path again if it doesn't exist. - const string DllExt = ".dll"; - const string NiDllExt = ".ni.dll"; - - string path = assembly.ManifestModule.FullyQualifiedName; - if (File.Exists(path)) - { - return path; - } - - if (path.EndsWith(DllExt, StringComparison.OrdinalIgnoreCase) && - !path.EndsWith(NiDllExt, StringComparison.OrdinalIgnoreCase)) - { - path = Path.ChangeExtension(path, NiDllExt); - if (File.Exists(path)) - { - return path; - } - } - // This could happen if the passed-in assembly is a dynamic assembly. - return null; -#else + // Porting note: Asembly.Location is in recent CoreCLR return assembly.Location; -#endif } /// @@ -337,6 +308,34 @@ namespace System.Management.Automation } #endif + /// + /// Porting note: Load assembly by name through the AssemblyLoadContext. + /// This is to ensure that the types get cached. + /// + internal static Assembly Load(AssemblyName assembly) + { +#if CORECLR + var psAssemblyLoader = GetAssemblyLoadContext(); + return psAssemblyLoader.LoadFromAssemblyName(assembly); +#else + return Assembly.Load(assembly); +#endif + } + + /// + /// Same as the above, but overloaded for a name in a string. + /// + internal static Assembly Load(string assembly) + { +#if CORECLR + var psAssemblyLoader = GetAssemblyLoadContext(); + return psAssemblyLoader.LoadFromAssemblyName(new AssemblyName(assembly)); +#else + return Assembly.Load(assembly); +#endif + } + + /// /// Facade for EnumBuilder.CreateTypeInfo /// @@ -570,20 +569,8 @@ namespace System.Management.Automation /// internal static DirectoryInfo GetParent(string path) { -#if CORECLR - // Implementation copied from .NET source code. - if (string.IsNullOrEmpty(path)) - throw new ArgumentNullException("path"); - - string fullPath = Path.GetFullPath(path); - - string s = Path.GetDirectoryName(fullPath); - if (s == null) - return null; - return new DirectoryInfo(s); -#else + // Porting note: this is in recent CoreCLR return Directory.GetParent(path); -#endif } /// diff --git a/src/System.Management.Automation/utils/ExtensionMethods.cs b/src/System.Management.Automation/utils/ExtensionMethods.cs index a25aefe17..32948d31f 100644 --- a/src/System.Management.Automation/utils/ExtensionMethods.cs +++ b/src/System.Management.Automation/utils/ExtensionMethods.cs @@ -29,12 +29,15 @@ namespace System.Management.Automation internal static class EnumerableExtensions { +#if !CORECLR + // Porting note: .NET Core has this, but full .NET does not internal static IEnumerable Append(this IEnumerable collection, T element) { foreach (T t in collection) yield return t; yield return element; } +#endif internal static IEnumerable Prepend(this IEnumerable collection, T element) { @@ -128,6 +131,11 @@ namespace System.Management.Automation [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool IsComObject(this Type type) { + if (!Platform.HasCom()) + { + return false; + } + #if CORECLR // Type.IsComObject(Type) is not in CoreCLR return ComObjectType.IsAssignableFrom(type); #else diff --git a/src/System.Management.Automation/utils/GraphicalHostReflectionWrapper.cs b/src/System.Management.Automation/utils/GraphicalHostReflectionWrapper.cs index b93c7ec62..4f71be6c1 100644 --- a/src/System.Management.Automation/utils/GraphicalHostReflectionWrapper.cs +++ b/src/System.Management.Automation/utils/GraphicalHostReflectionWrapper.cs @@ -1,4 +1,5 @@ -//----------------------------------------------------------------------- +#if !CORECLR +//----------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved. // @@ -223,3 +224,5 @@ namespace System.Management.Automation.Internal } } } + +#endif diff --git a/src/System.Management.Automation/utils/PowerShellETWTracer.cs b/src/System.Management.Automation/utils/PowerShellETWTracer.cs index 53bc633e9..7685073ba 100644 --- a/src/System.Management.Automation/utils/PowerShellETWTracer.cs +++ b/src/System.Management.Automation/utils/PowerShellETWTracer.cs @@ -1,7 +1,8 @@ +#if !NOETW // // Copyright (C) Microsoft. All rights reserved. // -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.Linq; @@ -1595,4 +1596,6 @@ namespace System.Management.Automation.Tracing } } //pragma warning restore 16001,16003 -} \ No newline at end of file +} + +#endif diff --git a/src/System.Management.Automation/utils/PsUtils.cs b/src/System.Management.Automation/utils/PsUtils.cs index c51a3ebfb..deb01a119 100644 --- a/src/System.Management.Automation/utils/PsUtils.cs +++ b/src/System.Management.Automation/utils/PsUtils.cs @@ -584,6 +584,19 @@ namespace System.Management.Automation } internal static string GetHostName() + { + // Note: non-windows CoreCLR does not support System.Net yet + if (Platform.IsWindows()) + { + return WinGetHostName(); + } + else + { + return Platform.NonWindowsGetHostName(); + } + } + + internal static string WinGetHostName() { System.Net.NetworkInformation.IPGlobalProperties ipProperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); @@ -598,6 +611,18 @@ namespace System.Management.Automation } internal static uint GetNativeThreadId() + { + if (Platform.IsWindows()) + { + return WinGetNativeThreadId(); + } + else + { + return Platform.NonWindowsGetThreadId(); + } + } + + internal static uint WinGetNativeThreadId() { return NativeMethods.GetCurrentThreadId(); } diff --git a/src/System.Management.Automation/utils/WindowsErrorReporting.cs b/src/System.Management.Automation/utils/WindowsErrorReporting.cs index 5d6b8896e..8d7d7e79d 100644 --- a/src/System.Management.Automation/utils/WindowsErrorReporting.cs +++ b/src/System.Management.Automation/utils/WindowsErrorReporting.cs @@ -1,7 +1,8 @@ +#if !CORECLR // // Copyright (C) Microsoft. All rights reserved. // -using System.Diagnostics; +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; @@ -129,7 +130,7 @@ namespace System.Management.Automation HonorRestart = 2, /// - /// Add the report to the WER queue without notifying the user. The report is queued only—reporting (sending the report to Microsoft) occurs later based on the user's consent level. + /// Add the report to the WER queue without notifying the user. The report is queued only-reporting (sending the report to Microsoft) occurs later based on the user's consent level. /// Queue = 4, @@ -1043,3 +1044,5 @@ namespace System.Management.Automation #endregion } } + +#endif diff --git a/src/System.Management.Automation/utils/perfCounters/CounterSetInstanceBase.cs b/src/System.Management.Automation/utils/perfCounters/CounterSetInstanceBase.cs index a38e96a7f..3acd83528 100644 --- a/src/System.Management.Automation/utils/perfCounters/CounterSetInstanceBase.cs +++ b/src/System.Management.Automation/utils/perfCounters/CounterSetInstanceBase.cs @@ -1,4 +1,5 @@ -/********************************************************************++ +#if !CORECLR +/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -603,3 +604,5 @@ namespace System.Management.Automation.PerformanceData } } + +#endif diff --git a/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs b/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs index 215e0a5a1..c51cb765a 100644 --- a/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs +++ b/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs @@ -1,4 +1,5 @@ -/********************************************************************++ +#if !CORECLR +/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -363,3 +364,5 @@ namespace System.Management.Automation.PerformanceData } } + +#endif diff --git a/src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs b/src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs index a533978e2..97061e3f2 100644 --- a/src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs +++ b/src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs @@ -1,4 +1,5 @@ -/********************************************************************++ +#if !CORECLR +/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -474,3 +475,5 @@ namespace System.Management.Automation.PerformanceData } } + +#endif diff --git a/src/System.Management.Automation/utils/tracing/EtwActivity.cs b/src/System.Management.Automation/utils/tracing/EtwActivity.cs index 6abd12063..19ed45d07 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivity.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivity.cs @@ -1,3 +1,4 @@ +#if !NOETW // // Copyright (C) Microsoft. All rights reserved. // @@ -547,3 +548,6 @@ namespace System.Management.Automation.Tracing } } } + + +#endif diff --git a/src/System.Management.Automation/utils/tracing/EtwActivityReverter.cs b/src/System.Management.Automation/utils/tracing/EtwActivityReverter.cs index 21e1236a7..ec3b9d385 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivityReverter.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivityReverter.cs @@ -1,4 +1,5 @@ -//----------------------------------------------------------------------- +#if !NOETW +//----------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved. // @@ -58,3 +59,6 @@ namespace System.Management.Automation.Tracing } } } + + +#endif diff --git a/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs b/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs index 722ff6a11..3cd849ea9 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs @@ -1,4 +1,5 @@ -//----------------------------------------------------------------------- +#if !NOETW +//----------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved. // @@ -68,3 +69,6 @@ namespace System.Management.Automation.Tracing #endregion } } + + +#endif diff --git a/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs b/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs index 4dc1221d8..a8df80b9e 100644 --- a/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs +++ b/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs @@ -1,4 +1,5 @@ -//----------------------------------------------------------------------- +#if !NOETW +//----------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved. // @@ -115,3 +116,6 @@ namespace System.Management.Automation.Tracing } } } + + +#endif diff --git a/src/System.Management.Automation/utils/tracing/IMethodInvoker.cs b/src/System.Management.Automation/utils/tracing/IMethodInvoker.cs index 37570678d..980788273 100644 --- a/src/System.Management.Automation/utils/tracing/IMethodInvoker.cs +++ b/src/System.Management.Automation/utils/tracing/IMethodInvoker.cs @@ -1,4 +1,5 @@ -//----------------------------------------------------------------------- +#if !NOETW +//----------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved. // @@ -14,3 +15,6 @@ namespace System.Management.Automation.Tracing object[] CreateInvokerArgs(Delegate methodToInvoke, object[] methodToInvokeArgs); } } + + +#endif diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs index d2d1b058a..c784b2975 100644 --- a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs @@ -1,3 +1,4 @@ +#if !NOETW // // Copyright (C) Microsoft. All rights reserved. // @@ -310,3 +311,6 @@ namespace System.Management.Automation.Tracing } } } + + +#endif diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs index 32bd8baa4..2f8d206e2 100644 --- a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs @@ -1,3 +1,4 @@ +#if !NOETW // // Copyright (C) Microsoft. All rights reserved. // @@ -462,4 +463,6 @@ namespace System.Management.Automation.Tracing EventProvider.SetActivityId(ref result); } } -} \ No newline at end of file +} + +#endif diff --git a/src/System.Management.Automation/utils/tracing/Tracing.cs b/src/System.Management.Automation/utils/tracing/Tracing.cs index 301d9ac98..eea3605ad 100644 --- a/src/System.Management.Automation/utils/tracing/Tracing.cs +++ b/src/System.Management.Automation/utils/tracing/Tracing.cs @@ -1,3 +1,4 @@ +#if !NOETW // // Copyright (C) Microsoft. All rights reserved. // @@ -52,4 +53,6 @@ namespace System.Management.Automation.Tracing { return true; } } -} \ No newline at end of file +} + +#endif diff --git a/src/System.Management.Automation/utils/tracing/TracingGen.cs b/src/System.Management.Automation/utils/tracing/TracingGen.cs index 35ff735ff..30564cff1 100644 --- a/src/System.Management.Automation/utils/tracing/TracingGen.cs +++ b/src/System.Management.Automation/utils/tracing/TracingGen.cs @@ -1,3 +1,4 @@ +#if !NOETW using System; using System.Collections; using System.Diagnostics.Eventing; @@ -987,3 +988,5 @@ namespace System.Management.Automation.Tracing { } // This code was generated on 02/01/2012 19:52:32 + +#endif diff --git a/src/TypeCatalogGen/TypeCatalogGen.cs b/src/TypeCatalogGen/TypeCatalogGen.cs index 3bc70e07d..ecaff01c0 100644 --- a/src/TypeCatalogGen/TypeCatalogGen.cs +++ b/src/TypeCatalogGen/TypeCatalogGen.cs @@ -14,6 +14,7 @@ */ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; @@ -90,7 +91,16 @@ Usage: TypeCatalogGen.exe <{0}> <{1}> } string fullName = GetTypeFullName(metadataReader, typeDefinition); - typeNameToAssemblyMap.Add(fullName, strongAssemblyName); + + // Only add unique types + if (!typeNameToAssemblyMap.ContainsKey(fullName)) + { + typeNameToAssemblyMap.Add(fullName, strongAssemblyName); + } + else + { + Debug.WriteLine($"Not adding duplicate key {fullName}!"); + } } } } diff --git a/src/powershell-native/nativemsh/pwrshcommon/ConfigFileReader.cpp b/src/powershell-native/nativemsh/pwrshcommon/ConfigFileReader.cpp index 6a23239a0..a070b6782 100644 --- a/src/powershell-native/nativemsh/pwrshcommon/ConfigFileReader.cpp +++ b/src/powershell-native/nativemsh/pwrshcommon/ConfigFileReader.cpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include "NativeMsh.h" #include "ConfigFileReader.h"