Replace ConhostConnection with ConptyConnection (#3461)

This commit deletes ConhostConnection and replaces it with
ConptyConnection. The ConptyConnection uses CreatePseudoConsole and
depends on winconpty to override the one from kernel32.

* winconpty must be packageable, so I've added GetPackagingOutputs.
   * To validate this, I added conpty.dll to the MSIX regression script.
* I moved the code from conpty-universal that deals with environment
  strings into the types library.

This puts us in a way better place to implement #2563, as we can now
separately detect a failure to launch a pseudoconsole, a failure to
CreateProcess, and an unexpected termination of the launched process.

Fixes #1131.
This commit is contained in:
Dustin L. Howett (MSFT)
2019-11-06 15:09:01 -08:00
committed by GitHub
parent d2dcdef620
commit 357e835f5d
17 changed files with 531 additions and 897 deletions

View File

@@ -82,6 +82,10 @@ Try {
Throw "Failed to find cpprest_2_10.dll -- check the WAP packaging project"
}
}
If ($null -eq (Get-Item "$AppxPackageRootPath\conpty.dll" -EA:Ignore)) {
Throw "Failed to find conpty.dll -- check the wapproj and winconpty.vcxproj"
}
} Finally {
Remove-Item -Recurse -Force $AppxPackageRootPath
}

View File

@@ -59,18 +59,13 @@
<ProjectReference Include="..\WindowsTerminal\WindowsTerminal.vcxproj" />
<ProjectReference Include="..\..\host\exe\Host.EXE.vcxproj" />
</ItemGroup>
<!-- Stomp the path to conhost.exe.
This task will copy OpenConsole.exe to the appx as conhost.exe, and place it
adjacent to WindowsTerminal.exe.
-->
<Target Name="OpenConsoleStompSourceProjectForWapProject" BeforeTargets="_ConvertItems">
<ItemGroup>
<!-- Stomp all "SourceProject" values for all incoming dependencies to flatten the package. -->
<_TemporaryFilteredWapProjOutput Include="@(_FilteredNonWapProjProjectOutput)" />
<_FilteredNonWapProjProjectOutput Remove="@(_TemporaryFilteredWapProjOutput)" />
<_FilteredNonWapProjProjectOutput Include="@(_TemporaryFilteredWapProjOutput)">
<!-- Override the filename for OpenConsole.exe (only) -->
<TargetPath Condition="'%(Filename)' == 'OpenConsole' and '%(Extension)' == '.exe'">conhost.exe</TargetPath>
<!-- Blank the SourceProject here to vend all files into the root of the package. -->
<SourceProject>
</SourceProject>

View File

@@ -459,12 +459,12 @@ namespace winrt::TerminalApp::implementation
else
{
auto conhostConn = TerminalConnection::ConhostConnection(settings.Commandline(),
settings.StartingDirectory(),
settings.StartingTitle(),
settings.InitialRows(),
settings.InitialCols(),
winrt::guid());
auto conhostConn = TerminalConnection::ConptyConnection(settings.Commandline(),
settings.StartingDirectory(),
settings.StartingTitle(),
settings.InitialRows(),
settings.InitialCols(),
winrt::guid());
sessionGuid = conhostConn.Guid();
connection = conhostConn;
}

View File

@@ -1,238 +0,0 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "pch.h"
#include "ConhostConnection.h"
#include "windows.h"
#include <sstream>
#include "ConhostConnection.g.cpp"
#include <conpty-universal.h>
#include "../../types/inc/Utils.hpp"
#include "../../types/inc/UTF8OutPipeReader.hpp"
using namespace ::Microsoft::Console;
namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
{
ConhostConnection::ConhostConnection(const hstring& commandline,
const hstring& startingDirectory,
const hstring& startingTitle,
const uint32_t initialRows,
const uint32_t initialCols,
const guid& initialGuid) :
_initialRows{ initialRows },
_initialCols{ initialCols },
_commandline{ commandline },
_startingDirectory{ startingDirectory },
_startingTitle{ startingTitle },
_guid{ initialGuid }
{
if (_guid == guid{})
{
_guid = Utils::CreateGuid();
}
}
winrt::guid ConhostConnection::Guid() const noexcept
{
return _guid;
}
winrt::event_token ConhostConnection::TerminalOutput(Microsoft::Terminal::TerminalConnection::TerminalOutputEventArgs const& handler)
{
return _outputHandlers.add(handler);
}
void ConhostConnection::TerminalOutput(winrt::event_token const& token) noexcept
{
_outputHandlers.remove(token);
}
winrt::event_token ConhostConnection::TerminalDisconnected(Microsoft::Terminal::TerminalConnection::TerminalDisconnectedEventArgs const& handler)
{
return _disconnectHandlers.add(handler);
}
void ConhostConnection::TerminalDisconnected(winrt::event_token const& token) noexcept
{
_disconnectHandlers.remove(token);
}
void ConhostConnection::Start()
{
std::wstring cmdline{ _commandline.c_str() };
std::optional<std::wstring> startingDirectory;
if (!_startingDirectory.empty())
{
startingDirectory = _startingDirectory;
}
EnvironmentVariableMapW extraEnvVars;
{
// Convert connection Guid to string and ignore the enclosing '{}'.
std::wstring wsGuid{ Utils::GuidToString(_guid) };
wsGuid.pop_back();
const wchar_t* const pwszGuid{ wsGuid.data() + 1 };
// Ensure every connection has the unique identifier in the environment.
extraEnvVars.emplace(L"WT_SESSION", pwszGuid);
}
STARTUPINFO si = { 0 };
si.cb = sizeof(STARTUPINFOW);
// If we have a startingTitle, create a mutable character buffer to add
// it to the STARTUPINFO.
std::unique_ptr<wchar_t[]> mutableTitle{ nullptr };
if (!_startingTitle.empty())
{
mutableTitle = std::make_unique<wchar_t[]>(_startingTitle.size() + 1);
THROW_IF_NULL_ALLOC(mutableTitle);
THROW_IF_FAILED(StringCchCopy(mutableTitle.get(), _startingTitle.size() + 1, _startingTitle.c_str()));
si.lpTitle = mutableTitle.get();
}
THROW_IF_FAILED(
CreateConPty(cmdline,
startingDirectory,
static_cast<short>(_initialCols),
static_cast<short>(_initialRows),
&_inPipe,
&_outPipe,
&_signalPipe,
&_piConhost,
0,
si,
extraEnvVars));
_startTime = std::chrono::high_resolution_clock::now();
// Create our own output handling thread
// This must be done after the pipes are populated.
// Each connection needs to make sure to drain the output from its backing host.
_hOutputThread.reset(CreateThread(nullptr,
0,
StaticOutputThreadProc,
this,
0,
nullptr));
THROW_LAST_ERROR_IF_NULL(_hOutputThread);
_connected = true;
}
void ConhostConnection::WriteInput(hstring const& data)
{
if (!_connected || _closing.load())
{
return;
}
// convert from UTF-16LE to UTF-8 as ConPty expects UTF-8
std::string str = winrt::to_string(data);
bool fSuccess = !!WriteFile(_inPipe.get(), str.c_str(), (DWORD)str.length(), nullptr, nullptr);
fSuccess;
}
void ConhostConnection::Resize(uint32_t rows, uint32_t columns)
{
if (!_connected)
{
_initialRows = rows;
_initialCols = columns;
}
else if (!_closing.load())
{
SignalResizeWindow(_signalPipe.get(), Utils::ClampToShortMax(columns, 1), Utils::ClampToShortMax(rows, 1));
}
}
void ConhostConnection::Close()
{
if (!_connected)
{
return;
}
if (!_closing.exchange(true))
{
// It is imperative that the signal pipe be closed first; this triggers the
// pseudoconsole host's teardown. See PtySignalInputThread.cpp.
_signalPipe.reset();
_inPipe.reset();
_outPipe.reset();
// Tear down our output thread -- now that the output pipe was closed on the
// far side, we can run down our local reader.
WaitForSingleObject(_hOutputThread.get(), INFINITE);
_hOutputThread.reset();
// Wait for conhost to terminate.
WaitForSingleObject(_piConhost.hProcess, INFINITE);
_hJob.reset(); // This is a formality.
_piConhost.reset();
}
}
DWORD WINAPI ConhostConnection::StaticOutputThreadProc(LPVOID lpParameter)
{
ConhostConnection* const pInstance = (ConhostConnection*)lpParameter;
return pInstance->_OutputThread();
}
DWORD ConhostConnection::_OutputThread()
{
UTF8OutPipeReader pipeReader{ _outPipe.get() };
std::string_view strView{};
// process the data of the output pipe in a loop
while (true)
{
HRESULT result = pipeReader.Read(strView);
if (FAILED(result) || result == S_FALSE)
{
if (_closing.load())
{
// This is okay, break out to kill the thread
return 0;
}
_disconnectHandlers();
return (DWORD)-1;
}
if (strView.empty())
{
return 0;
}
if (!_recievedFirstByte)
{
auto now = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> delta = now - _startTime;
TraceLoggingWrite(g_hTerminalConnectionProvider,
"RecievedFirstByte",
TraceLoggingDescription("An event emitted when the connection recieves the first byte"),
TraceLoggingGuid(_guid, "SessionGuid", "The WT_SESSION's GUID"),
TraceLoggingFloat64(delta.count(), "Duration"),
TraceLoggingKeyword(MICROSOFT_KEYWORD_MEASURES),
TelemetryPrivacyDataTag(PDT_ProductAndServicePerformance));
_recievedFirstByte = true;
}
// Convert buffer to hstring
auto hstr{ winrt::to_hstring(strView) };
// Pass the output to our registered event handlers
_outputHandlers(hstr);
}
return 0;
}
}

