diff --git a/premake5.lua b/premake5.lua index 7b88bb375..29a92ef5e 100644 --- a/premake5.lua +++ b/premake5.lua @@ -390,6 +390,7 @@ project "ConEmuCD" { ["Interface"] = {"**/Common.h", "**/SrvCommands.*", "**/Queue.*", "**/SrvPipes.*"} }, { ["Automation"] = {"**/Actions.*", "**/GuiMacro.*"} }, { ["Console"] = {"**/ConAnsi.*", "**/ConAnsiImpl.*", "**/ConData.*"} }, + { ["Server"] = {"**/ServerLegacy.*", "**/ConEmuSrv.*"} }, { ["Headers"] = {"**.h"} }, { ["Sources"] = {"**.cpp"} }, { ["Resources"] = {"**.rc", "**.rc2", "**.manifest"} }, diff --git a/src/ConEmuCD.vcxproj b/src/ConEmuCD.vcxproj index 106b9d7fa..2f6ccf3a2 100644 --- a/src/ConEmuCD.vcxproj +++ b/src/ConEmuCD.vcxproj @@ -276,15 +276,19 @@ + + + + @@ -313,6 +317,7 @@ + diff --git a/src/ConEmuCD.vcxproj.filters b/src/ConEmuCD.vcxproj.filters index 2e947ce49..3dd2f6c93 100644 --- a/src/ConEmuCD.vcxproj.filters +++ b/src/ConEmuCD.vcxproj.filters @@ -19,6 +19,9 @@ {000BCD17-6C75-818E-B5B3-3234215D5FE3} + + {7C62DFD0-6804-0AA7-51BF-1DFB3D0091F7} + {89565304-F535-D29F-FE4D-5D766AAC3801} @@ -36,15 +39,21 @@ Console - + Headers + + Server + Headers Headers + + Headers + Headers @@ -63,6 +72,12 @@ Headers + + Headers + + + Headers + Headers @@ -117,7 +132,7 @@ Sources - Sources + Server Sources @@ -143,6 +158,9 @@ Sources + + Sources + Sources diff --git a/src/ConEmuCD/Actions.cpp b/src/ConEmuCD/Actions.cpp index 08e5ac5d7..18543cd9a 100644 --- a/src/ConEmuCD/Actions.cpp +++ b/src/ConEmuCD/Actions.cpp @@ -50,9 +50,10 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../ConEmuHk/Injects.h" #include "../ConEmu/version.h" -#include "ConEmuSrv.h" #include "Actions.h" +#include "ConsoleMain.h" #include "GuiMacro.h" +#include "InjectRemote.h" #include "MapDump.h" #include "UnicodeTest.h" diff --git a/src/ConEmuCD/ConAnsi.cpp b/src/ConEmuCD/ConAnsi.cpp index 53f61fdde..139cf94e0 100644 --- a/src/ConEmuCD/ConAnsi.cpp +++ b/src/ConEmuCD/ConAnsi.cpp @@ -27,7 +27,7 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "../common/defines.h" +#include "ConsoleMain.h" #include #include #include diff --git a/src/ConEmuCD/ConAnsiImpl.cpp b/src/ConEmuCD/ConAnsiImpl.cpp index 5813d8e94..7130b5400 100644 --- a/src/ConEmuCD/ConAnsiImpl.cpp +++ b/src/ConEmuCD/ConAnsiImpl.cpp @@ -27,7 +27,7 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "../common/defines.h" +#include "ConsoleMain.h" #include #include #include diff --git a/src/ConEmuCD/ConEmuCmd.cpp b/src/ConEmuCD/ConEmuCmd.cpp index 5b14e5a8c..6baa74ea8 100644 --- a/src/ConEmuCD/ConEmuCmd.cpp +++ b/src/ConEmuCD/ConEmuCmd.cpp @@ -27,6 +27,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#include "ConsoleMain.h" +#include "ConEmuCmd.h" #include "ConEmuSrv.h" #include "../common/WFiles.h" diff --git a/src/ConEmuCD/ConEmuCmd.h b/src/ConEmuCD/ConEmuCmd.h new file mode 100644 index 000000000..9494ae5bc --- /dev/null +++ b/src/ConEmuCD/ConEmuCmd.h @@ -0,0 +1,33 @@ + +/* +Copyright (c) 2009-present Maximus5 +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +#pragma once + +int ComspecInit(); +void ComspecDone(int aiRc); diff --git a/src/ConEmuCD/ConEmuSrv.cpp b/src/ConEmuCD/ConEmuSrv.cpp index 57224e3d2..67bbadef2 100644 --- a/src/ConEmuCD/ConEmuSrv.cpp +++ b/src/ConEmuCD/ConEmuSrv.cpp @@ -30,7 +30,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #undef TEST_REFRESH_DELAYED +#include "ConsoleMain.h" #include "ConEmuSrv.h" +#include "LogFunction.h" +#include "InjectRemote.h" +#include "InputLogger.h" #include "../common/CmdLine.h" #include "../common/ConsoleAnnotation.h" #include "../common/ConsoleRead.h" @@ -78,9 +82,13 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #undef ASSERT_UNWANTED_SIZE #endif -extern BOOL gbTerminateOnExit; // для отладчика -extern BOOL gbTerminateOnCtrlBreak; -extern OSVERSIONINFO gOSVer; +/* Console Handles */ +MConHandle ghConOut(L"CONOUT$"); +//Used to store and restore console screen buffers in cmd_AltBuffer +MConHandle gPrimaryBuffer(NULL), gAltBuffer(NULL); +USHORT gnPrimaryBufferLastRow = 0; // last detected written row in gPrimaryBuffer + +BOOL gbTerminateOnExit = FALSE; // for debugging purposed // Some forward definitions bool TryConnect2Gui(HWND hGui, DWORD anGuiPID, CESERVER_REQ* pIn); @@ -194,191 +202,6 @@ void ServerInitFont() } } -LGSResult LoadGuiSettingsPtr(ConEmuGuiMapping& GuiMapping, const ConEmuGuiMapping* pInfo, bool abNeedReload, bool abForceCopy, DWORD& rnWrongValue) -{ - LGSResult liRc = lgs_Failed; - DWORD cbSize = 0; - bool lbNeedCopy = false; - bool lbCopied = false; - wchar_t szLog[80]; - - if (!pInfo) - { - liRc = lgs_MapPtr; - wcscpy_c(szLog, L"LoadGuiSettings(Failed, MapPtr is null)"); - LogFunction(szLog); - goto wrap; - } - - if (abForceCopy) - { - cbSize = std::min(sizeof(GuiMapping), pInfo->cbSize); - memmove(&GuiMapping, pInfo, cbSize); - gpSrv->guiSettings.cbSize = cbSize; - lbCopied = true; - } - - if (pInfo->cbSize >= (size_t)(sizeof(pInfo->nProtocolVersion) + ((LPBYTE)&pInfo->nProtocolVersion) - (LPBYTE)pInfo)) - { - if (pInfo->nProtocolVersion != CESERVER_REQ_VER) - { - liRc = lgs_WrongVersion; - rnWrongValue = pInfo->nProtocolVersion; - wcscpy_c(szLog, L"LoadGuiSettings(Failed, MapPtr is null)"); - swprintf_c(szLog, L"LoadGuiSettings(Failed, Version=%u, Required=%u)", rnWrongValue, (DWORD)CESERVER_REQ_VER); - LogFunction(szLog); - goto wrap; - } - } - - if (pInfo->cbSize != sizeof(ConEmuGuiMapping)) - { - liRc = lgs_WrongSize; - rnWrongValue = pInfo->cbSize; - swprintf_c(szLog, L"LoadGuiSettings(Failed, cbSize=%u, Required=%u)", pInfo->cbSize, (DWORD)sizeof(ConEmuGuiMapping)); - LogFunction(szLog); - goto wrap; - } - - lbNeedCopy = abNeedReload - || (gpSrv->guiSettingsChangeNum != pInfo->nChangeNum) - || (GuiMapping.bGuiActive != pInfo->bGuiActive) - ; - - if (lbNeedCopy) - { - wcscpy_c(szLog, L"LoadGuiSettings(Changed)"); - LogFunction(szLog); - if (!lbCopied) - memmove(&GuiMapping, pInfo, pInfo->cbSize); - _ASSERTE(GuiMapping.ComSpec.ConEmuExeDir[0]!=0 && GuiMapping.ComSpec.ConEmuBaseDir[0]!=0); - liRc = lgs_Updated; - } - else if (GuiMapping.dwActiveTick != pInfo->dwActiveTick) - { - // But active consoles list may be changed - if (!lbCopied) - memmove(GuiMapping.Consoles, pInfo->Consoles, sizeof(GuiMapping.Consoles)); - liRc = lgs_ActiveChanged; - } - else - { - liRc = lgs_Succeeded; - } - -wrap: - return liRc; -} - -LGSResult LoadGuiSettings(ConEmuGuiMapping& GuiMapping, DWORD& rnWrongValue) -{ - LGSResult liRc = lgs_Failed; - bool lbNeedReload = false; - DWORD dwGuiThreadId, dwGuiProcessId; - HWND hGuiWnd = ghConEmuWnd ? ghConEmuWnd : gpSrv->hGuiWnd; - const ConEmuGuiMapping* pInfo = NULL; - - if (!hGuiWnd || !IsWindow(hGuiWnd)) - { - LogFunction(L"LoadGuiSettings(Invalid window)"); - goto wrap; - } - - if (!gpSrv->pGuiInfoMap || (gpSrv->hGuiInfoMapWnd != hGuiWnd)) - { - lbNeedReload = true; - } - - if (lbNeedReload) - { - LogFunction(L"LoadGuiSettings(Opening)"); - - dwGuiThreadId = GetWindowThreadProcessId(hGuiWnd, &dwGuiProcessId); - if (!dwGuiThreadId) - { - _ASSERTE(dwGuiProcessId); - LogFunction(L"LoadGuiSettings(Failed, dwGuiThreadId==0)"); - goto wrap; - } - - if (!gpSrv->pGuiInfoMap) - gpSrv->pGuiInfoMap = new MFileMapping; - else - gpSrv->pGuiInfoMap->CloseMap(); - - gpSrv->pGuiInfoMap->InitName(CEGUIINFOMAPNAME, dwGuiProcessId); - pInfo = gpSrv->pGuiInfoMap->Open(); - - if (pInfo) - { - gpSrv->hGuiInfoMapWnd = hGuiWnd; - } - } - else - { - pInfo = gpSrv->pGuiInfoMap->Ptr(); - } - - liRc = LoadGuiSettingsPtr(GuiMapping, pInfo, lbNeedReload, false, rnWrongValue); -wrap: - return liRc; -} - -LGSResult ReloadGuiSettings(ConEmuGuiMapping* apFromCmd, LPDWORD pnWrongValue /*= NULL*/) -{ - bool lbChanged = false; - LGSResult lgsResult = lgs_Failed; - DWORD nWrongValue = 0; - - if (apFromCmd) - { - LogFunction(L"ReloadGuiSettings(apFromCmd)"); - lgsResult = LoadGuiSettingsPtr(gpSrv->guiSettings, apFromCmd, false, true, nWrongValue); - lbChanged = (lgsResult >= lgs_Succeeded); - } - else - { - gpSrv->guiSettings.cbSize = sizeof(ConEmuGuiMapping); - lgsResult = LoadGuiSettings(gpSrv->guiSettings, nWrongValue); - lbChanged = (lgsResult >= lgs_Succeeded) - && ((gpSrv->guiSettingsChangeNum != gpSrv->guiSettings.nChangeNum) - || (gpSrv->pConsole && gpSrv->pConsole->hdr.ComSpec.ConEmuExeDir[0] == 0)); - } - - if (pnWrongValue) - *pnWrongValue = nWrongValue; - - if (lbChanged) - { - LogFunction(L"ReloadGuiSettings(Apply)"); - - gpSrv->guiSettingsChangeNum = gpSrv->guiSettings.nChangeNum; - - gbLogProcess = (gpSrv->guiSettings.nLoggingType == glt_Processes); - - UpdateComspec(&gpSrv->guiSettings.ComSpec); // isAddConEmu2Path, ... - - SetConEmuFolders(gpSrv->guiSettings.ComSpec.ConEmuExeDir, gpSrv->guiSettings.ComSpec.ConEmuBaseDir); - - // Не будем ставить сами, эту переменную заполняет Gui при своем запуске - // соответственно, переменная наследуется серверами - //SetEnvironmentVariableW(L"ConEmuArgs", pInfo->sConEmuArgs); - - //wchar_t szHWND[16]; swprintf_c(szHWND, L"0x%08X", gpSrv->guiSettings.hGuiWnd.u); - //SetEnvironmentVariable(ENV_CONEMUHWND_VAR_W, szHWND); - SetConEmuWindows(gpSrv->guiSettings.hGuiWnd, ghConEmuWndDC, ghConEmuWndBack); - - if (gpSrv->pConsole) - { - CopySrvMapFromGuiMap(); - - UpdateConsoleMapHeader(L"guiSettings were changed"); - } - } - - return lgsResult; -} - // AutoAttach делать нельзя, когда ConEmu запускает процесс обновления bool IsAutoAttachAllowed() { @@ -2169,94 +1992,6 @@ void CmdOutputRestore(bool abSimpleMode) LogString("CmdOutputRestore finished"); } -static BOOL CALLBACK FindConEmuByPidProc(HWND hwnd, LPARAM lParam) -{ - DWORD dwPID; - GetWindowThreadProcessId(hwnd, &dwPID); - if (dwPID == gnConEmuPID) - { - wchar_t szClass[128]; - if (GetClassName(hwnd, szClass, countof(szClass))) - { - if (lstrcmp(szClass, VirtualConsoleClassMain) == 0) - { - *(HWND*)lParam = hwnd; - return FALSE; - } - } - } - return TRUE; -} - -HWND FindConEmuByPID(DWORD anSuggestedGuiPID /*= 0*/) -{ - LogFunction(L"FindConEmuByPID"); - - HWND hConEmuWnd = NULL; - DWORD nConEmuPID = anSuggestedGuiPID ? anSuggestedGuiPID : gnConEmuPID; - DWORD dwGuiThreadId = 0, dwGuiProcessId = 0; - - // В большинстве случаев PID GUI передан через параметры - if (nConEmuPID == 0) - { - // GUI может еще "висеть" в ожидании или в отладчике, так что пробуем и через Snapshot - //TODO: Reuse MToolHelp.h - HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); - - if (hSnap != INVALID_HANDLE_VALUE) - { - PROCESSENTRY32 prc = {sizeof(PROCESSENTRY32)}; - - if (Process32First(hSnap, &prc)) - { - do - { - if (prc.th32ProcessID == gnSelfPID) - { - nConEmuPID = prc.th32ParentProcessID; - break; - } - } - while (Process32Next(hSnap, &prc)); - } - - CloseHandle(hSnap); - } - } - - if (nConEmuPID) - { - HWND hGui = NULL; - - while ((hGui = FindWindowEx(NULL, hGui, VirtualConsoleClassMain, NULL)) != NULL) - { - dwGuiThreadId = GetWindowThreadProcessId(hGui, &dwGuiProcessId); - - if (dwGuiProcessId == nConEmuPID) - { - hConEmuWnd = hGui; - break; - } - } - - // Если "в лоб" по имени класса ничего не нашли - смотрим - // среди всех дочерних для текущего десктопа - if ((hConEmuWnd == NULL) && !anSuggestedGuiPID) - { - HWND hDesktop = GetDesktopWindow(); - EnumChildWindows(hDesktop, FindConEmuByPidProc, (LPARAM)&hConEmuWnd); - } - } - - // Ensure that returned hConEmuWnd match gnConEmuPID - if (!anSuggestedGuiPID && hConEmuWnd) - { - GetWindowThreadProcessId(hConEmuWnd, &gnConEmuPID); - } - - return hConEmuWnd; -} - void SetConEmuFolders(LPCWSTR asExeDir, LPCWSTR asBaseDir) { _ASSERTE(asExeDir && *asExeDir!=0 && asBaseDir && *asBaseDir); @@ -2332,10 +2067,8 @@ void CheckConEmuHwnd() { LogFunction(L"CheckConEmuHwnd"); - WARNING("Подозрение, что слишком много вызовов при старте сервера"); + // #WARNING too many calls during server start? - //HWND hWndFore = GetForegroundWindow(); - //HWND hWndFocus = GetFocus(); DWORD dwGuiThreadId = 0; if (gpSrv->DbgInfo.bDebuggerActive) @@ -3695,111 +3428,21 @@ void InitAnsiLog(const ConEmuAnsiLog& AnsiLog) SetEnvironmentVariable(ENV_CONEMUANSILOG_VAR_W, log_file); } -#if 0 -// Возвращает TRUE - если меняет РАЗМЕР видимой области (что нужно применить в консоль) -BOOL CorrectVisibleRect(CONSOLE_SCREEN_BUFFER_INFO* pSbi) -{ - BOOL lbChanged = FALSE; - _ASSERTE(gcrVisibleSize.Y<200); // высота видимой области - // Игнорируем горизонтальный скроллинг - SHORT nLeft = 0; - SHORT nRight = pSbi->dwSize.X - 1; - SHORT nTop = pSbi->srWindow.Top; - SHORT nBottom = pSbi->srWindow.Bottom; - - if (gnBufferHeight == 0) - { - // Сервер мог еще не успеть среагировать на изменение режима BufferHeight - if (pSbi->dwMaximumWindowSize.Y < pSbi->dwSize.Y) - { - // Это однозначно буферный режим, т.к. высота буфера больше максимально допустимого размера окна - // Вполне нормальная ситуация. Запуская VBinDiff который ставит свой буфер, - // соответственно сам убирая прокрутку, а при выходе возвращая ее... - //_ASSERTE(pSbi->dwMaximumWindowSize.Y >= pSbi->dwSize.Y); - gnBufferHeight = pSbi->dwSize.Y; - } - } - - // Игнорируем вертикальный скроллинг для обычного режима - if (gnBufferHeight == 0) - { - nTop = 0; - nBottom = pSbi->dwSize.Y - 1; - } - else if (gpSrv->nTopVisibleLine != -1) - { - // А для 'буферного' режима позиция может быть заблокирована - nTop = gpSrv->nTopVisibleLine; - nBottom = std::min((pSbi->dwSize.Y-1), (gpSrv->nTopVisibleLine+gcrVisibleSize.Y-1)); //-V592 - } - else - { - // Просто корректируем нижнюю строку по отображаемому в GUI региону - // хорошо бы эту коррекцию сделать так, чтобы курсор был видим - if (pSbi->dwCursorPosition.Y == pSbi->srWindow.Bottom) - { - // Если курсор находится в нижней видимой строке (теоретически, это может быть единственная видимая строка) - nTop = pSbi->dwCursorPosition.Y - gcrVisibleSize.Y + 1; // раздвигаем область вверх от курсора - } - else - { - // Иначе - раздвигаем вверх (или вниз) минимально, чтобы курсор стал видим - if ((pSbi->dwCursorPosition.Y < pSbi->srWindow.Top) || (pSbi->dwCursorPosition.Y > pSbi->srWindow.Bottom)) - { - nTop = pSbi->dwCursorPosition.Y - gcrVisibleSize.Y + 1; - } - } - - // Страховка от выхода за пределы - if (nTop<0) nTop = 0; - - // Корректируем нижнюю границу по верхней + желаемой высоте видимой области - nBottom = (nTop + gcrVisibleSize.Y - 1); - - // Если же расчетный низ вылезает за пределы буфера (хотя не должен бы?) - if (nBottom >= pSbi->dwSize.Y) - { - // корректируем низ - nBottom = pSbi->dwSize.Y - 1; - // и верх по желаемому размеру - nTop = std::max(0, (nBottom - gcrVisibleSize.Y + 1)); - } - } - -#ifdef _DEBUG - - if ((pSbi->srWindow.Bottom - pSbi->srWindow.Top)>pSbi->dwMaximumWindowSize.Y) - { - _ASSERTE((pSbi->srWindow.Bottom - pSbi->srWindow.Top)dwMaximumWindowSize.Y); - } - -#endif - - if (nLeft != pSbi->srWindow.Left - || nRight != pSbi->srWindow.Right - || nTop != pSbi->srWindow.Top - || nBottom != pSbi->srWindow.Bottom) - lbChanged = TRUE; - - return lbChanged; -} -#endif - bool CheckWasFullScreen() { bool bFullScreenHW = false; - if (gpSrv->pfnWasFullscreenMode) + if (gpSrv->wasFullscreenMode && pfnGetConsoleDisplayMode) { - DWORD nModeFlags = 0; gpSrv->pfnWasFullscreenMode(&nModeFlags); + DWORD nModeFlags = 0; pfnGetConsoleDisplayMode(&nModeFlags); if (nModeFlags & CONSOLE_FULLSCREEN_HARDWARE) { bFullScreenHW = true; } else { - gpSrv->pfnWasFullscreenMode = NULL; + gpSrv->wasFullscreenMode = false; } } diff --git a/src/ConEmuCD/ConEmuSrv.h b/src/ConEmuCD/ConEmuSrv.h index ee95ac6c0..df25be62d 100644 --- a/src/ConEmuCD/ConEmuSrv.h +++ b/src/ConEmuCD/ConEmuSrv.h @@ -29,126 +29,16 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #pragma once - -#undef SHOW_SHUTDOWNSRV_STEPS -#ifdef _DEBUG - #define SHOW_SHUTDOWNSRV_STEPS -#endif - - -#ifdef _DEBUG -// Раскомментировать для вывода в консоль информации режима Comspec -#define PRINT_COMSPEC(f,a) //wprintf(f,a) -//#define DEBUGSTR(s) OutputDebugString(s) -#elif defined(__GNUC__) -// Раскомментировать, чтобы сразу после запуска процесса (conemuc.exe) показать MessageBox, чтобы прицепиться дебаггером -// #define SHOW_STARTED_MSGBOX -#define PRINT_COMSPEC(f,a) //wprintf(f,a) -//#define DEBUGSTR(s) -#else -#define PRINT_COMSPEC(f,a) -#define DEBUGSTR(s) -#endif - -#ifdef _DEBUG -#define xf_check() { xf_validate(); xf_dump_chk(); } -#else -#define xf_check() -#endif - -#define DEBUGLOG(s) //DEBUGSTR(s) -#define DEBUGLOGSIZE(s) DEBUGSTR(s) -#define DEBUGLOGLANG(s) //DEBUGSTR(s) //; Sleep(2000) - -#include "LogFunction.h" - - - -#define CSECTION_NON_RAISE - -#include +#include "../common/defines.h" #include #ifdef _DEBUG #include #endif #include -#include #include "../common/RConStartArgs.h" -void ShutdownSrvStep(LPCWSTR asInfo, int nParm1 = 0, int nParm2 = 0, int nParm3 = 0, int nParm4 = 0); -enum SetTerminateEventPlace -{ - ste_None = 0, - ste_ServerDone, - ste_ConsoleMain, - ste_ProcessCountChanged, - ste_CheckProcessCount, - ste_DebugThread, - ste_WriteMiniDump, - ste_CmdDetachCon, - ste_HandlerRoutine, - ste_Attach2GuiFailed, -}; -extern SetTerminateEventPlace gTerminateEventPlace; -void SetTerminateEvent(SetTerminateEventPlace eFrom); - -bool isConEmuTerminated(); - -/* Global */ -extern DWORD gnSelfPID; -extern wchar_t gsModuleName[32]; -extern wchar_t gsVersion[20]; -extern wchar_t gsSelfExe[MAX_PATH]; // Full path+exe to our executable -extern wchar_t gsSelfPath[MAX_PATH]; // Directory of our executable -//HANDLE ghConIn = NULL, ghConOut = NULL; -extern HWND ghConWnd; -extern DWORD gnConEmuPID; // PID of ConEmu[64].exe (ghConEmuWnd) -extern HWND ghConEmuWnd; // Root! window -extern HWND ghConEmuWndDC; // ConEmu DC window -extern HWND ghConEmuWndBack; // ConEmu Back window -extern void SetConEmuWindows(HWND hRootWnd, HWND hDcWnd, HWND hBackWnd); -extern void SetConEmuFolders(LPCWSTR asExeDir, LPCWSTR asBaseDir); -extern DWORD gnMainServerPID; // PID сервера (инициализируется на старте, при загрузке Dll) -extern DWORD gnAltServerPID; // PID сервера (инициализируется на старте, при загрузке Dll) -extern BOOL gbLogProcess; // (pInfo->nLoggingType == glt_Processes) -extern BOOL gbWasBufferHeight; -extern BOOL gbNonGuiMode; -extern DWORD gnExitCode; -extern HANDLE ghExitQueryEvent; // выставляется когда в консоли не остается процессов -extern int nExitQueryPlace, nExitPlaceStep, nExitPlaceThread; -extern HANDLE ghQuitEvent; // когда мы в процессе закрытия (юзер уже нажал кнопку "Press to close console") -extern bool gbQuit; // когда мы в процессе закрытия (юзер уже нажал кнопку "Press to close console") -extern bool gbSkipHookersCheck; -extern RConStartArgs::CloseConfirm gnConfirmExitParm; -extern BOOL gbAlwaysConfirmExit, gbInShutdown, gbAutoDisableConfirmExit; -extern int gbRootWasFoundInCon; -extern BOOL gbComspecInitCalled; -typedef DWORD AttachModeEnum; -const AttachModeEnum - am_Simple = 0x0001, // As is - am_Auto = 0x0002, // Same as am_Simple, but always return 0 as errorlevel - am_Modes = (am_Simple|am_Auto), - am_Async = 0x0010, // "/AUTOATTACH" must be async to be able to call from cmd prompt - am_DefTerm = 0x0020, // "/ - am_Admin = 0x1000, // Special "attach" when ConEmu is run under "User" and console "As admin" - am_None = 0 -; -extern AttachModeEnum gbAttachMode; // сервер запущен НЕ из conemu.exe (а из плагина, из CmdAutoAttach, или -new_console) -extern BOOL gbAlternativeAttach; // TRUE - Подцепиться к существующей консоли, без внедрения в процесс ConEmuHk.dll -extern BOOL gbAlienMode; // сервер НЕ является владельцем консоли (корневым процессом этого консольного окна) -extern BOOL gbDontInjectConEmuHk; -extern BOOL gbForceHideConWnd; -extern DWORD gdwMainThreadId; -extern wchar_t* gpszRunCmd; -extern wchar_t* gpszRootExe; -extern bool gbRunInBackgroundTab; -extern DWORD gnImageSubsystem; -#ifdef _DEBUG -extern size_t gnHeapUsed, gnHeapMax; -extern HANDLE ghFarInExecuteEvent; -#endif #include "../common/Common.h" #include "../common/ConEmuCheck.h" @@ -161,89 +51,8 @@ extern HANDLE ghFarInExecuteEvent; #include "../common/InQueue.h" #include "ExitCodes.h" -#ifdef _DEBUG -extern wchar_t gszDbgModLabel[6]; -#endif - -#define START_MAX_PROCESSES 1000 -#define CHECK_PROCESSES_TIMEOUT 500 -#define CHECK_ANTIVIRUS_TIMEOUT (6*1000) -#define CHECK_ROOTSTART_TIMEOUT (10*1000) -#ifdef _DEBUG - #define CHECK_ROOTOK_TIMEOUT (IsDebuggerPresent() ? ((DWORD)-1) : (10*1000)) // под отладчиком - ждать всегда -#else - #define CHECK_ROOTOK_TIMEOUT (10*1000) -#endif -#define MAX_FORCEREFRESH_INTERVAL 500 -#define MAX_SYNCSETSIZE_WAIT 1000 -#define GUI_PIPE_TIMEOUT 300 -#define RELOAD_INFO_TIMEOUT 500 -#define EXTCONCOMMIT_TIMEOUT 500 -#define REQSIZE_TIMEOUT 5000 -#define GUIREADY_TIMEOUT 10000 -#define UPDATECONHANDLE_TIMEOUT 1000 -#define GUIATTACH_TIMEOUT 10000 -#define INPUT_QUEUE_TIMEOUT 100 -#define ATTACH2GUI_TIMEOUT 10000 -#define GUIATTACHEVENT_TIMEOUT 250 -#define REFRESH_FELL_SLEEP_TIMEOUT 3000 -#define LOCK_READOUTPUT_TIMEOUT 10000 -#define LOCK_REOPENCONOUT_TIMEOUT 250 -#define WAIT_SETCONSCRBUF_MAX_TIMEOUT 60000 -#define WAIT_SETCONSCRBUF_MIN_TIMEOUT 15000 -#define LOCK_REFRESH_CONTROL_TIMEOUT 2500 - -//#define IMAGE_SUBSYSTEM_DOS_EXECUTABLE 255 - -#define MAX_INPUT_QUEUE_EMPTY_WAIT 1000 -//#ifndef _DEBUG -// Релизный режим -#define FORCE_REDRAW_FIX -#define RELATIVE_TRANSMIT_DISABLE -//#else -//// Отладочный режим -////#define FORCE_REDRAW_FIX -//#endif - -#if !defined(CONSOLE_APPLICATION_16BIT) -#define CONSOLE_APPLICATION_16BIT 0x0001 -#endif - - -//#if defined(__GNUC__) -// //#include "assert.h" -// #ifndef _ASSERTE -// #define _ASSERTE(x) -// #endif -// #ifndef _ASSERT -// #define _ASSERT(x) -// #endif -//#else -// #include -//#endif - -#ifndef EVENT_CONSOLE_CARET -#define EVENT_CONSOLE_CARET 0x4001 -#define EVENT_CONSOLE_UPDATE_REGION 0x4002 -#define EVENT_CONSOLE_UPDATE_SIMPLE 0x4003 -#define EVENT_CONSOLE_UPDATE_SCROLL 0x4004 -#define EVENT_CONSOLE_LAYOUT 0x4005 -#define EVENT_CONSOLE_START_APPLICATION 0x4006 -#define EVENT_CONSOLE_END_APPLICATION 0x4007 -#endif - -//#undef USE_WINEVENT_SRV - -BOOL createProcess(BOOL abSkipWowChange, LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); - -BOOL ProcessSrvCommand(CESERVER_REQ& in, CESERVER_REQ** out); -//#ifdef USE_WINEVENT_SRV -//DWORD WINAPI WinEventThread(LPVOID lpvParam); -//void WINAPI WinEventProc(HWINEVENTHOOK hWinEventHook, DWORD anEvent, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime); -//#endif -void CheckCursorPos(); BOOL ReloadFullConsoleInfo(BOOL abForceSend); bool CheckWasFullScreen(); DWORD WINAPI RefreshThread(LPVOID lpvParam); // Thread reloading console contents @@ -252,84 +61,16 @@ bool ThawRefreshThread(); int ServerInit(); // Создать необходимые события и нити void ServerDone(int aiRc, bool abReportShutdown = false); BOOL ServerInitConsoleMode(); -void SetupCreateDumpOnException(); -int ComspecInit(); -void ComspecDone(int aiRc); -bool CoordInSmallRect(const COORD& cr, const SMALL_RECT& rc); -void RefillConsoleAttributes(const CONSOLE_SCREEN_BUFFER_INFO& csbi5, const WORD wOldText, const WORD wNewText); -BOOL SetConsoleSize(USHORT BufferHeight, COORD crNewSize, SMALL_RECT rNewRect, LPCSTR asLabel = NULL, bool bForceWriteLog = false); -void CreateLogSizeFile(int nLevel, const CESERVER_CONSOLE_MAPPING_HDR* pConsoleInfo = NULL); -void LogSize(const COORD* pcrSize, int newBufferHeight, LPCSTR pszLabel, bool bForceWriteLog = false); -void LogModeChange(LPCWSTR asName, DWORD oldVal, DWORD newVal); -bool LogString(LPCSTR asText); -bool LogString(LPCWSTR asText); -void PrintExecuteError(LPCWSTR asCmd, DWORD dwErr, LPCWSTR asSpecialInfo=NULL); BOOL MyReadConsoleOutput(HANDLE hOut, CHAR_INFO *pData, COORD& bufSize, SMALL_RECT& rgn); BOOL MyWriteConsoleOutput(HANDLE hOut, CHAR_INFO *pData, COORD& bufSize, COORD& crBufPos, SMALL_RECT& rgn); - -#if defined(__GNUC__) -extern "C" { -#endif - BOOL WINAPI HandlerRoutine(DWORD dwCtrlType); - int WINAPI RequestLocalServer(/*[IN/OUT]*/RequestLocalServerParm* Parm); -#if defined(__GNUC__) -}; -#endif - -int GetProcessCount(DWORD *rpdwPID, UINT nMaxCount); -BOOL CorrectVisibleRect(CONSOLE_SCREEN_BUFFER_INFO* pSbi); -bool MyLoadConsolePalette(HANDLE ahConOut, CESERVER_CONSOLE_PALETTE& Palette); -BOOL MyGetConsoleScreenBufferInfo(HANDLE ahConOut, PCONSOLE_SCREEN_BUFFER_INFO apsc); void CmdOutputStore(bool abCreateOnly = false); void CmdOutputRestore(bool abSimpleMode); + void CheckConEmuHwnd(); -HWND FindConEmuByPID(DWORD anSuggestedGuiPID = 0); -typedef BOOL (__stdcall *FGetConsoleKeyboardLayoutName)(wchar_t*); -extern FGetConsoleKeyboardLayoutName pfnGetConsoleKeyboardLayoutName; -void CheckKeyboardLayout(); -bool IsKeyboardLayoutChanged(DWORD& pdwLayout, LPDWORD pdwErrCode = NULL); -int CALLBACK FontEnumProc(ENUMLOGFONTEX *lpelfe, NEWTEXTMETRICEX *lpntme, DWORD FontType, LPARAM lParam); -typedef DWORD (WINAPI* FGetConsoleProcessList)(LPDWORD lpdwProcessList, DWORD dwProcessCount); -extern FGetConsoleProcessList pfnGetConsoleProcessList; -//BOOL HookWinEvents(int abEnabled); -void SendStarted(); -CESERVER_REQ* SendStopped(CONSOLE_SCREEN_BUFFER_INFO* psbi = NULL); -BOOL SendConsoleEvent(INPUT_RECORD* pr, UINT nCount); -typedef BOOL (WINAPI *FDebugActiveProcessStop)(DWORD dwProcessId); -extern FDebugActiveProcessStop pfnDebugActiveProcessStop; -typedef BOOL (WINAPI *FDebugSetProcessKillOnExit)(BOOL KillOnExit); -extern FDebugSetProcessKillOnExit pfnDebugSetProcessKillOnExit; -void ProcessDebugEvent(); -void _wprintf(LPCWSTR asBuffer); -bool IsOutputRedirected(); -void _printf(LPCSTR asBuffer); -void _printf(LPCSTR asFormat, DWORD dwErr); -void _printf(LPCSTR asFormat, DWORD dwErr, LPCWSTR asAddLine); -void _printf(LPCSTR asFormat, DWORD dw1, DWORD dw2, LPCWSTR asAddLine=NULL); -void print_error(DWORD dwErr = 0, LPCSTR asFormat = NULL); + HWND Attach2Gui(DWORD nTimeout); -CINFILTRATE_EXIT_CODES InjectRemote(DWORD nRemotePID, bool abDefTermOnly = false, LPDWORD pnErrCode = NULL); -CINFILTRATE_EXIT_CODES InfiltrateDll(HANDLE hProcess, LPCWSTR dll); - -int ParseCommandLine(LPCWSTR asCmdLine); -int GuiMacroCommandLine(LPCWSTR asCmdLine); -wchar_t* ParseConEmuSubst(LPCWSTR asCmd); -void ApplyEnvironmentCommands(LPCWSTR pszCommands); -void ApplyProcessSetEnvCmd(); -void UpdateConsoleTitle(); -BOOL SetTitle(LPCWSTR lsTitle); -void Help(); -void DosBoxHelp(); -int ExitWaitForKey(DWORD vkKeys, LPCWSTR asConfirm, BOOL abNewLine, BOOL abDontShowConsole, DWORD anMaxTimeout = 0); -bool IsMainServerPID(DWORD nPID); - -extern wchar_t gsSelfExe[MAX_PATH]; // Full path+exe to our executable -extern wchar_t gsSelfPath[MAX_PATH]; // Directory of our executable -void LoadExePath(); -void UnlockCurrentDirectory(); - bool AltServerWasStarted(DWORD nPID, HANDLE hAltServer, bool ForceThaw = false); int CreateMapHeader(); @@ -340,43 +81,13 @@ void InitAnsiLog(const ConEmuAnsiLog& AnsiLog); int Compare(const CESERVER_CONSOLE_MAPPING_HDR* p1, const CESERVER_CONSOLE_MAPPING_HDR* p2); void FixConsoleMappingHdr(CESERVER_CONSOLE_MAPPING_HDR *pMap); -enum LGSResult -{ - lgs_Failed = 0, - lgs_MapPtr, - lgs_WrongVersion, - lgs_WrongSize, - lgs_Succeeded, - lgs_ActiveChanged, - lgs_Updated, -}; -LGSResult ReloadGuiSettings(ConEmuGuiMapping* apFromCmd, LPDWORD pnWrongValue = NULL); - int CreateColorerHeader(bool bForceRecreate = false); -void DisableAutoConfirmExit(BOOL abFromFarPlugin=FALSE); - int MySetWindowRgn(CESERVER_REQ_SETWINDOWRGN* pRgn); bool IsAutoAttachAllowed(); -#ifdef _DEBUG - #undef WAIT_INPUT_READY -#else - #define WAIT_INPUT_READY -#endif -////#define USE_INPUT_SEMAPHORE -//#undef USE_INPUT_SEMAPHORE -//#define INSEMTIMEOUT_WRITE 250 -//#define INSEMTIMEOUT_READ 500 -//#ifdef USE_INPUT_SEMAPHORE -//extern HANDLE ghConInSemaphore; -//#endif -//void InitializeConsoleInputSemaphore(); -//void ReleaseConsoleInputSemaphore(); - /* Console Handles */ -//extern MConHandle ghConIn; extern MConHandle ghConOut; extern MConHandle gPrimaryBuffer, gAltBuffer; extern USHORT gnPrimaryBufferLastRow; @@ -384,32 +95,6 @@ void ConOutCloseHandle(); bool CmdOutputOpenMap(CONSOLE_SCREEN_BUFFER_INFO& lsbi, CESERVER_CONSAVE_MAPHDR*& pHdr, CESERVER_CONSAVE_MAP*& pData); bool isReopenHandleAllowed(); - -typedef enum tag_RunMode -{ - RM_UNDEFINED = 0, - RM_SERVER, - RM_COMSPEC, - RM_SETHOOK64, - RM_ALTSERVER, - RM_APPLICATION, - RM_GUIMACRO, - RM_AUTOATTACH, -} RunMode; - -extern RunMode gnRunMode; - -extern BOOL gbDumpServerInitStatus; -extern BOOL gbNoCreateProcess; -extern BOOL gbUseDosBox; -extern BOOL gbRootIsCmdExe; -extern BOOL gbAttachFromFar; -extern BOOL gbDefTermCall; -extern BOOL gbConsoleModeFlags; -extern DWORD gnConsoleModeFlags; -extern WORD gnDefTextColors, gnDefPopupColors; -extern BOOL gbVisibleOnStartup; - #ifdef WIN64 #ifndef __GNUC__ #pragma message("ComEmuC compiled in X64 mode") @@ -428,7 +113,7 @@ extern BOOL gbVisibleOnStartup; struct AltServerInfo { - DWORD nPID; // Для информации + DWORD nPID; // informational HANDLE hPrev; DWORD nPrevPID; }; @@ -437,9 +122,6 @@ struct ConProcess; #include "Debugger.h" -typedef BOOL (WINAPI* FGetConsoleDisplayMode)(LPDWORD); -extern FGetConsoleDisplayMode pfnGetConsoleDisplayMode; - struct SrvInfo { void InitFields(); @@ -522,7 +204,7 @@ struct SrvInfo CESERVER_REQ_CONINFO_FULL *pConsole; CHAR_INFO *pConsoleDataCopy; // Local (Alloc) MSectionSimple csReadConsoleInfo; - FGetConsoleDisplayMode pfnWasFullscreenMode; + bool wasFullscreenMode; // Input HANDLE hInputThread; DWORD dwInputThread; BOOL bInputTermination; @@ -605,111 +287,3 @@ struct SrvInfo DWORD nPreAliasSize; }; - -extern SrvInfo *gpSrv; -extern OSVERSIONINFO gOSVer; -extern WORD gnOsVer; -extern bool gbIsWine; -extern bool gbIsDBCS; -extern BOOL gbRootAliveLess10sec; -extern BOOL gbTerminateOnCtrlBreak; - -extern HMODULE ghOurModule; - -#define USER_IDLE_TIMEOUT ((DWORD)1000) -#define CHECK_IDLE_TIMEOUT 250 /* 1000 / 4 */ -#define USER_ACTIVITY ((gnBufferHeight == 0) || ((GetTickCount() - gpSrv->dwLastUserTick) <= USER_IDLE_TIMEOUT)) - -void PrintVersion(); - -extern COORD gcrVisibleSize; -extern BOOL gbParmVisibleSize, gbParmBufSize; -extern SHORT gnBufferHeight, gnBufferWidth; - -//extern HANDLE ghLogSize; -//extern wchar_t* wpszLogSizeFile; -class MFileLogEx; -extern MFileLogEx* gpLogSize; - - -extern BOOL gbInRecreateRoot; - - - -#include "ExitCodes.h" - - -#include - - -// Message Logger -// Originally from http://preshing.com/20120522/lightweight-in-memory-logging -namespace InputLogger -{ - static const int BUFFER_INFO_SIZE = RELEASEDEBUGTEST(0x1000,0x1000); // Must be a power of 2 - struct Event { - DWORD time; - enum Source { - evt_Empty, - evt_ReadInputQueue, - evt_SetEvent, - evt_ResetEvent, - evt_SendStart, - evt_SendEnd, - evt_ProcessInputMessage, - evt_WriteInputQueue1, - evt_WaitInputReady, - evt_WriteInputQueue2, - evt_InputQueueFlush, - evt_Overflow, - evt_SpeedHigh, - evt_SpeedLow, - evt_WaitConSize, - evt_WaitConEmpty, - evt_WriteConInput, - evt_ConSbiChanged, - evt_ConDataChanged, - } what; - LONG val; - INPUT_RECORD ir; - }; - extern Event g_evt[BUFFER_INFO_SIZE]; - extern LONG g_evtidx; - extern LONG g_overflow; - - inline void Log(Event::Source what, LONG val = 0) - { - // Get next message index - // Wrap to buffer size - LONG i = (_InterlockedIncrement(&g_evtidx) & (BUFFER_INFO_SIZE - 1)); - // Write a message at this index - g_evt[i].what = what; - g_evt[i].time = GetTickCount(); - g_evt[i].val = val; - g_evt[i].ir.EventType = 0; - } - - inline void Log(Event::Source what, const INPUT_RECORD& ir, LONG val = 0) - { - // Get next message index - // Wrap to buffer size - LONG i = (_InterlockedIncrement(&g_evtidx) & (BUFFER_INFO_SIZE - 1)); - // Write a message at this index - g_evt[i].what = what; - g_evt[i].time = GetTickCount(); - // Fill info - g_evt[i].val = val; - if (ir.EventType == KEY_EVENT) - { - ZeroStruct(g_evt[i].ir); - g_evt[i].ir.EventType = ir.EventType; - g_evt[i].ir.Event.KeyEvent.bKeyDown = ir.Event.KeyEvent.bKeyDown; - g_evt[i].ir.Event.KeyEvent.wRepeatCount = ir.Event.KeyEvent.wRepeatCount; - g_evt[i].ir.Event.KeyEvent.dwControlKeyState = ir.Event.KeyEvent.dwControlKeyState; - } - else - { - g_evt[i].ir = ir; - } - } -} diff --git a/src/ConEmuCD/ConProcess.cpp b/src/ConEmuCD/ConProcess.cpp index 3cce7dc53..c6b777f31 100644 --- a/src/ConEmuCD/ConProcess.cpp +++ b/src/ConEmuCD/ConProcess.cpp @@ -29,10 +29,12 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define SHOWDEBUGSTR #define DEBUGSTRPROC(x) DEBUGSTR(x) +#include "ConsoleMain.h" #include "ConEmuSrv.h" #include "ConProcess.h" #include "../common/MSection.h" #include "../common/ProcessData.h" +#include #define XTERM_PID_TIMEOUT 2500 diff --git a/src/ConEmuCD/ConsoleMain.cpp b/src/ConEmuCD/ConsoleMain.cpp index 2eb3ccac0..804fd2afd 100644 --- a/src/ConEmuCD/ConsoleMain.cpp +++ b/src/ConEmuCD/ConsoleMain.cpp @@ -29,8 +29,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #undef VALIDATE_AND_DELAY_ON_TERMINATE #ifdef _DEBUG -// Раскомментировать, чтобы сразу после запуска процесса (conemuc.exe) показать MessageBox, чтобы прицепиться дебаггером -// #define SHOW_STARTED_MSGBOX // #define SHOW_ADMIN_STARTED_MSGBOX // #define SHOW_MAIN_MSGBOX // #define SHOW_ALTERNATIVE_MSGBOX @@ -50,16 +48,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #define USE_PIPE_DEBUG_BOXES // #define SHOW_SETCONTITLE_MSGBOX #define SHOW_LOADCFGFILE_MSGBOX + #define SHOW_SHUTDOWNSRV_STEPS // #define DEBUG_ISSUE_623 // #define VALIDATE_AND_DELAY_ON_TERMINATE - -#elif defined(__GNUC__) -// Раскомментировать, чтобы сразу после запуска процесса (conemuc.exe) показать MessageBox, чтобы прицепиться дебаггером -// #define SHOW_STARTED_MSGBOX -#else -// #endif #define SHOWDEBUGSTR @@ -71,7 +64,9 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //#define SHOW_INJECT_MSGBOX +#include "ConsoleMain.h" #include "ConEmuSrv.h" +#include "ConEmuCmd.h" #include "../common/CmdLine.h" #include "../common/ConsoleAnnotation.h" #include "../common/ConsoleMixAttr.h" @@ -120,6 +115,7 @@ WARNING("Обязательно после запуска сделать apiSetF WARNING("Обязательно получить код и имя родительского процесса"); #ifdef USEPIPELOG +// required global variables for PipeServer.h namespace PipeServerLogger { Event g_events[BUFFER_SIZE]; @@ -151,13 +147,6 @@ FDebugSetProcessKillOnExit pfnDebugSetProcessKillOnExit = NULL; FGetConsoleDisplayMode pfnGetConsoleDisplayMode = NULL; -/* Console Handles */ -//MConHandle ghConIn ( L"CONIN$" ); -MConHandle ghConOut(L"CONOUT$"); -//Used to store and restore console screen buffers in cmd_AltBuffer -MConHandle gPrimaryBuffer(NULL), gAltBuffer(NULL); -USHORT gnPrimaryBufferLastRow = 0; // last detected written row in gPrimaryBuffer - // Время ожидания завершения консольных процессов, когда юзер нажал крестик в КОНСОЛЬНОМ окне // The system also displays this dialog box if the process does not respond within a certain time-out period // (5 seconds for CTRL_CLOSE_EVENT, and 20 seconds for CTRL_LOGOFF_EVENT or CTRL_SHUTDOWN_EVENT). @@ -172,8 +161,6 @@ wchar_t gsModuleName[32] = L""; wchar_t gsVersion[20] = L""; wchar_t gsSelfExe[MAX_PATH] = L""; // Full path+exe to our executable wchar_t gsSelfPath[MAX_PATH] = L""; // Directory of our executable -BOOL gbTerminateOnExit = FALSE; -//HANDLE ghConIn = NULL, ghConOut = NULL; HWND ghConWnd = NULL; DWORD gnConEmuPID = 0; // PID of ConEmu[64].exe (ghConEmuWnd) HWND ghConEmuWnd = NULL; // Root! window @@ -240,7 +227,7 @@ BOOL gbConsoleModeFlags = TRUE; DWORD gnConsoleModeFlags = 0; //(ENABLE_QUICK_EDIT_MODE|ENABLE_INSERT_MODE); WORD gnDefTextColors = 0, gnDefPopupColors = 0; // Передаются через "/TA=..." BOOL gbVisibleOnStartup = FALSE; -OSVERSIONINFO gOSVer; +OSVERSIONINFO gOSVer = {}; WORD gnOsVer = 0x500; bool gbIsWine = false; bool gbIsDBCS = false; @@ -265,13 +252,6 @@ MFileLogEx* gpLogSize = NULL; BOOL gbInRecreateRoot = FALSE; -namespace InputLogger -{ - Event g_evt[BUFFER_INFO_SIZE]; - LONG g_evtidx = -1; - LONG g_overflow = 0; -}; - namespace StdCon { @@ -4882,6 +4862,93 @@ bool isConEmuTerminated() return true; } +static BOOL CALLBACK FindConEmuByPidProc(HWND hwnd, LPARAM lParam) +{ + DWORD dwPID; + GetWindowThreadProcessId(hwnd, &dwPID); + if (dwPID == gnConEmuPID) + { + wchar_t szClass[128]; + if (GetClassName(hwnd, szClass, countof(szClass))) + { + if (lstrcmp(szClass, VirtualConsoleClassMain) == 0) + { + *(HWND*)lParam = hwnd; + return FALSE; + } + } + } + return TRUE; +} + +HWND FindConEmuByPID(DWORD anSuggestedGuiPID /*= 0*/) +{ + LogFunction(L"FindConEmuByPID"); + + HWND hConEmuWnd = NULL; + DWORD nConEmuPID = anSuggestedGuiPID ? anSuggestedGuiPID : gnConEmuPID; + DWORD dwGuiThreadId = 0, dwGuiProcessId = 0; + + // В большинстве случаев PID GUI передан через параметры + if (nConEmuPID == 0) + { + // GUI может еще "висеть" в ожидании или в отладчике, так что пробуем и через Snapshot + //TODO: Reuse MToolHelp.h + HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); + + if (hSnap != INVALID_HANDLE_VALUE) + { + PROCESSENTRY32 prc = {sizeof(PROCESSENTRY32)}; + + if (Process32First(hSnap, &prc)) + { + do + { + if (prc.th32ProcessID == gnSelfPID) + { + nConEmuPID = prc.th32ParentProcessID; + break; + } + } + while (Process32Next(hSnap, &prc)); + } + + CloseHandle(hSnap); + } + } + + if (nConEmuPID) + { + HWND hGui = NULL; + + while ((hGui = FindWindowEx(NULL, hGui, VirtualConsoleClassMain, NULL)) != NULL) + { + dwGuiThreadId = GetWindowThreadProcessId(hGui, &dwGuiProcessId); + + if (dwGuiProcessId == nConEmuPID) + { + hConEmuWnd = hGui; + break; + } + } + + // Если "в лоб" по имени класса ничего не нашли - смотрим + // среди всех дочерних для текущего десктопа + if ((hConEmuWnd == NULL) && !anSuggestedGuiPID) + { + HWND hDesktop = GetDesktopWindow(); + EnumChildWindows(hDesktop, FindConEmuByPidProc, (LPARAM)&hConEmuWnd); + } + } + + // Ensure that returned hConEmuWnd match gnConEmuPID + if (!anSuggestedGuiPID && hConEmuWnd) + { + GetWindowThreadProcessId(hConEmuWnd, &gnConEmuPID); + } + + return hConEmuWnd; +} void SendStarted() { @@ -5430,6 +5497,190 @@ CESERVER_REQ* SendStopped(CONSOLE_SCREEN_BUFFER_INFO* psbi) return pOut; } +LGSResult LoadGuiSettingsPtr(ConEmuGuiMapping& GuiMapping, const ConEmuGuiMapping* pInfo, bool abNeedReload, bool abForceCopy, DWORD& rnWrongValue) +{ + LGSResult liRc = lgs_Failed; + DWORD cbSize = 0; + bool lbNeedCopy = false; + bool lbCopied = false; + wchar_t szLog[80]; + + if (!pInfo) + { + liRc = lgs_MapPtr; + wcscpy_c(szLog, L"LoadGuiSettings(Failed, MapPtr is null)"); + LogFunction(szLog); + goto wrap; + } + + if (abForceCopy) + { + cbSize = std::min(sizeof(GuiMapping), pInfo->cbSize); + memmove(&GuiMapping, pInfo, cbSize); + gpSrv->guiSettings.cbSize = cbSize; + lbCopied = true; + } + + if (pInfo->cbSize >= (size_t)(sizeof(pInfo->nProtocolVersion) + ((LPBYTE)&pInfo->nProtocolVersion) - (LPBYTE)pInfo)) + { + if (pInfo->nProtocolVersion != CESERVER_REQ_VER) + { + liRc = lgs_WrongVersion; + rnWrongValue = pInfo->nProtocolVersion; + wcscpy_c(szLog, L"LoadGuiSettings(Failed, MapPtr is null)"); + swprintf_c(szLog, L"LoadGuiSettings(Failed, Version=%u, Required=%u)", rnWrongValue, (DWORD)CESERVER_REQ_VER); + LogFunction(szLog); + goto wrap; + } + } + + if (pInfo->cbSize != sizeof(ConEmuGuiMapping)) + { + liRc = lgs_WrongSize; + rnWrongValue = pInfo->cbSize; + swprintf_c(szLog, L"LoadGuiSettings(Failed, cbSize=%u, Required=%u)", pInfo->cbSize, (DWORD)sizeof(ConEmuGuiMapping)); + LogFunction(szLog); + goto wrap; + } + + lbNeedCopy = abNeedReload + || (gpSrv->guiSettingsChangeNum != pInfo->nChangeNum) + || (GuiMapping.bGuiActive != pInfo->bGuiActive) + ; + + if (lbNeedCopy) + { + wcscpy_c(szLog, L"LoadGuiSettings(Changed)"); + LogFunction(szLog); + if (!lbCopied) + memmove(&GuiMapping, pInfo, pInfo->cbSize); + _ASSERTE(GuiMapping.ComSpec.ConEmuExeDir[0]!=0 && GuiMapping.ComSpec.ConEmuBaseDir[0]!=0); + liRc = lgs_Updated; + } + else if (GuiMapping.dwActiveTick != pInfo->dwActiveTick) + { + // But active consoles list may be changed + if (!lbCopied) + memmove(GuiMapping.Consoles, pInfo->Consoles, sizeof(GuiMapping.Consoles)); + liRc = lgs_ActiveChanged; + } + else + { + liRc = lgs_Succeeded; + } + +wrap: + return liRc; +} + +LGSResult LoadGuiSettings(ConEmuGuiMapping& GuiMapping, DWORD& rnWrongValue) +{ + LGSResult liRc = lgs_Failed; + bool lbNeedReload = false; + DWORD dwGuiThreadId, dwGuiProcessId; + HWND hGuiWnd = ghConEmuWnd ? ghConEmuWnd : gpSrv->hGuiWnd; + const ConEmuGuiMapping* pInfo = NULL; + + if (!hGuiWnd || !IsWindow(hGuiWnd)) + { + LogFunction(L"LoadGuiSettings(Invalid window)"); + goto wrap; + } + + if (!gpSrv->pGuiInfoMap || (gpSrv->hGuiInfoMapWnd != hGuiWnd)) + { + lbNeedReload = true; + } + + if (lbNeedReload) + { + LogFunction(L"LoadGuiSettings(Opening)"); + + dwGuiThreadId = GetWindowThreadProcessId(hGuiWnd, &dwGuiProcessId); + if (!dwGuiThreadId) + { + _ASSERTE(dwGuiProcessId); + LogFunction(L"LoadGuiSettings(Failed, dwGuiThreadId==0)"); + goto wrap; + } + + if (!gpSrv->pGuiInfoMap) + gpSrv->pGuiInfoMap = new MFileMapping; + else + gpSrv->pGuiInfoMap->CloseMap(); + + gpSrv->pGuiInfoMap->InitName(CEGUIINFOMAPNAME, dwGuiProcessId); + pInfo = gpSrv->pGuiInfoMap->Open(); + + if (pInfo) + { + gpSrv->hGuiInfoMapWnd = hGuiWnd; + } + } + else + { + pInfo = gpSrv->pGuiInfoMap->Ptr(); + } + + liRc = LoadGuiSettingsPtr(GuiMapping, pInfo, lbNeedReload, false, rnWrongValue); +wrap: + return liRc; +} + +LGSResult ReloadGuiSettings(ConEmuGuiMapping* apFromCmd, LPDWORD pnWrongValue /*= NULL*/) +{ + bool lbChanged = false; + LGSResult lgsResult = lgs_Failed; + DWORD nWrongValue = 0; + + if (apFromCmd) + { + LogFunction(L"ReloadGuiSettings(apFromCmd)"); + lgsResult = LoadGuiSettingsPtr(gpSrv->guiSettings, apFromCmd, false, true, nWrongValue); + lbChanged = (lgsResult >= lgs_Succeeded); + } + else + { + gpSrv->guiSettings.cbSize = sizeof(ConEmuGuiMapping); + lgsResult = LoadGuiSettings(gpSrv->guiSettings, nWrongValue); + lbChanged = (lgsResult >= lgs_Succeeded) + && ((gpSrv->guiSettingsChangeNum != gpSrv->guiSettings.nChangeNum) + || (gpSrv->pConsole && gpSrv->pConsole->hdr.ComSpec.ConEmuExeDir[0] == 0)); + } + + if (pnWrongValue) + *pnWrongValue = nWrongValue; + + if (lbChanged) + { + LogFunction(L"ReloadGuiSettings(Apply)"); + + gpSrv->guiSettingsChangeNum = gpSrv->guiSettings.nChangeNum; + + gbLogProcess = (gpSrv->guiSettings.nLoggingType == glt_Processes); + + UpdateComspec(&gpSrv->guiSettings.ComSpec); // isAddConEmu2Path, ... + + SetConEmuFolders(gpSrv->guiSettings.ComSpec.ConEmuExeDir, gpSrv->guiSettings.ComSpec.ConEmuBaseDir); + + // Не будем ставить сами, эту переменную заполняет Gui при своем запуске + // соответственно, переменная наследуется серверами + //SetEnvironmentVariableW(L"ConEmuArgs", pInfo->sConEmuArgs); + + //wchar_t szHWND[16]; swprintf_c(szHWND, L"0x%08X", gpSrv->guiSettings.hGuiWnd.u); + //SetEnvironmentVariable(ENV_CONEMUHWND_VAR_W, szHWND); + SetConEmuWindows(gpSrv->guiSettings.hGuiWnd, ghConEmuWndDC, ghConEmuWndBack); + + if (gpSrv->pConsole) + { + CopySrvMapFromGuiMap(); + + UpdateConsoleMapHeader(L"guiSettings were changed"); + } + } + + return lgsResult; +} void CreateLogSizeFile(int nLevel, const CESERVER_CONSOLE_MAPPING_HDR* pConsoleInfo /*= NULL*/) { @@ -6682,6 +6933,7 @@ void RefillConsoleAttributes(const CONSOLE_SCREEN_BUFFER_INFO& csbi5, const WORD // crNewSize - размер ОКНА (ширина окна == ширине буфера) // rNewRect - для (BufferHeight!=0) определяет new upper-left and lower-right corners of the window // !!! rNewRect по идее вообще не нужен, за блокировку при прокрутке отвечает nSendTopLine +// #PTY move to Server part BOOL SetConsoleSize(USHORT BufferHeight, COORD crNewSize, SMALL_RECT rNewRect, LPCSTR asLabel, bool bForceWriteLog) { _ASSERTE(ghConWnd); diff --git a/src/ConEmuCD/ConsoleMain.h b/src/ConEmuCD/ConsoleMain.h new file mode 100644 index 000000000..089a09ec2 --- /dev/null +++ b/src/ConEmuCD/ConsoleMain.h @@ -0,0 +1,342 @@ + +/* +Copyright (c) 2009-present Maximus5 +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +#pragma once + +#include "../common/defines.h" +#include "../common/RConStartArgs.h" + +#ifdef _DEBUG +// #define SHOW_STARTED_MSGBOX // immediately after ConEmuC.exe process start show MessageBox, allows debugger attach +#define PRINT_COMSPEC(f,a) //wprintf(f,a) // prints to ConOut Comspec mode information +#define _DEBUGSTR(s) //OutputDebugString(s) + +#elif defined(__GNUC__) +// #define SHOW_STARTED_MSGBOX // immediately after ConEmuC.exe process start show MessageBox, allows debugger attach +#define PRINT_COMSPEC(f,a) //wprintf(f,a) +#define _DEBUGSTR(s) + +#else +#define PRINT_COMSPEC(f,a) +#define _DEBUGSTR(s) + +#endif + +#ifdef _DEBUG +#define xf_check() { xf_validate(); xf_dump_chk(); } +#else +#define xf_check() +#endif + +#define DEBUGLOG(s) //DEBUGSTR(s) +#define DEBUGLOGSIZE(s) DEBUGSTR(s) +#define DEBUGLOGLANG(s) //DEBUGSTR(s) //; Sleep(2000) + +#define CSECTION_NON_RAISE + +void ShutdownSrvStep(LPCWSTR asInfo, int nParm1 = 0, int nParm2 = 0, int nParm3 = 0, int nParm4 = 0); + +enum SetTerminateEventPlace +{ + ste_None = 0, + ste_ServerDone, + ste_ConsoleMain, + ste_ProcessCountChanged, + ste_CheckProcessCount, + ste_DebugThread, + ste_WriteMiniDump, + ste_CmdDetachCon, + ste_HandlerRoutine, + ste_Attach2GuiFailed, +}; +extern SetTerminateEventPlace gTerminateEventPlace; +void SetTerminateEvent(SetTerminateEventPlace eFrom); + +bool isConEmuTerminated(); + +/* Global */ +extern DWORD gnSelfPID; +extern wchar_t gsModuleName[32]; +extern wchar_t gsVersion[20]; +extern wchar_t gsSelfExe[MAX_PATH]; // Full path+exe to our executable +extern wchar_t gsSelfPath[MAX_PATH]; // Directory of our executable +//HANDLE ghConIn = NULL, ghConOut = NULL; +extern HWND ghConWnd; +extern DWORD gnConEmuPID; // PID of ConEmu[64].exe (ghConEmuWnd) +extern HWND ghConEmuWnd; // Root! window +extern HWND ghConEmuWndDC; // ConEmu DC window +extern HWND ghConEmuWndBack; // ConEmu Back window +extern void SetConEmuWindows(HWND hRootWnd, HWND hDcWnd, HWND hBackWnd); +extern void SetConEmuFolders(LPCWSTR asExeDir, LPCWSTR asBaseDir); +extern DWORD gnMainServerPID; // PID сервера (инициализируется на старте, при загрузке Dll) +extern DWORD gnAltServerPID; // PID сервера (инициализируется на старте, при загрузке Dll) +extern BOOL gbLogProcess; // (pInfo->nLoggingType == glt_Processes) +extern BOOL gbWasBufferHeight; +extern BOOL gbNonGuiMode; +extern DWORD gnExitCode; +extern HANDLE ghExitQueryEvent; // выставляется когда в консоли не остается процессов +extern int nExitQueryPlace, nExitPlaceStep, nExitPlaceThread; +extern HANDLE ghQuitEvent; // когда мы в процессе закрытия (юзер уже нажал кнопку "Press to close console") +extern bool gbQuit; // когда мы в процессе закрытия (юзер уже нажал кнопку "Press to close console") +extern bool gbSkipHookersCheck; +extern RConStartArgs::CloseConfirm gnConfirmExitParm; +extern BOOL gbAlwaysConfirmExit, gbInShutdown, gbAutoDisableConfirmExit; +extern int gbRootWasFoundInCon; +extern BOOL gbComspecInitCalled; +typedef DWORD AttachModeEnum; +const AttachModeEnum + am_Simple = 0x0001, // As is + am_Auto = 0x0002, // Same as am_Simple, but always return 0 as errorlevel + am_Modes = (am_Simple|am_Auto), + am_Async = 0x0010, // "/AUTOATTACH" must be async to be able to call from cmd prompt + am_DefTerm = 0x0020, // "/ + am_Admin = 0x1000, // Special "attach" when ConEmu is run under "User" and console "As admin" + am_None = 0 +; +extern AttachModeEnum gbAttachMode; // сервер запущен НЕ из conemu.exe (а из плагина, из CmdAutoAttach, или -new_console) +extern BOOL gbAlternativeAttach; // TRUE - Подцепиться к существующей консоли, без внедрения в процесс ConEmuHk.dll +extern BOOL gbAlienMode; // сервер НЕ является владельцем консоли (корневым процессом этого консольного окна) +extern BOOL gbDontInjectConEmuHk; +extern BOOL gbForceHideConWnd; +extern DWORD gdwMainThreadId; +extern wchar_t* gpszRunCmd; +extern wchar_t* gpszRootExe; +extern bool gbRunInBackgroundTab; +extern DWORD gnImageSubsystem; +#ifdef _DEBUG +extern size_t gnHeapUsed, gnHeapMax; +extern HANDLE ghFarInExecuteEvent; +#endif + +#include "../common/Common.h" +#include "../common/ConEmuCheck.h" +#include "../common/MConHandle.h" +#include "../common/MFileMapping.h" +#include "../common/MFileLogEx.h" +#include "../common/MSection.h" +#include "../common/WObjects.h" +#include "../common/ConsoleAnnotation.h" +#include "../common/InQueue.h" +#include "ExitCodes.h" +#include "LogFunction.h" + + +#define START_MAX_PROCESSES 1000 +#define CHECK_PROCESSES_TIMEOUT 500 +#define CHECK_ANTIVIRUS_TIMEOUT (6*1000) +#define CHECK_ROOTSTART_TIMEOUT (10*1000) +#ifdef _DEBUG + #define CHECK_ROOTOK_TIMEOUT (IsDebuggerPresent() ? ((DWORD)-1) : (10*1000)) // while debugging - wait infinitive +#else + #define CHECK_ROOTOK_TIMEOUT (10*1000) +#endif +#define MAX_FORCEREFRESH_INTERVAL 500 +#define MAX_SYNCSETSIZE_WAIT 1000 +#define GUI_PIPE_TIMEOUT 300 +#define RELOAD_INFO_TIMEOUT 500 +#define EXTCONCOMMIT_TIMEOUT 500 +#define REQSIZE_TIMEOUT 5000 +#define GUIREADY_TIMEOUT 10000 +#define UPDATECONHANDLE_TIMEOUT 1000 +#define GUIATTACH_TIMEOUT 10000 +#define INPUT_QUEUE_TIMEOUT 100 +#define ATTACH2GUI_TIMEOUT 10000 +#define GUIATTACHEVENT_TIMEOUT 250 +#define REFRESH_FELL_SLEEP_TIMEOUT 3000 +#define LOCK_READOUTPUT_TIMEOUT 10000 +#define LOCK_REOPENCONOUT_TIMEOUT 250 +#define WAIT_SETCONSCRBUF_MAX_TIMEOUT 60000 +#define WAIT_SETCONSCRBUF_MIN_TIMEOUT 15000 +#define LOCK_REFRESH_CONTROL_TIMEOUT 2500 + +//#define IMAGE_SUBSYSTEM_DOS_EXECUTABLE 255 + +#define MAX_INPUT_QUEUE_EMPTY_WAIT 1000 + + + +#if !defined(CONSOLE_APPLICATION_16BIT) +#define CONSOLE_APPLICATION_16BIT 0x0001 +#endif + +#ifndef EVENT_CONSOLE_CARET +#define EVENT_CONSOLE_CARET 0x4001 +#define EVENT_CONSOLE_UPDATE_REGION 0x4002 +#define EVENT_CONSOLE_UPDATE_SIMPLE 0x4003 +#define EVENT_CONSOLE_UPDATE_SCROLL 0x4004 +#define EVENT_CONSOLE_LAYOUT 0x4005 +#define EVENT_CONSOLE_START_APPLICATION 0x4006 +#define EVENT_CONSOLE_END_APPLICATION 0x4007 +#endif + +//#undef USE_WINEVENT_SRV + +BOOL createProcess(BOOL abSkipWowChange, LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); +void SetupCreateDumpOnException(); +void RefillConsoleAttributes(const CONSOLE_SCREEN_BUFFER_INFO& csbi5, const WORD wOldText, const WORD wNewText); +BOOL SetConsoleSize(USHORT BufferHeight, COORD crNewSize, SMALL_RECT rNewRect, LPCSTR asLabel = NULL, bool bForceWriteLog = false); +void CreateLogSizeFile(int nLevel, const CESERVER_CONSOLE_MAPPING_HDR* pConsoleInfo = NULL); +void LogSize(const COORD* pcrSize, int newBufferHeight, LPCSTR pszLabel, bool bForceWriteLog = false); +void LogModeChange(LPCWSTR asName, DWORD oldVal, DWORD newVal); +bool LogString(LPCSTR asText); +bool LogString(LPCWSTR asText); +void PrintExecuteError(LPCWSTR asCmd, DWORD dwErr, LPCWSTR asSpecialInfo=NULL); + +#if defined(__GNUC__) +extern "C" { +#endif + BOOL WINAPI HandlerRoutine(DWORD dwCtrlType); + int WINAPI RequestLocalServer(/*[IN/OUT]*/RequestLocalServerParm* Parm); +#if defined(__GNUC__) +}; +#endif + +int GetProcessCount(DWORD *rpdwPID, UINT nMaxCount); +bool MyLoadConsolePalette(HANDLE ahConOut, CESERVER_CONSOLE_PALETTE& Palette); +BOOL MyGetConsoleScreenBufferInfo(HANDLE ahConOut, PCONSOLE_SCREEN_BUFFER_INFO apsc); +HWND FindConEmuByPID(DWORD anSuggestedGuiPID = 0); + +void CheckKeyboardLayout(); +bool IsKeyboardLayoutChanged(DWORD& pdwLayout, LPDWORD pdwErrCode = NULL); +typedef BOOL (__stdcall *FGetConsoleKeyboardLayoutName)(wchar_t*); +extern FGetConsoleKeyboardLayoutName pfnGetConsoleKeyboardLayoutName; + +int CALLBACK FontEnumProc(ENUMLOGFONTEX *lpelfe, NEWTEXTMETRICEX *lpntme, DWORD FontType, LPARAM lParam); +typedef DWORD (WINAPI* FGetConsoleProcessList)(LPDWORD lpdwProcessList, DWORD dwProcessCount); +extern FGetConsoleProcessList pfnGetConsoleProcessList; + +void SendStarted(); +CESERVER_REQ* SendStopped(CONSOLE_SCREEN_BUFFER_INFO* psbi = NULL); + +typedef BOOL (WINAPI *FDebugActiveProcessStop)(DWORD dwProcessId); +extern FDebugActiveProcessStop pfnDebugActiveProcessStop; + +typedef BOOL (WINAPI *FDebugSetProcessKillOnExit)(BOOL KillOnExit); +extern FDebugSetProcessKillOnExit pfnDebugSetProcessKillOnExit; + +typedef BOOL (WINAPI* FGetConsoleDisplayMode)(LPDWORD); +extern FGetConsoleDisplayMode pfnGetConsoleDisplayMode; + +bool IsOutputRedirected(); +void _wprintf(LPCWSTR asBuffer); +void _printf(LPCSTR asBuffer); +void _printf(LPCSTR asFormat, DWORD dwErr); +void _printf(LPCSTR asFormat, DWORD dwErr, LPCWSTR asAddLine); +void _printf(LPCSTR asFormat, DWORD dw1, DWORD dw2, LPCWSTR asAddLine=NULL); +void print_error(DWORD dwErr = 0, LPCSTR asFormat = NULL); + +int ParseCommandLine(LPCWSTR asCmdLine); +wchar_t* ParseConEmuSubst(LPCWSTR asCmd); +void ApplyEnvironmentCommands(LPCWSTR pszCommands); +void ApplyProcessSetEnvCmd(); +void UpdateConsoleTitle(); +BOOL SetTitle(LPCWSTR lsTitle); +void Help(); +void DosBoxHelp(); +int ExitWaitForKey(DWORD vkKeys, LPCWSTR asConfirm, BOOL abNewLine, BOOL abDontShowConsole, DWORD anMaxTimeout = 0); +bool IsMainServerPID(DWORD nPID); + +void LoadExePath(); +void UnlockCurrentDirectory(); + +enum LGSResult +{ + lgs_Failed = 0, + lgs_MapPtr, + lgs_WrongVersion, + lgs_WrongSize, + lgs_Succeeded, + lgs_ActiveChanged, + lgs_Updated, +}; +LGSResult ReloadGuiSettings(ConEmuGuiMapping* apFromCmd, LPDWORD pnWrongValue = NULL); + +void DisableAutoConfirmExit(BOOL abFromFarPlugin=FALSE); + + +typedef enum tag_RunMode +{ + RM_UNDEFINED = 0, + RM_SERVER, + RM_COMSPEC, + RM_SETHOOK64, + RM_ALTSERVER, + RM_APPLICATION, + RM_GUIMACRO, + RM_AUTOATTACH, +} RunMode; + +extern RunMode gnRunMode; + +extern BOOL gbDumpServerInitStatus; +extern BOOL gbNoCreateProcess; +extern BOOL gbRootIsCmdExe; +extern BOOL gbAttachFromFar; +extern BOOL gbDefTermCall; +extern BOOL gbConsoleModeFlags; +extern DWORD gnConsoleModeFlags; +extern WORD gnDefTextColors, gnDefPopupColors; +extern BOOL gbVisibleOnStartup; + +#include "../common/PipeServer.h" +#include "../common/MArray.h" +#include "../common/MMap.h" + +struct ConProcess; + +#include "Debugger.h" + +struct SrvInfo; +extern SrvInfo *gpSrv; +extern OSVERSIONINFO gOSVer; +extern WORD gnOsVer; +extern bool gbIsWine; +extern bool gbIsDBCS; +extern BOOL gbRootAliveLess10sec; +extern BOOL gbTerminateOnCtrlBreak; + +extern HMODULE ghOurModule; + +#define USER_IDLE_TIMEOUT ((DWORD)1000) +#define CHECK_IDLE_TIMEOUT 250 /* 1000 / 4 */ +#define USER_ACTIVITY ((gnBufferHeight == 0) || ((GetTickCount() - gpSrv->dwLastUserTick) <= USER_IDLE_TIMEOUT)) + +void PrintVersion(); + +extern COORD gcrVisibleSize; +extern BOOL gbParmVisibleSize, gbParmBufSize; +extern SHORT gnBufferHeight, gnBufferWidth; + +//extern HANDLE ghLogSize; +//extern wchar_t* wpszLogSizeFile; +class MFileLogEx; +extern MFileLogEx* gpLogSize; + + +extern BOOL gbInRecreateRoot; diff --git a/src/ConEmuCD/Debugger.cpp b/src/ConEmuCD/Debugger.cpp index 76c7a972e..b09cf89e0 100644 --- a/src/ConEmuCD/Debugger.cpp +++ b/src/ConEmuCD/Debugger.cpp @@ -31,6 +31,7 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define DEBUGSTRFIN(x) DEBUGSTR(x) #define DEBUGSTRCP(x) DEBUGSTR(x) +#include "ConsoleMain.h" #include "ConEmuSrv.h" #include "../common/shlobj.h" #include "../ConEmu/version.h" diff --git a/src/ConEmuCD/Debugger.h b/src/ConEmuCD/Debugger.h index 7fc0f7c0a..c8ff13df5 100644 --- a/src/ConEmuCD/Debugger.h +++ b/src/ConEmuCD/Debugger.h @@ -28,6 +28,7 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #pragma once +void ProcessDebugEvent(); int AttachRootProcessHandle(); int RunDebugger(); void GenerateMiniDumpFromCtrlBreak(); diff --git a/src/ConEmuCD/DownloaderCall.cpp b/src/ConEmuCD/DownloaderCall.cpp index fec16b046..afa9e8be8 100644 --- a/src/ConEmuCD/DownloaderCall.cpp +++ b/src/ConEmuCD/DownloaderCall.cpp @@ -27,7 +27,7 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #define HIDE_USE_EXCEPTION_INFO -#include +#include "ConsoleMain.h" #include "../common/defines.h" #include "../common/EnvVar.h" #include "../common/MAssert.h" diff --git a/src/ConEmuCD/GuiMacro.cpp b/src/ConEmuCD/GuiMacro.cpp index 875cd83df..9e8b0c4d3 100644 --- a/src/ConEmuCD/GuiMacro.cpp +++ b/src/ConEmuCD/GuiMacro.cpp @@ -30,6 +30,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define HIDE_USE_EXCEPTION_INFO #define SHOWDEBUGSTR +#include "ConsoleMain.h" + #include "../common/Common.h" #include "../common/CmdLine.h" #include "../common/ConEmuCheck.h" @@ -38,7 +40,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../common/ProcessData.h" #include "Actions.h" -#include "ConEmuSrv.h" #include "GuiMacro.h" bool gbPreferSilentMode = false; diff --git a/src/ConEmuCD/GuiMacro.h b/src/ConEmuCD/GuiMacro.h index 406dbfd6e..a27e1c68f 100644 --- a/src/ConEmuCD/GuiMacro.h +++ b/src/ConEmuCD/GuiMacro.h @@ -57,3 +57,5 @@ int DoGuiMacro(LPCWSTR asCmdArg, MacroInstance& Inst, GuiMacroFlags Flags, BSTR* extern "C" #endif int __stdcall GuiMacro(LPCWSTR asInstance, LPCWSTR asMacro, BSTR* bsResult = NULL); + +int GuiMacroCommandLine(LPCWSTR asCmdLine); diff --git a/src/ConEmuCD/Infiltrate.h b/src/ConEmuCD/Infiltrate.h index 1ebad71dd..97d5dcdb9 100644 --- a/src/ConEmuCD/Infiltrate.h +++ b/src/ConEmuCD/Infiltrate.h @@ -1,11 +1,38 @@  -#ifndef _INFILTRATE_HEADER_ -#define _INFILTRATE_HEADER_ +/* +Copyright (c) 2013-present Maximus5 +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#pragma once typedef HMODULE (WINAPI* LoadLibraryW_t)(LPCWSTR); typedef DWORD (WINAPI* GetLastError_t)(); typedef void (WINAPI* SetLastError_t)(DWORD dwErrCode); -typedef HANDLE (WINAPI* CreateRemoteThread_t)(HANDLE hProcess, LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId); +typedef HANDLE (WINAPI* CreateRemoteThread_t)(HANDLE hProcess, LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, + LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId); struct InfiltrateArg @@ -19,5 +46,3 @@ struct InfiltrateArg }; size_t GetInfiltrateProc(void** ppCode); - -#endif diff --git a/src/ConEmuCD/InjectRemote.cpp b/src/ConEmuCD/InjectRemote.cpp index b6c561bc2..cdd4bdb4d 100644 --- a/src/ConEmuCD/InjectRemote.cpp +++ b/src/ConEmuCD/InjectRemote.cpp @@ -26,15 +26,17 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "ConEmuSrv.h" +#include "ConsoleMain.h" +#include "InjectRemote.h" +#include "Infiltrate.h" #include "../common/MAssert.h" #include "../common/MProcessBits.h" #include "../common/WFiles.h" #include "../common/WModuleCheck.h" -#include "Infiltrate.h" #include "../ConEmuHk/Injects.h" #include "../ConEmu/version.h" #include "../common/shlobj.h" +#include // 0 - OK, иначе - ошибка // Здесь вызывается CreateRemoteThread diff --git a/src/ConEmuCD/InjectRemote.h b/src/ConEmuCD/InjectRemote.h new file mode 100644 index 000000000..8f546517b --- /dev/null +++ b/src/ConEmuCD/InjectRemote.h @@ -0,0 +1,32 @@ + +/* +Copyright (c) 2013-present Maximus5 +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#pragma once + +CINFILTRATE_EXIT_CODES InjectRemote(DWORD nRemotePID, bool abDefTermOnly = false, LPDWORD pnErrCode = NULL); +CINFILTRATE_EXIT_CODES InfiltrateDll(HANDLE hProcess, LPCWSTR dll); diff --git a/src/ConEmuCD/InputLogger.cpp b/src/ConEmuCD/InputLogger.cpp new file mode 100644 index 000000000..866677426 --- /dev/null +++ b/src/ConEmuCD/InputLogger.cpp @@ -0,0 +1,36 @@ + +/* +Copyright (c) 2009-present Maximus5 +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include "InputLogger.h" + +namespace InputLogger +{ + Event g_evt[BUFFER_INFO_SIZE]; + LONG g_evtidx = -1; + LONG g_overflow = 0; +}; diff --git a/src/ConEmuCD/InputLogger.h b/src/ConEmuCD/InputLogger.h new file mode 100644 index 000000000..96455e45b --- /dev/null +++ b/src/ConEmuCD/InputLogger.h @@ -0,0 +1,106 @@ + +/* +Copyright (c) 2009-present Maximus5 +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +#pragma once + +#include "../common/defines.h" + +#include + +// Message Logger +// Originally from http://preshing.com/20120522/lightweight-in-memory-logging +namespace InputLogger +{ + static const int BUFFER_INFO_SIZE = RELEASEDEBUGTEST(0x1000,0x1000); // Must be a power of 2 + struct Event { + DWORD time; + enum Source { + evt_Empty, + evt_ReadInputQueue, + evt_SetEvent, + evt_ResetEvent, + evt_SendStart, + evt_SendEnd, + evt_ProcessInputMessage, + evt_WriteInputQueue1, + evt_WaitInputReady, + evt_WriteInputQueue2, + evt_InputQueueFlush, + evt_Overflow, + evt_SpeedHigh, + evt_SpeedLow, + evt_WaitConSize, + evt_WaitConEmpty, + evt_WriteConInput, + evt_ConSbiChanged, + evt_ConDataChanged, + } what; + LONG val; + INPUT_RECORD ir; + }; + extern Event g_evt[BUFFER_INFO_SIZE]; + extern LONG g_evtidx; + extern LONG g_overflow; + + inline void Log(Event::Source what, LONG val = 0) + { + // Get next message index + // Wrap to buffer size + LONG i = (_InterlockedIncrement(&g_evtidx) & (BUFFER_INFO_SIZE - 1)); + // Write a message at this index + g_evt[i].what = what; + g_evt[i].time = GetTickCount(); + g_evt[i].val = val; + g_evt[i].ir.EventType = 0; + } + + inline void Log(Event::Source what, const INPUT_RECORD& ir, LONG val = 0) + { + // Get next message index + // Wrap to buffer size + LONG i = (_InterlockedIncrement(&g_evtidx) & (BUFFER_INFO_SIZE - 1)); + // Write a message at this index + g_evt[i].what = what; + g_evt[i].time = GetTickCount(); + // Fill info + g_evt[i].val = val; + if (ir.EventType == KEY_EVENT) + { + ZeroStruct(g_evt[i].ir); + g_evt[i].ir.EventType = ir.EventType; + g_evt[i].ir.Event.KeyEvent.bKeyDown = ir.Event.KeyEvent.bKeyDown; + g_evt[i].ir.Event.KeyEvent.wRepeatCount = ir.Event.KeyEvent.wRepeatCount; + g_evt[i].ir.Event.KeyEvent.dwControlKeyState = ir.Event.KeyEvent.dwControlKeyState; + } + else + { + g_evt[i].ir = ir; + } + } +} diff --git a/src/ConEmuCD/LogFunction.cpp b/src/ConEmuCD/LogFunction.cpp index fd84c2106..8100cd8bf 100644 --- a/src/ConEmuCD/LogFunction.cpp +++ b/src/ConEmuCD/LogFunction.cpp @@ -26,6 +26,7 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#include "ConsoleMain.h" #include "LogFunction.h" #include "ConEmuSrv.h" #include @@ -67,7 +68,8 @@ void CLogFunction::DoLogFunction(const wchar_t* asFnName) const auto lLevel = std::min(++m_FnLevel, 20); mb_Logged = true; - if (!gpLogSize) return; + if (!gpLogSize) + return; const int cchFnInfo = std::size(mc_FnInfo); wchar_t* pc = mc_FnInfo; diff --git a/src/ConEmuCD/MapDump.cpp b/src/ConEmuCD/MapDump.cpp index c02060f49..90497caa4 100644 --- a/src/ConEmuCD/MapDump.cpp +++ b/src/ConEmuCD/MapDump.cpp @@ -30,12 +30,12 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define HIDE_USE_EXCEPTION_INFO #define SHOWDEBUGSTR +#include "ConsoleMain.h" #include "../common/Common.h" #include "../common/CEStr.h" #include "../common/CmdLine.h" #include "../common/MStrDup.h" #include -#include "ConEmuSrv.h" #include "MapDump.h" enum MapDumpEnum diff --git a/src/ConEmuCD/Queue.cpp b/src/ConEmuCD/Queue.cpp index c0688d62c..c6a03d459 100644 --- a/src/ConEmuCD/Queue.cpp +++ b/src/ConEmuCD/Queue.cpp @@ -28,7 +28,9 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define SHOWDEBUGSTR +#include "ConsoleMain.h" #include "ConEmuSrv.h" +#include "InputLogger.h" #include "Queue.h" #include "../common/Keyboard.h" diff --git a/src/ConEmuCD/Queue.h b/src/ConEmuCD/Queue.h index 7dff7afee..69a1f9397 100644 --- a/src/ConEmuCD/Queue.h +++ b/src/ConEmuCD/Queue.h @@ -36,3 +36,5 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. BOOL ProcessInputMessage(MSG64::MsgStr &msg, INPUT_RECORD &r); //BOOL WriteInputQueue(const INPUT_RECORD *pr, BOOL bSetEvent = TRUE); DWORD WINAPI InputThread(LPVOID lpvParam); + +BOOL SendConsoleEvent(INPUT_RECORD* pr, UINT nCount); diff --git a/src/ConEmuCD/SrvCommands.cpp b/src/ConEmuCD/SrvCommands.cpp index d49ca0908..6ef511c29 100644 --- a/src/ConEmuCD/SrvCommands.cpp +++ b/src/ConEmuCD/SrvCommands.cpp @@ -36,7 +36,7 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //#define SHOW_INJECT_MSGBOX -#include "../common/defines.h" +#include "ConsoleMain.h" #include "ConEmuSrv.h" #include "../common/CmdLine.h" #include "../common/ConsoleAnnotation.h" @@ -453,11 +453,6 @@ BOOL cmd_SetSizeXXX_CmdStartedFinished(CESERVER_REQ& in, CESERVER_REQ** out) gpSrv->bInSyncResize = TRUE; } - #if 0 - // Блокировка при прокрутке, значение используется только "виртуально" в CorrectVisibleRect - gpSrv->TopLeft = in.SetSize.TopLeft; - #endif - nTick1 = GetTickCount(); csRead.Unlock(); WARNING("Если указан dwFarPID - это что-ли два раза подряд выполнится?"); @@ -1780,6 +1775,7 @@ BOOL LoadFullConsoleData(HANDLE hOutput, WORD max_height, CESERVER_REQ** out) COORD BufSize = {lsbi.dwSize.X, lsbi.dwSize.Y}; SMALL_RECT ReadRect = {0, 0, lsbi.dwSize.X-1, lsbi.dwSize.Y-1}; + // #PTY Use proper server implementation lbRc = MyReadConsoleOutput(hOutput, pData->Data, BufSize, ReadRect); if (lbRc) @@ -1890,7 +1886,7 @@ BOOL cmd_SetFullScreen(CESERVER_REQ& in, CESERVER_REQ** out) if (!(*out)->FullScreenRet.bSucceeded) (*out)->FullScreenRet.nErrCode = GetLastError(); else - gpSrv->pfnWasFullscreenMode = pfnGetConsoleDisplayMode; + gpSrv->wasFullscreenMode = true; } lbRc = TRUE; } diff --git a/src/ConEmuCD/SrvPipes.cpp b/src/ConEmuCD/SrvPipes.cpp index 981ffd5dd..8402c87f6 100644 --- a/src/ConEmuCD/SrvPipes.cpp +++ b/src/ConEmuCD/SrvPipes.cpp @@ -26,7 +26,10 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#include "ConsoleMain.h" #include "ConEmuSrv.h" +#include "InputLogger.h" +#include "SrvCommands.h" #include "Queue.h" #define DEBUGSTRINPUTPIPE(s) //DEBUGSTR(s) // ConEmuC: Received key... / ConEmuC: Received input diff --git a/src/ConEmuCD/UnicodeTest.cpp b/src/ConEmuCD/UnicodeTest.cpp index 96a3fe80b..795c50187 100644 --- a/src/ConEmuCD/UnicodeTest.cpp +++ b/src/ConEmuCD/UnicodeTest.cpp @@ -30,6 +30,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define HIDE_USE_EXCEPTION_INFO #define SHOWDEBUGSTR +#include "ConsoleMain.h" + #include "../common/Common.h" #include "../common/ConsoleRead.h" #include "../common/EnvVar.h" diff --git a/src/ConEmuHk/InjectsBootstrap.h b/src/ConEmuHk/InjectsBootstrap.h index 69c5e1327..7a03920a5 100644 --- a/src/ConEmuHk/InjectsBootstrap.h +++ b/src/ConEmuHk/InjectsBootstrap.h @@ -60,7 +60,7 @@ int InjectHookDLL(PROCESS_INFORMATION pi, InjectHookFunctions* pfn /*UINT_PTR fn _ASSERTE(pfn->szKernelName && *pfn->szKernelName); size_t pnKernelNameLen = lstrlen(pfn->szKernelName); - size_t pstrSize = sizeof(USTR) + 8/*alignment*/ + sizeof(wchar_t)*(pnKernelNameLen+1); // UNICODE_STRING ( "kernel32.dll" | "kernelbase.dll" ) + size_t pstrSize = sizeof(USTR) + 8/*alignment*/ + sizeof(wchar_t) * (pnKernelNameLen + 1); // UNICODE_STRING ( "kernel32.dll" | "kernelbase.dll" ) //OSVERSIONINFO osv = {sizeof(osv)}; @@ -154,7 +154,7 @@ int InjectHookDLL(PROCESS_INFORMATION pi, InjectHookFunctions* pfn /*UINT_PTR fn memmove(code + codeSize, strHookDllPath, memLen); pStr = (PUSTR)((((DWORD_PTR)(code + codeSize + memLen + 7))>>3)<<3); - pStr->Length = pnKernelNameLen*sizeof(wchar_t); + pStr->Length = pnKernelNameLen * sizeof(wchar_t); pStr->MaximumLength = (pnKernelNameLen+1)*sizeof(wchar_t); #ifdef _WIN64 pStr->Pad = 0;