diff --git a/.gitmodules b/.gitmodules index c677d18caff..e69de29bb2d 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,4 +0,0 @@ -[submodule "src/libpsl-native/test/googletest"] - path = src/libpsl-native/test/googletest - url = https://github.com/google/googletest.git - ignore = dirty diff --git a/build.psm1 b/build.psm1 index 9296d98b0ea..a59db9aef96 100644 --- a/build.psm1 +++ b/build.psm1 @@ -177,220 +177,6 @@ if ( -not $env:PSModulePath.Contains($TestModulePath) ) { $env:PSModulePath = $TestModulePath+$TestModulePathSeparator+$($env:PSModulePath) } -function Test-Win10SDK { - # The Windows 10 SDK is installed to "${env:ProgramFiles(x86)}\Windows Kits\10\bin\x64", - # but the directory may exist even if the SDK has not been installed. - # - # A slightly more robust check is for the mc.exe binary within that directory. - # It is only present if the SDK is installed. - return (Test-Path "${env:ProgramFiles(x86)}\Windows Kits\10\bin\x64\mc.exe") -} - -function Start-BuildNativeWindowsBinaries { - param( - [ValidateSet('Debug', 'Release')] - [string]$Configuration = 'Release', - - # The `x64_arm` syntax is the build environment for VS2017, `x64` means the host is an x64 machine and will use - # the x64 built tool. The `arm` refers to the target architecture when doing cross compilation. - [ValidateSet('x64', 'x86', 'x64_arm64', 'x64_arm')] - [string]$Arch = 'x64', - - [switch]$Clean - ) - - if (-not $Environment.IsWindows) { - Write-Warning -Message "'Start-BuildNativeWindowsBinaries' is only supported on Windows platforms" - return - } - - # cmake is needed to build pwsh.exe - if (-not (precheck 'cmake' $null)) { - throw 'cmake not found. Run "Start-PSBootstrap -BuildWindowsNative". You can also install it from https://chocolatey.org/packages/cmake' - } - - Use-MSBuild - - # mc.exe is Message Compiler for native resources - if (-Not (Test-Win10SDK)) { - throw 'Win 10 SDK not found. Run "Start-PSBootstrap -BuildWindowsNative" or install Microsoft Windows 10 SDK from https://developer.microsoft.com/en-US/windows/downloads/windows-10-sdk' - } - - if ($env:VS140COMNTOOLS -ne $null) { - $vcPath = (Get-Item(Join-Path -Path "$env:VS140COMNTOOLS" -ChildPath '../../vc')).FullName - } else { - $vcPath = (Get-ChildItem "${env:ProgramFiles(x86)}\Microsoft Visual Studio\2017" -Filter "VC" -Directory -Recurse | Select-Object -First 1).FullName - } - - $atlMfcIncludePath = Join-Path -Path $vcPath -ChildPath 'atlmfc/include' - if (!(Test-Path $atlMfcIncludePath)) { # for VS2017, need to search for it - $atlMfcIncludePath = (Get-ChildItem $vcPath -Filter AtlBase.h -Recurse -File | Select-Object -First 1).DirectoryName - } - - # atlbase.h is included in the pwrshplugin project - if ((Test-Path -Path $atlMfcIncludePath\atlbase.h) -eq $false) { - throw "Could not find Visual Studio include file atlbase.h at $atlMfcIncludePath. Please ensure the optional feature 'Microsoft Foundation Classes for C++' is installed." - } - - # vcvarsall.bat is used to setup environment variables - $vcvarsallbatPath = "$vcPath\vcvarsall.bat" - if (!(Test-Path -Path $vcvarsallbatPath)) { # for VS2017, need to search for it - $vcvarsallbatPath = (Get-ChildItem $vcPath -Filter vcvarsall.bat -Recurse -File | Select-Object -First 1).FullName - } - - if ([string]::IsNullOrEmpty($vcvarsallbatPath) -or (Test-Path -Path $vcvarsallbatPath) -eq $false) { - throw "Could not find Visual Studio vcvarsall.bat at $vcvarsallbatPath. Please ensure the optional feature 'Common Tools for Visual C++' is installed." - } - - Write-Log "Start building native Windows binaries" - - if ($Clean) { - git clean -fdx - Remove-Item $HOME\source\cmakecache.txt -ErrorAction SilentlyContinue - } - - try { - Push-Location "$PSScriptRoot\src\powershell-native" - - # setup cmakeGenerator - $cmakeGeneratorPlatform = "" - if ($Arch -eq 'x86') { - $cmakeGenerator = 'Visual Studio 15 2017' - $cmakeArch = 'x86' - } elseif ($Arch -eq 'x64_arm') { - $cmakeGenerator = 'Visual Studio 15 2017 ARM' - $cmakeArch = 'arm' - } elseif ($Arch -eq 'x64_arm64') { - $cmakeGenerator = 'Visual Studio 15 2017' - $cmakeArch = 'arm64' - $cmakeGeneratorPlatform = "-A ARM64" - } else { - $cmakeGenerator = 'Visual Studio 15 2017 Win64' - $cmakeArch = 'x64' - } - - # Compile native resources - $currentLocation = Get-Location - @("nativemsh\pwrshplugin") | ForEach-Object { - $nativeResourcesFolder = $_ - Get-ChildItem $nativeResourcesFolder -Filter "*.mc" | ForEach-Object { - $command = @" -cmd.exe /C cd /d "$currentLocation" "&" "$vcvarsallbatPath" "$Arch" "&" mc.exe -o -d -c -U "$($_.FullName)" -h "$currentLocation\$nativeResourcesFolder" -r "$currentLocation\$nativeResourcesFolder" -"@ - Write-Log " Executing mc.exe Command: $command" - Start-NativeExecution { Invoke-Expression -Command:$command } - } - } - - # make sure we use version we installed and not from VS - $cmakePath = (Get-Command cmake).Source - # Disabling until I figure out if it is necessary - # $overrideFlags = "-DCMAKE_USER_MAKE_RULES_OVERRIDE=$PSScriptRoot\src\powershell-native\windows-compiler-override.txt" - $overrideFlags = "" - $command = @" -cmd.exe /C cd /d "$currentLocation" "&" "$vcvarsallbatPath" "$Arch" "&" "$cmakePath" "$overrideFlags" -DBUILD_ONECORE=ON -DBUILD_TARGET_ARCH=$cmakeArch -G "$cmakeGenerator" $cmakeGeneratorPlatform "$currentLocation" "&" msbuild ALL_BUILD.vcxproj "/p:Configuration=$Configuration" -"@ - Write-Log " Executing Build Command: $command" - Start-NativeExecution { Invoke-Expression -Command:$command } - - # Copy the binaries from the local build directory to the packaging directory - $FilesToCopy = @('pwrshplugin.dll', 'pwrshplugin.pdb') - $dstPath = "$PSScriptRoot\src\powershell-win-core" - $FilesToCopy | ForEach-Object { - $srcPath = [IO.Path]::Combine($PWD.Path, "bin", $Configuration, "CoreClr/$_") - - Write-Log " Copying $srcPath to $dstPath" - Copy-Item $srcPath $dstPath - } - - # - # Build the ETW manifest resource-only binary - # - $location = "$PSScriptRoot\src\PowerShell.Core.Instrumentation" - Set-Location -Path $location - - Remove-Item $HOME\source\cmakecache.txt -ErrorAction SilentlyContinue - - $command = @" -cmd.exe /C cd /d "$location" "&" "$vcvarsallbatPath" "$Arch" "&" "$cmakePath" "$overrideFlags" -DBUILD_ONECORE=ON -DBUILD_TARGET_ARCH=$cmakeArch -G "$cmakeGenerator" $cmakeGeneratorPlatform "$location" "&" msbuild ALL_BUILD.vcxproj "/p:Configuration=$Configuration" -"@ - Write-Log " Executing Build Command for PowerShell.Core.Instrumentation: $command" - Start-NativeExecution { Invoke-Expression -Command:$command } - - # Copy the binary to the packaging directory - # NOTE: No PDB file; it's a resource-only DLL. - $srcPath = [IO.Path]::Combine($PWD.Path, $Configuration, 'PowerShell.Core.Instrumentation.dll') - Copy-Item -Path $srcPath -Destination $dstPath - - } finally { - Pop-Location - } -} - -function Start-BuildNativeUnixBinaries { - param ( - [switch] $BuildLinuxArm - ) - - if (-not $Environment.IsLinux -and -not $Environment.IsMacOS) { - Write-Warning -Message "'Start-BuildNativeUnixBinaries' is only supported on Linux/macOS platforms" - return - } - - if ($BuildLinuxArm -and -not $Environment.IsUbuntu) { - throw "Cross compiling for linux-arm is only supported on Ubuntu environment" - } - - # Verify we have all tools in place to do the build - $precheck = $true - foreach ($Dependency in 'cmake', 'make', 'g++') { - $precheck = $precheck -and (precheck $Dependency "Build dependency '$Dependency' not found. Run 'Start-PSBootstrap'.") - } - - if ($BuildLinuxArm) { - foreach ($Dependency in 'arm-linux-gnueabihf-gcc', 'arm-linux-gnueabihf-g++') { - $precheck = $precheck -and (precheck $Dependency "Build dependency '$Dependency' not found. Run 'Start-PSBootstrap'.") - } - } - - # Abort if any precheck failed - if (-not $precheck) { - return - } - - # Build native components - $Ext = if ($Environment.IsLinux) { - "so" - } elseif ($Environment.IsMacOS) { - "dylib" - } - - $Native = "$PSScriptRoot/src/libpsl-native" - $Lib = "$PSScriptRoot/src/powershell-unix/libpsl-native.$Ext" - Write-Log "Start building $Lib" - - git clean -qfdX $Native - - try { - Push-Location $Native - if ($BuildLinuxArm) { - Start-NativeExecution { cmake -DCMAKE_TOOLCHAIN_FILE="./arm.toolchain.cmake" . } - Start-NativeExecution { make -j } - } - else { - Start-NativeExecution { cmake -DCMAKE_BUILD_TYPE=Debug . } - Start-NativeExecution { make -j } - Start-NativeExecution { ctest --verbose } - } - } finally { - Pop-Location - } - - if (-not (Test-Path $Lib)) { - throw "Compilation of $Lib failed" - } -} - <# .Synopsis Tests if a version is preview @@ -1719,7 +1505,6 @@ function Start-PSBootstrap { [string]$Version = $dotnetCLIRequiredVersion, [switch]$Package, [switch]$NoSudo, - [switch]$BuildWindowsNative, [switch]$BuildLinuxArm, [switch]$Force ) @@ -1909,75 +1694,6 @@ function Start-PSBootstrap { Invoke-WebRequest -OutFile "~/.rcedit/rcedit-x64.exe" -Uri $rceditUrl } - - if ($BuildWindowsNative) { - Write-Log "Install Windows dependencies for building PSRP plugin" - - $machinePath = [Environment]::GetEnvironmentVariable('Path', 'MACHINE') - $newMachineEnvironmentPath = $machinePath - - $cmakePresent = precheck 'cmake' $null - $sdkPresent = Test-Win10SDK - - # Install chocolatey - $chocolateyPath = "$env:AllUsersProfile\chocolatey\bin" - - if(precheck 'choco' $null) { - Write-Log "Chocolatey is already installed. Skipping installation." - } - elseif(($cmakePresent -eq $false) -or ($sdkPresent -eq $false)) { - Write-Log "Chocolatey not present. Installing chocolatey." - if ($Force -or $PSCmdlet.ShouldProcess("Install chocolatey via https://chocolatey.org/install.ps1")) { - Invoke-Expression ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1')) - if (-not ($machinePath.ToLower().Contains($chocolateyPath.ToLower()))) { - Write-Log "Adding $chocolateyPath to Path environment variable" - $env:Path += ";$chocolateyPath" - $newMachineEnvironmentPath += ";$chocolateyPath" - } else { - Write-Log "$chocolateyPath already present in Path environment variable" - } - } else { - Write-Error "Chocolatey is required to install missing dependencies. Please install it from https://chocolatey.org/ manually. Alternatively, install cmake and Windows 10 SDK." - return - } - } else { - Write-Log "Skipping installation of chocolatey, cause both cmake and Win 10 SDK are present." - } - - # Install cmake - $cmakePath = "${env:ProgramFiles}\CMake\bin" - if($cmakePresent -and !($force.IsPresent)) { - Write-Log "Cmake is already installed. Skipping installation." - } else { - Write-Log "Cmake not present or -Force used. Installing cmake." - Start-NativeExecution { choco install cmake -y --version 3.10.0 } - if (-not ($machinePath.ToLower().Contains($cmakePath.ToLower()))) { - Write-Log "Adding $cmakePath to Path environment variable" - $env:Path += ";$cmakePath" - $newMachineEnvironmentPath = "$cmakePath;$newMachineEnvironmentPath" - } else { - Write-Log "$cmakePath already present in Path environment variable" - } - } - - # Install Windows 10 SDK - $packageName = "windows-sdk-10.0" - - if (-not $sdkPresent) { - Write-Log "Windows 10 SDK not present. Installing $packageName." - Start-NativeExecution { choco install windows-sdk-10.0 -y } - } else { - Write-Log "Windows 10 SDK present. Skipping installation." - } - - # Update path machine environment variable - if ($newMachineEnvironmentPath -ne $machinePath) { - Write-Log "Updating Path machine environment variable" - if ($Force -or $PSCmdlet.ShouldProcess("Update Path machine environment variable to $newMachineEnvironmentPath")) { - [Environment]::SetEnvironmentVariable('Path', $newMachineEnvironmentPath, 'MACHINE') - } - } - } } } finally { Pop-Location diff --git a/src/PowerShell.Core.Instrumentation/CMakeLists.txt b/src/PowerShell.Core.Instrumentation/CMakeLists.txt deleted file mode 100644 index bfa5218b86c..00000000000 --- a/src/PowerShell.Core.Instrumentation/CMakeLists.txt +++ /dev/null @@ -1,75 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -# -# Builds PowerShell.Core.Instrumentation.dll resource-only DLL containing ETW event resources -# - -# The fully qualified path to the event manifest -SET(EVENTS_MANIFEST "${CMAKE_CURRENT_SOURCE_DIR}/PowerShell.Core.Instrumentation.man") - -# User mode manifest resource-only dll -function(add_manifest_binary) - - add_definitions(-D_DLL=1) - add_library(${ARGV}) - - # NOTE: EVENTS_MANIFEST must be the fully qualified path to the manifest - SET(MC_MANIFEST_FULLNAME ${EVENTS_MANIFEST}) - - # get the ETW manifest's filename without the directory or extension - get_filename_component(MC_MANIFEST_BASENAME ${EVENTS_MANIFEST} NAME_WE) - - SET(MC_COMMAND "mc.exe") - SET(GeneratedManifestFiles) - - # The target directory for generated managed files - SET (MC_GENERATED_DIR "${CMAKE_CURRENT_BINARY_DIR}") - - # include the generated directory in the include path - include_directories("${MC_GENERATED_DIR}") - - SET (MC_GENERATED_FILES - ${MC_GENERATED_DIR}/${MC_MANIFEST_BASENAME}.rc - ${MC_GENERATED_DIR}/${MC_MANIFEST_BASENAME}TEMP.BIN - ${MC_GENERATED_DIR}/${MC_MANIFEST_BASENAME}_MSG00001.BIN - ) - - SET(MC_COMMAND "mc.exe -h ${MC_GENERATED_DIR} -r ${MC_GENERATED_DIR} ${MC_MANIFEST_FULLNAME}") - - add_custom_command( - COMMENT "Generating native event manifest files for ${EVENTS_MANIFEST}" - OUTPUT ${MC_GENERATED_FILES} - DEPENDS ${MC_MANIFEST_FULLNAME} - COMMAND cmd.exe /c ${MC_COMMAND} - WORKING_DIRECTORY ${MC_GENERATED_DIR} - VERBATIM - ) - - list (APPEND GeneratedManifestFiles ${MC_GENERATED_DIR}/${MC_MANIFEST_BASENAME}.rc) - - set_source_files_properties(${GeneratedManifestFiles} PROPERTIES GENERATED TRUE) - add_custom_target(GeneratedManifestFiles DEPENDS ${GeneratedManifestFiles}) - - # for a resource only dll, cmake can report an error - # if there is no linker language set. - # CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly. - # Missing variable is: CMAKE_RC_CREATE_SHARED_LIBRARY - get_property(isSet TARGET ${ARGV0} PROPERTY LINKER_LANGUAGE SET) - if (NOT ${isSet}) - set_target_properties(${ARGV0} PROPERTIES LINKER_LANGUAGE "CXX") - endif() - - set_target_properties(${ARGV0} PROPERTIES LINK_FLAGS "/NODEFAULTLIB /NOENTRY") - - if (BUILD_ONECORE) - set_target_properties(${ARGV0} PROPERTIES COMPILE_DEFINITIONS "CORECLR") - endif (BUILD_ONECORE) - - # ensure the target is dependent on the generated files. - add_dependencies(${ARGV0} GeneratedManifestFiles) - -endfunction() - -file(GLOB SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/version.rc) - -add_manifest_binary(PowerShell.Core.Instrumentation SHARED ${SOURCES}) - diff --git a/src/PowerShell.Core.Instrumentation/PowerShell.Core.Instrumentation.nuspec b/src/PowerShell.Core.Instrumentation/PowerShell.Core.Instrumentation.nuspec deleted file mode 100644 index 3d27acf63b8..00000000000 --- a/src/PowerShell.Core.Instrumentation/PowerShell.Core.Instrumentation.nuspec +++ /dev/null @@ -1,12 +0,0 @@ - - - - PowerShell.Core.Instrumentation - 6.0.0-beta.10 - Microsoft - Microsoft - false - PowerShell Core ETW resource binary - (c) Microsoft Corporation. All rights reserved. - - diff --git a/src/PowerShell.Core.Instrumentation/README.md b/src/PowerShell.Core.Instrumentation/README.md new file mode 100644 index 00000000000..65c8d19fbcb --- /dev/null +++ b/src/PowerShell.Core.Instrumentation/README.md @@ -0,0 +1,5 @@ +# PowerShell.Core.Instrumentation + +The code under `PowerShell.Core.Instrumentation` is being migrated to [PowerShell-native](https://github.com/PowerShell/PowerShell-native) repository. +Please make PRs to the new repository. +Code under here will be removed once the move is complete. \ No newline at end of file diff --git a/src/PowerShell.Core.Instrumentation/version.rc b/src/PowerShell.Core.Instrumentation/version.rc deleted file mode 100644 index 7b797f36032..00000000000 --- a/src/PowerShell.Core.Instrumentation/version.rc +++ /dev/null @@ -1,15 +0,0 @@ -// -// Copyright (C) Microsoft. All rights reserved. -// -#include -#include - -#define VER_FILETYPE VFT_DLL -#define VER_FILESUBTYPE VFT2_UNKNOWN -#define VER_FILEDESCRIPTION_STR "PowerShellCore" -#define VER_INTERNALNAME_STR "PowerShell.Core.Instrumentation.dll" -#define VER_ORIGINALFILENAME_STR "PowerShell.Core.Instrumentation.dll" - -#include "common.ver" - -#include "PowerShell.Core.Instrumentation.rc" diff --git a/src/libpsl-native/.gitignore b/src/libpsl-native/.gitignore deleted file mode 100644 index 0dff6937259..00000000000 --- a/src/libpsl-native/.gitignore +++ /dev/null @@ -1,12 +0,0 @@ -CMakeCache.txt -CMakeFiles -CMakeScripts -Makefile -cmake_install.cmake -install_manifest.txt -CTestTestfile.cmake -Testing/ -test/psl-native-test -src/libpsl-native.so -src/libpsl-native.dylib -test/native-tests.xml diff --git a/src/libpsl-native/CMakeLists.txt b/src/libpsl-native/CMakeLists.txt deleted file mode 100644 index e4f33cce07b..00000000000 --- a/src/libpsl-native/CMakeLists.txt +++ /dev/null @@ -1,25 +0,0 @@ -cmake_minimum_required(VERSION 2.8.11) -project(PSL-NATIVE) - -# Can't use add_compile_options with 2.8.11 -set(CMAKE_BUILD_TYPE "Release") -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall -Werror -fstack-protector-strong -fpie -DFORTIFY_SOURCE=2 -O2") - -if (${CMAKE_SYSTEM_NAME} MATCHES "Linux") - set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-z,relro,-z,now") -elseif (${CMAKE_SYSTEM_NAME} MATCHES "Darwin") - set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl") -endif() - -set(LIBRARY_OUTPUT_PATH "${PROJECT_SOURCE_DIR}/../powershell-unix") - -if (CMAKE_SYSTEM_PROCESSOR MATCHES "arm*") - message(STATUS "Building for ARM, no tests") - add_subdirectory(src) -else () - # test in BUILD_DIR - message(STATUS "Tests enabled") - enable_testing() - add_subdirectory(src) - add_subdirectory(test) -endif () diff --git a/src/libpsl-native/README.md b/src/libpsl-native/README.md index e445e1debd4..70998594406 100644 --- a/src/libpsl-native/README.md +++ b/src/libpsl-native/README.md @@ -1,5 +1,5 @@ # libpsl-native -The code under `powershell-native` is being migrated to [PowerShell-native](https://github.com/PowerShell/PowerShell-native) repository. +The code under `libpsl-native` is being migrated to [PowerShell-native](https://github.com/PowerShell/PowerShell-native) repository. Please make PRs to the new repository. Code under here will be removed once the move is complete. diff --git a/src/libpsl-native/arm.toolchain.cmake b/src/libpsl-native/arm.toolchain.cmake deleted file mode 100644 index c2c68104d81..00000000000 --- a/src/libpsl-native/arm.toolchain.cmake +++ /dev/null @@ -1,20 +0,0 @@ -set(CMAKE_SYSTEM_NAME Linux) -set(CMAKE_SYSTEM_VERSION 1) -set(CMAKE_SYSTEM_PROCESSOR armv7l) -set(CMAKE_CXX_COMPILER arm-linux-gnueabihf-g++ -fstack-protector-strong -fpie -DFORTIFY_SOURCE=2 -O2) -set(CMAKE_SHARED_LINKER_FLAGS "-Wl,-z,relro,-z,now") -set(CMAKE_C_COMPILER arm-linux-gnueabihf-gcc) - -# add_compile_options(-target armv7-linux-gnueabihf) -add_compile_options(-mthumb) -add_compile_options(-mfpu=vfpv3) -add_compile_options(-g) - -set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${CROSS_LINK_FLAGS}" CACHE STRING "" FORCE) -set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${CROSS_LINK_FLAGS}" CACHE STRING "" FORCE) -set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${CROSS_LINK_FLAGS}" CACHE STRING "" FORCE) - -set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) -set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) -set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) -set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) diff --git a/src/libpsl-native/src/.gitignore b/src/libpsl-native/src/.gitignore deleted file mode 100644 index 5c8aecc64be..00000000000 --- a/src/libpsl-native/src/.gitignore +++ /dev/null @@ -1 +0,0 @@ -pal_config.h diff --git a/src/libpsl-native/src/CMakeLists.txt b/src/libpsl-native/src/CMakeLists.txt deleted file mode 100644 index b830e5d9fd0..00000000000 --- a/src/libpsl-native/src/CMakeLists.txt +++ /dev/null @@ -1,37 +0,0 @@ -include(CheckIncludeFiles) - -add_library(psl-native SHARED - getstat.cpp - getpwuid.cpp - getppid.cpp - getuserfrompid.cpp - getfileowner.cpp - getcurrentthreadid.cpp - getcurrentprocessorid.cpp - getusername.cpp - getcomputername.cpp - getlinkcount.cpp - getfullyqualifiedname.cpp - geterrorcategory.cpp - getinodedata.cpp - isfile.cpp - isdirectory.cpp - issamefilesystemitem.cpp - issymlink.cpp - isexecutable.cpp - setdate.cpp - createhardlink.cpp - createsymlink.cpp - followsymlink.cpp - createprocess.cpp - nativesyslog.cpp) - -check_include_files( - "sys/types.h;sys/sysctl.h" - HAVE_SYS_SYSCTL_H) - -configure_file( - ${CMAKE_CURRENT_SOURCE_DIR}/pal_config.h.in - ${CMAKE_CURRENT_BINARY_DIR}/pal_config.h) - -target_include_directories(psl-native PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) diff --git a/src/libpsl-native/src/createhardlink.cpp b/src/libpsl-native/src/createhardlink.cpp deleted file mode 100644 index 2d1f990458b..00000000000 --- a/src/libpsl-native/src/createhardlink.cpp +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief create new hard link - -#include "createhardlink.h" - -#include -#include -#include - -//! @brief Createhardlink create new symbolic link -//! -//! Createhardlink -//! -//! @param[in] link -//! @parblock -//! A pointer to the buffer that contains the symbolic link to create -//! -//! char* is marshaled as an LPStr, which on Linux is UTF-8. -//! @endparblock -//! -//! @param[in] target -//! @parblock -//! A pointer to the buffer that contains the existing file -//! -//! char* is marshaled as an LPStr, which on Linux is UTF-8. -//! @endparblock -//! -//! @retval 0 if successful, otherwise -1 -//! - -int32_t CreateHardLink(const char *newlink, const char *target) -{ - assert(newlink); - assert(target); - - return link(target, newlink); -} diff --git a/src/libpsl-native/src/createhardlink.h b/src/libpsl-native/src/createhardlink.h deleted file mode 100644 index c286934622f..00000000000 --- a/src/libpsl-native/src/createhardlink.h +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "pal.h" - -PAL_BEGIN_EXTERNC - -int32_t CreateHardLink(const char *link, const char *target); - -PAL_END_EXTERNC diff --git a/src/libpsl-native/src/createprocess.cpp b/src/libpsl-native/src/createprocess.cpp deleted file mode 100644 index 299cfd2811d..00000000000 --- a/src/libpsl-native/src/createprocess.cpp +++ /dev/null @@ -1,220 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#include "createprocess.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -enum -{ - SUPPRESS_PROCESS_SIGINT = 0x00000001 -}; - -enum -{ - READ_END_OF_PIPE = 0, - WRITE_END_OF_PIPE = 1 -}; - -static void CloseIfOpen(int fd) -{ - if (fd >= 0) - { - close(fd); // Ignoring errors from close is a deliberate choice - } -} - -// Checks if the IO operation was interrupted and needs to be retried. -// Returns true if the operation was interrupted; otherwise, false. -template -static inline bool CheckInterrupted(TInt result) -{ - return result < 0 && errno == EINTR; -} - -static int Dup2WithInterruptedRetry(int oldfd, int newfd) -{ - int result; - while (CheckInterrupted(result = dup2(oldfd, newfd))); - return result; -} - -int32_t SystemNative_Pipe(int32_t pipeFds[2], int32_t flags) -{ - int32_t result; - while (CheckInterrupted(result = pipe(pipeFds))); - - // Then, if O_CLOEXEC was specified, use fcntl to configure the file descriptors appropriately. - if ((flags & O_CLOEXEC) != 0 && result == 0) - { - while (CheckInterrupted(result = fcntl(pipeFds[0], F_SETFD, FD_CLOEXEC))); - if (result == 0) - { - while (CheckInterrupted(result = fcntl(pipeFds[1], F_SETFD, FD_CLOEXEC))); - } - - if (result != 0) - { - int tmpErrno = errno; - close(pipeFds[0]); - close(pipeFds[1]); - errno = tmpErrno; - } - } - - return result; -} - -int32_t ForkAndExecProcess( - const char* filename, - char* const argv[], - char* const envp[], - const char* cwd, - int32_t redirectStdin, - int32_t redirectStdout, - int32_t redirectStderr, - int32_t creationFlags, - int32_t* childPid, - int32_t* stdinFd, - int32_t* stdoutFd, - int32_t* stderrFd) -{ - int success = true; - int processId = -1; - int stdinFds[2] = { -1, -1 }; - int stdoutFds[2] = { -1, -1 }; - int stderrFds[2] = { -1, -1 }; - - // Validate arguments - if (nullptr == filename || nullptr == argv || nullptr == envp || nullptr == stdinFd || nullptr == stdoutFd || - nullptr == stderrFd || nullptr == childPid) - { - assert(false && "null argument."); - errno = EINVAL; - success = false; - goto done; - } - - if ((redirectStdin & ~1) != 0 || (redirectStdout & ~1) != 0 || (redirectStderr & ~1) != 0) - { - assert(false && "Boolean redirect* inputs must be 0 or 1."); - errno = EINVAL; - success = false; - goto done; - } - - // Make sure we can find and access the executable. exec will do this, of course, but at that point it's already - // in the child process, at which point it'll translate to the child process' exit code rather than to failing - // the Start itself. There's a race condition here, in that this could change prior to exec's checks, but there's - // little we can do about that. There are also more rigorous checks exec does, such as validating the executable - // format of the target; such errors will emerge via the child process' exit code. - if (access(filename, X_OK) != 0) - { - success = false; - goto done; - } - - // Open pipes for any requests to redirect stdin/stdout/stderr - if ((redirectStdin && SystemNative_Pipe(stdinFds, O_CLOEXEC) != 0) || - (redirectStdout && SystemNative_Pipe(stdoutFds, O_CLOEXEC) != 0) || - (redirectStderr && SystemNative_Pipe(stderrFds, O_CLOEXEC) != 0)) - { - success = false; - goto done; - } - - // Fork the child process - if ((processId = fork()) == -1) - { - success = false; - goto done; - } - - if (processId == 0) // processId == 0 if this is child process - { - // For any redirections that should happen, dup the pipe descriptors onto stdin/out/err. - // We don't explicitly close out the old pipe descriptors because they are set to close on execve. - if ((redirectStdin && Dup2WithInterruptedRetry(stdinFds[READ_END_OF_PIPE], STDIN_FILENO) == -1) || - (redirectStdout && Dup2WithInterruptedRetry(stdoutFds[WRITE_END_OF_PIPE], STDOUT_FILENO) == -1) || - (redirectStderr && Dup2WithInterruptedRetry(stderrFds[WRITE_END_OF_PIPE], STDERR_FILENO) == -1)) - { - _exit(errno != 0 ? errno : EXIT_FAILURE); - } - - // Change to the designated working directory, if one was specified - if (nullptr != cwd) - { - int result; - while (CheckInterrupted(result = chdir(cwd))); - if (result == -1) - { - _exit(errno != 0 ? errno : EXIT_FAILURE); - } - } - - // If SUPPRESS_PROCESS_SIGINT was chosen then create a process that ignores - // interrupt signals - if (creationFlags & SUPPRESS_PROCESS_SIGINT) - { - struct sigaction sa, saOld; - memset(&sa, 0, sizeof(sa)); - memset(&saOld, 0, sizeof(saOld)); - sigemptyset(&(sa.sa_mask)); - sa.sa_handler = SIG_IGN; // Ignore the signal - - int result = sigaction(SIGINT, &sa, &saOld); - if (result == -1) - { - _exit(errno != 0 ? errno : EXIT_FAILURE); - } - } - - // Finally, execute the new process. execve will not return if it's successful. - execve(filename, argv, envp); - _exit(errno != 0 ? errno : EXIT_FAILURE); // execve failed - } - - // This is the parent process. processId == pid of the child - *childPid = processId; - *stdinFd = stdinFds[WRITE_END_OF_PIPE]; - *stdoutFd = stdoutFds[READ_END_OF_PIPE]; - *stderrFd = stderrFds[READ_END_OF_PIPE]; - -done: - int priorErrno = errno; - - // Regardless of success or failure, close the parent's copy of the child's end of - // any opened pipes. The parent doesn't need them anymore. - CloseIfOpen(stdinFds[READ_END_OF_PIPE]); - CloseIfOpen(stdoutFds[WRITE_END_OF_PIPE]); - CloseIfOpen(stderrFds[WRITE_END_OF_PIPE]); - - // If we failed, close everything else and give back error values in all out arguments. - if (!success) - { - CloseIfOpen(stdinFds[WRITE_END_OF_PIPE]); - CloseIfOpen(stdoutFds[READ_END_OF_PIPE]); - CloseIfOpen(stderrFds[READ_END_OF_PIPE]); - - *stdinFd = -1; - *stdoutFd = -1; - *stderrFd = -1; - *childPid = -1; - - errno = priorErrno; - return -1; - } - - return 0; -} diff --git a/src/libpsl-native/src/createprocess.h b/src/libpsl-native/src/createprocess.h deleted file mode 100644 index af6afe40998..00000000000 --- a/src/libpsl-native/src/createprocess.h +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "pal.h" -#include - -PAL_BEGIN_EXTERNC - -int32_t ForkAndExecProcess( - const char* filename, // filename argument to execve - char* const argv[], // argv argument to execve - char* const envp[], // envp argument to execve - const char* cwd, // path passed to chdir in child process - int32_t redirectStdin, // whether to redirect standard input from the parent - int32_t redirectStdout, // whether to redirect standard output to the parent - int32_t redirectStderr, // whether to redirect standard error to the parent - int32_t creationFlags, // creation flags - int32_t* childPid, // [out] the child process' id - int32_t* stdinFd, // [out] if redirectStdin, the parent's fd for the child's stdin - int32_t* stdoutFd, // [out] if redirectStdout, the parent's fd for the child's stdout - int32_t* stderrFd); // [out] if redirectStderr, the parent's fd for the child's stderr - -PAL_END_EXTERNC diff --git a/src/libpsl-native/src/createsymlink.cpp b/src/libpsl-native/src/createsymlink.cpp deleted file mode 100644 index a652417e83b..00000000000 --- a/src/libpsl-native/src/createsymlink.cpp +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief create new symbolic link - -#include "createsymlink.h" - -#include -#include -#include -#include - -//! @brief Createsymlink create new symbolic link -//! -//! Createsymlink -//! -//! @param[in] link -//! @parblock -//! A pointer to the buffer that contains the symbolic link to create -//! -//! char* is marshaled as an LPStr, which on Linux is UTF-8. -//! @endparblock -//! -//! @param[in] target -//! @parblock -//! A pointer to the buffer that contains the existing file -//! -//! char* is marshaled as an LPStr, which on Linux is UTF-8. -//! @endparblock -//! -//! @retval 0 if successful, -1 otherwise -//! - -int32_t CreateSymLink(const char *link, const char *target) -{ - assert(link); - assert(target); - - errno = 0; - - return symlink(target, link); -} diff --git a/src/libpsl-native/src/createsymlink.h b/src/libpsl-native/src/createsymlink.h deleted file mode 100644 index 6f9252c85fa..00000000000 --- a/src/libpsl-native/src/createsymlink.h +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "pal.h" - -#include - -PAL_BEGIN_EXTERNC - -int32_t CreateSymLink(const char *link, const char *target); - -PAL_END_EXTERNC diff --git a/src/libpsl-native/src/followsymlink.cpp b/src/libpsl-native/src/followsymlink.cpp deleted file mode 100644 index 215130b3fe3..00000000000 --- a/src/libpsl-native/src/followsymlink.cpp +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief returns whether a path is a symbolic link - -#include "followsymlink.h" -#include "issymlink.h" - -#include -#include -#include -#include - -//! @brief FollowSymLink determines target path of a sym link -//! -//! @param[in] fileName -//! @parblock -//! A pointer to the buffer that contains the file name -//! -//! char* is marshaled as an LPStr, which on Linux is UTF-8. -//! @endparblock -//! -//! @retval target path, or NULL if unsuccessful -//! - -char* FollowSymLink(const char* fileName) -{ - assert(fileName); - errno = 0; - - // return null for non symlinks - if (!IsSymLink(fileName)) - { - return NULL; - } - - // attempt to resolve with the absolute file path - char buffer[PATH_MAX]; - char* realPath = realpath(fileName, buffer); - - if (realPath) - { - return strndup(realPath, strnlen(realPath, PATH_MAX)); - } - - // if the path wasn't resolved, use readlink - ssize_t sz = readlink(fileName, buffer, PATH_MAX); - if (sz == -1) - { - return NULL; - } - - buffer[sz] = '\0'; - return strndup(buffer, sz + 1); -} diff --git a/src/libpsl-native/src/followsymlink.h b/src/libpsl-native/src/followsymlink.h deleted file mode 100644 index 27f034477f6..00000000000 --- a/src/libpsl-native/src/followsymlink.h +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "pal.h" - -PAL_BEGIN_EXTERNC - -char* FollowSymLink(const char* fileName); - -PAL_END_EXTERNC diff --git a/src/libpsl-native/src/getcomputername.cpp b/src/libpsl-native/src/getcomputername.cpp deleted file mode 100644 index 89c54aa356b..00000000000 --- a/src/libpsl-native/src/getcomputername.cpp +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief Implements GetComputerName Win32 API - -#include "getcomputername.h" - -#include -#include -#include - -//! @brief GetComputerName retrieves the name of the host associated with -//! the current thread. -//! -//! @retval username as UTF-8 string, or null if unsuccessful - -char* GetComputerName() -{ - errno = 0; - // Get computername from system, note that gethostname(2) gets the - // nodename from uname - std::string computername(_POSIX_HOST_NAME_MAX, 0); - int32_t ret = gethostname(&computername[0], computername.length()); - // Map errno to Win32 Error Codes - if (ret != 0) - { - return NULL; - } - - return strdup(computername.c_str()); -} diff --git a/src/libpsl-native/src/getcomputername.h b/src/libpsl-native/src/getcomputername.h deleted file mode 100644 index 17d456080f4..00000000000 --- a/src/libpsl-native/src/getcomputername.h +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "pal.h" - -PAL_BEGIN_EXTERNC - -char *GetComputerName(); - -PAL_END_EXTERNC diff --git a/src/libpsl-native/src/getcurrentprocessorid.cpp b/src/libpsl-native/src/getcurrentprocessorid.cpp deleted file mode 100644 index 0bc168e2e7b..00000000000 --- a/src/libpsl-native/src/getcurrentprocessorid.cpp +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#include "getcurrentprocessorid.h" - -#include - -pid_t GetCurrentProcessId() -{ - return getpid(); -} diff --git a/src/libpsl-native/src/getcurrentprocessorid.h b/src/libpsl-native/src/getcurrentprocessorid.h deleted file mode 100644 index b0092d19b0a..00000000000 --- a/src/libpsl-native/src/getcurrentprocessorid.h +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "pal.h" -#include - -PAL_BEGIN_EXTERNC - -pid_t GetCurrentProcessId(); - -PAL_END_EXTERNC - diff --git a/src/libpsl-native/src/getcurrentthreadid.cpp b/src/libpsl-native/src/getcurrentthreadid.cpp deleted file mode 100644 index c1863949a03..00000000000 --- a/src/libpsl-native/src/getcurrentthreadid.cpp +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#include "getcurrentthreadid.h" - -#include -#include -#include -#include - -pid_t GetCurrentThreadId() -{ - pid_t tid = 0; -#if defined(__linux__) - tid = syscall(SYS_gettid); -#elif defined(__APPLE__) && defined(__MACH__) - uint64_t tid64; - pthread_threadid_np(NULL, &tid64); - tid = (pid_t)tid64; -#endif - return tid; -} diff --git a/src/libpsl-native/src/getcurrentthreadid.h b/src/libpsl-native/src/getcurrentthreadid.h deleted file mode 100644 index 3ac30648369..00000000000 --- a/src/libpsl-native/src/getcurrentthreadid.h +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "pal.h" - -#include - -PAL_BEGIN_EXTERNC - -pid_t GetCurrentThreadId(); - -PAL_END_EXTERNC diff --git a/src/libpsl-native/src/geterrorcategory.cpp b/src/libpsl-native/src/geterrorcategory.cpp deleted file mode 100644 index f436899a701..00000000000 --- a/src/libpsl-native/src/geterrorcategory.cpp +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#include "geterrorcategory.h" - -#include -#include -#include -#include -#include - -// Copy of PowerShell ErrorCategory enum from ErrorPackage.cs -enum ErrorCategory { - NotSpecified = 0, - OpenError = 1, - CloseError = 2, - DeviceError = 3, - DeadlockDetected = 4, - InvalidArgument = 5, - InvalidData = 6, - InvalidOperation = 7, - InvalidResult = 8, - InvalidType = 9, - MetadataError = 10, - NotImplemented = 11, - NotInstalled = 12, - ObjectNotFound = 13, - OperationStopped = 14, - OperationTimeout = 15, - SyntaxError = 16, - ParserError = 17, - PermissionDenied = 18, - ResourceBusy = 19, - ResourceExists = 20, - ResourceUnavailable = 21, - ReadError = 22, - WriteError = 23, - FromStdErr = 24, - SecurityError = 25, - ProtocolError = 26, - ConnectionError = 27, - AuthenticationError = 28, - LimitsExceeded = 29, - QuotaExceeded = 30, - NotEnabled = 31, -}; - -//! @brief Maps Linux errno to PowerShell ErrorCategory -int32_t GetErrorCategory(int32_t errnum) -{ - switch (errnum) - { - case EINVAL: - return InvalidArgument; - case ENOENT: - case ESRCH: - return ObjectNotFound; - case EINTR: - return OperationStopped; - case EACCES: - case EPERM: - return PermissionDenied; - default: - return NotSpecified; - } -} diff --git a/src/libpsl-native/src/geterrorcategory.h b/src/libpsl-native/src/geterrorcategory.h deleted file mode 100644 index 4310bdc4433..00000000000 --- a/src/libpsl-native/src/geterrorcategory.h +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "pal.h" - -PAL_BEGIN_EXTERNC - -int32_t GetErrorCategory(int32_t); - -PAL_END_EXTERNC diff --git a/src/libpsl-native/src/getfileowner.cpp b/src/libpsl-native/src/getfileowner.cpp deleted file mode 100644 index 1443f3074cd..00000000000 --- a/src/libpsl-native/src/getfileowner.cpp +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief returns the owner of a file - -#include "getstat.h" -#include "getpwuid.h" -#include "getfileowner.h" - -#include -#include -#include -#include -#include -#include -#include - -//! @brief GetFileOwner returns the owner of a file -//! -//! GetFileOwner -//! -//! @param[in] fileName -//! @parblock -//! A pointer to the buffer that contains the file name -//! -//! char* is marshaled as an LPStr, which on Linux is UTF-8. -//! @endparblock -//! -//! @retval file owner, or NULL if unsuccessful -//! -char* GetFileOwner(const char* fileName) -{ - assert(fileName); - errno = 0; - - struct stat buf; - int32_t ret = GetStat(fileName, &buf); - if (ret != 0) - { - return NULL; - } - - return GetPwUid(buf.st_uid); -} diff --git a/src/libpsl-native/src/getfileowner.h b/src/libpsl-native/src/getfileowner.h deleted file mode 100644 index 1d4578844dc..00000000000 --- a/src/libpsl-native/src/getfileowner.h +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "pal.h" - -PAL_BEGIN_EXTERNC - -char* GetFileOwner(const char* fileName); - -PAL_END_EXTERNC diff --git a/src/libpsl-native/src/getfullyqualifiedname.cpp b/src/libpsl-native/src/getfullyqualifiedname.cpp deleted file mode 100644 index 51df25a07ff..00000000000 --- a/src/libpsl-native/src/getfullyqualifiedname.cpp +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief Implements GetFullyQualifiedName on Linux - -#include "getcomputername.h" -#include "getfullyqualifiedname.h" - -#include -#include -#include -#include - -//! @brief GetFullyQualifiedName retrieves the fully qualified dns name of the host -//! -//! @retval username as UTF-8 string, or null if unsuccessful -char *GetFullyQualifiedName() -{ - errno = 0; - - char *computerName = GetComputerName(); - if (computerName == NULL) - { - return NULL; - } - - struct addrinfo hints, *info; - - memset(&hints, 0, sizeof hints); - hints.ai_family = AF_UNSPEC; /*either IPV4 or IPV6*/ - hints.ai_socktype = SOCK_STREAM; - hints.ai_flags = AI_CANONNAME; - - /* There are several ways to get the domain name: - * uname(2), gethostbyname(3), resolver(3), getdomainname(2), - * and getaddrinfo(3). Some of these are not portable, some aren't - * POSIX compliant, and some are being deprecated. getaddrinfo seems - * to be the best choice. - */ - char *fullName = NULL; - if (getaddrinfo(computerName, "http", &hints, &info) != 0) - { - goto exit; - } - - // return the first canonical name in the list - fullName = strndup(info->ai_canonname, strnlen(info->ai_canonname, NI_MAXHOST)); - - // only free info if getaddrinfo was successful - freeaddrinfo(info); -exit: - free(computerName); - return fullName; -} diff --git a/src/libpsl-native/src/getfullyqualifiedname.h b/src/libpsl-native/src/getfullyqualifiedname.h deleted file mode 100644 index a9fb2632517..00000000000 --- a/src/libpsl-native/src/getfullyqualifiedname.h +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "pal.h" - -PAL_BEGIN_EXTERNC - -char *GetFullyQualifiedName(); - -PAL_END_EXTERNC diff --git a/src/libpsl-native/src/getinodedata.cpp b/src/libpsl-native/src/getinodedata.cpp deleted file mode 100644 index 3534eac3b62..00000000000 --- a/src/libpsl-native/src/getinodedata.cpp +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief Retrieve the device ID and inode number of a file - -#include "getinodedata.h" - -#include -#include -#include -#include -#include -#include -#include - -//! @brief GetInodeData retrieves a file's device and inode information. -//! -//! GetInodeData -//! -//! @param[in] fileName -//! @parblock -//! A pointer to the buffer that contains the file path -//! -//! char* is marshaled as an LPStr, which on Linux is UTF-8. -//! @endparblock -//! -//! @param[out] device -//! @parblock -//! Points to a uint64_t value that will contain the file's device ID. -//! @endparblock -//! -//! @param[out] inode -//! @parblock -//! Points to a uint64_t value that will contain the file's inode number. -//! @endparblock -//! -//! @retval 0 If the function succeeds, -1 otherwise. -//! - -int32_t GetInodeData(const char* fileName, uint64_t* device, uint64_t* inode) -{ - assert(fileName); - assert(device); - assert(inode); - errno = 0; - - struct stat statBuf; - int ret = stat(fileName, &statBuf); - - if (ret == 0) - { - *device = statBuf.st_dev; - *inode = statBuf.st_ino; - } - - return ret; -} diff --git a/src/libpsl-native/src/getinodedata.h b/src/libpsl-native/src/getinodedata.h deleted file mode 100644 index ed21b61bf6f..00000000000 --- a/src/libpsl-native/src/getinodedata.h +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "pal.h" - -PAL_BEGIN_EXTERNC - -int32_t GetInodeData(const char* fileName, uint64_t* device, uint64_t* inode); - -PAL_END_EXTERNC diff --git a/src/libpsl-native/src/getlinkcount.cpp b/src/libpsl-native/src/getlinkcount.cpp deleted file mode 100644 index 6c4283b51aa..00000000000 --- a/src/libpsl-native/src/getlinkcount.cpp +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief Retrieve link count of a file - -#include "getlinkcount.h" - -#include -#include -#include -#include -#include -#include -#include - -//! @brief GetLinkCount retrieves the file link count (number of hard links) -//! for the given file -//! -//! GetLinkCount -//! -//! @param[in] fileName -//! @parblock -//! A pointer to the buffer that contains the file name -//! -//! char* is marshaled as an LPStr, which on Linux is UTF-8. -//! @endparblock -//! -//! @param[out] count -//! @parblock -//! This function returns the number of hard links associated with this file -//! @endparblock -//! -//! @retval 1 If the function succeeds, and the variable pointed to by buffer contains -//! information about the files -//! @retval 0 If the function fails, the return value is zero. To get -//! extended error information, call GetLastError. -//! - -int32_t GetLinkCount(const char* fileName, int32_t *count) -{ - assert(fileName); - assert(count); - errno = 0; - - struct stat statBuf; - - int32_t ret = lstat(fileName, &statBuf); - - *count = statBuf.st_nlink; - return ret; -} diff --git a/src/libpsl-native/src/getlinkcount.h b/src/libpsl-native/src/getlinkcount.h deleted file mode 100644 index 1b3dfd90304..00000000000 --- a/src/libpsl-native/src/getlinkcount.h +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "pal.h" - -PAL_BEGIN_EXTERNC - -int32_t GetLinkCount(const char* fileName, int32_t *count); - -PAL_END_EXTERNC diff --git a/src/libpsl-native/src/getppid.cpp b/src/libpsl-native/src/getppid.cpp deleted file mode 100644 index 7f64e285e06..00000000000 --- a/src/libpsl-native/src/getppid.cpp +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#include "pal_config.h" -#include "getppid.h" - -#include -#include - -#if HAVE_SYS_SYSCTL_H -#include -#endif - -//! @brief GetPPid returns the parent process id for a process -//! -//! GetPPid -//! -//! @param[in] pid -//! @parblock -//! The process id to query for it's parent. -//! @endparblock -//! -//! @retval the parent process id, or UINT_MAX if unsuccessful -//! -pid_t GetPPid(pid_t pid) -{ - -#if defined(__APPLE__) && defined(__MACH__) - - const pid_t PIDUnknown = UINT_MAX; - struct kinfo_proc info; - size_t length = sizeof(struct kinfo_proc); - int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid}; - if (sysctl(mib, 4, &info, &length, NULL, 0) < 0) - return PIDUnknown; - if (length == 0) - return PIDUnknown; - - return info.kp_eproc.e_ppid; - -#else - - return UINT_MAX; - -#endif -} diff --git a/src/libpsl-native/src/getppid.h b/src/libpsl-native/src/getppid.h deleted file mode 100644 index 7b7244f4b0d..00000000000 --- a/src/libpsl-native/src/getppid.h +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "pal.h" -#include - -PAL_BEGIN_EXTERNC - -pid_t GetPPid(pid_t pid); - -PAL_END_EXTERNC diff --git a/src/libpsl-native/src/getpwuid.cpp b/src/libpsl-native/src/getpwuid.cpp deleted file mode 100644 index a3b4a21ecae..00000000000 --- a/src/libpsl-native/src/getpwuid.cpp +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief returns the username for a uid - -#include "getpwuid.h" - -#include -#include -#include -#include -#include -#include - -//! @brief GetPwUid returns the username for a uid -//! -//! GetPwUid -//! -//! @param[in] uid -//! @parblock -//! The user identifier to lookup. -//! @endparblock -//! -//! @retval username as UTF-8 string, or NULL if unsuccessful -//! -char* GetPwUid(uid_t uid) -{ - int32_t ret = 0; - struct passwd pwd; - struct passwd* result = NULL; - char* buf; - - int buflen = sysconf(_SC_GETPW_R_SIZE_MAX); - if (buflen < 1) - { - buflen = 2048; - } - -allocate: - buf = (char*)calloc(buflen, sizeof(char)); - - errno = 0; - ret = getpwuid_r(uid, &pwd, buf, buflen, &result); - - if (ret != 0) - { - if (errno == ERANGE) - { - free(buf); - buflen *= 2; - goto allocate; - } - return NULL; - } - - // no result - if (result == NULL) - { - return NULL; - } - - // allocate copy on heap so CLR can free it - size_t userlen = strnlen(pwd.pw_name, buflen); - char* username = strndup(pwd.pw_name, userlen); - free(buf); - return username; -} diff --git a/src/libpsl-native/src/getpwuid.h b/src/libpsl-native/src/getpwuid.h deleted file mode 100644 index 939345eb030..00000000000 --- a/src/libpsl-native/src/getpwuid.h +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "pal.h" - -#include - -PAL_BEGIN_EXTERNC - -char* GetPwUid(uid_t uid); - -PAL_END_EXTERNC diff --git a/src/libpsl-native/src/getstat.cpp b/src/libpsl-native/src/getstat.cpp deleted file mode 100644 index 2cc6f66ce36..00000000000 --- a/src/libpsl-native/src/getstat.cpp +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief returns the stat of a file - -#include "getstat.h" - -#include -#include -#include -#include -#include -#include -#include - -//! @brief GetStat returns the stat of a file. This simply delegates to the -//! stat() system call and maps errno to the expected values for GetLastError. -//! -//! GetStat -//! -//! @param[in] path -//! @parblock -//! A pointer to the buffer that contains the file name -//! -//! char* is marshaled as an LPStr, which on Linux is UTF-8. -//! @endparblock -//! -//! @param[in] stat -//! @parblock -//! A pointer to the buffer in which to place the stat information -//! @endparblock -//! -//! @retval 0 if successful -//! @retval -1 if failed -//! - -// DO NOT use in managed code -// use externally defined structs in managed code has proven to be buggy -// (memory corruption issues due to layout difference between platforms) -// see https://github.com/dotnet/corefx/issues/29700#issuecomment-389313075 -int32_t GetStat(const char* path, struct stat* buf) -{ - assert(path); - errno = 0; - - return stat(path, buf); -} diff --git a/src/libpsl-native/src/getstat.h b/src/libpsl-native/src/getstat.h deleted file mode 100644 index 12270e0e61b..00000000000 --- a/src/libpsl-native/src/getstat.h +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "pal.h" - -#include - -PAL_BEGIN_EXTERNC - -int32_t GetStat(const char* path, struct stat* buf); - -PAL_END_EXTERNC diff --git a/src/libpsl-native/src/getuserfrompid.cpp b/src/libpsl-native/src/getuserfrompid.cpp deleted file mode 100644 index fe34733a235..00000000000 --- a/src/libpsl-native/src/getuserfrompid.cpp +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#include "pal.h" -#include "pal_config.h" -#include "getfileowner.h" -#include "getpwuid.h" -#include "getuserfrompid.h" - -#include -#include -#include - -#if HAVE_SYS_SYSCTL_H -#include -#endif - -char* GetUserFromPid(pid_t pid) -{ - -#if defined(__linux__) - - // Get effective owner of pid from procfs - std::stringstream ss; - ss << "/proc/" << pid; - std::string path; - ss >> path; - - return GetFileOwner(path.c_str()); - -#elif defined(__APPLE__) && defined(__MACH__) - - // Get effective owner of pid from sysctl - struct kinfo_proc oldp; - size_t oldlenp = sizeof(oldp); - int name[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid}; - u_int namelen = sizeof(name)/sizeof(int); - - // Read-only query - int ret = sysctl(name, namelen, &oldp, &oldlenp, NULL, 0); - if (ret != 0 || oldlenp == 0) - { - return NULL; - } - - return GetPwUid(oldp.kp_eproc.e_ucred.cr_uid); - -#else - - return NULL; - -#endif - -} diff --git a/src/libpsl-native/src/getuserfrompid.h b/src/libpsl-native/src/getuserfrompid.h deleted file mode 100644 index 1c58dcb30e2..00000000000 --- a/src/libpsl-native/src/getuserfrompid.h +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "pal.h" - -#include - -PAL_BEGIN_EXTERNC - -char* GetUserFromPid(pid_t pid); - -PAL_END_EXTERNC diff --git a/src/libpsl-native/src/getusername.cpp b/src/libpsl-native/src/getusername.cpp deleted file mode 100644 index ed694f16a5b..00000000000 --- a/src/libpsl-native/src/getusername.cpp +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief Implements GetUserName for Linux - -#include "getpwuid.h" -#include "getusername.h" - -#include - -//! @brief GetUserName retrieves the name of the user associated with -//! the current thread. -//! -//! @retval username as UTF-8 string, or null if unsuccessful -char* GetUserName() -{ - // geteuid() gets the effective user ID of the calling process, and is always successful - return GetPwUid(geteuid()); -} diff --git a/src/libpsl-native/src/getusername.h b/src/libpsl-native/src/getusername.h deleted file mode 100644 index e9461c715ec..00000000000 --- a/src/libpsl-native/src/getusername.h +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "pal.h" - -PAL_BEGIN_EXTERNC - -char* GetUserName(); - -PAL_END_EXTERNC diff --git a/src/libpsl-native/src/isdirectory.cpp b/src/libpsl-native/src/isdirectory.cpp deleted file mode 100644 index 1123dc5af68..00000000000 --- a/src/libpsl-native/src/isdirectory.cpp +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief returns if the path is a directory - -#include "getstat.h" -#include "getpwuid.h" -#include "getfileowner.h" -#include "isdirectory.h" - -#include -#include -#include -#include -#include -#include - -//! @brief returns if the path is a directory; uses stat and so follows symlinks -//! -//! IsDirectory -//! -//! @param[in] path -//! @parblock -//! A pointer to the buffer that contains the file name -//! -//! char* is marshaled as an LPStr, which on Linux is UTF-8. -//! @endparblock -//! -//! @retval true if directory, false otherwise -//! -bool IsDirectory(const char* path) -{ - assert(path); - - struct stat buf; - int32_t ret = GetStat(path, &buf); - if (ret != 0) - { - return false; - } - - return S_ISDIR(buf.st_mode); -} diff --git a/src/libpsl-native/src/isdirectory.h b/src/libpsl-native/src/isdirectory.h deleted file mode 100644 index a89e9021836..00000000000 --- a/src/libpsl-native/src/isdirectory.h +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "pal.h" - -#include - -PAL_BEGIN_EXTERNC - -bool IsDirectory(const char* path); - -PAL_END_EXTERNC diff --git a/src/libpsl-native/src/isexecutable.cpp b/src/libpsl-native/src/isexecutable.cpp deleted file mode 100644 index c4123797506..00000000000 --- a/src/libpsl-native/src/isexecutable.cpp +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief returns whether a file is executable - -#include "isexecutable.h" - -#include -#include -#include - -//! @brief IsExecutable determines if path is executable -//! -//! IsExecutable -//! -//! @param[in] path -//! @parblock -//! A pointer to the buffer that contains the file name -//! -//! char* is marshaled as an LPStr, which on Linux is UTF-8. -//! @endparblock -//! -//! @retval true if path is an executable, false otherwise -//! - -bool IsExecutable(const char* path) -{ - assert(path); - - return access(path, X_OK) != -1; -} diff --git a/src/libpsl-native/src/isexecutable.h b/src/libpsl-native/src/isexecutable.h deleted file mode 100644 index c04a4785251..00000000000 --- a/src/libpsl-native/src/isexecutable.h +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "pal.h" - -#include - -PAL_BEGIN_EXTERNC - -bool IsExecutable(const char* path); - -PAL_END_EXTERNC diff --git a/src/libpsl-native/src/isfile.cpp b/src/libpsl-native/src/isfile.cpp deleted file mode 100644 index 531282d5856..00000000000 --- a/src/libpsl-native/src/isfile.cpp +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief returns if the path exists - -#include "isfile.h" - -#include -#include -#include -#include -#include -#include -#include - -//! @brief returns if the path is a file or directory -//! -//! IsFile -//! -//! @param[in] path -//! @parblock -//! A pointer to the buffer that contains the file name -//! -//! char* is marshaled as an LPStr, which on Linux is UTF-8. -//! @endparblock -//! -//! @retval true if path exists, false otherwise -//! -bool IsFile(const char* path) -{ - assert(path); - - struct stat buf; - return lstat(path, &buf) == 0; -} diff --git a/src/libpsl-native/src/isfile.h b/src/libpsl-native/src/isfile.h deleted file mode 100644 index a7f5adf082c..00000000000 --- a/src/libpsl-native/src/isfile.h +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "pal.h" - -#include - -PAL_BEGIN_EXTERNC - -bool IsFile(const char* path); - -PAL_END_EXTERNC diff --git a/src/libpsl-native/src/issamefilesystemitem.cpp b/src/libpsl-native/src/issamefilesystemitem.cpp deleted file mode 100644 index ce8143582be..00000000000 --- a/src/libpsl-native/src/issamefilesystemitem.cpp +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief Determines whether two paths ultimately point to the same filesystem object - -#include "getstat.h" -#include "issamefilesystemitem.h" - -#include -#include -#include -#include - -//! @brief Returns a boolean value indicating whether two paths ultimately refer to the same file or directory. -//! -//! IsSameFileSystemItem -//! -//! @param[in] path_one -//! @parblock -//! A pointer to the buffer that contains the first path. -//! -//! char* is marshaled as an LPStr, which on Linux is UTF-8. -//! @endparblock -//! -//! @param[in] path_two -//! @parblock -//! A pointer to the buffer that contains the second path. -//! -//! char* is marshaled as an LPStr, which on Linux is UTF-8. -//! @endparblock -//! -//! @retval true if both paths point to the same filesystem object, -//! false otherwise -//! -bool IsSameFileSystemItem(const char* path_one, const char* path_two) -{ - assert(path_one); - assert(path_two); - - struct stat buf_1; - struct stat buf_2; - - if (GetStat(path_one, &buf_1) == 0 && GetStat(path_two, &buf_2) == 0) - { - return buf_1.st_dev == buf_2.st_dev && buf_1.st_ino == buf_2.st_ino; - } - - return false; -} diff --git a/src/libpsl-native/src/issamefilesystemitem.h b/src/libpsl-native/src/issamefilesystemitem.h deleted file mode 100644 index c2c89718260..00000000000 --- a/src/libpsl-native/src/issamefilesystemitem.h +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "pal.h" - -#include - -PAL_BEGIN_EXTERNC - -bool IsSameFileSystemItem(const char* path_one, const char* path_two); - -PAL_END_EXTERNC diff --git a/src/libpsl-native/src/issymlink.cpp b/src/libpsl-native/src/issymlink.cpp deleted file mode 100644 index 7fd518704f9..00000000000 --- a/src/libpsl-native/src/issymlink.cpp +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief returns whether a path is a symbolic link - -#include "issymlink.h" - -#include -#include -#include -#include -#include - -//! @brief IsSymlink determines if path is a symbolic link -//! -//! IsSymlink -//! -//! @param[in] path -//! @parblock -//! A pointer to the buffer that contains the file name -//! -//! char* is marshaled as an LPStr, which on Linux is UTF-8. -//! @endparblock -//! -//! @retval true if path is a symbolic link, false otherwise -//! - -bool IsSymLink(const char* path) -{ - assert(path); - - struct stat buf; - int32_t ret = lstat(path, &buf); - if (ret != 0) - { - return false; - } - - return S_ISLNK(buf.st_mode); -} diff --git a/src/libpsl-native/src/issymlink.h b/src/libpsl-native/src/issymlink.h deleted file mode 100644 index d0a1830ac0e..00000000000 --- a/src/libpsl-native/src/issymlink.h +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "pal.h" - -#include - -PAL_BEGIN_EXTERNC - -bool IsSymLink(const char* path); - -PAL_END_EXTERNC diff --git a/src/libpsl-native/src/nativesyslog.cpp b/src/libpsl-native/src/nativesyslog.cpp deleted file mode 100755 index 130481d0e73..00000000000 --- a/src/libpsl-native/src/nativesyslog.cpp +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @file nativesyslog.cpp -//! @brief Provides wrappers around the syslog apis to support exporting -//! for PInvoke calls by powershell. -//! These functions are intended only for PowerShell internal use. -//! To view log output in real time -//! On Linux -//! tail -f /var/log/syslog | grep powershell -//! On OSX -//! sudo log stream -//! NOTE: replace powershell with the LogIdentity value when overriding in configuration -#include -#include - -#if defined(__APPLE__) && defined(__MACH__) - -#include -#include -static os_log_t _log = NULL; - -// This format string ensures the message string for the log statements -// are visible. Using just %s marks them as private and the do not show -// up with log stream. -#define MESSAGE_FORMAT "%{public}s" - -// The submodule name to pass to os_log_create. -// The passed in ident value will be used for the category. -// see man os_log_create -#define SUBMODULE_NAME "com.microsoft.powershell" - -#endif - -//! @brief Native_SysLog is a wrapper around the syslog api. -//! It explicitly passes the message as a parameter to a %s format -//! string since the message may have arbitrary characters that can -//! be misinterpreted as format specifiers. -//! -//! @retval none. -extern "C" void Native_SysLog(int32_t priority, const char* message) -{ -#if defined(__APPLE__) && defined(__MACH__) - switch (priority) - { - case LOG_EMERG: - case LOG_ALERT: - case LOG_CRIT: - os_log_fault(_log, MESSAGE_FORMAT, message); - break; - - case LOG_ERR: - os_log_error(_log, MESSAGE_FORMAT, message); - break; - - case LOG_DEBUG: - os_log_debug(_log, MESSAGE_FORMAT, message); - break; - - default: - os_log(_log, MESSAGE_FORMAT, message); - break; - } -#else - syslog(priority, "%s", message); -#endif -} - -//! @brief Native_OpenLog is a wrapper around the openlog, syslog api. -//! it allows passing an ident and facility but uses an explicit -//! option value for consistent logging across powershell instances. -//! -//! @retval none. -extern "C" void Native_OpenLog(const char* ident, int facility) -{ -#if defined(__APPLE__) && defined(__MACH__) - _log = os_log_create(SUBMODULE_NAME, ident); -#else - openlog(ident, LOG_NDELAY | LOG_PID, facility); -#endif -} - -//! @brief Native_OpenLog is a wrapper around the closelog, syslog api. -//! -//! @retval none. -extern "C" void Native_CloseLog() -{ -#if defined(__APPLE__) && defined(__MACH__) - // Nothing to do here now, for now. -#else - closelog(); -#endif -} diff --git a/src/libpsl-native/src/nativesyslog.h b/src/libpsl-native/src/nativesyslog.h deleted file mode 100644 index d2613007cec..00000000000 --- a/src/libpsl-native/src/nativesyslog.h +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "pal.h" - -PAL_BEGIN_EXTERNC - -void Native_OpenLog(const char* ident, int facility); -void Native_SysLog(int32_t priority, const char* message); -void Native_CloseLog(); - -PAL_END_EXTERNC diff --git a/src/libpsl-native/src/pal.h b/src/libpsl-native/src/pal.h deleted file mode 100644 index 2323be806f0..00000000000 --- a/src/libpsl-native/src/pal.h +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include -#include -#include -#include - -/* -**============================================================================== -** -** PAL_BEGIN_EXTERNC -** PAL_END_EXTERNC -** -**============================================================================== -*/ - -#if defined(__cplusplus) -# define PAL_BEGIN_EXTERNC extern "C" { -# define PAL_END_EXTERNC } -#else -# define PAL_BEGIN_EXTERNC -# define PAL_END_EXTERNC -#endif - diff --git a/src/libpsl-native/src/pal_config.h.in b/src/libpsl-native/src/pal_config.h.in deleted file mode 100644 index f1d702d76b6..00000000000 --- a/src/libpsl-native/src/pal_config.h.in +++ /dev/null @@ -1,3 +0,0 @@ -#pragma once - -#cmakedefine01 HAVE_SYS_SYSCTL_H diff --git a/src/libpsl-native/src/setdate.cpp b/src/libpsl-native/src/setdate.cpp deleted file mode 100644 index 334d70ba066..00000000000 --- a/src/libpsl-native/src/setdate.cpp +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief set local/system date and time - -#include "setdate.h" - -#include -#include -#include -#include -#include -#include -#include - -//! @brief SetDate sets the date and time on local computer. -//! You must be super-user to set the time. -//! See comment in setdate.h about the use of private_tm -//! -//! SetDate -//! -//! @retval 0 successfully set date -//! @retval -1 if failure occurred. -//! -int32_t SetDate(struct private_tm* time) -{ - errno = 0; - - // Select locale from environment - setlocale(LC_ALL, ""); - - struct timeval tv; - int32_t result = GetTimeVal(*time,tv); - if(result != 0) - { - return result; - } - - return settimeofday(&tv, NULL); -} - -static int32_t GetTimeVal(struct private_tm& time, struct timeval& tv) -{ - struct tm nativeTime = {0}; - nativeTime.tm_hour = static_cast(time.Hour); - nativeTime.tm_isdst = static_cast(time.IsDst); - nativeTime.tm_mday = static_cast(time.DayOfMonth); - nativeTime.tm_min = static_cast(time.Minutes); - nativeTime.tm_mon = static_cast(time.Month); - nativeTime.tm_sec = static_cast(time.Seconds); - nativeTime.tm_wday = static_cast(time.DayOfWeek); - nativeTime.tm_yday = static_cast(time.DayInYear); - nativeTime.tm_year = static_cast(time.Year); - - time_t newTime = mktime(&nativeTime); - if (newTime == -1) - { - return -1; - } - - tv.tv_sec = newTime; - tv.tv_usec = 0; - - return 0; -} diff --git a/src/libpsl-native/src/setdate.h b/src/libpsl-native/src/setdate.h deleted file mode 100644 index 4d69f1e0a7c..00000000000 --- a/src/libpsl-native/src/setdate.h +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "pal.h" - -#include - -PAL_BEGIN_EXTERNC - -int32_t SetDate(struct private_tm* time); - -static int32_t GetTimeVal(struct private_tm& time, struct timeval& tv); - -PAL_END_EXTERNC - -// Using a private struct because theuse externally defined structs -// in managed code has proven to be buggy -// (memory corruption issues due to layout difference between platforms) -// see https://github.com/dotnet/corefx/issues/29700#issuecomment-389313075 -#pragma pack(push, 4) // exact fit - no padding -struct private_tm -{ - int32_t Seconds; /* Seconds (0-60) */ - int32_t Minutes; /* Minutes (0-59) */ - int32_t Hour; /* Hours (0-23) */ - int32_t DayOfMonth;/* Day of the month (1-31) */ - int32_t Month; /* Month (0-11) */ - int32_t Year; /* Year - 1900 */ - int32_t DayOfWeek; /* Day of the week (0-6, Sunday = 0) */ - int32_t DayInYear; /* Day in the year (0-365, 1 Jan = 0) */ - int32_t IsDst; /* Daylight saving time */ -}; -#pragma pack(pop) //back to whatever the previous packing mode was diff --git a/src/libpsl-native/test/CMakeLists.txt b/src/libpsl-native/test/CMakeLists.txt deleted file mode 100644 index 2f57741b0cb..00000000000 --- a/src/libpsl-native/test/CMakeLists.txt +++ /dev/null @@ -1,26 +0,0 @@ -add_subdirectory(googletest) - -add_executable(psl-native-test - test-getfileowner.cpp - test-locale.cpp - test-getuserfrompid.cpp - test-getcurrentprocessid.cpp - test-getusername.cpp - test-getcomputername.cpp - test-getlinkcount.cpp - test-getfullyqualifiedname.cpp - test-isdirectory.cpp - test-isfile.cpp - test-issymlink.cpp - test-isexecutable.cpp - test-createsymlink.cpp - test-createhardlink.cpp - main.cpp) - -# manually include gtest headers -target_include_directories(psl-native-test PRIVATE ${gtest_SOURCE_DIR}/include) - -target_link_libraries(psl-native-test psl-native gtest) - -add_test(NAME psl-native-test - COMMAND psl-native-test --gtest_output=xml:native-tests.xml) diff --git a/src/libpsl-native/test/googletest b/src/libpsl-native/test/googletest deleted file mode 160000 index c99458533a9..00000000000 --- a/src/libpsl-native/test/googletest +++ /dev/null @@ -1 +0,0 @@ -Subproject commit c99458533a9b4c743ed51537e25989ea55944908 diff --git a/src/libpsl-native/test/main.cpp b/src/libpsl-native/test/main.cpp deleted file mode 100644 index 45569a6b583..00000000000 --- a/src/libpsl-native/test/main.cpp +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#include - -int main(int argc, char** argv) -{ - ::testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} diff --git a/src/libpsl-native/test/test-createhardlink.cpp b/src/libpsl-native/test/test-createhardlink.cpp deleted file mode 100644 index 37e488e76d4..00000000000 --- a/src/libpsl-native/test/test-createhardlink.cpp +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief Implements test for CreateHardLink() - -#include -#include -#include "getlinkcount.h" -#include "createhardlink.h" - -using namespace std; - -class CreateHardLinkTest : public ::testing::Test -{ -protected: - - static const int bufSize = 64; - const string fileTemplate = "/tmp/symlinktest.fXXXXXX"; - const string dirTemplate = "/tmp/symlinktest.dXXXXXX"; - const string fileHardLink = "/tmp/symlinktest.flink"; - const string dirHardLink = "/tmp/symlinktest.dlink"; - char *file, *dir; - char fileTemplateBuf[bufSize], dirTemplateBuf[bufSize]; - - CreateHardLinkTest() - { - // since mkstemp and mkdtemp modifies the template string, let's give them writable buffers - strcpy(fileTemplateBuf, fileTemplate.c_str()); - strcpy(dirTemplateBuf, dirTemplate.c_str()); - - // First create a temp file - int fd = mkstemp(fileTemplateBuf); - EXPECT_TRUE(fd != -1); - file = fileTemplateBuf; - - // Create a temp directory - dir = mkdtemp(dirTemplateBuf); - EXPECT_TRUE(dir != NULL); - - // Create hard link to file - int ret = CreateHardLink(fileHardLink.c_str(), file); - EXPECT_EQ(ret, 0); - - // Create hard link to directory - should fail - ret = CreateHardLink(dirHardLink.c_str(), dir); - EXPECT_EQ(ret, -1); - } - - ~CreateHardLinkTest() - { - int ret; - - ret = unlink(fileHardLink.c_str()); - EXPECT_EQ(0, ret); - - ret = unlink(file); - EXPECT_EQ(0, ret); - - ret = rmdir(dir); - EXPECT_EQ(0, ret); - } -}; - -TEST_F(CreateHardLinkTest, FilePathNameDoesNotExist) -{ - std::string invalidFile = "/tmp/symlinktest_invalidFile"; - std::string invalidLink = "/tmp/symlinktest_invalidLink"; - - // make sure neither exists - unlink(invalidFile.c_str()); - unlink(invalidLink.c_str()); - - int ret = CreateHardLink(invalidLink.c_str(), invalidFile.c_str()); - EXPECT_EQ(-1, ret); -} - -TEST_F(CreateHardLinkTest, VerifyLinkCount) -{ - int count = 0; - int ret = GetLinkCount(fileHardLink.c_str(), &count); - EXPECT_EQ(0, ret); - EXPECT_EQ(2, count); -} diff --git a/src/libpsl-native/test/test-createsymlink.cpp b/src/libpsl-native/test/test-createsymlink.cpp deleted file mode 100644 index 3b570c8b2d9..00000000000 --- a/src/libpsl-native/test/test-createsymlink.cpp +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief Implements test for CreateSymLink() and FollowSymLink() - -#include -#include -#include -#include "issymlink.h" -#include "createsymlink.h" -#include "followsymlink.h" - -using namespace std; - -class CreateSymLinkTest : public ::testing::Test -{ -protected: - - static const int bufSize = 64; - const string fileTemplate = "/tmp/symlinktest.fXXXXXX"; - const string dirTemplate = "/tmp/symlinktest.dXXXXXX"; - const string fileSymLink = "/tmp/symlinktest.flink"; - const string dirSymLink = "/tmp/symlinktest.dlink"; - char *file, *dir; - char fileTemplateBuf[bufSize], dirTemplateBuf[bufSize]; - - CreateSymLinkTest() - { - // since mkstemp and mkdtemp modifies the template string, let's give them writable buffers - strcpy(fileTemplateBuf, fileTemplate.c_str()); - strcpy(dirTemplateBuf, dirTemplate.c_str()); - - // First create a temp file - int fd = mkstemp(fileTemplateBuf); - EXPECT_TRUE(fd != -1); - file = fileTemplateBuf; - - // Create a temp directory - dir = mkdtemp(dirTemplateBuf); - EXPECT_TRUE(dir != NULL); - - // Create symbolic link to file - int ret = CreateSymLink(fileSymLink.c_str(), file); - EXPECT_EQ(0, ret); - - // Create symbolic link to directory - ret = CreateSymLink(dirSymLink.c_str(), dir); - EXPECT_EQ(0, ret); - } - - ~CreateSymLinkTest() - { - bool ret; - - ret = unlink(fileSymLink.c_str()); - EXPECT_FALSE(ret); - - ret = unlink(dirSymLink.c_str()); - EXPECT_FALSE(ret); - - ret = unlink(file); - EXPECT_FALSE(ret); - - ret = rmdir(dir); - EXPECT_FALSE(ret); - } -}; - -TEST_F(CreateSymLinkTest, FilePathNameDoesNotExist) -{ - std::string invalidFile = "/tmp/symlinktest_invalidFile"; - std::string invalidLink = "/tmp/symlinktest_invalidLink"; - - // make sure neither exists - unlink(invalidFile.c_str()); - unlink(invalidLink.c_str()); - - // Linux allows creation of symbolic link that points to an invalid file - int ret = CreateSymLink(invalidLink.c_str(), invalidFile.c_str()); - EXPECT_EQ(0, ret); - - std::string target = FollowSymLink(invalidLink.c_str()); - EXPECT_EQ(target, invalidFile); - - unlink(invalidLink.c_str()); -} - -TEST_F(CreateSymLinkTest, SymLinkToFile) -{ - bool ret = IsSymLink(fileSymLink.c_str()); - EXPECT_TRUE(ret); - - std::string target = FollowSymLink(fileSymLink.c_str()); - char buffer[PATH_MAX]; - std::string expected = realpath(file, buffer); - EXPECT_EQ(expected, target); -} - -TEST_F(CreateSymLinkTest, SymLinkToDirectory) -{ - bool ret = IsSymLink(dirSymLink.c_str()); - EXPECT_TRUE(ret); - - std::string target = FollowSymLink(dirSymLink.c_str()); - char buffer[PATH_MAX]; - std::string expected = realpath(dir, buffer); - EXPECT_EQ(expected, target); -} - -TEST_F(CreateSymLinkTest, SymLinkAgain) -{ - int ret = CreateSymLink(fileSymLink.c_str(), file); - EXPECT_EQ(-1, ret); - EXPECT_EQ(EEXIST, errno); -} diff --git a/src/libpsl-native/test/test-getcomputername.cpp b/src/libpsl-native/test/test-getcomputername.cpp deleted file mode 100644 index 235220cf355..00000000000 --- a/src/libpsl-native/test/test-getcomputername.cpp +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief Unit tests for GetComputerName - -#include -#include "getcomputername.h" - -//! Test fixture for GetComputerNameTest -class GetComputerNameTest : public ::testing::Test -{ -}; - -TEST_F(GetComputerNameTest, Success) -{ - char expectedComputerName[_POSIX_HOST_NAME_MAX]; - - // the gethostname system call gets the nodename from uname - FILE *fPtr = popen("uname -n", "r"); - ASSERT_TRUE(fPtr != NULL); - - char *linePtr = fgets(expectedComputerName, sizeof(expectedComputerName), fPtr); - ASSERT_TRUE(linePtr != NULL); - - // There's a tendency to have \n at end of fgets string, so remove it before compare - size_t sz = strlen(expectedComputerName); - if (sz > 0 && expectedComputerName[sz - 1] == '\n') - { - expectedComputerName[sz - 1] = '\0'; - } - pclose(fPtr); - - ASSERT_STREQ(GetComputerName(), expectedComputerName); -} diff --git a/src/libpsl-native/test/test-getcurrentprocessid.cpp b/src/libpsl-native/test/test-getcurrentprocessid.cpp deleted file mode 100644 index 22ea7be7d0a..00000000000 --- a/src/libpsl-native/test/test-getcurrentprocessid.cpp +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#include -#include "getcurrentprocessorid.h" - -// This is a very simple test case to show how tests can be written -TEST(GetCurrentProcessId,simple) -{ - const int32_t currentProcessId = GetCurrentProcessId(); - const pid_t pid = getpid(); - - // first make sure that on this platform those types are of the same size - ASSERT_TRUE(sizeof(int32_t) >= sizeof(pid_t)); - - // now compare the actual values - ASSERT_EQ(currentProcessId,static_cast(pid)); -} - diff --git a/src/libpsl-native/test/test-getcurrentthreadid.cpp b/src/libpsl-native/test/test-getcurrentthreadid.cpp deleted file mode 100644 index a044defdff8..00000000000 --- a/src/libpsl-native/test/test-getcurrentthreadid.cpp +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#include -#include "getcurrentthreadid.h" -#include - -TEST(GetCurrentThreadId,simple) -{ - const HANDLE currentThreadId = GetCurrentThreadId(); - const pid_t tid = pthread_self(); - - // first make sure that on this platform those types are of the same size - ASSERT_TRUE(sizeof(HANDLE) >= sizeof(pid_t)); - - // now compare the actual values - ASSERT_EQ(currentThreadId,reinterpret_cast(tid)); -} - diff --git a/src/libpsl-native/test/test-getfileowner.cpp b/src/libpsl-native/test/test-getfileowner.cpp deleted file mode 100644 index ab1cf820ca8..00000000000 --- a/src/libpsl-native/test/test-getfileowner.cpp +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief Tests GetFileOwner - -#include -#include -#include -#include "getfileowner.h" - -TEST(GetFileOwnerTest, CanGetOwnerOfRoot) -{ - EXPECT_STREQ(GetFileOwner("/"), "root"); -} - -TEST(GetFileOwnerTest, CannotGetOwnerOfFakeFile) -{ - EXPECT_STREQ(GetFileOwner("SomeMadeUpFileNameThatDoesNotExist"), NULL); - EXPECT_EQ(ENOENT, errno); -} diff --git a/src/libpsl-native/test/test-getfullyqualifiedname.cpp b/src/libpsl-native/test/test-getfullyqualifiedname.cpp deleted file mode 100644 index 8378f3a6853..00000000000 --- a/src/libpsl-native/test/test-getfullyqualifiedname.cpp +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief Unit tests for GetFullyQualifiedName - -#include -#include "getcomputername.h" -#include "getfullyqualifiedname.h" -#include -#include -#include -#include - -TEST(GetFullyQualifiedNameTest, ValidateLinuxGetFullyQualifiedDomainName) -{ - char *hostname = GetComputerName(); - ASSERT_STRNE(NULL, hostname); - - // this might be fail - errno = 0; - char *actual = GetFullyQualifiedName(); - int fqdnErrno = errno; - - struct addrinfo hints, *info; - memset(&hints, 0, sizeof(hints)); - hints.ai_family = AF_UNSPEC; - hints.ai_socktype = SOCK_STREAM; - hints.ai_flags = AI_CANONNAME; - errno = 0; - if (getaddrinfo(hostname, "http", &hints, &info) != 0) - { - // test that getaddrinfo failed the same way - EXPECT_EQ(fqdnErrno, errno); - goto exit; - } - - // Compare canonical name to FQDN - EXPECT_STREQ(info->ai_canonname, actual); - freeaddrinfo(info); -exit: - free(hostname); -} diff --git a/src/libpsl-native/test/test-getlinkcount.cpp b/src/libpsl-native/test/test-getlinkcount.cpp deleted file mode 100644 index 741c0c55267..00000000000 --- a/src/libpsl-native/test/test-getlinkcount.cpp +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief Implements test for getLinkCount() - -#include -#include -#include -#include -#include -#include -#include -#include "getlinkcount.h" - -class getLinkCountTest : public ::testing::Test -{ -protected: - - static const int bufSize = 64; - const std::string fileTemplate = "/tmp/createFile.XXXXXX"; - char fileTemplateBuf[bufSize]; - - int32_t count; - char *file; - - getLinkCountTest() - { - // since mkstemp modifies the template string, let's give it writable buffer - strcpy(fileTemplateBuf, fileTemplate.c_str()); - - int fd = mkstemp(fileTemplateBuf); - EXPECT_TRUE(fd != -1); - file = fileTemplateBuf; - } - - void createFileForTesting(const std::string &theFile) - { - std::ofstream ofs; - ofs.open(theFile, std::ofstream::out); - ofs << "hi there, ms ostc!"; - ofs.close(); - } - - std::string createHardLink(const std::string &origFile) - { - std::string newFile = origFile + "_link"; - int ret = link(origFile.c_str(), newFile.c_str()); - EXPECT_EQ(0, ret); - - return newFile; - } - - void removeFile(const std::string &fileName) - { - int ret = unlink(fileName.c_str()); - EXPECT_EQ(0, ret); - } -}; - -TEST_F(getLinkCountTest, FilePathNameDoesNotExist) -{ - std::string invalidFile = "/tmp/createFile"; - int32_t ret = GetLinkCount(invalidFile.c_str(), &count); - ASSERT_EQ(-1, ret); - EXPECT_EQ(ENOENT, errno); -} - -TEST_F(getLinkCountTest, LinkCountOfSinglyLinkedFile) -{ - createFileForTesting(file); - int32_t ret = GetLinkCount(file, &count); - ASSERT_EQ(0, ret); - EXPECT_EQ(1, count); - - removeFile(file); -} - -TEST_F(getLinkCountTest, LinkCountOfMultiplyLinkedFile) -{ - createFileForTesting(file); - std::string newFile = createHardLink(file); - int32_t ret = GetLinkCount(file, &count); - ASSERT_EQ(0, ret); - EXPECT_EQ(2, count); - - removeFile(file); - removeFile(newFile); -} - diff --git a/src/libpsl-native/test/test-getuserfrompid.cpp b/src/libpsl-native/test/test-getuserfrompid.cpp deleted file mode 100644 index 2b908cd9095..00000000000 --- a/src/libpsl-native/test/test-getuserfrompid.cpp +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief Unit tests for GetUserFromPid - -#include -#include -#include "getuserfrompid.h" - -TEST(GetUserFromPid, Success) -{ - char* expected = getpwuid(geteuid())->pw_name; - EXPECT_STREQ(GetUserFromPid(getpid()), expected); -} diff --git a/src/libpsl-native/test/test-getusername.cpp b/src/libpsl-native/test/test-getusername.cpp deleted file mode 100644 index f3adf3ba161..00000000000 --- a/src/libpsl-native/test/test-getusername.cpp +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief Unit tests for GetUserName - -#include -#include -#include "getusername.h" - -TEST(GetUserName, Success) -{ - char* expected = getpwuid(geteuid())->pw_name; - EXPECT_STREQ(GetUserName(), expected); -} diff --git a/src/libpsl-native/test/test-isdirectory.cpp b/src/libpsl-native/test/test-isdirectory.cpp deleted file mode 100644 index a9f4a294ed7..00000000000 --- a/src/libpsl-native/test/test-isdirectory.cpp +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief Tests IsDirectory - -#include -#include -#include -#include "isdirectory.h" - -TEST(IsDirectoryTest, RootIsDirectory) -{ - EXPECT_TRUE(IsDirectory("/")); -} - -TEST(IsDirectoryTest, BinLsIsNotDirectory) -{ - EXPECT_FALSE(IsDirectory("/bin/ls")); -} - - -TEST(IsDirectoryTest, ReturnsFalseForFakeDirectory) -{ - EXPECT_FALSE(IsDirectory("SomeMadeUpFileNameThatDoesNotExist")); - EXPECT_EQ(ENOENT, errno); -} diff --git a/src/libpsl-native/test/test-isexecutable.cpp b/src/libpsl-native/test/test-isexecutable.cpp deleted file mode 100644 index e86e7250f4c..00000000000 --- a/src/libpsl-native/test/test-isexecutable.cpp +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief Implements test for isexecutable() - -#include -#include -#include -#include -#include "isexecutable.h" - -using namespace std; - -class IsExecutableTest : public ::testing::Test -{ -protected: - - static const int bufSize = 64; - const string fileTemplate = "/tmp/isexecutabletest.fXXXXXXX"; - const mode_t mode_700 = S_IRUSR | S_IWUSR | S_IXUSR; - const mode_t mode_070 = S_IRGRP | S_IWGRP | S_IXGRP; - const mode_t mode_007 = S_IROTH | S_IWOTH | S_IXOTH; - const mode_t mode_777 = mode_700 | mode_070 | mode_007; - const mode_t mode_444 = S_IRUSR | S_IRGRP | S_IROTH; - - char *file; - char fileTemplateBuf[bufSize]; - - IsExecutableTest() - { - // since mkstemp modifies the template string, let's give it writable buffers - strcpy(fileTemplateBuf, fileTemplate.c_str()); - - // First create a file - int fd = mkstemp(fileTemplateBuf); - EXPECT_TRUE(fd != -1); - file = fileTemplateBuf; - } - - ~IsExecutableTest() - { - EXPECT_FALSE(unlink(file)); - } - - void ChangeFilePermission(const char* file, mode_t mode) - { - EXPECT_FALSE(chmod(file, mode)); - } -}; - -TEST_F(IsExecutableTest, FilePathNameDoesNotExist) -{ - std::string invalidFile = "/tmp/isexecutabletest_invalidFile"; - EXPECT_FALSE(IsExecutable(invalidFile.c_str())); - EXPECT_EQ(ENOENT, errno); -} - -TEST_F(IsExecutableTest, NormalFileIsNotIsexecutable) -{ - EXPECT_FALSE(IsExecutable(file)); - - ChangeFilePermission(file, mode_444); - - EXPECT_FALSE(IsExecutable(file)); -} - -TEST_F(IsExecutableTest, FilePermission_700) -{ - ChangeFilePermission(file, mode_700); - - EXPECT_TRUE(IsExecutable(file)); -} - -TEST_F(IsExecutableTest, FilePermission_777) -{ - ChangeFilePermission(file, mode_777); - - EXPECT_TRUE(IsExecutable(file)); -} diff --git a/src/libpsl-native/test/test-isfile.cpp b/src/libpsl-native/test/test-isfile.cpp deleted file mode 100644 index 98373a146e9..00000000000 --- a/src/libpsl-native/test/test-isfile.cpp +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief Tests Isfile - -#include -#include -#include -#include "isfile.h" - -TEST(IsFileTest, RootIsFile) -{ - EXPECT_FALSE(IsFile("/")); -} - -TEST(IsFileTest, BinLsIsFile) -{ - EXPECT_TRUE(IsFile("/bin/ls")); -} - -TEST(IsFileTest, CannotGetOwnerOfFakeFile) -{ - EXPECT_FALSE(IsFile("SomeMadeUpFileNameThatDoesNotExist")); - EXPECT_EQ(errno, ENOENT); -} diff --git a/src/libpsl-native/test/test-issymlink.cpp b/src/libpsl-native/test/test-issymlink.cpp deleted file mode 100644 index 0bddaeab986..00000000000 --- a/src/libpsl-native/test/test-issymlink.cpp +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief Implements test for isSymLink() - -#include -#include -#include -#include "issymlink.h" - -using namespace std; - -class isSymLinkTest : public ::testing::Test -{ -protected: - - static const int bufSize = 64; - const string fileTemplate = "/tmp/symlinktest.fXXXXXX"; - const string dirTemplate = "/tmp/symlinktest.dXXXXXX"; - const string fileSymLink = "/tmp/symlinktest.flink"; - const string dirSymLink = "/tmp/symlinktest.dlink"; - char *file, *dir; - char fileTemplateBuf[bufSize], dirTemplateBuf[bufSize]; - - isSymLinkTest() - { - // since mkstemp and mkdtemp modifies the template string, let's give them writable buffers - strcpy(fileTemplateBuf, fileTemplate.c_str()); - strcpy(dirTemplateBuf, dirTemplate.c_str()); - - // First create a file - int fd = mkstemp(fileTemplateBuf); - EXPECT_TRUE(fd != -1); - file = fileTemplateBuf; - - // Create a temp directory - dir = mkdtemp(dirTemplateBuf); - EXPECT_TRUE(dir != NULL); - - // Create symbolic link to file - EXPECT_FALSE(symlink(file, fileSymLink.c_str())); - - // Create symbolic link to directory - EXPECT_FALSE(symlink(dir, dirSymLink.c_str())); - } - - ~isSymLinkTest() - { - EXPECT_FALSE(unlink(fileSymLink.c_str())); - - EXPECT_FALSE(unlink(dirSymLink.c_str())); - - EXPECT_FALSE(unlink(file)); - - EXPECT_FALSE(rmdir(dir)); - } -}; - -TEST_F(isSymLinkTest, FilePathNameDoesNotExist) -{ - std::string invalidFile = "/tmp/symlinktest_invalidFile"; - EXPECT_FALSE(IsSymLink(invalidFile.c_str())); - EXPECT_EQ(ENOENT, errno); -} - -TEST_F(isSymLinkTest, NormalFileIsNotSymLink) -{ - EXPECT_FALSE(IsSymLink(file)); -} - -TEST_F(isSymLinkTest, SymLinkToFile) -{ - EXPECT_TRUE(IsSymLink(fileSymLink.c_str())); -} - -TEST_F(isSymLinkTest, NormalDirectoryIsNotSymbLink) -{ - EXPECT_FALSE(IsSymLink(dir)); -} - -TEST_F(isSymLinkTest, SymLinkToDirectory) -{ - EXPECT_TRUE(IsSymLink(dirSymLink.c_str())); -} diff --git a/src/libpsl-native/test/test-locale.cpp b/src/libpsl-native/test/test-locale.cpp deleted file mode 100644 index 1abc92feb98..00000000000 --- a/src/libpsl-native/test/test-locale.cpp +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//! @brief Unit tests for linux locale - -#include -#include -#include -#include -#include -//! Test fixture for LocaleTest - -class LocaleTest : public ::testing::Test -{ -}; - -TEST_F(LocaleTest, Success) -{ - setlocale(LC_ALL, ""); - ASSERT_FALSE(nl_langinfo(CODESET) == NULL); - ASSERT_STREQ(nl_langinfo(CODESET), "UTF-8"); -} diff --git a/src/powershell-native/.gitignore b/src/powershell-native/.gitignore deleted file mode 100644 index 07bd02f36ea..00000000000 --- a/src/powershell-native/.gitignore +++ /dev/null @@ -1,17 +0,0 @@ -ALL_BUILD.vcxproj -ALL_BUILD.vcxproj.filters -CMakeCache.txt -CMakeFiles/ -*.sln -Win32/ -x64/ -cmake_install.cmake -*.dir/ -*.vcxproj -*.vcxproj.filters -Release/ - -# Resources -MSG*.bin -pwrshpluginerrorcodes.h -pwrshpluginerrorcodes.rc \ No newline at end of file diff --git a/src/powershell-native/CMakeLists.txt b/src/powershell-native/CMakeLists.txt deleted file mode 100644 index 051d880ca58..00000000000 --- a/src/powershell-native/CMakeLists.txt +++ /dev/null @@ -1,86 +0,0 @@ -cmake_minimum_required(VERSION 3.10.0) - -project(PowerShellNative) - -# -# Verify prerequisites -# -if (NOT $ENV{${WindowsSDKVersion}}) - message (FATAL_ERROR "WindowsSDKVersion environment variable not found") -endif () - -# -# Normalize the platform name -SET(BUILD_ARCH_ARM 0) -SET(BUILD_ARCH_ARM64 0) -SET(BUILD_ARCH_X86 0) -SET(BUILD_ARCH_AMD64 0) - -if (BUILD_TARGET_ARCH) - SET(WindowsSDKPlatform ${BUILD_TARGET_ARCH}) - message(STATUS "Building for " ${BUILD_TARGET_ARCH}) -else () - message(FATAL_ERROR "Target architecture value should be specified through BUILD_TARGET_ARCH. Supported values are x64, x86, arm, or arm64") -endif (BUILD_TARGET_ARCH) - -if (WindowsSDKPlatform STREQUAL "x64" OR WindowsSDKPlatform STREQUAL "X64" OR WindowsSDKPlatform STREQUAL "amd64" OR WindowsSDKPlatform STREQUAL "AMD64") - SET(WindowsSDKPlatform "x64") - SET(BUILD_ARCH_AMD64 1) -elseif (WindowsSDKPlatform STREQUAL "x86" OR WindowsSDKPlatform STREQUAL "X86") - SET(WindowsSDKPlatform "x86") - SET(BUILD_ARCH_X86 1) -elseif (WindowsSDKPlatform STREQUAL "arm" OR WindowsSDKPlatform STREQUAL "ARM") - SET(WindowsSDKPlatform "arm") - SET(BUILD_ARCH_ARM 1) -elseif (WindowsSDKPlatform STREQUAL "arm64" OR WindowsSDKPlatform STREQUAL "ARM64") - SET(WindowsSDKPlatform "arm64") - SET(BUILD_ARCH_ARM64 1) -else() - message(FATAL_ERROR "Unsupported WindowsSDKPlatform: " ${WindowsSDKPlatform}) -endif () - -# -# set the output path for all binaries -# -if (BUILD_ONECORE) - set(PWRSH_NATIVE_OUTPUT_DIRECTORY "CoreClr") -else () - set(PWRSH_NATIVE_OUTPUT_DIRECTORY "FullClr") -endif (BUILD_ONECORE) - -foreach(OUTPUTCONFIG ${CMAKE_CONFIGURATION_TYPES}) - string(TOUPPER ${OUTPUTCONFIG} OUTPUTCONFIG) - set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_${OUTPUTCONFIG} "${PROJECT_SOURCE_DIR}/Bin/${OUTPUTCONFIG}/${PWRSH_NATIVE_OUTPUT_DIRECTORY}") - # message(" Setting output directory for ${CMAKE_RUNTIME_OUTPUT_DIRECTORY_${OUTPUTCONFIG}}") -endforeach( OUTPUTCONFIG CMAKE_CONFIGURATION_TYPES ) - -# -# Definitions for ease of reading -# -SET (WIN_VERSION_WIN10_RS1 0x0A000002) -SET (WIN_VERSION_WIN10_TH2 0x0A000001) -SET (WIN_VERSION_WIN10 0x0A00) -SET (WIN_VERSION_WINTHRESHOLD 0x0A00) -SET (WIN_VERSION_WINBLUE 0x0603) -SET (WIN_VERSION_WIN8 0x0602) -SET (WIN_VERSION_WIN7 0x0601) -SET (NTDDI_VERSION_WIN7 0x06010000) -SET (NTDDI_VERSION_WIN10 0x0A000002) -SET (WIN_VERSION_VISTA 0x0600) -SET (WIN_VERSION_LONGHORN 0x0600) -SET (WIN_VERSION_WS03 0x0502) -SET (WIN_VERSION_WINXP 0x0501) - -include(coreclr_defs.cmake) - -# Default of BUILD_ONECORE should be ON once it is supported -option(BUILD_ONECORE "Compile the OneCore version of the binaries" ON) - -# Build the common library that powershell.exe and pwrshplugin.dll depend on -add_subdirectory(nativemsh/pwrshcommon) - -# Build pwrshplugin.dll -add_subdirectory(nativemsh/pwrshplugin) - -# Build powershell.exe -add_subdirectory(nativemsh/pwrshexe) diff --git a/src/powershell-native/coreclr_defs.cmake b/src/powershell-native/coreclr_defs.cmake deleted file mode 100644 index 1b6ea3eeb5e..00000000000 --- a/src/powershell-native/coreclr_defs.cmake +++ /dev/null @@ -1,174 +0,0 @@ -cmake_minimum_required(VERSION 3.10.0) - -set(CMAKE_CXX_STANDARD_LIBRARIES "") # do not link against standard win32 libs i.e. kernel32, uuid, user32, etc. - -if(NOT BUILD_ARCH_ARM64) - set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /guard:cf") - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /guard:cf") -endif (NOT BUILD_ARCH_ARM64) - -# Incremental linking with CFG is broken until next VS release. -# This needs to be appended to the last for each build type to override the default flag. -set(NO_INCREMENTAL_LINKER_FLAGS "/INCREMENTAL:NO") - -# Linker flags -# -# Disable the following line for UNIX altjit on Windows -set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /MANIFEST:NO") #Do not create Side-by-Side Assembly Manifest -set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /SUBSYSTEM:WINDOWS,6.00") #windows subsystem -set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /LARGEADDRESSAWARE") # can handle addresses larger than 2 gigabytes -set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /RELEASE") #sets the checksum in the header -set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /NXCOMPAT") #Compatible with Data Execution Prevention -set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /DYNAMICBASE") #Use address space layout randomization -set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /DEBUGTYPE:cv,fixup") #debugging format -set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /PDBCOMPRESS") #shrink pdb size -set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /DEBUG") - -set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /DEBUG /PDBCOMPRESS") -#set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /STACK:1572864") - -# Debug build specific flags -set(CMAKE_SHARED_LINKER_FLAGS_DEBUG "/NOVCFEATURE ${NO_INCREMENTAL_LINKER_FLAGS}") -set(CMAKE_SHARED_LINKER_FLAGS_DEBUG "${NO_INCREMENTAL_LINKER_FLAGS}") -set(CMAKE_EXE_LINKER_FLAGS_DEBUG "${NO_INCREMENTAL_LINKER_FLAGS}") - -# Checked build specific flags -set(CMAKE_SHARED_LINKER_FLAGS_CHECKED "${CMAKE_SHARED_LINKER_FLAGS_CHECKED} /OPT:REF /OPT:NOICF /NOVCFEATURE ${NO_INCREMENTAL_LINKER_FLAGS}") -set(CMAKE_STATIC_LINKER_FLAGS_CHECKED "${CMAKE_STATIC_LINKER_FLAGS_CHECKED}") -set(CMAKE_EXE_LINKER_FLAGS_CHECKED "${CMAKE_EXE_LINKER_FLAGS_CHECKED} /OPT:REF /OPT:NOICF ${NO_INCREMENTAL_LINKER_FLAGS}") - -# Release build specific flags -set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE} /LTCG /OPT:REF /OPT:ICF ${NO_INCREMENTAL_LINKER_FLAGS}") -set(CMAKE_STATIC_LINKER_FLAGS_RELEASE "${CMAKE_STATIC_LINKER_FLAGS_RELEASE} /LTCG") -set(CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS_RELEASE} /LTCG /OPT:REF /OPT:ICF ${NO_INCREMENTAL_LINKER_FLAGS}") - -# ReleaseWithDebugInfo build specific flags -set(CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO} /LTCG /OPT:REF /OPT:ICF ${NO_INCREMENTAL_LINKER_FLAGS}") -set(CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO} /LTCG") -set(CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO} /LTCG /OPT:REF /OPT:ICF ${NO_INCREMENTAL_LINKER_FLAGS}") - -# Force uCRT to be dynamically linked for Release build -set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE} /NODEFAULTLIB:libucrt.lib /DEFAULTLIB:ucrt.lib") -set(CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS_RELEASE} /NODEFAULTLIB:libucrt.lib /DEFAULTLIB:ucrt.lib") -set(CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO} /NODEFAULTLIB:libucrt.lib /DEFAULTLIB:ucrt.lib") -set(CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO} /NODEFAULTLIB:libucrt.lib /DEFAULTLIB:ucrt.lib") - -#------------------------------------ -# Definitions (for platform) -#----------------------------------- -if (BUILD_ARCH_AMD64) - add_definitions(-D_AMD64_) - add_definitions(-D_WIN64) - add_definitions(-DAMD64) - add_definitions(-DBIT64=1) - add_definitions(-D_M_AMD64) -elseif (BUILD_ARCH_X86) - add_definitions(-D_X86_) -elseif (BUILD_ARCH_ARM) - add_definitions(-D_ARM_) - add_definitions(-D_WIN32) - add_definitions(-D_M_ARM) - add_definitions(-DARM) -elseif (BUILD_ARCH_ARM64) - add_definitions(-D_ARM64_) - add_definitions(-DARM64) - add_definitions(-D_WIN64) - add_definitions(-DBIT64=1) - add_definitions(-D_M_ARM64) -endif () - -# Define the CRT lib references that link into Desktop imports -set(STATIC_MT_CRT_LIB "libcmt$<$,$>:d>.lib") -set(STATIC_MT_VCRT_LIB "libvcruntime$<$,$>:d>.lib") -set(STATIC_MT_CPP_LIB "libcpmt$<$,$>:d>.lib") - -# Define the uCRT lib reference -set(STATIC_UCRT_LIB "libucrt$<$,$>:d>.lib") -set(DYNAMIC_UCRT_LIB "ucrt$<$,$>:d>.lib") - -#------------------------------------ -# Definitions for compile -#----------------------------------- - -add_compile_options(/Zl) # omit default library name in .OBJ - -# The following options are set by the razzle build -add_compile_options(/TP) # compile all files as C++ -add_compile_options(/d2Zi+) # make optimized builds debugging easier -add_compile_options(/nologo) # Suppress Startup Banner -add_compile_options(/W3) # set warning level to 3 -#add_compile_options(/WX) # treat warnings as errors -add_compile_options(/Oi) # enable intrinsics -add_compile_options(/Oy-) # disable suppressing of the creation of frame pointers on the call stack for quicker function calls -add_compile_options(/U_MT) # undefine the predefined _MT macro -add_compile_options(/GF) # enable read-only string pooling -add_compile_options(/Gm-) # disable minimal rebuild -add_compile_options(/EHa) # enable C++ EH (w/ SEH exceptions) -add_compile_options(/Zp8) # pack structs on 8-byte boundary -add_compile_options(/Gy) # separate functions for linker -add_compile_options(/Zc:wchar_t-) # C++ language conformance: wchar_t is NOT the native type, but a typedef -add_compile_options(/Zc:forScope) # C++ language conformance: enforce Standard C++ for scoping rules -add_compile_options(/GR-) # disable C++ RTTI -add_compile_options(/FC) # use full pathnames in diagnostics -if (BUILD_CORECLR) - # This option is not supported for "FullClr" because it triggers: error C2813: #import is not supported with /MP - add_compile_options(/MP) # Build with Multiple Processes (number of processes equal to the number of processors) -endif (BUILD_CORECLR) -add_compile_options(/GS) # Buffer Security Check -add_compile_options(/Zm200) # Specify Precompiled Header Memory Allocation Limit of 150MB -#add_compile_options(/wd4960 /wd4961 /wd4603 /wd4627 /wd4838 /wd4456 /wd4457 /wd4458 /wd4459 /wd4091 /we4640) -add_compile_options(/Zi) # enable debugging information -add_compile_options(/ZH:SHA_256) # use SHA256 for generating hashes of compiler processed source files. - -if (BUILD_ARCH_X86) - add_compile_options(/Gz) -endif (BUILD_ARCH_X86) - -add_compile_options($<$,$>:/GL>) -add_compile_options($<$,$>,$>:/O1>) - -if (BUILD_ARCH_AMD64) -# The generator expression in the following command means that the /homeparams option is added only for debug builds - add_compile_options($<$:/homeparams>) # Force parameters passed in registers to be written to the stack -endif (BUILD_ARCH_AMD64) - -# enable control-flow-guard support for native components for non-Arm64 builds -add_compile_options(/guard:cf) - -# Statically linked CRT (libcmt[d].lib, libvcruntime[d].lib and libucrt[d].lib) by default. This is done to avoid -# linking in VCRUNTIME140.DLL for a simplified xcopy experience by reducing the dependency on VC REDIST. -# -# For Release builds, we shall dynamically link into uCRT [ucrtbase.dll] (which is pushed down as a Windows Update on downlevel OS) but -# wont do the same for debug/checked builds since ucrtbased.dll is not redistributable and Debug/Checked builds are not -# production-time scenarios. -add_compile_options($<$,$>:/MT>) -add_compile_options($<$,$>:/MTd>) - -#set(CMAKE_ASM_MASM_FLAGS "${CMAKE_ASM_MASM_FLAGS} /ZH:SHA_256") - -if (BUILD_ARCH_AMD64) - add_definitions(-D_TARGET_AMD64_=1) -elseif (BUILD_ARCH_ARM) - add_definitions(-D_TARGET_ARM_=1) -elseif (BUILD_ARCH_ARM64) - add_definitions(-D_TARGET_ARM64_=1) -elseif (BUILD_ARCH_X86) - add_definitions(-D_TARGET_X86_=1) -endif (BUILD_ARCH_AMD64) - -add_definitions(-DWIN32) -add_definitions(-D_WIN32) -add_definitions(-DWINVER=${WIN_VERSION_WIN8}) -add_definitions(-D_WIN32_WINNT=${WIN_VERSION_WIN8}) -add_definitions(-DWIN32_LEAN_AND_MEAN=1) -add_definitions(-D_CRT_SECURE_NO_WARNINGS) - -if(BUILD_ARCH_AMD64 OR BUILD_ARCH_X86) - # Only enable edit and continue on windows x86 and x64. - # Exclude arm & arm64 - add_definitions(-DEnC_SUPPORTED) -endif(BUILD_ARCH_AMD64 OR BUILD_ARCH_X86) - -add_definitions(-DUNICODE) -add_definitions(-D_UNICODE) - diff --git a/src/powershell-native/dsc_defs.cmake b/src/powershell-native/dsc_defs.cmake deleted file mode 100644 index 92bb2a4c591..00000000000 --- a/src/powershell-native/dsc_defs.cmake +++ /dev/null @@ -1,111 +0,0 @@ -cmake_minimum_required(VERSION 2.8.4) - -SET (WindowsSdkDir $ENV{WindowsSdkDir}) -SET (WindowsSDKVersion $ENV{WindowsSDKVersion}) -SET (NETFXSdkDir $ENV{NETFXSDKDir}) -#SET (FrameWorkLibPath $ENV{FrameworkDir}/$ENV{FrameworkVersion}) - -# -# Configure include directories -# -SET (WindowsSDKIncludeBase "${WindowsSdkDir}/Include/${WindowsSDKVersion}") - -SET (IncludePath) -#list (APPEND IncludePath "${INTERNAL_HEADER_DIR}") -#list (APPEND IncludePath "${PUBLIC_HEADER_DIR}") -list (APPEND IncludePath "${WindowsSDKIncludeBase}winrt") -# Don't include due to incompatible instance.h -# list (APPEND IncludePath "${WindowsSDKIncludeBase}um") -list (APPEND IncludePath "${WindowsSDKIncludeBase}shared") -list (APPEND IncludePath "${NETFXSdkDir}/Include/um") -list (APPEND IncludePath "${WindowsSDKIncludeBase}ucrt") -include_directories(BEFORE ${IncludePath}) - -# -# Configure lib directories -# -SET (WindowsSDKLibBase "${WindowsSdkDir}/Lib/${WindowsSDKVersion}") -SET (OneCoreLibBase "$ENV{VCInstallDir}lib/onecore/amd64") - -SET (LibraryPath) -if (BUILD_ONECORE) - list (APPEND LibraryPath "${OneCoreLibBase}") -endif (BUILD_ONECORE) -list (APPEND LibraryPath "${WindowsSDKLibBase}ucrt/${WindowsSDKPlatform}") -list (APPEND LibraryPath "${NETFXSdkDir}lib/um/${WindowsSDKPlatform}") -list (APPEND LibraryPath "${WindowsSDKLibBase}um/${WindowsSDKPlatform}" ) -list (APPEND LibraryPath "${INTERNAL_LIBRARY_DIR}") -list (APPEND LibraryPath "${PUBLIC_LIBRARY_DIR}") -#list (APPEND LibraryPath ${FrameWorkLibPath}) -SET (WindowsSDKLibBase "${WindowsSdkDir}/Lib/${WindowsSDKVersion}") -link_directories(${LibraryPath}) - -if (${WindowsSDKPlatform} STREQUAL "x64") - add_definitions ( - -D_WIN64 - -D_AMD64_ - -DAMD64 - -DBUILD_WOW64_ENABLED=1 - -DBUILD_UMS_ENABLED=1 - ) -else() - add_definitions ( - -DBUILD_WOW64_ENABLED=1 - -DBUILD_UMS_ENABLED=0 - ) -endif() - -# -# Common defines. -# -add_definitions ( - -D_CRT_SECURE_NO_WARNINGS - -DCONDITION_HANDLING=1 - -DNT_UP=1 - -DNT_INST=0 - -D_NT1X_=100 - -DWINNT=1 - -DWIN32_LEAN_AND_MEAN=1 - -DDEVL=1 - #-D_MT=1 - -DMD - -D_STL70_ - -DMI_INTERNAL - -DWINBUILD - -DHOOK_BUILD # TODO: should be target specific - -DCONFIG_ENABLE_WCHAR - -D_INTLSTR_NOTAPPEND_NULL - -DMSC_NOOPT - -DBUILD_WINDOWS - -D_USE_DECLSPECS_FOR_SAL=1 - -DUNICODE - -D_UNICODE - -D_USE_DEV11_CRT -) - -# -# platform specific defines -# -add_definitions( - #-DNTDDI_VERSION=${NTDDI_VERSION_WIN7} - -DNTDDI_VERSION=${NTDDI_VERSION_WIN10} - -DWINBLUE_KBSPRING14 - #-D_APISET_WINDOWS_VERSION=${WIN_VERSION_WIN7} - -D_APISET_WINDOWS_VERSION=${WIN_VERSION_WIN10} - #-D_APISET_MINWIN_VERSION=0x0100 - -D_APISET_MINWIN_VERSION=0x0106 - #-D_APISET_MINCORE_VERSION=0x0100 - -D_APISET_MINCORE_VERSION=0x0105 - -D_WIN32_IE=0x0800 - #-D_WIN32_WINNT=${WIN_VERSION_WIN7} - -D_WIN32_WINNT=${WIN_VERSION_WIN10} - #-DWINVER=${WIN_VERSION_WIN7} - -DWINVER=${WIN_VERSION_WIN10} - ) - -# if not DEBUG for DSC -set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /Zi") -set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE} /DEBUG /OPT:REF /OPT:ICF") -#set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE} /DEBUG /OPT:REF /OPT:ICF /NODEFAULTLIB") -set(CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS_RELEASE} /DEBUG /OPT:REF /OPT:ICF /NODEFAULTLIB") - diff --git a/src/powershell-native/nano_defs.cmake b/src/powershell-native/nano_defs.cmake deleted file mode 100644 index fe52150aafe..00000000000 --- a/src/powershell-native/nano_defs.cmake +++ /dev/null @@ -1,88 +0,0 @@ -cmake_minimum_required(VERSION 2.8.4) - -SET (WindowsSdkDir $ENV{WindowsSdkDir}) -SET (WindowsSDKVersion $ENV{WindowsSDKVersion}) -SET (NETFXSdkDir $ENV{NETFXSDKDir}) - -# -# Configure include directories -# -SET (WindowsSDKIncludeBase "${WindowsSdkDir}/Include/${WindowsSDKVersion}") - -SET (IncludePath) -list (APPEND IncludePath "${WindowsSDKIncludeBase}winrt") -list (APPEND IncludePath "${WindowsSDKIncludeBase}shared") -#list (APPEND IncludePath "${NETFXSdkDir}/Include/um") -list (APPEND IncludePath "${WindowsSDKIncludeBase}ucrt") -include_directories(BEFORE ${IncludePath}) - -# -# Configure lib directories -# -SET (WindowsSDKLibBase "${WindowsSdkDir}/Lib/${WindowsSDKVersion}") -SET (OneCoreLibBase "$ENV{VCInstallDir}lib/onecore/amd64") - -SET (LibraryPath) -list (APPEND LibraryPath "${OneCoreLibBase}") -list (APPEND LibraryPath "${WindowsSDKLibBase}ucrt/${WindowsSDKPlatform}") -list (APPEND LibraryPath "${WindowsSDKLibBase}um/${WindowsSDKPlatform}" ) -###list (APPEND LibraryPath "${NETFXSdkDir}lib/um/${WindowsSDKPlatform}") -link_directories(${LibraryPath}) - -# -# Tell CMake to set the platform toolset. Nano Server requires the Win10 SDK and updated onecore.lib -# -set(CMAKE_VS_PLATFORM_TOOLSET "v140") # Use VS 2015 with Win 10 SDK -set(CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION "10.0.10586.0") # Targets Windows 10. Alt is ${WindowsSDKVersion} - -if (BUILD_ONECORE) - set(CMAKE_CXX_STANDARD_LIBRARIES "") # do not link against standard win32 libs i.e. kernel32, uuid, user32, etc. -endif (BUILD_ONECORE) - -add_compile_options(/Zl) # omit default library name in .OBJ -add_compile_options(/Zi) # enable debugging information -add_compile_options(/nologo) # Suppress Startup Banner -add_compile_options(/W3) # set warning level to 3 -#add_compile_options(/WX-) # treat warnings as errors -add_compile_options(/wd4996) # Ignore deprecation warnings -add_compile_options(/Od) # enable intrinsics -add_compile_options(/sdl) - -add_compile_options(/Gm) # minimal rebuild -add_compile_options(/EHsc) # enable C++ EH (w/ SEH exceptions) -add_compile_options(/RTC1) -#add_compile_options(/MDd) -add_compile_options(/MD) -add_compile_options(/GS) # Buffer Security Check -add_compile_options(/fp:precise) -add_compile_options(/Zp8) # pack structs on 8-byte boundary -add_compile_options(/Zc:wchar_t) # C++ language conformance: wchar_t is NOT the native type, but a typedef -#add_compile_options(/U_WINDOWS) - -add_definitions( - -D_WIN64 - -D_AMD64_ - -DAMD64 - -D_APISET_WINDOWS_VERSION=0x601 - -D_APISET_MINWIN_VERSION=0x0101 - -D_APISET_MINCORE_VERSION=0x0100 - -DNTDDI_VERSION=0x0A000002 - # -DWIN32=100 - -D_DEBUG - -D_UNICODE - -DUNICODE - -DWIN32_LEAN_AND_MEAN=1 - #-DNDEBUG - ) - -set(CMAKE_ENABLE_EXPORTS ON) - -set(MY_COMMON_LINK_FLAGS "/NOLOGO /MANIFEST:NO /NXCOMPAT /DYNAMICBASE /TLBID:1 /MACHINE:x64 /guard:cf /OPT:REF /OPT:ICF /NODEFAULTLIB") -set(MY_COMMON_LINK_FLAGS "${MY_COMMON_LINK_FLAGS} /NODEFAULTLIB:kernel32.lib /NODEFAULTLIB:advapi32.lib") # Explicitly exclude kernel32 and advapi32 since CMake is including them and they block execution on Nano Server - -set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${MY_COMMON_LINK_FLAGS}") -set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /SUBSYSTEM:WINDOWS,6.00 /INCREMENTAL:NO") #windows subsystem - -set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${MY_COMMON_LINK_FLAGS}") -set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /SUBSYSTEM:CONSOLE /INCREMENTAL:NO") #windows subsystem - diff --git a/src/powershell-native/nativemsh/pwrshcommon/CMakeLists.txt b/src/powershell-native/nativemsh/pwrshcommon/CMakeLists.txt deleted file mode 100644 index cbcd67c68fc..00000000000 --- a/src/powershell-native/nativemsh/pwrshcommon/CMakeLists.txt +++ /dev/null @@ -1,39 +0,0 @@ -# -# CMake Instructions for producing pwrshcommon.lib for consumption by powershell.exe and -# pwrshplugin.dll. It is a library that is statically compiled into each binary. -# -add_library(pwrshcommon - pwrshcommon.cpp - WinSystemCallFacade.cpp - ConfigFileReader.cpp - ) - -target_include_directories(pwrshcommon PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) - -# -# VS 2017 corrupts the INCLUDE environment variable when processing the csproj -# file generated for this template. The netfxsdk path is shortened from -# C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\Include\um -# to -# Include\um -# This prevents msbuild from locating corerror.h and throws a resolution error -# during compilation. We work around the problem by force-including the -# contents of the environment variable before it gets corrupted. -# -target_include_directories(pwrshcommon PUBLIC $ENV{INCLUDE}) - -if (BUILD_ONECORE) - # Libraries to use when creating this binary for Windows on OneCore-based SKUs - set(PWRSHCOMMON_WINDOWS_LIBS - ) - set_target_properties(pwrshcommon PROPERTIES COMPILE_DEFINITIONS "CORECLR") -else () # NOT BUILD_ONECORE - # Libraries to use when creating this binary for Windows on full SKUs - # Note: The appropriate libs get added automatically by VS - set(PWRSHCOMMON_WINDOWS_LIBS - ) -endif (BUILD_ONECORE) - -target_link_libraries(pwrshcommon - ${PWRSHCOMMON_WINDOWS_LIBS}) - diff --git a/src/powershell-native/nativemsh/pwrshcommon/ClrHostWrapper.h b/src/powershell-native/nativemsh/pwrshcommon/ClrHostWrapper.h deleted file mode 100644 index e543db457a8..00000000000 --- a/src/powershell-native/nativemsh/pwrshcommon/ClrHostWrapper.h +++ /dev/null @@ -1,443 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// ---------------------------------------------------------------------- -// -// File: ClrHostWrapper.h -// -// Contents: Wrapper for the CLR runtime host -// -// ---------------------------------------------------------------------- - -#pragma once - -#include -#include "NativeMshConstants.h" - -namespace NativeMsh -{ - // - // Abstract class to abstract CLR runtime host operations so that they can be - // replaced with test code during test case execution. - // - class ClrHostWrapper - { - private: - DWORD m_appDomainId; - - public: - ClrHostWrapper() : m_appDomainId(INVALID_APPDOMAIN_ID) {} - virtual ~ClrHostWrapper() {} - - virtual bool IsInitialized() { return false; } - - // Graceful clean up of the object to prevent leaks - virtual unsigned int CleanUpHostWrapper() = 0; - - // - // The following methods are direct thin wrappers for the host calls. - // - virtual unsigned int SetupWrapper(LPCSTR coreClrPathPtr) = 0; - - virtual int InitializeClr( - const char* exePath, - const char* appDomainFriendlyName, - int propertyCount, - const char** propertyKeys, - const char** propertyValues) = 0; - - virtual int CreateDelegate( - const char* entryPointAssemblyName, - const char* entryPointTypeName, - const char* entryPointMethodName, - void** delegate) = 0; - - // TODO: This probably isn't needed - virtual int ShutdownClr() = 0; - }; - - // - // Concrete implementation of the wrapper for CoreClr.dll's - // Platform-Agnostic hosting interface. - // - class CoreClrHostingApiWrapper : public ClrHostWrapper - { - private: - // Handle of CoreClr.dll - HMODULE coreClrHandle; - HMODULE pinnedModuleHandle; - - // CoreCLR.dll API values that are hidden from the user and kept internal. - void* hostHandle; - unsigned int domainId; - - // The name of the CoreCLR native runtime DLL. - PCSTR coreClrDllName = "CoreCLR.dll"; - - // - // Function Pointer Definitions for the function pointers to load from CoreCLR.dll - // - typedef int (STDMETHODCALLTYPE *coreclr_initialize_ptr)( - const char* exePath, - const char* appDomainFriendlyName, - int propertyCount, - const char** propertyKeys, - const char** propertyValues, - void** hostHandle, - unsigned int* domainId); - - typedef int (STDMETHODCALLTYPE *coreclr_shutdown_ptr)( - void* hostHandle, - unsigned int domainId); - - typedef int (STDMETHODCALLTYPE *coreclr_create_delegate_ptr)( - void* hostHandle, - unsigned int domainId, - const char* entryPointAssemblyName, - const char* entryPointTypeName, - const char* entryPointMethodName, - void** delegate); - - // Pointers to exported functions of CoreClr.dll - coreclr_initialize_ptr initPtr; - coreclr_shutdown_ptr shutdownPtr; - coreclr_create_delegate_ptr createDelegatePtr; - - public: - CoreClrHostingApiWrapper() - : coreClrHandle(NULL), - pinnedModuleHandle(NULL), - hostHandle(NULL), - domainId(0), - initPtr(NULL), - shutdownPtr(NULL), - createDelegatePtr(NULL) - {} - - virtual ~CoreClrHostingApiWrapper() - { - this->CleanUpHostWrapper(); - } - - virtual bool IsInitialized() - { - return (NULL != coreClrHandle); - } - - // - // Attempts to load CoreCLR.dll from the specified directory. - // On success pins the dll, sets coreCLRDirectoryPath and returns the HMODULE. - // On failure returns NULL. - // - virtual unsigned int SetupWrapper(LPCSTR coreClrPathPtr) - { - std::string coreClrPath(coreClrPathPtr); - coreClrPath += coreClrDllName; - - HMODULE result = LoadLibraryExA(coreClrPath.c_str(), NULL, 0); - if (!result) - { - return EXIT_CODE_INIT_FAILURE; - } - - // Pin the module - CoreCLR.dll does not support being unloaded. - if (!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_PIN, coreClrPath.c_str(), &pinnedModuleHandle)) - { - return EXIT_CODE_INIT_FAILURE; - } - - initPtr = (coreclr_initialize_ptr)GetProcAddress(result, "coreclr_initialize"); - shutdownPtr = (coreclr_shutdown_ptr)GetProcAddress(result, "coreclr_shutdown"); - createDelegatePtr = (coreclr_create_delegate_ptr)GetProcAddress(result, "coreclr_create_delegate"); - - if (NULL == initPtr || - NULL == shutdownPtr || - NULL == createDelegatePtr) - { - return EXIT_CODE_INIT_FAILURE; - } - - // Initialization succeeded. Save the handle and return success; - coreClrHandle = result; - return EXIT_CODE_SUCCESS; - } - - virtual unsigned int CleanUpHostWrapper() - { - if (this->IsInitialized()) - { - HRESULT status = this->ShutdownClr(); - if (FAILED(status)) - { - return g_STOP_CLR_HOST_FAILED; - } - - if (this->coreClrHandle) - { - // TODO: Is this comment still relevant with the new hosting API? - // - // Free the module. This is done for completeness, but in fact CoreCLR.dll - // was pinned earlier so this call won't actually free it. The pinning is - // done because CoreCLR does not support unloading. - ::FreeLibrary(this->coreClrHandle); - this->coreClrHandle = NULL; - } - } - return EXIT_CODE_SUCCESS; - } - - virtual int InitializeClr( - const char* exePath, - const char* appDomainFriendlyName, - int propertyCount, - const char** propertyKeys, - const char** propertyValues) - { - if (initPtr) - { - return initPtr( - exePath, - appDomainFriendlyName, - propertyCount, - propertyKeys, - propertyValues, - &(this->hostHandle), - &(this->domainId)); - } - return E_FAIL; - } - - virtual int CreateDelegate( - const char* entryPointAssemblyName, - const char* entryPointTypeName, - const char* entryPointMethodName, - void** delegate) - { - if (createDelegatePtr) - { - return createDelegatePtr( - this->hostHandle, - this->domainId, - entryPointAssemblyName, - entryPointTypeName, - entryPointMethodName, - delegate); - } - return E_FAIL; - } - - virtual int ShutdownClr() - { - if (shutdownPtr) - { - return shutdownPtr( - this->hostHandle, - this->domainId); - } - return E_FAIL; - } - }; - - // Encapsulates the environment that CoreCLR will run in, including the TPALIST - class HostEnvironment - { - private: - // The path to this module - char m_hostPath[MAX_PATH]; - wchar_t m_hostPathW[MAX_PATH]; - - // The path to the directory containing this module - char m_hostDirectoryPath[MAX_PATH]; - wchar_t m_hostDirectoryPathW[MAX_PATH]; - - // The name of this module, without the path - std::string m_hostBinaryName; - std::wstring m_hostBinaryNameW; - - // The path to the directory that CoreCLR is in - char m_coreCLRDirectoryPath[MAX_PATH]; - wchar_t m_coreCLRDirectoryPathW[MAX_PATH]; - - void convertAnsiToWide(char* ansiArray, wchar_t* wideArray) - { - // Generate the wide version of the string and save its value; - // - // This is a two call function. The first call is to get the necessary length. - // The second call is to perform the actual operation. - int length = ::MultiByteToWideChar(CP_UTF8, 0, ansiArray, -1, NULL, 0); - if (0 < length) - { - LPWSTR result = new wchar_t[length]; - if (NULL != result) - { - length = ::MultiByteToWideChar(CP_UTF8, 0, ansiArray, -1, result, length); - if (0 < length) - { - wcscpy_s(wideArray, MAX_PATH, result); - } - delete[] result; // Free the allocated string to avoid a memory leak - } - } - } - - void convertWideToAnsi(wchar_t* wideArray, char* ansiArray) - { - // Generate the ansi version of the string and save its value; - // - // This is a two call function. The first call is to get the necessary length. - // The second call is to perform the actual operation. - int length = ::WideCharToMultiByte(CP_ACP, 0, wideArray, -1, NULL, 0, NULL, NULL); - if (0 < length) - { - LPSTR result = new char[length]; - if (NULL != result) - { - length = ::WideCharToMultiByte(CP_ACP, 0, wideArray, -1, result, length, NULL, NULL); - if (0 < length) - { - strcpy_s(ansiArray, MAX_PATH, result); - } - delete[] result; // Free the allocated string to avoid a memory leak - } - } - } - - public: - - HostEnvironment() - { - memset(m_hostPath, 0, sizeof(m_hostPath)); - memset(m_hostDirectoryPath, 0, sizeof(m_hostDirectoryPath)); - memset(m_coreCLRDirectoryPath, 0, sizeof(m_coreCLRDirectoryPath)); - } - - ~HostEnvironment() {} - - // Safely copies in a host path - void SetHostPath(PCSTR hostPath) - { - if (hostPath) - { - ::ExpandEnvironmentStringsA(hostPath, m_hostPath, MAX_PATH); - - convertAnsiToWide(m_hostPath, m_hostPathW); - } - } - void SetHostPathW(PCWSTR hostPath) - { - if (hostPath) - { - ::ExpandEnvironmentStringsW(hostPath, m_hostPathW, MAX_PATH); - - convertWideToAnsi(m_hostPathW, m_hostPath); - } - } - - // Returns the path to the host module - PCSTR GetHostPath() - { - return m_hostPath; - } - - PCWSTR GetHostPathW() - { - return m_hostPathW; - } - - // Safely copies in a host binary name - void SetHostBinaryName(PCSTR hostBinaryName) - { - if (hostBinaryName) - { - m_hostBinaryName = std::string(hostBinaryName); - } - } - - void SetHostBinaryNameW(PCWSTR hostBinaryName) - { - if (hostBinaryName) - { - m_hostBinaryNameW = std::wstring(hostBinaryName); - } - } - - // Returns the name of the host module - PCSTR GetHostBinaryName() - { - return m_hostBinaryName.c_str(); - } - - PCWSTR GetHostBinaryNameW() - { - return m_hostBinaryNameW.c_str(); - } - - // Safely copies in a host directory path - void SetHostDirectoryPath(PCSTR hostDirPath) - { - if (hostDirPath) - { - ::ExpandEnvironmentStringsA(hostDirPath, m_hostDirectoryPath, MAX_PATH); - - convertAnsiToWide(m_hostDirectoryPath, m_hostDirectoryPathW); - } - } - - void SetHostDirectoryPathW(PCWSTR hostDirPath) - { - if (hostDirPath) - { - ::ExpandEnvironmentStringsW(hostDirPath, m_hostDirectoryPathW, MAX_PATH); - - convertWideToAnsi(m_hostDirectoryPathW, m_hostDirectoryPath); - } - } - - // Returns the directory path of the host module - PCSTR GetHostDirectoryPath() - { - return m_hostDirectoryPath; - } - - // Returns the directory path of the host module as a wide char string - PCWSTR GetHostDirectoryPathW() - { - return m_hostDirectoryPathW; - } - - // Safely copies in a core clr directory path - void SetCoreCLRDirectoryPath(PCSTR hostClrPath) - { - if (hostClrPath) - { - ::ExpandEnvironmentStringsA(hostClrPath, m_coreCLRDirectoryPath, MAX_PATH); - - convertAnsiToWide(m_coreCLRDirectoryPath, m_coreCLRDirectoryPathW); - } - } - - void SetCoreCLRDirectoryPathW(PCWSTR hostClrPath) - { - if (hostClrPath) - { - ::ExpandEnvironmentStringsW(hostClrPath, m_coreCLRDirectoryPathW, MAX_PATH); - - convertWideToAnsi(m_coreCLRDirectoryPathW, m_coreCLRDirectoryPath); - } - } - - // Returns the directory path of the host module - PCSTR GetCoreCLRDirectoryPath() - { - return m_coreCLRDirectoryPath; - } - - // Returns the directory path of the host module - PCWSTR GetCoreCLRDirectoryPathW() - { - return m_coreCLRDirectoryPathW; - } - - - }; -} // namespace NativeMsh diff --git a/src/powershell-native/nativemsh/pwrshcommon/ConfigFileReader.cpp b/src/powershell-native/nativemsh/pwrshcommon/ConfigFileReader.cpp deleted file mode 100644 index f212917e55c..00000000000 --- a/src/powershell-native/nativemsh/pwrshcommon/ConfigFileReader.cpp +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#include -#include -#include - -#include "NativeMsh.h" -#include "ConfigFileReader.h" - -namespace NativeMsh -{ - // The name of the PowerShell config file that identifies the PowerShell install location. - // We use a config file to avoid writing to the registry during install - // or hard coding paths into the binary. - static PCWSTR powerShellConfigFileName = L"RemotePowerShellConfig.txt"; - - ConfigFileReader::ConfigFileReader() - { - } - - unsigned int ConfigFileReader::Read( - std::wstring pathToConfig) - { - std::wstring absolutePathToConfigFile(pathToConfig); - absolutePathToConfigFile += powerShellConfigFileName; - std::wfstream psConfigFile(absolutePathToConfigFile.c_str()); - - if (!psConfigFile.is_open()) - { - return EXIT_CODE_INIT_FAILURE; - } - - std::wstring line; - std::wstring psHomeDirTag(L"PSHOMEDIR="); - std::wstring coreClrDirTag(L"CORECLRDIR="); - while (std::getline(psConfigFile, line)) - { - // Search for the first actionable character in the line to - // limit the number of passes that are made iterating through the line. - for(std::wstring::const_iterator iter = line.begin(); iter != line.end(); iter++) - { - if (*iter == L'#') - { - // Stop parsing the line because the rest of it is a comment - break; - } - else if (*iter == L'p' || *iter == L'P') - { - std::wstring psHomeDir = this->getValueFromLine(line, psHomeDirTag); - HANDLE dirHandle = CreateFileW(psHomeDir.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); - if (INVALID_HANDLE_VALUE != dirHandle) - { - CloseHandle(dirHandle); - this->pathToPowerShellAssemblies = psHomeDir; - std::wstring::const_iterator slashIter = this->pathToPowerShellAssemblies.end(); - slashIter--; - if (*slashIter != L'\\') - { - // Guarantee that there is a '\' at the end of the path - this->pathToPowerShellAssemblies.append(L"\\"); - } - } - break; - } - else if (*iter == L'c' || *iter == L'C') - { - std::wstring coreClrDir = this->getValueFromLine(line, coreClrDirTag); - HANDLE dirHandle = CreateFileW(coreClrDir.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); - if (INVALID_HANDLE_VALUE != dirHandle) - { - CloseHandle(dirHandle); - this->coreClrDirectory = coreClrDir; - std::wstring::const_iterator slashIter = this->coreClrDirectory.end(); - slashIter--; - if (*slashIter != L'\\') - { - // Guarantee that there is a '\' at the end of the path - this->coreClrDirectory.append(L"\\"); - } - } - break; - } - // Else: Do nothing to ignore unmatched characters (whitespace, etc.) - } - } - if (0 == this->pathToPowerShellAssemblies.size() || - 0 == this->coreClrDirectory.size()) - { - return EXIT_CODE_INIT_FAILURE; - } - else - { - return EXIT_CODE_SUCCESS; - } - } - - // This trim function removes beginning and ending whitespace. It does not - // remove internal whitespace because that is valid within paths. - std::wstring ConfigFileReader::trim( - const std::wstring& toTrim) - { - static PCWSTR WHITESPACE_CHARS = L" \n\r\t"; - std::wstring copyToTrim = toTrim; - std::size_t first = copyToTrim.find_first_not_of(WHITESPACE_CHARS); - - if (first == std::wstring::npos) - { - // No non-whitespace found - return std::wstring(L""); - } - - // Result not checked for std::wstring::npos because it is guaranteed to have a value if the first pass succeeded. - copyToTrim.erase(copyToTrim.find_last_not_of(WHITESPACE_CHARS)+1); - - return copyToTrim.substr(first); - } - - // Parses the specified line for the given tag. Tags are assumed to include - // the "=" separator character. - std::wstring ConfigFileReader::getValueFromLine( - const std::wstring& line, // Passed by value to preserve the original line. - std::wstring& tagToFind) - { - std::wstring trimmedLine = this->trim(line); - std::size_t index = trimmedLine.find(tagToFind); - if (std::string::npos != index) - { - std::wstring value = trimmedLine.substr(index + tagToFind.size()); // Everything else after the tag - return this->trim(value); - } - else - { - return std::wstring(L""); - } - } -} - diff --git a/src/powershell-native/nativemsh/pwrshcommon/ConfigFileReader.h b/src/powershell-native/nativemsh/pwrshcommon/ConfigFileReader.h deleted file mode 100644 index e406b886501..00000000000 --- a/src/powershell-native/nativemsh/pwrshcommon/ConfigFileReader.h +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// --------------------------------------------------------------------------- -// -// Contents: A class that extracts the path to $PSHOME and the path to its -// CoreCLR from a configuration file. -// --------------------------------------------------------------------------- - -#pragma once - -#include - -namespace NativeMsh -{ - class ConfigFileReader - { - private: - std::wstring pathToPowerShellAssemblies; - std::wstring coreClrDirectory; - - std::wstring trim(const std::wstring& toTrim); - std::wstring getValueFromLine(const std::wstring& line, std::wstring& tagToFind); - - public: - ConfigFileReader(); - - // Initiates a Read operation of the specified configuration file. - unsigned int Read(std::wstring pathToConfig); - - // Information Getters - std::wstring GetPathToPowerShell() { return pathToPowerShellAssemblies; } - std::wstring GetPathToCoreClr() { return coreClrDirectory; } - }; -} // namespace NativeMsh - diff --git a/src/powershell-native/nativemsh/pwrshcommon/IPwrshCommonOutput.h b/src/powershell-native/nativemsh/pwrshcommon/IPwrshCommonOutput.h deleted file mode 100644 index 2f66ed10fd7..00000000000 --- a/src/powershell-native/nativemsh/pwrshcommon/IPwrshCommonOutput.h +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include - -namespace NativeMsh -{ - // - // Implement this interface to override the default no-op behaviour of the output. - // - class IPwrshCommonOutput - { - public: - // Virtual destructor to ensure that derived destructors are called - // during base class destruction. - virtual ~IPwrshCommonOutput() {} - - virtual VOID DisplayMessage( - bool bUseStdOut, - DWORD dwMessageId, - ...) = 0; - - virtual void DisplayErrorWithSystemError( - LONG lSystemErrorCode, - int messageId, - LPCWSTR insertionParam) = 0; - }; -} diff --git a/src/powershell-native/nativemsh/pwrshcommon/NativeMsh.h b/src/powershell-native/nativemsh/pwrshcommon/NativeMsh.h deleted file mode 100644 index ff2e82bf4d7..00000000000 --- a/src/powershell-native/nativemsh/pwrshcommon/NativeMsh.h +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// ---------------------------------------------------------------------- -// -// File: NativeMsh.h -// -// Contents: common code required to start powershell (exe and plugin) -// -// ---------------------------------------------------------------------- - -#pragma once - -#include -#include -#include -#include "NativeMshConstants.h" -#include "ClrHostWrapper.h" -#include "SystemCallFacade.h" -#include "ConfigFileReader.h" -#include "IPwrshCommonOutput.h" - -#if !CORECLR -#include -#endif - -namespace NativeMsh -{ - class PwrshCommon - { - private: - IPwrshCommonOutput* output; - ConfigFileReader* reader; - SystemCallFacade* sysCalls; - - public: - // Provides default implementations of all dependencies - PwrshCommon(); - - // Allows users to override the default dependency objects with a specific implementations. - // - // Note: This object deletes the pointers that are provided, so clients should - // allocate them with "new". - PwrshCommon( - IPwrshCommonOutput* outObj, // Enables clients to specify how error messages are displayed or suppressed - ConfigFileReader* rdr, // Enables specification of how the config file is read. - SystemCallFacade* systemCalls); // Wraps all calls to Windows APIs to allow for dependency injection via unit test - - ~PwrshCommon(); - - // - // The following functions are used by the components that link to this lib - // - bool StringIsNullOrEmpty( - LPCWSTR wsz); - - // TODO: This is static because it is needed by the EXE's output object. Design wise, it is a little awkward to do this, but it resolve the circular reference and circular initialization issue - static DWORD GetSystemErrorMessage( - IN LONG lErrorCode, - __deref_out_opt PWSTR * pwszErrorMessage); - - bool VerifyMonadVersionFormat( - LPCWSTR wszMonadVersion, - int * lpMajorVersion, - int * lpMinorVersion, - bool bAllowMinorVersion, - bool bReportError); - - unsigned int OpenEngineRegKey( - __deref_out_ecount(1) PHKEY phEngineKey, - __deref_out_opt PWSTR * pwszMshEngineRegKey, - __deref_out_opt PWSTR * pwszMonadVersion, - __inout_ecount(1) int* lpMonadMajorVersion); - - // API used to read a particular registry key value from the PowerShellEngine - // regkey path. For example to read "ApplicationBase" or "ConsoleHostAssemblyName" - // - // Note: During successful calls the following values must be freed by the caller: - // pwszMonadVersion - // pwszRuntimeVersion - // pwszRegKeyValue - // - // The caller must take care to check to see if they must be freed during error scenarios - // because the function may fail after allocating one or more strings. - // - _Success_(return == 0) - unsigned int GetRegistryInfo( - __out PWSTR * pwszMonadVersion, - __inout_ecount(1) int * lpMonadMajorVersion, - int monadMinorVersion, - __out PWSTR * pwszRuntimeVersion, - LPCWSTR lpszRegKeyNameToRead, - __out PWSTR * pwszRegKeyValue); - - _Success_(return == 0) - unsigned int GetRegistryInfo( - __out PWSTR * pwszMonadVersion, - __inout_ecount(1) int * lpMonadMajorVersion, - int monadMinorVersion, - __out PWSTR * pwszRuntimeVersion, - __out PWSTR * pwszConsoleHostAssemblyName); - - unsigned int LaunchCoreCLR( - ClrHostWrapper* hostWrapper, - HostEnvironment& hostEnvironment, - PCSTR friendlyName); - -#if !CORECLR - // NOTE: - // This must be ifdef'd out of the CoreCLR build because it uses .NET 1.0 - // types that have been deprecated and removed from mscoree.h. - // - // This code may be removed from #if protection once ICorRuntimeHost is - // upgraded to ICLRRuntimeHost. - // - unsigned int LaunchCLR( - LPCWSTR wszMonadVersion, - LPCWSTR wszRuntimeVersion, - __in_ecount(1) ICorRuntimeHost** pCLR); -#endif // !CORECLR - - protected: - // These methods are exposed as protected here to make them unit testable. - // Note: I tried hiding them within PwrshCommonFriend in pwrshcommon.cpp, but it made the unit testing difficult. - // Virtual methods may be overridden in the test code. - bool ParseInt( - const WCHAR * pwchStart, - const WCHAR * pwchEnd, - int * pInt); - - _Success_(return) bool ExtractFirstVersionComponent( - LPCWSTR wszVersionString, - int* lpFirstVersionComponent, - __deref_out_opt WCHAR** wszRemainingVersionString); - - bool RegOpenKeyWithErrorReport( - LPCWSTR wszRegPath, - LPCWSTR wszMonadVersion, - __out_ecount(1) PHKEY phResult); - - bool FormatStringWithErrorReporting( - LPCWSTR wszFormat, - __deref_out_opt PWSTR * pwszResult, - __out_ecount(1) LPDWORD lpdwLength, - int errorMessageId, - ...); - - bool OpenLatestMSHEngineRegistry( - __out_ecount(1) PHKEY phResult, - __deref_out_opt PWSTR * pwszMshEngineRegKeyPath, - __deref_out_opt PWSTR * pwszMonadVersion, - __out_ecount(1) int * lpMonadMajorVersion); - - bool RegQueryREG_SZValue( - _In_ HKEY hEngineKey, - _In_ LPCWSTR wszValueName, - _In_ LPCWSTR wszMshEngineRegKey, - __deref_out_opt PWSTR * pwszRegData); - - unsigned int IsEngineRegKeyWithVersionExisting( - LPCWSTR wszMonadVersion, - LPCWSTR wszMonadMajorVersion); - - unsigned int OpenEngineRegKeyWithVersion( - __deref_out_ecount(1) PHKEY phEngineKey, - __deref_out_opt PWSTR * pwszMshEngineRegKey, - LPCWSTR wszMonadVersion, - int monadMajorVersion); - - bool VerifyDOTNetVersionFormat( - LPCWSTR wszFullVersion, - __out_ecount(1) int * lpMajorVersion, - __out_ecount(1) int * lpMinorVersion); - - virtual bool DoesAssemblyExist( - std::string& fileToTest); - - virtual void ProbeAssembly( - _In_z_ PCSTR directoryPath, - _In_z_ PCSTR assemblyName, - std::string& result); - - virtual void GetTrustedAssemblyList( - PCSTR coreCLRDirectoryPath, - std::stringstream& assemblyList, - bool& listEmpty); - - virtual unsigned int IdentifyHostDirectory( - HostEnvironment& hostEnvironment); - - private: - // Explicitly disallow copy construction and assignment - PwrshCommon(const PwrshCommon&); - PwrshCommon& operator=(const PwrshCommon&); - }; -} // namespace NativeMsh diff --git a/src/powershell-native/nativemsh/pwrshcommon/NativeMshConstants.h b/src/powershell-native/nativemsh/pwrshcommon/NativeMshConstants.h deleted file mode 100644 index d8bb368abe1..00000000000 --- a/src/powershell-native/nativemsh/pwrshcommon/NativeMshConstants.h +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include - -namespace NativeMsh -{ - // - // Begin nativemsh.mc codes - // - const int g_MISSING_COMMAND_LINE_ARGUMENT = 1; - const int g_INVALID_CONSOLE_FILE_PATH = 2; - const int g_CLR_VERSION_NOT_INSTALLED = 3; - const int g_CORBINDTORUNTIME_FAILED = 4; - const int g_STARTING_CLR_FAILED = 5; - const int g_GETTING_DEFAULT_DOMAIN_FAILED = 6; - const int g_CREATING_MSH_ENTRANCE_FAILED = 7; - const int g_GETTING_DISPATCH_ID_FAILED = 8; - const int g_INOVKING_MSH_ENTRANCE_FAILED = 9; - const int g_MANAGED_MSH_EXCEPTION = 10; - const int g_READ_XML_COM_INIT_FAILED = 11; - const int g_READ_XML_CREATE_DOMDOCUMENT_FAILED = 12; - const int g_READ_XML_LOAD_FILE_FAILED = 13; - const int g_EMPTY_REG_SZ_VALUE = 14; - const int g_READ_XML_GET_CONSOLE_SCHEMA_VERSION_FAILED = 15; - const int g_READ_XML_INVALID_CONSOLE_SCHEMA_VERSION = 16; - const int g_INVALID_MONAD_VERSION = 17; - const int g_READ_XML_GET_MONAD_VERSION_TEXT_FAILED = 18; - const int g_SEARCH_LATEST_REG_KEY_FAILED_WITH = 19; - const int g_OPEN_REG_KEY_FAILED_WITH = 20; - const int g_CLOSE_REG_KEY_FAILED_WITH = 21; - const int g_READ_REG_VALUE_FAILED_WITH = 22; - const int g_CREATE_MSHENGINE_REG_KEY_PATH_FAILED_WITH = 23; - const int g_EXPECT_REG_SZ_VALUE = 24; - const int g_MSH_VERSION_NOT_INSTALLED = 25; - const int g_INCORRECT_CONSOLE_FILE_EXTENSION = 26; - const int g_INVALID_REG_MSHVERSION_VALUE = 27; - const int g_INCOMPATIBLE_MINOR_VERSION = 28; - const int g_NO_COMPLETELY_INSTALLED_FOUND_VERSION = 29; - const int g_MISSING_REG_KEY = 30; - const int g_READ_XML_LOAD_FILE_FAILED_WITH_SPECIFIC_ERROR = 31; - const int g_READ_XML_LOAD_FILE_FAILED_WITH_SPECIFIC_POSITION_ERROR = 32; - const int g_READ_XML_GET_EMPTY_MONAD_VERSION_TEXT = 33; - const int g_READ_XML_GET_PSCONSOLEFILE_FAILED = 34; - const int g_NOTSUPPORTED_MONAD_VERSION = 35; - const int g_NONSTANDARD_CLR_VERSION = 36; - const int g_SHELLBANNER1 = 37; - const int g_SHELLBANNER2 = 38; - // Win8: 622653 Creating a copy of g_MISSING_REG_KEY to address scenarios where pwszMonadVersion is NULL. - const int g_MISSING_REG_KEY1 = 39; - // - // End nativemsh.mc codes - // - const int g_UNLOAD_APPDOMAIN_FAILED = 40; - const int g_STOP_CLR_HOST_FAILED = 41; - const int g_RELEASE_CLR_HOST_FAILED = 42; - - const int g_MAX_REG_KEY_LENGTH = 255 + 1; - - const int g_MAX_VERSION_FIELD_LENGTH = 10; - - const unsigned int EXIT_CODE_SUCCESS = 0x00000000; - const unsigned int EXIT_CODE_INIT_FAILURE = 0xFFFF0000; - const unsigned int EXIT_CODE_BAD_COMMAND_LINE_PARAMETER = 0xFFFD0000; - const unsigned int EXIT_CODE_READ_CONSOLE_FILE_FAILURE = 0xFFFC0000; - const unsigned int EXIT_CODE_READ_REGISTRY_FAILURE = 0xFFFB0000; - const unsigned int EXIT_CODE_INCOMPATIBLE_MSH_VERSION = 0xFFFA0000; - - const DWORD INVALID_APPDOMAIN_ID = (DWORD)-1; // TODO: valid uninitialized value? -} // namespace NativeMsh diff --git a/src/powershell-native/nativemsh/pwrshcommon/SystemCallFacade.h b/src/powershell-native/nativemsh/pwrshcommon/SystemCallFacade.h deleted file mode 100644 index 63b4b583ed1..00000000000 --- a/src/powershell-native/nativemsh/pwrshcommon/SystemCallFacade.h +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// ---------------------------------------------------------------------- -// -// File: SystemCallFacade.h -// -// Contents: Facade for Windows API system calls -// -// ---------------------------------------------------------------------- - -#pragma once - -#include -#include - -namespace NativeMsh -{ - // - // Abstract class to abstract system call operations so that they can be - // replaced with test code during test case execution. - // - class SystemCallFacade - { - public: - SystemCallFacade() {} - virtual ~SystemCallFacade() {} - - // Module Manipulation Wrappers - virtual HMODULE WINAPI LoadLibraryExW( - _In_ PCWSTR lpFileName, - _Reserved_ HANDLE hFile, - _In_ DWORD dwFlags) = 0; - - virtual DWORD WINAPI GetModuleFileNameA( - _In_opt_ HMODULE hModule, - _Out_ LPSTR lpFilename, - _In_ DWORD nSize) = 0; - - virtual HMODULE WINAPI GetModuleHandleA( - _In_opt_ PCSTR lpModuleName) = 0; - - virtual FARPROC WINAPI GetProcAddress( - _In_ HMODULE hModule, - _In_ LPCSTR lpProcName) = 0; - - virtual BOOL WINAPI FreeLibrary( - _In_ HMODULE hModule) = 0; - - // File Manipulation Wrappers - virtual errno_t fopen_s( - FILE** file, - const char *filename, - const char *mode) = 0; - - virtual int fclose( - FILE *stream) = 0; - }; - -} // namespace NativeMsh diff --git a/src/powershell-native/nativemsh/pwrshcommon/WinSystemCallFacade.cpp b/src/powershell-native/nativemsh/pwrshcommon/WinSystemCallFacade.cpp deleted file mode 100644 index 36927735714..00000000000 --- a/src/powershell-native/nativemsh/pwrshcommon/WinSystemCallFacade.cpp +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// ---------------------------------------------------------------------- -// -// File: WinSystemCallFacade.h -// -// Contents: Wraps the actual API calls for production scenarios. -// -// ---------------------------------------------------------------------- - -#include "WinSystemCallFacade.h" - -namespace NativeMsh -{ - HMODULE WINAPI WinSystemCallFacade::LoadLibraryExW( - _In_ LPCWSTR lpFileName, - _Reserved_ HANDLE hFile, - _In_ DWORD dwFlags) - { - return ::LoadLibraryExW(lpFileName, hFile, dwFlags); - } - -#pragma prefast(push) -#pragma prefast (disable: 26006) // Possibly incorrect single element annotation on string buffer - This is a thin wrapper around a system call, so it's behavior is not controllable. - - DWORD WINAPI WinSystemCallFacade::GetModuleFileNameA( - _In_opt_ HMODULE hModule, - _Out_ LPSTR lpFilename, // _Out_writes_to_(nSize, return +1) OR __out_ecount_part(nSize, return + 1)? __out_ecount(nSize) - _In_ DWORD nSize) - { - return ::GetModuleFileNameA(hModule, lpFilename, nSize); - } - -#pragma prefast(pop) - - HMODULE WINAPI WinSystemCallFacade::GetModuleHandleA( - _In_opt_ LPCSTR lpModuleName) - { - return ::GetModuleHandleA(lpModuleName); - } - - FARPROC WINAPI WinSystemCallFacade::GetProcAddress( - _In_ HMODULE hModule, - _In_ LPCSTR lpProcName) - { - return ::GetProcAddress(hModule, lpProcName); - } - - BOOL WINAPI WinSystemCallFacade::FreeLibrary( - _In_ HMODULE hModule) - { - return ::FreeLibrary(hModule); - } - - errno_t WinSystemCallFacade::fopen_s( - FILE** file, - const char *filename, - const char *mode) - { - return ::fopen_s(file, filename, mode); - } - - int WinSystemCallFacade::fclose( - FILE *stream) - { - return ::fclose(stream); - } - -} // namespace NativeMsh diff --git a/src/powershell-native/nativemsh/pwrshcommon/WinSystemCallFacade.h b/src/powershell-native/nativemsh/pwrshcommon/WinSystemCallFacade.h deleted file mode 100644 index 0d60b8838cd..00000000000 --- a/src/powershell-native/nativemsh/pwrshcommon/WinSystemCallFacade.h +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// ---------------------------------------------------------------------- -// -// File: WinSystemCallFacade.h -// -// Contents: Wraps the actual API calls for production scenarios. -// -// ---------------------------------------------------------------------- - -#pragma once - -#include "SystemCallFacade.h" - -namespace NativeMsh -{ - // - // Actual implementation of the system calls for use during production. - // - class WinSystemCallFacade : public SystemCallFacade - { - public: - WinSystemCallFacade() {} - virtual ~WinSystemCallFacade() {} - - // Module Manipulation Wrappers - virtual HMODULE WINAPI LoadLibraryExW( - _In_ PCWSTR lpFileName, - _Reserved_ HANDLE hFile, - _In_ DWORD dwFlags); - - virtual DWORD WINAPI GetModuleFileNameA( - _In_opt_ HMODULE hModule, - _Out_ LPSTR lpFilename, - _In_ DWORD nSize); - - virtual HMODULE WINAPI GetModuleHandleA( - _In_opt_ LPCSTR lpModuleName); - - virtual FARPROC WINAPI GetProcAddress( - _In_ HMODULE hModule, - _In_ LPCSTR lpProcName); - - virtual BOOL WINAPI FreeLibrary( - _In_ HMODULE hModule); - - // File Manipulation Wrappers - virtual errno_t fopen_s( - FILE** file, - const char *filename, - const char *mode); - - virtual int fclose( - FILE *stream); - }; - -} // namespace NativeMsh diff --git a/src/powershell-native/nativemsh/pwrshcommon/pwrshcommon.cpp b/src/powershell-native/nativemsh/pwrshcommon/pwrshcommon.cpp deleted file mode 100644 index 79344c6bef4..00000000000 --- a/src/powershell-native/nativemsh/pwrshcommon/pwrshcommon.cpp +++ /dev/null @@ -1,1558 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// -// Implementation of common code used by native PowerShell -// - -#include "NativeMsh.h" -#include -#include -#include -#include -#include "WinSystemCallFacade.h" - -namespace NativeMsh -{ - // - // Defining these as "static" ensures internal linkage of the values. - // For some reason, LPCWSTR is removing that linkage during macro expansion. - // - static LPCWSTR g_MSH_REG_KEY_PATH = L"SOFTWARE\\Microsoft\\PowerShell"; - static LPCWSTR g_MSHVERSION_REG_KEY_PATH_TEMPLATE = L"SOFTWARE\\Microsoft\\PowerShell\\%1!ls!"; - static LPCWSTR g_MSHENGINE_REG_KEY_PATH_TEMPLATE = L"SOFTWARE\\Microsoft\\PowerShell\\%1!ls!\\PowerShellEngine"; - - // - // Definitions of the protected PwrshCommon methods - // - - bool PwrshCommon::ParseInt( - const WCHAR * pwchStart, - const WCHAR * pwchEnd, - int * pInt) - { - bool returnResult = true; - do - { - if (!(*pwchEnd < L'0' || *pwchEnd > L'9')) - { - returnResult = false; - break; - } - if (this->StringIsNullOrEmpty(pwchStart) || pwchStart >= pwchEnd) - { - returnResult = false; - break; - } - //skip leading 0s - while (pwchStart < pwchEnd && (*pwchStart == L'0')) - { - pwchStart++; - } - // MAX_INT has 10 digits only. this ensures the below call to wcstol won't overflow - if (pwchEnd - pwchStart > g_MAX_VERSION_FIELD_LENGTH) - { - returnResult = false; - break; - } - WCHAR * pwchIntEnd = NULL; - // this should never cause overflow because VerifyInteger guarantees pwchMinorVersion - // has less than g_MAX_NUMBER_OF_DIGITS_IN_VERSION which is 10. - unsigned long ulTempResult = wcstoul(pwchStart, &pwchIntEnd, 10); - // Make sure the whole string is an integer and fits an int - if (pwchEnd != pwchIntEnd || ulTempResult > (unsigned long)INT_MAX) - { - returnResult = false; - break; - } - *pInt = (int)ulTempResult; - } while (false); - return returnResult; - } - - _Success_(return) bool PwrshCommon::ExtractFirstVersionComponent( - LPCWSTR wszVersionString, - int* lpFirstVersionComponent, - __deref_out_opt WCHAR** wszRemainingVersionString) - { - bool returnResult = true; - do - { - if (this->StringIsNullOrEmpty(wszVersionString) || - (NULL == lpFirstVersionComponent) || - (NULL == wszRemainingVersionString)) - { - returnResult = false; - break; - } - const WCHAR * pwchDot = wcschr(wszVersionString, L'.'); - const WCHAR * pwchNull = wcschr(wszVersionString, L'\0'); - assert(NULL != pwchNull); - if (NULL == pwchNull) - { - returnResult = false; - break; - } - if (NULL != pwchDot) - { - returnResult = this->ParseInt( - wszVersionString, - pwchDot, - lpFirstVersionComponent); - if (!returnResult) - { - break; - } - *wszRemainingVersionString = _wcsinc(pwchDot); - } - else // pwchDot == NULL - { - returnResult = this->ParseInt( - wszVersionString, - pwchNull, - lpFirstVersionComponent); - if (!returnResult) - { - break; - } - *wszRemainingVersionString = NULL; - } - } while (false); - - return returnResult; - } - -#pragma prefast(push) -#pragma prefast (disable: 6101) -#pragma prefast (disable: 6054) -#pragma prefast (disable: 6001) - - bool PwrshCommon::RegOpenKeyWithErrorReport( - LPCWSTR wszRegPath, - LPCWSTR wszMonadVersion, - __out_ecount(1) PHKEY phResult) - { - bool returnResult = true; - LONG lResult = RegOpenKeyExW(HKEY_LOCAL_MACHINE, wszRegPath, 0, KEY_READ, phResult); - if (ERROR_SUCCESS != lResult) - { - // special case: if the reg key doesn't exist, don't print the win32 system error - // since it's not descriptive - if (ERROR_FILE_NOT_FOUND == lResult) - { - if (NULL == wszMonadVersion) - { - this->output->DisplayMessage(false, - g_MISSING_REG_KEY, - wszRegPath); - } - else - { - this->output->DisplayMessage(false, - g_MISSING_REG_KEY1, - wszRegPath, - wszMonadVersion); - } - } - else - { - this->output->DisplayErrorWithSystemError( - lResult, - g_OPEN_REG_KEY_FAILED_WITH, - wszRegPath); - } - returnResult = false; - } - return returnResult; - } - - bool PwrshCommon::FormatStringWithErrorReporting( - LPCWSTR wszFormat, - __deref_out_opt PWSTR * pwszResult, - __out_ecount(1) LPDWORD lpdwLength, - int errorMessageId, - ...) - { - LPWSTR wszTemp = NULL; - DWORD dwTempLength = 0; - bool returnResult = true; - va_list args; - va_start(args, errorMessageId); - do - { - if (NULL == wszFormat || NULL == pwszResult || NULL == lpdwLength) - { - returnResult = false; - break; - } - dwTempLength = FormatMessageW( - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_STRING, - wszFormat, - 0, - 0, - (LPWSTR)&wszTemp, - 0, - &args); - if (0 == dwTempLength) - { - LONG lastError = GetLastError(); - LPWSTR wszSystemErrorMessage = NULL; - DWORD dwErrorLength = - this->GetSystemErrorMessage( - lastError, - &wszSystemErrorMessage); - if (dwErrorLength > 0) - { - this->output->DisplayMessage(false, errorMessageId, wszSystemErrorMessage); - if (NULL != wszSystemErrorMessage) - { - delete[] wszSystemErrorMessage; - wszSystemErrorMessage = NULL; - } - } - returnResult = false; - break; - } - *pwszResult = new WCHAR[dwTempLength + 1]; - if (NULL == *pwszResult) - { - returnResult = false; - break; - } - //string function - if (SUCCEEDED(StringCchCopy(*pwszResult, dwTempLength + 1, wszTemp))) - { - *lpdwLength = dwTempLength; - } - else - { - if (NULL != *pwszResult) - { - delete[] * pwszResult; - *pwszResult = NULL; - } - returnResult = false; - break; - } - } while (false); - if (0 != dwTempLength) - { - LocalFree(wszTemp); - } - va_end(args); - return returnResult; - } - - bool PwrshCommon::OpenLatestMSHEngineRegistry( - __out_ecount(1) PHKEY phResult, - __deref_out_opt PWSTR * pwszMshEngineRegKeyPath, - __deref_out_opt PWSTR * pwszMonadVersion, - __out_ecount(1) int * lpMonadMajorVersion) - { - bool returnResult = true; - HKEY hMshRegKey = 0; - bool bMshRegKeyOpened = true; - LPWSTR lpSubKeyName = NULL; - do - { - if (NULL == phResult || NULL == pwszMshEngineRegKeyPath || - NULL == pwszMonadVersion || NULL == lpMonadMajorVersion) - { - returnResult = false; - break; - } - *lpMonadMajorVersion = -1; - LPCWSTR mshRegPath = g_MSH_REG_KEY_PATH; - if (!this->RegOpenKeyWithErrorReport(mshRegPath, *pwszMonadVersion, &hMshRegKey)) - { - bMshRegKeyOpened = false; - returnResult = false; - break; - } - lpSubKeyName = new WCHAR[g_MAX_REG_KEY_LENGTH]; - if (NULL == lpSubKeyName) - { - returnResult = false; - break; - } - - DWORD dwIndex = 0; - int latestVersionNumber = 0; - LPWSTR wszLatestSubKeyName = NULL; - DWORD cchLatestSubKeyName = 0; - while (true) - { - DWORD dwSubKeyNameLength = g_MAX_REG_KEY_LENGTH; - FILETIME ftLastWriteTime; - LONG lRegEnumResult = RegEnumKeyEx( - hMshRegKey, - dwIndex++, - lpSubKeyName, - &dwSubKeyNameLength, - NULL, - NULL, - NULL, - &ftLastWriteTime); - if (ERROR_NO_MORE_ITEMS == lRegEnumResult) - { - break; - } - if (ERROR_SUCCESS != lRegEnumResult) - { - this->output->DisplayErrorWithSystemError( - lRegEnumResult, - g_SEARCH_LATEST_REG_KEY_FAILED_WITH, - mshRegPath); - returnResult = false; - break; - } - int majorVersionNumber = 0, minorVersionNumberUnused; - if (this->VerifyMonadVersionFormat(lpSubKeyName, &majorVersionNumber, &minorVersionNumberUnused, false, false)) - { - // This key's name is a valid MSH version - // now it must be a natural number without sign prefix - // string function - if (majorVersionNumber > latestVersionNumber) - { - latestVersionNumber = majorVersionNumber; - cchLatestSubKeyName = dwSubKeyNameLength + 1; - if (NULL != wszLatestSubKeyName) - { - delete[] wszLatestSubKeyName; - wszLatestSubKeyName = NULL; - } - wszLatestSubKeyName = new WCHAR[cchLatestSubKeyName]; - if (NULL == wszLatestSubKeyName) - { - returnResult = false; - break; - } - // string function - if (FAILED(StringCchCopy(wszLatestSubKeyName, cchLatestSubKeyName, lpSubKeyName))) - { - returnResult = false; - break; - } - } - } - } - if (!returnResult) - { - break; - } - if (NULL == wszLatestSubKeyName) - { - this->output->DisplayMessage(false, g_NO_COMPLETELY_INSTALLED_FOUND_VERSION); - returnResult = false; - break; - } - - *pwszMonadVersion = wszLatestSubKeyName; - *lpMonadMajorVersion = latestVersionNumber; - DWORD dwUnused; - if (!this->FormatStringWithErrorReporting( - g_MSHENGINE_REG_KEY_PATH_TEMPLATE, - pwszMshEngineRegKeyPath, - &dwUnused, - g_CREATE_MSHENGINE_REG_KEY_PATH_FAILED_WITH, - wszLatestSubKeyName)) - { - returnResult = false; - break; - } - - returnResult = this->RegOpenKeyWithErrorReport(*pwszMshEngineRegKeyPath, *pwszMonadVersion, phResult); - } while (false); - - if (bMshRegKeyOpened && (NULL != hMshRegKey)) - { - RegCloseKey(hMshRegKey); - } - if (NULL != lpSubKeyName) - { - delete[] lpSubKeyName; - lpSubKeyName = NULL; - } - return returnResult; - } - - bool PwrshCommon::RegQueryREG_SZValue( - _In_ HKEY hEngineKey, - _In_ LPCWSTR wszValueName, - _In_ LPCWSTR wszMshEngineRegKey, - __deref_out_opt PWSTR * pwszRegData) - { - DWORD regValueType = 0; - DWORD valueLengthInByte = 0; - LONG result = 0; - wchar_t * wszValue = NULL; - bool returnResult = true; - - do - { - if (0 == hEngineKey || this->StringIsNullOrEmpty(wszMshEngineRegKey) || NULL == pwszRegData) - { - returnResult = false; - break; - } - // this call checks how many bytes the value occupies - result = RegQueryValueExW( - hEngineKey, - wszValueName, - NULL, - ®ValueType, - NULL, - &valueLengthInByte); - - if (result != ERROR_SUCCESS) - { - wchar_t * wszErrorMessage = NULL; - DWORD errorLength = - this->GetSystemErrorMessage( - result, - &wszErrorMessage); - if (0 < errorLength) - { - this->output->DisplayMessage(false, g_READ_REG_VALUE_FAILED_WITH, wszMshEngineRegKey, wszValueName, wszErrorMessage); - if (NULL != wszErrorMessage) - { - delete[] wszErrorMessage; - wszErrorMessage = NULL; - } - } - returnResult = false; - break; - } - if (REG_SZ != regValueType) - { - this->output->DisplayMessage(false, g_EXPECT_REG_SZ_VALUE, wszMshEngineRegKey, wszValueName); - returnResult = false; - break; - }; - if (0 == valueLengthInByte) - { - this->output->DisplayMessage(false, g_EMPTY_REG_SZ_VALUE, wszMshEngineRegKey, wszValueName); - returnResult = false; - break; - } - DWORD valueLength = valueLengthInByte / sizeof(wchar_t); - - wszValue = new wchar_t[valueLength + 1]; // plus 1 as RegQueryValueExW may not return null terminated string - if (NULL == wszValue) - { - returnResult = false; - break; - } - wszValue[valueLength] = L'\0'; // make sure wszValue is null terminated as RegQueryValueExW's returned value - // may not be null terminated - - result = RegQueryValueExW( - hEngineKey, - wszValueName, - NULL, - NULL, - (LPBYTE)wszValue, //simply casting to LPBYTE will make the returned unicode array work! - &valueLengthInByte); - if (result != ERROR_SUCCESS) - { - wchar_t * wszErrorMessage = NULL; - DWORD errorLength = - this->GetSystemErrorMessage( - result, - &wszErrorMessage); - if (0 < errorLength) - { - this->output->DisplayMessage(false, g_READ_REG_VALUE_FAILED_WITH, wszMshEngineRegKey, wszValueName, wszErrorMessage); - if (NULL != wszErrorMessage) - { - delete[] wszErrorMessage; - wszErrorMessage = NULL; - } - } - delete[] wszValue; - wszValue = NULL; - returnResult = false; - break; - } - } while (false); - if (returnResult && this->StringIsNullOrEmpty(wszValue)) - { - this->output->DisplayMessage(false, g_EMPTY_REG_SZ_VALUE, wszMshEngineRegKey, wszValueName); - returnResult = false; - } - *pwszRegData = wszValue; - return returnResult; - } - - unsigned int PwrshCommon::IsEngineRegKeyWithVersionExisting( - LPCWSTR wszMonadVersion, - LPCWSTR wszMonadMajorVersion) - { - unsigned int exitCode = EXIT_CODE_SUCCESS; - LPWSTR wszVersionKey = NULL; - DWORD dwLength = 0; - HKEY hVersionKey = NULL; - do - { - if (this->StringIsNullOrEmpty(wszMonadVersion) || - this->StringIsNullOrEmpty(wszMonadMajorVersion)) - { - exitCode = EXIT_CODE_READ_REGISTRY_FAILURE; - break; - } - if (!this->FormatStringWithErrorReporting( - g_MSHVERSION_REG_KEY_PATH_TEMPLATE, - &wszVersionKey, - &dwLength, - g_CREATE_MSHENGINE_REG_KEY_PATH_FAILED_WITH, - wszMonadMajorVersion)) - { - exitCode = EXIT_CODE_READ_REGISTRY_FAILURE; - break; - } - LONG result = RegOpenKeyExW(HKEY_LOCAL_MACHINE, wszVersionKey, 0, KEY_READ, &hVersionKey); - if (ERROR_SUCCESS != result) - { - exitCode = ERROR_FILE_NOT_FOUND == result ? - EXIT_CODE_INCOMPATIBLE_MSH_VERSION : - EXIT_CODE_READ_REGISTRY_FAILURE; - this->output->DisplayMessage(false, g_MSH_VERSION_NOT_INSTALLED, wszMonadVersion); - break; - } - } while (false); - if (NULL != wszVersionKey) - { - delete[] wszVersionKey; - wszVersionKey = NULL; - } - if (NULL != hVersionKey) - { - RegCloseKey(hVersionKey); - hVersionKey = NULL; - } - return exitCode; - } - - unsigned int PwrshCommon::OpenEngineRegKeyWithVersion( - __deref_out_ecount(1) PHKEY phEngineKey, - __deref_out_opt PWSTR * pwszMshEngineRegKey, - LPCWSTR wszMonadVersion, - int monadMajorVersion) - { - // version is specified with -version or -mshconsole - LPWSTR wszSubkey = NULL; - DWORD dwLength = 0; - unsigned int exitCode = EXIT_CODE_SUCCESS; - do - { - if (NULL == phEngineKey || - NULL == pwszMshEngineRegKey || - this->StringIsNullOrEmpty(wszMonadVersion)) - { - exitCode = EXIT_CODE_READ_REGISTRY_FAILURE; - break; - } - - // For PowerShell 3 and 4, the registry is 3. - if ((monadMajorVersion == 4) || (monadMajorVersion == 5)) - { - monadMajorVersion = 3; - } - - WCHAR wszMonadMajorVersion[g_MAX_VERSION_FIELD_LENGTH + 1]; - _itow_s(monadMajorVersion, wszMonadMajorVersion, g_MAX_VERSION_FIELD_LENGTH + 1, 10); - exitCode = this->IsEngineRegKeyWithVersionExisting(wszMonadVersion, wszMonadMajorVersion); - if (EXIT_CODE_SUCCESS != exitCode) - { - break; - } - // g_MAX_VERSION_FIELD_LENGTH + 1 for the null terminating char - if (!this->FormatStringWithErrorReporting( - g_MSHENGINE_REG_KEY_PATH_TEMPLATE, - &wszSubkey, - &dwLength, - g_CREATE_MSHENGINE_REG_KEY_PATH_FAILED_WITH, - wszMonadMajorVersion)) - { - exitCode = EXIT_CODE_READ_REGISTRY_FAILURE; - break; - } - if (!this->RegOpenKeyWithErrorReport(wszSubkey, wszMonadVersion, phEngineKey)) - { - exitCode = EXIT_CODE_READ_REGISTRY_FAILURE; - break; - } - *pwszMshEngineRegKey = wszSubkey; - } while (false); - return exitCode; - } - - bool PwrshCommon::VerifyDOTNetVersionFormat( - LPCWSTR wszFullVersion, - __out_ecount(1) int * lpMajorVersion, - __out_ecount(1) int * lpMinorVersion) - { - bool bReturnResult = true; - do - { - if (this->StringIsNullOrEmpty(wszFullVersion) || - NULL == lpMajorVersion || - NULL == lpMinorVersion) - { - bReturnResult = false; - break; - } - *lpMajorVersion = *lpMinorVersion = -1; - const WCHAR * pwchDot = wcschr(wszFullVersion, L'.'); - if (NULL == pwchDot) - { - bReturnResult = false; - break; - } - bReturnResult = this->ParseInt( - wszFullVersion, - pwchDot, - lpMajorVersion); - if (!bReturnResult) - { - break; - } - int cDotInt = 0; // counting how many .int's are after major (valid format: major(.int)+ (.int)+ up to 3) - int versionFields[3]; - while (true) - { - if (2 < cDotInt) - { - bReturnResult = false; - break; - } - const WCHAR * pwchField = _wcsinc(pwchDot); - pwchDot = wcschr(pwchField, L'.'); - if (NULL == pwchDot) - { - const WCHAR * pwchNull = wcschr(pwchField, L'\0'); - if (NULL == pwchNull) - { - bReturnResult = false; - break; - } - bReturnResult = this->ParseInt( - pwchField, - pwchNull, - versionFields + cDotInt); - break; - } - bReturnResult = this->ParseInt( - pwchField, - pwchDot, - versionFields + cDotInt); - if (!bReturnResult) - { - break; - } - cDotInt++; - } - if (!bReturnResult) - { - break; - } - *lpMinorVersion = versionFields[0]; - } while (false); - return bReturnResult; - } - - // The assemblies that are trusted by CoreCLR. These are the CoreCLR implementation - // and facade assemblies plus Microsoft.Management.Infrastructure (MI .Net) assemblies. - // System.Management.Automation must not be listed here. I should exist on the APP_PATH. - // - // NOTE: The names must not include the .dll extension because it will be added programmatically. - static PCSTR trustedAssemblies[] = - { - "Markdig", - "Microsoft.ApplicationInsights", - "Microsoft.CodeAnalysis.CSharp", - "Microsoft.CodeAnalysis", - "Microsoft.CSharp", - "Microsoft.DiaSymReader.Native.amd64", - "Microsoft.Management.Infrastructure", - "Microsoft.Management.Infrastructure.CimCmdlets", - "Microsoft.Management.Infrastructure.Native", - "Microsoft.PowerShell.Commands.Diagnostics", - "Microsoft.PowerShell.Commands.Management", - "Microsoft.PowerShell.Commands.Utility", - "Microsoft.PowerShell.ConsoleHost", - "Microsoft.PowerShell.CoreCLR.Eventing", - "Microsoft.PowerShell.SDK", - "Microsoft.PowerShell.Security", - "Microsoft.VisualBasic", - "Microsoft.Win32.Primitives", - "Microsoft.Win32.Registry", - "Microsoft.Win32.Registry.AccessControl", - "Microsoft.Win32.SystemEvents", - "Microsoft.WSMan.Management", - "Microsoft.WSMan.Runtime", - "mscorlib", - "netstandard", - "Newtonsoft.Json", - "NJsonSchema", - "PowerShell.Core.Instrumentation", - "System", - "System.AppContext", - "System.Buffers", - "System.CodeDom", - "System.Collections", - "System.Collections.Concurrent", - "System.Collections.Immutable", - "System.Collections.NonGeneric", - "System.Collections.Specialized", - "System.ComponentModel.Annotations", - "System.ComponentModel.Composition", - "System.ComponentModel.DataAnnotations", - "System.ComponentModel", - "System.ComponentModel.EventBasedAsync", - "System.ComponentModel.Primitives", - "System.ComponentModel.TypeConverter", - "System.Configuration", - "System.Configuration.ConfigurationManager", - "System.Console", - "System.Core", - "System.Data", - "System.Data.Common", - "System.Data.DataSetExtensions", - "System.Data.Odbc", - "System.Data.SqlClient", - "System.Diagnostics.Contracts", - "System.Diagnostics.Debug", - "System.Diagnostics.DiagnosticSource", - "System.Diagnostics.EventLog", - "System.Diagnostics.FileVersionInfo", - "System.Diagnostics.PerformanceCounter", - "System.Diagnostics.Process", - "System.Diagnostics.StackTrace", - "System.Diagnostics.TextWriterTraceListener", - "System.Diagnostics.Tools", - "System.Diagnostics.TraceSource", - "System.Diagnostics.Tracing", - "System.DirectoryServices", - "System.DirectoryServices.AccountManagement", - "System.DirectoryServices.Protocols", - "System.Drawing", - "System.Drawing.Common", - "System.Drawing.Primitives", - "System.Dynamic.Runtime", - "System.Globalization.Calendars", - "System.Globalization", - "System.Globalization.Extensions", - "System.IO", - "System.IO.Compression", - "System.IO.Compression.Brotli", - "System.IO.Compression.FileSystem", - "System.IO.Compression.ZipFile", - "System.IO.FileSystem", - "System.IO.FileSystem.AccessControl", - "System.IO.FileSystem.DriveInfo", - "System.IO.FileSystem.Primitives", - "System.IO.FileSystem.Watcher", - "System.IO.IsolatedStorage", - "System.IO.MemoryMappedFiles", - "System.IO.Packaging", - "System.IO.Pipes", - "System.IO.Pipes.AccessControl", - "System.IO.Ports", - "System.IO.UnmanagedMemoryStream", - "System.Linq", - "System.Linq.Expressions", - "System.Linq.Parallel", - "System.Linq.Queryable", - "System.Management", - "System.Management.Automation", - "System.Memory", - "System.Net", - "System.Net.Http", - "System.Net.Http.WinHttpHandler", - "System.Net.HttpListener", - "System.Net.Mail", - "System.Net.NameResolution", - "System.Net.NetworkInformation", - "System.Net.Ping", - "System.Net.Primitives", - "System.Net.Requests", - "System.Net.Security", - "System.Net.ServicePoint", - "System.Net.Sockets", - "System.Net.WebClient", - "System.Net.WebHeaderCollection", - "System.Net.WebProxy", - "System.Net.WebSockets", - "System.Net.WebSockets.Client", - "System.Numerics", - "System.Numerics.Vectors", - "System.ObjectModel", - "System.Private.CoreLib", - "System.Private.DataContractSerialization", - "System.Private.ServiceModel", - "System.Private.Uri", - "System.Private.Xml", - "System.Private.Xml.Linq", - "System.Reflection", - "System.Reflection.DispatchProxy", - "System.Reflection.Emit", - "System.Reflection.Emit.ILGeneration", - "System.Reflection.Emit.Lightweight", - "System.Reflection.Extensions", - "System.Reflection.Metadata", - "System.Reflection.Primitives", - "System.Reflection.TypeExtensions", - "System.Resources.Reader", - "System.Resources.ResourceManager", - "System.Resources.Writer", - "System.Runtime", - "System.Runtime.Caching", - "System.Runtime.CompilerServices.Unsafe", - "System.Runtime.CompilerServices.VisualC", - "System.Runtime.Extensions", - "System.Runtime.Handles", - "System.Runtime.InteropServices", - "System.Runtime.InteropServices.RuntimeInformation", - "System.Runtime.InteropServices.WindowsRuntime", - "System.Runtime.Loader", - "System.Runtime.Numerics", - "System.Runtime.Serialization", - "System.Runtime.Serialization.Formatters", - "System.Runtime.Serialization.Json", - "System.Runtime.Serialization.Primitives", - "System.Runtime.Serialization.Xml", - "System.Security.AccessControl", - "System.Security.Claims", - "System.Security.Cryptography.Algorithms", - "System.Security.Cryptography.Cng", - "System.Security.Cryptography.Csp", - "System.Security.Cryptography.Encoding", - "System.Security.Cryptography.OpenSsl", - "System.Security.Cryptography.Pkcs", - "System.Security.Cryptography.Primitives", - "System.Security.Cryptography.ProtectedData", - "System.Security.Cryptography.X509Certificates", - "System.Security.Cryptography.Xml", - "System.Security", - "System.Security.Permissions", - "System.Security.Principal", - "System.Security.Principal.Windows", - "System.Security.SecureString", - "System.ServiceModel", - "System.ServiceModel.Duplex", - "System.ServiceModel.Http", - "System.ServiceModel.NetTcp", - "System.ServiceModel.Primitives", - "System.ServiceModel.Security", - "System.ServiceModel.Syndication", - "System.ServiceModel.Web", - "System.ServiceProcess", - "System.ServiceProcess.ServiceController", - "System.Text.Encoding", - "System.Text.Encoding.CodePages", - "System.Text.Encoding.Extensions", - "System.Text.Encodings.Web", - "System.Text.RegularExpressions", - "System.Threading", - "System.Threading.AccessControl", - "System.Threading.Overlapped", - "System.Threading.Tasks.Dataflow", - "System.Threading.Tasks", - "System.Threading.Tasks.Extensions", - "System.Threading.Tasks.Parallel", - "System.Threading.Thread", - "System.Threading.ThreadPool", - "System.Threading.Timer", - "System.Transactions", - "System.Transactions.Local", - "System.ValueTuple", - "System.Web", - "System.Web.HttpUtility", - "System.Windows", - "System.Xml", - "System.Xml.Linq", - "System.Xml.ReaderWriter", - "System.Xml.Serialization", - "System.Xml.XDocument", - "System.Xml.XmlDocument", - "System.Xml.XmlSerializer", - "System.Xml.XPath", - "System.Xml.XPath.XDocument" - }; - - // Define the function pointer for the CLR entry point - typedef HRESULT(STDAPICALLTYPE *GetCLRRuntimeHostFp)(REFIID riid, IUnknown** pUnk); - - // The name of the CoreCLR native runtime DLL. - static PCSTR coreClrDll = "CoreCLR.dll"; - - // The location where CoreCLR is expected to be installed for inbox PowerShell. If CoreCLR.dll isn't - // found in the same directory as the host, it will be looked for here. - static PCSTR coreCLRInstallDirectory = "%windir%\\system32\\DotNetCore\\v1.0\\"; - - // The location where CoreCLR PowerShell Ext binaries are expected to be installed for inbox PowerShell. - static PCSTR coreCLRPowerShellExtInstallDirectory = "%windir%\\system32\\CoreClrPowerShellExt\\v1.0\\"; - - // The default PowerShell install directory for inbox PowerShell. - // This location may be overridden by placing a config file in the same directory as the PowerShell host. - static PCSTR powerShellInstallPath = "%windir%\\System32\\WindowsPowerShell\\v1.0\\"; - - unsigned int PwrshCommon::IdentifyHostDirectory( - HostEnvironment& hostEnvironment) - { - // Discover the path to the plugin or the executable (pwrshplugin.dll or powershell.exe). - // For PowerShell Core, the plugin no longer resides in %windir%\\system32 (it is in a sub-directory). - // If pwrshplugin.dll is not loaded, it means that this is running via powershell.exe. - wchar_t hostPath[MAX_PATH]; - DWORD thisModuleLength; - - if (GetModuleHandleW(L"pwrshplugin.dll")) - { - thisModuleLength = GetModuleFileNameW(GetModuleHandleW(L"pwrshplugin.dll"), hostPath, MAX_PATH); - } - else - { - thisModuleLength = GetModuleFileNameW(GetModuleHandleW(NULL), hostPath, MAX_PATH); - } - if (0 == thisModuleLength) // Greater than zero means it is the length of the fully qualified path (without the NULL character) - { - // TODO: Use GetLastError() to find the specific error # - return EXIT_CODE_INIT_FAILURE; - } - - // Search for the last backslash in the host path. - int lastBackslashIndex; - for (lastBackslashIndex = thisModuleLength - 1; lastBackslashIndex >= 0; lastBackslashIndex--) - { - if (hostPath[lastBackslashIndex] == L'\\') - { - break; - } - } - - // The remaining part of the path after the last '\' is the binary name. - hostEnvironment.SetHostBinaryNameW(hostPath + lastBackslashIndex + 1); - - // Copy the directory path portion of the path - hostPath[lastBackslashIndex + 1] = '\0'; - hostEnvironment.SetHostPathW(hostPath); - - // Read the config file to determine the appropriate host path and CoreCLR path to use. - unsigned int result = reader->Read(hostPath); - if (EXIT_CODE_SUCCESS == result) - { - // The config file was successfully parsed. Use those directories. - hostEnvironment.SetHostDirectoryPathW(reader->GetPathToPowerShell().c_str()); - hostEnvironment.SetCoreCLRDirectoryPathW(reader->GetPathToCoreClr().c_str()); - } - else - { - // There was an issue accessing or parsing the config file OR - // we are working for the EXE. - // - // TODO: This should not be the fallback for inbox PowerShell.exe. - // It should use coreCLRInstallDirectory and coreCLRPowerShellExtInstallDirectory. - // - // Use the directory detected via GetModuleFileName + GetModuleHandle - hostEnvironment.SetHostDirectoryPathW(hostPath); - // At the moment, CoreCLR is in the same directory as PowerShell Core. - // This path must be modified if we decide to use a different directory. - hostEnvironment.SetCoreCLRDirectoryPathW(hostPath); - } - return EXIT_CODE_SUCCESS; - } - - bool PwrshCommon::DoesAssemblyExist( - std::string& fileToTest) - { - //FILE *file = sysCalls->fopen(fileToTest.c_str(), "r"); // TODO: Use fopen_s? - FILE *file = NULL; - errno_t status = sysCalls->fopen_s(&file, fileToTest.c_str(), "r"); - - if (file != NULL) { - sysCalls->fclose(file); - return (status == 0); - } - return false; - } - - // This assumes that directoryPath already includes a trailing "\\" - void PwrshCommon::ProbeAssembly( - _In_z_ PCSTR directoryPath, - _In_z_ PCSTR assemblyName, - std::string& result) - { - PCSTR niExtension = ".ni.dll"; - PCSTR ilExtension = ".dll"; - - // Test NI extension first because it is preferable to IL - std::string fileToTest(directoryPath); - fileToTest += assemblyName; - fileToTest += niExtension; - if (DoesAssemblyExist(fileToTest)) { - result = fileToTest; - return; - } - - // Check IL if NI is not present - fileToTest = directoryPath; - fileToTest += assemblyName; - fileToTest += ilExtension; - if (DoesAssemblyExist(fileToTest)) { - result = fileToTest; - } - } - - // Returns the semicolon-separated list of paths to runtime dlls that are considered trusted. - // Do not put powershell assemblies in the TPA list as it will cause 'Security Transparent V.S. Security Critical' error. - void PwrshCommon::GetTrustedAssemblyList( - PCSTR coreCLRDirectoryPath, - std::stringstream& assemblyList, - bool& listEmpty) - { - for (const char* &assembly : trustedAssemblies) - { - std::string assemblyPath; - ProbeAssembly(coreCLRDirectoryPath, assembly, assemblyPath); - - if (assemblyPath.length() > 0) - { - if (listEmpty) - listEmpty = false; - else - assemblyList << ";"; - assemblyList << assemblyPath; - } - } - } - -#pragma prefast(pop) - - class PwrshCommonOutputDefault : public IPwrshCommonOutput - { - public: - virtual VOID DisplayMessage( - bool bUseStdOut, - DWORD dwMessageId, - ...) - { - return; - } - - virtual void DisplayErrorWithSystemError( - LONG lSystemErrorCode, - int messageId, - LPCWSTR insertionParam) - { - return; - } - }; - - // - // - // The following definitions for publicly accessible functions exposed in - // NativeMsh.h. - // - // - - PwrshCommon::PwrshCommon() - : output(new PwrshCommonOutputDefault()), reader(new ConfigFileReader()), sysCalls(new WinSystemCallFacade()) - { - } - - PwrshCommon::PwrshCommon( - IPwrshCommonOutput* outObj, - ConfigFileReader* rdr, - SystemCallFacade* systemCalls) - : output(outObj), reader(rdr), sysCalls(systemCalls) - { - if (NULL == output) - { - output = new PwrshCommonOutputDefault(); - } - - if (NULL == reader) - { - reader = new ConfigFileReader(); - } - - if (NULL == sysCalls) - { - sysCalls = new WinSystemCallFacade(); - } - } - - PwrshCommon::~PwrshCommon() - { - if (output) - { - delete output; - output = NULL; - } - - if (reader) - { - delete reader; - reader = NULL; - } - - if (sysCalls) - { - delete sysCalls; - sysCalls = NULL; - } - } - - bool PwrshCommon::StringIsNullOrEmpty( - LPCWSTR wsz) - { - return NULL == wsz || L'\0' == wsz[0]; - } - - DWORD PwrshCommon::GetSystemErrorMessage( - IN LONG lErrorCode, - __deref_out_opt PWSTR * pwszErrorMessage) - { - DWORD dwLength = 0; - do - { - if (NULL == pwszErrorMessage) - { - break; - } - *pwszErrorMessage = NULL; - LPWSTR wszSystemErrorMessage = NULL; - dwLength = FormatMessageW( - FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, - NULL, - lErrorCode, - 0, - (LPWSTR)&wszSystemErrorMessage, - 0, - NULL); - if (dwLength > 0) - { - *pwszErrorMessage = new wchar_t[dwLength + 1]; - if (NULL != *pwszErrorMessage) - { - //string function - if (FAILED(StringCchCopy(*pwszErrorMessage, dwLength + 1, wszSystemErrorMessage))) - { - dwLength = 0; - delete[](*pwszErrorMessage); - *pwszErrorMessage = NULL; - } - } - LocalFree(wszSystemErrorMessage); - } - } while (false); - return dwLength; - } - - bool PwrshCommon::VerifyMonadVersionFormat( - LPCWSTR wszMonadVersion, - int * lpMajorVersion, - int * lpMinorVersion, - bool bAllowMinorVersion, - bool bReportError) - { - bool returnResult = true; - - do - { - if (StringIsNullOrEmpty(wszMonadVersion) || - NULL == lpMajorVersion || - NULL == lpMinorVersion) - { - returnResult = false; - break; - } - - WCHAR* wszRemainingVersionStringAfterMajor = NULL; - returnResult = this->ExtractFirstVersionComponent(wszMonadVersion, - lpMajorVersion, &wszRemainingVersionStringAfterMajor); - - if (false == returnResult) - { - returnResult = false; - break; - } - - if (NULL != wszRemainingVersionStringAfterMajor) - { - if (!bAllowMinorVersion) - { - returnResult = false; - break; - } - - WCHAR* wszRemainingVersionStringAfterMinor = NULL; - returnResult = this->ExtractFirstVersionComponent(wszRemainingVersionStringAfterMajor, - lpMinorVersion, &wszRemainingVersionStringAfterMinor); - - if (!returnResult) - { - break; - } - } - else - { - *lpMinorVersion = -1; - } - } while (false); - if (!returnResult && bReportError) - { - this->output->DisplayMessage( - false, - g_INVALID_MONAD_VERSION, - wszMonadVersion); - } - return returnResult; - } - -#pragma prefast(push) -#pragma prefast (disable: 6101) -#pragma prefast (disable: 6054) -#pragma prefast (disable: 6001) - - unsigned int PwrshCommon::OpenEngineRegKey( - __deref_out_ecount(1) PHKEY phEngineKey, - __deref_out_opt PWSTR * pwszMshEngineRegKey, - __deref_out_opt PWSTR * pwszMonadVersion, - __inout_ecount(1) int* lpMonadMajorVersion) - { - unsigned int exitCode = EXIT_CODE_SUCCESS; - do - { - if (NULL == phEngineKey || - NULL == pwszMshEngineRegKey || - NULL == pwszMonadVersion || - NULL == lpMonadMajorVersion) - { - exitCode = EXIT_CODE_READ_REGISTRY_FAILURE; - break; - } - if (NULL == *pwszMonadVersion) - { - // neither -version nor -monadconsole is used, - // need to find the latest version from the registry - - if (!this->OpenLatestMSHEngineRegistry( - phEngineKey, - pwszMshEngineRegKey, - pwszMonadVersion, - lpMonadMajorVersion)) - { - exitCode = EXIT_CODE_READ_REGISTRY_FAILURE; - } - } - else - { - exitCode = this->OpenEngineRegKeyWithVersion(phEngineKey, pwszMshEngineRegKey, *pwszMonadVersion, *lpMonadMajorVersion); - } - } while (false); - return exitCode; - } - - // API used to read a particular registry key value from the PowerShellEngine - // regkey path. For example to read "ApplicationBase" or "ConsoleHostAssemblyName" - // - // Note: During successful calls the following values must be freed by the caller: - // pwszMonadVersion - // pwszRuntimeVersion - // pwszRegKeyValue - // - // The caller must take care to check to see if they must be freed during error scenarios - // because the function may fail after allocating one or more strings. - // - _Success_(return == 0) - unsigned int PwrshCommon::GetRegistryInfo( - __out PWSTR * pwszMonadVersion, - __inout_ecount(1) int * lpMonadMajorVersion, - int monadMinorVersion, - __out PWSTR * pwszRuntimeVersion, - LPCWSTR lpszRegKeyNameToRead, - __out PWSTR * pwszRegKeyValue) - { - HKEY hEngineKey = NULL; - bool bEngineKeyOpened = true; - unsigned int exitCode = EXIT_CODE_SUCCESS; - wchar_t * wszMshEngineRegKeyPath = NULL; - LPWSTR wszFullMonadVersion = NULL; - - if (NULL != pwszRegKeyValue) - { - *pwszRegKeyValue = NULL; - } - - if (NULL != pwszRuntimeVersion) - { - *pwszRuntimeVersion = NULL; - } - - if (NULL != pwszMonadVersion) - { - *pwszMonadVersion = NULL; - } - - do - { - if (NULL == pwszMonadVersion || - NULL == lpMonadMajorVersion || - NULL == pwszRuntimeVersion || - NULL == pwszRegKeyValue) - { - exitCode = EXIT_CODE_READ_REGISTRY_FAILURE; - break; - } - exitCode = OpenEngineRegKey(&hEngineKey, &wszMshEngineRegKeyPath, pwszMonadVersion, lpMonadMajorVersion); - if (EXIT_CODE_SUCCESS != exitCode) - { - bEngineKeyOpened = false; - break; - } - - LPCWSTR wszMshVersionRegValueName = L"PowerShellVersion"; - - if (!this->RegQueryREG_SZValue(hEngineKey, wszMshVersionRegValueName, wszMshEngineRegKeyPath, &wszFullMonadVersion)) - { - exitCode = EXIT_CODE_READ_REGISTRY_FAILURE; - break; - } - - //verify pwszFullMonadVersion format - int installedMajorVersion = -1, installedMinorVersion = -1; - if (!this->VerifyDOTNetVersionFormat(wszFullMonadVersion, &installedMajorVersion, &installedMinorVersion)) - { - this->output->DisplayMessage(false, g_INVALID_REG_MSHVERSION_VALUE, wszMshEngineRegKeyPath, wszMshVersionRegValueName); - exitCode = EXIT_CODE_READ_REGISTRY_FAILURE; - break; - } - - *lpMonadMajorVersion = installedMajorVersion; - - if (-1 != monadMinorVersion) - { - if (installedMinorVersion < monadMinorVersion) - { - this->output->DisplayMessage(false, g_INCOMPATIBLE_MINOR_VERSION, *pwszMonadVersion); - exitCode = EXIT_CODE_INCOMPATIBLE_MSH_VERSION; - break; - } - } - - LPCWSTR wszRuntimeVersionRegValueName = L"RuntimeVersion"; - if (!this->RegQueryREG_SZValue(hEngineKey, wszRuntimeVersionRegValueName, - wszMshEngineRegKeyPath, pwszRuntimeVersion)) - { - exitCode = EXIT_CODE_READ_REGISTRY_FAILURE; - break; - } - - if (NULL != lpszRegKeyNameToRead) - { - LPCWSTR wszRequestedRegValueName = lpszRegKeyNameToRead; - if (!this->RegQueryREG_SZValue(hEngineKey, wszRequestedRegValueName, - wszMshEngineRegKeyPath, pwszRegKeyValue)) - { - exitCode = EXIT_CODE_READ_REGISTRY_FAILURE; - break; - } - } - } while (false); - if (NULL != wszMshEngineRegKeyPath) - { - delete[] wszMshEngineRegKeyPath; - wszMshEngineRegKeyPath = NULL; - } - - if (NULL != wszFullMonadVersion) - { - delete[] wszFullMonadVersion; - wszFullMonadVersion = NULL; - } - - if (bEngineKeyOpened && (NULL != hEngineKey)) - { - LONG regCloseResult = RegCloseKey(hEngineKey); - if (ERROR_SUCCESS != regCloseResult) - { - LPWSTR wszSystemErrorMessage = NULL; - DWORD dwLength = - GetSystemErrorMessage( - regCloseResult, - &wszSystemErrorMessage); - - if (dwLength > 0) - { - this->output->DisplayMessage(false, g_CLOSE_REG_KEY_FAILED_WITH, wszMshEngineRegKeyPath, wszSystemErrorMessage); - if (NULL != wszSystemErrorMessage) - { - delete[] wszSystemErrorMessage; - wszSystemErrorMessage = NULL; - } - } - } - hEngineKey = NULL; - // not return false when close registry failed - } - return exitCode; - } - - _Success_(return == 0) - unsigned int PwrshCommon::GetRegistryInfo( - __out PWSTR * pwszMonadVersion, - __inout_ecount(1) int * lpMonadMajorVersion, - int monadMinorVersion, - __out PWSTR * pwszRuntimeVersion, - __out PWSTR * pwszConsoleHostAssemblyName) - { - return GetRegistryInfo(pwszMonadVersion, - lpMonadMajorVersion, - monadMinorVersion, - pwszRuntimeVersion, L"ConsoleHostAssemblyName", pwszConsoleHostAssemblyName); - } - - unsigned int PwrshCommon::LaunchCoreCLR( - ClrHostWrapper* hostWrapper, - HostEnvironment& hostEnvironment, - PCSTR friendlyName) - { - unsigned int exitCode = this->IdentifyHostDirectory(hostEnvironment); - if (EXIT_CODE_SUCCESS != exitCode) - { - this->output->DisplayMessage(false, g_STARTING_CLR_FAILED, GetLastError()); - return exitCode; - } - - exitCode = hostWrapper->SetupWrapper(hostEnvironment.GetCoreCLRDirectoryPath()); - if (EXIT_CODE_SUCCESS != exitCode) - { - this->output->DisplayMessage(false, g_STARTING_CLR_FAILED, GetLastError()); - return exitCode; - } - - const int nMaxProps = 8; - LPCSTR props[nMaxProps]; - LPCSTR vals[nMaxProps]; - int nProps = 0; - - // The TPA list is the required list of CoreCLR assemblies that comprise - // the trusted platform upon which PowerShell will run. - std::stringstream assemblyList; - bool listEmpty = true; - this->GetTrustedAssemblyList(hostEnvironment.GetCoreCLRDirectoryPath(), assemblyList, listEmpty); - - if (listEmpty) - { - // Fall back to attempt to load the CLR from the alternate inbox location - char coreCLRPowerShellExtInstallPath[MAX_PATH]; - ::ExpandEnvironmentStringsA(coreCLRPowerShellExtInstallDirectory, coreCLRPowerShellExtInstallPath, MAX_PATH); - this->GetTrustedAssemblyList(coreCLRPowerShellExtInstallPath, assemblyList, listEmpty); - } - if (listEmpty) - { - // No CoreCLR assemblies were found in either location. There is no - // point in continuing. - this->output->DisplayMessage(false, g_STARTING_CLR_FAILED, GetLastError()); - return EXIT_CODE_INIT_FAILURE; - } - - props[nProps] = "TRUSTED_PLATFORM_ASSEMBLIES"; - std::string tempStr = assemblyList.str(); - vals[nProps] = tempStr.c_str(); - nProps++; - - props[nProps] = "APP_PATHS"; - vals[nProps] = ""; // Used to be hostEnvironment.GetHostDirectoryPath() - nProps++; - - props[nProps] = "APP_NI_PATHS"; - vals[nProps] = ""; // Used to be hostEnvironment.GetHostDirectoryPath() - nProps++; - - int hr = hostWrapper->InitializeClr( - hostEnvironment.GetHostDirectoryPath(), - friendlyName, - nProps, - props, - vals); - - if (FAILED(hr)) - { - this->output->DisplayMessage(false, g_STARTING_CLR_FAILED, GetLastError()); - return EXIT_CODE_INIT_FAILURE; - } - - return EXIT_CODE_SUCCESS; - } - -#if !CORECLR - // NOTE: - // This must be ifdef'd out of the CoreCLR build because it uses .NET 1.0 - // types that have been deprecated and removed from mscoree.h. - // - // This code may be removed from #if protection once ICorRuntimeHost is - // upgraded to ICLRRuntimeHost. - // - unsigned int PwrshCommon::LaunchCLR( - LPCWSTR wszMonadVersion, - LPCWSTR wszRuntimeVersion, - __in_ecount(1) ICorRuntimeHost** pCLR) - { - unsigned int exitCode = EXIT_CODE_SUCCESS; - HRESULT hr = S_OK; - do - { - // don't check StringIsNullOrEmpty(wszConsoleHostAssemblyName) here - // because it will check below with better error reporting - if (StringIsNullOrEmpty(wszMonadVersion) || - StringIsNullOrEmpty(wszRuntimeVersion)) - { - exitCode = EXIT_CODE_INIT_FAILURE; - break; - } - - if (NULL == pCLR) - { - exitCode = EXIT_CODE_INIT_FAILURE; - break; - } - - SetErrorMode(SEM_FAILCRITICALERRORS); - - LPCWSTR wszCLRBuildFlavorWorkStation = L"wks"; - - hr = CorBindToRuntimeEx( - wszRuntimeVersion, - wszCLRBuildFlavorWorkStation, // use the workstation build of CLR - STARTUP_LOADER_OPTIMIZATION_MULTI_DOMAIN, // add STARTUP_LOADER_SAFEMODE if skipping load CLR policy - CLSID_CorRuntimeHost, - IID_ICorRuntimeHost, - (PVOID*)pCLR); - - if ((CLR_E_SHIM_RUNTIMELOAD == hr) || (NULL == (*pCLR))) - { - this->output->DisplayMessage(false, g_CLR_VERSION_NOT_INSTALLED, wszRuntimeVersion, wszMonadVersion); - exitCode = EXIT_CODE_INIT_FAILURE; - break; - } - - hr = (*pCLR)->Start(); - - if (FAILED(hr)) - { - this->output->DisplayMessage(false, g_STARTING_CLR_FAILED, hr); - exitCode = EXIT_CODE_INIT_FAILURE; - break; - } - } while (false); - - return exitCode; - } -#endif // !CORECLR - -#pragma prefast(pop) - -} // namespace NativeMsh diff --git a/src/powershell-native/nativemsh/pwrshexe/CMakeLists.txt b/src/powershell-native/nativemsh/pwrshexe/CMakeLists.txt deleted file mode 100644 index 25ef183c75e..00000000000 --- a/src/powershell-native/nativemsh/pwrshexe/CMakeLists.txt +++ /dev/null @@ -1,62 +0,0 @@ -# -# Builds PowerShell.exe, the native host for PowerShell. -# - -if (BUILD_ONECORE) - # Settings to use when creating PowerShell.exe for Windows on OneCore-based SKUs - set(PWRSHEXE_WINDOWS_SOURCES - CssMainEntry.cpp - ) - set(PWRSHEXE_WINDOWS_LIBS - onecore.lib - ${STATIC_MT_CRT_LIB} - ${STATIC_MT_VCRT_LIB} - ) - set(powershell_definitions - _CONSOLE - CORECLR - ) - - # - # Configure lib directories so that CI picks up onecore.lib - # - if (BUILD_ARCH_AMD64) - SET (WindowsSdkDir $ENV{WindowsSdkDir}) - SET (WindowsSDKVersion $ENV{WindowsSDKVersion}) - SET (WindowsSDKLibBase "${WindowsSdkDir}/Lib/${WindowsSDKVersion}") - SET (OneCoreLibBase "$ENV{VCInstallDir}lib/onecore/amd64") - - SET (LibraryPath) - list (APPEND LibraryPath "${OneCoreLibBase}") - list (APPEND LibraryPath "${WindowsSDKLibBase}ucrt/${WindowsSDKPlatform}") - list (APPEND LibraryPath "${WindowsSDKLibBase}um/${WindowsSDKPlatform}" ) - link_directories(${LibraryPath}) - endif () - -else () - # Settings to use when creating PowerShell.exe for Windows on full SKUs or downlevel platforms - set(PWRSHEXE_WINDOWS_SOURCES - MainEntry.cpp - ) - # Most libs are automatically added by VS - set(PWRSHEXE_WINDOWS_LIBS - # CoreCLR libs - ${STATIC_MT_CRT_LIB} - ${STATIC_MT_VCRT_LIB} - MUILoad.lib - msxml6.lib - mscoree.lib - legacy_stdio_definitions.lib # Resolves: LNK2019: unresolved external symbol _vsnwprintf - ) - set(powershell_definitions - _CONSOLE - ) -endif (BUILD_ONECORE) - -add_executable(powershell - ${PWRSHEXE_WINDOWS_SOURCES}) - -set_target_properties(powershell PROPERTIES COMPILE_DEFINITIONS "${powershell_definitions}") - -target_link_libraries(powershell ${PWRSHEXE_WINDOWS_LIBS}) -target_link_libraries(powershell pwrshcommon) diff --git a/src/powershell-native/nativemsh/pwrshexe/CssMainEntry.cpp b/src/powershell-native/nativemsh/pwrshexe/CssMainEntry.cpp deleted file mode 100644 index 6cba4b49345..00000000000 --- a/src/powershell-native/nativemsh/pwrshexe/CssMainEntry.cpp +++ /dev/null @@ -1,239 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// ---------------------------------------------------------------------- -// -// File: CoreCLRHost.cpp -// -// Contents: Unmanaged startup point for powershell.exe console app. -// -// ---------------------------------------------------------------------- - -#include -#include -#include -#if !CORECLR - #include "mscoree.h" -#endif -#include "NativeMsh.h" -#include "ClrHostWrapper.h" -#include "OutputWriter.h" -#include "ConfigFileReader.h" -#include "WinSystemCallFacade.h" - -namespace NativeMsh -{ - // Define the function pointer for the powershell entry point. - typedef int (STDMETHODCALLTYPE *MonadRunHelperFp)(LPCWSTR consoleFilePath, LPCWSTR * args, int argc); // int UnmanagedPSEntry.Start(string consoleFilePath, string[] args, int argc) - - bool TryRun(const int argc, const wchar_t* argv[], HostEnvironment &hostEnvironment, int &exitCode, bool verbose) - { - // Assume failure - exitCode = -1; - - // All these objects will be destroyed when commonFuncs goes out of scope. - PwrshExeOutput* output = new PwrshExeOutput(); - PwrshCommon commonFuncs(output, new ConfigFileReader(), new WinSystemCallFacade()); - CoreClrHostingApiWrapper hostWrapper; - - exitCode = commonFuncs.LaunchCoreCLR(&hostWrapper, hostEnvironment, "powershell"); - if (EXIT_CODE_SUCCESS != exitCode) - { - if (verbose) - ::wprintf(L"Unable to launch CoreCLR\n"); - return false; - } - - if (!hostWrapper.IsInitialized()) // TODO: redundant? - { - if (verbose) - ::wprintf(L"Unable to initialize CoreCLR\n"); - return false; - } - - //------------------------------------------------------------- - // Start the assembly - MonadRunHelperFp pfnDelegate = NULL; - HRESULT hr = hostWrapper.CreateDelegate( - "Microsoft.PowerShell.ConsoleHost, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", - "Microsoft.PowerShell.UnmanagedPSEntry", - "Start", - (void**)&pfnDelegate); - - if (FAILED(hr)) - { - output->DisplayMessage(false, g_CREATING_MSH_ENTRANCE_FAILED, hr); - } - else - { - exitCode = pfnDelegate(NULL, &argv[0], argc); - } - - // Unload the AppDomain - if (verbose) - ::wprintf(L"Unloading the AppDomain\n"); - - int utilExitCode = hostWrapper.CleanUpHostWrapper(); - if (EXIT_CODE_SUCCESS != utilExitCode) - { - if (verbose) - { - if (g_UNLOAD_APPDOMAIN_FAILED == utilExitCode) - { - // TODO: If we want localization, these must be added to nativemsh.mc - ::wprintf(L"Failed to unload the AppDomain. ERRORCODE: %u\n", utilExitCode); - } - else if (g_STOP_CLR_HOST_FAILED == utilExitCode) - { - ::wprintf(L"Failed to stop the host. ERRORCODE: %u\n", utilExitCode); - } - else if (g_RELEASE_CLR_HOST_FAILED == utilExitCode) - { - ::wprintf(L"Failed to release the host.ERRORCODE: %u\n", utilExitCode); - } - } - return false; - } - - return true; - } - - void showHelp() { - static PCWSTR coreCLRInstallDirectory = L"%windir%\\system32\\DotNetCore\\v1.0\\"; - ::wprintf( - L"USAGE: powershell [-Verbose] [-Debug] [-File ] [-Command] \r\n" - L"\r\n" - L" CoreCLR is searched for in the directory that powershell.exe is in,\r\n" - L" then in %s.\r\n", - coreCLRInstallDirectory - ); - } - -} // namespace NativeMsh - -int __cdecl wmain(const int argc, const wchar_t* argv[]) -{ - // Parse the options from the command line - const wchar_t *verboseParameter = L"-Verbose"; - const wchar_t *debugParameter = L"-Debug"; - - const wchar_t *versionParameter = L"-Version"; - const wchar_t *psConsoleFileParameter = L"-PSConsoleFile"; - const wchar_t *runtimeVersionParameter = L"-RuntimeVersion"; - - bool verbose = false; - bool debug = false; - bool helpRequested = false; - - bool versionSpecified = false; - bool psConsoleFileSpecified = false; - bool runtimeVersionSpecified = false; - - - int newArgc = argc - 1; - const wchar_t **newArgv = argv + 1; - - auto stringsMatch = [](const wchar_t * const userInput, const wchar_t * const parameter) -> bool { - size_t userInputLength = ::wcslen(userInput); - size_t parameterLength = ::wcslen(parameter); - - // If the user input is longer than the parameter, they cannot be matched. - if (userInputLength > parameterLength) { - return false; - } - - // Return true if the user input is a prefix of the parameter - return ::_wcsnicmp(userInput, parameter, userInputLength) == 0; - }; - - auto stringsEqual = [](const wchar_t * const a, const wchar_t * const b) -> bool { - return ::_wcsicmp(a, b) == 0; - }; - - // These parameters are considered 'native only' - they should NOT be passed to managed layer - auto skipParameter = [&](const wchar_t * arg) -> bool { - if (stringsMatch(arg, verboseParameter)) { - verbose = true; - } - else if (stringsEqual(arg, L"/?") || stringsEqual(arg, L"-?")) { - helpRequested = true; - } - else if (stringsMatch(arg, debugParameter)) - { - debug = true; - } - else if (stringsEqual(arg, versionParameter)) - { - versionSpecified = true; - } - else if (stringsMatch(arg, psConsoleFileParameter)) - { - psConsoleFileSpecified = true; - } - else if (stringsMatch(arg, runtimeVersionParameter)) { - runtimeVersionSpecified = true; - } - else { - return false; - } - - return true; - }; - - // Find the last 'native' parameter, and chomp everything up until it. - while (newArgc > 0 && skipParameter(newArgv[0])) - { - newArgc--; - newArgv++; - - if (versionSpecified) { - // skip the next arg if there is one - versionSpecified = false; - if (newArgc > 0) { - newArgc--; - newArgv++; - } - } - - if (psConsoleFileSpecified) { - // skip the next arg if there is one - psConsoleFileSpecified = false; - if (newArgc > 0) { - newArgc--; - newArgv++; - } - } - - if (runtimeVersionSpecified) { - // skip the next arg if there is one - runtimeVersionSpecified = false; - if (newArgc > 0) { - newArgc--; - newArgv++; - } - } - } - - if (debug) - { - ::wprintf(L" Attach the debugger to powershell.exe and press any key to continue\n"); - (void) ::getchar(); - } - - if (helpRequested) - { - NativeMsh::showHelp(); - return -1; - } - else - { - int exitCode; - NativeMsh::HostEnvironment hostEnvironment; - - auto success = TryRun(newArgc, newArgv, hostEnvironment, exitCode, verbose); - - if (verbose) - ::wprintf(L"Execution %s\n", (success ? L"succeeded" : L"failed")); - return exitCode; - } -} diff --git a/src/powershell-native/nativemsh/pwrshexe/MainEntry.cpp b/src/powershell-native/nativemsh/pwrshexe/MainEntry.cpp deleted file mode 100644 index b49baef5138..00000000000 --- a/src/powershell-native/nativemsh/pwrshexe/MainEntry.cpp +++ /dev/null @@ -1,1781 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// ---------------------------------------------------------------------- -// -// File: MainEntry.cpp -// -// Contents: Unmanaged startup point for powershell.exe console app. -// -// ---------------------------------------------------------------------- - -#ifdef _PREFAST_ -#pragma prefast (push) -#pragma prefast (disable: 6054) -#endif /* _PREFAST_ */ - -#include "Nativemsh.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "OutputWriter.h" -#include "ConfigFileReader.h" -#include "WinSystemCallFacade.h" - -// include the tlb for mscorlib for access to the default AppDomain through COM Interop -#import raw_interfaces_only high_property_prefixes("_get","_put","_putref")\ - rename("ReportEvent", "CLRReportEvent") - -const UINT PS_TASK_NUM = 4; -#define CheckAndReturn(x) if (FAILED(x)){return (x);} - -using namespace mscorlib; -using namespace NativeMsh; - -LPCWSTR g_ISE_BINARY_PATH= L"%systemroot%\\system32\\windowspowershell\\v1.0\\powershell_ise.exe"; -LPCWSTR g_ConsoleHostShortcutTarget_KEY_PATH = L"SOFTWARE\\Microsoft\\PowerShell\\3"; -wchar_t g_PROFILE[] = L"profile.ps1"; -wchar_t g_PROFILE_WITH_SHELL_ID[] = L"microsoft.powerShell_profile.ps1"; -wchar_t g_PRODUCT_NAME[] = L"\\windowspowerShell\\"; -wchar_t g_PSHOME_VERSION[] = L"v1.0\\"; - -WCHAR g_IconApp[MAX_PATH+1]; - -// All these objects will be destroyed when pwrshCommon goes out of scope. -PwrshExeOutput* pwrshExeOutput = new PwrshExeOutput(); -PwrshCommon pwrshCommon(pwrshExeOutput, new ConfigFileReader(), new WinSystemCallFacade()); - -bool ConvertArgvToSafeArray( - IN int argc, - __in_ecount(argc) LPWSTR * argv, - IN int skipIndex, - __deref_out_opt SAFEARRAY ** ppSafeArray) -{ - // Collect the command line arguments to the managed exe - SAFEARRAY *psa = NULL; - SAFEARRAYBOUND rgsabound[1]; - bool returnResult = true; - do - { - if (NULL == argv || NULL == ppSafeArray) - { - returnResult = false; - break; - } - - rgsabound[0].lLbound = 0; - - // rgsabound[0].cElements holds the number of elements that need to be passed to managed exe - rgsabound[0].cElements = argc - 1 - skipIndex; - psa = SafeArrayCreate(VT_BSTR, 1, rgsabound); - - if (psa == NULL) - { - returnResult = false; - break; - } - - long psaIndex[1]; - psaIndex[0] = 0; - - if (0 != rgsabound[0].cElements) - { - // Skip elements from 1 to argc-rgsabound[0].cElements-1 - for (int i = skipIndex+1; i < argc; i++) - { - BSTR bArg = SysAllocString(argv[i]); - if (NULL == bArg) - { - returnResult = false; - break; - } - HRESULT hrSafeArrayPutElement = SafeArrayPutElement(psa, psaIndex, bArg); - // Free bArg - SysFreeString(bArg); - psaIndex[0]++; - - if (FAILED(hrSafeArrayPutElement)) - { - returnResult = false; - break; - } - } - } - } - while (false); - *ppSafeArray = psa; - return returnResult; -} - -bool FileExists(__in LPWSTR pszFileName) -{ - return (GetFileAttributesW(pszFileName) != INVALID_FILE_ATTRIBUTES); -} - -unsigned int LaunchManagedMonad( - LPCWSTR wszMonadVersion, - int monadMajorVersion, - LPCWSTR wszConsoleFile, - LPCWSTR wszRuntimeVersion, - LPCWSTR wszConsoleHostAssemblyName, - __in_ecount_opt(1) SAFEARRAY * pArgvSA, - int skipIndex, - int argc, - __in_ecount(argc) LPWSTR * argv) -{ - unsigned int exitCode = EXIT_CODE_SUCCESS; - HRESULT hr = S_OK; - BSTR bstrConsoleFile = NULL; - do - { - // don't check StringIsNullOrEmpty(wszConsoleHostAssemblyName) here - // because it will check below with better error reporting - if (pwrshCommon.StringIsNullOrEmpty(wszMonadVersion) || - pwrshCommon.StringIsNullOrEmpty(wszRuntimeVersion)) - { - exitCode = EXIT_CODE_INIT_FAILURE; - break; - } - // Use the hosting interfaces from .Net Framework 1.1 - CComPtr pCLR = NULL; - - exitCode = pwrshCommon.LaunchCLR(wszMonadVersion, wszRuntimeVersion, &pCLR); - - if (EXIT_CODE_INIT_FAILURE == exitCode) - { - break; - } - - if(!ConvertArgvToSafeArray( - argc, - argv, - skipIndex, - &pArgvSA)) - { - exitCode = EXIT_CODE_INIT_FAILURE; - break; - } - - // Get a pointer to the default AppDomain - CComPtr<_AppDomain> spDefaultDomain = NULL; - CComPtr spAppDomainPunk = NULL; - - hr = pCLR->GetDefaultDomain(&spAppDomainPunk); - if (FAILED(hr) || spAppDomainPunk == NULL) - { - pwrshExeOutput->DisplayMessage(false, g_GETTING_DEFAULT_DOMAIN_FAILED, hr); - exitCode = EXIT_CODE_INIT_FAILURE; - break; - } - - hr = spAppDomainPunk->QueryInterface(__uuidof(_AppDomain), (PVOID*) &spDefaultDomain); - if (FAILED(hr) || spDefaultDomain == NULL) - { - pwrshExeOutput->DisplayMessage(false, g_GETTING_DEFAULT_DOMAIN_FAILED, hr); - exitCode = EXIT_CODE_INIT_FAILURE; - break; - } - - CComPtr<_ObjectHandle> spObjectHandle; - - // use CreateInstance because we use the assembly strong name (as opposed to CreateInstanceFrom) - _bstr_t bstrConsoleHostAssemblyName = _bstr_t(wszConsoleHostAssemblyName); - _bstr_t bstrUnmanagedMshEntryClass = _bstr_t(L"Microsoft.PowerShell.UnmanagedPSEntry"); - - hr = spDefaultDomain->CreateInstance( - bstrConsoleHostAssemblyName, - bstrUnmanagedMshEntryClass, - &spObjectHandle); - if (FAILED(hr) || spObjectHandle == NULL) - { - pwrshExeOutput->DisplayMessage(false, g_CREATING_MSH_ENTRANCE_FAILED, hr); - exitCode = EXIT_CODE_INIT_FAILURE; - break; - } - - CComVariant VntUnwrapped; - hr = spObjectHandle->Unwrap(&VntUnwrapped); - if (FAILED(hr)) - { - pwrshExeOutput->DisplayMessage(false, g_CREATING_MSH_ENTRANCE_FAILED, hr); - exitCode = EXIT_CODE_INIT_FAILURE; - break; - } - - CComPtr pDisp; - pDisp = VntUnwrapped.pdispVal; - - OLECHAR FAR * wszMember = L"Start"; - - DISPID dispid; - //Retrieve the DISPID - hr = pDisp->GetIDsOfNames ( - IID_NULL, - &wszMember, - 1, - LOCALE_SYSTEM_DEFAULT, - &dispid); - - if (FAILED(hr)) - { - pwrshExeOutput->DisplayMessage(false, g_GETTING_DISPATCH_ID_FAILED, hr); - exitCode = EXIT_CODE_INIT_FAILURE; - break; - } - - VARIANT pVarArgs[2]; - - // Both EnterWithConsoleFile and EnterWithConsoleFile take a string and a string array - // The order of the arguments need to be reversed in this array - pVarArgs[0].vt = VT_ARRAY; - pVarArgs[0].parray = pArgvSA; - - // NTRAID#Windows Out Of Band Releases-918924 - // using _bstr_t here fails consistently on one single machine. - // changing the call to SysAllocString fixes the problem. - if (wszConsoleFile != NULL) - { - bstrConsoleFile = SysAllocString(wszConsoleFile); - if (NULL == bstrConsoleFile) - { - exitCode = EXIT_CODE_INIT_FAILURE; - break; - } - } - pVarArgs[1].vt = VT_BSTR; - pVarArgs[1].bstrVal = bstrConsoleFile; - DISPPARAMS dispparamsTwoArgs = {pVarArgs, NULL, 2}; - - VARIANT varResult; - varResult.vt = VT_UINT; - varResult.uintVal = 0x00000000; - EXCEPINFO exception; - unsigned int uArgErr = 0; - - //Invoke the method on the Dispatch Interface - hr = pDisp->Invoke( - dispid, - IID_NULL, - LOCALE_SYSTEM_DEFAULT, - DISPATCH_METHOD, - &dispparamsTwoArgs, - &varResult, - &exception, - &uArgErr - ); - exitCode = varResult.uintVal; - if (FAILED(hr)) - { - if (DISP_E_EXCEPTION == hr) - { - pwrshExeOutput->DisplayMessage(false, g_MANAGED_MSH_EXCEPTION, exception.bstrDescription); - } - else - { - pwrshExeOutput->DisplayMessage(false, g_INOVKING_MSH_ENTRANCE_FAILED, hr); - } - exitCode = EXIT_CODE_INIT_FAILURE; - break; - } - } - while (false); - - // No need to call pCLR->Stop() because, - // as the common language runtime is automatically unloaded when the process exits. - - SysFreeString(bstrConsoleFile); - return exitCode; -} - -static bool IsDash(WCHAR wch) -{ - const WCHAR enDash = (WCHAR)0x2013; - const WCHAR emDash = (WCHAR)0x2014; - const WCHAR horizontalBar = (WCHAR)0x2015; - return (enDash == wch || emDash == wch || horizontalBar == wch || '-' == wch); -} - -static bool IsParameterMatched( - LPCWSTR wszParameter, - int cchParameter, - LPCWSTR wszCommandLineInput) -{ - - assert(cchParameter > 1 && !pwrshCommon.StringIsNullOrEmpty(wszParameter) && - wszCommandLineInput != NULL); - - // A parameter has to start with a dash... - if (!IsDash(wszCommandLineInput[0])) return false; - - // Skip over the dash character... - wszCommandLineInput = _wcsinc(wszCommandLineInput); - - if (pwrshCommon.StringIsNullOrEmpty(wszCommandLineInput)) return false; - - bool bReturnResult = true; - do - { - if (cchParameter <= 1 || pwrshCommon.StringIsNullOrEmpty(wszParameter) - && pwrshCommon.StringIsNullOrEmpty(wszCommandLineInput)) - { - bReturnResult = false; - break; - } - if (L'\0' == *wszCommandLineInput) - { - bReturnResult = false; - break; - } - size_t size_tCommandLineInput = 0; - // Since cchParameter is no larger than STRSAFE_MAX_CCH and wszCommandLineInput can't be - // null, StringCchLength won't return S_OK iff wszCommandLineInput is longer than - // cchParameter, in which case wszCommandLineInput is not a prefix of wszParameter - if (FAILED(StringCchLength(wszCommandLineInput, cchParameter, &size_tCommandLineInput))) - { - bReturnResult = false; - break; - } - int cchCommandLineInput = (int)size_tCommandLineInput; - - // string function - // since we know wszCommandLineInput is no longer than wszParameter, just compare the two strings - // up to the length of wszCommandLineInput - int comparison = CompareStringW( - LOCALE_INVARIANT, - NORM_IGNORECASE, - wszParameter, - cchCommandLineInput, // compare up to the size of wszRHSting - wszCommandLineInput, - cchCommandLineInput); - - assert(comparison); - if (0 == comparison) - { - bReturnResult = false; - break; - } - bReturnResult = comparison == CSTR_EQUAL; - } while (false); - return bReturnResult; -} - -static bool CheckConsoleFileExtension( - LPCWSTR wszFileName) -{ - bool bReturnResult = true; - do - { - if (pwrshCommon.StringIsNullOrEmpty(wszFileName)) - { - bReturnResult = false; - break; - } - LPCWSTR dot = wcsrchr(wszFileName, L'.'); - if (NULL == dot) - { - bReturnResult = false; - break; - } - //string function - LPCWSTR wszMonadConsoleFileExtension = L".psc1"; - const int cchMonadConsoleFileExtension = 5; - int comparison = CompareStringW( - LOCALE_INVARIANT, - NORM_IGNORECASE, - dot, - -1, - wszMonadConsoleFileExtension, - cchMonadConsoleFileExtension); - assert(comparison); - if (0 == comparison) - { - bReturnResult = false; - break; - } - bReturnResult = comparison == CSTR_EQUAL; - } while (false); - if (!bReturnResult) - { - pwrshExeOutput->DisplayMessage(false, g_INCORRECT_CONSOLE_FILE_EXTENSION, wszFileName); - } - return bReturnResult; -} - -bool VerifyConsoleSchemaVersion( - LPCWSTR wszConsoleSchemaVersion, - LPCWSTR wszFileName) -{ - bool returnResult = true; - do - { - if (pwrshCommon.StringIsNullOrEmpty(wszFileName)) - { - returnResult = false; - break; - } - - size_t cch = 0; - // make sure cch is in the range of int for the below call to CompareStringW - //string function - if (FAILED(StringCchLength(wszConsoleSchemaVersion, INT_MAX, &cch))) - { - pwrshExeOutput->DisplayMessage(false, g_READ_XML_INVALID_CONSOLE_SCHEMA_VERSION, wszFileName); - returnResult = false; - break; - } - //string function - LPCWSTR wszSupportedConsoleSchemaVersion = L"1.0"; - const int cchSupportedConsoleSchemaVersion = 3; - if (CSTR_EQUAL != CompareStringW( - LOCALE_INVARIANT, - 0, - wszSupportedConsoleSchemaVersion, - cchSupportedConsoleSchemaVersion, - wszConsoleSchemaVersion, (int)cch)) - { - pwrshExeOutput->DisplayMessage(false, g_READ_XML_INVALID_CONSOLE_SCHEMA_VERSION, wszFileName); - returnResult = false; - break; - } - } while (false); - return returnResult; -} - -_Success_(return) -bool ReadConsoleSchemaVersion( - CComPtr spRoot, - LPCWSTR wszFileName, - __deref_out_opt PWSTR * pwszConsoleSchemaVersion) -{ - bool returnResult = true; - CComPtr spMshConsoleFile = NULL; - CComPtr spMshConsoleFileAttrs = NULL; - CComPtr spConsoleSchemaVersion = NULL; - HRESULT hr = 0; - do - { - assert(!pwrshCommon.StringIsNullOrEmpty(wszFileName) && - spRoot != NULL && - pwszConsoleSchemaVersion != NULL); - if (pwrshCommon.StringIsNullOrEmpty(wszFileName) || - spRoot == NULL || - NULL == pwszConsoleSchemaVersion) - { - returnResult = false; - break; - } - _bstr_t bstrMshConsoleFileXPath = _bstr_t(L"/PSConsoleFile"); - hr = spRoot->selectSingleNode(bstrMshConsoleFileXPath, &spMshConsoleFile); - if (FAILED(hr) || spMshConsoleFile == NULL) - { - pwrshExeOutput->DisplayMessage(false, g_READ_XML_GET_PSCONSOLEFILE_FAILED, wszFileName); - returnResult = false; - break; - } - - hr = spMshConsoleFile->get_attributes(&spMshConsoleFileAttrs); - if (FAILED(hr) || spMshConsoleFileAttrs == NULL) - { - pwrshExeOutput->DisplayMessage(false, g_READ_XML_GET_CONSOLE_SCHEMA_VERSION_FAILED, wszFileName); - returnResult = false; - break; - } - - _bstr_t bstrConsoleSchemaVersionAttr = _bstr_t(L"ConsoleSchemaVersion"); - hr = spMshConsoleFileAttrs->getNamedItem(bstrConsoleSchemaVersionAttr, &spConsoleSchemaVersion); - if (FAILED(hr) || spConsoleSchemaVersion == NULL) - { - pwrshExeOutput->DisplayMessage(false, g_READ_XML_GET_CONSOLE_SCHEMA_VERSION_FAILED, wszFileName); - returnResult = false; - break; - } - - BSTR bstrConsoleSchemaVersion = NULL; - hr = spConsoleSchemaVersion->get_text(&bstrConsoleSchemaVersion); - - if (FAILED(hr)) - { - pwrshExeOutput->DisplayMessage(false, g_READ_XML_GET_CONSOLE_SCHEMA_VERSION_FAILED, wszFileName); - returnResult = false; - break; - } - - *pwszConsoleSchemaVersion = bstrConsoleSchemaVersion; - } while (false); - return returnResult; -} - -void DisplaySpecificXMLDOMError( - CComPtr spXMLDoc, - LPCWSTR wszFileName) -{ - bool bIsSpecificErrorDisplayed = true; - BSTR bstrReason = NULL; - do - { - assert(spXMLDoc != NULL && !pwrshCommon.StringIsNullOrEmpty(wszFileName)); - if (spXMLDoc == NULL || pwrshCommon.StringIsNullOrEmpty(wszFileName)) - { - break; - } - // check for file existence, permission, etc first because - // IXMLDOMParseError's message is not as descriptive - HANDLE xmlFileHandle = CreateFile(wszFileName, - FILE_READ_DATA, - FILE_SHARE_READ, - NULL, - OPEN_EXISTING, - 0, - NULL); - if (INVALID_HANDLE_VALUE == xmlFileHandle) - { - LONG systemErrorCode = GetLastError(); - pwrshExeOutput->DisplayErrorWithSystemError(systemErrorCode, - g_READ_XML_LOAD_FILE_FAILED_WITH_SPECIFIC_ERROR, - wszFileName); - break; - } - CloseHandle(xmlFileHandle); - - CComPtr spIParseError = NULL; - HRESULT hr = spXMLDoc->get_parseError(&spIParseError); - if (FAILED(hr) || spIParseError == NULL) - { - bIsSpecificErrorDisplayed = false; - break; - } - hr = spIParseError->get_reason(&bstrReason); - if (FAILED(hr) || (NULL == bstrReason)) - { - bIsSpecificErrorDisplayed = false; - break; - } - long line = -1; - hr = spIParseError->get_line(&line); - if (FAILED(hr) || (line == -1)) - { - bIsSpecificErrorDisplayed = false; - break; - } - long linepos = -1; - hr = spIParseError->get_linepos(&linepos); - if (FAILED(hr) || (linepos == -1)) - { - bIsSpecificErrorDisplayed = false; - break; - } - pwrshExeOutput->DisplayMessage(false, - g_READ_XML_LOAD_FILE_FAILED_WITH_SPECIFIC_POSITION_ERROR, - wszFileName, - bstrReason, - line, - linepos); - } while (false); - SysFreeString(bstrReason); - if (!bIsSpecificErrorDisplayed) - { - // if displaying specific error failed, display a generic error - pwrshExeOutput->DisplayMessage(false, g_READ_XML_LOAD_FILE_FAILED, wszFileName); - } -} - -static bool ReadVersionFromConsoleFile( - LPCWSTR wszFileName, - __deref_out_opt PWSTR * pwszMonadVersion, - __out_ecount(1) int * lpMonadMajorVersion, - __out_ecount(1) int * lpMonadMinorVersion) -{ - assert(pwszMonadVersion); - if (NULL == pwszMonadVersion || - NULL == lpMonadMajorVersion || NULL == lpMonadMinorVersion) - { - return false; - } - *pwszMonadVersion = NULL; - *lpMonadMajorVersion = *lpMonadMinorVersion = -1; - if (NULL == wszFileName) - { - pwrshExeOutput->DisplayMessage(true, g_INVALID_CONSOLE_FILE_PATH, L"NULL"); - return false; - } - bool returnResult = true; - bool coInited = false; - BSTR bstrVersion = NULL; - do - { - HRESULT hr = S_OK; - CComVariant xmlSource = wszFileName; - CComPtr spXMLDoc = NULL; - CComPtr spDocElem = NULL; - CComPtr spRoot = NULL; - CComPtr spVersion = NULL; - hr = - CoInitializeEx( - NULL, - COINIT_MULTITHREADED); - - if (FAILED(hr)) - { - pwrshExeOutput->DisplayMessage(false, g_READ_XML_COM_INIT_FAILED, hr); - returnResult = false; - break; - } - coInited = true; - hr = CoCreateInstance( - CLSID_DOMDocument60, // by default, ProhibitDTD = true, ResolveExternals = false, UseInlineSchema = false - NULL, - CLSCTX_INPROC_SERVER, - IID_IXMLDOMDocument, - (void **)&spXMLDoc); - if (FAILED(hr)) - { - pwrshExeOutput->DisplayMessage(false, g_READ_XML_CREATE_DOMDOCUMENT_FAILED, hr); - returnResult = false; - break; - } - - spXMLDoc->put_async(false); - - VARIANT_BOOL bIsSuccessful = 1; - hr = spXMLDoc->load(xmlSource, &bIsSuccessful); - if (FAILED(hr) || !bIsSuccessful) - { - DisplaySpecificXMLDOMError(spXMLDoc, wszFileName); - returnResult = false; - break; - } - - hr = spXMLDoc->get_documentElement(&spDocElem); - if (FAILED(hr) || spDocElem == NULL) - { - pwrshExeOutput->DisplayMessage(false, g_READ_XML_GET_MONAD_VERSION_TEXT_FAILED, wszFileName); - returnResult = false; - break; - } - - hr = spDocElem->get_firstChild(&spRoot); - if (FAILED(hr) || spRoot == NULL) - { - pwrshExeOutput->DisplayMessage(false, g_READ_XML_GET_MONAD_VERSION_TEXT_FAILED, wszFileName); - returnResult = false; - break; - }; - LPWSTR wszConsoleSchemaVersion = NULL; - if (!ReadConsoleSchemaVersion(spRoot, wszFileName, &wszConsoleSchemaVersion)) - { - returnResult = false; - break; - } - if (!VerifyConsoleSchemaVersion(wszConsoleSchemaVersion, wszFileName)) - { - returnResult = false; - break; - } - - _bstr_t bstrMshVersionTextXPath = _bstr_t(L"/PSConsoleFile/PSVersion/text()"); - hr = spRoot->selectSingleNode(bstrMshVersionTextXPath, &spVersion); - if (FAILED(hr)) - { - pwrshExeOutput->DisplayMessage(false, g_READ_XML_GET_MONAD_VERSION_TEXT_FAILED, wszFileName); - returnResult = false; - break; - } - if (spVersion == NULL) - { - pwrshExeOutput->DisplayMessage(false, g_READ_XML_GET_EMPTY_MONAD_VERSION_TEXT, wszFileName); - returnResult = false; - break; - } - - hr = spVersion->get_text(&bstrVersion); - if (FAILED(hr)) - { - pwrshExeOutput->DisplayMessage(false, g_READ_XML_GET_MONAD_VERSION_TEXT_FAILED, wszFileName); - returnResult = false; - break; - } - if (!pwrshCommon.VerifyMonadVersionFormat(bstrVersion, lpMonadMajorVersion, lpMonadMinorVersion, true, true)) - { - returnResult = false; - break; - } - // SysStringLen does not include terminating null - UINT wszVersionLength = SysStringLen(bstrVersion) + 1; - WCHAR * wszVersion = new WCHAR[wszVersionLength]; - if (NULL == wszVersion) - { - returnResult = false; - break; - } - if (FAILED(StringCchCopy(wszVersion, wszVersionLength, bstrVersion))) - { - returnResult = false; - break; - } - *pwszMonadVersion = wszVersion; - } while (false); - if (coInited) - { - CoUninitialize(); - } - SysFreeString(bstrVersion); - return returnResult; -} - -#pragma prefast(push) -#pragma prefast (disable: 6101) // Returning uninitialized memory - pwszRuntimeVersion, pwszConsoleFile, pwszMonadVersion, and pwszRuntimeVersion are not always set on success. - - -unsigned int ParseCommandLineArguments( - IN int argc, - __in_ecount(argc) LPWSTR * argv, - __deref_out_opt PWSTR * pwszMonadVersion, - __out_ecount(1) int * lpMonadMajorVersion, - __out_ecount(1) int * lpMonadMinorVersion, - __inout_ecount(1) int * lpMonadVersionIndex, - __deref_out_opt PWSTR * pwszRuntimeVersion, - __out_ecount(1) int * lpRuntimeVersionIndex, - __deref_out_opt PWSTR * pwszConsoleFile, - __inout_ecount(1) int * lpConsoleFileIndex, - __inout_ecount(1) int * lpProfileIndex) -{ - const wchar_t * wszArgumentVersion = L"version"; - const int cchArgumentVersion = 8; // including null terminating - const wchar_t * wszArgumentMonadConsole = L"psconsolefile"; - const int cchArgumentMonadConsole = 15; // including null terminating - const wchar_t * wszArgumentRuntimeVersion = L"runtimeversion"; - const int cchArgumentRuntimeVersion = 15; // including null terminating - const wchar_t * wszArgumentMonadProfile = L"noprofile"; - const int cchArgumentMonadProfile = 10; // including null terminating - const wchar_t * wszArgumentMonadProfileShort = L"nop"; - const int cchArgumentMonadProfileShort = 4; // including null terminating - const wchar_t * wszArgumentServerMode20 = L"servermode"; - const int cchArgumentServerMode20 = 11; // including null terminating - const wchar_t * wszArgumentServerMode20Short = L"s"; - const int cchArgumentServerMode20Short = 2; // including null terminating - bool bServerMode20Specified = false; - - int version_lpMonadMajorVersion = -1; - int version_lpMonadMinorVersion = -1; - wchar_t * version_pwszMonadVersion = NULL; - - unsigned int exitCode = EXIT_CODE_SUCCESS; - do - { - assert(pwszMonadVersion && lpMonadVersionIndex && pwszConsoleFile && lpConsoleFileIndex && pwszRuntimeVersion && lpRuntimeVersionIndex); - if (NULL == pwszMonadVersion || - NULL == lpMonadMajorVersion || - NULL == lpMonadMinorVersion || - NULL == lpMonadVersionIndex || - NULL == pwszRuntimeVersion || - NULL == lpRuntimeVersionIndex || - NULL == pwszConsoleFile || - NULL == lpConsoleFileIndex || - NULL == lpProfileIndex ) - { - exitCode = EXIT_CODE_BAD_COMMAND_LINE_PARAMETER; - break; - } - - *lpMonadVersionIndex = *lpMonadMinorVersion = -1; - if (1 >= argc) - { - // no parameters given - break; - } - - - int idxParameterPosition = 1; - LPCWSTR wszCommandLineInput = argv[idxParameterPosition]; - - // Parse for -version - if (IsParameterMatched(wszArgumentVersion, cchArgumentVersion, wszCommandLineInput)) - { - if (idxParameterPosition < argc - 1) - { - idxParameterPosition++; - if (!pwrshCommon.VerifyMonadVersionFormat(argv[idxParameterPosition], lpMonadMajorVersion, lpMonadMinorVersion, true, true)) - { - exitCode = EXIT_CODE_BAD_COMMAND_LINE_PARAMETER; - break; - } - *lpMonadVersionIndex = idxParameterPosition - 1; - *pwszMonadVersion = argv[idxParameterPosition]; - - // Save the version values in case we need to override the version in psconsolefile - version_lpMonadMajorVersion = *lpMonadMajorVersion; - version_lpMonadMinorVersion = *lpMonadMinorVersion; - version_pwszMonadVersion = argv[idxParameterPosition]; - - if (idxParameterPosition < argc - 1) - { - idxParameterPosition = idxParameterPosition + 1; - wszCommandLineInput = argv[idxParameterPosition]; - } - } - else - { - pwrshExeOutput->DisplayMessage( - false, - g_MISSING_COMMAND_LINE_ARGUMENT, - wszArgumentVersion); - exitCode = EXIT_CODE_BAD_COMMAND_LINE_PARAMETER; - break; - } - } - - // Parse for -ServerMode. - // PowerShell 2.0's Start-Job using the string "-s -nologo -noprofile". To let - // powershell 2.0 launch a 2.0 background job, we are hardcoding the version here. - // PowerShell 3.0 and beyond, will be using the string "-s -version <> -noprofile -nologo". - // The -Version parameter processed before should take care of loading correct - // powershell in 3.0 and beyond case. - if ((IsParameterMatched(wszArgumentServerMode20, cchArgumentServerMode20, wszCommandLineInput) || - IsParameterMatched(wszArgumentServerMode20Short, cchArgumentServerMode20Short, wszCommandLineInput)) && - (*lpMonadVersionIndex == -1)) - { - idxParameterPosition++; - *lpMonadMajorVersion = 2; - *lpMonadMinorVersion = -1; - bServerMode20Specified = true; - *pwszMonadVersion = L"2.0"; - - // let the rest of the parameter processing happen in managed code for -ServerMode - // hence not updating wszCommandLineInput - } - - // Parse for CLR Version - if (IsParameterMatched(wszArgumentRuntimeVersion, cchArgumentRuntimeVersion, wszCommandLineInput)) - { - if (idxParameterPosition < argc - 1) - { - idxParameterPosition++; - - // No need for validation of CLR version, it is validated outside of the - // parameter processing code (because we might also read it from the registry) - *lpRuntimeVersionIndex = idxParameterPosition - 1; - *pwszRuntimeVersion = argv[idxParameterPosition]; - - if (idxParameterPosition < argc - 1) - { - idxParameterPosition = idxParameterPosition + 1; - wszCommandLineInput = argv[idxParameterPosition]; - } - } - else - { - pwrshExeOutput->DisplayMessage( - false, - g_MISSING_COMMAND_LINE_ARGUMENT, - wszArgumentRuntimeVersion); - exitCode = EXIT_CODE_BAD_COMMAND_LINE_PARAMETER; - break; - } - } - - // Parse for MshConsoleFile - if (IsParameterMatched(wszArgumentMonadConsole, cchArgumentMonadConsole, wszCommandLineInput)) - { - if (idxParameterPosition < argc - 1) - { - idxParameterPosition++; - if (!CheckConsoleFileExtension(argv[idxParameterPosition])) - { - exitCode = EXIT_CODE_READ_CONSOLE_FILE_FAILURE; - break; - } - if (!ReadVersionFromConsoleFile(argv[idxParameterPosition], pwszMonadVersion, - lpMonadMajorVersion, lpMonadMinorVersion)) - { - exitCode = EXIT_CODE_READ_CONSOLE_FILE_FAILURE; - break; - } - *lpConsoleFileIndex = idxParameterPosition - 1; - *pwszConsoleFile = argv[idxParameterPosition]; - } - else - { - pwrshExeOutput->DisplayMessage( - false, - g_MISSING_COMMAND_LINE_ARGUMENT, - wszArgumentMonadConsole); - exitCode = EXIT_CODE_BAD_COMMAND_LINE_PARAMETER; - break; - } - } - - // Parse for NoProfile - if (IsParameterMatched(wszArgumentMonadProfile, cchArgumentMonadProfile, wszCommandLineInput) || - IsParameterMatched(wszArgumentMonadProfileShort, cchArgumentMonadProfileShort, wszCommandLineInput)) - { - idxParameterPosition++; - *lpProfileIndex = idxParameterPosition - 1; - } - - // If version parameter is not specified, always load the PowerShell 3.0 - if ((*lpMonadVersionIndex == -1) && (!bServerMode20Specified)) - { - *lpMonadMajorVersion = 3; - *lpMonadMinorVersion = -1; - - wchar_t * wszConsoleFile = NULL; - wchar_t * wszConsoleHostAssemblyName = NULL; - wchar_t * wszRuntimeVersion = NULL; - wchar_t * tempMonadVersion = NULL; - - // This gets the Monad Version from the registry - exitCode = pwrshCommon.GetRegistryInfo( - &tempMonadVersion, - lpMonadMajorVersion, - *lpMonadMinorVersion, - &wszRuntimeVersion, - &wszConsoleHostAssemblyName); - - if (EXIT_CODE_SUCCESS != exitCode) - { - break; - } - - // This holds 3.0 - *pwszMonadVersion = tempMonadVersion; - } - - // In case both version and psconsolefile are specified, load the powershell specified in the version parameter. - if (*lpMonadVersionIndex != -1 && *lpConsoleFileIndex != -1) - { - *lpMonadMajorVersion = version_lpMonadMajorVersion; - *lpMonadMinorVersion = version_lpMonadMinorVersion; - *pwszMonadVersion = version_pwszMonadVersion; - } - - } - while(false); - - return exitCode; -} - -#pragma prefast(pop) - -/********************************************************* - Loads a string from the modules resource -**********************************************************/ -HRESULT SafeLoadString(UINT uId, __deref_out LPWSTR* ppszString) -{ - HINSTANCE hInstance = NULL; - HRESULT hr = S_OK; - - // get a handle to the current application - hInstance = GetModuleHandle(NULL); - - if (hInstance != NULL) - { - LPWSTR pszString = NULL; - pszString = static_cast(::malloc(sizeof(WCHAR) * (100 + 1))); - - if (pszString != NULL) - { - DWORD length = ::LoadStringW(hInstance, uId, pszString, 100); - - if ( length > 0 && length < 100) - { - *ppszString = pszString; - } - else - { - // string with specified resource id is longer, - // quit without loading - free(pszString); - hr = HRESULT_FROM_WIN32(::GetLastError()); - } - } - else - { - // Allocation failed - hr = HRESULT_FROM_WIN32(::GetLastError()); - } - return hr; - } - hr = HRESULT_FROM_WIN32(::GetLastError()); - return hr; -} - -#ifdef _PREFAST_ -#pragma prefast (pop) -#endif /* _PREFAST_ */ - -#if (WINVER >= _WIN32_WINNT_WIN7) - -/************************************************************************* -Creates a shortcut from the specified properties - -ppShortCut will contain the IShellLink that represents this -shortcut - -Note that the above short cut will not be stored on disk -**************************************************************************/ -HRESULT CreateShortCut(PCWSTR pszDisplay, PCWSTR pszAppPath, PCWSTR pszDescription, - PCWSTR pszArguments, PCWSTR pszIconAppPath, int iIconIndex, bool requiresElevation, - bool console,IShellLink **ppShortCut) -{ - CComPtr pShellLink; // pointer to a shell link - - HRESULT hr = pShellLink.CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER); - - CheckAndReturn(hr); - - // set the path to the application - hr = pShellLink->SetPath(pszAppPath); - CheckAndReturn(hr); - - // set the application arguments - hr = pShellLink->SetArguments(pszArguments); - CheckAndReturn(hr); - - // set the icon index - hr = pShellLink->SetIconLocation(pszIconAppPath, iIconIndex); - CheckAndReturn(hr); - - // IShellLink contains a property store - // the title for a task should be contained - // in the PKEY_Title property in this - // property store - CComPtr pPropertyStore; - - // query for interface - hr = pShellLink->QueryInterface(IID_PPV_ARGS(&pPropertyStore)); - CheckAndReturn(hr); - - // set PKEY_Title property to the specified display - PROPVARIANT propvar; - hr = InitPropVariantFromString(pszDisplay, &propvar); - CheckAndReturn(hr); - - hr = pPropertyStore->SetValue(PKEY_Title, propvar); - PropVariantClear(&propvar); - CheckAndReturn(hr); - - hr = pPropertyStore->Commit(); - CheckAndReturn(hr); - - // IShellLink implements an interface IShellLinkDataList - // if we need to set console properties or if the shortcut - // requires elevation, then we need to query for - // IShellLinkDataList and work with the same - CComPtr pShellLinkDataList; - - pShellLink->QueryInterface(IID_PPV_ARGS(&pShellLinkDataList)); - CheckAndReturn(hr); - - DWORD dwFlags = 0; - hr = pShellLinkDataList->GetFlags(&dwFlags); - CheckAndReturn(hr); - - dwFlags |= SLDF_ALLOW_LINK_TO_LINK; - hr = pShellLinkDataList->SetFlags(dwFlags); - CheckAndReturn(hr); - - // if elevation is required, set the flags accordingly - if (requiresElevation) - { - // It has methods GetFlags() and SetFlags() to obtain - // and modify the flags on a shell link. The - // SLDF_RUNAS_USER should be set to allow running as an - // administrator - - dwFlags |= SLDF_RUNAS_USER; - hr = pShellLinkDataList->SetFlags(dwFlags); - CheckAndReturn(hr); - } - - hr = pShellLink->QueryInterface(IID_PPV_ARGS(ppShortCut)); - - return hr; -} - -#endif - -/******************************************************************** -Checks to see if ISE is present -*********************************************************************/ -INT CheckForISE() -{ - WIN32_FIND_DATA FindFileData; - HANDLE handle = NULL; - DWORD length = MAX_PATH; - int isePresent = 0; - - LPWSTR pszExpandedPath = static_cast(::malloc((length + 1) * sizeof(WCHAR))); - if (pszExpandedPath != NULL) - { - DWORD retlen = ExpandEnvironmentStrings(g_ISE_BINARY_PATH, pszExpandedPath, length); - - if (retlen > 0 && retlen <= length) - { - handle = ::FindFirstFile(pszExpandedPath, &FindFileData); - - if (handle != INVALID_HANDLE_VALUE) - { - isePresent = 1; - ::FindClose(handle); - } - } - free(pszExpandedPath); - } - - return isePresent; -} - -/********************************************************************** - Function to check if the current process is a WOW64 process -**********************************************************************/ -BOOL IsWow64() -{ - HANDLE hCurrentProc = GetCurrentProcess(); - - BOOL isWow64Process = FALSE; - BOOL ret = IsWow64Process(hCurrentProc, &isWow64Process); - - if (ret) - { - return isWow64Process; - } - - return FALSE; -} - -/********************************************************************** - Function to check if the current process is a WinPE process -**********************************************************************/ -bool IsWinPEHost() -{ - HKEY hkResult; - LONG lRes = RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\MiniNT", 0, KEY_READ, &hkResult) ; - - if(lRes == ERROR_SUCCESS) - { - RegCloseKey(hkResult); - } - - // The Registry Path does not exit on any other SKU except WinPE - return lRes == ERROR_SUCCESS; -} - -/********************************************************************** - Function to check if the current OS is Win7 or later -**********************************************************************/ -bool IsOSLWin7OrLater() -{ - return IsWindows7OrGreater(); -} - -// Validate that the CLR was present when PowerShell was installed -// (if on a downlevel machine) -unsigned int ValidateDownlevelSetupHadClrWhenInstalled( - __in PWSTR wszMonadVersion, - int monadMajorVersion, - __in PWSTR wszRuntimeVersion, - int useMonadMajorVersion) - -{ - unsigned int exitCode = ERROR_SUCCESS; - - HKEY hEngineKey = NULL; - wchar_t * wszMshEngineRegKeyPath = NULL; - wchar_t * NetFxV4IsInstalledKeyValue = NULL; - DWORD valueLengthInByte = 0; - - static LPCWSTR g_NetFX_V4_IS_INSTALLED_KEY = L"NetFrameworkV4IsInstalled"; - - do - { - exitCode = pwrshCommon.OpenEngineRegKey(&hEngineKey, &wszMshEngineRegKeyPath, &wszMonadVersion, &useMonadMajorVersion); - if (EXIT_CODE_SUCCESS != exitCode) - { - break; - } - - // If NetFramework4IsInstalled key exists and value equals No, output error message. - // Else, Launch PowerShell - LONG lResult = RegQueryValueExW(hEngineKey, g_NetFX_V4_IS_INSTALLED_KEY, NULL, NULL, NULL, &valueLengthInByte); - if (lResult == ERROR_SUCCESS) - { - // If the data has the REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ type, this size includes any terminating null character or characters - // unless the data was stored without them - http://msdn.microsoft.com/library/ms724911(VS.85).aspx - NetFxV4IsInstalledKeyValue = new wchar_t[valueLengthInByte / sizeof(wchar_t)]; - if (NULL == NetFxV4IsInstalledKeyValue) - { - exitCode = EXIT_CODE_INIT_FAILURE; - } - else - { - memset(NetFxV4IsInstalledKeyValue, 0, valueLengthInByte); - - lResult = RegQueryValueExW( - hEngineKey, - g_NetFX_V4_IS_INSTALLED_KEY, - NULL, - NULL, - (LPBYTE) NetFxV4IsInstalledKeyValue, - &valueLengthInByte); - - if (lResult == ERROR_SUCCESS) - { - if (0 == wcsncmp(NetFxV4IsInstalledKeyValue, L"No", 2)) - { - exitCode = EXIT_CODE_INIT_FAILURE; - pwrshExeOutput->DisplayMessage(false, g_CLR_VERSION_NOT_INSTALLED, wszRuntimeVersion, wszMonadVersion); - } - } - } - } - } - while(false); - - if (NULL != hEngineKey) - { - RegCloseKey(hEngineKey); - hEngineKey = NULL; - } - - if (NULL != wszMshEngineRegKeyPath) - { - delete[] wszMshEngineRegKeyPath; - wszMshEngineRegKeyPath = NULL; - } - - if (NULL != NetFxV4IsInstalledKeyValue) - { - delete[] NetFxV4IsInstalledKeyValue; - NetFxV4IsInstalledKeyValue = NULL; - } - - return exitCode; -} - -#if (WINVER >= _WIN32_WINNT_WIN7) - -#pragma prefast(push) -#pragma prefast (disable: 6031) // Return value ignored - StringCchLengthW return value is ignored - -/********************************************************************** - Adds the required PowerShell Tasks to the custom destination list -***********************************************************************/ -HRESULT AddPowerShellTasksToList(ICustomDestinationList *pCustDestList, STARTUPINFO &startupInfo) -{ - LPCWSTR lpParentShortCut = startupInfo.lpTitle; - LPWSTR pathRegValue = NULL; - BOOL foundlnkFile = false; - - if (NULL == lpParentShortCut || ( (startupInfo.dwFlags & STARTF_TITLEISLINKNAME) != STARTF_TITLEISLINKNAME ) ) - { - LPWSTR pathRegValueName =NULL; - DWORD valueLengthInByte = 0; - LONG retVal = 0; - - if (IsWow64()) - { - pathRegValueName = L"ConsoleHostShortcutTargetX86"; - } - else - { - pathRegValueName = L"ConsoleHostShortcutTarget"; - } - - retVal = RegGetValue(HKEY_LOCAL_MACHINE, g_ConsoleHostShortcutTarget_KEY_PATH, pathRegValueName, RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ | RRF_NOEXPAND, NULL, NULL, &valueLengthInByte); - if (ERROR_SUCCESS == retVal) - { - pathRegValue = new wchar_t[valueLengthInByte / sizeof(wchar_t) +1]; - memset(pathRegValue, 0, valueLengthInByte + sizeof(wchar_t)); - - retVal = RegGetValue(HKEY_LOCAL_MACHINE, g_ConsoleHostShortcutTarget_KEY_PATH, pathRegValueName, RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ | RRF_NOEXPAND, NULL, pathRegValue, &valueLengthInByte); - if (retVal == ERROR_SUCCESS) - { - lpParentShortCut = pathRegValue; - foundlnkFile = true; - } - else - { - if (IsWow64()) - { - // Check for Threshold: Windows PowerShell (x86).lnk - if (FileExists(L"%AppData%\\Microsoft\\Windows\\Start Menu\\Programs\\Windows PowerShell\\Windows PowerShell(x86).lnk")) - { - lpParentShortCut = L"%AppData%\\Microsoft\\Windows\\Start Menu\\Programs\\Windows PowerShell\\Windows PowerShell(x86).lnk"; - foundlnkFile = true; - } - - // Check for Win8 & BLUE: Windows PowerShell (x86).lnk - if (!foundlnkFile && FileExists(L"%ProgramData%\\Microsoft\\Windows\\Start Menu\\Programs\\Administrative Tools\\Windows PowerShell (x86).lnk")) - { - lpParentShortCut = L"%ProgramData%\\Microsoft\\Windows\\Start Menu\\Programs\\Administrative Tools\\Windows PowerShell (x86).lnk"; - foundlnkFile = true; - } - - // Check for Win7: Windows PowerShell (x86).lnk - if(!foundlnkFile && FileExists(L"%ProgramData%\\Microsoft\\Windows\\Start Menu\\Programs\\Accessories\\Windows PowerShell\\Windows PowerShell (x86).lnk")) - { - lpParentShortCut = L"%ProgramData%\\Microsoft\\Windows\\Start Menu\\Programs\\Accessories\\Windows PowerShell\\Windows PowerShell (x86).lnk"; - foundlnkFile = true; - } - } - else - { - // Check for Threshold: Windows PowerShell.lnk - if (FileExists(L"%AppData%\\Microsoft\\Windows\\Start Menu\\Programs\\Windows PowerShell\\Windows PowerShell.lnk")) - { - lpParentShortCut = L"%AppData%\\Microsoft\\Windows\\Start Menu\\Programs\\Windows PowerShell\\Windows PowerShell.lnk"; - foundlnkFile = true; - } - - // Check for Win8 & BLUE: Windows PowerShell.lnk - if (!foundlnkFile && FileExists(L"%ProgramData%\\Microsoft\\Windows\\Start Menu\\Programs\\System Tools\\Windows PowerShell.lnk")) - { - lpParentShortCut = L"%ProgramData%\\Microsoft\\Windows\\Start Menu\\Programs\\System Tools\\Windows PowerShell.lnk"; - foundlnkFile = true; - } - - // Check for Win7: Windows PowerShell.lnk - if(!foundlnkFile && FileExists(L"%ProgramData%\\Microsoft\\Windows\\Start Menu\\Programs\\Accessories\\Windows PowerShell\\Windows PowerShell.lnk")) - { - lpParentShortCut = L"%ProgramData%\\Microsoft\\Windows\\Start Menu\\Programs\\Accessories\\Windows PowerShell\\Windows PowerShell.lnk"; - foundlnkFile = true; - } - } - } - - // Update the Console title. - LPWSTR pszTitle = NULL; - HRESULT hresult = SafeLoadString(109, &pszTitle); - CheckAndReturn(hresult); - SetConsoleTitle(pszTitle); - free(pszTitle); - } - - size_t length; - StringCchLength(lpParentShortCut, STRSAFE_MAX_LENGTH, &length); - - StringCchCopy(g_IconApp, length+1, lpParentShortCut); - } - - if(!foundlnkFile) - { - size_t length2; - StringCchLength(lpParentShortCut, STRSAFE_MAX_LENGTH, &length2); - StringCchCopy(g_IconApp, length2+1, lpParentShortCut); - } - - CComPtr pPersistFile; - CComPtr pShellLink; - - HRESULT hr = pShellLink.CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER); - CheckAndReturn(hr); - - hr = pShellLink->QueryInterface(IID_IPersistFile, (LPVOID*)&pPersistFile); - CheckAndReturn(hr); - - hr = pPersistFile->Load(g_IconApp, STGM_READWRITE); - int iconIndex = 0; - if (SUCCEEDED(hr)) - { - hr = pShellLink->GetIconLocation(g_IconApp, MAX_PATH, &iconIndex); - CheckAndReturn(hr); - } - else - { - LPCWSTR powerShellExec = L"%windir%\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"; - - size_t length; - - StringCchLength(powerShellExec, STRSAFE_MAX_LENGTH, &length); - - StringCchCopy(g_IconApp, length+1, powerShellExec); - } - - CComPtr pShortCutCollection; - - hr = pShortCutCollection.CoCreateInstance(CLSID_EnumerableObjectCollection, NULL, CLSCTX_INPROC); - CheckAndReturn(hr); - - CComPtr pShortCut; - - LPWSTR pszDisplay = NULL; // display string - LPWSTR pszDescription = NULL; // description string - - - // 1. Add "Run Windows PowerShell as admin" - hr = SafeLoadString(118, &pszDisplay); - CheckAndReturn(hr); - SafeLoadString(119, &pszDescription); - CheckAndReturn(hr); - - // create shortcut - hr = CreateShortCut(pszDisplay, lpParentShortCut, pszDescription, - NULL, g_IconApp, iconIndex, true, true, &pShortCut); - delete[] pathRegValue; - free(pszDisplay); - free(pszDescription); - CheckAndReturn(hr); - - // add short cut to collection - hr = pShortCutCollection->AddObject(pShortCut); - CheckAndReturn(hr); - - // 2. Add Windows PowerShell ISE - // check if ISE is present - if (CheckForISE()) - { - // Add shortcut for "Run ISE as Administrator" - hr = SafeLoadString(122, &pszDisplay); - CheckAndReturn(hr); - SafeLoadString(123, &pszDescription); - CheckAndReturn(hr); - - // create new shortcut, free the previous one (already transferred to the collection) - pShortCut = NULL; - hr = CreateShortCut(pszDisplay, g_ISE_BINARY_PATH, pszDescription, NULL,g_ISE_BINARY_PATH, 0, true, false, &pShortCut); - free(pszDisplay); - free(pszDescription); - CheckAndReturn(hr); - - // add short cut to collection - hr = pShortCutCollection->AddObject(pShortCut); - CheckAndReturn(hr); - - hr = SafeLoadString(101, &pszDisplay); - CheckAndReturn(hr); - SafeLoadString(111, &pszDescription); - CheckAndReturn(hr); - - // create new shortcut, free the previous one (already transferred to the collection) - pShortCut = NULL; - hr = CreateShortCut(pszDisplay, g_ISE_BINARY_PATH, pszDescription, NULL,g_ISE_BINARY_PATH, 0, false, false, &pShortCut); - free(pszDisplay); - free(pszDescription); - CheckAndReturn(hr); - - // add short cut to collection - hr = pShortCutCollection->AddObject(pShortCut); - CheckAndReturn(hr); - } - - // obtain IObjectArry from the short cut collection - // since AddUserTasks requires one - CComPtr pObjectArray; - hr = pShortCutCollection->QueryInterface(IID_PPV_ARGS(&pObjectArray)); - CheckAndReturn(hr); - - hr = pCustDestList->AddUserTasks(pObjectArray); - - return hr; -} - -/********************************************************************* -* FileExists is a helper function used to check if the file path -* provided as argument to this function exists or not. -*********************************************************************/ -BOOL FileExists(LPCWSTR fileName) -{ - HANDLE hFile; - LPSECURITY_ATTRIBUTES pSec = (LPSECURITY_ATTRIBUTES)NULL; - ::SetLastError(ERROR_SUCCESS); - hFile = ::CreateFile(fileName, - GENERIC_READ, - FILE_SHARE_READ, // | FILE_SHARE_WRITE, - pSec, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS, - 0); - if(hFile != INVALID_HANDLE_VALUE) - { - ::CloseHandle(hFile); - return TRUE; - } - else { - return FALSE; - } -} - -/********************************************************************* -* Create a Custom Destination List for PowerShell on first run -*********************************************************************/ -void CreateCustomDestinationList(STARTUPINFO &startupInfo) -{ - CoInitialize(NULL); - - CComPtr pCustDestList; // pointer to the jump list - UINT uMaxSlots = 0; // maximum slots available for us - // to create items in jump list - - HRESULT hr = pCustDestList.CoCreateInstance(CLSID_DestinationList, NULL, CLSCTX_INPROC_SERVER); - - if (SUCCEEDED(hr)) - { - CComPtr pRemovedItems; // Items just removed when this transaction begins - - // start a list building transaction - // this method needs to be called before - // any of the other methods in ICustomDestinationList - hr = pCustDestList->BeginList(&uMaxSlots, IID_PPV_ARGS(&pRemovedItems)); - - if (SUCCEEDED(hr)) - { - // we need to verify if there is enough - // space for us to add the required items - if (uMaxSlots < PS_TASK_NUM) - { - return; - } - - hr = AddPowerShellTasksToList(pCustDestList, startupInfo); - - if (SUCCEEDED(hr)) - { - // if adding tasks succeeded commit the list - hr = pCustDestList->CommitList(); - } - } - } - - CoUninitialize(); -} - -#pragma prefast(push) - -#endif - -int __cdecl - wmain( - int argc, - __in_ecount(argc) LPWSTR * argv) -{ - #ifdef ALLOWDEBUG - // This loop is added to assist debugging server. - // Attach a debugger to the server and set this variable to true - // from the debugger. - bool isDebuggerAttached = false; - do - { - Sleep(1); - }while(!isDebuggerAttached); - #endif - - wchar_t * wszMonadVersion = NULL; - wchar_t * wszConsoleFile = NULL; - SAFEARRAY * pArgvSA = NULL; - wchar_t * wszDefaultRuntimeVersion = NULL; - wchar_t * wszRuntimeVersion = NULL; - wchar_t * wszConsoleHostAssemblyName = NULL; - - bool isDeletewszMonadVersionNeeded = false; - - unsigned int exitCode = EXIT_CODE_SUCCESS; - - // Windows OS Bug: 1979038 - // Change the thread user interface to a language that the - // windows console can display. This is important as starting - // from windows vista and later, the OS support thread user - // interface language separate from thread locale. - // Setting this will enable OS resource loader to load correct - // resource that can display properly in a console window. - // Note: If the language identifier is 0, the function always - // succeeds. - SetThreadUILanguage(0); - - if (IsOSLWin7OrLater()) - { - // populate jumplist (which is supported in w7 or later) - #if (WINVER >= _WIN32_WINNT_WIN7) - STARTUPINFO startupInfo; - GetStartupInfo(&startupInfo); - - // Only populate the jumplist if we are creating a new window, otherwise it's unnecessary - // because there is no taskbar item to update, or it has been done already. - if ((startupInfo.dwFlags & STARTF_USESHOWWINDOW) && (startupInfo.wShowWindow != SW_HIDE)) - { - CreateCustomDestinationList(startupInfo); - } - #endif - } - - do - { - // The default powershell version is 3 so that the exe will - // load the registry key HKLM\Software\Microsoft\PowerShell\3\PowerShellEngine - int monadMajorVersion = -1; - int monadMinorVersion = -1; - int monadVersionIndex = -1; - int runtimeVersionIndex = -1; - int consoleFileIndex = -1; - int profileIndex = -1; - const float win8DefaultMonadMajorVersion = 3.0; - - exitCode = ParseCommandLineArguments( - argc, - argv, - &wszMonadVersion, - &monadMajorVersion, - &monadMinorVersion, - &monadVersionIndex, - &wszRuntimeVersion, - &runtimeVersionIndex, - &wszConsoleFile, - &consoleFileIndex, - &profileIndex); - if (EXIT_CODE_SUCCESS != exitCode) - { - break; - } - - // WinPE supports only PowerShell >=3.0. - // If the PowerShell host is a WinPE machine & if the requested - // PowerShell version is not 3.0, then display an not supported monad version error message. - if(IsWinPEHost() && (monadMajorVersion == 1 || monadMajorVersion == 2)) - { - exitCode = g_NOTSUPPORTED_MONAD_VERSION; - pwrshExeOutput->DisplayMessage(false, g_NOTSUPPORTED_MONAD_VERSION, monadMajorVersion, win8DefaultMonadMajorVersion); - break; - } - - // This is for remembering which major version is requested from command line. - // GetRegistryInfo call after this will change monadMajorVersion to be PowerShell - // major version installed (based on registry). - // int requestedMonadMajorVersion = monadMajorVersion; - - // For GetRegistryInfo call, monadMajorVersion is used to calculate the version key in registry. - // For PowerShell V2, version key in registry is 1. - if (monadMajorVersion == 2) - { - monadMajorVersion = 1; - } - else if ((monadMajorVersion == 4) || (monadMajorVersion == 5)) - { - // For PowerShell 4.0 and 5.0 the registry is the same as 3.0. - monadMajorVersion = 3; - } - // if monadVersionIndex is set by ParseCommandLineArguments, - // wszMonadVersion is pointing to argv[monadVersionIndex] and - // no need to delete it. - isDeletewszMonadVersionNeeded = monadVersionIndex == -1; - exitCode = pwrshCommon.GetRegistryInfo( - &wszMonadVersion, - &monadMajorVersion, - monadMinorVersion, - &wszDefaultRuntimeVersion, - &wszConsoleHostAssemblyName); - if (EXIT_CODE_SUCCESS != exitCode) - { - break; - } - - bool skipProfile = profileIndex != -1; - - // skipIndex holds the position of the last parameter that needs to be handled by the native layer. - // In other words, skipIndex + 1 will give the position of the first parameter that needs to be passed to managed layer. - // Find the last native parameter, and chomp everything up until it. - // We don't do this for NoProfile. We parse it once here and then parse it again in the managed layer. - int skipIndex = -1; - - if(monadVersionIndex > skipIndex) { skipIndex = monadVersionIndex; } - if(consoleFileIndex > skipIndex) { skipIndex = consoleFileIndex; } - if(runtimeVersionIndex > skipIndex) { skipIndex = runtimeVersionIndex; } - - skipIndex = skipIndex + 1; - - // WTR - Check for the key that indicates absence of NetFx4 and output appropriate message to the user - - // Open PowerShellEngine Registry Key - // For GetRegistryInfo call, monadMajorVersion is used to calculate the version key in registry. - // For PowerShell V2, version key in registry is 1. - int useMonadMajorVersion = -1; - if (monadMajorVersion == 2) - { - useMonadMajorVersion = 1; - } - else - { - useMonadMajorVersion = 3; - } - - // If runtimeVersion is not supplied, validate that the defaultRuntimeVersion is installed. - // We can't do runtimeVersion validation on the user input, as this frequently changes per - // release of the .NET Framework. - if(NULL == wszRuntimeVersion) - { - wszRuntimeVersion = wszDefaultRuntimeVersion; - wszDefaultRuntimeVersion = NULL; - } - else - { - // Display the warning that they're using a version of the runtime that PowerShell is - // not tested with. - pwrshExeOutput->DisplayMessage(false, g_NONSTANDARD_CLR_VERSION, wszRuntimeVersion); - } - - // On downlevel setups, verify that the CLR was present when PowerShell was installed. - // If it wasn't, then PowerShell is in a bad state and needs to be installed after the - // CLR. - exitCode = ValidateDownlevelSetupHadClrWhenInstalled( - wszMonadVersion, - monadMajorVersion, - wszRuntimeVersion, - useMonadMajorVersion); - if (EXIT_CODE_SUCCESS != exitCode) - { - break; - } - - exitCode = LaunchManagedMonad( - wszMonadVersion, - monadMajorVersion, - wszConsoleFile, - wszRuntimeVersion, - wszConsoleHostAssemblyName, - pArgvSA, - skipIndex, - argc, - argv); - if (EXIT_CODE_SUCCESS != exitCode) - { - break; - } - } - while (false); - - if (NULL != pArgvSA) - { - SafeArrayDestroy(pArgvSA); - pArgvSA = NULL; - } - - if (NULL != wszDefaultRuntimeVersion) - { - delete [] wszDefaultRuntimeVersion; - wszDefaultRuntimeVersion = NULL; - } - - if (NULL != wszConsoleHostAssemblyName) - { - delete [] wszConsoleHostAssemblyName; - wszConsoleHostAssemblyName = NULL; - } - - if (isDeletewszMonadVersionNeeded) - { - delete [] wszMonadVersion; - wszMonadVersion = NULL; - } - - if (g_hResInstance) - { - FreeMUILibrary(g_hResInstance); - } - - return exitCode; -} diff --git a/src/powershell-native/nativemsh/pwrshexe/Monad.ico b/src/powershell-native/nativemsh/pwrshexe/Monad.ico deleted file mode 100644 index b3285f96784..00000000000 Binary files a/src/powershell-native/nativemsh/pwrshexe/Monad.ico and /dev/null differ diff --git a/src/powershell-native/nativemsh/pwrshexe/MshResources.rc b/src/powershell-native/nativemsh/pwrshexe/MshResources.rc deleted file mode 100644 index ec1afc43daa..00000000000 --- a/src/powershell-native/nativemsh/pwrshexe/MshResources.rc +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// resource script for msh.exe -// - -#include - -#define MANIFEST_RESOURCE_ID 1 - -MANIFEST_RESOURCE_ID RT_MANIFEST "powershell.exe.manifest" -MSH_MAIN ICON "monad.ico" -MSH_SECURITY ICON "powershell_securitybadge.ico" - -STRINGTABLE DISCARDABLE -BEGIN - - // Elements of our jump list, and file descriptions, and LNK - // descriptions - 101 "Windows PowerShell ISE" - 102 "Windows PowerShell ISE (x86)" - 103 "Windows PowerShell Script" - 104 "Windows PowerShell Data File" - 105 "Windows PowerShell XML Document" - 106 "Windows PowerShell Script Module" - 107 "Windows PowerShell Console File" - 108 "Run with PowerShell" - 109 "Windows PowerShell" - 110 "Windows PowerShell (x86)" - 111 "Performs object-based (command-line) functions" - 112 "Run as 32" - 113 "Windows PowerShell Integrated Scripting Environment. Performs object-based (command-line) functions" - 118 "Run as Administrator" - 119 "Runs with administrator privileges" - 120 "Windows PowerShell Cmdlet Definition XML Document" - 121 "Windows PowerShell Session Configuration File" - 122 "Run ISE as Administrator" - 123 "Runs ISE with administrator privileges" - - // Misc resources - - // Friendly name for our OID mapping - 124 "Document Encryption" -END - -#include "nativemsh.rc" -#include "version.rc" diff --git a/src/powershell-native/nativemsh/pwrshexe/NativeMsh.mc b/src/powershell-native/nativemsh/pwrshexe/NativeMsh.mc deleted file mode 100644 index 63f9ba41ffb..00000000000 --- a/src/powershell-native/nativemsh/pwrshexe/NativeMsh.mc +++ /dev/null @@ -1,235 +0,0 @@ -;// Copyright (c) Microsoft Corporation. All rights reserved. - -MessageId=1 -SymbolicName=MISSING_COMMAND_LINE_ARGUMENT -Language=English -Missing argument for parameter %1!ls!. -. - -MessageId=2 -SymbolicName=INVALID_CONSOLE_FILE_PATH -Language=English -Windows PowerShell console file path "%1!ls!" is invalid. -. - -MessageId=3 -SymbolicName=CLR_VERSION_NOT_INSTALLED -Language=English -Version %1!ls! of the .NET Framework is not installed and it is required to run version %2!ls! of Windows PowerShell. -. - -MessageId=4 -SymbolicName=CORBINDTORUNTIME_FAILED -Language=English -CLR initialization failed with error %1!lx!. -. - -MessageId=5 -SymbolicName=STARTING_CLR_FAILED -Language=English -Starting the CLR failed with HRESULT %1!lx!. -. - -MessageId=6 -SymbolicName=GETTING_DEFAULT_DOMAIN_FAILED -Language=English -Internal Windows PowerShell error. Default CLR domain initialization failed with error %1!lx!. -. - -MessageId=7 -SymbolicName=CREATING_MSH_ENTRANCE_FAILED -Language=English -Internal Windows PowerShell error. Loading managed Windows PowerShell failed with error %1!lx!. -. - -MessageId=8 -SymbolicName=GETTING_DISPATCH_ID_FAILED -Language=English -Internal Windows PowerShell error. Retrieving Dispatch ID for managed Windows PowerShell entrance method failed with error %1!lx!. -. - -MessageId=9 -SymbolicName=INOVKING_MSH_ENTRANCE_FAILED -Language=English -Internal Windows PowerShell error. Invoking managed Windows PowerShell failed with error %1!lx!. -. - -MessageId=10 -SymbolicName=MANAGED_MSH_EXCEPTION -Language=English -Windows PowerShell terminated with the following error: %n %1!ls! -. - -MessageId=11 -SymbolicName=READ_XML_COM_INIT_FAILED -Language=English -Internal Windows PowerShell error. COM initialization failed while reading Windows PowerShell console file with error %1!lx!. -. - -MessageId=12 -SymbolicName=READ_XML_CREATE_DOMDOCUMENT_FAILED -Language=English -Internal Windows PowerShell error. DOMDocument creation for Windows PowerShell console file failed with error %1!lx!. -. - -MessageId=13 -SymbolicName=READ_XML_LOAD_FILE_FAILED -Language=English -Failed to load Windows PowerShell console file "%1!ls!". -. - -MessageId=14 -SymbolicName=EMPTY_REG_SZ_VALUE -Language=English -The value of the registry key %1!ls!\%2!ls! cannot be empty. -. - -MessageId=15 -SymbolicName=READ_XML_GET_CONSOLE_SCHEMA_VERSION_FAILED -Language=English -Cannot locate the required element ConsoleSchemaVersion in the Windows PowerShell console file "%1!ls!". -. - -MessageId=16 -SymbolicName=READ_XML_INVALID_CONSOLE_SCHEMA_VERSION -Language=English -A required element ConsoleSchemaVersion in Windows PowerShell console file "%1!ls!" is invalid. -. - -MessageId=17 -SymbolicName=INVALID_MONAD_VERSION -Language=English -"%1!ls!" is not a valid Windows PowerShell version. Specify a valid Windows PowerShell version of the format major.minor version. -. - -MessageId=18 -SymbolicName=READ_XML_GET_MONAD_VERSION_TEXT_FAILED -Language=English -Cannot read the Windows PowerShell version from Windows PowerShell console file "%1!ls!". -. - -MessageId=19 -SymbolicName=SEARCH_LATEST_REG_KEY_FAILED_WITH -Language=English -Encountered a problem reading the registry. Cannot read registry key %1!ls!. System error:%n %2!ls!. -. - -MessageId=20 -SymbolicName=OPEN_REG_KEY_FAILED_WITH -Language=English -Encountered a problem reading the registry. Cannot open registry key %1!ls!. System error:%n %2!ls!. -. - -MessageId=21 -SymbolicName=CLOSE_REG_KEY_FAILED_WITH -Language=English -Closing registry key %1!ls! causes the following Win32 error:%n %2!ls! -. - -MessageId=22 -SymbolicName=READ_REG_VALUE_FAILED_WITH -Language=English -Reading the value of registry key %1!ls!\%2!ls! causes the following Win32 error:%n %3!ls! -. - -MessageId=23 -SymbolicName=CREATE_MSHENGINE_REG_KEY_PATH_FAILED_WITH -Language=English -Encountered a problem creating the registry key path PowerShellEngine. System error:%n %1!ls!. -. - -MessageId=24 -SymbolicName=EXPECT_REG_SZ_VALUE -Language=English -Invalid registry key value. Value for registry key %1!ls!\%2!ls! must be REG_SZ. -. - -MessageId=25 -SymbolicName=MSH_VERSION_NOT_INSTALLED -Language=English -Cannot start Windows PowerShell version %1!ls! because it is not installed. -. - -MessageId=26 -SymbolicName=INCORRECT_CONSOLE_FILE_EXTENSION -Language=English -Windows PowerShell console file "%1!ls!" extension is not psc1. Windows PowerShell console file extension must be psc1. -. - -MessageId=27 -SymbolicName=INVALID_REG_MSHVERSION_VALUE -Language=English -The value of registry key %1!ls!\%2!ls! is an invalid .NET version. Valid version format is major.minor.build.revision. -. - -MessageId=28 -SymbolicName=INCOMPATIBLE_MINOR_VERSION -Language=English -Cannot start Windows PowerShell. No version of Windows PowerShell compatible to %1!ls! is installed. -. - -MessageId=29 -SymbolicName=NO_COMPLETELY_INSTALLED_FOUND_VERSION -Language=English -Cannot start Windows PowerShell. No correctly installed versions of Windows PowerShell found. -. - -MessageId=30 -SymbolicName=MISSING_REG_KEY -Language=English -Encountered a problem reading the registry. Cannot find registry key %1!ls!. -. - -MessageId=31 -SymbolicName=READ_XML_LOAD_FILE_FAILED_WITH_SPECIFIC_ERROR -Language=English -Failed to load Windows PowerShell console file "%1!ls!". WIN 32 error: %2!ls! -. - -MessageId=32 -SymbolicName=READ_XML_LOAD_FILE_FAILED_WITH_SPECIFIC_POSITION_ERROR -Language=English -Failed to load Windows PowerShell console file "%1!ls!": %2!ls!At line:%3!li! char:%4!li! -. - -MessageId=33 -SymbolicName=READ_XML_GET_EMPTY_MONAD_VERSION_TEXT -Language=English -Windows PowerShell version in the Windows PowerShell console file "%1!ls!" cannot be empty. -. - -MessageId=34 -SymbolicName=READ_XML_GET_PSCONSOLEFILE_FAILED -Language=English -Cannot locate the required element PSConsoleFile in the Windows PowerShell console file "%1!ls!". -. - -MessageId=35 -SymbolicName=NOTSUPPORTED_MONAD_VERSION -Language=English -The requested Windows PowerShell version %1!d! is not supported on WinPE. WinPE supports only Windows PowerShell %1!d!. -. - -MessageId=36 -SymbolicName=NONSTANDARD_CLR_VERSION -Language=English -Warning: Windows PowerShell was started with CLR version "%1!ls!". This CLR version has not been tested with Windows PowerShell and might not operate properly. For more information about supported versions of the CLR, see http://go.microsoft.com/fwlink/?LinkId=215538.%r%n -. - -MessageId=37 -SymbolicName=SHELLBANNER1 -Language=English -Windows PowerShell -. - -MessageId=38 -SymbolicName=SHELLBANNER2 -Language=English -Copyright (c) Microsoft Corporation. All rights reserved. -. - -MessageId=39 -SymbolicName=MISSING_REG_KEY1 -Language=English -Encountered a problem reading the registry. Cannot find registry key %1!ls!. The Windows PowerShell %2!ls! engine is not installed on this computer. -. diff --git a/src/powershell-native/nativemsh/pwrshexe/OutputWriter.h b/src/powershell-native/nativemsh/pwrshexe/OutputWriter.h deleted file mode 100644 index 7f6de26f54e..00000000000 --- a/src/powershell-native/nativemsh/pwrshexe/OutputWriter.h +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include "NativeMsh.h" - -HINSTANCE g_hResInstance = 0; -LPCWSTR g_MAIN_BINARY_NAME = L"powershell.exe"; - -// Copied from JSchwart -DWORD FileType( - IN HANDLE fp) -{ - DWORD htype = GetFileType(fp); - htype &= ~FILE_TYPE_REMOTE; - return htype; -} - -// Copied from dnsrv\admin\dscmd>parser\varg.cpp -void MyWriteConsole( - HANDLE fp, - __in_ecount(cchBuffer) LPCWCH lpBuffer, - DWORD cchBuffer - ) -{ - - if (!lpBuffer || !cchBuffer) - { - assert(false); - return; - } - // - // Jump through hoops for output because: - // - // 1. printf() family chokes on international output (stops - // printing when it hits an unrecognized character) - // - // 2. WriteConsole() works great on international output but - // fails if the handle has been redirected (i.e., when the - // output is piped to a file) - // - // 3. WriteFile() works great when output is piped to a file - // but only knows about bytes, so Unicode characters are - // printed as two Ansi characters. - // - DWORD cchBufferWritten = 0; - if (FILE_TYPE_CHAR == FileType(fp)) - { - WriteConsole(fp, lpBuffer, cchBuffer, &cchBufferWritten, NULL); - } - else - { - //Buffer bounds are passed correctly. - WriteFile(fp, lpBuffer, cchBuffer*sizeof(WCHAR), &cchBufferWritten, NULL); - } -} - -// Copied from dnsrv\admin\dscmd>parser\varg.cpp -void WriteStandard( - bool bUseStdOut, - __in_ecount(cchBuffer) LPCWCH lpMessage, - DWORD cchBuffer) -{ - static HANDLE handle = - GetStdHandle(bUseStdOut ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE); - - // - // Verify parameters - // - if (!lpMessage) - { - return; - } - - // - // Output the results - // - MyWriteConsole(handle, - lpMessage, - cchBuffer); -} - -/********************************************************************++ -Copyright (c) Microsoft Corporation. All rights reserved. ---********************************************************************/ - -class PwrshExeOutput : public NativeMsh::IPwrshCommonOutput -{ -public: - virtual ~PwrshExeOutput() {} - - virtual VOID DisplayMessage( - bool bUseStdOut, - DWORD dwMessageId, - ...) - { - LPWSTR messageDisplayString = NULL; - DWORD dwLength = 0; - - va_list args; - va_start(args, dwMessageId); - /* - HMODULE LoadMUILibrary(LPCTSTR lpFileName, DWORD dwFlags, LANGID LangID) - - This function loads and returns the MUI resource module (e.g. foo.dll.mui) of a main binary module (e.g. foo.dll). Developers should call this function to obtain a MUI resource module handle and use the returned handle for the purpose of resource access ONLY. - - The APIs behaves slightly different on different OS: - - For W2K, XP and WS03 systems: when the caller doesn?t pass any LangID, the MUI module is searched in this order: - - 1. This function will look for the MUI module in the folder with the folder name that matches the current user's UI language. - 2. If it doesn't find any folder for that language or the file is not in the folder, it will look for the MUI module in a folder named in the language of the OS (if the OS language is different that the user's language). - 3. If the folder or the file does not exist, it will try to load the MUI module installed in the English folder (en-US). - 4. If the English (en-US) MUI module does not exist either, the function will try to load the MUI module located in the same folder as the main binary. - 5. If everything fails, the function will then load the main module and return a handle to it. - - If the caller specifies a LangID, the API will try to load the mui module for that language and if the mui files doesn?t exist the API will return an error (the same one returned by the LoadLibrary() call) - - For win9x/nt4 systems: when the caller doesn?t pass a LangID, the MUI module search order is the same that above but step (1) is not searched since that setting does not exist on those operating systems. - - The API behaves the same way than in W2K, XP and WS03 when the caller specifies a LangID. - - For Longhorn systems: regardless if the caller pass a LangID or not, the function does not do anything and will let the Longhorn resource loader handle the redirection to locate the correct MUI module for loading. - - - Parameters - - lpFileName - [in] Pointer to a null-terminated string that names the executable module (either a .dll or an .exe file) whose MUI resource module (.mui file) is to be loaded. The name specified is the file name of the executable module. - - dwFlags - [in] The flag value determines the convention that the function uses to search for MUI files on down-level systems ONLY. The flag has no effect on Longhorn system. Please also refer to the MUI File installation section for more details on the location of the MUI files. dwFlags can take on the following mutually exclusive values: - - MUI_LANGUAGE_ID: The function will search for MUI files using the LCID language convention (e.g. 0411) - MUI_LANGUAGE_NAME: (default) The function will search for MUI files using the ISO language name convention (e.g. ja-JP) - - LangID ? [in] specifies the language of the resources the caller wants to load. - - Note: the dwFlags and LangID are only use when the component is running on down-level systems. They don?t have any effect on Longhorn systems. - - In Down-level and Longhorn system you can use MLANG function RFC1766ToLCID() and LCIDToRFC1766() to map between language name and LCIDs. - - */ - - do - { - // if we had unlocalizable resources, we would have to try to load the resource from - // the language-neutral module handle - if (g_hResInstance == 0) - { -#ifdef CORECLR - g_hResInstance = LoadLibraryEx(g_MAIN_BINARY_NAME, 0, LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_IMAGE_RESOURCE); -#else - g_hResInstance = LoadMUILibraryW(g_MAIN_BINARY_NAME, MUI_LANGUAGE_NAME, 0); -#endif - } - - //string function - dwLength = FormatMessageW( - FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_ALLOCATE_BUFFER, - g_hResInstance, - dwMessageId, - 0, - (LPWSTR)&messageDisplayString, - 0, - &args); - - if (dwLength != 0) - { - WriteStandard(bUseStdOut, messageDisplayString, dwLength); - LocalFree(messageDisplayString); - } - } while (false); - va_end(args); - } - - virtual void DisplayErrorWithSystemError( - LONG lSystemErrorCode, - int messageId, - LPCWSTR insertionParam) - { - wchar_t * wszSystemErrorMessage = NULL; - DWORD dwLength = NativeMsh::PwrshCommon::GetSystemErrorMessage( - lSystemErrorCode, - &wszSystemErrorMessage); - - if (dwLength > 0) - { - this->DisplayMessage(false, messageId, insertionParam, wszSystemErrorMessage); - if (wszSystemErrorMessage != NULL) - { - delete[] wszSystemErrorMessage; - wszSystemErrorMessage = NULL; - } - } - } -}; diff --git a/src/powershell-native/nativemsh/pwrshexe/PowerShell.exe.manifest b/src/powershell-native/nativemsh/pwrshexe/PowerShell.exe.manifest deleted file mode 100644 index 782c9bfaab7..00000000000 --- a/src/powershell-native/nativemsh/pwrshexe/PowerShell.exe.manifest +++ /dev/null @@ -1,36 +0,0 @@ - - - PowerShell - - - - - - - - - - - - - - - - - - - - - - - - true - - - diff --git a/src/powershell-native/nativemsh/pwrshexe/PowerShell_securitybadge.ico b/src/powershell-native/nativemsh/pwrshexe/PowerShell_securitybadge.ico deleted file mode 100644 index 0aa11972d82..00000000000 Binary files a/src/powershell-native/nativemsh/pwrshexe/PowerShell_securitybadge.ico and /dev/null differ diff --git a/src/powershell-native/nativemsh/pwrshexe/version.rc b/src/powershell-native/nativemsh/pwrshexe/version.rc deleted file mode 100644 index 796fc8c0390..00000000000 --- a/src/powershell-native/nativemsh/pwrshexe/version.rc +++ /dev/null @@ -1,13 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -#include -#include - -#define VER_FILETYPE VFT_APP -#define VER_FILESUBTYPE VFT2_UNKNOWN -#define VER_FILEDESCRIPTION_STR "Windows PowerShell" -#define VER_INTERNALNAME_STR "POWERSHELL" -#define VER_ORIGINALFILENAME_STR "PowerShell.EXE" - -#include diff --git a/src/powershell-native/nativemsh/pwrshplugin/CMakeLists.txt b/src/powershell-native/nativemsh/pwrshplugin/CMakeLists.txt deleted file mode 100644 index 2090d7de2b2..00000000000 --- a/src/powershell-native/nativemsh/pwrshplugin/CMakeLists.txt +++ /dev/null @@ -1,41 +0,0 @@ -# -# Builds pwrshplugin.dll, the WinRM plugin for PowerShell remote hosting. -# -add_library(pwrshplugin SHARED - entrypoints.cpp - pwrshclrhost.cpp - pwrshpluginerrorcodes.mc - #pwrshpluginerrorcodes.rc - pwrshpluginResources.rc - pwrshplugin.def - ) - -if (BUILD_ONECORE) - # Libraries to use when creating this binary for Windows on OneCore-based SKUs - set(PWRSHPLUGIN_WINDOWS_LIBS - ${STATIC_MT_CRT_LIB} - ${STATIC_MT_VCRT_LIB} - kernel32.lib - advapi32.lib - ole32.lib - wsmsvc.lib - ) - set_target_properties(pwrshplugin PROPERTIES COMPILE_DEFINITIONS "CORECLR") -else () - # Libraries to use when creating this binary for Windows on full SKUs - set(PWRSHPLUGIN_WINDOWS_LIBS - MUILoad.lib - mscoree.lib - wsmsvc.lib - # CoreCLR lib - ${STATIC_MT_CRT_LIB} - ${STATIC_MT_VCRT_LIB} - legacy_stdio_definitions.lib # Resolves: LNK2019: unresolved external symbol _vsnwprintf - ) - set(pwrshplugin_definitions ${common_pwrsh_definitions}) -endif (BUILD_ONECORE) - -target_link_libraries(pwrshplugin - ${PWRSHPLUGIN_WINDOWS_LIBS}) - -target_link_libraries(pwrshplugin pwrshcommon) diff --git a/src/powershell-native/nativemsh/pwrshplugin/entrypoints.cpp b/src/powershell-native/nativemsh/pwrshplugin/entrypoints.cpp deleted file mode 100644 index a55de1645c1..00000000000 --- a/src/powershell-native/nativemsh/pwrshplugin/entrypoints.cpp +++ /dev/null @@ -1,776 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// ---------------------------------------------------------------------- -// -// Contents: Entry points for PowerShell plugin used to host powershell -// in a WSMan service. -// ---------------------------------------------------------------------- - -#include "pwrshplugin.h" -// [Porting note] SQM is for Telemetry in Windows. Temporarily disabled. -//#include -//#include "common/WindowsSqmDataID.h" -//#include "common/winrmsqm.h" - -#if !CORECLR -#include -#endif - -HINSTANCE g_hResourceInstance = 0; // TODO: Where is this freed? FreeMUILibrary for nonCoreClr and FreeLibrary for CoreCLR -LPCWSTR g_MAIN_BINARY_NAME = L"pwrshplugin.dll"; - -// [Porting note] SQM is for Telemetry in Windows. Temporarily disabled. -// typedef VOID (NTAPI *PFN_WinSqmSetDWORD)( -// __in_opt HSESSION hSession, -// __in DWORD dwDatapointId, -// __in DWORD dwDatapointValue -// ); - -// gets the error message from the resources section of the current module. -// the caller should free pwszErrorMessage using LocalFree(). -// returns: If the function succeeds the return value is the number of CHARs stored int the output -// buffer, excluding the terminating null character. If the function fails the return value is zero. -_Success_(return > 0) -DWORD GetFormattedErrorMessage(__out PWSTR * pwszErrorMessage, DWORD dwMessageId, va_list* arguments) -{ - DWORD dwLength = 0; - LPWSTR wszSystemErrorMessage = NULL; - - do - { - if (NULL == pwszErrorMessage) - { - break; - } - *pwszErrorMessage = NULL; - - if (NULL == g_hResourceInstance) - { -#ifdef CORECLR - g_hResourceInstance = LoadLibraryEx(g_MAIN_BINARY_NAME, 0, LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_IMAGE_RESOURCE); -#else - g_hResourceInstance = LoadMUILibraryW(g_MAIN_BINARY_NAME, MUI_LANGUAGE_NAME, 0); -#endif - } - - dwLength = FormatMessageW( - FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_ALLOCATE_BUFFER, - g_hResourceInstance, - dwMessageId, - 0, - (LPWSTR)&wszSystemErrorMessage, - 0, - arguments); - - if (dwLength == 0) - { - break; - } - - *pwszErrorMessage = new WCHAR[dwLength + 1]; - if (*pwszErrorMessage == NULL) - { - dwLength = 0; - break; - } - - if (FAILED(StringCchCopyW(*pwszErrorMessage, dwLength + 1, wszSystemErrorMessage))) - { - dwLength = 0; - delete [] (*pwszErrorMessage); - *pwszErrorMessage = NULL; - } - - }while(false); - - if (NULL != wszSystemErrorMessage) - { - LocalFree(wszSystemErrorMessage); - } - - return dwLength; -} - -DWORD GetFormattedErrorMessage(__out PWSTR * pwszErrorMessage, DWORD dwMessageId, ...) -{ - DWORD result = 0; - - va_list args; - va_start(args, dwMessageId); - - result = GetFormattedErrorMessage(pwszErrorMessage, dwMessageId, &args); - - va_end(args); - - return result; -} - -#pragma prefast(push) -#pragma prefast (disable: 6101) -#pragma prefast (disable: 6054) - -unsigned int ConstructPowerShellVersion(int iPSMajorVersion, - int iPSMinorVersion, - __deref_out_opt PWSTR *pwszMonadVersion) -{ - unsigned int exitCode = EXIT_CODE_SUCCESS; - wchar_t* wszMajorVersion = new wchar_t[10]; - wchar_t* wszMinorVersion = new wchar_t[10]; - - do - { - if ((NULL == pwszMonadVersion) || ( 0 > iPSMajorVersion) || (0 > iPSMinorVersion)) - { - exitCode = EXIT_CODE_BAD_INPUT; - break; - } - - if (0 != _itow_s(iPSMajorVersion, wszMajorVersion, 10, 10)) - { - exitCode = EXIT_CODE_BAD_INPUT; - break; - } - - if (0 != _itow_s(iPSMinorVersion, wszMinorVersion, 10, 10)) - { - exitCode = EXIT_CODE_BAD_INPUT; - break; - } - - size_t iMajorLength; - size_t iMinorLength; - - if (SUCCEEDED(StringCchLength(wszMajorVersion, 10, &iMajorLength)) && - SUCCEEDED(StringCchLength(wszMinorVersion, 10, &iMinorLength))) - { - size_t totalLength = iMajorLength + iMinorLength + 2; - *pwszMonadVersion = new wchar_t[totalLength]; - if (NULL == *pwszMonadVersion) - { - exitCode = ERROR_NOT_ENOUGH_MEMORY; - break; - } - - *pwszMonadVersion[0] = L'\0'; - if (SUCCEEDED(StringCchCopyW(*pwszMonadVersion, totalLength, wszMajorVersion)) && - SUCCEEDED(StringCchCatW(*pwszMonadVersion, totalLength, L".")) && - SUCCEEDED(StringCchCatW(*pwszMonadVersion, totalLength, wszMinorVersion))) - { - break; - } - else - { - exitCode = EXIT_CODE_BAD_INPUT; - break; - } - } - else - { - exitCode = EXIT_CODE_BAD_INPUT; - break; - } - }while(false); - - if (NULL != wszMajorVersion) - { - delete[] wszMajorVersion; - } - - if (NULL != wszMinorVersion) - { - delete[] wszMinorVersion; - } - - return exitCode; -} - -#pragma prefast(pop) - -static PwrshCommon sPwrshCommon; - -// Gets the CLR Version for a given PowerShell Version. PowerShell Version is -// supplied with 2 parameters iPSMajorVersion (PowerShell major version) and -// iPSMinorVersion (PowerShell minor version). The CLR version is returned through -// pwszRuntimeVersion and pRuntimeVersionLength represents the size of pwszRuntimeVersion. -// returns: 0 on success, non-zero on failure. -_Success_(return == 0) //EXIT_CODE_SUCCESS -extern "C" -unsigned int GetCLRVersionForPSVersion(int iPSMajorVersion, - int iPSMinorVersion, - size_t runtimeVersionLength, - __inout_ecount_part(runtimeVersionLength, *pRuntimeVersionLength) wchar_t* pwszRuntimeVersion, - __out_ecount(1) size_t* pRuntimeVersionLength) -{ - unsigned int exitCode = EXIT_CODE_SUCCESS; - wchar_t * wszMonadVersion = NULL; - wchar_t* wszConsoleHostAssemblyName = NULL; - wchar_t* wszTempVersion = NULL; - size_t tempVersionLength = 0; - - if (NULL != pRuntimeVersionLength) - { - // Initialize the output size to zero prior to attempting the copy - *pRuntimeVersionLength = 0; - } - - do - { - int requestedMonadMajorVersion = iPSMajorVersion; - int requestedMonadMinorVersion = iPSMinorVersion; - - // For GetRegistryInfo call, monadMajorVersion is used to calculate the version key in registry. - // For PowerShell V2, version key in registry is 1. - if (2 == requestedMonadMajorVersion) - { - requestedMonadMajorVersion = 1; - } - - // For PowerShell 3, 4 and 5, the registry is 3. - if ((requestedMonadMajorVersion == 4) || (requestedMonadMajorVersion == 5)) - { - requestedMonadMajorVersion = 3; - } - - exitCode = ConstructPowerShellVersion(iPSMajorVersion, iPSMinorVersion, &wszMonadVersion); - if (EXIT_CODE_SUCCESS != exitCode) - { - break; - } - - exitCode = sPwrshCommon.GetRegistryInfo( - &wszMonadVersion, - &requestedMonadMajorVersion, - requestedMonadMinorVersion, - &wszTempVersion, - &wszConsoleHostAssemblyName); - - if (EXIT_CODE_SUCCESS != exitCode) - { - break; - } - - HRESULT hResult = StringCchLength(wszTempVersion, STRSAFE_MAX_CCH, &tempVersionLength); - - if (FAILED(hResult)) - { - exitCode = EXIT_CODE_READ_REGISTRY_FAILURE; - break; - } - - if (NULL != pwszRuntimeVersion) - { - // +1 for the '\0' - if (runtimeVersionLength < (tempVersionLength + 1)) - { - exitCode = EXIT_CODE_BAD_INPUT; - break; - } - - hResult = StringCchCopy(pwszRuntimeVersion, tempVersionLength + 1, wszTempVersion); - - if (FAILED(hResult)) - { - exitCode = EXIT_CODE_READ_REGISTRY_FAILURE; - break; - } - - if (NULL != pRuntimeVersionLength) - { - // OACR warning 26030: Postcondition violation that could result in overflow - // pRuntimeVersionLength should only be populated if the copy operation succeeded - // +1 for the '\0' - *pRuntimeVersionLength = tempVersionLength + 1; - } - } - }while(false); - - if (NULL != wszMonadVersion) - { - delete [] wszMonadVersion; - wszMonadVersion = NULL; - } - - if (NULL != wszTempVersion) - { - delete [] wszTempVersion; - wszTempVersion = NULL; - } - - if (NULL != wszConsoleHostAssemblyName) - { - delete [] wszConsoleHostAssemblyName; - wszConsoleHostAssemblyName = NULL; - } - - return exitCode; -} - -DWORD ReportOperationComplete(WSMAN_PLUGIN_REQUEST *requestDetails, DWORD errorCode) -{ - if (NULL == requestDetails) - { - // cannot report if requestDetails is NULL. - return EXIT_CODE_SUCCESS; - } - - DWORD result = EXIT_CODE_SUCCESS; - PWSTR pwszErrorMessage = NULL; - if (GetFormattedErrorMessage(&pwszErrorMessage, errorCode) == 0) - { - /* if an error message could not be loaded, generate a fallback - message to provide a level of diagnosability. - */ - WCHAR szFallbackMessageMessage[64] = L"\0"; - swprintf_s(szFallbackMessageMessage, _countof(szFallbackMessageMessage), L"ReportOperationComplete: %d", errorCode); - - result = WSManPluginOperationComplete(requestDetails, 0, errorCode, szFallbackMessageMessage); - } - else - { - result = WSManPluginOperationComplete(requestDetails, 0, errorCode, pwszErrorMessage); - delete[] pwszErrorMessage; - } - - return result; -} - -// ----------------------------------------------------------------------------- -// Each plug-in needs to support the Startup callback. A plug-in may be -// initialized more than once within the same process, but only once per -// applicationIdentification. -// ----------------------------------------------------------------------------- -extern "C" -DWORD WINAPI WSManPluginStartup( - __in DWORD flags, - __in PCWSTR applicationIdentification, - __in_opt PCWSTR extraInfo, - __out PVOID *pluginContext - ) -{ -// -#ifdef REMOTINGDEBUG - // This loop is added to assist debugging server. - // Attach a debugger to the server and set this variable to true - // from the debugger. - bool isDebuggerAttached = false; - do - { - Sleep(1); - }while(!isDebuggerAttached); -#endif - - PwrshPlugIn* result = NULL; - try - { - *pluginContext = NULL; - PwrshPlugInMediator* pluginMediator = PwrshPlugInMediator::GetPwrshPlugInMediator(extraInfo); - - PwrshPlugIn* result = pluginMediator->CreatePwrshPlugIn(applicationIdentification, extraInfo); - *pluginContext = (PVOID)result; - - // Using global SQM session - // WinSQMSetDWORD is not available on Vista - - // [Porting note] SQM is for Telemetry in Windows. Temporarily disabled. - // HMODULE hModule; - // PFN_WinSqmSetDWORD pfnWinSqmSetDWORD; - - // hModule = GetModuleHandleW(L"ntdll"); - // if (hModule) - // { - // pfnWinSqmSetDWORD = (PFN_WinSqmSetDWORD) GetProcAddress(hModule, "WinSqmSetDWORD"); - // if (pfnWinSqmSetDWORD) - // { - // pfnWinSqmSetDWORD( - // NULL, - // DATAID_WINRMREMOTEENABLED, - // WINRM_SQM_DATA_REMOTEENABLED - // ); - // } - // } - - return NO_ERROR; - } - catch(PlugInException* e) - { - DWORD errorId = g_CREATION_FAILED; - if (NULL != e) - { - errorId = e->dwMessageId; - delete e; - } - - if (NULL != result) - { - delete result; - } - - return errorId; - } -} - -// ------------------------------------------------------------------------------------ -//The WSManPluginShutdown method is called after all operations have been cancelled and -//right before the DLL is unloaded. The DLL entry point name must be WSManPluginShutdown. -//This method has an important purpose of making sure all plug-in threads are shut down -//before this method returns. If the plug-in only handles synchronous operations and all -//threads report a cancellation result before they return then this method does not have to -//do anything too complex other than plug-in cleanup. However for an asynchronous plug-in, -//any threads that are used to process the plug-in threads, including the ones that just reported -//the cancellation for all operations need to completely shutdown. Not doing this will cause -//potential crashes in the DLL because code may be executed after the DLL is unloaded. -// ------------------------------------------------------------------------------------ -// reason: If this is a system shutdown this will be WSMAN_PLUGIN_SHUTDOWN_SYSTEM. -// For WSMan service shutdown this will be WSMAN_PLUGIN_SHUTDOWN_SERVICE. For an IIS host -//shutdown this will be WSMAN_PLUGIN_SHUTDOWN_IISHOST. -extern "C" -DWORD WINAPI WSManPluginShutdown( - __in PVOID pluginContext, - __in DWORD flags, - __in DWORD reason - ) -{ - if (NULL == pluginContext) - { - return g_NULL_PLUGIN_CONTEXT; - } - - try - { - PwrshPlugInMediator* pluginMediator = PwrshPlugInMediator::GetPwrshPlugInMediator(NULL); - pluginMediator->Shutdown(flags, reason); - } - catch(PlugInException* e) - { - // ignore plugin exceptions during shutdown. - if (NULL != e) - { - delete e; - } - } - - // free resources occupied by this plugin.. - // WSMan frees shell/command resources before calling - // plugin shutdown. - PwrshPlugIn* plugIn = reinterpret_cast(pluginContext); - delete plugIn; - - return NO_ERROR; -} - -#ifndef WIN32_FROM_HRESULT -#define WIN32_FROM_HRESULT(hr) (HRESULT_FACILITY(hr) == FACILITY_WIN32 ? HRESULT_CODE(hr) : hr) -#endif - -// ----------------------------------------------------------------------------- -// A plug-in that supports the Shell operations needs to implement this callback -// to allow commands to be created and to allow data to be streamed into either -// a shell or command. The plug-in must call WSManPluginReportContext to -// report the shell context. Once the shell is completed or when it is closed -// via the operationClosed boolean value or operationClosedHandle in the -// requestDetails the plug-in needs to call WSManPluginOperationComplete. -// The shell is active until this time. -// ----------------------------------------------------------------------------- -extern "C" -VOID WINAPI WSManPluginShell( - __in PVOID pluginContext, - __in WSMAN_PLUGIN_REQUEST *requestDetails, - __in DWORD flags, - __in_opt WSMAN_SHELL_STARTUP_INFO *startupInfo, - __in_opt WSMAN_DATA *inboundShellInformation - ) -{ - PwrshPlugIn* plugIn = (NULL != pluginContext) ? (PwrshPlugIn*)pluginContext : NULL; - bool comInitialized = false; - - if (NULL == plugIn) - { - ReportOperationComplete(requestDetails, g_INVALID_PLUGIN_CONTEXT); - return; - } - - try - { - PwrshPlugInMediator* pluginMediator = PwrshPlugInMediator::GetPwrshPlugInMediator(NULL); - - HRESULT hr = CoInitializeEx(0,COINIT_MULTITHREADED); - if (hr == S_OK) - { - comInitialized = true; - } - else if (hr == S_FALSE) - { - CoUninitialize(); - comInitialized = false; - } - else if (hr == RPC_E_CHANGED_MODE) - { - comInitialized = false; //ignore - } - else - { - ReportOperationComplete(requestDetails, WIN32_FROM_HRESULT(hr)); - return; - } - - pluginMediator->CreateShell(plugIn, requestDetails, flags, startupInfo, inboundShellInformation); - - if (comInitialized) - { - CoUninitialize(); - comInitialized = false; - } - } - catch(PlugInException* e) - { - DWORD errorId = g_CREATION_FAILED; - if (NULL != e) - { - errorId = e->dwMessageId; - delete e; - } - - if (comInitialized) - { - CoUninitialize(); - comInitialized = false; - } - - ReportOperationComplete(requestDetails, errorId); - } -} - -// ----------------------------------------------------------------------------- -// WS-Man calls the WSMAN_PLUGIN_RELEASE_SHELL_CONTEXT entry point during shell -// shutdown when it is safe to delete the plug-in shell context. Any context -// reported through WSManPluginReportContext may not be deleted until the -// corresponding release function has been called. Failure to follow the contract -// will result in errors being generated. -// ----------------------------------------------------------------------------- -extern "C" -VOID WINAPI WSManPluginReleaseShellContext(__in PVOID shellContext) -{ - if ((NULL == shellContext)) - { - return; - } - - try - { - PwrshPlugInMediator* pluginMediator = PwrshPlugInMediator::GetPwrshPlugInMediator(NULL); - pluginMediator->ReleaseShell(shellContext); - } - catch(PlugInException* e) - { - // ignore plugin exceptions. - if (NULL != e) - { - delete e; - } - } -} - -// -// ----------------------------------------------------------------------------- -// A plug-in that supports the Shell operations and needs to create commands -// that are associated with the shell needs to implement this callback. -// The plug-in must call WSManPluginReportContext to -// report the command context. Once the command is completed or when it is closed -// via the operationClosed boolean value or operationClosedHandle in the -// requestDetails the plug-in needs to call WSManPluginOperationComplete. -// The command is active until this time. -// ----------------------------------------------------------------------------- -extern "C" -VOID WINAPI WSManPluginCommand( - __in WSMAN_PLUGIN_REQUEST *requestDetails, - __in DWORD flags, - __in PVOID shellContext, - __in PCWSTR commandLine, - __in_opt WSMAN_COMMAND_ARG_SET *arguments -) -{ - try - { - PwrshPlugInMediator* pluginMediator = PwrshPlugInMediator::GetPwrshPlugInMediator(NULL); - pluginMediator->CreateCommand(requestDetails, flags, shellContext, commandLine, arguments); - } - catch(PlugInException* e) - { - DWORD errorId = g_CREATION_FAILED; - if (NULL != e) - { - errorId = e->dwMessageId; - delete e; - } - - ReportOperationComplete(requestDetails, errorId); - } -} - -// --------------------------------------------------------------------------------- -// WS-Man calls the WSMAN_PLUGIN_RELEASE_COMMAND_CONTEXT entry point during command -// shutdown when it is safe to delete the plug-in shell context. Any context -// reported through WSManPluginReportContext may not be deleted until the -// corresponding release function has been called. Failure to follow the contract -// will result in errors being generated. -// --------------------------------------------------------------------------------- -extern "C" -VOID WINAPI WSManPluginReleaseCommandContext( - __in PVOID shellContext, - __in PVOID commandContext - ) -{ - if ((NULL == shellContext) || (NULL == commandContext)) - { - return; - } - - try - { - PwrshPlugInMediator* pluginMediator = PwrshPlugInMediator::GetPwrshPlugInMediator(NULL); - pluginMediator->ReleaseCommand(shellContext, commandContext); - } - catch(PlugInException* e) - { - // ignore plugin exceptions. - if (NULL != e) - { - delete e; - } - } -} - -// ----------------------------------------------------------------------------- -// A plug-in receives an inbound data stream to either the shell or command -// via this callback. Each piece of data causes the callback to be called once. -// For each piece of data the plug-in calls WSManPluginResultComplete to -// acknowledge receipt and to allow the next piece of data to be delivered. -// ----------------------------------------------------------------------------- -extern "C" -VOID WINAPI WSManPluginSend( - __in WSMAN_PLUGIN_REQUEST *requestDetails, - __in DWORD flags, - __in PVOID shellContext, - __in_opt PVOID commandContext, - __in PCWSTR stream, - __in WSMAN_DATA *inboundData - ) -{ - try - { - PwrshPlugInMediator* pluginMediator = PwrshPlugInMediator::GetPwrshPlugInMediator(NULL); - pluginMediator->SendOneItemToShellOrCommand(requestDetails, flags, shellContext, commandContext, stream, inboundData); - } - catch(PlugInException* e) - { - DWORD errorId = g_INVALID_PLUGIN_CONTEXT; - if (NULL != e) - { - errorId = e->dwMessageId; - delete e; - } - - ReportOperationComplete(requestDetails, errorId); - } -} - -// ----------------------------------------------------------------------------- -// A plug-in sends an outbound data stream from either the shell or command -// via this callback. This API is called when an inbound request from a client -// is received. This callback may be called against the shell and/or command -// based on the client request. Each piece of data that needs to be sent back -// to the client is done so through the WSManPluginReceiveResult API. Once -// all data has been send, when the stream is terminated via some internal means, -// or if the receive call is cancelled through the operationClosed boolean -// value or operationClosedHandle, the plug-in needs to call -// WSManPluginResultComplete. The operation is marked as active until this -// time. -// ----------------------------------------------------------------------------- -extern "C" -VOID WINAPI WSManPluginReceive( - __in WSMAN_PLUGIN_REQUEST *requestDetails, - __in DWORD flags, - __in PVOID shellContext, - __in_opt PVOID commandContext, - __in_opt WSMAN_STREAM_ID_SET *streamSet - ) -{ - try - { - PwrshPlugInMediator* pluginMediator = PwrshPlugInMediator::GetPwrshPlugInMediator(NULL); - pluginMediator->EnableShellOrCommandToSendDataToClient(requestDetails, flags, shellContext, commandContext, streamSet); - } - catch(PlugInException* e) - { - DWORD errorId = g_INVALID_PLUGIN_CONTEXT; - if (NULL != e) - { - errorId = e->dwMessageId; - delete e; - } - - ReportOperationComplete(requestDetails, errorId); - } -} - -// ----------------------------------------------------------------------------- -// A plug-in receives an inbound signal to either the shell or command -// via this callback. Each signal causes the callback to be called once. -// For each callthe plug-in calls WSManPluginResultComplete to -// acknowledge receipt and to allow the next signal to be received. -// A signal can cause the shell or command to be terminated, so the result -// of this callback may be many completion calls for the Signal, Receive, Command -// and Shell operations. -// ----------------------------------------------------------------------------- -extern "C" -VOID WINAPI WSManPluginSignal( - __in WSMAN_PLUGIN_REQUEST *requestDetails, - __in DWORD flags, - __in PVOID shellContext, - __in_opt PVOID commandContext, - __in PCWSTR code) -{ - try - { - PwrshPlugInMediator* pluginMediator = PwrshPlugInMediator::GetPwrshPlugInMediator(NULL); - pluginMediator->SignalShellOrCmd(requestDetails, flags, shellContext, commandContext, code); - } - catch(PlugInException* e) - { - DWORD errorId = g_INVALID_PLUGIN_CONTEXT; - if (NULL != e) - { - errorId = e->dwMessageId; - delete e; - } - - ReportOperationComplete(requestDetails, errorId); - } -} - -extern "C" -VOID WINAPI WSManPluginConnect( - __in WSMAN_PLUGIN_REQUEST *requestDetails, - __in DWORD flags, - __in PVOID shellContext, - __in_opt PVOID commandContext, - __in_opt WSMAN_DATA *inboundConnectInformation) -{ - try - { - PwrshPlugInMediator* pluginMediator = PwrshPlugInMediator::GetPwrshPlugInMediator(NULL); - pluginMediator->ExecuteConnectToShellOrCommand(requestDetails, flags, shellContext, commandContext, inboundConnectInformation); - } - catch(PlugInException* e) - { - DWORD errorId = g_INVALID_PLUGIN_CONTEXT; - if (NULL != e) - { - errorId = e->dwMessageId; - delete e; - } - - ReportOperationComplete(requestDetails, errorId); - } -} diff --git a/src/powershell-native/nativemsh/pwrshplugin/entrypoints.h b/src/powershell-native/nativemsh/pwrshplugin/entrypoints.h deleted file mode 100644 index 8bb3430c07e..00000000000 --- a/src/powershell-native/nativemsh/pwrshplugin/entrypoints.h +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// -// Contents: Headers used by pwrshplugin. -// pwrshplugin is totally unmanaged. -// ---------------------------------------------------------------------- - -#pragma once - -#include -#include -#include "pwrshpluginerrorcodes.h" - -const int EXIT_CODE_BAD_INPUT = 100; - -extern DWORD GetFormattedErrorMessage(__out PWSTR * pwszErrorMessage, DWORD dwMessageId, ...); -extern unsigned int ConstructPowerShellVersion(int iPSMajorVersion, int iPSMinorVersion, __deref_out_opt PWSTR *pwszMonadVersion); - diff --git a/src/powershell-native/nativemsh/pwrshplugin/pwrshclrhost.cpp b/src/powershell-native/nativemsh/pwrshplugin/pwrshclrhost.cpp deleted file mode 100644 index 8289ae858fa..00000000000 --- a/src/powershell-native/nativemsh/pwrshplugin/pwrshclrhost.cpp +++ /dev/null @@ -1,447 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// ---------------------------------------------------------------------- -// -// Contents: Source code for abstraction of CLR and worker differences between PowerShell versions. -// pwrshplugin is totally unmanaged. -// ---------------------------------------------------------------------- - -#pragma once - -#include "pwrshclrhost.h" -#include "NativeMsh.h" -#include "entrypoints.h" -#include "WinSystemCallFacade.h" - -#if !CORECLR - -// include the tlb for mscorlib for access to the default AppDomain through COM Interop -#import raw_interfaces_only high_property_prefixes("_get","_put","_putref")\ - rename("ReportEvent", "CLRReportEvent") - -using namespace mscorlib; - -#endif - -using namespace NativeMsh; - -// Init function calls are handled internally here within the context of the mediator singleton -typedef void (WINAPI *InitPluginFuncPtr)(); // Original PS init -typedef DWORD (WINAPI *InitPluginWkrPtrsFuncPtr)(__out PwrshPluginWkr_Ptrs* wkrPtrs); // Updated PS init - -#ifdef CORECLR - -unsigned int PowerShellCoreClrWorker::LaunchClr( - _In_ LPCWSTR wszMonadVersion, - _In_ LPCWSTR wszRuntimeVersion, - _In_ LPCSTR friendlyName) -{ - return commonLib->LaunchCoreCLR(hostWrapper, hostEnvironment, friendlyName); -} - -unsigned int PowerShellCoreClrWorker::LoadWorkerCallbackPtrs( - _In_ PwrshPluginWkr_Ptrs* workerCallbackPtrs, - _In_z_ wchar_t* wszMgdPlugInFileName, - _Outptr_result_maybenull_ PlugInException** pPluginException) -{ - - *pPluginException = NULL; - - // Call into powershell entry point - InitPluginWkrPtrsFuncPtr entryPointDelegate = NULL; - - // Create the function pointer for the managed entry point - // It must be targeted at a static method in the managed code. - HRESULT hr = hostWrapper->CreateDelegate( - "System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", - "System.Management.Automation.Remoting.WSManPluginManagedEntryWrapper", - "InitPlugin", - (void**)&entryPointDelegate); - - if (FAILED(hr)) - { - output->DisplayMessage(false, g_CREATING_MSH_ENTRANCE_FAILED, hr); - - return EXIT_CODE_INIT_FAILURE; - } - - // Passes empty pointer structure to the function, expects a filled struct if successful - return entryPointDelegate(workerCallbackPtrs); -} - -PowerShellCoreClrWorker::PowerShellCoreClrWorker() - : systemCalls(new WinSystemCallFacade()), - hostWrapper(new CoreClrHostingApiWrapper()), - output(new PwrshPluginOutputDefault()), - commonLib(new PwrshCommon()) -{ -} - -// -// sysCalls is expected to be new'd by the caller. -// It will be freed in PowerShellCoreClrWorker's destructor. -// -PowerShellCoreClrWorker::PowerShellCoreClrWorker( - SystemCallFacade* sysCalls, - ClrHostWrapper* hstWrp, - PwrshCommon* cmnLib) - : systemCalls(sysCalls), - hostWrapper(hstWrp), - output(new PwrshPluginOutputDefault()), - commonLib(cmnLib) -{ - if (NULL == systemCalls) - { - // Instantiate it even if one is not provided to guarantee that it will - // always be non-NULL during execution. - systemCalls = new WinSystemCallFacade(); - } - - if (NULL == hostWrapper) - { - // Instantiate it even if one is not provided to guarantee that it will - // always be non-NULL during execution. - hostWrapper = new CoreClrHostingApiWrapper(); - } - - if (NULL == commonLib) - { - commonLib = new PwrshCommon(new PwrshPluginOutputDefault(), new ConfigFileReader(), new WinSystemCallFacade()); - } -} - -PowerShellCoreClrWorker::~PowerShellCoreClrWorker() -{ - unsigned int exitCode = hostWrapper->CleanUpHostWrapper(); - if (EXIT_CODE_SUCCESS != exitCode) - { - output->DisplayMessage(false, exitCode); - } - - if (systemCalls) - { - delete systemCalls; - systemCalls = NULL; - } - - if (hostWrapper) - { - delete hostWrapper; - hostWrapper = NULL; - } - - if (output) - { - delete output; - output = NULL; - } - - if (commonLib) - { - delete commonLib; - commonLib = NULL; - } -} - -#else // !CORECLR - -PowerShellClrWorker::PowerShellClrWorker() : - pHost(NULL), - hManagedPluginModule(NULL), - systemCalls(new WinSystemCallFacade()), - g_INIT_PLUGIN("InitPlugin"), - g_SHUTDOWN_PLUGIN("ShutdownPlugin"), - g_MANAGED_PLUGIN_CREATE_SHELL("WSManPluginShell"), - g_MANAGED_PLUGIN_RELEASE_SHELL("WSManPluginReleaseShellContext"), - g_MANAGED_PLUGIN_CREATE_COMMAND("WSManPluginCommand"), - g_MANAGED_PLUGIN_RELEASE_COMMAND("WSManPluginReleaseCommandContext"), - g_MANAGED_PLUGIN_SEND("WSManPluginSend"), - g_MANAGED_PLUGIN_RECEIVE("WSManPluginReceive"), - g_MANAGED_PLUGIN_SIGNAL("WSManPluginSignal"), - g_MANAGED_PLUGIN_CONNECT("WSManPluginConnect"), - output(new PwrshPluginOutputDefault()) -{} - -PowerShellClrWorker::PowerShellClrWorker( - SystemCallFacade* sysCalls) - : pHost(NULL), - hManagedPluginModule(NULL), - systemCalls(sysCalls), - g_INIT_PLUGIN("InitPlugin"), - g_SHUTDOWN_PLUGIN("ShutdownPlugin"), - g_MANAGED_PLUGIN_CREATE_SHELL("WSManPluginShell"), - g_MANAGED_PLUGIN_RELEASE_SHELL("WSManPluginReleaseShellContext"), - g_MANAGED_PLUGIN_CREATE_COMMAND("WSManPluginCommand"), - g_MANAGED_PLUGIN_RELEASE_COMMAND("WSManPluginReleaseCommandContext"), - g_MANAGED_PLUGIN_SEND("WSManPluginSend"), - g_MANAGED_PLUGIN_RECEIVE("WSManPluginReceive"), - g_MANAGED_PLUGIN_SIGNAL("WSManPluginSignal"), - g_MANAGED_PLUGIN_CONNECT("WSManPluginConnect"), - output(new PwrshPluginOutputDefault()) -{ - if (NULL == systemCalls) - { - systemCalls = new WinSystemCallFacade(); - } -} - -PowerShellClrWorker::~PowerShellClrWorker() -{ - if (NULL != hManagedPluginModule) - { - FreeLibrary(hManagedPluginModule); - hManagedPluginModule = NULL; - } - - if (output) - { - delete output; - output = NULL; - } - - if (systemCalls) - { - delete systemCalls; - systemCalls = NULL; - } -} - -unsigned int PowerShellClrWorker::LaunchClr( - _In_ LPCWSTR wszMonadVersion, - _In_ LPCWSTR wszRuntimeVersion, - _In_ LPCSTR friendlyName) -{ - return commonLib.LaunchCLR(wszMonadVersion, wszRuntimeVersion, &pHost); -} - -unsigned int PowerShellClrWorker::LoadWorkerCallbackPtrs( - _In_ PwrshPluginWkr_Ptrs* workerCallbackPtrs, - _In_z_ wchar_t* wszMgdPlugInFileName, - _Outptr_result_maybenull_ PlugInException** pPluginException) -{ - *pPluginException = NULL; -#pragma prefast(push) -#pragma prefast (disable: 28752) - if (wszMgdPlugInFileName) - { - hManagedPluginModule = systemCalls->LoadLibraryExW(wszMgdPlugInFileName, NULL, 0); - } -#pragma prefast(pop) - - unsigned int exitCode = EXIT_CODE_SUCCESS; - - if (NULL == hManagedPluginModule) - { - // Get Extended error information.. to know why load failed. - PWSTR msg = NULL; - exitCode = g_MANAGED_PLUGIN_LOAD_FAILED; - commonLib.GetSystemErrorMessage(GetLastError(), &msg); - *pPluginException = new PlugInException(exitCode, msg); - return exitCode; - } - - // Now get the proc address for all the plugin API. - // Init is handled differently because it is not used in the updated - // worker module. - InitPluginFuncPtr hInitPluginMethodAddress = (InitPluginFuncPtr)systemCalls->GetProcAddress(hManagedPluginModule, g_INIT_PLUGIN); - - // This is not strictly necessary (they can be directly assigned), but I am doing this - // to keep all the code paths common - workerCallbackPtrs->shutdownPluginFuncPtr = (ShutdownPluginFuncPtr)systemCalls->GetProcAddress(hManagedPluginModule, g_SHUTDOWN_PLUGIN); - workerCallbackPtrs->wsManPluginShellFuncPtr = (WSManPluginShellFuncPtr)systemCalls->GetProcAddress(hManagedPluginModule, g_MANAGED_PLUGIN_CREATE_SHELL); - workerCallbackPtrs->wsManPluginReleaseShellContextFuncPtr = (WSManPluginReleaseShellContextFuncPtr)systemCalls->GetProcAddress(hManagedPluginModule, g_MANAGED_PLUGIN_RELEASE_SHELL); - workerCallbackPtrs->wsManPluginCommandFuncPtr = (WSManPluginCommandFuncPtr)systemCalls->GetProcAddress(hManagedPluginModule, g_MANAGED_PLUGIN_CREATE_COMMAND); - workerCallbackPtrs->wsManPluginReleaseCommandContextFuncPtr = (WSManPluginReleaseCommandContextFuncPtr)systemCalls->GetProcAddress(hManagedPluginModule, g_MANAGED_PLUGIN_RELEASE_COMMAND); - workerCallbackPtrs->wsManPluginSendFuncPtr = (WSManPluginSendFuncPtr)systemCalls->GetProcAddress(hManagedPluginModule, g_MANAGED_PLUGIN_SEND); - workerCallbackPtrs->wsManPluginReceiveFuncPtr = (WSManPluginReceiveFuncPtr)systemCalls->GetProcAddress(hManagedPluginModule, g_MANAGED_PLUGIN_RECEIVE); - workerCallbackPtrs->wsManPluginSignalFuncPtr = (WSManPluginSignalFuncPtr)systemCalls->GetProcAddress(hManagedPluginModule, g_MANAGED_PLUGIN_SIGNAL); - workerCallbackPtrs->wsManPluginConnectFuncPtr = (WSManPluginConnectFuncPtr)systemCalls->GetProcAddress(hManagedPluginModule, g_MANAGED_PLUGIN_CONNECT); - - // Initialize the loaded module (pspluginwkr.dll) - if (hInitPluginMethodAddress) - { - // Only the "old" version of the worker requires a stand-alone init call. - // This object is a member of the PwrshPlugInMediator singleton, so this - // call is made from that context. - (hInitPluginMethodAddress)(); - } - else - { - PWSTR msg = NULL; - exitCode = g_MANAGED_METHOD_RESOLUTION_FAILED; - /* NOTE: don't use a string literal for a fallback; PlugInException expects msg to allocated - and will free it but also supports NULL. - */ - (void) GetFormattedErrorMessage(&msg, exitCode); - *pPluginException = new PlugInException(exitCode, msg); - return exitCode; - } - - return exitCode; -} - -unsigned int PowerShellClrManagedWorker::LaunchClr( - _In_ LPCWSTR wszMonadVersion, - _In_ LPCWSTR wszRuntimeVersion, - _In_ LPCSTR friendlyName) -{ - return commonLib.LaunchCLR(wszMonadVersion, wszRuntimeVersion, &pHost); -} - -unsigned int PowerShellClrManagedWorker::LoadWorkerCallbackPtrs( - _In_ PwrshPluginWkr_Ptrs* workerCallbackPtrs, - _In_z_ wchar_t* wszMgdPlugInFileName, - _Outptr_result_maybenull_ PlugInException** pPluginException) -{ - unsigned int exitCode = EXIT_CODE_SUCCESS; - HRESULT hr = S_OK; - *pPluginException = NULL; - - do - { - // Get a pointer to the default AppDomain - CComPtr<_AppDomain> spDefaultDomain = NULL; - CComPtr spAppDomainPunk = NULL; - - hr = pHost->GetDefaultDomain(&spAppDomainPunk); - if (FAILED(hr) || spAppDomainPunk == NULL) - { - output->DisplayMessage(false, g_GETTING_DEFAULT_DOMAIN_FAILED, hr); - exitCode = EXIT_CODE_INIT_FAILURE; - break; - } - - hr = spAppDomainPunk->QueryInterface(__uuidof(_AppDomain), (PVOID*)&spDefaultDomain); - if (FAILED(hr) || spDefaultDomain == NULL) - { - output->DisplayMessage(false, g_GETTING_DEFAULT_DOMAIN_FAILED, hr); - exitCode = EXIT_CODE_INIT_FAILURE; - break; - } - - CComPtr<_ObjectHandle> spObjectHandle; - - // use CreateInstance because we use the assembly strong name (as opposed to CreateInstanceFrom) - // - // wszMgdPlugInFileName is system.management.automation.dll within the powershell install path. - // For inbox PowerShell, this is %systemdir%\Windows\System32\WindowsPowerShell\v1.0\system.management.automation.dll (Aka $PSHOME\system.management.automation.dll) - _bstr_t bstrConsoleHostAssemblyName = _bstr_t(L"System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); - _bstr_t bstrUnmanagedMshEntryClass = _bstr_t(L"System.Management.Automation.Remoting.WSManPluginManagedEntryInstanceWrapper"); - - hr = spDefaultDomain->CreateInstance( - bstrConsoleHostAssemblyName, - bstrUnmanagedMshEntryClass, - &spObjectHandle); - if (FAILED(hr) || spObjectHandle == NULL) - { - output->DisplayMessage(false, g_CREATING_MSH_ENTRANCE_FAILED, hr); - exitCode = EXIT_CODE_INIT_FAILURE; - break; - } - - CComVariant VntUnwrapped; - hr = spObjectHandle->Unwrap(&VntUnwrapped); - if (FAILED(hr)) - { - output->DisplayMessage(false, g_CREATING_MSH_ENTRANCE_FAILED, hr); - exitCode = EXIT_CODE_INIT_FAILURE; - break; - } - - CComPtr pDisp; - pDisp = VntUnwrapped.pdispVal; - - OLECHAR FAR * wszMember = L"GetEntryDelegate"; - - DISPID dispid; - //Retrieve the DISPID - hr = pDisp->GetIDsOfNames( - IID_NULL, - &wszMember, - 1, - LOCALE_SYSTEM_DEFAULT, - &dispid); - - if (FAILED(hr)) - { - output->DisplayMessage(false, g_GETTING_DISPATCH_ID_FAILED, hr); - exitCode = EXIT_CODE_INIT_FAILURE; - break; - } - - DISPPARAMS dispparamsOneArg = { NULL, NULL, 0 }; - VARIANT varResult; - VariantInit(&varResult); - EXCEPINFO exception; - unsigned int uArgErr = 0; - - //Invoke the method on the Dispatch Interface - hr = pDisp->Invoke( - dispid, - IID_NULL, - LOCALE_SYSTEM_DEFAULT, - DISPATCH_METHOD, - &dispparamsOneArg, - &varResult, - &exception, - &uArgErr); - - InitPluginWkrPtrsFuncPtr entryPointDelegate = (InitPluginWkrPtrsFuncPtr)varResult.byref; - - if (FAILED(hr) || - NULL == entryPointDelegate) - { - if (DISP_E_EXCEPTION == hr) - { - output->DisplayMessage(false, g_MANAGED_MSH_EXCEPTION, exception.bstrDescription); - } - else - { - output->DisplayMessage(false, g_INOVKING_MSH_ENTRANCE_FAILED, hr); - } - exitCode = EXIT_CODE_INIT_FAILURE; - break; - } - - // Passes empty pointer structure to the function, expects a filled struct if successful - exitCode = entryPointDelegate(workerCallbackPtrs); - } - while (false); - - return exitCode; -} - -PowerShellClrManagedWorker::~PowerShellClrManagedWorker() -{ - // No need to call pHost->Stop() because, - // as the common language runtime is automatically unloaded when the process exits. - if (output) - { - delete output; - output = NULL; - } -} - -#endif - -// -// This factory method analyzes the wszMgdPlugInFileName and determines the -// appropriate IPowerShellClrHost to instantiate. It is the caller's responsibility -// to free the IPowerShellClrHost once finished using it. -// -IPowerShellClrHost* PowerShellClrWorkerFactory( - _In_ PWSTR wszMgdPlugInFileName) -{ -#ifdef CORECLR - return new PowerShellCoreClrWorker(); // Calls into System.Management.Automation.dll -#else // !CORECLR - std::wstring pluginFileName(wszMgdPlugInFileName); - // This is a case-sensitive search. It checks to see if the file name portion of the path matches the v3 module name. - if (std::wstring::npos != pluginFileName.rfind(g_MANAGED_PLUGIN_FILENAME_V3_STRING)) - { - return new PowerShellClrManagedWorker(); // Calls into System.Management.Automation.dll - } - return new PowerShellClrWorker(); // Calls into pspluginwkr.dll (previous generation of plugin worker) -#endif // !CORECLR -} diff --git a/src/powershell-native/nativemsh/pwrshplugin/pwrshclrhost.h b/src/powershell-native/nativemsh/pwrshplugin/pwrshclrhost.h deleted file mode 100644 index 6594c8a76e7..00000000000 --- a/src/powershell-native/nativemsh/pwrshplugin/pwrshclrhost.h +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// ---------------------------------------------------------------------- -// -// Contents: Headers used by pwrshplugin. -// pwrshplugin is totally unmanaged. -// ---------------------------------------------------------------------- - -#pragma once - -#include "pwrshplugindefs.h" // PwrshPluginWkr_Ptrs and PlugInException -#if !CORECLR -#include -#endif -#include -#include -#include "SystemCallFacade.h" -#include "ClrHostWrapper.h" -#include "NativeMsh.h" - -class PwrshPluginOutputDefault : public NativeMsh::IPwrshCommonOutput -{ -public: - virtual VOID DisplayMessage( - bool bUseStdOut, - DWORD dwMessageId, - ...) - { - return; - } - - virtual void DisplayErrorWithSystemError( - LONG lSystemErrorCode, - int messageId, - LPCWSTR insertionParam) - { - return; - } -}; - -class IPowerShellClrHost -{ -public: - // Virtual destructor to ensure that derived destructors are called - // during base class destruction. - virtual ~IPowerShellClrHost() {} - - virtual unsigned int LaunchClr( - _In_ LPCWSTR wszMonadVersion, - _In_ LPCWSTR wszRuntimeVersion, - _In_ LPCSTR friendlyName) = 0; - - virtual unsigned int LoadWorkerCallbackPtrs( - _In_ PwrshPluginWkr_Ptrs* workerCallbackPtrs, - _In_z_ PWSTR wszMgdPlugInFileName, - _Outptr_result_maybenull_ PlugInException** pPluginException) = 0; -}; - -#if !CORECLR // See note for LaunchCLR for an explanation. - -class PowerShellClrWorker : public IPowerShellClrHost -{ -private: - CComPtr pHost; - HMODULE hManagedPluginModule; - NativeMsh::IPwrshCommonOutput* output; - NativeMsh::PwrshCommon commonLib; - - const LPCSTR g_INIT_PLUGIN; - const LPCSTR g_SHUTDOWN_PLUGIN; - const LPCSTR g_MANAGED_PLUGIN_CREATE_SHELL; - const LPCSTR g_MANAGED_PLUGIN_RELEASE_SHELL; - const LPCSTR g_MANAGED_PLUGIN_CREATE_COMMAND; - const LPCSTR g_MANAGED_PLUGIN_RELEASE_COMMAND; - const LPCSTR g_MANAGED_PLUGIN_SEND; - const LPCSTR g_MANAGED_PLUGIN_RECEIVE; - const LPCSTR g_MANAGED_PLUGIN_SIGNAL; - const LPCSTR g_MANAGED_PLUGIN_CONNECT; - - NativeMsh::SystemCallFacade* systemCalls; - -public: - PowerShellClrWorker(); - PowerShellClrWorker(NativeMsh::SystemCallFacade* sysCalls); - - virtual ~PowerShellClrWorker(); - - // - // IPowerShellClrHost Methods - // - virtual unsigned int LaunchClr( - _In_ LPCWSTR wszMonadVersion, - _In_ LPCWSTR wszRuntimeVersion, - _In_ LPCSTR friendlyName); - - virtual unsigned int LoadWorkerCallbackPtrs( - _In_ PwrshPluginWkr_Ptrs* workerCallbackPtrs, - _In_z_ wchar_t* wszMgdPlugInFileName, - _Outptr_result_maybenull_ PlugInException** pPluginException); -}; - -class PowerShellClrManagedWorker : public IPowerShellClrHost -{ -private: - CComPtr pHost; - NativeMsh::IPwrshCommonOutput* output; - NativeMsh::PwrshCommon commonLib; - -public: - PowerShellClrManagedWorker() : pHost(NULL), output(new PwrshPluginOutputDefault()) - {} - - virtual ~PowerShellClrManagedWorker(); - - // - // IPowerShellClrHost Methods - // - virtual unsigned int LaunchClr( - _In_ LPCWSTR wszMonadVersion, - _In_ LPCWSTR wszRuntimeVersion, - _In_ LPCSTR friendlyName); - - virtual unsigned int LoadWorkerCallbackPtrs( - _In_ PwrshPluginWkr_Ptrs* workerCallbackPtrs, - _In_z_ wchar_t* wszMgdPlugInFileName, - _Outptr_result_maybenull_ PlugInException** pPluginException); -}; - -#else // CORECLR - -class PowerShellCoreClrWorker : public IPowerShellClrHost -{ -private: - NativeMsh::ClrHostWrapper* hostWrapper; - NativeMsh::SystemCallFacade* systemCalls; - NativeMsh::PwrshCommon* commonLib; - NativeMsh::IPwrshCommonOutput* output; - NativeMsh::HostEnvironment hostEnvironment; - -public: - PowerShellCoreClrWorker(); - - PowerShellCoreClrWorker( - NativeMsh::SystemCallFacade* sysCalls, - NativeMsh::ClrHostWrapper* hstWrp, - NativeMsh::PwrshCommon* cmnLib); - - virtual ~PowerShellCoreClrWorker(); - - std::wstring GetHostDirectory() { return std::wstring(hostEnvironment.GetHostDirectoryPathW()); } - std::wstring GetClrDirectory() { return std::wstring(hostEnvironment.GetCoreCLRDirectoryPathW()); } - - // - // IPowerShellClrHost Methods - // - virtual unsigned int LaunchClr( - _In_ LPCWSTR wszMonadVersion, - _In_ LPCWSTR wszRuntimeVersion, - _In_ LPCSTR friendlyName); - - virtual unsigned int LoadWorkerCallbackPtrs( - _In_ PwrshPluginWkr_Ptrs* workerCallbackPtrs, - _In_z_ PWSTR wszMgdPlugInFileName, - _Outptr_result_maybenull_ PlugInException** pPluginException); -}; - -#endif // CORECLR - -IPowerShellClrHost* PowerShellClrWorkerFactory( - _In_ PWSTR wszMgdPlugInFileName); diff --git a/src/powershell-native/nativemsh/pwrshplugin/pwrshheaders.h b/src/powershell-native/nativemsh/pwrshplugin/pwrshheaders.h deleted file mode 100644 index 7029157cb06..00000000000 --- a/src/powershell-native/nativemsh/pwrshplugin/pwrshheaders.h +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// ---------------------------------------------------------------------- -// -// Contents: Headers used by internal windows teams to access certain -// Powershell functionality -// ---------------------------------------------------------------------- - -#pragma once - -// Gets the CLR Version for a given PowerShell Version. PowerShell Version is -// supplied with 2 parameters iPSMajorVersion (PowerShell major version) and -// iPSMinorVersion (PowerShell minor version). The CLR version is returned through -// pwszRuntimeVersion and pRuntimeVersionLength represents the size of pwszRuntimeVersion. -// returns: 0 on success, non-zero on failure. -_Success_(return == 0) // EXIT_CODE_SUCCESS -extern "C" -unsigned int GetCLRVersionForPSVersion(int iPSMajorVersion, - int iPSMinorVersion, - size_t runtimeVersionLength, - __inout_ecount_part(runtimeVersionLength , *pRuntimeVersionLength) wchar_t* pwszRuntimeVersion, - __out_ecount(1) size_t* pRuntimeVersionLength); diff --git a/src/powershell-native/nativemsh/pwrshplugin/pwrshplugin.def b/src/powershell-native/nativemsh/pwrshplugin/pwrshplugin.def deleted file mode 100644 index ef1208d3875..00000000000 --- a/src/powershell-native/nativemsh/pwrshplugin/pwrshplugin.def +++ /dev/null @@ -1,17 +0,0 @@ -LIBRARY pwrshplugin - -EXPORTS - -GetCLRVersionForPSVersion - -WSManPluginStartup -WSManPluginShutdown - -WSManPluginShell -WSManPluginReleaseShellContext -WSManPluginCommand -WSManPluginReleaseCommandContext -WSManPluginSend -WSManPluginSignal -WSManPluginReceive -WSManPluginConnect diff --git a/src/powershell-native/nativemsh/pwrshplugin/pwrshplugin.dll.manifest b/src/powershell-native/nativemsh/pwrshplugin/pwrshplugin.dll.manifest deleted file mode 100644 index ef7b2351c9d..00000000000 --- a/src/powershell-native/nativemsh/pwrshplugin/pwrshplugin.dll.manifest +++ /dev/null @@ -1,17 +0,0 @@ - - - PowerShell Plugin - - - - - - - - diff --git a/src/powershell-native/nativemsh/pwrshplugin/pwrshplugin.h b/src/powershell-native/nativemsh/pwrshplugin/pwrshplugin.h deleted file mode 100644 index 1c73e6b6027..00000000000 --- a/src/powershell-native/nativemsh/pwrshplugin/pwrshplugin.h +++ /dev/null @@ -1,1101 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// ---------------------------------------------------------------------- -// -// Contents: Headers used by pwrshplugin. -// pwrshplugin is totally unmanaged. -// ---------------------------------------------------------------------- - -#pragma once - -#include "NativeMsh.h" -#include "NativeMshConstants.h" -#include "entrypoints.h" -#include "pwrshheaders.h" -#include "pwrshplugindefs.h" -#include "pwrshclrhost.h" - -// include wsman.h header file..it is required to declare the version -// number of the wsman API to use -#define WSMAN_API_VERSION_1_0 -#include - -using namespace NativeMsh; - -// Forward declaration of class PwrshPlugIn -class PwrshPlugIn; - -class PwrshPlugIn -{ -private: - PCWSTR pAppIdentifier; - PCWSTR initParameters; - -public: - // applicationIdentification: - // This relates to the application HTTP suffix that is hosting the plug-in. - // For the main WSMan service by default this would be "wsman", whereas for - // an IIS host it would relate to the application endpoint for that host and - // would be something like "MyCompany/MyApplication". - PwrshPlugIn(PCWSTR applicationIdentification, PCWSTR pInitParams) - { - pAppIdentifier = applicationIdentification; - initParameters = pInitParams; - } - - ~PwrshPlugIn() - { - if (NULL != initParameters) - { - delete[] initParameters; - } - } - - PCWSTR GetApplicationIdentifier() - { - return pAppIdentifier; - } - - PCWSTR GetInitParameters() - { - return initParameters; - } -}; - -class PwrshPlugInMediator -{ -private: - // handle to managed powershell plugin - ShutdownPluginFuncPtr hShutdownPluginMethodAddress; - WSManPluginShellFuncPtr hCreateShellMethodAddress; - WSManPluginReleaseShellContextFuncPtr hReleaseShellMethodAddress; - WSManPluginCommandFuncPtr hCreateCommandMethodAddress; - WSManPluginReleaseCommandContextFuncPtr hReleaseCommandMethodAddress; - WSManPluginSendFuncPtr hSendMethodAddress; - WSManPluginReceiveFuncPtr hReceiveMethodAddress; - WSManPluginSignalFuncPtr hSignalMethodAddress; - WSManPluginConnectFuncPtr hConnectMethodAddress; - - // boolean to keep track if the managed plugin is loaded successfully - bool bIsPluginLoaded; - int iMajorVersion; - wchar_t* wszCLRVersion; - wchar_t* wszAppBase; - bool bIsDisposed; - - // fields needed to validate 2 plugins initializing at the same time - CRITICAL_SECTION criticalSection; - bool isCSInitSucceeded; - - // Abstraction of the differences between CLR hosting environments with - // respect to the interface with pspluginwkr. - IPowerShellClrHost* powerShellClrHost; - - // Default no-op implementation used for the output functions. - NativeMsh::PwrshCommon pwrshCommon; - - // private constructor..to make Mediator Singleton - PwrshPlugInMediator() - { - bIsPluginLoaded = false; - bIsDisposed = false; - iMajorVersion = 0; - wszCLRVersion = NULL; - wszAppBase = NULL; - - hShutdownPluginMethodAddress = NULL; - hCreateShellMethodAddress = NULL; - hReleaseShellMethodAddress = NULL; - hCreateCommandMethodAddress = NULL; - hReleaseCommandMethodAddress = NULL; - hSendMethodAddress = NULL; - hReceiveMethodAddress = NULL; - hSignalMethodAddress = NULL; - hConnectMethodAddress = NULL; - - isCSInitSucceeded = false; - - powerShellClrHost = NULL; - - // spin count is set to 1024 - if (InitializeCriticalSectionAndSpinCount(&criticalSection, 0x80000400)) - { - isCSInitSucceeded = true; - } - } - - // Clear plugin specific resources. - void CleanUp() - { - if (!bIsDisposed) - { - bIsDisposed = true; - - if (NULL != powerShellClrHost) - { - delete powerShellClrHost; - powerShellClrHost = NULL; - } - - if (NULL != wszCLRVersion) - { - delete[] wszCLRVersion; - wszCLRVersion = NULL; - } - - if (NULL != wszAppBase) - { - delete[] wszAppBase; - wszAppBase = NULL; - } - } - } - -public: - - static PwrshPlugInMediator* GetPwrshPlugInMediator(__in_opt PCWSTR extraInfo) throw (...) - { - // to make plugin mediator singleton - // Create object, when called for the first time - static PwrshPlugInMediator singletonInstance; - - if (!singletonInstance.isCSInitSucceeded) - { - PWSTR msg = NULL; - GetFormattedErrorMessage(&msg, g_INIT_CRITICALSECTION_FAILED); - throw new PlugInException(g_INIT_CRITICALSECTION_FAILED, msg); - } - - // this check avoids entering/exiting critical sections - // frequently - if (!singletonInstance.bIsPluginLoaded) - { - EnterCriticalSection(&singletonInstance.criticalSection); - try - { - if (!singletonInstance.bIsPluginLoaded) - { - // process extra info initializes the pwrshplugin - // by initializing the CLR version and obtaining access - // pointers for the plugin worker or for System.Management.Automation.dll. - singletonInstance.ProcessExtraInfo(extraInfo, NULL); - } - } - catch(PlugInException* e) - { - LeaveCriticalSection(&singletonInstance.criticalSection); - throw e; - } - - LeaveCriticalSection(&singletonInstance.criticalSection); - } - - return &singletonInstance; - } - - ~PwrshPlugInMediator() - { - if (isCSInitSucceeded) - { - DeleteCriticalSection(&criticalSection); - } - - CleanUp(); - } - - // Clear plugin specific resources. - DWORD Shutdown(__in DWORD flags, __in DWORD reason) throw (...) - { - // this null condition should never occur.. but for server process safety ensure we - // fail safely.. - if (NULL != hShutdownPluginMethodAddress) - { - (hShutdownPluginMethodAddress)((PVOID)this); - } - - CleanUp(); - return NO_ERROR; - } - - PwrshPlugIn* CreatePwrshPlugIn(__in PCWSTR applicationIdentification, - __in_opt PCWSTR extraInfo) throw (...) - { - PWSTR initParameters = NULL; - // ProcessExtraInfo might throw... - // storing the extra info for plugin use later. - VerifyAndStoreExtraInfo(extraInfo, &initParameters); - PwrshPlugIn* result = new PwrshPlugIn(applicationIdentification, initParameters); - return result; - } - - VOID CreateShell( - __in PwrshPlugIn *plugInToUseWithCreateShell, - __in WSMAN_PLUGIN_REQUEST *requestDetails, - __in DWORD flags, - __in_opt WSMAN_SHELL_STARTUP_INFO *startupInfo, - __in_opt WSMAN_DATA *inboundShellInformation) - { - if ((NULL == plugInToUseWithCreateShell) || - (NULL == requestDetails) || - (NULL == startupInfo) || - (NULL == requestDetails->operationInfo)) - { - ReportError(requestDetails, g_INVALID_INPUT, L"WSManPluginShell"); - return; - } - - // this null condition should never occur.. but for server process safety ensure we - // fail safely.. - if (NULL == hCreateShellMethodAddress) - { - ReportError(requestDetails, g_MANAGED_METHOD_RESOLUTION_FAILED); - return; - } - - __try - { - PCWSTR initParameters = plugInToUseWithCreateShell->GetInitParameters(); - (hCreateShellMethodAddress)((PVOID)this, requestDetails, flags, initParameters, startupInfo, inboundShellInformation); - } - __except(ProcessException(requestDetails, GetExceptionCode())) - { - } - } - - VOID ReleaseShell(__in PVOID shellContext) - { - // this null condition should never occur.. but for server process safety ensure we - // fail safely.. - if (NULL != hReleaseShellMethodAddress) - { - (hReleaseShellMethodAddress)((PVOID)this, shellContext); - } - } - - VOID CreateCommand( - __in WSMAN_PLUGIN_REQUEST *requestDetails, - __in DWORD flags, - __in PVOID shellContext, - __in PCWSTR commandLine, - __in_opt WSMAN_COMMAND_ARG_SET *arguments) - { - if (NULL == requestDetails) - { - ReportError(requestDetails, g_INVALID_INPUT, L"WSManPluginCommand"); - return; - } - - if (NULL == hCreateCommandMethodAddress) - { - ReportError(requestDetails, g_MANAGED_METHOD_RESOLUTION_FAILED); - return; - } - - __try - { - (hCreateCommandMethodAddress)((PVOID)this, requestDetails, flags, shellContext, commandLine, arguments); - } - __except(ProcessException(requestDetails, GetExceptionCode())) - { - } - } - - VOID ReleaseCommand(__in PVOID shellContext, - __in PVOID commandContext) - { - // this null condition should never occur.. but for server process safety ensure we - // fail safely.. - if (NULL != hReleaseShellMethodAddress) - { - (hReleaseCommandMethodAddress)((PVOID)this, shellContext, commandContext); - } - } - - VOID ExecuteConnectToShellOrCommand( - __in WSMAN_PLUGIN_REQUEST *requestDetails, - __in DWORD flags, - __in PVOID shellContext, - __in_opt PVOID commandContext, - __in_opt WSMAN_DATA *inboundConnectInformation) - { - if (NULL == requestDetails) - { - ReportError(requestDetails, g_INVALID_INPUT, L"WSManPluginConnect"); - return; - } - - if (NULL == hConnectMethodAddress) - { - ReportError(requestDetails, g_MANAGED_CONNECT_METHOD_RESOLUTION_FAILED); - return; - } - - __try - { - (hConnectMethodAddress)((PVOID)this, requestDetails, flags, shellContext, commandContext, inboundConnectInformation); - } - __except(ProcessException(requestDetails, GetExceptionCode())) - { - } - - } - - VOID SendOneItemToShellOrCommand( - __in WSMAN_PLUGIN_REQUEST *requestDetails, - __in DWORD flags, - __in PVOID shellContext, - __in_opt PVOID commandContext, - __in PCWSTR stream, - __in WSMAN_DATA *inboundData) - { - if (NULL == requestDetails) - { - ReportError(requestDetails, g_INVALID_INPUT, L"WSManPluginSend"); - return; - } - - if (NULL == hSendMethodAddress) - { - ReportError(requestDetails, g_MANAGED_METHOD_RESOLUTION_FAILED); - return; - } - - __try - { - (hSendMethodAddress)((PVOID)this, requestDetails, flags, shellContext, commandContext, stream, inboundData); - } - __except(ProcessException(requestDetails, GetExceptionCode())) - { - } - } - - VOID EnableShellOrCommandToSendDataToClient( - __in WSMAN_PLUGIN_REQUEST *requestDetails, - __in DWORD flags, - __in PVOID shellContext, - __in_opt PVOID commandContext, - __in_opt WSMAN_STREAM_ID_SET* streamSet) - { - if (NULL == requestDetails) - { - ReportError(requestDetails, g_INVALID_INPUT, L"WSManPluginReceive"); - return; - } - - if (NULL == hReceiveMethodAddress) - { - ReportError(requestDetails, g_MANAGED_METHOD_RESOLUTION_FAILED); - return; - } - - __try - { - (hReceiveMethodAddress)((PVOID)this, requestDetails, flags, shellContext, commandContext, streamSet); - } - __except(ProcessException(requestDetails, GetExceptionCode())) - { - } - } - - VOID SignalShellOrCmd( - __in WSMAN_PLUGIN_REQUEST *requestDetails, - __in DWORD flags, - __in PVOID shellContext, - __in_opt PVOID commandContext, - __in PCWSTR code) - { - if (NULL == requestDetails) - { - ReportError(requestDetails, g_INVALID_INPUT, L"WSManPluginSignal"); - return; - } - - if (NULL == hSignalMethodAddress) - { - ReportError(requestDetails, g_MANAGED_METHOD_RESOLUTION_FAILED); - return; - } - - __try - { - (hSignalMethodAddress)((PVOID)this, requestDetails, flags, shellContext, commandContext, code); - } - __except(ProcessException(requestDetails, GetExceptionCode())) - { - } - } - -private: - // checks if the current plugin is active. - inline bool IsActive() - { - return bIsDisposed; - } - - /* Process error code from the exception. The current code always - * returns EXCEPTION_CONTINUE_SEARCH after logging the error code. - * - * requestDetails is used to report WSMan operation complete - */ - int ProcessException(WSMAN_PLUGIN_REQUEST *requestDetails, unsigned int errorCode) - { - WSManPluginOperationComplete(requestDetails, 0, errorCode, NULL); - return EXCEPTION_CONTINUE_EXECUTION; - } - - DWORD ReportError(WSMAN_PLUGIN_REQUEST *requestDetails, DWORD dwMessageId, ...) - { - PWSTR extendedErrorInformation = NULL; - - va_list args; - va_start(args, dwMessageId); - - GetFormattedErrorMessage(&extendedErrorInformation, dwMessageId, &args); - - va_end(args); - - DWORD errorCode = dwMessageId; - DWORD result = WSManPluginOperationComplete(requestDetails, 0, errorCode, extendedErrorInformation); - - if (NULL != extendedErrorInformation) - { - delete[] extendedErrorInformation; - } - - return result; - } - - DWORD ReportError(WSMAN_PLUGIN_REQUEST *requestDetails, PlugInException* e) - { - DWORD errorCode = e->dwMessageId; - - DWORD result = WSManPluginOperationComplete(requestDetails, 0, errorCode, e->extendedErrorInformation); - return result; - } - - unsigned int CreateMgdPluginFileName( - int iVPSMajorVersion, - int iVPSMinorVersion, - _In_ PWSTR wszVAppBase, - __out PWSTR* wszMgdPlugInFileName) - { - int monadMajorVersion = iVPSMajorVersion; - int monadMinorVersion = iVPSMinorVersion; - wchar_t * wszMonadVersion = NULL; - wchar_t* wszTempCLRVersion = NULL; - unsigned int exitCode = EXIT_CODE_SUCCESS; - - do - { - iMajorVersion = iVPSMajorVersion; - - if (NULL != wszMgdPlugInFileName) - { - *wszMgdPlugInFileName = NULL; - } - - exitCode = ConstructPowerShellVersion(iVPSMajorVersion, iVPSMinorVersion, &wszMonadVersion); - if (EXIT_CODE_SUCCESS != exitCode) - { - break; - } - - // Read managed plugin's full path from registry, if such a path exists. - exitCode = pwrshCommon.GetRegistryInfo( - &wszMonadVersion, - &monadMajorVersion, - monadMinorVersion, - &wszTempCLRVersion, - g_PSPLUGINWKRV3_REGISTRY_KEY, - wszMgdPlugInFileName); - - if (*wszMgdPlugInFileName == NULL) - { - // Reset exit code to EXIT_CODE_SUCCESS - exitCode = EXIT_CODE_SUCCESS; - - // construct managed plugin's full path - size_t iAppBaseLength; - size_t iFileNameLength; - size_t iTotalLength; - - if (FAILED(StringCchLength(wszVAppBase, STRSAFE_MAX_CCH, &iAppBaseLength)) || - FAILED(StringCchLength(g_MANAGED_PLUGIN_FILENAME_STRING, STRSAFE_MAX_CCH, &iFileNameLength))) - { - exitCode = g_INVALID_INPUT; - break; - } - - iTotalLength = iAppBaseLength + iFileNameLength + 2; - - *wszMgdPlugInFileName = new wchar_t[iTotalLength]; - if (NULL == *wszMgdPlugInFileName) - { - exitCode = E_OUTOFMEMORY; - break; - } - (*wszMgdPlugInFileName)[0] = '\0'; - - if (FAILED(StringCchCopyW(*wszMgdPlugInFileName, iTotalLength, wszVAppBase)) || - FAILED(StringCchCatW(*wszMgdPlugInFileName, iTotalLength, L"\\")) || - FAILED(StringCchCatW(*wszMgdPlugInFileName, iTotalLength, g_MANAGED_PLUGIN_FILENAME_STRING))) - { - exitCode = g_MANAGED_PLUGIN_PATH_CONSTRUCTION_ERROR; - break; - } - } - } while (false); - - if (NULL != wszMonadVersion) - { - delete[] wszMonadVersion; - } - - if (NULL != wszTempCLRVersion) - { - delete[] wszTempCLRVersion; - } - return exitCode; - } - - // returns non-zero code on error + plugin exception is populated in some cases - // like plugin load error. so the caller is expected to check both these - // to see if there is any error. - unsigned int LoadManagedPlugIn( - _In_ PWSTR wszMgdPlugInFileName, - _In_ PWSTR wszVCLRVersion, // Conditionally set to wszCLRVersion on success - _In_ PWSTR wszVAppBase, // Conditionally set to wszAppBase on success - __out PlugInException** pPluginException ) - { - unsigned int exitCode = EXIT_CODE_SUCCESS; - - if (NULL != pPluginException) - { - *pPluginException = NULL; - } - else - { - return g_INVALID_INPUT; - } - - if (bIsPluginLoaded) - { - return g_MANAGED_PLUGIN_ALREADY_LOADED; - } - - if ((NULL == wszVCLRVersion) || (NULL == wszVAppBase)) - { - return g_INVALID_INPUT; - } - - do - { - // Setting global AppBase and CLR Version - wszCLRVersion = wszVCLRVersion; - wszAppBase = wszVAppBase; - - // Load managed plugin worker.. - - PwrshPluginWkr_Ptrs workerCallbackPtrs; - memset(&workerCallbackPtrs, 0, sizeof(PwrshPluginWkr_Ptrs)); - - // The loader will obtain the worker pointers from the appropriate DLL. - // If this call succeeds, PwrshPluginWkr_Ptrs should be populated. - exitCode = powerShellClrHost->LoadWorkerCallbackPtrs(&workerCallbackPtrs, wszMgdPlugInFileName, pPluginException); - - if (EXIT_CODE_SUCCESS == exitCode) - { - // Now get the proc address for all the plugin API.. - hShutdownPluginMethodAddress = workerCallbackPtrs.shutdownPluginFuncPtr; - hCreateShellMethodAddress = workerCallbackPtrs.wsManPluginShellFuncPtr; - hReleaseShellMethodAddress = workerCallbackPtrs.wsManPluginReleaseShellContextFuncPtr; - hCreateCommandMethodAddress = workerCallbackPtrs.wsManPluginCommandFuncPtr; - hReleaseCommandMethodAddress = workerCallbackPtrs.wsManPluginReleaseCommandContextFuncPtr; - hSendMethodAddress = workerCallbackPtrs.wsManPluginSendFuncPtr; - hReceiveMethodAddress = workerCallbackPtrs.wsManPluginReceiveFuncPtr; - hSignalMethodAddress = workerCallbackPtrs.wsManPluginSignalFuncPtr; - hConnectMethodAddress = workerCallbackPtrs.wsManPluginConnectFuncPtr; - } - - if (// if pwrsplugin v2 plugin, this function does not exist - // (NULL == hShutdownPluginMethodAddress) || - (NULL == hCreateShellMethodAddress) || (NULL == hReleaseShellMethodAddress) || - (NULL == hCreateCommandMethodAddress) || (NULL == hReleaseCommandMethodAddress) || - (NULL == hSendMethodAddress) || (NULL == hReceiveMethodAddress) || - (NULL == hSignalMethodAddress)) - { - PWSTR msg = NULL; - exitCode = g_MANAGED_METHOD_RESOLUTION_FAILED; - GetFormattedErrorMessage(&msg, g_MANAGED_METHOD_RESOLUTION_FAILED); - *pPluginException = new PlugInException(exitCode, msg); - break; - } - - bIsPluginLoaded = true; - }while(false); - - if (exitCode != EXIT_CODE_SUCCESS) - { - wszCLRVersion = NULL; - wszAppBase = NULL; - } - - return exitCode; - } - - void LoadPowerShell(PCWSTR version) throw (...) - { - // Verify incoming powershell version format. - int iPSMajorVersion = 0; - int iPSMinorVersion = 0; - if (!pwrshCommon.VerifyMonadVersionFormat(version, &iPSMajorVersion, &iPSMinorVersion, true, false)) - { - PWSTR msg = NULL; - GetFormattedErrorMessage(&msg, g_OPTION_SET_NOT_COMPLY, g_BUILD_VERSION); - throw new PlugInException(g_OPTION_SET_NOT_COMPLY, msg); - } - - // client is requesting powershell 1.x version. Remoting doesn't support - // powershell 1.0, remoting is supported from 2.0 - if (1 >= iPSMajorVersion) - { - PWSTR msg = NULL; - GetFormattedErrorMessage(&msg, g_OPTION_SET_NOT_COMPLY, g_BUILD_VERSION); - throw new PlugInException(g_OPTION_SET_NOT_COMPLY, msg); - } - - // the reg key from 2 and 1 is 1.. - int requestedMonadMajorVersion = iPSMajorVersion; - if (2 == requestedMonadMajorVersion) - { - requestedMonadMajorVersion = 1; - } - - wchar_t* wszMonadVersion = NULL; // Allocated via ConstructPowerShellVersion || GetRegistryInfo - wchar_t* wszTempCLRVersion = NULL; // Allocated via GetRegistryInfo - wchar_t* wszTempAppBase = NULL; // Allocated via GetRegistryInfo - PWSTR wszMgdPlugInFileName = NULL; // Allocated in CreateMgdPluginFileName - unsigned int exitCode = EXIT_CODE_SUCCESS; - PlugInException* pErrorMsg = NULL; - - do - { - exitCode = ConstructPowerShellVersion(iPSMajorVersion, iPSMinorVersion, &wszMonadVersion); - if (exitCode != EXIT_CODE_SUCCESS) - { - PWSTR msg = NULL; - GetFormattedErrorMessage(&msg, g_OPTION_SET_NOT_COMPLY, g_BUILD_VERSION); - pErrorMsg = new PlugInException(exitCode, msg); - break; - } - - // Read CLR version from registry - exitCode = pwrshCommon.GetRegistryInfo( - &wszMonadVersion, - &requestedMonadMajorVersion, - iPSMinorVersion, - &wszTempCLRVersion, - L"ApplicationBase", - &wszTempAppBase); - if (EXIT_CODE_SUCCESS != exitCode) - { - PWSTR msg = NULL; - GetFormattedErrorMessage(&msg, g_OPTION_SET_NOT_COMPLY, g_BUILD_VERSION); - pErrorMsg = new PlugInException(exitCode, msg); - break; - } - - exitCode = CreateMgdPluginFileName(requestedMonadMajorVersion, iPSMinorVersion, wszTempAppBase, &wszMgdPlugInFileName); - if (EXIT_CODE_SUCCESS != exitCode) - { - break; - } - - if (!bIsPluginLoaded) - { - this->powerShellClrHost = PowerShellClrWorkerFactory(wszMgdPlugInFileName); - if (NULL == this->powerShellClrHost) - { - exitCode = ERROR_NOT_ENOUGH_MEMORY; - break; - } - - exitCode = powerShellClrHost->LaunchClr(wszMonadVersion, wszTempCLRVersion, "PwrshPlugin"); - if (EXIT_CODE_SUCCESS != exitCode) - { - PWSTR msg = NULL; - GetFormattedErrorMessage(&msg, g_CLR_LOAD_FAILED, wszTempCLRVersion); - pErrorMsg = new PlugInException(g_CLR_LOAD_FAILED, msg); - break; - } - - exitCode = LoadManagedPlugIn(wszMgdPlugInFileName, wszTempCLRVersion, wszTempAppBase, &pErrorMsg); - } - else - { - if (requestedMonadMajorVersion != iMajorVersion) - { - exitCode = g_OPTION_SET_MAJOR_VERSION_NOT_MATCH; - } - else if (0 != _wcsnicmp(wszTempCLRVersion, wszCLRVersion, 20)) - { - exitCode = g_OPTION_SET_CLR_VERSION_NOT_MATCH; - } - else if (0 != _wcsicmp(wszTempAppBase, wszAppBase)) - { - exitCode = g_OPTION_SET_APP_BASE_NOT_MATCH; - } - } - } while (false); - - if (NULL != wszMonadVersion) - { - delete[] wszMonadVersion; - } - - if (NULL != wszMgdPlugInFileName) - { - delete[] wszMgdPlugInFileName; - } - - if (exitCode != EXIT_CODE_SUCCESS) - { - // Assigned to this->wszCLRVersion on success in LoadManagedPlugIn, so it shouldn't be freed here on success - if (NULL != wszTempCLRVersion) - { - delete[] wszTempCLRVersion; - } - - // Assigned to this->wszAppBase on success LoadManagedPlugIn, so it shouldn't be freed here on success - if (NULL != wszTempAppBase) - { - delete[] wszTempAppBase; - } - - if (NULL != pErrorMsg) - { - throw pErrorMsg; - } - else - { - PWSTR msg = NULL; - (void) GetFormattedErrorMessage(&msg, g_OPTION_SET_NOT_COMPLY, g_BUILD_VERSION); - /* NOTE: Passing possible NULL msg. PlugInExpecption requires allocated - or NULL. Literal strings are not supported. */ - throw new PlugInException(exitCode, msg); - } - } - } - -public: - // extraInfo is supplied by WSMan and WSMan validates the XML syntax - // before supplying this value to plugin..because of this, the following - // method will not check for xml element syntax. - void VerifyAndStoreExtraInfo(PCWSTR extraInfo, - __deref_opt_out PWSTR *initParameters) throw(...) - { - if (NULL == extraInfo) - { - PWSTR msg = NULL; - GetFormattedErrorMessage(&msg, - g_PSVERSION_NOT_FOUND_IN_CONFIG, g_PSVERSION_CONFIG, g_INITIALIZATIONPARAM_CONFIG); - throw new PlugInException(g_PSVERSION_NOT_FOUND_IN_CONFIG, msg); - } - - size_t initParamsLength; - if (FAILED(StringCchLength(extraInfo, STRSAFE_MAX_CCH, &initParamsLength))) - { - PWSTR msg = NULL; - GetFormattedErrorMessage(&msg, - g_BAD_INITPARAMETERS, g_INITIALIZATIONPARAM_CONFIG); - throw new PlugInException(g_BAD_INITPARAMETERS, msg); - } - - if (NULL != initParameters) - { - // make a local copy of the extra info for future use - // this will be used whenever a new shell is created. - *initParameters = new wchar_t[initParamsLength + 1]; - if (FAILED(StringCchCopyNW(*initParameters, initParamsLength + 1, extraInfo, initParamsLength))) - { - PWSTR msg = NULL; - GetFormattedErrorMessage(&msg, - g_BAD_INITPARAMETERS, g_INITIALIZATIONPARAM_CONFIG); - throw new PlugInException(g_BAD_INITPARAMETERS, msg); - } - } - } - - void ProcessExtraInfo(PCWSTR extraInfo, - __deref_opt_out PWSTR *initParameters) throw(...) - { - VerifyAndStoreExtraInfo(extraInfo, initParameters); - - // Get PSVersion and MaxPSVersion values from the config xml - wchar_t* psversion = NULL; - wchar_t* maxpsversion = NULL; - // Win8: 97936: To support backward compatability, if PSVersion = 2.0 and AssemblyToken - // is specified we set maxPSVersion = 2.0..so that the endpoint is not automatically - // transferred to PS 3.0 - wchar_t* assemblyToken = NULL; - - // This will hold the powershell version calculated from psversion and maxpsversion - wchar_t* version = NULL; - - size_t initParamsLength; - if (FAILED(StringCchLength(extraInfo, STRSAFE_MAX_CCH, &initParamsLength))) - { - PWSTR msg = NULL; - GetFormattedErrorMessage(&msg, - g_BAD_INITPARAMETERS, g_INITIALIZATIONPARAM_CONFIG); - throw new PlugInException(g_BAD_INITPARAMETERS, msg); - } - - PCWSTR param = wcsstr(extraInfo, L" 0) - { - version = new wchar_t[length + 1]; - - try - { - if (FAILED(StringCchCopyNW(version, length + 1, startVersion, length))) - { - PWSTR msg = NULL; - GetFormattedErrorMessage(&msg, - g_BAD_INITPARAMETERS, g_INITIALIZATIONPARAM_CONFIG); - throw new PlugInException(g_BAD_INITPARAMETERS, msg); - } - return version; - } - catch(...) - { - if (NULL != version) - { - delete[] version; - } - throw; - } - - // delete the version in non-throw case. - if (NULL != version) - { - delete[] version; - } - } - } - return NULL; - } - - wchar_t* CalculatePowershellVersion(__in wchar_t* psversion, - __in_opt wchar_t* maxpsversion) - { - wchar_t* version = NULL; - int majorPSVersionNumber = -1, minorPSVersionNumber = -1; - int majorMaxPSVersionNumber = -1, minorMaxPSVersionNumber = -1 ; - if (pwrshCommon.VerifyMonadVersionFormat(psversion, &majorPSVersionNumber, &minorPSVersionNumber, true, true)) - { - if (maxpsversion != NULL) - { - if (pwrshCommon.VerifyMonadVersionFormat(maxpsversion, &majorMaxPSVersionNumber, &minorMaxPSVersionNumber, true, true)) - { - // TODO: Don't understand this. - if (majorMaxPSVersionNumber > majorPSVersionNumber) - { - PWSTR msg = NULL; - GetFormattedErrorMessage(&msg, - g_BAD_INITPARAMETERS, g_INITIALIZATIONPARAM_CONFIG); - throw new PlugInException(g_BAD_INITPARAMETERS, msg); - } - - // TODO: why hardcoding is needed here - if (majorPSVersionNumber == 3 && majorMaxPSVersionNumber == 2) - { - PWSTR msg = NULL; - GetFormattedErrorMessage(&msg, - g_BAD_INITPARAMETERS, g_INITIALIZATIONPARAM_CONFIG); - throw new PlugInException(g_BAD_INITPARAMETERS, msg); - } - - if (majorPSVersionNumber == 2 && majorMaxPSVersionNumber == 2) - { - size_t length; - if (FAILED(StringCchLength(psversion, STRSAFE_MAX_CCH, &length))) - { - PWSTR msg = NULL; - GetFormattedErrorMessage(&msg, - g_BAD_INITPARAMETERS, g_INITIALIZATIONPARAM_CONFIG); - throw new PlugInException(g_BAD_INITPARAMETERS, msg); - } - - version = new wchar_t[length + 1]; - // Set version as the psversion - if (FAILED(StringCchCopyNW(version, length + 1, psversion, length))) - { - PWSTR msg = NULL; - GetFormattedErrorMessage(&msg, - g_BAD_INITPARAMETERS, g_INITIALIZATIONPARAM_CONFIG); - throw new PlugInException(g_BAD_INITPARAMETERS, msg); - } - } - } - } - else - { - version = L"3.0"; - } - } - return version; - } -}; diff --git a/src/powershell-native/nativemsh/pwrshplugin/pwrshpluginResources.rc b/src/powershell-native/nativemsh/pwrshplugin/pwrshpluginResources.rc deleted file mode 100644 index cbf92dff714..00000000000 --- a/src/powershell-native/nativemsh/pwrshplugin/pwrshpluginResources.rc +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// resource script for msh.exe -// - -#include - -#define MANIFEST_RESOURCE_ID 1 - -MANIFEST_RESOURCE_ID RT_MANIFEST "pwrshplugin.dll.manifest" - -#include "pwrshpluginerrorcodes.rc" -#include "version.rc" \ No newline at end of file diff --git a/src/powershell-native/nativemsh/pwrshplugin/pwrshplugindefs.h b/src/powershell-native/nativemsh/pwrshplugin/pwrshplugindefs.h deleted file mode 100644 index 6306dddf95f..00000000000 --- a/src/powershell-native/nativemsh/pwrshplugin/pwrshplugindefs.h +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// ---------------------------------------------------------------------- -// -// Contents: Headers used by pwrshplugin. -// pwrshplugin is totally unmanaged. -// ---------------------------------------------------------------------- - -#pragma once - -#include -#include - -// include wsman.h header file..it is required to declare the version -// number of the wsman API to use -#define WSMAN_API_VERSION_1_0 -#include - -// plugin errors start from 1000 -const int g_NULL_PLUGIN_CONTEXT = 1100; -const int g_CREATION_FAILED = 1101; -const int g_MANAGED_PLUGIN_ALREADY_LOADED = 1102; -const int g_MANAGED_PLUGIN_PATH_CONSTRUCTION_ERROR = 1103; -const int g_MANAGED_PLUGIN_LOAD_FAILED = 1104; - -const int g_SHELL_CREATION_FAILED = 1201; -const int g_OPTION_SET_MAJOR_VERSION_NOT_MATCH = 1202; -const int g_OPTION_SET_CLR_VERSION_NOT_MATCH = 1203; -const int g_OPTION_SET_APP_BASE_NOT_MATCH = 1204; - -const PCWSTR g_VERSION_OPTION_STRING = L"version"; -const PCWSTR g_PSPLUGINWKRV3_REGISTRY_KEY = L"PSPluginWkrModuleName"; -const PCWSTR g_MANAGED_PLUGIN_FILENAME_STRING = L"pspluginwkr.dll"; -const PCWSTR g_MANAGED_PLUGIN_FILENAME_V3_STRING = L"system.management.automation.dll"; -const PCWSTR g_PSVERSION_CONFIG = L"PSVersion"; -const PCWSTR g_INITIALIZATIONPARAM_CONFIG = L"InitializationParameters"; - -// The following VER_ macros are defined in ntverp.h -const PCWSTR g_BUILD_VERSION = LVER_PRODUCTVERSION_STR; - -// Managed and mixed-mode plugin worker method entrypoints -// -// The v3 version of the worker is a mixed-mode managed C++ DLL, so it can -// be accessed directly using GetProcAddress. -// The CoreCLR-compliant worker is included in System.Management.Automation.dll, -// so we have to use alternate means to acquire the function pointers. -// Once we have the pointers, they may be used in the same way regardless of the -// method used to obtain them. - -typedef void (WINAPI *ShutdownPluginFuncPtr)(__in PVOID pluginContext); - -typedef void (WINAPI *WSManPluginShellFuncPtr)( - __in PVOID pluginContext, - __in WSMAN_PLUGIN_REQUEST *requestDetails, - __in DWORD flags, - __in PCWSTR extraInfo, - __in_opt WSMAN_SHELL_STARTUP_INFO *startupInfo, - __in_opt WSMAN_DATA *inboundShellInformation - ); - -typedef void (WINAPI *WSManPluginConnectFuncPtr)( - __in PVOID pluginContext, - __in WSMAN_PLUGIN_REQUEST *requestDetails, - __in DWORD flags, - __in PVOID shellContext, - __in_opt PVOID commandContext, - __in_opt WSMAN_DATA *inboundConnectInformation - ); - -typedef void (WINAPI *WSManPluginReleaseShellContextFuncPtr)( - __in PVOID pluginContext, - __in PVOID shellContext - ); - -typedef void (WINAPI *WSManPluginCommandFuncPtr)( - __in PVOID pluginContext, - __in WSMAN_PLUGIN_REQUEST *requestDetails, - __in DWORD flags, - __in PVOID shellContext, - __in PCWSTR commandLine, - __in_opt WSMAN_COMMAND_ARG_SET *arguments - ); - -typedef void (WINAPI *WSManPluginReleaseCommandContextFuncPtr)( - __in PVOID pluginContext, - __in PVOID shellContext, - __in PVOID commandContext - ); - -typedef void (WINAPI *WSManPluginSendFuncPtr)( - __in PVOID pluginContext, - __in WSMAN_PLUGIN_REQUEST *requestDetails, - __in DWORD flags, - __in PVOID shellContext, - __in_opt PVOID commandContext, - __in PCWSTR stream, - __in WSMAN_DATA *inboundData - ); - -typedef void (WINAPI *WSManPluginReceiveFuncPtr)( - __in PVOID pluginContext, - __in WSMAN_PLUGIN_REQUEST *requestDetails, - __in DWORD flags, - __in PVOID shellContext, - __in_opt PVOID commandContext, - __in_opt WSMAN_STREAM_ID_SET* streamSet - ); - -typedef void (WINAPI *WSManPluginSignalFuncPtr)( - __in PVOID pluginContext, - __in WSMAN_PLUGIN_REQUEST *requestDetails, - __in DWORD flags, - __in PVOID shellContext, - __in_opt PVOID commandContext, - __in PCWSTR code); - -typedef void (WINAPI *WSManPluginOperationShutdownFuncPtr)( - __in PVOID pluginContext); - -typedef struct _PwrshPluginWkr_Ptrs -{ - ShutdownPluginFuncPtr shutdownPluginFuncPtr; - WSManPluginShellFuncPtr wsManPluginShellFuncPtr; - WSManPluginReleaseShellContextFuncPtr wsManPluginReleaseShellContextFuncPtr; - WSManPluginCommandFuncPtr wsManPluginCommandFuncPtr; - WSManPluginReleaseCommandContextFuncPtr wsManPluginReleaseCommandContextFuncPtr; - WSManPluginSendFuncPtr wsManPluginSendFuncPtr; - WSManPluginReceiveFuncPtr wsManPluginReceiveFuncPtr; - WSManPluginSignalFuncPtr wsManPluginSignalFuncPtr; - WSManPluginConnectFuncPtr wsManPluginConnectFuncPtr; - WSManPluginOperationShutdownFuncPtr wsmanPluginOperationShutdownFuncPtr; // This ptr is not used in this environment, but is required to keep the memory layout identical between unmanaged and managed code. -} PwrshPluginWkr_Ptrs; - -class PlugInException -{ -public: - DWORD dwMessageId; - // This message is allocated outside the exception, but the exception frees - // the memory. - PWSTR extendedErrorInformation; - - PlugInException(DWORD msgId, __in_opt PWSTR msg) - { - dwMessageId = msgId; - extendedErrorInformation = msg; - } - - ~PlugInException() - { - if (NULL != extendedErrorInformation) - { - delete[] extendedErrorInformation; - extendedErrorInformation = NULL; - } - } -private: - // Provided without implementation to prevent automatic instantiation and copying - // since copying will lead to double frees given the existing code. - PlugInException(); - PlugInException(const PlugInException&); - PlugInException& operator=(const PlugInException&); -}; diff --git a/src/powershell-native/nativemsh/pwrshplugin/pwrshpluginerrorcodes.mc b/src/powershell-native/nativemsh/pwrshplugin/pwrshpluginerrorcodes.mc deleted file mode 100644 index 45e389e42da..00000000000 --- a/src/powershell-native/nativemsh/pwrshplugin/pwrshpluginerrorcodes.mc +++ /dev/null @@ -1,80 +0,0 @@ -;// Copyright (c) Microsoft Corporation. All rights reserved. - -;#undef FACILITY_POWERSHELL -FacilityNames=(PowerShell=84:FACILITY_POWERSHELL) -SeverityNames=(Success=0x0 - CoError=0x2 - ) - -MessageId=1001 -Facility=POWERSHELL -Severity=CoError -SymbolicName=g_INVALID_PLUGIN_CONTEXT -Language=English -The supplied plugin context is invalid. -. - -MessageId=1002 -Facility=POWERSHELL -Severity=CoError -SymbolicName=g_INVALID_INPUT -Language=English -Invalid parameter to plugin method %1!ls!. -. - -MessageId=1003 -Facility=POWERSHELL -Severity=CoError -SymbolicName=g_MANAGED_METHOD_RESOLUTION_FAILED -Language=English -Unable to find plugin methods WSManPluginShell, WSManPluginCommand, WSManPluginSend, WSManPluginReceive in the Managed plugin module. -. - -MessageId=1004 -Facility=POWERSHELL -Severity=CoError -SymbolicName=g_OPTION_SET_NOT_COMPLY -Language=English -Powershell plugin does not support the options requested. Make sure client is compatible with build %1!ls! of PowerShell. -. - -MessageId=1005 -Facility=POWERSHELL -Severity=CoError -SymbolicName=g_PSVERSION_NOT_FOUND_IN_CONFIG -Language=English -A "%1!ls!" name-value pair is expected in the "%2!ls!" element of the configuration xml. Contact your administrator. -. - -MessageId=1006 -Facility=POWERSHELL -Severity=CoError -SymbolicName=g_BAD_INITPARAMETERS -Language=English -The "%1!ls!" element in the configuration xml is badly formatted. Contact your administrator. -. - -MessageId=1007 -Facility=POWERSHELL -Severity=CoError -SymbolicName=g_INIT_CRITICALSECTION_FAILED -Language=English -An error occurred while initializing the plugin. Contact your administrator. -. - -MessageId=1008 -Facility=POWERSHELL -Severity=CoError -SymbolicName=g_CLR_LOAD_FAILED -Language=English -An error occurred while loading version %1!ls! of CLR. Contact your administrator. -. - -MessageId=1009 -Facility=POWERSHELL -Severity=CoError -SymbolicName=g_MANAGED_CONNECT_METHOD_RESOLUTION_FAILED -Language=English -An error occured while processing the connect operation. A relevant entry point is not found in the managed plugin module -Make sure that the configured plugin supports connect operation. -. diff --git a/src/powershell-native/nativemsh/pwrshplugin/version.rc b/src/powershell-native/nativemsh/pwrshplugin/version.rc deleted file mode 100644 index 016c85d0b83..00000000000 --- a/src/powershell-native/nativemsh/pwrshplugin/version.rc +++ /dev/null @@ -1,13 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -#include -#include - -#define VER_FILETYPE VFT_DLL -#define VER_FILESUBTYPE VFT2_UNKNOWN -#define VER_FILEDESCRIPTION_STR "pwrshplugin.dll" -#define VER_INTERNALNAME_STR "pwrshplugin.dll" -#define VER_ORIGINALFILENAME_STR "pwrshplugin.dll" - -#include diff --git a/src/powershell-native/windows-compiler-override.txt b/src/powershell-native/windows-compiler-override.txt deleted file mode 100644 index f6cb16856cd..00000000000 --- a/src/powershell-native/windows-compiler-override.txt +++ /dev/null @@ -1,16 +0,0 @@ -SET (CMAKE_C_FLAGS_INIT "/Wall /FC") -SET (CMAKE_C_FLAGS_DEBUG_INIT "/Od /Zi") -SET (CLR_C_FLAGS_CHECKED_INIT "/O1 /Zi") -SET (CMAKE_C_FLAGS_RELEASE_INIT "/Ox /Zi") -SET (CMAKE_C_FLAGS_RELWITHDEBINFO_INIT "/O2 /Zi") - -SET (CMAKE_CXX_FLAGS_INIT "/Wall /FC") -SET (CMAKE_CXX_FLAGS_DEBUG_INIT "/Od /Zi") -SET (CLR_CXX_FLAGS_CHECKED_INIT "/O1 /Zi") -SET (CMAKE_CXX_FLAGS_RELEASE_INIT "/Ox /Zi") -SET (CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT "/O2 /Zi") - -SET (CLR_DEFINES_DEBUG_INIT DEBUG _DEBUG _DBG URTBLDENV_FRIENDLY=Checked BUILDENV_CHECKED=1) -SET (CLR_DEFINES_CHECKED_INIT DEBUG _DEBUG _DBG URTBLDENV_FRIENDLY=Checked BUILDENV_CHECKED=1) -SET (CLR_DEFINES_RELEASE_INIT NDEBUG URTBLDENV_FRIENDLY=Retail) -SET (CLR_DEFINES_RELWITHDEBINFO_INIT NDEBUG URTBLDENV_FRIENDLY=Retail) \ No newline at end of file