View File

@@ -1,58 +0,0 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#pragma once
#include "ConhostConnection.g.h"
namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
{
struct ConhostConnection : ConhostConnectionT<ConhostConnection>
{
ConhostConnection(const hstring& cmdline, const hstring& startingDirectory, const hstring& startingTitle, const uint32_t rows, const uint32_t cols, const guid& guid);
winrt::event_token TerminalOutput(TerminalConnection::TerminalOutputEventArgs const& handler);
void TerminalOutput(winrt::event_token const& token) noexcept;
winrt::event_token TerminalDisconnected(TerminalConnection::TerminalDisconnectedEventArgs const& handler);
void TerminalDisconnected(winrt::event_token const& token) noexcept;
void Start();
void WriteInput(hstring const& data);
void Resize(uint32_t rows, uint32_t columns);
void Close();
winrt::guid Guid() const noexcept;
private:
winrt::event<TerminalConnection::TerminalOutputEventArgs> _outputHandlers;
winrt::event<TerminalConnection::TerminalDisconnectedEventArgs> _disconnectHandlers;
uint32_t _initialRows{};
uint32_t _initialCols{};
hstring _commandline;
hstring _startingDirectory;
hstring _startingTitle;
guid _guid{}; // A unique session identifier for connected client
bool _connected{};
std::atomic<bool> _closing{ false };
bool _recievedFirstByte{ false };
std::chrono::high_resolution_clock::time_point _startTime{};
wil::unique_hfile _inPipe; // The pipe for writing input to
wil::unique_hfile _outPipe; // The pipe for reading output from
wil::unique_hfile _signalPipe;
wil::unique_handle _hOutputThread;
wil::unique_process_information _piConhost;
wil::unique_handle _hJob;
static DWORD WINAPI StaticOutputThreadProc(LPVOID lpParameter);
DWORD _OutputThread();
};
}
namespace winrt::Microsoft::Terminal::TerminalConnection::factory_implementation
{
struct ConhostConnection : ConhostConnectionT<ConhostConnection, implementation::ConhostConnection>
{
};
}

View File

@@ -1,15 +0,0 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import "ITerminalConnection.idl";
namespace Microsoft.Terminal.TerminalConnection
{
[default_interface] runtimeclass ConhostConnection : ITerminalConnection
{
ConhostConnection(String cmdline, String startingDirectory, String startingTitle, UInt32 rows, UInt32 columns, Guid guid);
Guid Guid { get; };
};
}

View File

