diff --git a/.travis.yml b/.travis.yml
index 06d3135f1a..2dcd41aa54 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -8,7 +8,7 @@ os:
- osx
sudo: required
dist: trusty
-osx_image: xcode7.3
+osx_image: xcode8.1
matrix:
fast_finish: true
@@ -25,7 +25,7 @@ install:
- popd
# Default 2.0.0 Ruby is buggy
# Default bundler version is buggy
- - if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then rvm use 2.3.1; gem uninstall bundler -v1.13.1; fi
+ - if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then rvm install ruby-2.3.1; rvm use 2.3.1; fi
# spellcheck
- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then
nvm install 6.4.0 &&
diff --git a/appveyor.yml b/appveyor.yml
index fd66fb1788..e7b4d03b7a 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -2,9 +2,10 @@ version: 6.0.0-alpha.18-{build}
image: Visual Studio 2015
+# cache version - netcoreapp.2.0.0-preview1-001913-00
cache:
- - '%LocalAppData%\Microsoft\dotnet'
- - '%HOMEDRIVE%%HOMEPATH%\.nuget\packages'
+ - '%LocalAppData%\Microsoft\dotnet -> appveyor.yml'
+ - '%HOMEDRIVE%%HOMEPATH%\.nuget\packages -> appveyor.yml'
nuget:
project_feed: true
diff --git a/build.psm1 b/build.psm1
index ebefa46b13..5108a3e874 100644
--- a/build.psm1
+++ b/build.psm1
@@ -265,15 +265,6 @@ function Start-PSBuild {
}
($srcProjectDirs + $testProjectDirs) | % { Start-NativeExecution { dotnet restore $_ $RestoreArguments } }
-
- # .NET Core's crypto library needs brew's OpenSSL libraries added to its rpath
- if ($IsOSX) {
- # This is the restored library used to build
- # This is allowed to fail since the user may have already restored
- Write-Warning ".NET Core links the incorrect OpenSSL, correcting NuGet package libraries..."
- find $env:HOME/.nuget -name System.Security.Cryptography.Native.OpenSsl.dylib | % { sudo install_name_tool -add_rpath /usr/local/opt/openssl/lib $_ }
- find $env:HOME/.nuget -name System.Net.Http.Native.dylib | % { sudo install_name_tool -change /usr/lib/libcurl.4.dylib /usr/local/opt/curl/lib/libcurl.4.dylib $_ }
- }
}
# handle ResGen
@@ -414,6 +405,8 @@ cmd.exe /C cd /d "$location" "&" "$($vcVarsPath)\vcvarsall.bat" "$NativeHostArch
Start-TypeGen
}
+ # Get the folder path where powershell.exe is located.
+ $publishPath = Split-Path $Options.Output -Parent
try {
# Relative paths do not work well if cwd is not changed to project
Push-Location $Options.Top
@@ -421,7 +414,6 @@ cmd.exe /C cd /d "$location" "&" "$($vcVarsPath)\vcvarsall.bat" "$NativeHostArch
Start-NativeExecution { dotnet $Arguments }
if ($CrossGen) {
- $publishPath = Split-Path $Options.Output
Start-CrossGen -PublishPath $publishPath -Runtime $script:Options.Runtime
log "PowerShell.exe with ngen binaries is available at: $($Options.Output)"
} else {
@@ -431,13 +423,32 @@ cmd.exe /C cd /d "$location" "&" "$($vcVarsPath)\vcvarsall.bat" "$NativeHostArch
Pop-Location
}
+ # add 'x' permission when building the standalone application
+ # this is temporary workaround to a bug in dotnet.exe, tracking by dotnet/cli issue #6286
+ if ($Options.Configuration -eq "Linux" -and $Options.Publish) {
+ chmod u+x $Options.Output
+ }
+
+ # publish netcoreapp2.0 reference assemblies
+ try {
+ Push-Location "$PSScriptRoot/src/TypeCatalogGen"
+ $refAssemblies = Get-Content -Path "powershell.inc" | ? { $_ -like "*microsoft.netcore.app*" } | % { $_.TrimEnd(';') }
+ $refDestFolder = Join-Path -Path $publishPath -ChildPath "ref"
+
+ if (Test-Path $refDestFolder -PathType Container) {
+ Remove-Item $refDestFolder -Force -Recurse -ErrorAction Stop
+ }
+ New-Item -Path $refDestFolder -ItemType Directory -Force -ErrorAction Stop > $null
+ Copy-Item -Path $refAssemblies -Destination $refDestFolder -Force -ErrorAction Stop
+ } finally {
+ Pop-Location
+ }
+
+ # download modules from powershell gallery.
+ # - PowerShellGet, PackageManagement, Microsoft.PowerShell.Archive
if($PSModuleRestore)
{
$ProgressPreference = "SilentlyContinue"
- # Downloading the PowerShellGet and PackageManagement modules.
- # $Options.Output is pointing to something like "...\src\powershell-win-core\bin\Debug\netcoreapp1.1\win10-x64\publish\powershell.exe",
- # so we need to get its parent directory
- $publishPath = Split-Path $Options.Output -Parent
log "Restore PowerShell modules to $publishPath"
$modulesDir = Join-Path -Path $publishPath -ChildPath "Modules"
@@ -474,7 +485,7 @@ function New-PSOptions {
[ValidateSet("Linux", "Debug", "Release", "CodeCoverage", "")]
[string]$Configuration,
- [ValidateSet("netcoreapp1.1", "net451")]
+ [ValidateSet("netcoreapp2.0", "net451")]
[string]$Framework,
# These are duplicated from Start-PSBuild
@@ -561,7 +572,7 @@ function New-PSOptions {
$Framework = if ($FullCLR) {
"net451"
} else {
- "netcoreapp1.1"
+ "netcoreapp2.0"
}
Write-Verbose "Using framework '$Framework'"
}
@@ -694,7 +705,7 @@ function Publish-PSTestTools {
Find-Dotnet
- $tools = "$PSScriptRoot/test/tools/EchoArgs","$PSScriptRoot/test/tools/CreateChildProcess"
+ $tools = @("$PSScriptRoot/test/tools/EchoArgs", "echoargs"), @("$PSScriptRoot/test/tools/CreateChildProcess", "createchildprocess")
if ($Options -eq $null)
{
$Options = New-PSOptions
@@ -703,9 +714,16 @@ function Publish-PSTestTools {
# Publish EchoArgs so it can be run by tests
foreach ($tool in $tools)
{
- Push-Location $tool
+ Push-Location $tool[0]
try {
dotnet publish --output bin --configuration $Options.Configuration --framework $Options.Framework --runtime $Options.Runtime
+
+ # add 'x' permission when building the standalone application
+ # this is temporary workaround to a bug in dotnet.exe, tracking by dotnet/cli issue #6286
+ if ($Options.Configuration -eq "Linux") {
+ $executable = Join-Path -Path $tool[0] -ChildPath "bin/$($tool[1])"
+ chmod u+x $executable
+ }
} finally {
Pop-Location
}
@@ -972,8 +990,8 @@ function Start-PSxUnit {
function Install-Dotnet {
[CmdletBinding()]
param(
- [string]$Channel,
- [string]$Version,
+ [string]$Channel = "preview",
+ [string]$Version = "2.0.0-preview1-005724",
[switch]$NoSudo
)
@@ -981,7 +999,7 @@ function Install-Dotnet {
# Note that when it is null, Invoke-Expression (but not &) must be used to interpolate properly
$sudo = if (!$NoSudo) { "sudo" }
- $obtainUrl = "https://raw.githubusercontent.com/dotnet/cli/v1.0.1/scripts/obtain"
+ $obtainUrl = "https://raw.githubusercontent.com/dotnet/cli/master/scripts/obtain"
# Install for Linux and OS X
if ($IsLinux -or $IsOSX) {
@@ -1007,14 +1025,6 @@ function Install-Dotnet {
curl -sO $obtainUrl/$installScript
bash ./$installScript -c $Channel -v $Version
}
-
- # .NET Core's crypto library needs brew's OpenSSL libraries added to its rpath
- if ($IsOSX) {
- # This is the library shipped with .NET Core
- # This is allowed to fail as the user may have installed other versions of dotnet
- Write-Warning ".NET Core links the incorrect OpenSSL, correcting .NET CLI libraries..."
- find $env:HOME/.dotnet -name System.Security.Cryptography.Native.OpenSsl.dylib | % { sudo install_name_tool -add_rpath /usr/local/opt/openssl/lib $_ }
- }
} elseif ($IsWindows) {
Remove-Item -ErrorAction SilentlyContinue -Recurse -Force ~\AppData\Local\Microsoft\dotnet
$installScript = "dotnet-install.ps1"
@@ -1040,11 +1050,10 @@ function Start-PSBootstrap {
SupportsShouldProcess=$true,
ConfirmImpact="High")]
param(
- [string]$Channel = "rel-1.0.0",
- # we currently pin dotnet-cli version, because tool
- # is currently migrating to msbuild toolchain
- # and requires constant updates to our build process.
- [string]$Version = "1.0.1",
+ [string]$Channel = "preview",
+ # we currently pin dotnet-cli version, and will
+ # update it when more stable version comes out.
+ [string]$Version = "2.0.0-preview1-005724",
[switch]$Package,
[switch]$NoSudo,
[switch]$Force
@@ -1250,7 +1259,7 @@ function Start-PSPackage {
-not $Script:Options.CrossGen -or ## Last build didn't specify -CrossGen
$Script:Options.Runtime -ne $Runtime -or ## Last build wasn't for the required RID
$Script:Options.Configuration -ne $Configuration -or ## Last build was with configuration other than 'Release'
- $Script:Options.Framework -ne "netcoreapp1.1") ## Last build wasn't for CoreCLR
+ $Script:Options.Framework -ne "netcoreapp2.0") ## Last build wasn't for CoreCLR
{
# It's possible that the most recent build doesn't satisfy the package requirement but
# an earlier build does. e.g., run the following in order on win10-x64:
@@ -2048,11 +2057,11 @@ function Start-TypeGen
$GetDependenciesTargetValue = @'
+ DependsOnTargets="ResolveAssemblyReferencesDesignTime">
- <_DependentAssemblyPath Include="%(_DependenciesDesignTime.Path)%3B" Condition=" '%(_DependenciesDesignTime.Type)' == 'Assembly' And '%(_DependenciesDesignTime.Name)' != 'Microsoft.Management.Infrastructure.Native.dll' And '%(_DependenciesDesignTime.Name)' != 'Microsoft.Management.Infrastructure.dll' " />
+ <_RefAssemblyPath Include="%(_ReferencesFromRAR.ResolvedPath)%3B" Condition=" '%(_ReferencesFromRAR.Type)' == 'assembly' And '%(_ReferencesFromRAR.PackageName)' != 'Microsoft.Management.Infrastructure' " />
-
+
'@
@@ -2771,19 +2780,9 @@ function Start-CrossGen {
"win7-x64"
}
} elseif ($IsLinux) {
- if ($IsUbuntu) {
- "ubuntu.14.04-x64"
- } elseif ($IsCentOS) {
- "rhel.7-x64"
- } elseif ($IsFedora) {
- "fedora.24-x64"
- } elseif ($IsOpenSUSE13) {
- "opensuse.13.2-x64"
- } elseif (${IsOpenSUSE42.1}) {
- "opensuse.42.1-x64"
- }
+ "linux-x64"
} elseif ($IsOSX) {
- "osx.10.10-x64"
+ "osx.10.12-x64"
}
if (-not $crossGenRuntime) {
@@ -2827,8 +2826,6 @@ function Start-CrossGen {
$commonAssembliesForAddType = @(
"Microsoft.CodeAnalysis.CSharp.dll"
"Microsoft.CodeAnalysis.dll"
- "Microsoft.CodeAnalysis.VisualBasic.dll"
- "Microsoft.CSharp.dll"
)
# Common PowerShell libraries to crossgen
diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/Microsoft.Management.Infrastructure.CimCmdlets.csproj b/src/Microsoft.Management.Infrastructure.CimCmdlets/Microsoft.Management.Infrastructure.CimCmdlets.csproj
index 25527c1fc0..81d02a3dab 100644
--- a/src/Microsoft.Management.Infrastructure.CimCmdlets/Microsoft.Management.Infrastructure.CimCmdlets.csproj
+++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/Microsoft.Management.Infrastructure.CimCmdlets.csproj
@@ -2,7 +2,7 @@
6.0.0
- netstandard1.6
+ netcoreapp2.0
true
true
Microsoft.Management.Infrastructure.CimCmdlets
@@ -16,7 +16,7 @@
-
+
$(DefineConstants);CORECLR
portable
diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CoreCLR/Stubs.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CoreCLR/Stubs.cs
index 451331418e..88b3a6f134 100644
--- a/src/Microsoft.PowerShell.Commands.Diagnostics/CoreCLR/Stubs.cs
+++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CoreCLR/Stubs.cs
@@ -1,7 +1,6 @@
#if CORECLR
using System.ComponentModel;
-using Microsoft.PowerShell.CoreClr.Stubs;
namespace System.Diagnostics
{
diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj b/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj
index d3fa64b993..7de1cbfae4 100644
--- a/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj
+++ b/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj
@@ -2,7 +2,7 @@
6.0.0
- netstandard1.6
+ netcoreapp2.0
$(NoWarn);CS1591
true
true
@@ -19,11 +19,11 @@
-
+
$(DefineConstants);CORECLR
-
+
diff --git a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj
index bdd7e584ac..d1195d345a 100644
--- a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj
+++ b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj
@@ -2,7 +2,7 @@
6.0.0
- netstandard1.6
+ netcoreapp2.0
$(NoWarn);CS1570
true
true
@@ -20,11 +20,11 @@
-
+
$(DefineConstants);CORECLR
-
+
@@ -77,10 +77,8 @@
full
-
-
-
-
+
+
diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs
index 907795da29..53c531b79f 100644
--- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs
+++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs
@@ -9,11 +9,6 @@ using System.Runtime.Serialization;
using Microsoft.Management.Infrastructure;
using Dbg = System.Management.Automation.Diagnostics;
-#if CORECLR
-// Use stubs for SerializableAttribute, SystemException and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace Microsoft.PowerShell.Cmdletization.Cim
{
///
diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs
index 7b8b61136a..30fec5de0b 100644
--- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs
+++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs
@@ -15,13 +15,6 @@ using Microsoft.Management.Infrastructure.Options;
using Microsoft.PowerShell.Cim;
using Dbg = System.Management.Automation.Diagnostics;
-#if CORECLR
-// Some APIs are missing from System.Environment. We use System.Management.Automation.Environment as a proxy type:
-// - for missing APIs, System.Management.Automation.Environment has extension implementation.
-// - for existing APIs, System.Management.Automation.Environment redirect the call to System.Environment.
-using Environment = System.Management.Automation.Environment;
-#endif
-
namespace Microsoft.PowerShell.Cmdletization.Cim
{
///
diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs
index 7b7f908c61..35e968d4d3 100644
--- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs
+++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs
@@ -8,6 +8,7 @@ using System.Diagnostics;
using System.Globalization;
using System.Management.Automation;
using System.Net;
+using System.Net.Mail;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Security;
@@ -18,13 +19,6 @@ using Microsoft.Management.Infrastructure;
using Dbg = System.Management.Automation.Diagnostics;
using System.Runtime.InteropServices;
-#if CORECLR
-// Use stub for MailAddress.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#else
-using System.Net.Mail;
-#endif
-
// TODO/FIXME: Move this class to src/cimSupport/other directory (to map to the namespace it lives in and functionality it implements [cmdletization independent])
namespace Microsoft.PowerShell.Cim
diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs
index 37ba3f4d78..3f92fb8049 100644
--- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs
+++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs
@@ -18,6 +18,7 @@ using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security.Cryptography;
+using System.Security.Permissions;
using System.Text;
using System.Threading;
using Microsoft.Win32;
@@ -32,8 +33,6 @@ using Microsoft.PowerShell.CoreClr.Stubs;
#else
//TODO:CORECLR System.DirectoryServices is not available on CORE CLR
using System.DirectoryServices;
-//TODO:CORECLR System.Security.Permission is not available on CORE CLR
-using System.Security.Permissions;
using System.Management; // We are not porting the library to CoreCLR
using Microsoft.WSMan.Management;
#endif
diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs
index 206f5a6b9e..ed1b0881ab 100644
--- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs
+++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs
@@ -9,6 +9,7 @@ using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics; // Process class
using System.ComponentModel; // Win32Exception
+using System.Runtime.ConstrainedExecution;
using System.Runtime.Serialization;
using System.Threading;
using System.Management.Automation;
@@ -17,6 +18,7 @@ using System.Net;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
+using System.Security.Permissions;
using System.Security.Principal;
using Microsoft.Win32.SafeHandles;
using System.Management.Automation.Internal;
@@ -26,15 +28,6 @@ using Microsoft.Management.Infrastructure;
using FileNakedHandle = System.IntPtr;
using DWORD = System.UInt32;
-#if CORECLR
-// Use stubs for SafeHandleZeroOrMinusOneIsInvalid and SerializableAttribute
-using Microsoft.PowerShell.CoreClr.Stubs;
-using Environment = System.Management.Automation.Environment;
-#else
-using System.Runtime.ConstrainedExecution;
-using System.Security.Permissions;
-#endif
-
namespace Microsoft.PowerShell.Commands
{
// 2004/12/17-JonN ProcessNameGlobAttribute was deeply wrong.
@@ -752,13 +745,143 @@ namespace Microsoft.PowerShell.Commands
}
else
{
- WriteObject(ClrFacade.AddProcessProperties(IncludeUserName.IsPresent, process));
+ WriteObject(IncludeUserName.IsPresent ? AddUserNameToProcess(process) : (object)process);
}
}//for loop
} // ProcessRecord
#endregion Overrides
+ #region Privates
+
+ ///
+ /// New PSTypeName added to the process object
+ ///
+ private const string TypeNameForProcessWithUserName = "System.Diagnostics.Process#IncludeUserName";
+
+ ///
+ /// Add the 'UserName' NoteProperty to the Process object
+ ///
+ ///
+ ///
+ private static PSObject AddUserNameToProcess(Process process)
+ {
+ // Return null if we failed to get the owner information
+ string userName = RetrieveProcessUserName(process);
+
+ PSObject processAsPsobj = PSObject.AsPSObject(process);
+ PSNoteProperty noteProperty = new PSNoteProperty("UserName", userName);
+
+ processAsPsobj.Properties.Add(noteProperty, true);
+ processAsPsobj.TypeNames.Insert(0, TypeNameForProcessWithUserName);
+
+ return processAsPsobj;
+ }
+
+
+ ///
+ /// Retrieve the UserName through PInvoke
+ ///
+ ///
+ ///
+ private static string RetrieveProcessUserName(Process process)
+ {
+ string userName = null;
+#if UNIX
+ userName = Platform.NonWindowsGetUserFromPid(process.Id);
+#else
+ IntPtr tokenUserInfo = IntPtr.Zero;
+ IntPtr processTokenHandler = IntPtr.Zero;
+
+ const uint TOKEN_QUERY = 0x0008;
+
+ try
+ {
+ do
+ {
+ int error;
+ if (!Win32Native.OpenProcessToken(ClrFacade.GetSafeProcessHandle(process), TOKEN_QUERY, out processTokenHandler)) { break; }
+
+ // Set the default length to be 256, so it will be sufficient for most cases
+ int tokenInfoLength = 256;
+ tokenUserInfo = Marshal.AllocHGlobal(tokenInfoLength);
+ if (!Win32Native.GetTokenInformation(processTokenHandler, Win32Native.TOKEN_INFORMATION_CLASS.TokenUser, tokenUserInfo, tokenInfoLength, out tokenInfoLength))
+ {
+ error = Marshal.GetLastWin32Error();
+ if (error == Win32Native.ERROR_INSUFFICIENT_BUFFER)
+ {
+ Marshal.FreeHGlobal(tokenUserInfo);
+ tokenUserInfo = Marshal.AllocHGlobal(tokenInfoLength);
+
+ if (!Win32Native.GetTokenInformation(processTokenHandler, Win32Native.TOKEN_INFORMATION_CLASS.TokenUser, tokenUserInfo, tokenInfoLength, out tokenInfoLength)) { break; }
+ }
+ else
+ {
+ break;
+ }
+ }
+
+ var tokenUser = ClrFacade.PtrToStructure(tokenUserInfo);
+
+ // Set the default length to be 256, so it will be sufficient for most cases
+ int userNameLength = 256, domainNameLength = 256;
+ var userNameStr = new StringBuilder(userNameLength);
+ var domainNameStr = new StringBuilder(domainNameLength);
+ Win32Native.SID_NAME_USE accountType;
+
+ if (!Win32Native.LookupAccountSid(null, tokenUser.User.Sid, userNameStr, ref userNameLength, domainNameStr, ref domainNameLength, out accountType))
+ {
+ error = Marshal.GetLastWin32Error();
+ if (error == Win32Native.ERROR_INSUFFICIENT_BUFFER)
+ {
+ userNameStr.EnsureCapacity(userNameLength);
+ domainNameStr.EnsureCapacity(domainNameLength);
+
+ if (!Win32Native.LookupAccountSid(null, tokenUser.User.Sid, userNameStr, ref userNameLength, domainNameStr, ref domainNameLength, out accountType)) { break; }
+ }
+ else
+ {
+ break;
+ }
+ }
+
+ userName = domainNameStr + "\\" + userNameStr;
+ } while (false);
+ }
+ catch (NotSupportedException)
+ {
+ // The Process not started yet, or it's a process from a remote machine
+ }
+ catch (InvalidOperationException)
+ {
+ // The Process has exited, Process.Handle will raise this exception
+ }
+ catch (Win32Exception)
+ {
+ // We might get an AccessDenied error
+ }
+ catch (Exception)
+ {
+ // I don't expect to get other exceptions,
+ }
+ finally
+ {
+ if (tokenUserInfo != IntPtr.Zero)
+ {
+ Marshal.FreeHGlobal(tokenUserInfo);
+ }
+
+ if (processTokenHandler != IntPtr.Zero)
+ {
+ Win32Native.CloseHandle(processTokenHandler);
+ }
+ }
+
+#endif
+ return userName;
+ }
+
+ #endregion Privates
}//GetProcessCommand
#endregion GetProcessCommand
@@ -1873,11 +1996,7 @@ namespace Microsoft.PowerShell.Commands
{
startInfo.Domain = nwcredential.Domain;
}
-#if CORECLR
- startInfo.PasswordInClearText = ClrFacade.ConvertSecureStringToString(_credential.Password);
-#else
startInfo.Password = _credential.Password;
-#endif
}
//RedirectionInput File Check -> Not Exist -> Throw Error
@@ -2402,11 +2521,7 @@ namespace Microsoft.PowerShell.Commands
IntPtr password = IntPtr.Zero;
try
{
-#if CORECLR
- password = (startinfo.PasswordInClearText == null) ? Marshal.StringToCoTaskMemUni(string.Empty) : Marshal.StringToCoTaskMemUni(startinfo.PasswordInClearText);
-#else
- password = (startinfo.Password == null) ? Marshal.StringToCoTaskMemUni(string.Empty) : ClrFacade.SecureStringToCoTaskMemUnicode(startinfo.Password);
-#endif
+ password = (startinfo.Password == null) ? Marshal.StringToCoTaskMemUni(string.Empty) : Marshal.SecureStringToCoTaskMemUnicode(startinfo.Password);
flag = ProcessNativeMethods.CreateProcessWithLogonW(startinfo.UserName, startinfo.Domain, password, logonFlags, null, cmdLine, creationFlags, AddressOfEnvironmentBlock, startinfo.WorkingDirectory, lpStartupInfo, lpProcessInformation);
if (!flag)
{
@@ -2821,7 +2936,7 @@ namespace Microsoft.PowerShell.Commands
}
}
- [SuppressUnmanagedCodeSecurity, HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
+ [SuppressUnmanagedCodeSecurity]
internal sealed class SafeJobHandle : SafeHandleZeroOrMinusOneIsInvalid
{
internal SafeJobHandle(IntPtr jobHandle)
diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs
index 5fa6832883..fb6bedc658 100644
--- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs
+++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs
@@ -13,16 +13,10 @@ using System.Management.Automation.Internal;
using System.ComponentModel; // Win32Exception
using System.Runtime.Serialization;
using System.Runtime.InteropServices; // Marshal, DllImport
+using System.Security.Permissions;
using NakedWin32Handle = System.IntPtr;
using DWORD = System.UInt32;
-#if CORECLR
-// Use the stub for SystemException
-using Microsoft.PowerShell.CoreClr.Stubs;
-#else
-using System.Security.Permissions;
-#endif
-
namespace Microsoft.PowerShell.Commands
{
#region ServiceBaseCommand
diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj
index 19c55763fa..ce3d5d925f 100644
--- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj
+++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj
@@ -2,7 +2,7 @@
6.0.0
- netstandard1.6
+ netcoreapp2.0
$(NoWarn);CS1570
true
true
@@ -20,11 +20,11 @@
-
+
$(DefineConstants);CORECLR
-
+
@@ -89,9 +89,9 @@
full
-
-
-
+
+
+
diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs
index ae015335ed..ef824f8b65 100644
--- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs
+++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs
@@ -22,6 +22,8 @@ using Microsoft.CodeAnalysis.CSharp;
using System.IO;
using Microsoft.CodeAnalysis.Emit;
using System.Collections.Immutable;
+using System.Security;
+using PathType = System.IO.Path;
#else
using System.CodeDom.Compiler;
using System.Runtime.CompilerServices;
@@ -324,7 +326,7 @@ namespace Microsoft.PowerShell.Commands
string activeExtension = null;
foreach (string path in resolvedPaths)
{
- string currentExtension = System.IO.Path.GetExtension(path).ToUpperInvariant();
+ string currentExtension = PathType.GetExtension(path).ToUpperInvariant();
switch (currentExtension)
{
@@ -452,11 +454,9 @@ namespace Microsoft.PowerShell.Commands
get { return referencedAssemblies; }
set
{
- referencedAssemblies = value ?? Utils.EmptyArray();
- referencedAssembliesSpecified = true;
+ if (value != null) { referencedAssemblies = value; }
}
}
- internal bool referencedAssembliesSpecified = false;
internal string[] referencedAssemblies = Utils.EmptyArray();
///
@@ -964,7 +964,7 @@ namespace Microsoft.PowerShell.Commands
Assembly assembly = LoadAssemblyHelper(assemblyName);
if (assembly == null)
{
- assembly = LoadFrom(ResolveReferencedAssembly(assemblyName));
+ assembly = LoadFrom(ResolveAssemblyName(assemblyName, false));
}
if (passThru)
@@ -1015,92 +1015,135 @@ namespace Microsoft.PowerShell.Commands
}
}
- private static string s_frameworkFolder = System.IO.Path.GetDirectoryName(typeof(object).GetTypeInfo().Assembly.Location);
-
- // there are two different assemblies: framework contract and framework implementation.
- // Version 1.1.1 of Microsoft.CodeAnalysis doesn't provide a good way to handle contract separately from implementation.
- // To simplify user experience we always add both of them to references.
- // 1) It's a legitimate scenario, when user provides a custom referenced assembly that was built against the contract assembly
- // (i.e. System.Management.Automation), so we need the contract one.
- // 2) We have to provide implementation assembly explicitly, Roslyn doesn't have a way to figure out implementation by itself.
- // So we are adding both.
- private static PortableExecutableReference s_objectImplementationAssemblyReference =
- MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location);
-
- private static PortableExecutableReference s_mscorlibAssemblyReference =
- MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("mscorlib")).Location);
-
- // This assembly should be System.Runtime.dll
- private static PortableExecutableReference s_systemRuntimeAssemblyReference =
- MetadataReference.CreateFromFile(ClrFacade.GetAssemblies(typeof(object).FullName).First().Location);
-
- // SecureString is defined in a separate assembly.
- // This fact is an implementation detail and should not require the user to specify one more assembly,
- // if they want to use SecureString in Add-Type -TypeDefinition.
- // So this assembly should be in the default assemblies list to provide the best experience.
- private static PortableExecutableReference s_secureStringAssemblyReference =
- MetadataReference.CreateFromFile(typeof(System.Security.SecureString).GetTypeInfo().Assembly.Location);
-
+ // We now ship the NetCoreApp2.0 reference assemblies with PowerShell Core, so that Add-Type can work
+ // in a predictable way and won't be broken when we move to newer version of .NET Core.
+ // The NetCoreApp2.0 reference assemblies are located at '$PSHOME\ref'.
+ private static string s_netcoreAppRefFolder = PathType.Combine(PathType.GetDirectoryName(typeof(PSObject).Assembly.Location), "ref");
+ private static string s_frameworkFolder = PathType.GetDirectoryName(typeof(object).Assembly.Location);
// These assemblies are always automatically added to ReferencedAssemblies.
- private static PortableExecutableReference[] s_autoReferencedAssemblies = new PortableExecutableReference[]
- {
- s_mscorlibAssemblyReference,
- s_systemRuntimeAssemblyReference,
- s_secureStringAssemblyReference,
- s_objectImplementationAssemblyReference
- };
+ private static Lazy s_autoReferencedAssemblies = new Lazy(InitAutoIncludedRefAssemblies);
+
+ // A HashSet of assembly names to be ignored if they are specified in '-ReferencedAssemblies'
+ private static Lazy> s_refAssemblyNamesToIgnore = new Lazy>(InitRefAssemblyNamesToIgnore);
// These assemblies are used, when ReferencedAssemblies parameter is not specified.
- private static PortableExecutableReference[] s_defaultAssemblies = new PortableExecutableReference[]
- {
- s_mscorlibAssemblyReference,
- s_systemRuntimeAssemblyReference,
- s_secureStringAssemblyReference,
- s_objectImplementationAssemblyReference,
- MetadataReference.CreateFromFile(typeof(PSObject).GetTypeInfo().Assembly.Location)
- };
+ private static Lazy s_defaultAssemblies = new Lazy(InitDefaultRefAssemblies);
private bool InMemory { get { return String.IsNullOrEmpty(outputAssembly); } }
- private string ResolveReferencedAssembly(string referencedAssembly)
+ ///
+ /// Initialize the list of reference assemblies that will be used when '-ReferencedAssemblies' is not specified.
+ ///
+ private static PortableExecutableReference[] InitDefaultRefAssemblies()
+ {
+ // netcoreapp2.0 currently comes with 137 reference assemblies (maybe more in future), so we use a capacity of '150'.
+ var defaultRefAssemblies = new List(150);
+ foreach (string file in Directory.EnumerateFiles(s_netcoreAppRefFolder, "*.dll", SearchOption.TopDirectoryOnly))
+ {
+ defaultRefAssemblies.Add(MetadataReference.CreateFromFile(file));
+ }
+ defaultRefAssemblies.Add(MetadataReference.CreateFromFile(typeof(PSObject).Assembly.Location));
+ return defaultRefAssemblies.ToArray();
+ }
+
+ ///
+ /// Initialize the set of assembly names that should be ignored when they are specified in '-ReferencedAssemblies'.
+ /// - System.Private.CoreLib.ni.dll - the runtim dll that contains most core/primitive types
+ /// - System.Private.Uri.dll - the runtime dll that contains 'System.Uri' and related types
+ /// Referencing these runtime dlls may cause ambiguous type identity or other issues.
+ /// - System.Runtime.dll - the corresponding reference dll will be automatically included
+ /// - System.Runtime.InteropServices.dll - the corresponding reference dll will be automatically included
+ ///
+ private static HashSet InitRefAssemblyNamesToIgnore()
+ {
+ return new HashSet(StringComparer.OrdinalIgnoreCase) {
+ PathType.GetFileName(typeof(object).Assembly.Location),
+ PathType.GetFileName(typeof(Uri).Assembly.Location),
+ PathType.GetFileName(GetReferenceAssemblyPathBasedOnType(typeof(object))),
+ PathType.GetFileName(GetReferenceAssemblyPathBasedOnType(typeof(SecureString)))
+ };
+ }
+
+ ///
+ /// Initialize the list of reference assemblies that will be automatically added when '-ReferencedAssemblies' is specified.
+ ///
+ private static PortableExecutableReference[] InitAutoIncludedRefAssemblies()
+ {
+ return new PortableExecutableReference[] {
+ MetadataReference.CreateFromFile(GetReferenceAssemblyPathBasedOnType(typeof(object))),
+ MetadataReference.CreateFromFile(GetReferenceAssemblyPathBasedOnType(typeof(SecureString)))
+ };
+ }
+
+ ///
+ /// Get the path of reference assembly where the type is declared.
+ ///
+ private static string GetReferenceAssemblyPathBasedOnType(Type type)
+ {
+ string refAsmFileName = PathType.GetFileName(ClrFacade.GetAssemblies(type.FullName).First().Location);
+ return PathType.Combine(s_netcoreAppRefFolder, refAsmFileName);
+ }
+
+ private string ResolveAssemblyName(string assembly, bool isForReferenceAssembly)
{
// if it's a path, resolve it
- if (referencedAssembly.Contains(System.IO.Path.DirectorySeparatorChar) || referencedAssembly.Contains(System.IO.Path.AltDirectorySeparatorChar))
+ if (assembly.Contains(PathType.DirectorySeparatorChar) || assembly.Contains(PathType.AltDirectorySeparatorChar))
{
- if (System.IO.Path.IsPathRooted(referencedAssembly))
+ if (PathType.IsPathRooted(assembly))
{
- return referencedAssembly;
+ return assembly;
}
else
{
- var paths = SessionState.Path.GetResolvedPSPathFromPSPath(referencedAssembly);
+ var paths = SessionState.Path.GetResolvedPSPathFromPSPath(assembly);
return paths[0].Path;
}
}
- if (!String.Equals(System.IO.Path.GetExtension(referencedAssembly), ".dll", StringComparison.OrdinalIgnoreCase))
+ string refAssemblyDll = assembly;
+ if (!assembly.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
{
- // If we already load the assembly, we can reference it by name
- Assembly result = LoadAssemblyHelper(referencedAssembly);
- if (result != null)
+ // It could be a short assembly name or a full assembly name, but we
+ // alwasy want the short name to find the corresponding assembly file.
+ var assemblyName = new AssemblyName(assembly);
+ refAssemblyDll = assemblyName.Name + ".dll";
+ }
+
+ // We look up in reference/framework only when it's for resolving reference assemblies.
+ // In case of 'Add-Type -AssemblyName' scenario, we don't attempt to resolve against framework assemblies because
+ // 1. Explicitly loading a framework assembly usually is not necessary in PowerShell Core.
+ // 2. A user should use assembly name instead of path if they want to explicitly load a framework assembly.
+ if (isForReferenceAssembly)
+ {
+ // If it's for resolving a reference assembly, then we look in NetCoreApp ref assemblies first
+ string netcoreAppRefPath = PathType.Combine(s_netcoreAppRefFolder, refAssemblyDll);
+ if (File.Exists(netcoreAppRefPath))
{
- return result.Location;
+ return netcoreAppRefPath;
}
- else
+
+ // Look up the assembly in the framework folder. This may happen when assembly is not part of
+ // NetCoreApp, but comes from an additional package, such as 'Json.Net'.
+ string frameworkPossiblePath = PathType.Combine(s_frameworkFolder, refAssemblyDll);
+ if (File.Exists(frameworkPossiblePath))
{
- referencedAssembly += ".dll";
+ return frameworkPossiblePath;
+ }
+
+ // The assembly name may point to a third-party assembly that is already loaded at run time.
+ if (!assembly.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
+ {
+ Assembly result = LoadAssemblyHelper(assembly);
+ if (result != null)
+ {
+ return result.Location;
+ }
}
}
- // lookup in framework folders and the current folder
- string frameworkPossiblePath = System.IO.Path.Combine(s_frameworkFolder, referencedAssembly);
- if (File.Exists(frameworkPossiblePath))
- {
- return frameworkPossiblePath;
- }
-
- string currentFolderPath = SessionState.Path.GetResolvedPSPathFromPSPath(referencedAssembly)[0].Path;
+ // Look up the assembly in the current folder
+ string currentFolderPath = SessionState.Path.GetResolvedPSPathFromPSPath(refAssemblyDll)[0].Path;
if (File.Exists(currentFolderPath))
{
return currentFolderPath;
@@ -1108,10 +1151,10 @@ namespace Microsoft.PowerShell.Commands
ErrorRecord errorRecord = new ErrorRecord(
new Exception(
- String.Format(ParserStrings.ErrorLoadingAssembly, referencedAssembly)),
+ String.Format(ParserStrings.ErrorLoadingAssembly, assembly)),
"ErrorLoadingAssembly",
ErrorCategory.InvalidOperation,
- referencedAssembly);
+ assembly);
ThrowTerminatingError(errorRecord);
return null;
@@ -1195,17 +1238,29 @@ namespace Microsoft.PowerShell.Commands
}
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source, parseOptions);
- var references = s_defaultAssemblies;
- if (referencedAssembliesSpecified)
+ var references = s_defaultAssemblies.Value;
+ if (ReferencedAssemblies.Length > 0)
{
- var tempReferences = ReferencedAssemblies.Select(a => MetadataReference.CreateFromFile(ResolveReferencedAssembly(a))).ToList();
- tempReferences.AddRange(s_autoReferencedAssemblies);
+ var tempReferences = new List(s_autoReferencedAssemblies.Value);
+ foreach (string assembly in ReferencedAssemblies)
+ {
+ if (string.IsNullOrWhiteSpace(assembly)) { continue; }
+ string resolvedAssemblyPath = ResolveAssemblyName(assembly, true);
+ // Ignore some specified reference assemblies
+ string fileName = PathType.GetFileName(resolvedAssemblyPath);
+ if (s_refAssemblyNamesToIgnore.Value.Contains(fileName))
+ {
+ WriteVerbose(StringUtil.Format(AddTypeStrings.ReferenceAssemblyIgnored, resolvedAssemblyPath));
+ continue;
+ }
+ tempReferences.Add(MetadataReference.CreateFromFile(resolvedAssemblyPath));
+ }
references = tempReferences.ToArray();
}
CSharpCompilation compilation = CSharpCompilation.Create(
- System.IO.Path.GetRandomFileName(),
+ PathType.GetRandomFileName(),
syntaxTrees: new[] { syntaxTree },
references: references,
options: new CSharpCompilationOptions(OutputAssemblyTypeToOutputKind(OutputType)));
diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs
index ca9abe8339..26e7508493 100644
--- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs
+++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs
@@ -9,13 +9,6 @@ using System.IO;
using System.Management.Automation;
using System.Management.Automation.Internal;
-#if CORECLR
-// Some APIs are missing from System.Environment. We use System.Management.Automation.Environment as a proxy type:
-// - for missing APIs, System.Management.Automation.Environment has extension implementation.
-// - for existing APIs, System.Management.Automation.Environment redirect the call to System.Environment.
-using Environment = System.Management.Automation.Environment;
-#endif
-
namespace Microsoft.PowerShell.Commands
{
///
diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs
index 9bcccd5335..5cc6d26738 100644
--- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs
+++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs
@@ -13,11 +13,6 @@ using System.Management.Automation.Internal;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
-#if CORECLR
-// Use stub for ICloneable
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace Microsoft.PowerShell.Commands
{
///
diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs
index 1dcfa04285..72e1ec4e3b 100644
--- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs
+++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs
@@ -85,11 +85,7 @@ namespace Microsoft.PowerShell.Commands
}
if (_waitHandle != null)
{
-#if CORECLR //TODO:CORECLR bool WaitOne(int millisecondsTimeout,bool exitContext) is not available on CLR yet
- _waitHandle.WaitOne(new TimeSpan(0, 0, 0, 0, milliSecondsToSleep));
-#else
- _waitHandle.WaitOne(new TimeSpan(0, 0, 0, 0, milliSecondsToSleep), true);
-#endif
+ _waitHandle.WaitOne(milliSecondsToSleep, true);
}
}
diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/select-object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/select-object.cs
index 916876a290..dcc86a8e88 100644
--- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/select-object.cs
+++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/select-object.cs
@@ -10,11 +10,6 @@ using Microsoft.PowerShell.Commands.Internal.Format;
using System.Management.Automation.Internal;
using System.Diagnostics.CodeAnalysis;
-#if CORECLR
-// Use stubs for SystemException
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace Microsoft.PowerShell.Commands
{
///
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 16f2c01b6c..9ccc64b3fe 100644
--- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs
+++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs
@@ -4,15 +4,10 @@ Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Text;
+using System.Security.Permissions;
using System.Management.Automation;
using System.Management.Automation.Internal.Host;
-#if CORECLR
-using Microsoft.PowerShell.CoreClr.Stubs;
-#else
-using System.Security.Permissions;
-#endif
-
namespace Microsoft.PowerShell.Commands
{
///
diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/write.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/write.cs
index 79aa29e5ef..99d4c8b240 100644
--- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/write.cs
+++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/write.cs
@@ -8,12 +8,6 @@ using System.Management.Automation.Internal;
using System.Runtime.Serialization;
using System.Diagnostics.CodeAnalysis;
-#if CORECLR
-// Use stub for SystemException, SerializationInfo, SerializableAttribute and Serializable
-// It is needed for WriteErrorException which ONLY used in Write-Error cmdlet.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace Microsoft.PowerShell.Commands
{
#region WriteDebugCommand
diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/AddTypeStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/AddTypeStrings.resx
index b9a7b7f9dd..498d049f4a 100644
--- a/src/Microsoft.PowerShell.Commands.Utility/resources/AddTypeStrings.resx
+++ b/src/Microsoft.PowerShell.Commands.Utility/resources/AddTypeStrings.resx
@@ -171,4 +171,7 @@
Cannot add type. Definition of new types is not supported in this language mode.
+
+ The specified reference assembly '{0}' is unnecessary and ignored.
+
\ No newline at end of file
diff --git a/src/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj b/src/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj
index dc6ae33299..9e0922018e 100644
--- a/src/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj
+++ b/src/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj
@@ -3,7 +3,7 @@
PowerShell Host
6.0.0
- netstandard1.6
+ netcoreapp2.0
$(NoWarn);CS1570
true
true
@@ -27,11 +27,11 @@
-
+
$(DefineConstants);CORECLR
-
+
@@ -51,9 +51,4 @@
full
-
-
-
-
-
diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs
index b26dfae3ba..85702a4057 100644
--- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs
+++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs
@@ -23,13 +23,6 @@ using System.Management.Automation.Security;
using System.Threading;
using System.Runtime.InteropServices;
using System.Management.Automation.Language;
-#if CORECLR
-using Microsoft.PowerShell.CoreClr.Stubs;
-// Some APIs are missing from System.Environment. We use System.Management.Automation.Environment as a proxy type:
-// - for missing APIs, System.Management.Automation.Environment has extension implementation.
-// - for existing APIs, System.Management.Automation.Environment redirect the call to System.Environment.
-using Environment = System.Management.Automation.Environment;
-#endif
using Dbg = System.Management.Automation.Diagnostics;
using ConsoleHandle = Microsoft.Win32.SafeHandles.SafeFileHandle;
diff --git a/src/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext.csproj b/src/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext.csproj
index b2b1ab816c..2233ec757f 100644
--- a/src/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext.csproj
+++ b/src/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext.csproj
@@ -2,19 +2,18 @@
6.0.0
- netstandard1.6
+ netcoreapp2.0
true
true
true
Microsoft.PowerShell.CoreCLR.AssemblyLoadContext
../signing/visualstudiopublic.snk
true
- 1.6.1
false
false
-
+
$(DefineConstants);CORECLR
@@ -30,11 +29,4 @@
full
-
-
-
-
-
-
-
diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj b/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj
index 414d20f5b9..a5968b902a 100644
--- a/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj
+++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj
@@ -2,7 +2,7 @@
6.0.0
- netstandard1.6
+ netcoreapp2.0
$(NoWarn);CS1591
true
true
@@ -11,12 +11,11 @@
Microsoft.PowerShell.CoreCLR.Eventing
../signing/visualstudiopublic.snk
true
- 1.6.1
false
false
-
+
$(DefineConstants);CORECLR
@@ -32,11 +31,8 @@
full
-
-
-
-
-
+
+
diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Exceptions.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Exceptions.cs
index 7893dd603c..a9f7193efe 100644
--- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Exceptions.cs
+++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Exceptions.cs
@@ -4,10 +4,6 @@ using System.Management.Automation.SecurityAccountsManager;
using System.Runtime.Serialization;
using Microsoft.PowerShell.LocalAccounts;
-#if CORECLR
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace Microsoft.PowerShell.Commands
{
///
@@ -80,22 +76,12 @@ namespace Microsoft.PowerShell.Commands
///
public LocalAccountsException(String message, Exception ex) : base(message, ex) { }
-#if CORECLR
- ///
- /// Compliance Constructor
- ///
- ///
- ///
- // This is not supported for CoreCLR
- protected LocalAccountsException(SerializationInfo info, StreamingContext ctx) : base() { }
-#else
///
/// Compliance Constructor
///
///
///
protected LocalAccountsException(SerializationInfo info, StreamingContext ctx) : base(info, ctx) { }
-#endif
}
///
diff --git a/src/Microsoft.PowerShell.LocalAccounts/Microsoft.PowerShell.LocalAccounts.csproj b/src/Microsoft.PowerShell.LocalAccounts/Microsoft.PowerShell.LocalAccounts.csproj
index c33e201651..ad95daa318 100644
--- a/src/Microsoft.PowerShell.LocalAccounts/Microsoft.PowerShell.LocalAccounts.csproj
+++ b/src/Microsoft.PowerShell.LocalAccounts/Microsoft.PowerShell.LocalAccounts.csproj
@@ -2,7 +2,7 @@
6.0.0
- netstandard1.6
+ netcoreapp2.0
true
true
true
@@ -20,7 +20,7 @@
-
+
$(DefineConstants);CORECLR
@@ -36,8 +36,4 @@
full
-
-
-
-
diff --git a/src/Microsoft.PowerShell.PSReadLine/ConsoleLib.cs b/src/Microsoft.PowerShell.PSReadLine/ConsoleLib.cs
index bf09b48bac..01090bae33 100644
--- a/src/Microsoft.PowerShell.PSReadLine/ConsoleLib.cs
+++ b/src/Microsoft.PowerShell.PSReadLine/ConsoleLib.cs
@@ -1094,12 +1094,5 @@ namespace Microsoft.PowerShell.Internal
}
#endif
-#if CORECLR // TODO: remove if CORECLR adds this attribute back
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event)]
- sealed class ExcludeFromCodeCoverageAttribute : Attribute
- {
- }
-#endif
-
#pragma warning restore 1591
}
diff --git a/src/Microsoft.PowerShell.PSReadLine/Microsoft.PowerShell.PSReadLine.csproj b/src/Microsoft.PowerShell.PSReadLine/Microsoft.PowerShell.PSReadLine.csproj
index 2846e764ee..9b7ee605cf 100644
--- a/src/Microsoft.PowerShell.PSReadLine/Microsoft.PowerShell.PSReadLine.csproj
+++ b/src/Microsoft.PowerShell.PSReadLine/Microsoft.PowerShell.PSReadLine.csproj
@@ -2,7 +2,7 @@
6.0.0
- netstandard1.6
+ netcoreapp2.0
true
true
true
@@ -23,7 +23,7 @@
-
+
$(DefineConstants);CORECLR
diff --git a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj
index 2f93bb761e..680ef13b1d 100644
--- a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj
+++ b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj
@@ -4,9 +4,8 @@
false
PowerShell SDK metapackage
6.0.0
- netstandard1.6
+ netcoreapp2.0
Microsoft.PowerShell.SDK
- 1.6.1
@@ -17,87 +16,18 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Microsoft.PowerShell.SDK/README.md b/src/Microsoft.PowerShell.SDK/README.md
index f89c3bc35b..95846dfa60 100644
--- a/src/Microsoft.PowerShell.SDK/README.md
+++ b/src/Microsoft.PowerShell.SDK/README.md
@@ -1,25 +1,8 @@
Microsoft PowerShell SDK
========================
-This project is a metapackage referencing the PowerShell projects and .NET Core packages that PowerShell ships.
+This is a meta-project that serves two purposes:
-The package dependencies consist of two parts:
+1. Group PowerShell sub projects to avoid unnecessary duplication of reference declarations.
+2. Group extra .NET Core packages that PowerShell doesn't depend on directly but must provide for our users at runtime.
-1. PowerShell projects: local source code with own sets of dependencies
-2. .NET Core packages: the framework libraries that we ensure are present for PowerShell developers at runtime
-
-This second set includes packages that we do not necessarily require at compile-time, but must provide for our users at runtime.
-For example, we include the library `System.Runtime.Serialization.Json.dll` so that users of PowerShell can utilize its types and methods,
-even though PowerShell does not directly depend on the library.
-
-There are intentionally duplicated dependencies.
-Instead of relying on dependency transitivity where A -> B, B -> C, so A -> C,
-we explicitly include A -> C if A requires C despite the removal of B.
-Additionally, we want to easily identify our complete dependency set without generating a lockfile
-(an artifact of `dotnet restore` after it resolves the dependency graph).
-For example, `System.Management.Automation` depends on `System.Diagnostics.TraceSource`,
-but `Microsoft.PowerShell.SDK` depends on both `System.Diagnostics.TraceSource` and `System.Management.Automation`.
-
-Transitive dependencies not listed in [project.json][] are **not a part of public contract**.
-
-[project.json]: project.json
diff --git a/src/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.csproj b/src/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.csproj
index cb1e09d35c..9c6eed2a6c 100644
--- a/src/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.csproj
+++ b/src/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.csproj
@@ -2,7 +2,7 @@
6.0.0
- netstandard1.6
+ netcoreapp2.0
$(NoWarn);CS1570
true
true
@@ -20,11 +20,11 @@
-
+
$(DefineConstants);CORECLR
-
+
diff --git a/src/Microsoft.PowerShell.Security/security/AclCommands.cs b/src/Microsoft.PowerShell.Security/security/AclCommands.cs
index 8aa20b44b8..876c5ed89c 100644
--- a/src/Microsoft.PowerShell.Security/security/AclCommands.cs
+++ b/src/Microsoft.PowerShell.Security/security/AclCommands.cs
@@ -19,12 +19,7 @@ using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Globalization;
using System.ComponentModel;
-
-#if CORECLR
-// Use stub for SystemException
-using Microsoft.PowerShell.CoreClr.Stubs;
using System.Reflection;
-#endif
namespace Microsoft.PowerShell.Commands
{
diff --git a/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs b/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs
index 11c5c0ee88..bc75354826 100644
--- a/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs
+++ b/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs
@@ -218,14 +218,7 @@ namespace Microsoft.PowerShell.Commands
private static X509Certificate2 GetCertFromPfxFile(string path, SecureString password)
{
- //
- // NTRAID#DevDiv Bugs-33007-2004/7/08-kumarp
- // the following will not be required once X509Certificate2.Import()
- // accepts a SecureString
- //
- string clearTextPassword = Utils.GetStringFromSecureString(password);
-
- var cert = new X509Certificate2(path, clearTextPassword, X509KeyStorageFlags.DefaultKeySet);
+ var cert = new X509Certificate2(path, password, X509KeyStorageFlags.DefaultKeySet);
return cert;
}
}
diff --git a/src/Microsoft.PowerShell.Security/security/certificateproviderexceptions.cs b/src/Microsoft.PowerShell.Security/security/certificateproviderexceptions.cs
index 9c6d87203e..ba21f0c351 100644
--- a/src/Microsoft.PowerShell.Security/security/certificateproviderexceptions.cs
+++ b/src/Microsoft.PowerShell.Security/security/certificateproviderexceptions.cs
@@ -6,11 +6,6 @@ Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Runtime.Serialization;
-#if CORECLR
-// Use stub for SerializableAttribute, SystemException, ThreadAbortException and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace Microsoft.PowerShell.Commands
{
///
diff --git a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj
index 56fc40d7fb..0f9f93aca3 100644
--- a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj
+++ b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj
@@ -2,7 +2,7 @@
6.0.0
- netstandard1.6
+ netcoreapp2.0
true
true
Microsoft.WSMan.Management
@@ -17,11 +17,11 @@
-
+
$(DefineConstants);CORECLR
-
+
diff --git a/src/Microsoft.WSMan.Runtime/Microsoft.WSMan.Runtime.csproj b/src/Microsoft.WSMan.Runtime/Microsoft.WSMan.Runtime.csproj
index 4777ac739a..7e9cc3ea3a 100644
--- a/src/Microsoft.WSMan.Runtime/Microsoft.WSMan.Runtime.csproj
+++ b/src/Microsoft.WSMan.Runtime/Microsoft.WSMan.Runtime.csproj
@@ -2,18 +2,17 @@
6.0.0
- netstandard1.6
+ netcoreapp2.0
true
true
Microsoft.WSMan.Runtime
../signing/visualstudiopublic.snk
true
- 1.6.1
false
false
-
+
$(DefineConstants);CORECLR
diff --git a/src/ResGen/ResGen.csproj b/src/ResGen/ResGen.csproj
index bff4017bf8..3f1fd8ba92 100644
--- a/src/ResGen/ResGen.csproj
+++ b/src/ResGen/ResGen.csproj
@@ -2,15 +2,10 @@
Generates C# typed bindings for .resx files
- netcoreapp1.1
+ netcoreapp2.0
resgen
Exe
ubuntu.16.10-x64;ubuntu.16.04-x64;ubuntu.14.04-x64;debian.8-x64;centos.7-x64;fedora.24-x64;win7-x86;win7-x64;win81-x64;win10-x64;osx.10.11-x64;osx.10.12-x64;opensuse.13.2-x64;opensuse.42.1-x64
- 1.1.1
-
-
-
-
diff --git a/src/System.Management.Automation/CoreCLR/CorePsExtensions.cs b/src/System.Management.Automation/CoreCLR/CorePsExtensions.cs
index d4e1ba033e..7434907a2a 100644
--- a/src/System.Management.Automation/CoreCLR/CorePsExtensions.cs
+++ b/src/System.Management.Automation/CoreCLR/CorePsExtensions.cs
@@ -3,1619 +3,10 @@
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.ComponentModel;
-using System.Text;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-using Microsoft.Win32;
-
-namespace System.Management.Automation
-{
- #region Reflection and Type related extensions
-
- #region Enums
-
- [Flags]
- internal enum MemberTypes
- {
- Constructor = 0x01,
- Event = 0x02,
- Field = 0x04,
- Method = 0x08,
- Property = 0x10,
- All = 0xbf,
- }
-
- #endregion Enums
-
- ///
- /// The type extension methods within this partial class are only used for CoreCLR powershell.
- ///
- /// * If you want to add an extension method that will be used by both FullCLR and CoreCLR powershell, please
- /// add it to the 'PSTypeExtensions' partial class in 'ExtensionMethods.cs'.
- /// * If you want to add an extension method that will be used only by CoreCLR powershell, please add it here.
- ///
- internal static partial class PSTypeExtensions
- {
- #region Miscs
-
- internal static bool IsSubclassOf(this Type targetType, Type type)
- {
- return targetType.GetTypeInfo().IsSubclassOf(type);
- }
-
- #endregion Miscs
-
- #region Interface
-
- internal static Type GetInterface(this Type type, string name)
- {
- // The search is case-sensitive, as it's in the full CLR version
- return GetInterface(type, name, false);
- }
-
- internal static Type GetInterface(this Type type, string name, bool ignoreCase)
- {
- var stringComparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
- return type.GetTypeInfo().ImplementedInterfaces.FirstOrDefault(
- implementedInterface => String.Equals(name, implementedInterface.Name, stringComparison));
- }
-
- #endregion Interface
-
- #region Member
-
- internal static MemberInfo[] GetMember(this Type type, string name, MemberTypes memberType, BindingFlags bindingAttr)
- {
- if (bindingAttr == 0)
- {
- return new MemberInfo[0];
- }
-
- var members = new List();
- if ((memberType & MemberTypes.Field) != 0)
- {
- var fields = type.GetFields(name, bindingAttr);
- if (fields != null)
- {
- for (int i = 0; i < fields.Length; i++)
- {
- members.Add(fields[i]);
- }
- }
- }
-
- if ((memberType & MemberTypes.Property) != 0)
- {
- var properties = type.GetProperties(name, bindingAttr);
- if (properties != null)
- {
- for (int i = 0; i < properties.Length; i++)
- {
- members.Add(properties[i]);
- }
- }
- }
-
- return members.ToArray();
- }
-
- #endregion Member
-
- #region Field
-
- internal static FieldInfo[] GetFields(this Type type, string name, BindingFlags bindingFlags)
- {
- return GetFields(type, name, bindingFlags, false);
- }
-
- ///
- /// GetFields
- ///
- internal static FieldInfo[] GetFields(this Type type, string name, BindingFlags bindingFlags, bool isNameNull)
- {
- if (!isNameNull && (name == null || (name = name.Trim()) == ""))
- {
- throw new PSArgumentNullException("name");
- }
-
- if (bindingFlags == 0)
- {
- return null;
- }
-
- Type currentType = type;
- StringComparison strCompare = (bindingFlags & BindingFlags.IgnoreCase) != 0
- ? StringComparison.OrdinalIgnoreCase
- : StringComparison.Ordinal;
- var fields = new List();
- bool isInHierarchy = false;
-
- do
- {
- TypeInfo currentTypeInfo = currentType.GetTypeInfo();
-
- foreach (FieldInfo field in currentTypeInfo.DeclaredFields)
- {
- if (!isNameNull && !String.Equals(name, field.Name, strCompare))
- {
- continue;
- }
-
- if (((bindingFlags & BindingFlags.Instance) != 0 && !field.IsStatic) ||
- ((bindingFlags & BindingFlags.Static) != 0 && field.IsStatic))
- {
- if (isInHierarchy)
- {
- // Specify BindingFlags.FlattenHierarchy to include public and protected static members up the hierarchy;
- // private static members in inherited classes are not included
- if (!field.IsPublic && !(field.IsFamily && field.IsStatic))
- {
- continue;
- }
- }
-
- if ((bindingFlags & BindingFlags.Public) != 0 && field.IsPublic)
- {
- fields.Add(field);
- continue;
- }
-
- if ((bindingFlags & BindingFlags.NonPublic) != 0 && !field.IsPublic)
- {
- fields.Add(field);
- }
- }
- }
-
- if ((bindingFlags & BindingFlags.FlattenHierarchy) != 0 && (bindingFlags & BindingFlags.DeclaredOnly) == 0)
- {
- isInHierarchy = true;
- currentType = currentTypeInfo.BaseType;
- }
- else
- {
- currentType = null;
- }
-
- } while (currentType != null);
-
- return fields.ToArray();
- }
-
- #endregion Field
-
- #region Property
-
- internal static PropertyInfo[] GetProperties(this Type type, string name, BindingFlags bindingFlags)
- {
- return GetProperties(type, name, bindingFlags, false);
- }
-
- ///
- /// GetProperty
- ///
- internal static PropertyInfo[] GetProperties(this Type type, string name, BindingFlags bindingFlags, bool isNameNull)
- {
- if (!isNameNull && (name == null || (name = name.Trim()) == ""))
- {
- throw new PSArgumentNullException("name");
- }
-
- if (bindingFlags == 0)
- {
- return null;
- }
-
- Type currentType = type;
- StringComparison strCompare = (bindingFlags & BindingFlags.IgnoreCase) != 0
- ? StringComparison.OrdinalIgnoreCase
- : StringComparison.Ordinal;
- var properties = new List();
- bool isInHierarchy = false;
-
- do
- {
- TypeInfo currentTypeInfo = currentType.GetTypeInfo();
-
- foreach (PropertyInfo property in currentTypeInfo.DeclaredProperties)
- {
- if (!isNameNull && !String.Equals(name, property.Name, strCompare))
- {
- continue;
- }
-
- if (((bindingFlags & BindingFlags.Instance) != 0 && IsInstanceProperty(property)) ||
- ((bindingFlags & BindingFlags.Static) != 0 && IsStaticProperty(property)))
- {
- if (isInHierarchy)
- {
- // Specify BindingFlags.FlattenHierarchy to include public and protected static members up the hierarchy;
- // private static members in inherited classes are not included
- if (!IsPublicProperty(property) && !(IsProtectedProperty(property) && IsStaticProperty(property)))
- {
- continue;
- }
- }
-
- if ((bindingFlags & BindingFlags.Public) != 0 && IsPublicProperty(property))
- {
- properties.Add(property);
- continue;
- }
-
- if ((bindingFlags & BindingFlags.NonPublic) != 0 && IsNonPublicProperty(property))
- {
- properties.Add(property);
- continue;
- }
- }
- }
-
- if ((bindingFlags & BindingFlags.FlattenHierarchy) != 0 && (bindingFlags & BindingFlags.DeclaredOnly) == 0)
- {
- isInHierarchy = true;
- currentType = currentTypeInfo.BaseType;
- }
- else
- {
- currentType = null;
- }
-
- } while (currentType != null);
-
- return properties.ToArray();
- }
-
- #region Property Helper Methods
-
- private static bool IsInstanceProperty(PropertyInfo property)
- {
- if (property.GetMethod != null && property.GetMethod.IsStatic)
- {
- return false;
- }
-
- if (property.SetMethod != null && property.SetMethod.IsStatic)
- {
- return false;
- }
-
- if (property.GetMethod == null && property.SetMethod == null)
- {
- return false;
- }
-
- return true;
- }
-
- private static bool IsStaticProperty(PropertyInfo property)
- {
- if (property.GetMethod != null && !property.GetMethod.IsStatic)
- {
- return false;
- }
-
- if (property.SetMethod != null && !property.SetMethod.IsStatic)
- {
- return false;
- }
-
- if (property.GetMethod == null && property.SetMethod == null)
- {
- return false;
- }
-
- return true;
- }
-
- private static bool IsPublicProperty(PropertyInfo property)
- {
- if ((property.GetMethod != null && property.GetMethod.IsPublic) || (property.SetMethod != null && property.SetMethod.IsPublic))
- {
- return true;
- }
-
- return false;
- }
-
- private static bool IsNonPublicProperty(PropertyInfo property)
- {
- if (property.GetMethod == null && property.SetMethod == null)
- {
- return false;
- }
-
- if (property.GetMethod != null && property.GetMethod.IsPublic)
- {
- return false;
- }
-
- if (property.SetMethod != null && property.SetMethod.IsPublic)
- {
- return false;
- }
-
- return true;
- }
-
- private static bool IsProtectedProperty(PropertyInfo property)
- {
- if (property.GetMethod == null && property.SetMethod == null)
- {
- return false;
- }
-
- if (property.GetMethod != null && !property.GetMethod.IsFamily)
- {
- return false;
- }
-
- if (property.SetMethod != null && !property.SetMethod.IsFamily)
- {
- return false;
- }
-
- return true;
- }
-
- #endregion Property Helper Methods
-
- #endregion Property
-
- #region Constructor
-
- ///
- /// Search for a constructor that matches the specified bindingFlags and parameter types
- ///
- internal static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, string binderNotUsed, Type[] types, string modifiersNotUsed)
- {
- if (binderNotUsed != null || modifiersNotUsed != null)
- {
- throw new ArgumentException("Parameters 'binder' and 'modifier' should not be used");
- }
-
- if (types == null || types.Any(element => element == null))
- {
- throw new ArgumentNullException("types");
- }
-
- ConstructorInfo[] results = GetConstructors(type, bindingFlags, null);
- return results != null ? GetMatchingConstructor(results, types) : null;
- }
-
- internal static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, string binderNotUsed,
- CallingConventions callConvention, Type[] types, string modifiersNotUsed)
- {
- if (binderNotUsed != null || modifiersNotUsed != null)
- {
- throw new ArgumentException("Parameters 'binder' and 'modifier' should not be used");
- }
-
- if (types == null || types.Any(element => element == null))
- {
- throw new ArgumentNullException("types");
- }
-
- ConstructorInfo[] results = GetConstructors(type, bindingFlags, callConvention);
- return results != null ? GetMatchingConstructor(results, types) : null;
- }
-
- ///
- /// Helper method - Get the matching constructor based on the parameter types
- ///
- private static ConstructorInfo GetMatchingConstructor(ConstructorInfo[] constructors, Type[] types)
- {
- // Compare the parameter types in two passes.
- // The first pass is to check if the parameter types are exactly the same,
- // The second pass is to check if the parameter types is assignable from the given argument types.
- var matchConstructors = new List();
- bool inSecondPass = false;
-
- do
- {
- // Use 'for' loop to avoid construct new ArrayEnumerator object
- for (int constructorIndex = 0; constructorIndex < constructors.Length; constructorIndex++)
- {
- var constructor = constructors[constructorIndex];
- ParameterInfo[] parameters = constructor.GetParameters();
- if (types.Length == parameters.Length)
- {
- bool success = true;
- for (int typeIndex = 0; typeIndex < types.Length; typeIndex++)
- {
- if (!IsParameterTypeMatching(parameters[typeIndex].ParameterType, types[typeIndex], inSecondPass))
- {
- success = false;
- break;
- }
- }
-
- if (success)
- {
- matchConstructors.Add(constructor);
- }
- }
- }
-
- // Flip the 'inSecondPass' flag, so that we run another pass only if we're about
- // to start the second pass and we didn't find anything from the first pass.
- inSecondPass = !inSecondPass;
-
- } while (matchConstructors.Count == 0 && inSecondPass);
-
- if (matchConstructors.Count > 1)
- {
- throw new AmbiguousMatchException();
- }
-
- return matchConstructors.Count == 1 ? matchConstructors[0] : null;
- }
-
- ///
- /// Constructors defined in the current type
- ///
- internal static ConstructorInfo[] GetConstructors(this Type type, BindingFlags bindingFlags, CallingConventions? callConvention)
- {
- if ((bindingFlags & BindingFlags.FlattenHierarchy) != 0)
- {
- throw new PSArgumentException("Invalid binding flags");
- }
-
- if (((bindingFlags & BindingFlags.Instance) != 0 && (bindingFlags & BindingFlags.Static) != 0) ||
- ((bindingFlags & BindingFlags.Instance) == 0 && (bindingFlags & BindingFlags.Static) == 0))
- {
- throw new PSArgumentException("Invalid binding flags");
- }
-
- // If bindingFlags is zero, return null.
- if (bindingFlags == 0)
- {
- return null;
- }
-
- // If type is a generic parameter, return empty array
- if (type.IsGenericParameter)
- {
- return new ConstructorInfo[0];
- }
-
- var ctors = new List();
-
- foreach (ConstructorInfo ctor in type.GetTypeInfo().DeclaredConstructors)
- {
- /* CallingConventions is different on CoreCLR ...
- * TODO -- find out how different and what problem it causes.
- if (callConvention.HasValue && ctor.CallingConvention != callConvention.Value)
- {
- continue;
- }
- */
-
- if ((bindingFlags & BindingFlags.Instance) != 0 && ctor.IsStatic)
- {
- continue;
- }
-
- if ((bindingFlags & BindingFlags.Static) != 0 && !ctor.IsStatic)
- {
- continue;
- }
-
- if ((bindingFlags & BindingFlags.Public) != 0 && ctor.IsPublic)
- {
- ctors.Add(ctor);
- continue;
- }
-
- if ((bindingFlags & BindingFlags.NonPublic) != 0 && !ctor.IsPublic)
- {
- ctors.Add(ctor);
- continue;
- }
- }
-
- return ctors.ToArray();
- }
-
- #endregion Constructor
-
- #region Method
-
- internal static MethodInfo GetMethod(this Type targetType, string name, BindingFlags bindingFlags, string binderNotUsed, Type[] types, string modifierNotUsed)
- {
- if (binderNotUsed != null || modifierNotUsed != null)
- {
- throw new ArgumentException("Parameters 'binderNotUsed' and 'modifier_NotUsed' should not be used.");
- }
-
- if (types == null || types.Any(element => element == null))
- {
- throw new ArgumentNullException("types");
- }
-
- MethodInfo[] methods = GetMethods(targetType, name, bindingFlags);
- return methods != null ? GetMatchingMethod(methods, types) : null;
- }
-
- internal static MethodInfo GetMethod(this Type targetType, string name, BindingFlags bindingFlags, string binderNotUsed, CallingConventions callConvention, Type[] types, string modifierNotUsed)
- {
- if (binderNotUsed != null || modifierNotUsed != null)
- {
- throw new ArgumentException("Parameters 'binderNotUsed' and 'modifier_NotUsed' should not be used.");
- }
-
- if (types == null || types.Any(element => element == null))
- {
- throw new ArgumentNullException("types");
- }
-
- MethodInfo[] methods = GetMethods(targetType, name, bindingFlags, false, callConvention);
- return methods != null ? GetMatchingMethod(methods, types) : null;
- }
-
- // Helper method
- private static MethodInfo GetMatchingMethod(MethodInfo[] methods, Type[] types)
- {
- // Compare the parameter types in two passes.
- // The first pass is to check if the parameter types are exactly the same,
- // The second pass is to check if the parameter types is assignable from the given argument types.
- var matchMethods = new List();
- bool inSecondPass = false;
-
- do
- {
- // Use for loop to avoid construct new ArrayEnumerator object
- for (int methodIndex = 0; methodIndex < methods.Length; methodIndex++)
- {
- var method = methods[methodIndex];
- ParameterInfo[] parameters = method.GetParameters();
- if (parameters.Length == types.Length)
- {
- bool success = true;
- for (int typeIndex = 0; typeIndex < types.Length; typeIndex++)
- {
- if (!IsParameterTypeMatching(parameters[typeIndex].ParameterType, types[typeIndex], inSecondPass))
- {
- success = false;
- break;
- }
- }
-
- if (success)
- {
- matchMethods.Add(method);
- }
- }
- }
-
- // Flip the 'inSecondPass' flag, so that we run another pass only if we're about
- // to start the second pass and we didn't find anything from the first pass.
- inSecondPass = !inSecondPass;
-
- } while (matchMethods.Count == 0 && inSecondPass);
-
- if (matchMethods.Count > 1)
- {
- throw new AmbiguousMatchException();
- }
-
- return matchMethods.Count == 1 ? matchMethods[0] : null;
- }
-
- private static bool IsParameterTypeMatching(Type paramType, Type argType, bool inSecondPass)
- {
- return inSecondPass
- ? paramType.IsAssignableFrom(argType)
- : paramType == argType;
- }
-
- internal static MethodInfo[] GetMethods(this Type type, string name, BindingFlags bindingFlags)
- {
- return GetMethods(type, name, bindingFlags, false, null);
- }
-
- internal static MethodInfo[] GetMethods(this Type type, string name, BindingFlags bindingFlags, bool isNameNull, CallingConventions? callConvention)
- {
- if (!isNameNull && (name == null || (name = name.Trim()) == ""))
- {
- throw new ArgumentNullException("name");
- }
-
- if (bindingFlags == 0)
- {
- return null;
- }
-
- Type currentType = type;
- StringComparison strCompare = (bindingFlags & BindingFlags.IgnoreCase) != 0
- ? StringComparison.OrdinalIgnoreCase
- : StringComparison.Ordinal;
- var methods = new List();
- bool isInHierarchy = false;
-
- do
- {
- TypeInfo currentTypeInfo = currentType.GetTypeInfo();
-
- foreach (MethodInfo method in currentTypeInfo.DeclaredMethods)
- {
- if (!isNameNull && !String.Equals(name, method.Name, strCompare))
- {
- continue;
- }
-
- if (callConvention.HasValue && method.CallingConvention != callConvention.Value)
- {
- continue;
- }
-
- if (((bindingFlags & BindingFlags.Instance) != 0 && !method.IsStatic) ||
- ((bindingFlags & BindingFlags.Static) != 0 && method.IsStatic))
- {
- if (isInHierarchy)
- {
- // Specify BindingFlags.FlattenHierarchy to include public and protected static members up the hierarchy;
- // private static members in inherited classes are not included
- if (!method.IsPublic && !(method.IsFamily && method.IsStatic))
- {
- continue;
- }
- }
-
- if ((bindingFlags & BindingFlags.Public) != 0 && method.IsPublic)
- {
- methods.Add(method);
- continue;
- }
-
- if ((bindingFlags & BindingFlags.NonPublic) != 0 && !method.IsPublic)
- {
- methods.Add(method);
- }
- }
- }
-
- if ((bindingFlags & BindingFlags.FlattenHierarchy) != 0 && (bindingFlags & BindingFlags.DeclaredOnly) == 0)
- {
- isInHierarchy = true;
- currentType = currentTypeInfo.BaseType;
- }
- else
- {
- currentType = null;
- }
-
- } while (currentType != null);
-
- return methods.ToArray();
- }
-
- #endregion Method
-
- #region TypeCode
-
- private static readonly Dictionary s_typeCodeMap =
- new Dictionary()
- {
- // 'DBNull = 2' is removed from 'System.TypeCode' in CoreCLR. We return
- // '(TypeCode)2' for 'System.DBNull' to avoid any breaking changes.
- {typeof(DBNull), (TypeCode)2},
- {typeof(Boolean),TypeCode.Boolean},
- {typeof(Char),TypeCode.Char},
- {typeof(sbyte),TypeCode.SByte},
- {typeof(byte), TypeCode.Byte},
- {typeof(Int16),TypeCode.Int16},
- {typeof(UInt16),TypeCode.UInt16},
- {typeof(Int32),TypeCode.Int32},
- {typeof(UInt32),TypeCode.UInt32},
- {typeof(Int64),TypeCode.Int64},
- {typeof(UInt64),TypeCode.UInt64},
- {typeof(Single),TypeCode.Single},
- {typeof(Double),TypeCode.Double},
- {typeof(string),TypeCode.String},
- {typeof(Decimal),TypeCode.Decimal},
- {typeof(DateTime),TypeCode.DateTime},
- };
-
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal static TypeCode GetTypeCodeInCoreClr(Type type)
- {
- if (type == null)
- return TypeCode.Empty;
- if (s_typeCodeMap.ContainsKey(type))
- return s_typeCodeMap[type];
- if (type.GetTypeInfo().IsEnum)
- return GetTypeCode(Enum.GetUnderlyingType(type));
- return TypeCode.Object;
- }
-
- #endregion TypeCode
- }
-
- #endregion Reflection and Type related extensions
-
- #region Environment Extensions
-
- // TODO:CORECLR - Environment Extensions need serious work to refine.
- internal enum EnvironmentVariableTarget
- {
- Process,
- User,
- Machine
- }
-
- internal static partial class Environment
- {
- #region Forward_To_System.Environment
-
- #region Properties
-
- public static int CurrentManagedThreadId
- {
- get
- {
- return System.Environment.CurrentManagedThreadId;
- }
- }
-
- public static bool HasShutdownStarted
- {
- get
- {
- return System.Environment.HasShutdownStarted;
- }
- }
-
- public static string NewLine
- {
- get
- {
- return System.Environment.NewLine;
- }
- }
-
- public static int ProcessorCount
- {
- get
- {
- return System.Environment.ProcessorCount;
- }
- }
-
- public static string StackTrace
- {
- get
- {
- return System.Environment.StackTrace;
- }
- }
-
- public static int TickCount
- {
- get
- {
- return System.Environment.TickCount;
- }
- }
-
- #endregion Properties
-
- #region Methods
-
- public static string ExpandEnvironmentVariables(string name)
- {
- return System.Environment.ExpandEnvironmentVariables(name);
- }
-
- public static void FailFast(string message)
- {
- System.Environment.FailFast(message);
- }
-
- public static void FailFast(string message, Exception exception)
- {
- System.Environment.FailFast(message, exception);
- }
-
- public static string GetEnvironmentVariable(string variable)
- {
- return System.Environment.GetEnvironmentVariable(variable);
- }
-
- public static IDictionary GetEnvironmentVariables()
- {
- return System.Environment.GetEnvironmentVariables();
- }
-
- public static void SetEnvironmentVariable(string variable, string value)
- {
- System.Environment.SetEnvironmentVariable(variable, value);
- }
-
- #endregion Methods
-
- #endregion Forward_To_System.Environment
-
- private const int MaxMachineNameLength = 256;
- private static string[] s_commandLineArgs = new string[0];
-
- public static string[] GetCommandLineArgs()
- {
- return s_commandLineArgs;
- }
-
- #region EnvironmentVariable_Extensions
-
- ///
- /// The code is mostly copied from the .NET implementation.
- /// The only difference is how resource string is retrieved.
- /// We use the same resource string as in .NET implementation.
- ///
- public static IDictionary GetEnvironmentVariables(EnvironmentVariableTarget target)
- {
- if (target == EnvironmentVariableTarget.Process)
- {
- return GetEnvironmentVariables();
- }
-
-#if UNIX
- return null;
-#else
- if( target == EnvironmentVariableTarget.Machine)
- {
- using (RegistryKey environmentKey =
- Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Session Manager\Environment", false))
- {
- return GetRegistryKeyNameValuePairs(environmentKey);
- }
- }
- else // target == EnvironmentVariableTarget.User
- {
- using (RegistryKey environmentKey =
- Registry.CurrentUser.OpenSubKey("Environment", false))
- {
- return GetRegistryKeyNameValuePairs(environmentKey);
- }
- }
-#endif
- }
-
- ///
- /// The code is mostly copied from the .NET implementation.
- /// The only difference is how resource string is retrieved.
- /// We use the same resource string as in .NET implementation.
- ///
- internal static IDictionary GetRegistryKeyNameValuePairs(RegistryKey registryKey)
- {
- Hashtable table = new Hashtable(20);
-
- if (registryKey != null)
- {
- string[] names = registryKey.GetValueNames();
- foreach (string name in names)
- {
- string value = registryKey.GetValue(name, "").ToString();
- table.Add(name, value);
- }
- }
- return table;
- }
-
- ///
- /// The code is mostly copied from the .NET implementation.
- /// The only difference is how resource string is retrieved.
- /// We use the same resource string as in .NET implementation.
- ///
- public static string GetEnvironmentVariable(string variable, EnvironmentVariableTarget target)
- {
- if (variable == null)
- {
- throw new ArgumentNullException("variable");
- }
-
- if (target == EnvironmentVariableTarget.Process)
- {
- return System.Environment.GetEnvironmentVariable(variable);
- }
-
-#if UNIX
- return null;
-#else
- if (target == EnvironmentVariableTarget.Machine)
- {
- using (RegistryKey environmentKey =
- Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Session Manager\Environment", false))
- {
- if (environmentKey == null) { return null; }
-
- string value = environmentKey.GetValue(variable) as string;
- return value;
- }
- }
- else // target == EnvironmentVariableTarget.User
- {
- using (RegistryKey environmentKey = Registry.CurrentUser.OpenSubKey("Environment", false))
- {
- if (environmentKey == null) { return null; }
-
- string value = environmentKey.GetValue(variable) as string;
- return value;
- }
- }
-#endif
- }
-
- #endregion EnvironmentVariable_Extensions
-
- #region Property_Extensions
-
- ///
- /// UserDomainName
- ///
- public static string UserDomainName
- {
- get
- {
-#if UNIX
- return Platform.NonWindowsGetDomainName();
-#else
- return WinGetUserDomainName();
-#endif
- }
- }
-
- ///
- /// UserName
- ///
- public static string UserName
- {
- get
- {
-#if UNIX
- return Platform.Unix.UserName;
-#else
- return WinGetUserName();
-#endif
- }
- }
-
- ///
- /// MachineName
- ///
- public static string MachineName
- {
- get
- {
- return System.Environment.MachineName;
- }
- }
-
- ///
- /// OSVersion
- ///
- public static OperatingSystem OSVersion
- {
- get
- {
- if (s_os == null)
- {
-#if UNIX
- // TODO:PSL use P/Invoke to provide proper version
- // OSVersion will be back in CoreCLR 1.1
- s_os = new Environment.OperatingSystem(new Version(1, 0, 0, 0), "");
-#else
- s_os = WinGetOSVersion();
-#endif
- }
- return s_os;
- }
- }
- private static volatile OperatingSystem s_os;
-
- #endregion Property_Extensions
-
- #region SpecialFolder_Extensions
-
- ///
- /// The code is copied from the .NET implementation.
- ///
- public static string GetFolderPath(SpecialFolder folder)
- {
- return InternalGetFolderPath(folder);
- }
-
- ///
- /// The API set 'api-ms-win-shell-shellfolders-l1-1-0.dll' was removed from NanoServer, so we cannot depend on 'SHGetFolderPathW'
- /// to get the special folder paths. Instead, we need to rely on the basic environment variables to get the special folder paths.
- ///
- ///
- /// The path to the specified system special folder, if that folder physically exists on your computer.
- /// Otherwise, an empty string ("").
- ///
- private static string InternalGetFolderPath(SpecialFolder folder)
- {
- // The API 'SHGetFolderPath' is not available on OneCore, so we have to rely on environment variables
- string folderPath = null;
-
-#if UNIX
- string envHome = System.Environment.GetEnvironmentVariable(Platform.CommonEnvVariableNames.Home);
- if (null == envHome)
- {
- envHome = Platform.GetTemporaryDirectory();
- }
- switch (folder)
- {
- case SpecialFolder.ProgramFiles:
- folderPath = "/bin";
- if (!System.IO.Directory.Exists(folderPath)) { folderPath = null; }
- break;
- case SpecialFolder.ProgramFilesX86:
- folderPath = "/usr/bin";
- if (!System.IO.Directory.Exists(folderPath)) { folderPath = null; }
- break;
- case SpecialFolder.System:
- case SpecialFolder.SystemX86:
- folderPath = "/sbin";
- if (!System.IO.Directory.Exists(folderPath)) { folderPath = null; }
- break;
- case SpecialFolder.Personal:
- folderPath = envHome;
- break;
- case SpecialFolder.LocalApplicationData:
- folderPath = System.IO.Path.Combine(envHome, ".config");
- if (!System.IO.Directory.Exists(folderPath))
- {
- try
- {
- System.IO.Directory.CreateDirectory(folderPath);
- }
- catch (UnauthorizedAccessException)
- {
- // directory creation may fail if the account doesn't have filesystem permission such as some service accounts
- folderPath = String.Empty;
- }
- }
- break;
- default:
- throw new NotSupportedException();
- }
-#else
- string systemRoot = null;
- string userProfile = null;
-
- switch (folder)
- {
- case SpecialFolder.ProgramFiles:
- folderPath = System.Environment.GetEnvironmentVariable("ProgramFiles");
- if (!System.IO.Directory.Exists(folderPath)) { folderPath = null; }
- break;
- case SpecialFolder.ProgramFilesX86:
- folderPath = System.Environment.GetEnvironmentVariable("ProgramFiles(x86)");
- if (!System.IO.Directory.Exists(folderPath)) { folderPath = null; }
- break;
- case SpecialFolder.System:
- systemRoot = System.Environment.GetEnvironmentVariable("SystemRoot");
- if (systemRoot != null)
- {
- folderPath = System.IO.Path.Combine(systemRoot, "system32");
- if (!System.IO.Directory.Exists(folderPath)) { folderPath = null; }
- }
- break;
- case SpecialFolder.SystemX86:
- systemRoot = System.Environment.GetEnvironmentVariable("SystemRoot");
- if (systemRoot != null)
- {
- folderPath = System.IO.Path.Combine(systemRoot, "SysWOW64");
- if (!System.IO.Directory.Exists(folderPath)) { folderPath = null; }
- }
- break;
- case SpecialFolder.MyDocuments: // same as SpecialFolder.Personal
- userProfile = System.Environment.GetEnvironmentVariable(Platform.CommonEnvVariableNames.Home);
- if (userProfile != null)
- {
- folderPath = System.IO.Path.Combine(userProfile, "Documents");
- // CSS doesn't include a Documents directory for each user, so we create one if needed.
- if (!System.IO.Directory.Exists(folderPath)) { System.IO.Directory.CreateDirectory(folderPath); }
- }
- break;
- case SpecialFolder.LocalApplicationData:
- folderPath = System.Environment.GetEnvironmentVariable("LOCALAPPDATA");
- // When powershell gets executed in SetupComplete.cmd during NanoServer's first boot, 'LOCALAPPDATA' won't be set yet.
- // In this case, we need to return an alternate path, so that module auto-loading can continue to work properly.
- if (folderPath == null)
- {
- // It's guaranteed by NanoServer team that 'USERPROFILE' will be already set when SetupComplete.cmd runs.
- // So we use the path '%USERPROFILE%\AppData\Local' as an alternative in this case, and also set the env
- // variable %LOCALAPPDATA% to it, so that modules running in PS can depend on this env variable.
- userProfile = System.Environment.GetEnvironmentVariable(Platform.CommonEnvVariableNames.Home);
- if (userProfile != null)
- {
- string alternatePath = System.IO.Path.Combine(userProfile, @"AppData\Local");
- if (System.IO.Directory.Exists(alternatePath))
- {
- System.Environment.SetEnvironmentVariable("LOCALAPPDATA", alternatePath);
- folderPath = alternatePath;
- }
- }
- }
- else if (!System.IO.Directory.Exists(folderPath))
- {
- folderPath = null;
- }
- break;
- default:
- throw new NotSupportedException();
- }
-#endif
-
- return folderPath ?? string.Empty;
- }
-
- #endregion SpecialFolder_Extensions
-
- #region WinPlatform_Specific_Methods
-#if !UNIX
- ///
- /// Windows UserDomainName implementation
- ///
- private 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);
- }
-
- ///
- /// Windows UserName implementation
- ///
- private 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;
- }
-
- ///
- /// Windows OSVersion implementation
- ///
- private static OperatingSystem WinGetOSVersion()
- {
- 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);
- }
-
- ///
- /// 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 const int NameSamCompatible = 2; // EXTENDED_NAME_FORMAT - NameSamCompatible
-
- private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
- private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
- private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000;
-
- [DllImport("SspiCli.dll", CharSet = CharSet.Unicode, SetLastError = true)]
- // Win32 return type is BOOLEAN (which is 1 byte and not BOOL which is 4bytes)
- internal static extern byte GetUserNameEx(int format, [Out] StringBuilder domainName, ref uint domainNameLen);
-
- [DllImport(PinvokeDllNames.FormatMessageDllName, CharSet = CharSet.Unicode)]
- internal static extern int FormatMessage(int dwFlags, IntPtr lpSource, int dwMessageId,
- int dwLanguageId, [Out]StringBuilder lpBuffer,
- int nSize, IntPtr va_list_arguments);
-
- [DllImport(PinvokeDllNames.GetVersionExDllName, CharSet = CharSet.Unicode, SetLastError = true)]
- internal static extern bool GetVersionEx(ref OSVERSIONINFOEX osVerEx);
-
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
- internal struct OSVERSIONINFOEX
- {
- // The OSVersionInfoSize field must be set to Marshal.SizeOf(this)
- public int OSVersionInfoSize;
- public int MajorVersion;
- public int MinorVersion;
- public int BuildNumber;
- public int PlatformId;
- [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
- public string CSDVersion;
- public ushort ServicePackMajor;
- public ushort ServicePackMinor;
- public short SuiteMask;
- public byte ProductType;
- public byte Reserved;
- }
-
- ///
- /// The code is mostly copied from the .NET implementation.
- /// The only difference is how resource string is retrieved.
- /// We use the same resource string as in .NET implementation.
- ///
- internal static string GetMessage(int errorCode)
- {
- StringBuilder sb = new StringBuilder(512);
- int result = Win32Native.FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS |
- FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
- IntPtr.Zero, errorCode, 0, sb, sb.Capacity, IntPtr.Zero);
- if (result != 0)
- {
- return sb.ToString();
- }
- else
- {
- return string.Format(CultureInfo.CurrentCulture, CoreClrStubResources.UnknownErrorNumber, errorCode);
- }
- }
- }
-#endif
- #endregion WinPlatform_Specific_Methods
-
- #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
- {
- Personal = 0x05,
- MyDocuments = 0x05,
- LocalApplicationData = 0x1c,
- ProgramFiles = 0x26,
- ProgramFilesX86 = 0x2a,
- System = 0x25,
- SystemX86 = 0x29,
- }
-
- ///
- /// It only contains the properties that get used in powershell
- ///
- internal sealed class OperatingSystem
- {
- private Version _version;
- private string _servicePack;
- private string _versionString;
-
- internal OperatingSystem(Version version, string servicePack)
- {
- if (version == null)
- throw new ArgumentNullException("version");
-
- _version = version;
- _servicePack = servicePack;
- }
-
- ///
- /// OS version
- ///
- public Version Version
- {
- get { return _version; }
- }
-
- ///
- /// VersionString
- ///
- public string VersionString
- {
- get
- {
- if (_versionString != null)
- {
- return _versionString;
- }
-
- // It's always 'VER_PLATFORM_WIN32_NT' for NanoServer and IoT
- const string os = "Microsoft Windows NT ";
- if (string.IsNullOrEmpty(_servicePack))
- {
- _versionString = os + _version.ToString();
- }
- else
- {
- _versionString = os + _version.ToString(3) + " " + _servicePack;
- }
-
- return _versionString;
- }
- }
- }
-
- #endregion NestedTypes
- }
-
- #endregion Environment Extensions
-
- #region Non-generic collection extensions
-
- ///
- /// Add the AttributeCollection type with stripped functionalities for powershell on CoreCLR.
- /// The Adapter type has a protected abstract method 'PropertyAttributes' that returns an AttributeCollection
- /// instance. Third party adapter may already implement this method and thus we cannot change the return
- /// type for full powershell code. Therefore, we add the AttributeCollection type with minimal functionalities
- /// so that the code also work with CoreCLR.
- ///
- public class AttributeCollection : ICollection, IEnumerable
- {
- ///
- /// AttributeCollection
- ///
- public static readonly AttributeCollection Empty = new AttributeCollection(null);
-
- #region Constructors
-
- ///
- /// AttributeCollection protected constructor
- ///
- protected AttributeCollection()
- {
- }
-
- ///
- /// AttributeCollection public constructor
- ///
- ///
- public AttributeCollection(params Attribute[] attributes)
- {
- if (attributes == null)
- {
- attributes = new Attribute[0];
- }
-
- _attributes = attributes;
- for (int i = 0; i < attributes.Length; i++)
- {
- if (attributes[i] == null)
- {
- throw new ArgumentNullException("attributes");
- }
- }
- }
-
- #endregion Constructors
-
- #region Methods
-
- ///
- /// Copies the collection to an array, starting at the specified index.
- ///
- ///
- ///
- public void CopyTo(Array array, int index)
- {
- Array.Copy(this.Attributes, 0, array, index, this.Attributes.Length);
- }
-
- ///
- /// Gets an enumerator for this collection.
- ///
- ///
- public IEnumerator GetEnumerator()
- {
- return this.Attributes.GetEnumerator();
- }
-
- IEnumerator IEnumerable.GetEnumerator()
- {
- return this.GetEnumerator();
- }
-
- #endregion Methods
-
- #region Properties
-
- private readonly Attribute[] _attributes;
- ///
- /// Gets the attribute collection.
- ///
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
- protected virtual Attribute[] Attributes
- {
- get
- {
- return _attributes;
- }
- }
-
- ///
- /// Gets the number of attributes.
- ///
- public int Count
- {
- get
- {
- return this.Attributes.Length;
- }
- }
-
- ///
- /// Gets the attribute with the specified index number.
- ///
- ///
- ///
- public virtual Attribute this[int index]
- {
- get
- {
- return this.Attributes[index];
- }
- }
-
- int ICollection.Count
- {
- get
- {
- return this.Count;
- }
- }
-
- bool ICollection.IsSynchronized
- {
- get
- {
- return false;
- }
- }
-
- object ICollection.SyncRoot
- {
- get
- {
- return null;
- }
- }
-
- #endregion Properties
- }
-
- #endregion Non-generic collection extensions
-
- #region Misc extensions
-
- ///
- /// Add the Pointer type with stripped functionalities for PowerShell on CoreCLR.
- /// We need this type because if a method returns a pointer, we need to wrap it into an object.
- ///
- public sealed class Pointer
- {
- private unsafe void* _ptr;
- private Type _ptrType;
-
- private Pointer()
- {
- }
-
- #region Methods
-
- ///
- /// Boxes the supplied unmanaged memory pointer and the type associated with that pointer into a managed Pointer wrapper object.
- /// The value and the type are saved so they can be accessed from the native code during an invocation.
- ///
- ///
- ///
- ///
- public static unsafe object Box(void* ptr, Type type)
- {
- if (type == null)
- {
- throw new ArgumentNullException("type");
- }
- if (!type.IsPointer)
- {
- throw new ArgumentException("Argument must be pointer", "ptr");
- }
-
- Pointer pointer = new Pointer();
- pointer._ptr = ptr;
- pointer._ptrType = type;
- return pointer;
- }
-
- ///
- /// Returns the stored pointer.
- ///
- ///
- ///
- public static unsafe void* Unbox(object ptr)
- {
- var pointer = ptr as Pointer;
- if (pointer == null)
- {
- throw new ArgumentException("Argument must be pointer", "ptr");
- }
- return ((Pointer)ptr)._ptr;
- }
-
- #endregion Methods
- }
-
- internal static class ListExtensions
- {
- internal static void ForEach(this List list, Action action)
- {
- if (list == null)
- {
- throw new ArgumentNullException("list");
- }
-
- if (action == null)
- {
- throw new ArgumentNullException("action");
- }
-
- for (int i = 0; i < list.Count; i++)
- {
- action(list[i]);
- }
- }
- }
-
- internal static class X509StoreExtensions
- {
- ///
- /// X509Store.Close() is not in CoreCLR and it's supposed to be replaced by X509Store.Dispose().
- /// However, X509Store.Dispose() is not supported until .NET 4.6. So we have to have this extension
- /// method 'Close' for X509Store for OneCore powershell, so that it works for both Full/Core CLR.
- ///
- internal static void Close(this System.Security.Cryptography.X509Certificates.X509Store x509Store)
- {
- x509Store.Dispose();
- }
- }
-
- #endregion Misc extensions
-}
-
-
namespace Microsoft.PowerShell.CoreCLR
{
using System.IO;
+ using System.Reflection;
using System.Management.Automation;
///
diff --git a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs
index d3f8cead66..8444727136 100644
--- a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs
+++ b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs
@@ -410,6 +410,73 @@ namespace System.Management.Automation
}
#endif
+ ///
+ /// The code is copied from the .NET implementation.
+ ///
+ internal static string GetFolderPath(System.Environment.SpecialFolder folder)
+ {
+ return InternalGetFolderPath(folder);
+ }
+
+ ///
+ /// The API set 'api-ms-win-shell-shellfolders-l1-1-0.dll' was removed from NanoServer, so we cannot depend on 'SHGetFolderPathW'
+ /// to get the special folder paths. Instead, we need to rely on the basic environment variables to get the special folder paths.
+ ///
+ ///
+ /// The path to the specified system special folder, if that folder physically exists on your computer.
+ /// Otherwise, an empty string ("").
+ ///
+ private static string InternalGetFolderPath(System.Environment.SpecialFolder folder)
+ {
+ string folderPath = null;
+#if UNIX
+ string envHome = System.Environment.GetEnvironmentVariable(Platform.CommonEnvVariableNames.Home);
+ if (null == envHome)
+ {
+ envHome = Platform.GetTemporaryDirectory();
+ }
+ switch (folder)
+ {
+ case System.Environment.SpecialFolder.ProgramFiles:
+ folderPath = "/bin";
+ if (!System.IO.Directory.Exists(folderPath)) { folderPath = null; }
+ break;
+ case System.Environment.SpecialFolder.ProgramFilesX86:
+ folderPath = "/usr/bin";
+ if (!System.IO.Directory.Exists(folderPath)) { folderPath = null; }
+ break;
+ case System.Environment.SpecialFolder.System:
+ case System.Environment.SpecialFolder.SystemX86:
+ folderPath = "/sbin";
+ if (!System.IO.Directory.Exists(folderPath)) { folderPath = null; }
+ break;
+ case System.Environment.SpecialFolder.Personal:
+ folderPath = envHome;
+ break;
+ case System.Environment.SpecialFolder.LocalApplicationData:
+ folderPath = System.IO.Path.Combine(envHome, ".config");
+ if (!System.IO.Directory.Exists(folderPath))
+ {
+ try
+ {
+ System.IO.Directory.CreateDirectory(folderPath);
+ }
+ catch (UnauthorizedAccessException)
+ {
+ // directory creation may fail if the account doesn't have filesystem permission such as some service accounts
+ folderPath = String.Empty;
+ }
+ }
+ break;
+ default:
+ throw new NotSupportedException();
+ }
+#else
+ folderPath = System.Environment.GetFolderPath(folder);
+#endif
+ return folderPath ?? string.Empty;
+ }
+
// Platform methods prefixed NonWindows are:
// - non-windows by the definition of the IsWindows method above
// - here, because porting to Linux and other operating systems
diff --git a/src/System.Management.Automation/CoreCLR/CorePsStub.cs b/src/System.Management.Automation/CoreCLR/CorePsStub.cs
index 8c4bc8ba89..f070a11f9b 100644
--- a/src/System.Management.Automation/CoreCLR/CorePsStub.cs
+++ b/src/System.Management.Automation/CoreCLR/CorePsStub.cs
@@ -5,12 +5,8 @@ Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Globalization;
-using System.Reflection;
-using System.Collections;
using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
using Microsoft.Win32;
-using System.Management.Automation.Remoting;
#pragma warning disable 1591, 1572, 1571, 1573, 1587, 1570, 0067
@@ -20,515 +16,6 @@ using System.Management.Automation.Remoting;
// We use the stubs in this namespace to reduce #if/def in the code as much as possible.
namespace Microsoft.PowerShell.CoreClr.Stubs
{
- using System.Runtime.InteropServices;
- // We create some stub attribute types to make some attribute markers work in CoreCLR.
- // The purpose of this is to avoid #if/def in powershell code as much as possible.
-
- #region Attribute_Related
-
- ///
- /// Stub for SpecialNameAttribute
- ///
- public sealed class SpecialNameAttribute : Attribute
- {
- ///
- ///
- ///
- public SpecialNameAttribute() { }
- }
-
- ///
- /// Stub for SerializableAttribute
- ///
- public sealed class SerializableAttribute : Attribute
- {
- ///
- ///
- ///
- public SerializableAttribute() { }
- }
-
- ///
- /// Stub for NonSerializedAttribute
- ///
- public sealed class NonSerializedAttribute : Attribute
- {
- ///
- ///
- ///
- public NonSerializedAttribute() { }
- }
-
- ///
- /// Stub for SecurityAction
- ///
- public enum SecurityAction
- {
- Assert = 3,
- Demand = 2,
- InheritanceDemand = 7,
- LinkDemand = 6,
- PermitOnly = 5
- }
-
- ///
- /// Stub for SecurityPermissionAttribute
- ///
- public sealed class SecurityPermissionAttribute : Attribute
- {
- public SecurityPermissionAttribute(SecurityAction action) { }
- public bool SerializationFormatter { get; set; }
-
- public bool UnmanagedCode { get; set; }
- }
-
- ///
- /// Stub for TypeLibTypeAttribute
- ///
- public sealed class TypeLibTypeAttribute : Attribute
- {
- ///
- ///
- ///
- ///
- public TypeLibTypeAttribute(short flags) { }
- }
-
- ///
- /// Stub for SuppressUnmanagedCodeSecurityAttribute
- ///
- public class SuppressUnmanagedCodeSecurityAttribute : Attribute
- { }
-
- ///
- /// Stub for HostProtectionAttribute
- ///
- public sealed class HostProtectionAttribute : Attribute
- {
- public HostProtectionAttribute(SecurityAction action) { }
- public bool MayLeakOnAbort { get; set; }
- }
-
- ///
- /// Stub for ResourceExposureAttribute
- ///
- public sealed class ResourceExposureAttribute : Attribute
- {
- private ResourceScope _resourceExposureLevel;
-
- public ResourceExposureAttribute(ResourceScope exposureLevel)
- {
- _resourceExposureLevel = exposureLevel;
- }
-
- public ResourceScope ResourceExposureLevel
- {
- get { return _resourceExposureLevel; }
- }
- }
-
- ///
- /// Stub for ResourceScope
- ///
- public enum ResourceScope
- {
- None = 0,
- // Resource type
- Machine = 0x1,
- Process = 0x2,
- AppDomain = 0x4,
- Library = 0x8,
- // Visibility
- Private = 0x10, // Private to this one class.
- Assembly = 0x20, // Assembly-level, like C#'s "internal"
- }
-
- ///
- /// Stub for ReliabilityContractAttribute
- ///
- public sealed class ReliabilityContractAttribute : Attribute
- {
- ///
- ///
- ///
- public ReliabilityContractAttribute(Consistency consistencyGuarantee, Cer cer)
- {
- }
- }
-
- ///
- /// Stub for Cer
- ///
- public enum Cer
- {
- ///
- /// None
- ///
- None,
-
- ///
- /// MayFail
- ///
- MayFail,
-
- ///
- /// Success
- ///
- Success
- }
-
- ///
- /// Stub for Consistency
- ///
- public enum Consistency
- {
- ///
- /// MayCorruptProcess
- ///
- MayCorruptProcess,
-
- ///
- /// MayCorruptAppDomain
- ///
- MayCorruptAppDomain,
-
- ///
- /// MayCorruptInstance
- ///
- MayCorruptInstance,
-
- ///
- /// WillNotCorruptState
- ///
- WillNotCorruptState
- }
-
- #endregion Attribute_Related
-
- #region Serialization_Related
-
- ///
- /// Stub for SerializationInfo
- ///
- public sealed class SerializationInfo
- {
- ///
- ///
- ///
- public SerializationInfo() { }
-
- ///
- ///
- ///
- ///
- ///
- public void AddValue(string name, object value)
- {
- throw new NotImplementedException("AddValue(string name, object value)");
- }
-
- ///
- ///
- ///
- ///
- ///
- public void AddValue(string name, bool value)
- {
- throw new NotImplementedException("AddValue(string name, bool value)");
- }
-
- ///
- ///
- ///
- ///
- ///
- ///
- public void AddValue(string name, Object value, Type type)
- {
- throw new NotImplementedException("AddValue(string name, Object value, Type type)");
- }
-
- ///
- ///
- ///
- ///
- ///
- public void AddValue(string name, int value)
- {
- throw new NotImplementedException("AddValue(string name, int value)");
- }
-
- ///
- ///
- ///
- ///
- ///
- ///
- public object GetValue(string name, Type type)
- {
- throw new NotImplementedException("GetValue(string name, Type type)");
- }
-
- ///
- ///
- ///
- ///
- ///
- public string GetString(string name)
- {
- throw new NotImplementedException("GetString(string name)");
- }
-
- ///
- ///
- ///
- ///
- ///
- public bool GetBoolean(string name)
- {
- throw new NotImplementedException("GetBoolean(string name)");
- }
-
- ///
- ///
- ///
- ///
- ///
- public int GetInt32(string name)
- {
- throw new NotImplementedException("GetInt32(string name)");
- }
-
- ///
- ///
- ///
- ///
- public void SetType(System.Type type)
- {
- throw new NotImplementedException("SetType(System.Type type)");
- }
-
- ///
- ///
- ///
- ///
- ///
- public long GetInt64(string name)
- {
- throw new NotImplementedException("GetInt64(string name)");
- }
- }
-
- #endregion Serialization_Related
-
- #region Interface_Related
-
- ///
- /// Stub for ISerializable
- ///
- public interface ISerializable
- {
- ///
- ///
- ///
- ///
- ///
- void GetObjectData(SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
- }
-
- ///
- /// Stub for ICloneable
- ///
- public interface ICloneable
- {
- ///
- ///
- ///
- ///
- object Clone();
- }
-
- ///
- /// Stub for IObjectReference
- ///
- public interface IObjectReference
- {
- ///
- ///
- ///
- ///
- ///
- Object GetRealObject(System.Runtime.Serialization.StreamingContext context);
- }
-
- ///
- /// Stub for IRuntimeVariables
- ///
- public interface IRuntimeVariables
- {
- ///
- ///
- ///
- int Count { get; }
-
- ///
- ///
- ///
- ///
- ///
- object this[int index] { get; set; }
- }
-
- #endregion Interface_Related
-
- #region Exception_Related
-
- ///
- /// Stub for SystemException
- ///
- public class SystemException : Exception
- {
- ///
- /// SystemException constructor
- ///
- public SystemException() : base() { }
-
- ///
- /// SystemException constructor
- ///
- ///
- public SystemException(string message) : base(message) { }
-
- ///
- /// SystemException constructor
- ///
- ///
- ///
- public SystemException(string message, Exception innerException) : base(message, innerException) { }
-
- ///
- /// SystemException constructor
- ///
- ///
- ///
- protected SystemException(SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
-
- ///
- /// SystemException constructor
- ///
- ///
- ///
- public virtual void GetObjectData(SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
- }
-
- ///
- /// Stub for AccessViolationException
- ///
- public class AccessViolationException : Exception
- {
- ///
- /// AccessViolationException constructor
- ///
- public AccessViolationException() : base() { }
-
- ///
- /// AccessViolationException constructor
- ///
- ///
- public AccessViolationException(string message) : base(message) { }
-
- ///
- /// AccessViolationException constructor
- ///
- ///
- ///
- public AccessViolationException(string message, Exception innerException) : base(message, innerException) { }
-
- ///
- /// AccessViolationException constructor
- ///
- ///
- ///
- protected AccessViolationException(SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
-
- ///
- /// AccessViolationException constructor
- ///
- ///
- ///
- public virtual void GetObjectData(SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
- }
-
- ///
- /// Stub for ThreadAbortException
- ///
- public sealed class ThreadAbortException : Exception
- {
- }
-
- ///
- /// Stub for AppDomainUnloadedException
- ///
- public sealed class AppDomainUnloadedException : Exception
- {
- }
-
- #endregion Exception_Related
-
- #region SafeHandle_Related
-
- ///
- /// Stub for SafeHandleZeroOrMinusOneIsInvalid
- ///
- public abstract class SafeHandleZeroOrMinusOneIsInvalid : SafeHandle
- {
- ///
- /// Constructor
- ///
- protected SafeHandleZeroOrMinusOneIsInvalid(bool ownsHandle)
- : base(IntPtr.Zero, ownsHandle)
- {
- }
-
- ///
- /// IsInvalid
- ///
- public override bool IsInvalid
- {
- get
- {
- return handle == IntPtr.Zero || handle == new IntPtr(-1);
- }
- }
- }
-
- ///
- /// Stub for SafeHandleMinusOneIsInvalid
- ///
- public abstract class SafeHandleMinusOneIsInvalid : SafeHandle
- {
- ///
- /// Constructor
- ///
- protected SafeHandleMinusOneIsInvalid(bool ownsHandle)
- : base(new IntPtr(-1), ownsHandle)
- {
- }
-
- ///
- /// IsInvalid
- ///
- public override bool IsInvalid
- {
- get
- {
- return handle == new IntPtr(-1);
- }
- }
- }
-
- #endregion SafeHandle_Related
-
#region Misc_Types
///
@@ -546,22 +33,15 @@ namespace Microsoft.PowerShell.CoreClr.Stubs
}
///
- /// Stub for ProcessWindowStyle
+ /// Stub for TypeLibTypeAttribute
///
- public enum ProcessWindowStyle
+ public sealed class TypeLibTypeAttribute : Attribute
{
- Normal,
- Hidden,
- Minimized,
- Maximized
- }
-
- ///
- /// Stub for MailAddress
- ///
- public class MailAddress
- {
- public MailAddress(string address) { }
+ ///
+ ///
+ ///
+ ///
+ public TypeLibTypeAttribute(short flags) { }
}
#endregion Misc_Types
@@ -642,125 +122,6 @@ namespace Microsoft.PowerShell.CoreClr.Stubs
#endregion
}
-
-//TODO:CORECLR Put Stubs to System.Management.Core.dll
-namespace System
-{
- ///
- /// TODO:CORECLR Inspection of the binary module needs to be re-write without using AppDomain
- ///
- internal sealed class AppDomain
- {
- ///
- ///
- ///
- public static System.AppDomain CreateDomain(string friendlyName)
- {
- return null;
- }
-
- ///
- ///
- ///
- public static void Unload(System.AppDomain domain)
- {
- }
- }
-}
-
-namespace System.Net
-{
- internal class WebClient //: Component
- {
- public WebClient() { }
-
- public void Dispose() { }
-
- public bool UseDefaultCredentials { get; set; }
- }
-}
-
-namespace System.Security
-{
- using System.Text;
-
- ///
- ///
- ///
- sealed public class SecurityElement
- {
- private static readonly string[] s_escapeStringPairs = new string[]
- {
- // these must be all once character escape sequences or a new escaping algorithm is needed
- "<", "<",
- ">", ">",
- "\"", """,
- "\'", "'",
- "&", "&"
- };
- private static readonly char[] s_escapeChars = new char[] { '<', '>', '\"', '\'', '&' };
-
- ///
- /// Replaces invalid XML characters in a string with their valid XML equivalent.
- ///
- public static string Escape(string str)
- {
- if (str == null)
- return null;
-
- StringBuilder sb = null;
-
- int strLen = str.Length;
- int index; // Pointer into the string that indicates the location of the current '&' character
- int newIndex = 0; // Pointer into the string that indicates the start index of the "remaining" string (that still needs to be processed).
-
- do
- {
- index = str.IndexOfAny(s_escapeChars, newIndex);
-
- if (index == -1)
- {
- if (sb == null)
- return str;
- else
- {
- sb.Append(str, newIndex, strLen - newIndex);
- return sb.ToString();
- }
- }
- else
- {
- if (sb == null)
- sb = new StringBuilder();
-
- sb.Append(str, newIndex, index - newIndex);
- sb.Append(GetEscapeSequence(str[index]));
-
- newIndex = (index + 1);
- }
- }
- while (true);
- }
-
- private static string GetEscapeSequence(char c)
- {
- int iMax = s_escapeStringPairs.Length;
-
- for (int i = 0; i < iMax; i += 2)
- {
- String strEscSeq = s_escapeStringPairs[i];
- String strEscValue = s_escapeStringPairs[i + 1];
-
- if (strEscSeq[0] == c)
- return strEscValue;
- }
-
- Diagnostics.Debug.Assert(false, "Unable to find escape sequence for this character");
- return c.ToString();
- }
- }
-}
-
#endregion CLR_STUBS
#region PS_STUBS
@@ -1357,18 +718,6 @@ namespace System.Management.Automation
}
#endregion
-
- #region Environment
-
- internal static partial class Environment
- {
- //TODO:CORECLR Need to be removed once we decide what will be the replacement
- internal static void Exit(int exitCode)
- {
- }
- }
-
- #endregion Environment
}
namespace System.Management.Automation.Security
@@ -1427,6 +776,7 @@ namespace System.Management.Automation.Security
// Porting note: Tracing is absolutely not available on Linux
namespace System.Management.Automation.Tracing
{
+ using System.Diagnostics.CodeAnalysis;
using System.Management.Automation.Internal;
///
@@ -1792,61 +1142,6 @@ namespace Microsoft.PowerShell
#endregion TEMPORARY
-
-
-#region Timer
-namespace System
-{
- // Summary:
- // Provides data for the event that is raised when there is an exception that
- // is not handled in any application domain.
- //[Serializable]
- //[ComVisible(true)]
- internal class UnhandledExceptionEventArgs : EventArgs
- {
- // Summary:
- // Initializes a new instance of the System.UnhandledExceptionEventArgs class
- // with the exception object and a common language runtime termination flag.
- //PS_STUBS_FOR_REMOTE
- // Parameters:
- // exception:
- // The exception that is not handled.
- //
- // isTerminating:
- // true if the runtime is terminating; otherwise, false.
- public UnhandledExceptionEventArgs(object exception, bool isTerminating) { }
-
- // Summary:
- // Gets the unhandled exception object.
- //
- // Returns:
- // The unhandled exception object.
- public object ExceptionObject
- {
- get
- {
- return null;
- }
- }
-
- //
- // Summary:
- // Indicates whether the common language runtime is terminating.
- //
- // Returns:
- // true if the runtime is terminating; otherwise, false.
- public bool IsTerminating
- {
- get
- {
- return false;
- }
- }
- }
-}
-
-#endregion Timer
-
#pragma warning restore 1591, 1572, 1571, 1573, 1587, 1570, 0067
#endif
diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs
index 8f86b4cdd0..2a8d104cf2 100644
--- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs
+++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs
@@ -17,13 +17,6 @@ using System.Runtime.InteropServices;
using System.Reflection;
using System.Text;
using System.Security;
-using Dbg = System.Management.Automation.Diagnostics;
-
-#if CORECLR
-
-using Environment = System.Management.Automation.Environment;
-
-#endif
namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
{
@@ -618,15 +611,6 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
Initialize(null, null);
}
-#if CORECLR
- ///
- ///
- private static string SystemDirectory
- {
- get { return Environment.GetFolderPath(Environment.SpecialFolder.System); }
- }
-#endif
-
///
/// Initialize the class cache with the default classes in $ENV:SystemDirectory\Configuration.
///
@@ -679,12 +663,8 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
}
else
{
-#if CORECLR
- var systemResourceRoot = Path.Combine(SystemDirectory, "Configuration");
-#else
- var systemResourceRoot = Path.Combine(Environment.SystemDirectory, "Configuration");
-#endif
- var programFilesDirectory = Environment.GetEnvironmentVariable("ProgramFiles");
+ var systemResourceRoot = Path.Combine(Platform.GetFolderPath(Environment.SpecialFolder.System), "Configuration");
+ var programFilesDirectory = Platform.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
Debug.Assert(programFilesDirectory != null, "Program Files environment variable does not exist!");
var customResourceRoot = Path.Combine(programFilesDirectory, "WindowsPowerShell\\Configuration");
Debug.Assert(Directory.Exists(customResourceRoot), "%ProgramFiles%\\WindowsPowerShell\\Configuration Directory does not exist");
@@ -724,11 +704,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
List modulePaths = new List();
if (modulePathList == null || modulePathList.Count == 0)
{
-#if CORECLR
- modulePaths.Add(Path.Combine(SystemDirectory, InboxDscResourceModulePath));
-#else
- modulePaths.Add(Path.Combine(Environment.SystemDirectory, InboxDscResourceModulePath));
-#endif
+ modulePaths.Add(Path.Combine(Platform.GetFolderPath(Environment.SpecialFolder.System), InboxDscResourceModulePath));
isInboxResource = true;
}
else
@@ -989,11 +965,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
if (value != null)
{
-#if CORECLR
- IntPtr ptr = SecureStringMarshal.SecureStringToCoTaskMemUnicode(value);
-#else
IntPtr ptr = Marshal.SecureStringToCoTaskMemUnicode(value);
-#endif
passwordValueToAdd = Marshal.PtrToStringUni(ptr);
Marshal.ZeroFreeCoTaskMemUnicode(ptr);
}
diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj
index 4be687a262..54ea060932 100644
--- a/src/System.Management.Automation/System.Management.Automation.csproj
+++ b/src/System.Management.Automation/System.Management.Automation.csproj
@@ -2,7 +2,7 @@
6.0.0
- netstandard1.6
+ netcoreapp2.0
$(NoWarn);CS1570;CS1734
true
true
@@ -16,50 +16,22 @@
false
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
-
+
$(DefineConstants);CORECLR
-
+
@@ -123,7 +95,6 @@
-
@@ -137,6 +108,7 @@
+
diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs
index 96980f0978..64baa319c6 100644
--- a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs
+++ b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs
@@ -22,13 +22,6 @@ using System.Management.Automation.Language;
using Microsoft.PowerShell.Commands;
using Dbg = System.Management.Automation.Diagnostics;
-#if CORECLR
-// Some APIs are missing from System.Environment. We use System.Management.Automation.Environment as a proxy type:
-// - for missing APIs, System.Management.Automation.Environment has extension implementation.
-// - for existing APIs, System.Management.Automation.Environment redirect the call to System.Environment.
-using Environment = System.Management.Automation.Environment;
-#endif
-
namespace Microsoft.PowerShell.Cmdletization
{
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
@@ -54,9 +47,6 @@ namespace Microsoft.PowerShell.Cmdletization
ScriptWriter.s_xmlReaderSettings.MaxCharactersFromEntities = 16384; // generous guess for the upper bound
ScriptWriter.s_xmlReaderSettings.MaxCharactersInDocument = 128 * 1024 * 1024; // generous guess for the upper bound
-#if CORECLR // XmlReaderSettings doesn't have XmlResolver and Schema Validation related members in CoreCLR.
- ScriptWriter.s_xmlReaderSettings.DtdProcessing = DtdProcessing.Ignore; // DtdProcessing.Parse is not in CoreCLR, so we ignore DTDs in OneCore powershell
-#else
ScriptWriter.s_xmlReaderSettings.DtdProcessing = DtdProcessing.Parse; // Allowing DTD parsing with limits of MaxCharactersFromEntities/MaxCharactersInDocument
ScriptWriter.s_xmlReaderSettings.XmlResolver = null; // do not fetch external documents
// xsd schema related settings
@@ -68,7 +58,6 @@ namespace Microsoft.PowerShell.Cmdletization
ScriptWriter.s_xmlReaderSettings.Schemas = new XmlSchemaSet();
ScriptWriter.s_xmlReaderSettings.Schemas.Add(null, cmdletizationSchemaReader);
ScriptWriter.s_xmlReaderSettings.Schemas.XmlResolver = null; // do not fetch external documents
-#endif
}
#endregion Static code reused for reading cmdletization xml
@@ -110,13 +99,12 @@ namespace Microsoft.PowerShell.Cmdletization
}
catch (InvalidOperationException e)
{
-#if !CORECLR // No XmlSchema Validation In CoreCLR
XmlSchemaException schemaException = e.InnerException as XmlSchemaException;
if (schemaException != null)
{
throw new XmlException(schemaException.Message, schemaException, schemaException.LineNumber, schemaException.LinePosition);
}
-#endif
+
XmlException xmlException = e.InnerException as XmlException;
if (xmlException != null)
{
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 62ccf78250..2caaf34487 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
@@ -13,14 +13,7 @@ using System.Diagnostics.CodeAnalysis;
using Microsoft.PowerShell.Commands.Internal.Format;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
-
-#if CORECLR
-// Use stubs for SerializationInfo, SecurityPermissionAttribute and Serializable
-using Microsoft.PowerShell.CoreClr.Stubs;
-#else
-// TODO:CORECLR Permissions is not available on CORE CLR yet
using System.Security.Permissions;
-#endif
namespace System.Management.Automation.Runspaces
{
diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs
index 53f974f31d..682b09c23a 100644
--- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs
+++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs
@@ -11,11 +11,6 @@ using System.Management.Automation.Host;
using System.Globalization;
using System.Text;
-#if CORECLR
-// Use stubs for SystemException
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
/*
SUMMARY: this file contains a general purpose, reusable framework for
loading XML files, and do data validation.
diff --git a/src/System.Management.Automation/engine/Credential.cs b/src/System.Management.Automation/engine/Credential.cs
index 76d62f4702..26a1d0ac0c 100644
--- a/src/System.Management.Automation/engine/Credential.cs
+++ b/src/System.Management.Automation/engine/Credential.cs
@@ -7,17 +7,10 @@ Copyright (c) Microsoft Corporation. All rights reserved.
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Security;
-using SafeString = System.String;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using Microsoft.PowerShell;
-#if CORECLR
-// Use stubs for ISerializable related types
-using Microsoft.PowerShell.CoreClr.Stubs;
-using System.Runtime.InteropServices;
-#endif
-
// FxCop suppressions for resource strings:
[module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "Credential.resources", MessageId = "Cred")]
@@ -163,8 +156,8 @@ namespace System.Management.Automation
_userName = (string)info.GetValue("UserName", typeof(string));
// deserialize to secure string
- SafeString safePassword = (SafeString)info.GetValue("Password", typeof(SafeString));
- if (safePassword == SafeString.Empty)
+ string safePassword = (string)info.GetValue("Password", typeof(string));
+ if (safePassword == string.Empty)
{
_password = new SecureString();
}
@@ -272,28 +265,7 @@ namespace System.Management.Automation
if (IsValidUserName(_userName, out user, out domain))
{
-#if CORECLR
- // NetworkCredential constructor only accepts plain string password in .NET Core.
- // TODO: This raises security concerns about having the plain string password in memory
- // for an indefinite period of time. So we need to change back to the constructor that
- // takes a SecureString password once it becomes available in .NET Core.
- IntPtr unmanagedPtr = IntPtr.Zero;
- try
- {
- unmanagedPtr = ClrFacade.SecureStringToCoTaskMemUnicode(_password);
- string pwdInPlainText = System.Runtime.InteropServices.Marshal.PtrToStringUni(unmanagedPtr);
- _netCred = new NetworkCredential(user, pwdInPlainText, domain);
- }
- finally
- {
- if (unmanagedPtr != IntPtr.Zero)
- {
- Marshal.ZeroFreeCoTaskMemUnicode(unmanagedPtr);
- }
- }
-#else
_netCred = new NetworkCredential(user, _password, domain);
-#endif
}
}
diff --git a/src/System.Management.Automation/engine/ErrorPackage.cs b/src/System.Management.Automation/engine/ErrorPackage.cs
index 9fc3f1a147..1927a4746f 100644
--- a/src/System.Management.Automation/engine/ErrorPackage.cs
+++ b/src/System.Management.Automation/engine/ErrorPackage.cs
@@ -13,15 +13,8 @@ using System.Text;
using System.Resources;
using System.Runtime.Serialization;
using System.Reflection;
-using Dbg = System.Management.Automation.Diagnostics;
using System.Management.Automation.Language;
-
-#if CORECLR
-// Use stubs for SerializableAttribute, SecurityPermissionAttribute and ISerializable related types
-using Microsoft.PowerShell.CoreClr.Stubs;
-#else
using System.Security.Permissions;
-#endif
namespace System.Management.Automation
{
diff --git a/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs b/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs
index 69f113f744..61b2195d79 100644
--- a/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs
+++ b/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs
@@ -4,13 +4,7 @@ Copyright (c) Microsoft Corporation. All rights reserved.
using System.Runtime.Serialization;
using System.Management.Automation.Internal;
-
-#if !CORECLR
using System.Security.Permissions;
-#else
-// Use stubs for ISerializable related types
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
namespace System.Management.Automation
{
@@ -537,7 +531,7 @@ namespace System.Management.Automation
public class PSInvalidCastException : InvalidCastException, IContainsErrorRecord
{
#region Serialization
-#if !CORECLR // InvalidCastException Has No Serialization In CoreCLR
+
///
/// Populates a with the
/// data needed to serialize the PSInvalidCastException object.
@@ -564,7 +558,7 @@ namespace System.Management.Automation
{
_errorId = info.GetString("ErrorId");
}
-#endif
+
#endregion Serialization
///
diff --git a/src/System.Management.Automation/engine/ExternalScriptInfo.cs b/src/System.Management.Automation/engine/ExternalScriptInfo.cs
index 39ce6dd4c5..0a2897ed50 100644
--- a/src/System.Management.Automation/engine/ExternalScriptInfo.cs
+++ b/src/System.Management.Automation/engine/ExternalScriptInfo.cs
@@ -11,11 +11,6 @@ using System.Collections.Generic;
using System.Management.Automation.Language;
using System.Management.Automation.Security;
-#if CORECLR
-// Use stub for SerializableAttribute
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace System.Management.Automation
{
///
diff --git a/src/System.Management.Automation/engine/InformationRecord.cs b/src/System.Management.Automation/engine/InformationRecord.cs
index 2b2ca1dc45..13ae2c99b9 100644
--- a/src/System.Management.Automation/engine/InformationRecord.cs
+++ b/src/System.Management.Automation/engine/InformationRecord.cs
@@ -2,14 +2,8 @@
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
-using Dbg = System.Management.Automation.Diagnostics;
using System.Runtime.Serialization;
using System.Collections.Generic;
-using System.Management.Automation.Language;
-
-#if CORECLR
-using Environment = System.Management.Automation.Environment;
-#endif
namespace System.Management.Automation
{
diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs
index 49f6051190..41513799c0 100644
--- a/src/System.Management.Automation/engine/LanguagePrimitives.cs
+++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs
@@ -2127,7 +2127,8 @@ namespace System.Management.Automation
using (typeConversion.TraceScope("Looking for \"{0}\" cast operator.", methodName))
{
// Get multiple matched Public & Static methods
- var methods = ClrFacade.GetMethods(targetType, methodName);
+ const BindingFlags flagsToUse = BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod;
+ var methods = targetType.GetMember(methodName, flagsToUse);
foreach (MethodInfo method in methods)
{
if (!resultType.IsAssignableFrom(method.ReturnType))
diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs
index 92d73aeb8f..ee2a571458 100644
--- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs
+++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs
@@ -20,13 +20,6 @@ using System.Xml;
using Microsoft.PowerShell.Cmdletization;
using Dbg = System.Management.Automation.Diagnostics;
-#if CORECLR
-// Some APIs are missing from System.Environment. We use System.Management.Automation.Environment as a proxy type:
-// - for missing APIs, System.Management.Automation.Environment has extension implementation.
-// - for existing APIs, System.Management.Automation.Environment redirect the call to System.Environment.
-using Environment = System.Management.Automation.Environment;
-#endif
-
//
// Now define the set of commands for manipulating modules.
//
diff --git a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs
index 8b7b34d6a4..c903b5b622 100644
--- a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs
+++ b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs
@@ -16,13 +16,6 @@ using System.Management.Automation.Internal;
using System.Diagnostics.CodeAnalysis;
using Dbg = System.Management.Automation.Diagnostics;
-#if CORECLR
-// Some APIs are missing from System.Environment. We use System.Management.Automation.Environment as a proxy type:
-// - for missing APIs, System.Management.Automation.Environment has extension implementation.
-// - for existing APIs, System.Management.Automation.Environment redirect the call to System.Environment.
-using Environment = System.Management.Automation.Environment;
-#endif
-
//
// Now define the set of commands for manipulating modules.
//
@@ -837,7 +830,7 @@ namespace Microsoft.PowerShell.Commands
///
protected override void EndProcessing()
{
- // Win8: 264471 - Error message for New-ModuleManifest –ProcessorArchitecture is obsolete.
+ // Win8: 264471 - Error message for New-ModuleManifest -ProcessorArchitecture is obsolete.
// If an undefined value is passed for the ProcessorArchitecture parameter, the error message from parameter binder includes all the values from the enum.
// The value 'IA64' for ProcessorArchitecture is not supported. But since we do not own the enum System.Reflection.ProcessorArchitecture, we cannot control the values in it.
// So, we add a separate check in our code to give an error if user specifies IA64
diff --git a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs
index 49351032f0..8fb272b488 100644
--- a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs
+++ b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs
@@ -10,11 +10,6 @@ using System.Text;
using System.Management.Automation.Language;
using System.Text.RegularExpressions;
-#if CORECLR
-// Use stub for SerializableAttribute.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace System.Management.Automation
{
///
diff --git a/src/System.Management.Automation/engine/MshObject.cs b/src/System.Management.Automation/engine/MshObject.cs
index 25d0f304a5..197bdd4c7b 100644
--- a/src/System.Management.Automation/engine/MshObject.cs
+++ b/src/System.Management.Automation/engine/MshObject.cs
@@ -7,6 +7,7 @@ using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
+using System.Data;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
@@ -23,14 +24,9 @@ using System.Runtime.Serialization;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Management.Infrastructure;
-using Dbg = System.Management.Automation.Diagnostics;
#if !CORECLR
-using System.Data;
using System.DirectoryServices;
-#else
-// Use stubs for Serializable attribute and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
#endif
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
@@ -47,9 +43,7 @@ namespace System.Management.Automation
/// It is permitted to subclass
/// but there is no established scenario for doing this, nor has it been tested.
///
-#if !CORECLR // TypeDescriptionProvider is not supported in CoreCLR
[TypeDescriptionProvider(typeof(PSObjectTypeDescriptionProvider))]
-#endif
[Serializable]
public class PSObject : IFormattable, IComparable, ISerializable, IDynamicMetaObjectProvider
{
diff --git a/src/System.Management.Automation/engine/MshSecurityException.cs b/src/System.Management.Automation/engine/MshSecurityException.cs
index 00d7fe5ecd..482bd865a5 100644
--- a/src/System.Management.Automation/engine/MshSecurityException.cs
+++ b/src/System.Management.Automation/engine/MshSecurityException.cs
@@ -4,11 +4,6 @@ Copyright (c) Microsoft Corporation. All rights reserved.
using System.Runtime.Serialization;
-#if CORECLR
-// Use stubs for Serializable attribute and ISerializable related types
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace System.Management.Automation
{
///
diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs
index 7ae2d7f812..677a0a64e5 100644
--- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs
+++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs
@@ -20,11 +20,6 @@ using System.Diagnostics.CodeAnalysis;
using System.Collections.Concurrent;
using System.Collections.Generic;
-#if CORECLR
-// Use stubs for SerializableAttribute and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace System.Management.Automation
{
///
diff --git a/src/System.Management.Automation/engine/ProcessCodeMethods.cs b/src/System.Management.Automation/engine/ProcessCodeMethods.cs
index 7cc8fc4cf2..3cc5c2c67f 100644
--- a/src/System.Management.Automation/engine/ProcessCodeMethods.cs
+++ b/src/System.Management.Automation/engine/ProcessCodeMethods.cs
@@ -36,11 +36,10 @@ namespace Microsoft.PowerShell {
///
///
/// the parent process, or null if the parent is no longer running
- public static PSObject GetParentProcess(PSObject obj)
+ public static object GetParentProcess(PSObject obj)
{
var process = PSObject.Base(obj) as Process;
- var parent = process?.GetParent();
- return parent != null ? ClrFacade.AddProcessProperties(false, parent) : null;
+ return process?.GetParent();
}
///
diff --git a/src/System.Management.Automation/engine/PropertyAccessor.cs b/src/System.Management.Automation/engine/PropertyAccessor.cs
index aefbc868fb..3d03988e50 100644
--- a/src/System.Management.Automation/engine/PropertyAccessor.cs
+++ b/src/System.Management.Automation/engine/PropertyAccessor.cs
@@ -12,10 +12,6 @@ using System.Management.Automation;
using Microsoft.Win32;
#if CORECLR
-// Some APIs are missing from System.Environment. We use System.Management.Automation.Environment as a proxy type:
-// - for missing APIs, System.Management.Automation.Environment has extension implementation.
-// - for existing APIs, System.Management.Automation.Environment redirect the call to System.Environment.
-using Environment = System.Management.Automation.Environment;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
#endif
diff --git a/src/System.Management.Automation/engine/PseudoParameters.cs b/src/System.Management.Automation/engine/PseudoParameters.cs
index eb24051cbe..80c8572665 100644
--- a/src/System.Management.Automation/engine/PseudoParameters.cs
+++ b/src/System.Management.Automation/engine/PseudoParameters.cs
@@ -5,11 +5,6 @@ Copyright (c) Microsoft Corporation. All rights reserved.
using System.Collections.Generic;
using System.Collections.ObjectModel;
-#if CORECLR
-// Use stub for SerializableAttribute
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace System.Management.Automation
{
///
diff --git a/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs b/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs
index 16b4cbf9c2..de4220b2ea 100644
--- a/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs
+++ b/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs
@@ -6,11 +6,6 @@ using System.Collections.ObjectModel;
using System.Management.Automation.Provider;
using System.Security.AccessControl;
-#if CORECLR
-// Use stub for SystemException
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace System.Management.Automation
{
///
diff --git a/src/System.Management.Automation/engine/TypeTable.cs b/src/System.Management.Automation/engine/TypeTable.cs
index b0bbe18336..5c7d9c7614 100644
--- a/src/System.Management.Automation/engine/TypeTable.cs
+++ b/src/System.Management.Automation/engine/TypeTable.cs
@@ -18,12 +18,7 @@ using System.Runtime.Serialization;
using System.Security;
using System.Xml;
using Dbg = System.Diagnostics.Debug;
-#if !CORECLR
using System.Security.Permissions;
-#else
-// Use stub for SerializableAttribute, SecurityPermissionAttribute and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs
index f426f53941..37344380a8 100644
--- a/src/System.Management.Automation/engine/Utils.cs
+++ b/src/System.Management.Automation/engine/Utils.cs
@@ -26,7 +26,6 @@ using TypeTable = System.Management.Automation.Runspaces.TypeTable;
#if CORECLR
using System.Diagnostics;
using Microsoft.Win32.SafeHandles;
-using Microsoft.PowerShell.CoreClr.Stubs;
#else
using System.Security.Principal;
using PSUtils = System.Management.Automation.PsUtils;
@@ -318,7 +317,7 @@ namespace System.Management.Automation
{
baseDirectories.Add(appBase);
}
-
+#if !UNIX
// Win8: 454976
// Now add the two variations of System32
baseDirectories.Add(Environment.GetFolderPath(Environment.SpecialFolder.System));
@@ -327,7 +326,7 @@ namespace System.Management.Automation
{
baseDirectories.Add(systemX86);
}
-
+#endif
// And built-in modules
string progFileDir;
// TODO: #1184 will resolve this work-around
@@ -345,9 +344,6 @@ namespace System.Management.Automation
baseDirectories.Add(Path.Combine(progFileDir, "PowerShellGet"));
baseDirectories.Add(Path.Combine(progFileDir, "Pester"));
baseDirectories.Add(Path.Combine(progFileDir, "PSReadLine"));
-#if CORECLR
- baseDirectories.Add(Path.Combine(progFileDir, "Json.Net"));
-#endif // CORECLR
}
Interlocked.CompareExchange(ref s_productFolderDirectories, baseDirectories.ToArray(), null);
}
diff --git a/src/System.Management.Automation/engine/VariablePath.cs b/src/System.Management.Automation/engine/VariablePath.cs
index 5706252ab6..84150f2e05 100644
--- a/src/System.Management.Automation/engine/VariablePath.cs
+++ b/src/System.Management.Automation/engine/VariablePath.cs
@@ -5,11 +5,6 @@ Copyright (c) Microsoft Corporation. All rights reserved.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-#if CORECLR
-// Use stubs for SerializableAttribute
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace System.Management.Automation
{
[Flags]
diff --git a/src/System.Management.Automation/engine/hostifaces/Connection.cs b/src/System.Management.Automation/engine/hostifaces/Connection.cs
index 2c086626dc..40973e81f6 100644
--- a/src/System.Management.Automation/engine/hostifaces/Connection.cs
+++ b/src/System.Management.Automation/engine/hostifaces/Connection.cs
@@ -11,11 +11,6 @@ using System.Collections.Generic;
using System.Collections.ObjectModel;
using Dbg = System.Management.Automation.Diagnostics;
-#if CORECLR
-// Use stub for SerializableAttribute, NonSerializedAttribute and ISerializable related types
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace System.Management.Automation.Runspaces
{
#region Exceptions
@@ -225,7 +220,7 @@ namespace System.Management.Automation.Runspaces
ReuseThread = 2,
///
- /// Doesn’t create a new thread; the execution occurs on the
+ /// Doesn't create a new thread; the execution occurs on the
/// thread that calls Invoke.
///
///
diff --git a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs
index e73eeb5fcf..dfff02fb31 100644
--- a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs
+++ b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs
@@ -12,12 +12,6 @@ using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Security;
using System.Globalization;
-#if CORECLR
-// Some APIs are missing from System.Environment. We use System.Management.Automation.Environment as a proxy type:
-// - for missing APIs, System.Management.Automation.Environment has extension implementation.
-// - for existing APIs, System.Management.Automation.Environment redirect the call to System.Environment.
-using Environment = System.Management.Automation.Environment;
-#endif
namespace System.Management.Automation
{
diff --git a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs
index d9e295282c..46333bb3d2 100644
--- a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs
+++ b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs
@@ -18,12 +18,6 @@ using System.Diagnostics;
using System.Linq;
using Microsoft.PowerShell.Telemetry.Internal;
-
-#if CORECLR
-// Use stubs for SerializableAttribute and ISerializable related types
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
namespace System.Management.Automation.Runspaces
@@ -380,7 +374,7 @@ namespace System.Management.Automation.Runspaces
}
}
- private static string s_debugPreferenceCachePath = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "WindowsPowerShell"), "DebugPreference.clixml");
+ private static string s_debugPreferenceCachePath = Path.Combine(Path.Combine(Platform.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "WindowsPowerShell"), "DebugPreference.clixml");
private static object s_debugPreferenceLockObject = new object();
///
diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs
index fc3bc4f97e..d3cf16bc0a 100644
--- a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs
+++ b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs
@@ -976,7 +976,7 @@ namespace System.Management.Automation.Host
internal static string GetTranscriptPath()
{
- string baseDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
+ string baseDirectory = Platform.GetFolderPath(Environment.SpecialFolder.MyDocuments);
return GetTranscriptPath(baseDirectory, false);
}
@@ -984,14 +984,14 @@ namespace System.Management.Automation.Host
{
if (String.IsNullOrEmpty(baseDirectory))
{
- baseDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
+ baseDirectory = Platform.GetFolderPath(Environment.SpecialFolder.MyDocuments);
}
else
{
if (!Path.IsPathRooted(baseDirectory))
{
baseDirectory = Path.Combine(
- Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
+ Platform.GetFolderPath(Environment.SpecialFolder.MyDocuments),
baseDirectory);
}
}
diff --git a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs
index 129cfe0f25..982b19c426 100644
--- a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs
+++ b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs
@@ -11,11 +11,6 @@ using System.Reflection;
using System.Runtime.Serialization;
using Dbg = System.Management.Automation.Diagnostics;
-#if CORECLR
-// Use stub for SerializableAttribute and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace System.Management.Automation
{
#region DataAddedEventArgs
diff --git a/src/System.Management.Automation/engine/hostifaces/Pipeline.cs b/src/System.Management.Automation/engine/hostifaces/Pipeline.cs
index 34b35550cc..88e83f4d2e 100644
--- a/src/System.Management.Automation/engine/hostifaces/Pipeline.cs
+++ b/src/System.Management.Automation/engine/hostifaces/Pipeline.cs
@@ -9,11 +9,6 @@ using System.Runtime.Serialization;
using Dbg = System.Management.Automation.Diagnostics;
using System.Management.Automation.Internal;
-#if CORECLR
-// Use stub for SerializableAttribute, SystemException, ThreadAbortException and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace System.Management.Automation.Runspaces
{
#region Exceptions
diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs
index 996312acc4..b060fb353c 100644
--- a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs
+++ b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs
@@ -16,11 +16,6 @@ using Dbg = System.Management.Automation.Diagnostics;
using System.Diagnostics;
using Microsoft.Management.Infrastructure;
-#if CORECLR
-// Use stub for SerializableAttribute, NoSerializedAttribute, SystemException, ThreadAbortException and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
namespace System.Management.Automation
diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs b/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs
index 55947576c3..84ac1e4fbc 100644
--- a/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs
+++ b/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs
@@ -126,11 +126,7 @@ namespace System.Management.Automation.Runspaces
_startInfo.UserName = netCredential.UserName;
_startInfo.Domain = string.IsNullOrEmpty(netCredential.Domain) ? "." : netCredential.Domain;
-#if CORECLR
- _startInfo.PasswordInClearText = ClrFacade.ConvertSecureStringToString(credential.Password);
-#else
_startInfo.Password = credential.Password;
-#endif
}
Process = new Process { StartInfo = _startInfo, EnableRaisingEvents = true };
diff --git a/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs b/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs
index 10c3d54706..78dc8d777d 100644
--- a/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs
+++ b/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs
@@ -4,17 +4,11 @@ Copyright (c) Microsoft Corporation. All rights reserved.
using System.Threading;
using PSHost = System.Management.Automation.Host.PSHost;
-using Dbg = System.Management.Automation.Diagnostics;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces.Internal;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
-#if CORECLR
-// Use stub for SerializableAttribute, NonSerializedAttribute and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace System.Management.Automation.Runspaces
{
#region Exceptions
diff --git a/src/System.Management.Automation/engine/interpreter/Interpreter.cs b/src/System.Management.Automation/engine/interpreter/Interpreter.cs
index db44c2d9e6..83ba7d34c5 100644
--- a/src/System.Management.Automation/engine/interpreter/Interpreter.cs
+++ b/src/System.Management.Automation/engine/interpreter/Interpreter.cs
@@ -19,10 +19,6 @@ using System.Linq.Expressions;
using Microsoft.Scripting.Ast;
#endif
-#if CORECLR
-// Use stub for SpecialNameAttribute
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
using System.Runtime.CompilerServices;
using System.Threading;
@@ -117,7 +113,6 @@ namespace System.Management.Automation.Interpreter
}
}
-#if !CORECLR // Thread.Abort and ThreadAbortException are not in CoreCLR.
///
/// To get to the current AbortReason object on Thread.CurrentThread
/// we need to use ExceptionState property of any ThreadAbortException instance.
@@ -153,14 +148,6 @@ namespace System.Management.Automation.Interpreter
}
}
}
-#else
- ///
- /// A thread cannot be aborted in CoreCLR, as Thread.Abort() is not available in CoreCLR (neither is ThreadAbortException).
- /// So this method doesn't need to do anything when running with CoreCLR
- ///
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal static void AbortThreadIfRequested(InterpretedFrame frame, int targetLabelIndex) { }
-#endif
internal int ReturnAndRethrowLabelIndex
{
diff --git a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs
index 627602fee0..1db56c3409 100644
--- a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs
+++ b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs
@@ -19,10 +19,6 @@ using System.Linq;
using System.Linq.Expressions;
#endif
-#if CORECLR
-// Use stubs for Serializable attribute and SystemException
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
diff --git a/src/System.Management.Automation/engine/interpreter/LightLambdaClosureVisitor.cs b/src/System.Management.Automation/engine/interpreter/LightLambdaClosureVisitor.cs
index 5524a99245..4bd3dca13b 100644
--- a/src/System.Management.Automation/engine/interpreter/LightLambdaClosureVisitor.cs
+++ b/src/System.Management.Automation/engine/interpreter/LightLambdaClosureVisitor.cs
@@ -22,11 +22,6 @@ using System.Collections.Generic;
using System.Runtime.CompilerServices;
using AstUtils = System.Management.Automation.Interpreter.Utils;
-#if CORECLR
-// Use stub for IRuntimeVariables.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace System.Management.Automation.Interpreter
{
///
diff --git a/src/System.Management.Automation/engine/interpreter/RuntimeVariables.cs b/src/System.Management.Automation/engine/interpreter/RuntimeVariables.cs
index ef7dd7216c..b679311696 100644
--- a/src/System.Management.Automation/engine/interpreter/RuntimeVariables.cs
+++ b/src/System.Management.Automation/engine/interpreter/RuntimeVariables.cs
@@ -15,11 +15,6 @@
using System.Runtime.CompilerServices;
-#if CORECLR
-// Use stub for IRuntimeVariables.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace System.Management.Automation.Interpreter
{
internal sealed class RuntimeVariables : IRuntimeVariables
diff --git a/src/System.Management.Automation/engine/lang/parserutils.cs b/src/System.Management.Automation/engine/lang/parserutils.cs
index c2b71e2f0e..b8089c73f6 100644
--- a/src/System.Management.Automation/engine/lang/parserutils.cs
+++ b/src/System.Management.Automation/engine/lang/parserutils.cs
@@ -17,11 +17,6 @@ using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
using Dbg = System.Management.Automation.Diagnostics;
-#if CORECLR
-// Use stubs for SystemException and SerializationInfo
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
namespace System.Management.Automation
diff --git a/src/System.Management.Automation/engine/lang/scriptblock.cs b/src/System.Management.Automation/engine/lang/scriptblock.cs
index e04d32f594..3972dd7225 100644
--- a/src/System.Management.Automation/engine/lang/scriptblock.cs
+++ b/src/System.Management.Automation/engine/lang/scriptblock.cs
@@ -19,11 +19,6 @@ using System.Management.Automation.Runspaces;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.ExceptionServices;
-#if CORECLR
-// Use stubs for Serializable attribute and SerializationInfo
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace System.Management.Automation
{
///
diff --git a/src/System.Management.Automation/engine/parser/AstVisitor.cs b/src/System.Management.Automation/engine/parser/AstVisitor.cs
index 1b19c6392c..d0e0a9982b 100644
--- a/src/System.Management.Automation/engine/parser/AstVisitor.cs
+++ b/src/System.Management.Automation/engine/parser/AstVisitor.cs
@@ -265,7 +265,7 @@ namespace System.Management.Automation.Language
Type type = ast.TypeName.GetReflectionType();
if (type != null)
{
- Diagnostics.Assert(!(type.GetTypeInfo() is TypeBuilder), "ReflectionType can never be TypeBuilder");
+ Diagnostics.Assert(!(type is TypeBuilder), "ReflectionType can never be TypeBuilder");
}
return AstVisitAction.Continue;
}
diff --git a/src/System.Management.Automation/engine/parser/PSType.cs b/src/System.Management.Automation/engine/parser/PSType.cs
index 7144ad1530..78a8c1de07 100644
--- a/src/System.Management.Automation/engine/parser/PSType.cs
+++ b/src/System.Management.Automation/engine/parser/PSType.cs
@@ -274,7 +274,7 @@ namespace System.Management.Automation.Language
_typeBuilder = module.DefineType(typeName, Reflection.TypeAttributes.Class | Reflection.TypeAttributes.Public, baseClass, interfaces.ToArray());
_staticHelpersTypeBuilder = module.DefineType(string.Format(CultureInfo.InvariantCulture, "{0}_", typeName), Reflection.TypeAttributes.Class);
DefineCustomAttributes(_typeBuilder, typeDefinitionAst.Attributes, _parser, AttributeTargets.Class);
- _typeDefinitionAst.Type = _typeBuilder.AsType();
+ _typeDefinitionAst.Type = _typeBuilder;
_fieldsToInitForMemberFunctions = new List>();
_definedMethods = new Dictionary>>(StringComparer.OrdinalIgnoreCase);
@@ -582,7 +582,7 @@ namespace System.Management.Automation.Language
if (hasValidateAttributes)
{
- var typeToLoad = _typeBuilder.AsType();
+ Type typeToLoad = _typeBuilder;
setIlGen.Emit(OpCodes.Ldtoken, typeToLoad);
setIlGen.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle")); // load current Type on stack
setIlGen.Emit(OpCodes.Ldstr, propertyMemberAst.Name); // load name of Property
@@ -703,14 +703,14 @@ namespace System.Management.Automation.Language
private bool MethodExistsOnBaseClassAndFinal(string methodName, Type[] parameterTypes)
{
- TypeInfo baseType = _typeBuilder.BaseType.GetTypeInfo();
+ Type baseType = _typeBuilder.BaseType;
// If baseType is PS class, then method will be virtual, once we define it.
if (baseType is TypeBuilder)
{
return false;
}
- var mi = baseType.AsType().GetMethod(methodName, parameterTypes);
+ var mi = baseType.GetMethod(methodName, parameterTypes);
return mi != null && mi.IsFinal;
}
@@ -1159,16 +1159,16 @@ namespace System.Management.Automation.Language
foreach (var helper in defineTypeHelpers)
{
- Diagnostics.Assert(helper._typeDefinitionAst.Type.GetTypeInfo() is TypeBuilder, "Type should be the TypeBuilder");
+ Diagnostics.Assert(helper._typeDefinitionAst.Type is TypeBuilder, "Type should be the TypeBuilder");
bool runtimeTypeAssigned = false;
if (!helper.HasFatalErrors)
{
try
{
- var type = helper._typeBuilder.CreateTypeInfo().AsType();
+ var type = helper._typeBuilder.CreateType();
helper._typeDefinitionAst.Type = type;
runtimeTypeAssigned = true;
- var helperType = helper._staticHelpersTypeBuilder.CreateTypeInfo().AsType();
+ var helperType = helper._staticHelpersTypeBuilder.CreateType();
if (helper._fieldsToInitForMemberFunctions != null)
{
diff --git a/src/System.Management.Automation/engine/parser/TypeResolver.cs b/src/System.Management.Automation/engine/parser/TypeResolver.cs
index f46a5d2b6b..e484596a77 100644
--- a/src/System.Management.Automation/engine/parser/TypeResolver.cs
+++ b/src/System.Management.Automation/engine/parser/TypeResolver.cs
@@ -12,6 +12,7 @@ using System.Linq;
using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
using System.Net;
+using System.Net.Mail;
using System.Net.NetworkInformation;
using System.Numerics;
using System.Reflection;
@@ -25,7 +26,6 @@ using Microsoft.PowerShell.Commands;
#if !CORECLR
// System.DirectoryServices are not in CoreCLR
using System.DirectoryServices;
-using System.Net.Mail;
#endif
namespace System.Management.Automation.Language
@@ -803,14 +803,14 @@ namespace System.Management.Automation
{ typeof(X500DistinguishedName), new[] { "X500DistinguishedName" } },
{ typeof(XmlDocument), new[] { "xml" } },
{ typeof(CimSession), new[] { "CimSession" } },
+ { typeof(MailAddress), new[] { "mailaddress" } },
#if !CORECLR
// Following types not in CoreCLR
{ typeof(DirectoryEntry), new[] { "adsi" } },
{ typeof(DirectorySearcher), new[] { "adsisearcher" } },
{ typeof(ManagementClass), new[] { "wmiclass" } },
{ typeof(ManagementObject), new[] { "wmi" } },
- { typeof(ManagementObjectSearcher), new[] { "wmisearcher" } },
- { typeof(MailAddress), new[] { "mailaddress" } }
+ { typeof(ManagementObjectSearcher), new[] { "wmisearcher" } }
#endif
}
);
diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs
index 4488daf92e..f6a187bbb6 100644
--- a/src/System.Management.Automation/engine/parser/ast.cs
+++ b/src/System.Management.Automation/engine/parser/ast.cs
@@ -2624,7 +2624,7 @@ namespace System.Management.Automation.Language
// 2. TypeBuilder
// 3. RuntimeType
// We also allow wipe type (assign to null), because there could be errors.
- Diagnostics.Assert(value == null || _type == null || _type.GetTypeInfo() is TypeBuilder, "Type must be assigned only once to RuntimeType");
+ Diagnostics.Assert(value == null || _type == null || _type is TypeBuilder, "Type must be assigned only once to RuntimeType");
_type = value;
}
}
diff --git a/src/System.Management.Automation/engine/regex.cs b/src/System.Management.Automation/engine/regex.cs
index a2bb71565e..fbe58907a4 100644
--- a/src/System.Management.Automation/engine/regex.cs
+++ b/src/System.Management.Automation/engine/regex.cs
@@ -14,11 +14,6 @@ using System.Management.Automation.Internal;
using System.Runtime.Serialization;
using Dbg = System.Management.Automation.Diagnostics;
-#if CORECLR
-// Use stub for SerializableAttribute, NonSerializedAttribute and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace System.Management.Automation
{
///
@@ -733,12 +728,10 @@ namespace System.Management.Automation
{
RegexOptions regexOptions = RegexOptions.Singleline;
-#if !CORECLR // RegexOptions.Compiled is not in CoreCLR
if ((options & WildcardOptions.Compiled) != 0)
{
regexOptions |= RegexOptions.Compiled;
}
-#endif
if ((options & WildcardOptions.IgnoreCase) != 0)
{
regexOptions |= RegexOptions.IgnoreCase;
diff --git a/src/System.Management.Automation/engine/remoting/client/Job.cs b/src/System.Management.Automation/engine/remoting/client/Job.cs
index f923af6921..63686740cb 100644
--- a/src/System.Management.Automation/engine/remoting/client/Job.cs
+++ b/src/System.Management.Automation/engine/remoting/client/Job.cs
@@ -18,11 +18,6 @@ using System.Text;
using Microsoft.PowerShell.Commands;
using Dbg = System.Management.Automation.Diagnostics;
-#if CORECLR
-// Use stubs for SerializableAttribute, SystemException, SerializationInfo and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
// Stops compiler from warning about unknown warnings
#pragma warning disable 1634, 1691
diff --git a/src/System.Management.Automation/engine/remoting/client/Job2.cs b/src/System.Management.Automation/engine/remoting/client/Job2.cs
index e6b251df2a..43ec4f9b07 100644
--- a/src/System.Management.Automation/engine/remoting/client/Job2.cs
+++ b/src/System.Management.Automation/engine/remoting/client/Job2.cs
@@ -14,11 +14,6 @@ using System.Management.Automation.Tracing;
using System.Management.Automation.Language;
using Dbg = System.Management.Automation.Diagnostics;
-#if CORECLR
-// Use stubs for SerializableAttribute and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
// Stops compiler from warning about unknown warnings
#pragma warning disable 1634, 1691
diff --git a/src/System.Management.Automation/engine/remoting/client/JobManager.cs b/src/System.Management.Automation/engine/remoting/client/JobManager.cs
index 242c284f84..c27c7dd389 100644
--- a/src/System.Management.Automation/engine/remoting/client/JobManager.cs
+++ b/src/System.Management.Automation/engine/remoting/client/JobManager.cs
@@ -13,11 +13,6 @@ using System.Security;
using System.Threading;
using Dbg = System.Management.Automation.Diagnostics;
-#if CORECLR
-// Use stub for ThreadAbortException.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
// Stops compiler from warning about unknown warnings
#pragma warning disable 1634, 1691
diff --git a/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs b/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs
index 24aed35947..a972cd2793 100644
--- a/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs
+++ b/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs
@@ -10,11 +10,6 @@ using System.IO;
using System.Collections;
using System.Runtime.Serialization;
-#if CORECLR
-// Use stubs for SerializableAttribute, SerializationInfo and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
// Stops compiler from warning about unknown warnings
#pragma warning disable 1634, 1691
diff --git a/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs b/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs
index cc5841d236..cf52f20cc2 100644
--- a/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs
+++ b/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs
@@ -5,13 +5,7 @@
using System.Runtime.Serialization;
using System.Management.Automation.Remoting;
using System.Diagnostics.CodeAnalysis;
-
-#if CORECLR
-// Use stubs for SerializableAttribute, SecurityPermissionAttribute and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#else
using System.Security.Permissions;
-#endif
namespace System.Management.Automation.Runspaces
{
diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs
index 92e52ceefb..1407d11313 100644
--- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs
+++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs
@@ -27,13 +27,6 @@ using System.Security;
using System.Collections.Generic;
using System.Security.Principal;
-#if CORECLR
-// Some APIs are missing from System.Environment. We use System.Management.Automation.Environment as a proxy type:
-// - for missing APIs, System.Management.Automation.Environment has extension implementation.
-// - for existing APIs, System.Management.Automation.Environment redirect the call to System.Environment.
-using Environment = System.Management.Automation.Environment;
-#endif
-
namespace Microsoft.PowerShell.Commands
{
#region Register-PSSessionConfiguration cmdlet
diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs
index 503a17e5b3..b9bbb71a7a 100644
--- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs
+++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs
@@ -10,13 +10,6 @@ using System.Diagnostics;
using System.Management.Automation.Internal;
using System.Globalization;
-#if CORECLR
-// Some APIs are missing from System.Environment. We use System.Management.Automation.Environment as a proxy type:
-// - for missing APIs, System.Management.Automation.Environment has extension implementation.
-// - for existing APIs, System.Management.Automation.Environment redirect the call to System.Environment.
-using Environment = System.Management.Automation.Environment;
-#endif
-
namespace Microsoft.PowerShell.Commands
{
///
diff --git a/src/System.Management.Automation/engine/remoting/common/PSSessionConfigurationTypeOption.cs b/src/System.Management.Automation/engine/remoting/common/PSSessionConfigurationTypeOption.cs
index ed1c8bb784..179748f4c3 100644
--- a/src/System.Management.Automation/engine/remoting/common/PSSessionConfigurationTypeOption.cs
+++ b/src/System.Management.Automation/engine/remoting/common/PSSessionConfigurationTypeOption.cs
@@ -5,11 +5,6 @@
using System.Collections;
using System.Management.Automation.Runspaces;
-#if CORECLR
-// Use stub for ICloneable type.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace System.Management.Automation
{
///
diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs
index 45041208c6..0cc4b790aa 100644
--- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs
+++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs
@@ -10,11 +10,6 @@ using System.Text;
using System.Threading;
using Dbg = System.Diagnostics.Debug;
-#if CORECLR
-// Use stubs for SerializableAttribute.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace System.Management.Automation.Remoting
{
[SerializableAttribute]
diff --git a/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs b/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs
index 56e24c02e5..5e0f2c0977 100644
--- a/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs
+++ b/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs
@@ -4,13 +4,7 @@
using System.Runtime.Serialization;
using System.Management.Automation.Internal;
-
-#if CORECLR
-// Use stubs for SerializableAttribute, SecurityPermissionAttribute and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#else
using System.Security.Permissions;
-#endif
namespace System.Management.Automation.Remoting
{
diff --git a/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs b/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs
index 04e7693683..e47b118499 100644
--- a/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs
+++ b/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs
@@ -13,11 +13,6 @@ using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
using Microsoft.PowerShell;
-#if CORECLR
-// Use stub for SerializableAttribute, SerializationInfo and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace System.Management.Automation.Remoting
{
///
diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs
index dda67f0320..a262751b79 100644
--- a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs
+++ b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs
@@ -650,7 +650,7 @@ namespace System.Management.Automation
// on Remoting in PowerShell engine
try
{
- string personalfolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
+ string personalfolder = Platform.GetFolderPath(Environment.SpecialFolder.MyDocuments);
args.Runspace.ExecutionContext.EngineSessionState.SetLocation(personalfolder);
}
catch (Exception)
diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs
index 4b39654e71..e181075ef3 100644
--- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs
+++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs
@@ -18,11 +18,6 @@ using System.Text;
using System.Threading.Tasks;
using Microsoft.PowerShell.Telemetry.Internal;
-#if CORECLR
-// Use stub for Serializable attribute and ISerializable related types
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace System.Management.Automation
{
internal enum CompileInterpretChoice
diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs
index c335e97fde..b1a223bf00 100644
--- a/src/System.Management.Automation/engine/serialization.cs
+++ b/src/System.Management.Automation/engine/serialization.cs
@@ -14,6 +14,7 @@ using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Tracing;
+using System.Net.Mail;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
@@ -25,13 +26,6 @@ using Microsoft.PowerShell.Commands;
using Dbg = System.Management.Automation.Diagnostics;
using System.Management.Automation.Remoting;
-#if CORECLR
-// Use stubs for SerializableAttribute and ISerializable related types
-using Microsoft.PowerShell.CoreClr.Stubs;
-#else
-using MailAddress = System.Net.Mail.MailAddress;
-#endif
-
namespace System.Management.Automation
{
[Flags]
diff --git a/src/System.Management.Automation/help/CabinetNativeApi.cs b/src/System.Management.Automation/help/CabinetNativeApi.cs
index 17172592ab..1078d7a895 100644
--- a/src/System.Management.Automation/help/CabinetNativeApi.cs
+++ b/src/System.Management.Automation/help/CabinetNativeApi.cs
@@ -6,10 +6,6 @@ using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
-#if CORECLR
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace System.Management.Automation.Internal
{
internal class CabinetExtractor : ICabinetExtractor
diff --git a/src/System.Management.Automation/help/HelpCategoryInvalidException.cs b/src/System.Management.Automation/help/HelpCategoryInvalidException.cs
index c4cef89c69..ec24e0804f 100644
--- a/src/System.Management.Automation/help/HelpCategoryInvalidException.cs
+++ b/src/System.Management.Automation/help/HelpCategoryInvalidException.cs
@@ -9,13 +9,7 @@ using System;
using System.Management.Automation;
using System.Runtime.Serialization;
using System.Reflection;
-
-#if CORECLR
-// Use stub for SerializableAttribute, SerializationInfo and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#else
using System.Security.Permissions;
-#endif
namespace Microsoft.PowerShell.Commands
{
@@ -109,7 +103,7 @@ namespace Microsoft.PowerShell.Commands
return base.Message;
}
}
-#if !CORECLR
+
#region Serialization
///
/// Initializes a new instance of the HelpCategoryInvalidException class.
@@ -144,7 +138,6 @@ namespace Microsoft.PowerShell.Commands
}
#endregion Serialization
-#endif
}
}
diff --git a/src/System.Management.Automation/help/HelpNotFoundException.cs b/src/System.Management.Automation/help/HelpNotFoundException.cs
index 34bbcc3f44..aec33ac03a 100644
--- a/src/System.Management.Automation/help/HelpNotFoundException.cs
+++ b/src/System.Management.Automation/help/HelpNotFoundException.cs
@@ -9,13 +9,7 @@ using System;
using System.Management.Automation;
using System.Runtime.Serialization;
using System.Reflection;
-
-#if CORECLR
-// Use stub for SerializableAttribute, SerializationInfo and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#else
using System.Security.Permissions;
-#endif
namespace Microsoft.PowerShell.Commands
{
@@ -115,7 +109,6 @@ namespace Microsoft.PowerShell.Commands
}
}
-#if !CORECLR
#region Serialization
///
@@ -151,7 +144,6 @@ namespace Microsoft.PowerShell.Commands
}
#endregion Serialization
-#endif
}
}
diff --git a/src/System.Management.Automation/help/UpdatableHelpSystem.cs b/src/System.Management.Automation/help/UpdatableHelpSystem.cs
index 2243451ae4..2b90450b27 100644
--- a/src/System.Management.Automation/help/UpdatableHelpSystem.cs
+++ b/src/System.Management.Automation/help/UpdatableHelpSystem.cs
@@ -21,8 +21,6 @@ using System.Security;
using System.IO.Compression;
using System.Net.Http;
using System.Threading.Tasks;
-// Use stub for SerializableAttribute, SerializationInfo and ISerializable related types. WebClient.
-using Microsoft.PowerShell.CoreClr.Stubs;
#else
using System.Xml.Schema;
#endif
diff --git a/src/System.Management.Automation/minishell/api/RunspaceConfigurationAttributeException.cs b/src/System.Management.Automation/minishell/api/RunspaceConfigurationAttributeException.cs
index 15559c1b9c..01231c44cf 100644
--- a/src/System.Management.Automation/minishell/api/RunspaceConfigurationAttributeException.cs
+++ b/src/System.Management.Automation/minishell/api/RunspaceConfigurationAttributeException.cs
@@ -4,13 +4,7 @@ Copyright (c) Microsoft Corporation. All rights reserved.
using System.Runtime.Serialization;
using System.Reflection;
-
-#if CORECLR
-// Use stubs for SystemException, SerializationInfo and SecurityPermissionAttribute
-using Microsoft.PowerShell.CoreClr.Stubs;
-#else
using System.Security.Permissions;
-#endif
namespace System.Management.Automation.Runspaces
{
diff --git a/src/System.Management.Automation/minishell/api/RunspaceConfigurationTypeException.cs b/src/System.Management.Automation/minishell/api/RunspaceConfigurationTypeException.cs
index 9ee67e0fc4..d5b7996f1c 100644
--- a/src/System.Management.Automation/minishell/api/RunspaceConfigurationTypeException.cs
+++ b/src/System.Management.Automation/minishell/api/RunspaceConfigurationTypeException.cs
@@ -4,13 +4,7 @@ Copyright (c) Microsoft Corporation. All rights reserved.
using System.Runtime.Serialization;
using System.Reflection;
-
-#if CORECLR
-// Use stubs for SystemException, SerializationInfo and SecurityPermissionAttribute
-using Microsoft.PowerShell.CoreClr.Stubs;
-#else
using System.Security.Permissions;
-#endif
namespace System.Management.Automation.Runspaces
{
diff --git a/src/System.Management.Automation/namespaces/Buffer.cs b/src/System.Management.Automation/namespaces/Buffer.cs
index 397d5382fe..81a4de05b0 100644
--- a/src/System.Management.Automation/namespaces/Buffer.cs
+++ b/src/System.Management.Automation/namespaces/Buffer.cs
@@ -5,18 +5,12 @@
//
using BCLDebug = System.Diagnostics.Debug;
+using System.Runtime.ConstrainedExecution;
namespace Microsoft.PowerShell.Commands.Internal
{
//Only contains static methods. Does not require serialization
-#if CORECLR
- // Use stub for ReliabilityContractAttribute
- using Microsoft.PowerShell.CoreClr.Stubs;
-#else
- using System.Runtime.ConstrainedExecution;
-#endif
-
[System.Runtime.InteropServices.ComVisible(true)]
internal static class Buffer
{
diff --git a/src/System.Management.Automation/namespaces/EnvironmentProvider.cs b/src/System.Management.Automation/namespaces/EnvironmentProvider.cs
index 85376fe0da..f9af5240e7 100644
--- a/src/System.Management.Automation/namespaces/EnvironmentProvider.cs
+++ b/src/System.Management.Automation/namespaces/EnvironmentProvider.cs
@@ -11,13 +11,6 @@ using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Provider;
-#if CORECLR
-// Some APIs are missing from System.Environment. We use System.Management.Automation.Environment as a proxy type:
-// - for missing APIs, System.Management.Automation.Environment has extension implementation.
-// - for existing APIs, System.Management.Automation.Environment redirect the call to System.Environment.
-using Environment = System.Management.Automation.Environment;
-#endif
-
namespace Microsoft.PowerShell.Commands
{
///
diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs
index 213a7e66ac..481048fd74 100644
--- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs
+++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs
@@ -25,9 +25,8 @@ using System.Runtime.InteropServices;
using System.Management.Automation.Runspaces;
#if CORECLR
-// Use stubs for SafeHandleZeroOrMinusOneIsInvalid and SecurityZone
+// Use stubs for SecurityZone
using Microsoft.PowerShell.CoreClr.Stubs;
-using Environment = System.Management.Automation.Environment;
#endif
namespace Microsoft.PowerShell.Commands
@@ -266,9 +265,7 @@ namespace Microsoft.PowerShell.Commands
string.IsNullOrEmpty(this.ProviderInfo.HelpFile) ? "" : this.ProviderInfo.HelpFile);
XmlReaderSettings settings = new XmlReaderSettings();
-#if !CORECLR // No XmlReaderSettings.XmlResolver in CoreCLR
settings.XmlResolver = null;
-#endif
reader = XmlReader.Create(fullHelpPath, settings);
document.Load(reader);
diff --git a/src/System.Management.Automation/namespaces/SafeRegistryHandle.cs b/src/System.Management.Automation/namespaces/SafeRegistryHandle.cs
index b769fea05b..4a0f4f706d 100644
--- a/src/System.Management.Automation/namespaces/SafeRegistryHandle.cs
+++ b/src/System.Management.Automation/namespaces/SafeRegistryHandle.cs
@@ -18,14 +18,8 @@ using System.Security;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Microsoft.Win32.SafeHandles;
-
-#if CORECLR
-// Use stubs for SafeHandleZeroOrMinusOneIsInvalid and ReliabilityContractAttribute
-using Microsoft.PowerShell.CoreClr.Stubs;
-#else
using System.Runtime.ConstrainedExecution;
using System.Security.Permissions;
-#endif
namespace Microsoft.PowerShell.Commands.Internal
{
@@ -52,13 +46,9 @@ namespace Microsoft.PowerShell.Commands.Internal
protected override bool ReleaseHandle()
{
-#if UNIX
- return true;
-#else
// Returns a Win32 error code, 0 for success
int r = RegCloseKey(handle);
return r == 0;
-#endif
}
}
}
diff --git a/src/System.Management.Automation/namespaces/Win32Native.cs b/src/System.Management.Automation/namespaces/Win32Native.cs
index 13d05d5de3..d8352f5168 100644
--- a/src/System.Management.Automation/namespaces/Win32Native.cs
+++ b/src/System.Management.Automation/namespaces/Win32Native.cs
@@ -21,18 +21,12 @@ namespace Microsoft.PowerShell.Commands.Internal
using System.Management.Automation;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
+ using System.Runtime.ConstrainedExecution;
using BOOL = System.Int32;
using DWORD = System.UInt32;
using ULONG = System.UInt32;
-#if CORECLR
- // Use stubs for SuppressUnmanagedCodeSecurityAttribute and ReliabilityContractAttribute
- using Microsoft.PowerShell.CoreClr.Stubs;
-#else
- using System.Runtime.ConstrainedExecution;
-#endif
-
/**
* Win32 encapsulation for MSCORLIB.
*/
@@ -897,26 +891,4 @@ namespace Microsoft.PowerShell.Commands.Internal
#endif
}
-
-
- internal sealed class SafeProcessHandle : SafeHandle
- {
- internal SafeProcessHandle() : base(IntPtr.Zero, true) { }
-
- internal SafeProcessHandle(IntPtr existingHandle)
- : base(IntPtr.Zero, true)
- {
- SetHandle(existingHandle);
- }
-
- protected override bool ReleaseHandle()
- {
- return base.IsClosed ? true : Win32Native.CloseHandle(base.handle);
- }
-
- public override bool IsInvalid
- {
- get { return handle == IntPtr.Zero || handle == new IntPtr(-1); }
- }
- }
}
diff --git a/src/System.Management.Automation/security/Authenticode.cs b/src/System.Management.Automation/security/Authenticode.cs
index c10bd45ed4..e8ed6e1dc7 100644
--- a/src/System.Management.Automation/security/Authenticode.cs
+++ b/src/System.Management.Automation/security/Authenticode.cs
@@ -13,11 +13,6 @@ using System.Management.Automation.Internal;
using System.Management.Automation.Security;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
-#if CORECLR
-// Use stub for
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
using DWORD = System.UInt32;
namespace System.Management.Automation
diff --git a/src/System.Management.Automation/security/SecurityManager.cs b/src/System.Management.Automation/security/SecurityManager.cs
index eb2eacb3dd..9c035c7531 100644
--- a/src/System.Management.Automation/security/SecurityManager.cs
+++ b/src/System.Management.Automation/security/SecurityManager.cs
@@ -17,7 +17,6 @@ using System.Security.Cryptography.X509Certificates;
#if CORECLR
// Use stub for SecurityZone
using Microsoft.PowerShell.CoreClr.Stubs;
-using Environment = System.Management.Automation.Environment;
#endif
namespace Microsoft.PowerShell
@@ -329,8 +328,8 @@ namespace Microsoft.PowerShell
if (String.Equals(fi.Extension, ".ps1xml", StringComparison.OrdinalIgnoreCase))
{
string[] trustedDirectories = new string[]
- { Environment.GetFolderPath(Environment.SpecialFolder.System),
- Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)
+ { Platform.GetFolderPath(Environment.SpecialFolder.System),
+ Platform.GetFolderPath(Environment.SpecialFolder.ProgramFiles)
};
foreach (string trustedDirectory in trustedDirectories)
diff --git a/src/System.Management.Automation/security/SecuritySupport.cs b/src/System.Management.Automation/security/SecuritySupport.cs
index fe6f53daab..9f0bbecada 100644
--- a/src/System.Management.Automation/security/SecuritySupport.cs
+++ b/src/System.Management.Automation/security/SecuritySupport.cs
@@ -10,7 +10,7 @@ using System.Diagnostics.CodeAnalysis;
using System.IO;
using Microsoft.PowerShell;
using Microsoft.PowerShell.Commands;
-using System.Management.Automation.Security;
+using Microsoft.Win32;
using System.Management.Automation.Internal;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
@@ -20,11 +20,7 @@ using System.Globalization;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.InteropServices;
-
-using Microsoft.Win32;
-
using DWORD = System.UInt32;
-using BOOL = System.UInt32;
namespace Microsoft.PowerShell
{
@@ -1080,7 +1076,7 @@ namespace System.Management.Automation
StringBuilder output = new StringBuilder();
output.AppendLine(BEGIN_CMS_SIGIL);
- string encodedString = ClrFacade.ToBase64StringWithLineBreaks(bytes);
+ string encodedString = Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks);
output.AppendLine(encodedString);
output.Append(END_CMS_SIGIL);
diff --git a/src/System.Management.Automation/security/nativeMethods.cs b/src/System.Management.Automation/security/nativeMethods.cs
index 6285563b1e..0c26ee1714 100644
--- a/src/System.Management.Automation/security/nativeMethods.cs
+++ b/src/System.Management.Automation/security/nativeMethods.cs
@@ -10,14 +10,9 @@ Copyright (c) Microsoft Corporation. All rights reserved.
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Management.Automation.Internal;
+using System.Runtime.ConstrainedExecution;
using DWORD = System.UInt32;
using BOOL = System.UInt32;
-#if CORECLR
-// Use stub for ReliabilityContractAttribute
-using Microsoft.PowerShell.CoreClr.Stubs;
-#else
-using System.Runtime.ConstrainedExecution;
-#endif
namespace System.Management.Automation.Security
{
diff --git a/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs b/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs
index d7353d5301..7eeb95dd96 100644
--- a/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs
+++ b/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs
@@ -5,13 +5,7 @@ Copyright (c) Microsoft Corporation. All rights reserved.
using System.Runtime.Serialization;
using System.Text;
using System.Collections.ObjectModel;
-
-#if CORECLR
-// Use stubs for SystemException, SerializationInfo and SecurityPermissionAttribute
-using Microsoft.PowerShell.CoreClr.Stubs;
-#else
using System.Security.Permissions;
-#endif
namespace System.Management.Automation.Runspaces
{
diff --git a/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs b/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs
index 4f2c9c52c1..a156a96ae7 100644
--- a/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs
+++ b/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs
@@ -4,13 +4,7 @@ Copyright (c) Microsoft Corporation. All rights reserved.
using System.Runtime.Serialization;
using System.Reflection;
-
-#if CORECLR
-// Use stubs for SystemException, SerializationInfo and SecurityPermissionAttribute
-using Microsoft.PowerShell.CoreClr.Stubs;
-#else
using System.Security.Permissions;
-#endif
namespace System.Management.Automation.Runspaces
{
diff --git a/src/System.Management.Automation/utils/ClrFacade.cs b/src/System.Management.Automation/utils/ClrFacade.cs
index 6a14967bba..d037485bc4 100644
--- a/src/System.Management.Automation/utils/ClrFacade.cs
+++ b/src/System.Management.Automation/utils/ClrFacade.cs
@@ -28,10 +28,6 @@ using System.Text.RegularExpressions;
#else
using System.Runtime.Serialization; /* used in facade API 'GetUninitializedObject' */
#endif
-#if !UNIX
-using System.ComponentModel; /* used in the facade API RetrieveProcessUserName */
-using Microsoft.PowerShell.Commands.Internal; /* used in the facade APIs related to 'SafeProcessHandle' and 'RetreiveUserName' */
-#endif
namespace System.Management.Automation
{
@@ -47,24 +43,6 @@ namespace System.Management.Automation
///
internal static readonly char FIRST_CHAR_PSASSEMBLY_MARK = (char)0x29f9;
- #region Type
-
- ///
- /// Facade for Type.GetMember(string, BindingFlags) to return multiple matched Public Static methods
- ///
- internal static MemberInfo[] GetMethods(Type targetType, string methodName)
- {
-#if CORECLR
- const BindingFlags flagsToUse = BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static;
- return targetType.GetMethods(methodName, flagsToUse);
-#else
- const BindingFlags flagsToUse = BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod;
- return targetType.GetMember(methodName, flagsToUse);
-#endif
- }
-
- #endregion Type
-
#region Process
///
@@ -117,160 +95,6 @@ namespace System.Management.Automation
#endif
}
-#region Facade for AddProcessProperties
-
- ///
- /// Ensures the 'UserName' and 'HandleCount' Properties exist the Process object.
- ///
- ///
- ///
- ///
- internal static PSObject AddProcessProperties(bool includeUserName, Process process)
- {
- PSObject processAsPsobj = includeUserName ? AddUserNameToProcess(process) : PSObject.AsPSObject(process);
-#if CORECLR
- // In CoreCLR, the System.Diagnostics.Process.HandleCount property does not exist.
- // I am adding a note property HandleCount and temporarily setting it to zero.
- // This issue will be fix for RTM and it is tracked by 5024994: Get-process does not populate the Handles field.
- PSMemberInfo hasHandleCount = processAsPsobj.Properties["HandleCount"];
- if (hasHandleCount == null)
- {
- PSNoteProperty noteProperty = new PSNoteProperty("HandleCount", 0);
- processAsPsobj.Properties.Add(noteProperty, true);
- processAsPsobj.TypeNames.Insert(0, "System.Diagnostics.Process#HandleCount");
- }
-#endif
- return processAsPsobj;
- }
- ///
- /// New PSTypeName added to the process object
- ///
- private const string TypeNameForProcessWithUserName = "System.Diagnostics.Process#IncludeUserName";
-
- ///
- /// Add the 'UserName' NoteProperty to the Process object
- ///
- ///
- ///
- private static PSObject AddUserNameToProcess(Process process)
- {
- // Return null if we failed to get the owner information
- string userName = ClrFacade.RetrieveProcessUserName(process);
-
- PSObject processAsPsobj = PSObject.AsPSObject(process);
- PSNoteProperty noteProperty = new PSNoteProperty("UserName", userName);
-
- processAsPsobj.Properties.Add(noteProperty, true);
- processAsPsobj.TypeNames.Insert(0, TypeNameForProcessWithUserName);
-
- return processAsPsobj;
- }
-
-
- ///
- /// Retrieve the UserName through PInvoke
- ///
- ///
- ///
- private static string RetrieveProcessUserName(Process process)
- {
- string userName = null;
-#if UNIX
- userName = Platform.NonWindowsGetUserFromPid(process.Id);
-#else
- IntPtr tokenUserInfo = IntPtr.Zero;
- IntPtr processTokenHandler = IntPtr.Zero;
-
- const uint TOKEN_QUERY = 0x0008;
-
- try
- {
- do
- {
- int error;
- if (!Win32Native.OpenProcessToken(ClrFacade.GetSafeProcessHandle(process), TOKEN_QUERY, out processTokenHandler)) { break; }
-
- // Set the default length to be 256, so it will be sufficient for most cases
- int tokenInfoLength = 256;
- tokenUserInfo = Marshal.AllocHGlobal(tokenInfoLength);
- if (!Win32Native.GetTokenInformation(processTokenHandler, Win32Native.TOKEN_INFORMATION_CLASS.TokenUser, tokenUserInfo, tokenInfoLength, out tokenInfoLength))
- {
- error = Marshal.GetLastWin32Error();
- if (error == Win32Native.ERROR_INSUFFICIENT_BUFFER)
- {
- Marshal.FreeHGlobal(tokenUserInfo);
- tokenUserInfo = Marshal.AllocHGlobal(tokenInfoLength);
-
- if (!Win32Native.GetTokenInformation(processTokenHandler, Win32Native.TOKEN_INFORMATION_CLASS.TokenUser, tokenUserInfo, tokenInfoLength, out tokenInfoLength)) { break; }
- }
- else
- {
- break;
- }
- }
-
- var tokenUser = ClrFacade.PtrToStructure(tokenUserInfo);
-
- // Set the default length to be 256, so it will be sufficient for most cases
- int userNameLength = 256, domainNameLength = 256;
- var userNameStr = new StringBuilder(userNameLength);
- var domainNameStr = new StringBuilder(domainNameLength);
- Win32Native.SID_NAME_USE accountType;
-
- if (!Win32Native.LookupAccountSid(null, tokenUser.User.Sid, userNameStr, ref userNameLength, domainNameStr, ref domainNameLength, out accountType))
- {
- error = Marshal.GetLastWin32Error();
- if (error == Win32Native.ERROR_INSUFFICIENT_BUFFER)
- {
- userNameStr.EnsureCapacity(userNameLength);
- domainNameStr.EnsureCapacity(domainNameLength);
-
- if (!Win32Native.LookupAccountSid(null, tokenUser.User.Sid, userNameStr, ref userNameLength, domainNameStr, ref domainNameLength, out accountType)) { break; }
- }
- else
- {
- break;
- }
- }
-
- userName = domainNameStr + "\\" + userNameStr;
- } while (false);
- }
- catch (NotSupportedException)
- {
- // The Process not started yet, or it's a process from a remote machine
- }
- catch (InvalidOperationException)
- {
- // The Process has exited, Process.Handle will raise this exception
- }
- catch (Win32Exception)
- {
- // We might get an AccessDenied error
- }
- catch (Exception)
- {
- // I don't expect to get other exceptions,
- }
- finally
- {
- if (tokenUserInfo != IntPtr.Zero)
- {
- Marshal.FreeHGlobal(tokenUserInfo);
- }
-
- if (processTokenHandler != IntPtr.Zero)
- {
- Win32Native.CloseHandle(processTokenHandler);
- }
- }
-
-#endif
- return userName;
- }
-
-#endregion
-
#if CORECLR
///
/// Facade for ProcessStartInfo.Environment
@@ -288,32 +112,6 @@ namespace System.Management.Automation
return startInfo.EnvironmentVariables;
}
#endif
-#if CORECLR
- ///
- /// Converts the given SecureString to a string
- ///
- ///
- ///
- internal static string ConvertSecureStringToString(SecureString secureString)
- {
- string passwordInClearText;
- IntPtr unmanagedMemory = IntPtr.Zero;
-
- try
- {
- unmanagedMemory = SecureStringToCoTaskMemUnicode(secureString);
- passwordInClearText = Marshal.PtrToStringUni(unmanagedMemory);
- }
- finally
- {
- if (unmanagedMemory != IntPtr.Zero)
- {
- Marshal.ZeroFreeCoTaskMemUnicode(unmanagedMemory);
- }
- }
- return passwordInClearText;
- }
-#endif
#endregion Process
@@ -838,36 +636,6 @@ namespace System.Management.Automation
#region Misc
- ///
- /// Facade for Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks)
- /// Inserts line breaks after every 76 characters in the string representation.
- ///
- internal static string ToBase64StringWithLineBreaks(byte[] bytes)
- {
-#if CORECLR
- // Inserts line breaks after every 76 characters in the string representation.
- string encodedRawString = Convert.ToBase64String(bytes);
- if (encodedRawString.Length <= 76)
- return encodedRawString;
-
- StringBuilder builder = new StringBuilder(encodedRawString.Length);
- int index = 0, remainingLen = encodedRawString.Length;
- while (remainingLen > 76)
- {
- builder.Append(encodedRawString, index, 76);
- builder.Append(System.Environment.NewLine);
-
- index += 76;
- remainingLen -= 76;
- }
-
- builder.Append(encodedRawString, index, remainingLen);
- return builder.ToString();
-#else
- return Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks);
-#endif
- }
-
///
/// Facade for RemotingServices.IsTransparentProxy(object)
///
diff --git a/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs b/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs
index b77bd444e8..a1e3fce7e3 100644
--- a/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs
+++ b/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs
@@ -6,13 +6,7 @@ using System.Runtime.Serialization;
using System.Text;
using System.Collections.ObjectModel;
using System.Management.Automation.Internal;
-
-#if !CORECLR
using System.Security.Permissions;
-#else
-// Use stub for SerializableAttribute, SecurityPermissionAttribute and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
namespace System.Management.Automation
{
diff --git a/src/System.Management.Automation/utils/CommandProcessorExceptions.cs b/src/System.Management.Automation/utils/CommandProcessorExceptions.cs
index 4a3096268d..40385b3c1f 100644
--- a/src/System.Management.Automation/utils/CommandProcessorExceptions.cs
+++ b/src/System.Management.Automation/utils/CommandProcessorExceptions.cs
@@ -4,11 +4,6 @@ Copyright (c) Microsoft Corporation. All rights reserved.
using System.Runtime.Serialization;
-#if CORECLR
-// Use stub for SerializableAttribute and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace System.Management.Automation
{
///
diff --git a/src/System.Management.Automation/utils/CryptoUtils.cs b/src/System.Management.Automation/utils/CryptoUtils.cs
index 44e07dfcaa..f3bcb747a6 100644
--- a/src/System.Management.Automation/utils/CryptoUtils.cs
+++ b/src/System.Management.Automation/utils/CryptoUtils.cs
@@ -7,18 +7,12 @@ using System.Security;
using System.Threading;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
+using System.Runtime.ConstrainedExecution;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics.CodeAnalysis;
using Dbg = System.Management.Automation.Diagnostics;
using System.Management.Automation.Remoting;
-#if CORECLR
-// Use stubs for SerializableAttribute, SecurityPermissionAttribute, ReliabilityContractAttribute and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#else
-using System.Runtime.ConstrainedExecution;
-#endif
-
namespace System.Management.Automation.Internal
{
///
@@ -380,7 +374,6 @@ namespace System.Management.Automation.Internal
_errorCode = unchecked((uint)-1);
}
-#if !CORECLR
///
/// Constructor which has type specific serialization logic
///
@@ -395,12 +388,10 @@ namespace System.Management.Automation.Internal
_errorCode = unchecked(0xFFFFFFF);
Dbg.Assert(false, "type-specific serialization logic not implemented and so this constructor should not be called");
}
-#endif
+
#endregion Constructors
#region ISerializable Overrides
-
-#if !CORECLR
///
/// Returns base implementation
///
@@ -410,7 +401,6 @@ namespace System.Management.Automation.Internal
{
base.GetObjectData(info, context);
}
-#endif
#endregion ISerializable Overrides
}
diff --git a/src/System.Management.Automation/utils/ExecutionExceptions.cs b/src/System.Management.Automation/utils/ExecutionExceptions.cs
index 0586a69c19..c1e276cb51 100644
--- a/src/System.Management.Automation/utils/ExecutionExceptions.cs
+++ b/src/System.Management.Automation/utils/ExecutionExceptions.cs
@@ -9,13 +9,7 @@ Copyright (c) Microsoft Corporation. All rights reserved.
using System.Runtime.Serialization;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation.Internal;
-
-#if !CORECLR
using System.Security.Permissions;
-#else
-// Use stub for SerializableAttribute, SecurityPermissionAttribute and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
diff --git a/src/System.Management.Automation/utils/ExtensionMethods.cs b/src/System.Management.Automation/utils/ExtensionMethods.cs
index fcc4c4c7ac..ab911554ad 100644
--- a/src/System.Management.Automation/utils/ExtensionMethods.cs
+++ b/src/System.Management.Automation/utils/ExtensionMethods.cs
@@ -82,7 +82,6 @@ namespace System.Management.Automation
/// Type.EmptyTypes is not in CoreCLR. Use this one to replace it.
///
internal static Type[] EmptyTypes = new Type[0];
- private static readonly Type s_comObjectType = Type.GetType("System.__ComObject");
///
/// Check does the type have an instance default constructor with visibility that allows calling it from subclass.
@@ -133,8 +132,6 @@ namespace System.Management.Automation
{
#if UNIX
return false;
-#elif CORECLR // Type.IsComObject(Type) is not in CoreCLR
- return s_comObjectType.IsAssignableFrom(type);
#else
return type.IsCOMObject;
#endif
@@ -143,11 +140,7 @@ namespace System.Management.Automation
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static TypeCode GetTypeCode(this Type type)
{
-#if CORECLR // Type.GetTypeCode(Type) is not in CoreCLR
- return GetTypeCodeInCoreClr(type);
-#else
return Type.GetTypeCode(type);
-#endif
}
internal static IEnumerable GetCustomAttributes(this Type type, bool inherit)
diff --git a/src/System.Management.Automation/utils/HostInterfacesExceptions.cs b/src/System.Management.Automation/utils/HostInterfacesExceptions.cs
index a35698aece..ad7e421790 100644
--- a/src/System.Management.Automation/utils/HostInterfacesExceptions.cs
+++ b/src/System.Management.Automation/utils/HostInterfacesExceptions.cs
@@ -4,12 +4,6 @@ Copyright (c) Microsoft Corporation. All rights reserved.
using System.Runtime.Serialization;
using System.Management.Automation.Internal;
-using Dbg = System.Management.Automation.Diagnostics;
-
-#if CORECLR
-// Use stub for SerializableAttribute and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
namespace System.Management.Automation.Host
{
diff --git a/src/System.Management.Automation/utils/MetadataExceptions.cs b/src/System.Management.Automation/utils/MetadataExceptions.cs
index 1c4ce305a5..733bf12766 100644
--- a/src/System.Management.Automation/utils/MetadataExceptions.cs
+++ b/src/System.Management.Automation/utils/MetadataExceptions.cs
@@ -6,11 +6,6 @@ using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
using System.Management.Automation.Internal;
-#if CORECLR
-// Use stub for SerializableAttribute and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace System.Management.Automation
{
///
diff --git a/src/System.Management.Automation/utils/MshArgumentException.cs b/src/System.Management.Automation/utils/MshArgumentException.cs
index 7b34ff56b0..0f1cbb4a04 100644
--- a/src/System.Management.Automation/utils/MshArgumentException.cs
+++ b/src/System.Management.Automation/utils/MshArgumentException.cs
@@ -3,13 +3,7 @@ Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Runtime.Serialization;
-
-#if !CORECLR
using System.Security.Permissions;
-#else
-// Use stub for SerializableAttribute.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
namespace System.Management.Automation
{
@@ -69,7 +63,6 @@ namespace System.Management.Automation
}
#region Serialization
-#if !CORECLR // ArgumentException Has No Serialization In CoreCLR
///
/// Initializes a new instance of the PSArgumentException class
/// using data serialized via
@@ -103,7 +96,6 @@ namespace System.Management.Automation
info.AddValue("ErrorId", _errorId);
info.AddValue("PSArgumentException_MessageOverride", _message);
}
-#endif
#endregion Serialization
///
diff --git a/src/System.Management.Automation/utils/MshArgumentNullException.cs b/src/System.Management.Automation/utils/MshArgumentNullException.cs
index 3e3a6c772b..48fda99021 100644
--- a/src/System.Management.Automation/utils/MshArgumentNullException.cs
+++ b/src/System.Management.Automation/utils/MshArgumentNullException.cs
@@ -3,13 +3,7 @@ Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Runtime.Serialization;
-
-#if !CORECLR
using System.Security.Permissions;
-#else
-// Use stub for SerializableAttribute.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
namespace System.Management.Automation
{
@@ -80,7 +74,6 @@ namespace System.Management.Automation
}
#region Serialization
-#if !CORECLR // ArgumentNullException Has No Serialization In CoreCLR
///
/// Initializes a new instance of the PSArgumentNullException class
/// using data serialized via
@@ -114,7 +107,6 @@ namespace System.Management.Automation
info.AddValue("ErrorId", _errorId);
info.AddValue("PSArgumentNullException_MessageOverride", _message);
}
-#endif
#endregion Serialization
#endregion ctor
diff --git a/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs b/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs
index 242ea2e5b6..c440aec518 100644
--- a/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs
+++ b/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs
@@ -3,13 +3,7 @@ Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Runtime.Serialization;
-
-#if !CORECLR
using System.Security.Permissions;
-#else
-// Use stub for SerializableAttribute.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
namespace System.Management.Automation
{
@@ -68,7 +62,6 @@ namespace System.Management.Automation
}
#region Serialization
-#if !CORECLR // ArgumentOutOfRangeException Has No Serialization In CoreCLR
///
/// Initializes a new instance of the PSArgumentOutOfRangeException class
/// using data serialized via
@@ -100,7 +93,6 @@ namespace System.Management.Automation
base.GetObjectData(info, context);
info.AddValue("ErrorId", _errorId);
}
-#endif
#endregion Serialization
///
diff --git a/src/System.Management.Automation/utils/MshInvalidOperationException.cs b/src/System.Management.Automation/utils/MshInvalidOperationException.cs
index cd66a58ec2..2a034416e0 100644
--- a/src/System.Management.Automation/utils/MshInvalidOperationException.cs
+++ b/src/System.Management.Automation/utils/MshInvalidOperationException.cs
@@ -3,13 +3,7 @@ Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Runtime.Serialization;
-
-#if !CORECLR
using System.Security.Permissions;
-#else
-// Use stub for SerializableAttribute.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
namespace System.Management.Automation
{
@@ -39,7 +33,6 @@ namespace System.Management.Automation
}
#region Serialization
-#if !CORECLR // InvalidOperationException Has No Serialization In CoreCLR
///
/// Initializes a new instance of the PSInvalidOperationException class
/// using data serialized via
@@ -71,7 +64,6 @@ namespace System.Management.Automation
base.GetObjectData(info, context);
info.AddValue("ErrorId", _errorId);
}
-#endif
#endregion Serialization
///
diff --git a/src/System.Management.Automation/utils/MshNotImplementedException.cs b/src/System.Management.Automation/utils/MshNotImplementedException.cs
index f5a6894fee..c250a3d7b6 100644
--- a/src/System.Management.Automation/utils/MshNotImplementedException.cs
+++ b/src/System.Management.Automation/utils/MshNotImplementedException.cs
@@ -3,13 +3,7 @@ Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Runtime.Serialization;
-
-#if !CORECLR
using System.Security.Permissions;
-#else
-// Use stub for SerializableAttribute.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
namespace System.Management.Automation
{
@@ -39,7 +33,6 @@ namespace System.Management.Automation
}
#region Serialization
-#if !CORECLR // NotImplementedException Has No Serialization In CoreCLR
///
/// Initializes a new instance of the PSNotImplementedException class
/// using data serialized via
@@ -71,7 +64,6 @@ namespace System.Management.Automation
base.GetObjectData(info, context);
info.AddValue("ErrorId", _errorId);
}
-#endif
#endregion Serialization
///
diff --git a/src/System.Management.Automation/utils/MshNotSupportedException.cs b/src/System.Management.Automation/utils/MshNotSupportedException.cs
index 1e8d33d021..a1f2c57f05 100644
--- a/src/System.Management.Automation/utils/MshNotSupportedException.cs
+++ b/src/System.Management.Automation/utils/MshNotSupportedException.cs
@@ -3,13 +3,7 @@ Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Runtime.Serialization;
-
-#if CORECLR
-// Use stub for SerializableAttribute.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#else
using System.Security.Permissions;
-#endif
namespace System.Management.Automation
{
@@ -39,7 +33,6 @@ namespace System.Management.Automation
}
#region Serialization
-#if !CORECLR // NotSupportedException Has No Serialization In CoreCLR
///
/// Initializes a new instance of the PSNotSupportedException class
/// using data serialized via
@@ -71,7 +64,6 @@ namespace System.Management.Automation
base.GetObjectData(info, context);
info.AddValue("ErrorId", _errorId);
}
-#endif
#endregion Serialization
///
diff --git a/src/System.Management.Automation/utils/MshObjectDisposedException.cs b/src/System.Management.Automation/utils/MshObjectDisposedException.cs
index 04466fb6cb..4b3f437dbd 100644
--- a/src/System.Management.Automation/utils/MshObjectDisposedException.cs
+++ b/src/System.Management.Automation/utils/MshObjectDisposedException.cs
@@ -3,13 +3,7 @@ Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Runtime.Serialization;
-
-#if !CORECLR
using System.Security.Permissions;
-#else
-// Use stub for SerializableAttribute.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
namespace System.Management.Automation
{
@@ -67,7 +61,6 @@ namespace System.Management.Automation
}
#region Serialization
-#if !CORECLR // ObjectDisposedException Has No Serialization In CoreCLR
///
/// Initializes a new instance of the PSObjectDisposedException class
/// using data serialized via
@@ -99,7 +92,6 @@ namespace System.Management.Automation
base.GetObjectData(info, context);
info.AddValue("ErrorId", _errorId);
}
-#endif
#endregion Serialization
#endregion ctor
diff --git a/src/System.Management.Automation/utils/PSTelemetryMethods.cs b/src/System.Management.Automation/utils/PSTelemetryMethods.cs
index bdc6282693..05520d0695 100644
--- a/src/System.Management.Automation/utils/PSTelemetryMethods.cs
+++ b/src/System.Management.Automation/utils/PSTelemetryMethods.cs
@@ -11,11 +11,6 @@ using System.Management.Automation;
using System.Management.Automation.Language;
using System.Threading;
using System.Threading.Tasks;
-#if CORECLR
-using Environment = System.Management.Automation.Environment;
-#else
-using Environment = System.Environment;
-#endif
namespace Microsoft.PowerShell.Telemetry.Internal
{
@@ -175,7 +170,7 @@ namespace Microsoft.PowerShell.Telemetry.Internal
(modulePath != null &&
(modulePath.StartsWith(Utils.GetApplicationBase(Utils.DefaultPowerShellShellID), StringComparison.OrdinalIgnoreCase) ||
// The following covers both 64 and 32 bit Program Files by assuming 32bit is just ...\Program Files + " (x86)"
- modulePath.StartsWith(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), StringComparison.OrdinalIgnoreCase))) ||
+ modulePath.StartsWith(Platform.GetFolderPath(Environment.SpecialFolder.ProgramFiles), StringComparison.OrdinalIgnoreCase))) ||
(companyName != null &&
foundModule.CompanyName.StartsWith("Microsoft", StringComparison.OrdinalIgnoreCase));
if (couldBeMicrosoftModule)
diff --git a/src/System.Management.Automation/utils/ParameterBinderExceptions.cs b/src/System.Management.Automation/utils/ParameterBinderExceptions.cs
index f1399e86e9..bbbfa0447c 100644
--- a/src/System.Management.Automation/utils/ParameterBinderExceptions.cs
+++ b/src/System.Management.Automation/utils/ParameterBinderExceptions.cs
@@ -5,13 +5,7 @@ Copyright (c) Microsoft Corporation. All rights reserved.
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Runtime.Serialization;
-
-#if !CORECLR
using System.Security.Permissions;
-#else
-// Use stub for SerializableAttribute, SecurityPermissionAttribute and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
namespace System.Management.Automation
{
diff --git a/src/System.Management.Automation/utils/ParserException.cs b/src/System.Management.Automation/utils/ParserException.cs
index d3e4966eb4..bc16ea00cd 100644
--- a/src/System.Management.Automation/utils/ParserException.cs
+++ b/src/System.Management.Automation/utils/ParserException.cs
@@ -7,11 +7,6 @@ using System.Linq;
using System.Management.Automation.Language;
using System.Runtime.Serialization;
-#if CORECLR
-// Use stub for SerializableAttribute and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace System.Management.Automation
{
///
diff --git a/src/System.Management.Automation/utils/PlatformInvokes.cs b/src/System.Management.Automation/utils/PlatformInvokes.cs
index 1706d242a4..afe585bdb7 100644
--- a/src/System.Management.Automation/utils/PlatformInvokes.cs
+++ b/src/System.Management.Automation/utils/PlatformInvokes.cs
@@ -5,14 +5,8 @@ Copyright (c) Microsoft Corporation. All rights reserved.
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Win32.SafeHandles;
-
-#if CORECLR
-// Use stubs for SafeHandleZeroOrMinusOneIsInvalid, SecurityPermissionAttribute and ReliabilityContractAttribute
-using Microsoft.PowerShell.CoreClr.Stubs;
-#else
using System.Security.Permissions;
using System.Runtime.ConstrainedExecution;
-#endif
namespace System.Management.Automation
{
diff --git a/src/System.Management.Automation/utils/PsUtils.cs b/src/System.Management.Automation/utils/PsUtils.cs
index d764203da2..f59015a99d 100644
--- a/src/System.Management.Automation/utils/PsUtils.cs
+++ b/src/System.Management.Automation/utils/PsUtils.cs
@@ -15,10 +15,6 @@ using System.Xml;
using Microsoft.Win32;
using System.Collections.Generic;
using System.Management.Automation.Language;
-#if CORECLR
-// Use stubs for SerializableAttribute, SecurityPermissionAttribute, ReliabilityContractAttribute and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
namespace System.Management.Automation
{
diff --git a/src/System.Management.Automation/utils/RuntimeException.cs b/src/System.Management.Automation/utils/RuntimeException.cs
index f16a477058..aa40d8f8b6 100644
--- a/src/System.Management.Automation/utils/RuntimeException.cs
+++ b/src/System.Management.Automation/utils/RuntimeException.cs
@@ -4,13 +4,7 @@ Copyright (c) Microsoft Corporation. All rights reserved.
using System.Management.Automation.Language;
using System.Runtime.Serialization;
-
-#if !CORECLR
using System.Security.Permissions;
-#else
-// Use stub for SerializableAttribute, SecurityPermissionAttribute and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
namespace System.Management.Automation
{
diff --git a/src/System.Management.Automation/utils/SessionStateExceptions.cs b/src/System.Management.Automation/utils/SessionStateExceptions.cs
index d6b3415776..7b8e9ed505 100644
--- a/src/System.Management.Automation/utils/SessionStateExceptions.cs
+++ b/src/System.Management.Automation/utils/SessionStateExceptions.cs
@@ -5,13 +5,7 @@ Copyright (c) Microsoft Corporation. All rights reserved.
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.Management.Automation.Internal;
-
-#if !CORECLR
using System.Security.Permissions;
-#else
-// Use stub for SerializableAttribute, SecurityPermissionAttribute and ISerializable related types.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
namespace System.Management.Automation
{
diff --git a/src/System.Management.Automation/utils/assert.cs b/src/System.Management.Automation/utils/assert.cs
index 9d2b1054e8..0a80a46562 100644
--- a/src/System.Management.Automation/utils/assert.cs
+++ b/src/System.Management.Automation/utils/assert.cs
@@ -14,11 +14,6 @@ Copyright (c) Microsoft Corporation. All rights reserved.
using System.Diagnostics;
using System.Text;
-#if CORECLR
-// Use stub for SystemException.
-using Microsoft.PowerShell.CoreClr.Stubs;
-#endif
-
namespace System.Management.Automation
{
///
@@ -63,7 +58,6 @@ namespace System.Management.Automation
{
internal static string StackTrace(int framesToSkip)
{
-#if !CORECLR //TODO:CORECLR StackTrace - unable to get stack trace
StackTrace trace = new StackTrace(true);
StackFrame[] frames = trace.GetFrames();
StringBuilder frameString = new StringBuilder();
@@ -75,9 +69,6 @@ namespace System.Management.Automation
frameString.Append(frame.ToString());
}
return frameString.ToString();
-#else
- return string.Empty;
-#endif
}
private static object s_throwInsteadOfAssertLock = 1;
@@ -196,9 +187,6 @@ namespace System.Management.Automation
builder.Append(Diagnostics.StackTrace(2));
tracer.TraceError(builder.ToString());
}
-#elif CORECLR // Debug.Fail is not in CoreCLR
- string assertionMessage = "ASSERT: " + whyThisShouldNeverHappen + " " + detailMessage + " ";
- throw new AssertException(assertionMessage);
#else
if (Diagnostics.ThrowInsteadOfAssert)
{
diff --git a/src/TypeCatalogGen/TypeCatalogGen.cs b/src/TypeCatalogGen/TypeCatalogGen.cs
index a17a67bf73..7d3522a6f5 100644
--- a/src/TypeCatalogGen/TypeCatalogGen.cs
+++ b/src/TypeCatalogGen/TypeCatalogGen.cs
@@ -14,7 +14,6 @@
*/
using System;
using System.Collections.Generic;
-using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
@@ -27,18 +26,28 @@ namespace Microsoft.PowerShell.CoreCLR
{
public class TypeCatalogGen
{
+ // Help messages
private const string Param_TargetCSharpFilePath = "TargetCSharpFilePath";
private const string Param_ReferenceListPath = "ReferenceListPath";
+ private const string Param_PrintDebugMessage = "-debug";
private const string HelpMessage = @"
-Usage: TypeCatalogGen.exe <{0}> <{1}>
+Usage: TypeCatalogGen.exe <{0}> <{1}> [{2}]
- {0}: Path of the target C# source file to generate.
- {1}: Path of the file containing all reference assembly paths, separated by semicolons.
+ - [{2}]: Write out debug messages. Optional.
";
+
+ // Error messages
private const string TargetSourceDirNotFound = "Cannot find the target source directory. The path '{0}' doesn't exist.";
private const string ReferenceListFileNotFound = "Cannot find the file that contains the reference list. The path '{0}' doesn't exist.";
private const string RefAssemblyNotFound = "Reference assembly '{0}' is declared in the reference list file '{1}', but the assembly doesn't exist.";
private const string UnexpectedFileExtension = "Cannot process '{0}' because its extension is neither '.DLL' nor '.METADATA_DLL'. Please make sure the file is an reference assembly.";
+ // Format strings for constructing type names
+ private const string Format_RegularType = "{0}.{1}";
+ private const string Format_SingleLevelNestedType = "{0}.{1}+{2}";
+ private const string Format_MultiLevelNestedType = "{0}+{1}";
+
/*
* Go through all reference assemblies of .NET Core and generate the type catalog -> Dictionary
* Then auto-generate the partial class 'PowerShellAssemblyLoadContext' that has the code to initialize the type catalog cache.
@@ -48,19 +57,21 @@ Usage: TypeCatalogGen.exe <{0}> <{1}>
*/
public static void Main(string[] args)
{
- if (args.Length != 2)
+ if (args.Length < 2 || args.Length > 3)
{
string message = string.Format(CultureInfo.CurrentCulture, HelpMessage,
Param_TargetCSharpFilePath,
- Param_ReferenceListPath);
+ Param_ReferenceListPath,
+ Param_PrintDebugMessage);
Console.WriteLine(message);
return;
}
+ bool printDebugMessage = args.Length == 3 && string.Equals(Param_PrintDebugMessage, args[2], StringComparison.OrdinalIgnoreCase);
string targetFilePath = ResolveTargetFilePath(args[0]);
List refAssemblyFiles = ResolveReferenceAssemblies(args[1]);
- Dictionary typeNameToAssemblyMap = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ Dictionary typeNameToAssemblyMap = new Dictionary(StringComparer.OrdinalIgnoreCase);
// mscorlib.metadata_dll doesn't contain any type definition.
foreach (string filePath in refAssemblyFiles)
@@ -91,15 +102,36 @@ Usage: TypeCatalogGen.exe <{0}> <{1}>
}
string fullName = GetTypeFullName(metadataReader, typeDefinition);
+ bool isTypeObsolete = IsTypeObsolete(metadataReader, typeDefinition);
- // Only add unique types
if (!typeNameToAssemblyMap.ContainsKey(fullName))
{
- typeNameToAssemblyMap.Add(fullName, strongAssemblyName);
+ // Add unique type.
+ typeNameToAssemblyMap.Add(fullName, new TypeMetadata(strongAssemblyName, isTypeObsolete));
}
- else
+ else if (typeNameToAssemblyMap[fullName].IsObsolete && !isTypeObsolete)
{
- Debug.WriteLine($"Not adding duplicate key {fullName}!");
+ // Duplicate types found defined in different assemblies, but the previous one is obsolete while the current one is not.
+ // Replace the existing type with the current one.
+ if (printDebugMessage)
+ {
+ var existingTypeMetadata = typeNameToAssemblyMap[fullName];
+ Console.WriteLine($@"
+REPLACE '{fullName}' from '{existingTypeMetadata.AssemblyName}' (IsObsolete? {existingTypeMetadata.IsObsolete})
+ WITH '{strongAssemblyName}' (IsObsolete? {isTypeObsolete})");
+ }
+ typeNameToAssemblyMap[fullName] = new TypeMetadata(strongAssemblyName, isTypeObsolete);
+ }
+ else if (printDebugMessage)
+ {
+ // Duplicate types found defined in different assemblies, and fall into one of the following conditions:
+ // - both are obsolete
+ // - both are not obsolete
+ // - the existing type is not obsolete while the new one is obsolete
+ var existingTypeMetadata = typeNameToAssemblyMap[fullName];
+ Console.WriteLine($@"
+DUPLICATE key '{fullName}' from '{strongAssemblyName}' (IsObsolete? {isTypeObsolete}).
+ -- Already exist in '{existingTypeMetadata.AssemblyName}' (IsObsolete? {existingTypeMetadata.IsObsolete})");
}
}
}
@@ -108,6 +140,69 @@ Usage: TypeCatalogGen.exe <{0}> <{1}>
WritePowerShellAssemblyLoadContextPartialClass(targetFilePath, typeNameToAssemblyMap);
}
+ ///
+ /// Check if the type is obsolete.
+ ///
+ private static bool IsTypeObsolete(MetadataReader reader, TypeDefinition typeDefinition)
+ {
+ const string obsoleteFullTypeName = "System.ObsoleteAttribute";
+
+ foreach (var customAttributeHandle in typeDefinition.GetCustomAttributes())
+ {
+ var customAttribute = reader.GetCustomAttribute(customAttributeHandle);
+ if (IsAttributeOfType(reader, customAttribute, obsoleteFullTypeName))
+ {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ ///
+ /// Check if the attribute type name is what we expected.
+ ///
+ private static bool IsAttributeOfType(MetadataReader reader, CustomAttribute customAttribute, string expectedTypeName)
+ {
+ string attributeFullName = null;
+ switch (customAttribute.Constructor.Kind)
+ {
+ case HandleKind.MethodDefinition:
+ // Attribute is defined in the same module
+ MethodDefinition methodDef = reader.GetMethodDefinition((MethodDefinitionHandle)customAttribute.Constructor);
+ TypeDefinitionHandle declaringTypeDefHandle = methodDef.GetDeclaringType();
+ if (declaringTypeDefHandle.IsNil) { /* Global method */ return false; }
+
+ TypeDefinition declaringTypeDef = reader.GetTypeDefinition(declaringTypeDefHandle);
+ attributeFullName = GetTypeFullName(reader, declaringTypeDef);
+ break;
+
+ case HandleKind.MemberReference:
+ MemberReference memberRef = reader.GetMemberReference((MemberReferenceHandle)customAttribute.Constructor);
+ switch (memberRef.Parent.Kind)
+ {
+ case HandleKind.TypeReference:
+ TypeReference typeRef = reader.GetTypeReference((TypeReferenceHandle)memberRef.Parent);
+ attributeFullName = GetTypeFullName(reader, typeRef);
+ break;
+
+ case HandleKind.TypeDefinition:
+ TypeDefinition typeDef = reader.GetTypeDefinition((TypeDefinitionHandle)memberRef.Parent);
+ attributeFullName = GetTypeFullName(reader, typeDef);
+ break;
+
+ default:
+ // constructor is global method, vararg method, or from a generic type.
+ return false;
+ }
+ break;
+
+ default:
+ throw new BadImageFormatException("Invalid custom attribute.");
+ }
+
+ return string.Equals(attributeFullName, expectedTypeName, StringComparison.Ordinal);
+ }
+
///
/// Get the strong name of a reference assembly represented by the 'metadataReader'
///
@@ -164,7 +259,48 @@ Usage: TypeCatalogGen.exe <{0}> <{1}>
}
///
- /// Get the full name of a Type.
+ /// Get the full name of a Type reference.
+ ///
+ private static string GetTypeFullName(MetadataReader metadataReader, TypeReference typeReference)
+ {
+ string fullName;
+ string typeName = metadataReader.GetString(typeReference.Name);
+ string nsName = metadataReader.GetString(typeReference.Namespace);
+
+ EntityHandle resolutionScope = typeReference.ResolutionScope;
+ if (resolutionScope.IsNil || resolutionScope.Kind != HandleKind.TypeReference)
+ {
+ fullName = string.Format(CultureInfo.InvariantCulture, Format_RegularType, nsName, typeName);
+ }
+ else
+ {
+ // It's a nested type.
+ fullName = typeName;
+ while (!resolutionScope.IsNil && resolutionScope.Kind == HandleKind.TypeReference)
+ {
+ TypeReference declaringTypeRef = metadataReader.GetTypeReference((TypeReferenceHandle)resolutionScope);
+ resolutionScope = declaringTypeRef.ResolutionScope;
+ if (resolutionScope.IsNil || resolutionScope.Kind != HandleKind.TypeReference)
+ {
+ fullName = string.Format(CultureInfo.InvariantCulture, Format_SingleLevelNestedType,
+ metadataReader.GetString(declaringTypeRef.Namespace),
+ metadataReader.GetString(declaringTypeRef.Name),
+ fullName);
+ }
+ else
+ {
+ fullName = string.Format(CultureInfo.InvariantCulture, Format_MultiLevelNestedType,
+ metadataReader.GetString(declaringTypeRef.Name),
+ fullName);
+ }
+ }
+ }
+
+ return fullName;
+ }
+
+ ///
+ /// Get the full name of a Type definition.
///
private static string GetTypeFullName(MetadataReader metadataReader, TypeDefinition typeDefinition)
{
@@ -176,7 +312,7 @@ Usage: TypeCatalogGen.exe <{0}> <{1}>
TypeDefinitionHandle declaringTypeHandle = typeDefinition.GetDeclaringType();
if (declaringTypeHandle.IsNil)
{
- fullName = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", nsName, typeName);
+ fullName = string.Format(CultureInfo.InvariantCulture, Format_RegularType, nsName, typeName);
}
else
{
@@ -187,14 +323,14 @@ Usage: TypeCatalogGen.exe <{0}> <{1}>
declaringTypeHandle = declaringTypeDef.GetDeclaringType();
if (declaringTypeHandle.IsNil)
{
- fullName = string.Format(CultureInfo.InvariantCulture, "{0}.{1}+{2}",
+ fullName = string.Format(CultureInfo.InvariantCulture, Format_SingleLevelNestedType,
metadataReader.GetString(declaringTypeDef.Namespace),
metadataReader.GetString(declaringTypeDef.Name),
fullName);
}
else
{
- fullName = string.Format(CultureInfo.InvariantCulture, "{0}+{1}",
+ fullName = string.Format(CultureInfo.InvariantCulture, Format_MultiLevelNestedType,
metadataReader.GetString(declaringTypeDef.Name),
fullName);
}
@@ -272,7 +408,7 @@ Usage: TypeCatalogGen.exe <{0}> <{1}>
///
/// Generate the CSharp source code that initialize the type catalog.
///
- private static void WritePowerShellAssemblyLoadContextPartialClass(string targetFilePath, Dictionary typeNameToAssemblyMap)
+ private static void WritePowerShellAssemblyLoadContextPartialClass(string targetFilePath, Dictionary typeNameToAssemblyMap)
{
const string SourceFormat = " typeCatalog[\"{0}\"] = \"{1}\";";
const string SourceHead = @"//
@@ -302,9 +438,9 @@ namespace System.Management.Automation
";
StringBuilder sourceCode = new StringBuilder(string.Format(CultureInfo.InvariantCulture, SourceHead, typeNameToAssemblyMap.Count));
- foreach (KeyValuePair pair in typeNameToAssemblyMap)
+ foreach (KeyValuePair pair in typeNameToAssemblyMap)
{
- sourceCode.AppendLine(string.Format(CultureInfo.InvariantCulture, SourceFormat, pair.Key, pair.Value));
+ sourceCode.AppendLine(string.Format(CultureInfo.InvariantCulture, SourceFormat, pair.Key, pair.Value.AssemblyName));
}
sourceCode.Append(SourceEnd);
@@ -314,6 +450,20 @@ namespace System.Management.Automation
writer.Write(sourceCode.ToString());
}
}
+
+ ///
+ /// Helper class to keep the metadata of a type
+ ///
+ private class TypeMetadata
+ {
+ internal readonly string AssemblyName;
+ internal readonly bool IsObsolete;
+ internal TypeMetadata(string assemblyName, bool isTypeObsolete)
+ {
+ this.AssemblyName = assemblyName;
+ this.IsObsolete = isTypeObsolete;
+ }
+ }
}
}
diff --git a/src/TypeCatalogGen/TypeCatalogGen.csproj b/src/TypeCatalogGen/TypeCatalogGen.csproj
index 37ea7a265f..adcb3b13b6 100644
--- a/src/TypeCatalogGen/TypeCatalogGen.csproj
+++ b/src/TypeCatalogGen/TypeCatalogGen.csproj
@@ -2,11 +2,10 @@
Generates CorePsTypeCatalog.cs given powershell.inc
- netcoreapp1.1
+ netcoreapp2.0
TypeCatalogGen
Exe
ubuntu.14.04-x64;ubuntu.16.04-x64;ubuntu.16.10-x64;debian.8-x64;centos.7-x64;fedora.24-x64;win7-x86;win7-x64;win81-x64;win10-x64;osx.10.11-x64;osx.10.12-x64;opensuse.13.2-x64;opensuse.42.1-x64
- 1.1.1
@@ -21,9 +20,4 @@
full
-
-
-
-
-
diff --git a/src/powershell-unix/powershell-unix.csproj b/src/powershell-unix/powershell-unix.csproj
index 3990e9caf9..035bc332d2 100644
--- a/src/powershell-unix/powershell-unix.csproj
+++ b/src/powershell-unix/powershell-unix.csproj
@@ -3,14 +3,13 @@
PowerShell top-level project with .NET CLI host
6.0.0
- netcoreapp1.1
+ netcoreapp2.0
true
true
true
powershell
Exe
ubuntu.14.04-x64;ubuntu.16.04-x64;ubuntu.16.10-x64;debian.8-x64;centos.7-x64;fedora.24-x64;osx.10.11-x64;osx.10.12-x64;opensuse.13.2-x64;opensuse.42.1-x64
- 1.1.1
@@ -37,7 +36,7 @@
-
+
$(DefineConstants);CORECLR
diff --git a/src/powershell-win-core/powershell-win-core.csproj b/src/powershell-win-core/powershell-win-core.csproj
index 889bf83d12..71f16d5140 100644
--- a/src/powershell-win-core/powershell-win-core.csproj
+++ b/src/powershell-win-core/powershell-win-core.csproj
@@ -3,14 +3,13 @@
PowerShell Core on Windows top-level project
6.0.0
- netcoreapp1.1
+ netcoreapp2.0
true
true
true
powershell
Exe
win7-x86;win7-x64;win81-x64;win10-x64
- 1.1.1
@@ -47,7 +46,7 @@
-
+
$(DefineConstants);CORECLR
diff --git a/test/PSReadLine/PSReadLine.tests.csproj b/test/PSReadLine/PSReadLine.tests.csproj
index ccd38134b8..65adc7b676 100644
--- a/test/PSReadLine/PSReadLine.tests.csproj
+++ b/test/PSReadLine/PSReadLine.tests.csproj
@@ -2,12 +2,11 @@
PSReadLine basic tests
- netcoreapp1.1
+ netcoreapp2.0
true
TestPSReadLine
Exe
ubuntu.14.04-x64;ubuntu.16.04-x64;centos.7-x64;fedora.24-x64;win7-x86;win7-x64;win10-x64;osx.10.11-x64;osx.10.12-x64;opensuse.13.2-x64;opensuse.42.1-x64
- 1.1.1
false
false
false
diff --git a/test/csharp/csharp.tests.csproj b/test/csharp/csharp.tests.csproj
index 91c3ccb435..902437e174 100644
--- a/test/csharp/csharp.tests.csproj
+++ b/test/csharp/csharp.tests.csproj
@@ -2,14 +2,12 @@
PowerShell On Linux xUnit Tests
- netcoreapp1.1
+ netcoreapp2.0
true
powershell-tests
../../src/signing/visualstudiopublic.snk
true
- true
ubuntu.14.04-x64;ubuntu.16.04-x64;debian.8-x64;centos.7-x64;fedora.24-x64;win7-x86;win7-x64;win81-x64;win10-x64;osx.10.11-x64;osx.10.12-x64;opensuse.13.2-x64;opensuse.42.1-x64
- $(PackageTargetFallback);dnxcore50
@@ -17,8 +15,9 @@
-
-
+
+
+
diff --git a/test/csharp/test_CorePsExtensions.cs b/test/csharp/test_CorePsExtensions.cs
deleted file mode 100644
index 97d2ee50f7..0000000000
--- a/test/csharp/test_CorePsExtensions.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-using Xunit;
-using System;
-using System.Management.Automation;
-
-namespace PSTests
-{
- [Collection("AssemblyLoadContext")]
- public static class CorePsExtensionsTests
- {
- [Fact]
- public static void TestEnvironmentOSVersion()
- {
- // this test primarily checks that there is no exception thrown
- // NOTE: the type name is explicitly written here to make clear what
- // type and function is tested
- System.Management.Automation.Environment.OperatingSystem os = System.Management.Automation.Environment.OSVersion;
- Assert.NotNull(os);
- }
- }
-}
diff --git a/test/csharp/test_CorePsPlatform.cs b/test/csharp/test_CorePsPlatform.cs
index 96abeeebd0..fa304a4bd0 100644
--- a/test/csharp/test_CorePsPlatform.cs
+++ b/test/csharp/test_CorePsPlatform.cs
@@ -57,7 +57,7 @@ namespace PSTests
// The process should return an exit code of 0 on success
Assert.Equal(0, process.ExitCode);
// It should be the same as what our platform code returns
- Assert.Equal(hostname, System.Management.Automation.Environment.MachineName);
+ Assert.Equal(hostname, Environment.MachineName);
}
}
diff --git a/test/powershell/Language/Classes/Scripting.Classes.Attributes.Tests.ps1 b/test/powershell/Language/Classes/Scripting.Classes.Attributes.Tests.ps1
index d2edfd2416..e29e467647 100644
--- a/test/powershell/Language/Classes/Scripting.Classes.Attributes.Tests.ps1
+++ b/test/powershell/Language/Classes/Scripting.Classes.Attributes.Tests.ps1
@@ -45,7 +45,7 @@ namespace Dummy
}
}
'@
- Add-Type -TypeDefinition $dummyAttributesSource -ReferencedAssemblies "System.Management.Automation","mscorlib"
+ Add-Type -TypeDefinition $dummyAttributesSource
}
diff --git a/test/powershell/Language/Parser/ParameterBinding.Tests.ps1 b/test/powershell/Language/Parser/ParameterBinding.Tests.ps1
index b5ae9b7d59..038b0dc32e 100644
--- a/test/powershell/Language/Parser/ParameterBinding.Tests.ps1
+++ b/test/powershell/Language/Parser/ParameterBinding.Tests.ps1
@@ -45,7 +45,7 @@ Describe 'Argument transformation attribute on optional argument with explicit $
}
}
'@
- $mod = Add-Type -PassThru -TypeDefinition $tdefinition -refer mscorlib,System.Management.Automation
+ $mod = Add-Type -PassThru -TypeDefinition $tdefinition
Import-Module $mod[0].Assembly
diff --git a/test/powershell/Language/Scripting/ConstrainedLanguageMode.Tests.ps1 b/test/powershell/Language/Scripting/ConstrainedLanguageMode.Tests.ps1
index 7b6da753c9..268fffc138 100644
--- a/test/powershell/Language/Scripting/ConstrainedLanguageMode.Tests.ps1
+++ b/test/powershell/Language/Scripting/ConstrainedLanguageMode.Tests.ps1
@@ -1,11 +1,9 @@
Describe "Test constrained language mode" -Tags "CI" {
It "dynamic invocation on non-PowerShell thread should work" {
- $refAssemblies = if ($IsCoreCLR) {
- "Microsoft.CSharp","System.Dynamic.Runtime","System.Management.Automation"
- }
- else {
- "Microsoft.CSharp"
+ $refAssemblies = @()
+ if (!$IsCoreCLR) {
+ $refAssemblies += "Microsoft.CSharp"
}
$t,$null = Add-Type -ReferencedAssemblies $refAssemblies -WarningAction Ignore -PassThru @"
@@ -39,4 +37,4 @@ Describe "Test constrained language mode" -Tags "CI" {
$ps.Dispose()
}
}
-}
\ No newline at end of file
+}
diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Member.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Member.Tests.ps1
index 067a1aa008..0e5e044324 100644
--- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Member.Tests.ps1
+++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Member.Tests.ps1
@@ -256,7 +256,9 @@ Describe "Get-Member DRT Unit Tests" -Tags "CI" {
Context "Verify Get-Member with other parameters" {
It 'works with View Parameter' {
$results = [xml]'some text' | Get-Member -view adapted
- $results.Length | Should Be 38
+ $results | ? Name -eq a | Should Not BeNullOrEmpty
+ $results | ? Name -eq CreateElement | Should Not BeNullOrEmpty
+ $results | ? Name -eq CreateNode | Should Not BeNullOrEmpty
}
It 'Get hidden members'{
diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Import-Csv.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Import-Csv.Tests.ps1
index 20769f27bb..61ea6b5322 100644
--- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Import-Csv.Tests.ps1
+++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Import-Csv.Tests.ps1
@@ -81,8 +81,7 @@ Describe "Import-Csv #Type Tests" -Tags "CI" {
$processlist = (Get-Process)[0..1]
$processlist | Export-Csv -Path $testfile -Force
# Import-Csv add "CSV:" before actual type
- # (Why #HandleCount ? See Issue #1812)
- $expectedProcessType = "CSV:System.Diagnostics.Process#HandleCount"
+ $expectedProcessType = "CSV:System.Diagnostics.Process"
}
It "Test import-csv import Object" {
diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Start-Sleep.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Start-Sleep.Tests.ps1
index 2326498502..ed0766ac7d 100644
--- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Start-Sleep.Tests.ps1
+++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Start-Sleep.Tests.ps1
@@ -1,20 +1,22 @@
Describe "Start-Sleep DRT Unit Tests" -Tags "CI" {
- It "Should be works properly when sleeping with Second" {
- $dtStart = [DateTime]::Now
+
+ # WaitHandle.WaitOne(milliseconds, exitContext) is not accurate.
+ # The wait time varies from 980ms to 1020ms from observation, so
+ # the tests here are changed to be greater than 950ms.
+
+ It "Should work properly when sleeping with Second" {
+ $watch = [System.Diagnostics.Stopwatch]::StartNew()
Start-Sleep -Seconds 1
- $dtEnd = [DateTime]::Now
- $milliseconds = (New-TimeSpan -Start $dtStart -End $dtEnd).TotalMilliseconds
- $milliseconds | Should BeGreaterThan 1000
+ $watch.Stop()
+ $watch.ElapsedMilliseconds | Should BeGreaterThan 950
}
- It "Should be works properly when sleeping with Milliseconds" {
- $dtStart = [DateTime]::Now
+ It "Should work properly when sleeping with Milliseconds" {
+ $watch = [System.Diagnostics.Stopwatch]::StartNew()
Start-Sleep -Milliseconds 1000
- $dtEnd = [DateTime]::Now
- $milliseconds = (New-TimeSpan -Start $dtStart -End $dtEnd).TotalMilliseconds
- $milliseconds -ge 1000 | Should Be $true
+ $watch.Stop()
+ $watch.ElapsedMilliseconds | Should BeGreaterThan 950
}
-
}
Describe "Start-Sleep" -Tags "CI" {
diff --git a/test/powershell/Modules/PowerShellGet/PowerShellGet.Tests.ps1 b/test/powershell/Modules/PowerShellGet/PowerShellGet.Tests.ps1
index 961d37be57..653b1ca0c0 100644
--- a/test/powershell/Modules/PowerShellGet/PowerShellGet.Tests.ps1
+++ b/test/powershell/Modules/PowerShellGet/PowerShellGet.Tests.ps1
@@ -6,6 +6,8 @@ $SourceLocation = 'https://dtlgalleryint.cloudapp.net'
$RegisteredINTRepo = $false
$ContosoServer = 'ContosoServer'
$FabrikamServerScript = 'Fabrikam-ServerScript'
+$Initialized = $false
+
#region Utility functions
@@ -65,25 +67,28 @@ $script:MyDocumentsScriptsPath = Microsoft.PowerShell.Management\Join-Path -Path
#region Register a test repository
-# Check if the PackageManagement works in the base-oS or PowerShellCore
-$PSHome
-$PSVersionTable
-$env:PSModulePath
-
-Get-Module -ListAvailable -Name PackageManagement, PowerShellGet
-Import-Module PackageManagement -verbose
-Get-PackageProvider -ListAvailable
-
-$repo = Get-PSRepository -ErrorAction SilentlyContinue |
- Where-Object {$_.SourceLocation.StartsWith($SourceLocation, [System.StringComparison]::OrdinalIgnoreCase)}
-if($repo)
+function Initialize
{
- $RepositoryName = $repo.Name
-}
-else
-{
- Register-PSRepository -Name $RepositoryName -SourceLocation $SourceLocation -InstallationPolicy Trusted
- $RegisteredINTRepo = $true
+ # Check if the PackageManagement works in the base-oS or PowerShellCore
+ $PSHome
+ $PSVersionTable
+ $env:PSModulePath
+
+ Get-Module -ListAvailable -Name PackageManagement, PowerShellGet
+ Import-Module PackageManagement -verbose
+ Get-PackageProvider -ListAvailable
+
+ $repo = Get-PSRepository -ErrorAction SilentlyContinue |
+ Where-Object {$_.SourceLocation.StartsWith($SourceLocation, [System.StringComparison]::OrdinalIgnoreCase)}
+ if($repo)
+ {
+ $script:RepositoryName = $repo.Name
+ }
+ else
+ {
+ Register-PSRepository -Name $RepositoryName -SourceLocation $SourceLocation -InstallationPolicy Trusted
+ $script:RegisteredINTRepo = $true
+ }
}
#endregion
@@ -95,6 +100,13 @@ function Remove-InstalledModules
Describe "PowerShellGet - Module tests" -tags "Feature" {
+ BeforeAll {
+ if ($script:Initialized -eq $false) {
+ Initialize
+ $script:Initialized = $true
+ }
+ }
+
BeforeEach {
Remove-InstalledModules
}
@@ -125,6 +137,13 @@ Describe "PowerShellGet - Module tests" -tags "Feature" {
Describe "PowerShellGet - Module tests (Admin)" -tags @('Feature', 'RequireAdminOnWindows') {
+ BeforeAll {
+ if ($script:Initialized -eq $false) {
+ Initialize
+ $script:Initialized = $true
+ }
+ }
+
BeforeEach {
Remove-InstalledModules
}
@@ -154,6 +173,13 @@ function Remove-InstalledScripts
Describe "PowerShellGet - Script tests" -tags "Feature" {
+ BeforeAll {
+ if ($script:Initialized -eq $false) {
+ Initialize
+ $script:Initialized = $true
+ }
+ }
+
BeforeEach {
Remove-InstalledScripts
}
@@ -180,6 +206,13 @@ Describe "PowerShellGet - Script tests" -tags "Feature" {
Describe "PowerShellGet - Script tests (Admin)" -tags @('Feature', 'RequireAdminOnWindows') {
+ BeforeAll {
+ if ($script:Initialized -eq $false) {
+ Initialize
+ $script:Initialized = $true
+ }
+ }
+
BeforeEach {
Remove-InstalledScripts
}
diff --git a/test/powershell/engine/Remoting/InvokeCommandRemoteDebug.Tests.ps1 b/test/powershell/engine/Remoting/InvokeCommandRemoteDebug.Tests.ps1
index 96def606e2..9d5d7d8b65 100644
--- a/test/powershell/engine/Remoting/InvokeCommandRemoteDebug.Tests.ps1
+++ b/test/powershell/engine/Remoting/InvokeCommandRemoteDebug.Tests.ps1
@@ -129,7 +129,7 @@ Describe "Invoke-Command remote debugging tests" -Tags 'Feature' {
"Hello!"
'@)
- Add-Type -TypeDefinition $typeDef -ReferencedAssemblies "System.Globalization","System.Management.Automation"
+ Add-Type -TypeDefinition $typeDef
$dummyHost = [TestRunner.DummyHost]::new()
[runspace] $rs = [runspacefactory]::CreateRunspace($dummyHost)
diff --git a/test/tools/CreateChildProcess/CreateChildProcess.csproj b/test/tools/CreateChildProcess/CreateChildProcess.csproj
index 2abd37a575..2f50744943 100644
--- a/test/tools/CreateChildProcess/CreateChildProcess.csproj
+++ b/test/tools/CreateChildProcess/CreateChildProcess.csproj
@@ -2,11 +2,10 @@
Very simple little console app that creates child processes of itself
- netcoreapp1.1
+ netcoreapp2.0
createchildprocess
Exe
ubuntu.16.04-x64;ubuntu.14.04-x64;debian.8-x64;centos.7-x64;fedora.24-x64;win7-x86;win7-x64;win81-x64;win10-x64;osx.10.11-x64;osx.10.12-x64;opensuse.13.2-x64;opensuse.42.1-x64
- 1.1.1
diff --git a/test/tools/EchoArgs/EchoArgs.csproj b/test/tools/EchoArgs/EchoArgs.csproj
index 33c1a2abe2..60566fe6e2 100644
--- a/test/tools/EchoArgs/EchoArgs.csproj
+++ b/test/tools/EchoArgs/EchoArgs.csproj
@@ -2,11 +2,10 @@
Very simple little console class that you can use to see how PowerShell is passing parameters to legacy console apps.
- netcoreapp1.1
+ netcoreapp2.0
echoargs
Exe
ubuntu.16.04-x64;ubuntu.14.04-x64;debian.8-x64;centos.7-x64;fedora.24-x64;win7-x86;win7-x64;win81-x64;win10-x64;osx.10.11-x64;osx.10.12-x64;opensuse.13.2-x64;opensuse.42.1-x64
- 1.1.1
diff --git a/test/tools/Modules/TestHostCS/TestHostCS.psm1 b/test/tools/Modules/TestHostCS/TestHostCS.psm1
index 2f4408bcfd..4e97aaa4e3 100755
--- a/test/tools/Modules/TestHostCS/TestHostCS.psm1
+++ b/test/tools/Modules/TestHostCS/TestHostCS.psm1
@@ -300,9 +300,7 @@ function New-TestHost
{
If ($IsCoreCLR)
{
- $references = "mscorlib","System.Management.Automation",
- "System.Collections.NonGeneric","System.Console","System.Collections",
- "System.Globalization"
+ $references = @()
}
else
{