@@ -4,27 +4,151 @@
#include "pch.h"
#include "ConptyConnection.h"
#include <Windows.h>
#include <windows.h>
#include "ConptyConnection.g.cpp"
#include "../../types/inc/Utils.hpp"
#include "../../types/inc/Environment.hpp"
#include "../../types/inc/UTF8OutPipeReader.hpp"
using namespace ::Microsoft::Console;
namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
{
ConptyConnection::ConptyConnection(hstring const& commandline,
uint32_t initialRows,
uint32_t initialCols) :
_connected{ false },
_inPipe{ INVALID_HANDLE_VALUE },
_outPipe{ INVALID_HANDLE_VALUE },
_hPC{ INVALID_HANDLE_VALUE },
_outputThreadId{ 0 },
_hOutputThread{ INVALID_HANDLE_VALUE },
_piClient{ 0 }
// Function Description:
// - creates some basic anonymous pipes and passes them to CreatePseudoConsole
// Arguments:
// - size: The size of the conpty to create, in characters.
// - phInput: Receives the handle to the newly-created anonymous pipe for writing input to the conpty.
// - phOutput: Receives the handle to the newly-created anonymous pipe for reading the output of the conpty.
// - phPc: Receives a token value to identify this conpty
static HRESULT _CreatePseudoConsoleAndPipes(const COORD size, const DWORD dwFlags, HANDLE* phInput, HANDLE* phOutput, HPCON* phPC)
{
_commandline = commandline;
_initialRows = initialRows;
_initialCols = initialCols;
RETURN_HR_IF(E_INVALIDARG, phPC == nullptr || phInput == nullptr || phOutput == nullptr);
wil::unique_hfile outPipeOurSide, outPipePseudoConsoleSide;
wil::unique_hfile inPipeOurSide, inPipePseudoConsoleSide;
RETURN_IF_WIN32_BOOL_FALSE(CreatePipe(&inPipePseudoConsoleSide, &inPipeOurSide, NULL, 0));
RETURN_IF_WIN32_BOOL_FALSE(CreatePipe(&outPipeOurSide, &outPipePseudoConsoleSide, NULL, 0));
RETURN_IF_FAILED(CreatePseudoConsole(size, inPipePseudoConsoleSide.get(), outPipePseudoConsoleSide.get(), dwFlags, phPC));
*phInput = inPipeOurSide.release();
*phOutput = outPipeOurSide.release();
return S_OK;
}
winrt::event_token ConptyConnection::TerminalOutput(TerminalConnection::TerminalOutputEventArgs const& handler)
// Function Description:
// - launches the client application attached to the new pseudoconsole
HRESULT ConptyConnection::_LaunchAttachedClient() noexcept
{
STARTUPINFOEX siEx{ 0 };
siEx.StartupInfo.cb = sizeof(STARTUPINFOEX);
siEx.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
size_t size{};
// This call will return an error (by design); we are ignoring it.
InitializeProcThreadAttributeList(NULL, 1, 0, (PSIZE_T)&size);
auto attrList{ std::make_unique<std::byte[]>(size) };
siEx.lpAttributeList = reinterpret_cast<PPROC_THREAD_ATTRIBUTE_LIST>(attrList.get());
RETURN_IF_WIN32_BOOL_FALSE(InitializeProcThreadAttributeList(siEx.lpAttributeList, 1, 0, (PSIZE_T)&size));
RETURN_IF_WIN32_BOOL_FALSE(UpdateProcThreadAttribute(siEx.lpAttributeList,
0,
PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,
_hPC.get(),
sizeof(HPCON),
NULL,
NULL));
std::wstring cmdline{ _commandline.c_str() }; // mutable copy -- required for CreateProcessW
Utils::EnvironmentVariableMapW environment;
{
// Convert connection Guid to string and ignore the enclosing '{}'.
std::wstring wsGuid{ Utils::GuidToString(_guid) };
wsGuid.pop_back();
const wchar_t* const pwszGuid{ wsGuid.data() + 1 };
// Ensure every connection has the unique identifier in the environment.
environment.emplace(L"WT_SESSION", pwszGuid);
}
std::vector<wchar_t> newEnvVars;
auto zeroNewEnv = wil::scope_exit([&] {
::SecureZeroMemory(newEnvVars.data(),
newEnvVars.size() * sizeof(decltype(newEnvVars.begin())::value_type));
});
auto zeroEnvMap = wil::scope_exit([&] {
// Can't zero the keys, but at least we can zero the values.
for (auto& [name, value] : environment)
{
::SecureZeroMemory(value.data(), value.size() * sizeof(decltype(value.begin())::value_type));
}
environment.clear();
});
RETURN_IF_FAILED(Utils::UpdateEnvironmentMapW(environment));
RETURN_IF_FAILED(Utils::EnvironmentMapToEnvironmentStringsW(environment, newEnvVars));
LPWCH lpEnvironment = newEnvVars.empty() ? nullptr : newEnvVars.data();
// If we have a startingTitle, create a mutable character buffer to add
// it to the STARTUPINFO.
std::wstring mutableTitle{};
if (!_startingTitle.empty())
{
mutableTitle = _startingTitle;
siEx.StartupInfo.lpTitle = mutableTitle.data();
}
RETURN_IF_WIN32_BOOL_FALSE(CreateProcessW(
nullptr,
cmdline.data(),
nullptr, // lpProcessAttributes
nullptr, // lpThreadAttributes
false, // bInheritHandles
EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT, // dwCreationFlags
lpEnvironment, // lpEnvironment
_startingDirectory.c_str(),
&siEx.StartupInfo, // lpStartupInfo
&_piClient // lpProcessInformation
));
DeleteProcThreadAttributeList(siEx.lpAttributeList);
return S_OK;
}
ConptyConnection::ConptyConnection(const hstring& commandline,
const hstring& startingDirectory,
const hstring& startingTitle,
const uint32_t initialRows,
const uint32_t initialCols,
const guid& initialGuid) :
_initialRows{ initialRows },
_initialCols{ initialCols },
_commandline{ commandline },
_startingDirectory{ startingDirectory },
_startingTitle{ startingTitle },
_guid{ initialGuid }
{
if (_guid == guid{})
{
_guid = Utils::CreateGuid();
}
}
winrt::guid ConptyConnection::Guid() const noexcept
{
return _guid;
}
winrt::event_token ConptyConnection::TerminalOutput(Microsoft::Terminal::TerminalConnection::TerminalOutputEventArgs const& handler)
{
return _outputHandlers.add(handler);
}
@@ -34,223 +158,176 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
_outputHandlers.remove(token);
}
winrt::event_token ConptyConnection::TerminalDisconnected(TerminalConnection::TerminalDisconnectedEventArgs const& handler)
winrt::event_token ConptyConnection::TerminalDisconnected(Microsoft::Terminal::TerminalConnection::TerminalDisconnectedEventArgs const& handler)
{
handler;
throw hresult_not_implemented();
return _disconnectHandlers.add(handler);
}
void ConptyConnection::TerminalDisconnected(winrt::event_token const& token) noexcept
{
token;
// throw hresult_not_implemented();
_disconnectHandlers.remove(token);
}
void ConptyConnection::Start()
try
{
_CreatePseudoConsole();
const COORD dimensions{ gsl::narrow_cast<SHORT>(_initialCols), gsl::narrow_cast<SHORT>(_initialRows) };
THROW_IF_FAILED(_CreatePseudoConsoleAndPipes(dimensions, 0, &_inPipe, &_outPipe, &_hPC));
THROW_IF_FAILED(_LaunchAttachedClient());
_connected = true;
_startTime = std::chrono::high_resolution_clock::now();
// Create our own output handling thread
// Each console needs to make sure to drain the output from it's backing host.
_outputThreadId = (DWORD)-1;
_hOutputThread = CreateThread(nullptr,
0,
StaticOutputThreadProc,
this,
0,
&_outputThreadId);
// This must be done after the pipes are populated.
// Each connection needs to make sure to drain the output from its backing host.
_hOutputThread.reset(CreateThread(
nullptr,
0,
[](LPVOID lpParameter) {
ConptyConnection* const pInstance = reinterpret_cast<ConptyConnection*>(lpParameter);
return pInstance->_OutputThread();
},
this,
0,
nullptr));
//// When we recieve some data:
//hstring outputFromConpty = L"hello world";
////TerminalOutputEventArgs args(outputFromConpty);
////_outputHandlers(*this, args);
//_outputHandlers(outputFromConpty);
THROW_LAST_ERROR_IF_NULL(_hOutputThread);
_clientExitWait.reset(CreateThreadpoolWait(
[](PTP_CALLBACK_INSTANCE /*callbackInstance*/, PVOID context, PTP_WAIT /*wait*/, TP_WAIT_RESULT /*waitResult*/) {
ConptyConnection* const pInstance = reinterpret_cast<ConptyConnection*>(context);
pInstance->_ClientTerminated();
},
this,
nullptr));
SetThreadpoolWait(_clientExitWait.get(), _piClient.hProcess, nullptr);
_connected = true;
}
catch (...)
{
const auto hr = wil::ResultFromCaughtException();
// TODO GH#2563 - signal a transition into failed state here!
LOG_HR(hr);
_disconnectHandlers();
}
void ConptyConnection::_ClientTerminated() noexcept
{
if (_closing.load())
{
// This is okay, break out to kill the thread
return;
}
// TODO GH#2563 - get the exit code from the process and see whether it was a failing one.
_disconnectHandlers();
}
void ConptyConnection::WriteInput(hstring const& data)
{
data;
if (!_connected || _closing.load())
{
return;
}
throw hresult_not_implemented();
// convert from UTF-16LE to UTF-8 as ConPty expects UTF-8
// TODO GH#3378 reconcile and unify UTF-8 converters
std::string str = winrt::to_string(data);
LOG_IF_WIN32_BOOL_FALSE(WriteFile(_inPipe.get(), str.c_str(), (DWORD)str.length(), nullptr, nullptr));
}
void ConptyConnection::Resize(uint32_t rows, uint32_t columns)
{
rows;
columns;
throw hresult_not_implemented();
if (!_hPC)
{
_initialRows = rows;
_initialCols = columns;
}
else if (!_closing.load())
{
THROW_IF_FAILED(ResizePseudoConsole(_hPC.get(), { Utils::ClampToShortMax(columns, 1), Utils::ClampToShortMax(rows, 1) }));
}
}
void ConptyConnection::Close()
{
// TODO:
// terminate the output thread
// Close our handles
// Close the Pseudoconsole
// terminate our processes
throw hresult_not_implemented();
}
// Function Description:
// - Sample function which combines the creation of some basic anonymous pipes
// and passes them to CreatePseudoConsole.
// Arguments:
// - size: The size of the conpty to create, in characters.
// - phInput: Receives the handle to the newly-created anonymous pipe for writing input to the conpty.
// - phOutput: Receives the handle to the newly-created anonymous pipe for reading the output of the conpty.
// - phPty: Receives a token value to identify this conpty
HRESULT _CreatePseudoConsoleAndHandles(COORD size,
_In_ DWORD dwFlags,
_Out_ HANDLE* phInput,
_Out_ HANDLE* phOutput,
_Out_ HPCON* phPC)
{
if (phPC == NULL || phInput == NULL || phOutput == NULL)
if (!_connected)
{
return E_INVALIDARG;
return;
}
HANDLE outPipeOurSide;
HANDLE inPipeOurSide;
HANDLE outPipePseudoConsoleSide;
HANDLE inPipePseudoConsoleSide;
HRESULT hr = S_OK;
if (!CreatePipe(&inPipePseudoConsoleSide, &inPipeOurSide, NULL, 0))
if (!_closing.exchange(true))
{
hr = HRESULT_FROM_WIN32(GetLastError());
_clientExitWait.reset(); // immediately stop waiting for the client to exit.
_hPC.reset();
_inPipe.reset();
_outPipe.reset();
// Tear down our output thread -- now that the output pipe was closed on the
// far side, we can run down our local reader.
LOG_LAST_ERROR_IF(WAIT_FAILED == WaitForSingleObject(_hOutputThread.get(), INFINITE));
_hOutputThread.reset();
// Wait for the client to terminate.
LOG_LAST_ERROR_IF(WAIT_FAILED == WaitForSingleObject(_piClient.hProcess, INFINITE));
_piClient.reset();
}
if (SUCCEEDED(hr))
{
if (!CreatePipe(&outPipeOurSide, &outPipePseudoConsoleSide, NULL, 0))
{
hr = HRESULT_FROM_WIN32(GetLastError());
}
if (SUCCEEDED(hr))
{
hr = CreatePseudoConsole(size, inPipePseudoConsoleSide, outPipePseudoConsoleSide, dwFlags, phPC);
if (FAILED(hr))
{
CloseHandle(inPipeOurSide);
CloseHandle(outPipeOurSide);
}
else
{
*phInput = inPipeOurSide;
*phOutput = outPipeOurSide;
}
CloseHandle(outPipePseudoConsoleSide);
}
else
{
CloseHandle(inPipeOurSide);
}
CloseHandle(inPipePseudoConsoleSide);
}
return hr;
}
// Prepares the `lpAttributeList` member of a STARTUPINFOEX for attaching a
// client application to a pseudoconsole.
// Prior to calling this function, hPty should be initialized with a call to
// CreatePseudoConsole, and the pAttrList should be initialized with a call
// to InitializeProcThreadAttributeList. The caller of
// InitializeProcThreadAttributeList should add one to the dwAttributeCount
// param when creating the attribute list for usage by this function.
HRESULT _AttachPseudoConsole(HPCON hPC, LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList)
{
BOOL fSuccess = UpdateProcThreadAttribute(lpAttributeList,
0,
PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,
hPC,
sizeof(HPCON),
NULL,
NULL);
return fSuccess ? S_OK : HRESULT_FROM_WIN32(GetLastError());
}
void ConptyConnection::_CreatePseudoConsole()
{
bool fSuccess;
COORD dimensions{ _initialCols, _initialRows };
THROW_IF_FAILED(_CreatePseudoConsoleAndHandles(dimensions, 0, &_inPipe, &_outPipe, &_hPC));
STARTUPINFOEX siEx;
siEx = { 0 };
siEx.StartupInfo.cb = sizeof(STARTUPINFOEX);
size_t size;
InitializeProcThreadAttributeList(NULL, 1, 0, (PSIZE_T)&size);
BYTE* attrList = new BYTE[size];
siEx.lpAttributeList = reinterpret_cast<PPROC_THREAD_ATTRIBUTE_LIST>(attrList);
fSuccess = InitializeProcThreadAttributeList(siEx.lpAttributeList, 1, 0, (PSIZE_T)&size);
THROW_LAST_ERROR_IF(!fSuccess);
THROW_IF_FAILED(_AttachPseudoConsole(_hPC, siEx.lpAttributeList));
std::wstring realCommand = _commandline.c_str(); //winrt::to_string(_commandline);
if (realCommand == L"")
{
realCommand = L"cmd.exe";
}
std::unique_ptr<wchar_t[]> mutableCommandline = std::make_unique<wchar_t[]>(realCommand.length() + 1);
THROW_IF_NULL_ALLOC(mutableCommandline);
HRESULT hr = StringCchCopy(mutableCommandline.get(), realCommand.length() + 1, realCommand.c_str());
THROW_IF_FAILED(hr);
fSuccess = !!CreateProcessW(
nullptr,
mutableCommandline.get(),
nullptr, // lpProcessAttributes
nullptr, // lpThreadAttributes
true, // bInheritHandles
EXTENDED_STARTUPINFO_PRESENT, // dwCreationFlags
nullptr, // lpEnvironment
nullptr, // lpCurrentDirectory
&siEx.StartupInfo, // lpStartupInfo
&_piClient // lpProcessInformation
);
THROW_LAST_ERROR_IF(!fSuccess);
DeleteProcThreadAttributeList(siEx.lpAttributeList);
}
DWORD WINAPI ConptyConnection::StaticOutputThreadProc(LPVOID lpParameter)
{
ConptyConnection* const pInstance = (ConptyConnection*)lpParameter;
return pInstance->_OutputThread();
}
DWORD ConptyConnection::_OutputThread()
{
BYTE buffer[256];
DWORD dwRead;
UTF8OutPipeReader pipeReader{ _outPipe.get() };
std::string_view strView{};
// process the data of the output pipe in a loop
while (true)
{
dwRead = 0;
bool fSuccess = false;
HRESULT result = pipeReader.Read(strView);
if (FAILED(result) || result == S_FALSE)
{
if (_closing.load())
{
// This is okay, break out to kill the thread
return 0;
}
fSuccess = !!ReadFile(_outPipe, buffer, ARRAYSIZE(buffer), &dwRead, nullptr);
_disconnectHandlers();
return (DWORD)-1;
}
THROW_LAST_ERROR_IF(!fSuccess);
if (strView.empty())
{
return 0;
}
if (!_recievedFirstByte)
{
auto now = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> delta = now - _startTime;
TraceLoggingWrite(g_hTerminalConnectionProvider,
"RecievedFirstByte",
TraceLoggingDescription("An event emitted when the connection recieves the first byte"),
TraceLoggingGuid(_guid, "SessionGuid", "The WT_SESSION's GUID"),
TraceLoggingFloat64(delta.count(), "Duration"),
TraceLoggingKeyword(MICROSOFT_KEYWORD_MEASURES),
TelemetryPrivacyDataTag(PDT_ProductAndServicePerformance));
_recievedFirstByte = true;
}
// Convert buffer to hstring
char* pchStr = (char*)(buffer);
std::string str{ pchStr, dwRead };
auto hstr = winrt::to_hstring(str);
auto hstr{ winrt::to_hstring(strView) };
// Pass the output to our registered event handlers
_outputHandlers(hstr);
// if (this->_active)
// {
// _pfnReadCallback(buffer, dwRead);
// }
}
return 0;
}
}

View File

@@ -4,16 +4,18 @@
#pragma once
#include "ConptyConnection.g.h"
// Note that the ConptyConnection is no longer a part of this project
// Until there's platform-level support for full-trust universal applications,
// all ProcThreadAttribute things will be unusable. Unfortunately, this means
// we'll be unable to use the conpty API directly.
namespace wil
{
// These belong in WIL upstream, so when we reingest the change that has them we'll get rid of ours.
using unique_pseudoconsole_handle = wil::unique_any<HPCON, decltype(&::ClosePseudoConsole), ::ClosePseudoConsole>;
}
namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
{
struct ConptyConnection : ConptyConnectionT<ConptyConnection>
{
ConptyConnection() = delete;
ConptyConnection(hstring const& commandline, uint32_t initialRows, uint32_t initialCols);
ConptyConnection(const hstring& cmdline, const hstring& startingDirectory, const hstring& startingTitle, const uint32_t rows, const uint32_t cols, const guid& guid);
winrt::event_token TerminalOutput(TerminalConnection::TerminalOutputEventArgs const& handler);
void TerminalOutput(winrt::event_token const& token) noexcept;
@@ -24,23 +26,34 @@ namespace winrt::Microsoft::Terminal::TerminalConnection::implementation
void Resize(uint32_t rows, uint32_t columns);
void Close();
winrt::guid Guid() const noexcept;
private:
HRESULT _LaunchAttachedClient() noexcept;
void _ClientTerminated() noexcept;
winrt::event<TerminalConnection::TerminalOutputEventArgs> _outputHandlers;
winrt::event<TerminalConnection::TerminalDisconnectedEventArgs> _disconnectHandlers;
uint32_t _initialRows;
uint32_t _initialCols;
uint32_t _initialRows{};
uint32_t _initialCols{};
hstring _commandline;
hstring _startingDirectory;
hstring _startingTitle;
guid _guid{}; // A unique session identifier for connected client
bool _connected;
HANDLE _inPipe; // The pipe for writing input to
HANDLE _outPipe; // The pipe for reading output from
HPCON _hPC;
DWORD _outputThreadId;
HANDLE _hOutputThread;
PROCESS_INFORMATION _piClient;
bool _connected{};
std::atomic<bool> _closing{ false };
bool _recievedFirstByte{ false };
std::chrono::high_resolution_clock::time_point _startTime{};
wil::unique_hfile _inPipe; // The pipe for writing input to
wil::unique_hfile _outPipe; // The pipe for reading output from
wil::unique_handle _hOutputThread;
wil::unique_process_information _piClient;
wil::unique_pseudoconsole_handle _hPC;
wil::unique_threadpool_wait _clientExitWait;
static DWORD WINAPI StaticOutputThreadProc(LPVOID lpParameter);
void _CreatePseudoConsole();
DWORD _OutputThread();
};
}

View File

@@ -8,7 +8,8 @@ namespace Microsoft.Terminal.TerminalConnection
[default_interface]
runtimeclass ConptyConnection : ITerminalConnection
{
ConptyConnection(String commandline, UInt32 initialRows, UInt32 initialCols);
ConptyConnection(String cmdline, String startingDirectory, String startingTitle, UInt32 rows, UInt32 columns, Guid guid);
Guid Guid { get; };
};
}

View File

@@ -35,8 +35,8 @@
<ClInclude Include="AzureConnection-ARM64.h" Condition="'$(Platform)'=='ARM64'" />
<ClInclude Include="AzureConnectionStrings.h" Condition="'$(Platform)'!='ARM64'" />
<ClInclude Include="pch.h" />
<ClInclude Include="ConhostConnection.h">
<DependentUpon>ConhostConnection.idl</DependentUpon>
<ClInclude Include="ConptyConnection.h">
<DependentUpon>ConptyConnection.idl</DependentUpon>
</ClInclude>
<ClInclude Include="EchoConnection.h">
<DependentUpon>EchoConnection.idl</DependentUpon>
@@ -49,17 +49,17 @@
<ClCompile Include="pch.cpp">
<PrecompiledHeader>Create</PrecompiledHeader>
</ClCompile>
<ClCompile Include="ConhostConnection.cpp">
<DependentUpon>ConhostConnection.idl</DependentUpon>
</ClCompile>
<ClCompile Include="EchoConnection.cpp">
<DependentUpon>EchoConnection.idl</DependentUpon>
</ClCompile>
<ClCompile Include="ConptyConnection.cpp">
<DependentUpon>ConptyConnection.idl</DependentUpon>
</ClCompile>
<ClCompile Include="$(GeneratedFilesDir)module.g.cpp" />
</ItemGroup>
<ItemGroup>
<Midl Include="ITerminalConnection.idl" />
<Midl Include="ConhostConnection.idl" />
<Midl Include="ConptyConnection.idl" />
<Midl Include="EchoConnection.idl" />
<Midl Include="AzureConnection.idl" />
</ItemGroup>
@@ -77,6 +77,9 @@
<ProjectReference Include="$(OpenConsoleDir)src\types\lib\types.vcxproj">
<Project>{18D09A24-8240-42D6-8CB6-236EEE820263}</Project>
</ProjectReference>
<ProjectReference Include="..\..\winconpty\winconpty.vcxproj">
<Project>{58a03bb2-df5a-4b66-91a0-7ef3ba01269a}</Project>
</ProjectReference>
</ItemGroup>
<Import Project="$(OpenConsoleDir)src\cppwinrt.build.post.props" />
@@ -88,4 +91,10 @@
</PropertyGroup>
<Error Condition="!Exists('..\..\..\packages\vcpkg-cpprestsdk.2.10.0\build\native\vcpkg-cpprestsdk.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\..\packages\vcpkg-cpprestsdk.2.10.0\build\native\vcpkg-cpprestsdk.targets'))" />
</Target>
<ItemDefinitionGroup>
<Link>
<AdditionalDependencies>$(OpenConsoleCommonOutDir)\conpty.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
</Project>

View File

@@ -12,23 +12,22 @@
<ItemGroup>
<ClCompile Include="pch.cpp" />
<ClCompile Include="EchoConnection.cpp" />
<ClCompile Include="ConhostConnection.cpp" />
<ClCompile Include="$(GeneratedFilesDir)module.g.cpp" />
<ClCompile Include="AzureConnection.cpp" />
<ClCompile Include="init.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="pch.h" />
<ClInclude Include="EchoConnection.h" />
<ClInclude Include="ConhostConnection.h" />
<ClInclude Include="AzureConnection.h" />
<ClInclude Include="AzureClientID.h" />
<ClInclude Include="AzureConnectionStrings.h" />
</ItemGroup>
<ItemGroup>
<Midl Include="ITerminalConnection.idl" />
<Midl Include="ConhostConnection.idl" />
<Midl Include="EchoConnection.idl" />
<Midl Include="AzureConnection.idl" />
<Midl Include="ConptyConnection.idl" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />

View File

@@ -11,6 +11,10 @@
<OutDir>$(SolutionDir)bin\$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)obj\$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<PropertyGroup>
<!-- This one is always set so that non-redirected projects can depend on it. -->
<OpenConsoleCommonOutDir>$(SolutionDir)bin\$(Platform)\$(Configuration)\</OpenConsoleCommonOutDir>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />

View File

@@ -1,358 +0,0 @@
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
//
// WARNING!!!
// This is a fork of conpty.h
// It has some small modifications to help debug conhost-backed pseudoconsoles
// within the context of Universal Applications. Notably:
// * SetHandleInformation and HANDLE_FLAG_INHERIT are not present in
// WINAPI_PARTITION_APP, so we're just leaving the handles inheritable for
// now. This is definitely a bug, but the ConhostConnection isn't meant to
// be shipping code. Conhosts created by this version of CreateConPty will
// only go away when the app is closed, not when the pipes are broken.
// Fortunately, because the universal app is containered, they'll be
// cleaned up when the app is terminated. IF YOU USE THIS HEADER OUTSIDE OF
// A UNIVERSAL APP, THE CHILD CONHOST.EXE PROCESSES WILL NOT BE TERMINATED.
// * Whoever includes this will also need to define STARTF_USESTDHANDLES:
// ```
// #ifndef STARTF_USESTDHANDLES
// #define STARTF_USESTDHANDLES 0x00000100
// #endif
// ```
#include <windows.h>
#include <string>
#include <sstream>
#include <strsafe.h>
#include <memory>
#pragma once
const unsigned int PTY_SIGNAL_RESIZE_WINDOW = 8u;
// A case-insensitive wide-character map is used to store environment variables
// due to documented requirements:
//
// "All strings in the environment block must be sorted alphabetically by name.
// The sort is case-insensitive, Unicode order, without regard to locale.
// Because the equal sign is a separator, it must not be used in the name of
// an environment variable."
// https://docs.microsoft.com/en-us/windows/desktop/ProcThread/changing-environment-variables
//
struct WStringCaseInsensitiveCompare
{
[[nodiscard]] bool operator()(const std::wstring& lhs, const std::wstring& rhs) const noexcept
{
return (::_wcsicmp(lhs.c_str(), rhs.c_str()) < 0);
}
};
using EnvironmentVariableMapW = std::map<std::wstring, std::wstring, WStringCaseInsensitiveCompare>;
[[nodiscard]] HRESULT CreateConPty(const std::wstring& cmdline,
const unsigned short w,
const unsigned short h,
HANDLE* const hInput,
HANDLE* const hOutput,
HANDLE* const hSignal,
PROCESS_INFORMATION* const piPty,
DWORD dwCreationFlags = 0,
const EnvironmentVariableMapW& extraEnvVars = {}) noexcept;
bool SignalResizeWindow(const HANDLE hSignal,
const unsigned short w,
const unsigned short h);
[[nodiscard]] HRESULT UpdateEnvironmentMapW(EnvironmentVariableMapW& map) noexcept;
[[nodiscard]] HRESULT EnvironmentMapToEnvironmentStringsW(EnvironmentVariableMapW& map,
std::vector<wchar_t>& newEnvVars) noexcept;
// Function Description:
// - Updates an EnvironmentVariableMapW with the current process's unicode
// environment variables ignoring ones already set in the provided map.
// Arguments:
// - map: The map to populate with the current processes's environment variables.
// Return Value:
// - S_OK if we succeeded, or an appropriate HRESULT for failing
[[nodiscard]] __declspec(noinline) inline HRESULT UpdateEnvironmentMapW(EnvironmentVariableMapW& map) noexcept
{
LPWCH currentEnvVars{};
auto freeCurrentEnv = wil::scope_exit([&] {
if (currentEnvVars)
{
(void)FreeEnvironmentStringsW(currentEnvVars);
currentEnvVars = nullptr;
}
});
RETURN_IF_NULL_ALLOC(currentEnvVars = ::GetEnvironmentStringsW());
// Each entry is NULL-terminated; block is guaranteed to be double-NULL terminated at a minimum.
for (wchar_t const* lastCh{ currentEnvVars }; *lastCh != '\0'; ++lastCh)
{
// Copy current entry into temporary map.
const size_t cchEntry{ ::wcslen(lastCh) };
const std::wstring_view entry{ lastCh, cchEntry };
// Every entry is of the form "name=value\0".
auto pos = entry.find_first_of(L"=", 0, 1);
RETURN_HR_IF(E_UNEXPECTED, pos == std::wstring::npos);
std::wstring name{ entry.substr(0, pos) }; // portion before '='
std::wstring value{ entry.substr(pos + 1) }; // portion after '='
// Don't replace entries that already exist.
map.try_emplace(std::move(name), std::move(value));
lastCh += cchEntry;
}
return S_OK;
}
// Function Description:
// - Creates a new environment block using the provided vector as appropriate
// (resizing if needed) based on the provided environment variable map
// matching the format of GetEnvironmentStringsW.
// Arguments:
// - map: The map to populate the new environment block vector with.
// - newEnvVars: The vector that will be used to create the new environment block.
// Return Value:
// - S_OK if we succeeded, or an appropriate HRESULT for failing
[[nodiscard]] __declspec(noinline) inline HRESULT EnvironmentMapToEnvironmentStringsW(EnvironmentVariableMapW& map, std::vector<wchar_t>& newEnvVars) noexcept
{
// Clear environment block before use.
constexpr size_t cbChar{ sizeof(decltype(newEnvVars.begin())::value_type) };
if (!newEnvVars.empty())
{
::SecureZeroMemory(newEnvVars.data(), newEnvVars.size() * cbChar);
}
// Resize environment block to fit map.
size_t cchEnv{ 2 }; // For the block's double NULL-terminator.
for (const auto& [name, value] : map)
{
// Final form of "name=value\0".
cchEnv += name.size() + 1 + value.size() + 1;
}
newEnvVars.resize(cchEnv);
// Ensure new block is wiped if we exit due to failure.
auto zeroNewEnv = wil::scope_exit([&] {
::SecureZeroMemory(newEnvVars.data(), newEnvVars.size() * cbChar);
});
// Transform each map entry and copy it into the new environment block.
LPWCH pEnvVars{ newEnvVars.data() };
size_t cbRemaining{ cchEnv * cbChar };
for (const auto& [name, value] : map)
{
// Final form of "name=value\0" for every entry.
{
const size_t cchSrc{ name.size() };
const size_t cbSrc{ cchSrc * cbChar };
RETURN_HR_IF(E_OUTOFMEMORY, memcpy_s(pEnvVars, cbRemaining, name.c_str(), cbSrc) != 0);
pEnvVars += cchSrc;
cbRemaining -= cbSrc;
}
RETURN_HR_IF(E_OUTOFMEMORY, memcpy_s(pEnvVars, cbRemaining, L"=", cbChar) != 0);
++pEnvVars;
cbRemaining -= cbChar;
{
const size_t cchSrc{ value.size() };
const size_t cbSrc{ cchSrc * cbChar };
RETURN_HR_IF(E_OUTOFMEMORY, memcpy_s(pEnvVars, cbRemaining, value.c_str(), cbSrc) != 0);
pEnvVars += cchSrc;
cbRemaining -= cbSrc;
}
RETURN_HR_IF(E_OUTOFMEMORY, memcpy_s(pEnvVars, cbRemaining, L"\0", cbChar) != 0);
++pEnvVars;
cbRemaining -= cbChar;
}
// Environment block only has to be NULL-terminated, but double NULL-terminate anyway.
RETURN_HR_IF(E_OUTOFMEMORY, memcpy_s(pEnvVars, cbRemaining, L"\0\0", cbChar * 2) != 0);
cbRemaining -= cbChar * 2;
RETURN_HR_IF(E_UNEXPECTED, cbRemaining != 0);
zeroNewEnv.release(); // success; don't wipe new environment block on exit
return S_OK;
}
// Function Description:
// - Creates a headless conhost in "pty mode" and launches the given commandline
// attached to the conhost. Gives back handles to three different pipes:
// * hInput: The caller can write input to the conhost, encoded in utf-8, on
// this pipe. For keys that don't have character representations, the
// caller should use the `TERM=xterm` VT sequences for encoding the input.
// * hOutput: The caller should read from this pipe. The headless conhost will
// "render" it's state to a stream of utf-8 encoded text with VT sequences.
// * hSignal: The caller can use this to resize the size of the underlying PTY
// using the SignalResizeWindow function.
// Arguments:
// - cmdline: The commandline to launch as a console process attached to the pty
// that's created.
// - startingDirectory: The directory to start the process in
// - w: The initial width of the pty, in characters
// - h: The initial height of the pty, in characters
// - hInput: A handle to the pipe for writing input to the pty.
// - hOutput: A handle to the pipe for reading the output of the pty.
// - hSignal: A handle to the pipe for writing signal messages to the pty.
// - piPty: The PROCESS_INFORMATION of the pty process. NOTE: This is *not* the
// PROCESS_INFORMATION of the process that's created as a result the cmdline.
// - startupInfo : A STARTUPINFO struct to use as additional information to pass
// into the created conhost process. Conhost may pass some of the properties
// in this struct to its child process, notably, the lpTitle.
// - extraEnvVars : A map of pairs of (Name, Value) representing additional
// environment variable strings and values to be set in the client process
// environment. May override any already present in parent process.
// Return Value:
// - S_OK if we succeeded, or an appropriate HRESULT for failing format the
// commandline or failing to launch the conhost
[[nodiscard]] __declspec(noinline) inline HRESULT CreateConPty(const std::wstring& cmdline,
std::optional<std::wstring> startingDirectory,
const unsigned short w,
const unsigned short h,
HANDLE* const hInput,
HANDLE* const hOutput,
HANDLE* const hSignal,
PROCESS_INFORMATION* const piPty,
DWORD dwCreationFlags = 0,
const STARTUPINFO startupInfo = { 0 },
const EnvironmentVariableMapW& extraEnvVars = {}) noexcept
{
// Create some anon pipes so we can pass handles down and into the console.
// IMPORTANT NOTE:
// We're creating the pipe here with un-inheritable handles, then marking
// the conhost sides of the pipes as inheritable. We do this because if
// the entire pipe is marked as inheritable, when we pass the handles
// to CreateProcess, at some point the entire pipe object is copied to
// the conhost process, which includes the terminal side of the pipes
// (_inPipe and _outPipe). This means that if we die, there's still
// outstanding handles to our side of the pipes, and those handles are
// in conhost, despite conhost being unable to reference those handles
// and close them.
// CRITICAL: Close our side of the handles. Otherwise you'll get the same
// problem if you close conhost, but not us (the terminal).
HANDLE outPipeConhostSide;
HANDLE inPipeConhostSide;
HANDLE signalPipeConhostSide;
SECURITY_ATTRIBUTES sa;
sa = { 0 };
sa.nLength = sizeof(sa);
sa.bInheritHandle = FALSE;
sa.lpSecurityDescriptor = nullptr;
CreatePipe(&inPipeConhostSide, hInput, &sa, 0);
CreatePipe(hOutput, &outPipeConhostSide, &sa, 0);
CreatePipe(&signalPipeConhostSide, hSignal, &sa, 0);
SetHandleInformation(inPipeConhostSide, HANDLE_FLAG_INHERIT, 1);
SetHandleInformation(outPipeConhostSide, HANDLE_FLAG_INHERIT, 1);
SetHandleInformation(signalPipeConhostSide, HANDLE_FLAG_INHERIT, 1);
std::wstring conhostCmdline = L"conhost.exe";
conhostCmdline += L" --headless";
std::wstringstream ss;
if (w != 0 && h != 0)
{
ss << L" --width " << (unsigned long)w;
ss << L" --height " << (unsigned long)h;
}
ss << L" --signal 0x" << std::hex << HandleToUlong(signalPipeConhostSide);
conhostCmdline += ss.str();
conhostCmdline += L" -- ";
conhostCmdline += cmdline;
STARTUPINFO si = startupInfo;
si.cb = sizeof(STARTUPINFOW);
si.hStdInput = inPipeConhostSide;
si.hStdOutput = outPipeConhostSide;
si.hStdError = outPipeConhostSide;
si.dwFlags |= STARTF_USESTDHANDLES;
std::unique_ptr<wchar_t[]> mutableCommandline = std::make_unique<wchar_t[]>(conhostCmdline.length() + 1);
if (mutableCommandline == nullptr)
{
return E_OUTOFMEMORY;
}
HRESULT hr = StringCchCopy(mutableCommandline.get(), conhostCmdline.length() + 1, conhostCmdline.c_str());
if (!SUCCEEDED(hr))
{
return hr;
}
LPCWSTR lpCurrentDirectory = startingDirectory.has_value() ? startingDirectory.value().c_str() : nullptr;
std::vector<wchar_t> newEnvVars;
auto zeroNewEnv = wil::scope_exit([&] {
::SecureZeroMemory(newEnvVars.data(),
newEnvVars.size() * sizeof(decltype(newEnvVars.begin())::value_type));
});
if (!extraEnvVars.empty())
{
EnvironmentVariableMapW tempEnvMap{ extraEnvVars };
auto zeroEnvMap = wil::scope_exit([&] {
// Can't zero the keys, but at least we can zero the values.
for (auto& [name, value] : tempEnvMap)
{
::SecureZeroMemory(value.data(), value.size() * sizeof(decltype(value.begin())::value_type));
}
tempEnvMap.clear();
});
RETURN_IF_FAILED(UpdateEnvironmentMapW(tempEnvMap));
RETURN_IF_FAILED(EnvironmentMapToEnvironmentStringsW(tempEnvMap, newEnvVars));
// Required when using a unicode environment block.
dwCreationFlags |= CREATE_UNICODE_ENVIRONMENT;
}
LPWCH lpEnvironment = newEnvVars.empty() ? nullptr : newEnvVars.data();
bool fSuccess = !!CreateProcessW(
nullptr,
mutableCommandline.get(),
nullptr, // lpProcessAttributes
nullptr, // lpThreadAttributes
true, // bInheritHandles
dwCreationFlags, // dwCreationFlags
lpEnvironment, // lpEnvironment
lpCurrentDirectory, // lpCurrentDirectory
&si, // lpStartupInfo
piPty // lpProcessInformation
);
CloseHandle(inPipeConhostSide);
CloseHandle(outPipeConhostSide);
CloseHandle(signalPipeConhostSide);
return fSuccess ? S_OK : HRESULT_FROM_WIN32(GetLastError());
}
// Function Description:
// - Resizes the pty that's connected to hSignal.
// Arguments:
// - hSignal: A signal pipe as returned by CreateConPty.
// - w: The new width of the pty, in characters
// - h: The new height of the pty, in characters
// Return Value:
// - true if the resize succeeded, else false.
__declspec(noinline) inline bool SignalResizeWindow(HANDLE hSignal, const unsigned short w, const unsigned short h)
{
unsigned short signalPacket[3];
signalPacket[0] = PTY_SIGNAL_RESIZE_WINDOW;
signalPacket[1] = w;
signalPacket[2] = h;
return !!WriteFile(hSignal, signalPacket, sizeof(signalPacket), nullptr, nullptr);
}

132
src/types/Environment.cpp Normal file
View File

@@ -0,0 +1,132 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "precomp.h"
#include "inc/Environment.hpp"
using namespace ::Microsoft::Console::Utils;
// We cannot use spand or not_null because we're dealing with \0\0-terminated buffers of unknown length
#pragma warning(disable : 26481 26429)
// Function Description:
// - Updates an EnvironmentVariableMapW with the current process's unicode
// environment variables ignoring ones already set in the provided map.
// Arguments:
// - map: The map to populate with the current processes's environment variables.
// Return Value:
// - S_OK if we succeeded, or an appropriate HRESULT for failing
HRESULT Microsoft::Console::Utils::UpdateEnvironmentMapW(EnvironmentVariableMapW& map) noexcept
try
{
LPWCH currentEnvVars{};
auto freeCurrentEnv = wil::scope_exit([&] {
if (currentEnvVars)
{
FreeEnvironmentStringsW(currentEnvVars);
currentEnvVars = nullptr;
}
});
currentEnvVars = ::GetEnvironmentStringsW();
RETURN_HR_IF_NULL(E_OUTOFMEMORY, currentEnvVars);
// Each entry is NULL-terminated; block is guaranteed to be double-NULL terminated at a minimum.
for (wchar_t const* lastCh{ currentEnvVars }; *lastCh != '\0'; ++lastCh)
{
// Copy current entry into temporary map.
const size_t cchEntry{ ::wcslen(lastCh) };
const std::wstring_view entry{ lastCh, cchEntry };
// Every entry is of the form "name=value\0".
const auto pos = entry.find_first_of(L"=", 0, 1);
RETURN_HR_IF(E_UNEXPECTED, pos == std::wstring::npos);
std::wstring name{ entry.substr(0, pos) }; // portion before '='
std::wstring value{ entry.substr(pos + 1) }; // portion after '='
// Don't replace entries that already exist.
map.try_emplace(std::move(name), std::move(value));
lastCh += cchEntry;
}
return S_OK;
}
CATCH_RETURN();
// Function Description:
// - Creates a new environment block using the provided vector as appropriate
// (resizing if needed) based on the provided environment variable map
// matching the format of GetEnvironmentStringsW.
// Arguments:
// - map: The map to populate the new environment block vector with.
// - newEnvVars: The vector that will be used to create the new environment block.
// Return Value:
// - S_OK if we succeeded, or an appropriate HRESULT for failing
HRESULT Microsoft::Console::Utils::EnvironmentMapToEnvironmentStringsW(EnvironmentVariableMapW& map, std::vector<wchar_t>& newEnvVars) noexcept
try
{
// Clear environment block before use.
constexpr size_t cbChar{ sizeof(decltype(newEnvVars.begin())::value_type) };
if (!newEnvVars.empty())
{
::SecureZeroMemory(newEnvVars.data(), newEnvVars.size() * cbChar);
}
// Resize environment block to fit map.
size_t cchEnv{ 2 }; // For the block's double NULL-terminator.
for (const auto& [name, value] : map)
{
// Final form of "name=value\0".
cchEnv += name.size() + 1 + value.size() + 1;
}
newEnvVars.resize(cchEnv);
// Ensure new block is wiped if we exit due to failure.
auto zeroNewEnv = wil::scope_exit([&]() noexcept {
::SecureZeroMemory(newEnvVars.data(), newEnvVars.size() * cbChar);
});
// Transform each map entry and copy it into the new environment block.
LPWCH pEnvVars{ newEnvVars.data() };
size_t cbRemaining{ cchEnv * cbChar };
for (const auto& [name, value] : map)
{
// Final form of "name=value\0" for every entry.
{
const size_t cchSrc{ name.size() };
const size_t cbSrc{ cchSrc * cbChar };
RETURN_HR_IF(E_OUTOFMEMORY, memcpy_s(pEnvVars, cbRemaining, name.c_str(), cbSrc) != 0);
pEnvVars += cchSrc;
cbRemaining -= cbSrc;
}
RETURN_HR_IF(E_OUTOFMEMORY, memcpy_s(pEnvVars, cbRemaining, L"=", cbChar) != 0);
++pEnvVars;
cbRemaining -= cbChar;
{
const size_t cchSrc{ value.size() };
const size_t cbSrc{ cchSrc * cbChar };
RETURN_HR_IF(E_OUTOFMEMORY, memcpy_s(pEnvVars, cbRemaining, value.c_str(), cbSrc) != 0);
pEnvVars += cchSrc;
cbRemaining -= cbSrc;
}
RETURN_HR_IF(E_OUTOFMEMORY, memcpy_s(pEnvVars, cbRemaining, L"\0", cbChar) != 0);
++pEnvVars;
cbRemaining -= cbChar;
}
// Environment block only has to be NULL-terminated, but double NULL-terminate anyway.
RETURN_HR_IF(E_OUTOFMEMORY, memcpy_s(pEnvVars, cbRemaining, L"\0\0", cbChar * 2) != 0);
cbRemaining -= cbChar * 2;
RETURN_HR_IF(E_UNEXPECTED, cbRemaining != 0);
zeroNewEnv.release(); // success; don't wipe new environment block on exit
return S_OK;
}
CATCH_RETURN();

View File

@@ -0,0 +1,31 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
namespace Microsoft::Console::Utils
{
//
// A case-insensitive wide-character map is used to store environment variables
// due to documented requirements:
//
// "All strings in the environment block must be sorted alphabetically by name.
// The sort is case-insensitive, Unicode order, without regard to locale.
// Because the equal sign is a separator, it must not be used in the name of
// an environment variable."
// https://docs.microsoft.com/en-us/windows/desktop/ProcThread/changing-environment-variables
//
struct WStringCaseInsensitiveCompare
{
[[nodiscard]] bool operator()(const std::wstring& lhs, const std::wstring& rhs) const noexcept
{
return (::_wcsicmp(lhs.c_str(), rhs.c_str()) < 0);
}
};
using EnvironmentVariableMapW = std::map<std::wstring, std::wstring, WStringCaseInsensitiveCompare>;
[[nodiscard]] HRESULT UpdateEnvironmentMapW(EnvironmentVariableMapW& map) noexcept;
[[nodiscard]] HRESULT EnvironmentMapToEnvironmentStringsW(EnvironmentVariableMapW& map,
std::vector<wchar_t>& newEnvVars) noexcept;
};

View File

@@ -12,6 +12,7 @@
<ItemGroup>
<ClCompile Include="..\CodepointWidthDetector.cpp" />
<ClCompile Include="..\convert.cpp" />
<ClCompile Include="..\Environment.cpp" />
<ClCompile Include="..\GlyphWidth.cpp" />
<ClCompile Include="..\MouseEvent.cpp" />
<ClCompile Include="..\FocusEvent.cpp" />
@@ -37,6 +38,7 @@
<ClInclude Include="..\IConsoleWindow.hpp" />
<ClInclude Include="..\inc\CodepointWidthDetector.hpp" />
<ClInclude Include="..\inc\convert.hpp" />
<ClInclude Include="..\inc\Environment.hpp" />
<ClInclude Include="..\inc\GlyphWidth.hpp" />
<ClInclude Include="..\inc\IInputEvent.hpp" />
<ClInclude Include="..\inc\ThemeUtils.h" />

View File

@@ -6,7 +6,7 @@
<RootNamespace>winconpty</RootNamespace>
<ProjectName>winconpty</ProjectName>
<TargetName>conpty</TargetName>
<ConfigurationType>DynamicLibrary</ConfigurationType>
<ConfigurationType>DynamicLibrary</ConfigurationType>
</PropertyGroup>
<Import Project="$(SolutionDir)src\common.build.pre.props" />
<ItemGroup>
@@ -31,4 +31,40 @@
<ModuleDefinitionFile>winconpty.def</ModuleDefinitionFile>
</Link>
</ItemDefinitionGroup>
<!-- Override GetPackagingOutputs to roll up our DLL.
This is a heavily stripped version of the one in Microsoft.*.AppxPackage.targets.
-->
<PropertyGroup>
<_ContinueOnError Condition="'$(BuildingProject)' == 'true'">true</_ContinueOnError>
<_ContinueOnError Condition="'$(BuildingProject)' != 'true'">false</_ContinueOnError>
</PropertyGroup>
<Target Name="GetPackagingOutputs" Returns="@(PackagingOutputs)">
<CallTarget Targets="BuiltProjectOutputGroup">
<Output TaskParameter="TargetOutputs" ItemName="_BuiltProjectOutputGroupOutput"/>
</CallTarget>
<ItemGroup>
<_PackagingOutputsUnexpanded Include="%(_BuiltProjectOutputGroupOutput.FinalOutputPath)">
<TargetPath>%(_BuiltProjectOutputGroupOutput.TargetPath)</TargetPath>
<OutputGroup>BuiltProjectOutputGroup</OutputGroup>
<ProjectName>$(ProjectName)</ProjectName>
</_PackagingOutputsUnexpanded>
</ItemGroup>
<CallTarget Targets="DebugSymbolsProjectOutputGroup">
<Output TaskParameter="TargetOutputs" ItemName="_DebugSymbolsProjectOutputGroupOutput"/>
</CallTarget>
<ItemGroup>
<_PackagingOutputsUnexpanded Include="%(_DebugSymbolsProjectOutputGroupOutput.FinalOutputPath)">
<OutputGroup>DebugSymbolsProjectOutputGroup</OutputGroup>
<ProjectName>$(ProjectName)</ProjectName>
</_PackagingOutputsUnexpanded>
</ItemGroup>
<ItemGroup>
<PackagingOutputs Include="@(_PackagingOutputsUnexpanded)">
<TargetPath>%(Filename)%(Extension)</TargetPath>
</PackagingOutputs>
</ItemGroup>
</Target>
</Project>