// Vista+ only // Функция глюкавая. По крайней мере в Win7. // 1. После ее вызова слетает видимая область в окне консоли // 2. После ее вызова окно консоли безусловно показыватся // 1 - поправлено здесь, 2 - озаботиться должен вызывающий BOOL apiSetConsoleScreenBufferInfoEx(HANDLE hConsoleOutput, MY_CONSOLE_SCREEN_BUFFER_INFOEX* lpConsoleScreenBufferInfoEx) { typedef BOOL (WINAPI* SetConsoleScreenBufferInfoEx_t)(HANDLE hConsoleOutput, MY_CONSOLE_SCREEN_BUFFER_INFOEX* lpConsoleScreenBufferInfoEx); static SetConsoleScreenBufferInfoEx_t SetConsoleScreenBufferInfoEx_f = NULL; static bool bFuncChecked = false; if (!bFuncChecked) { HMODULE hKernel32 = GetModuleHandle(L"kernel32.dll"); SetConsoleScreenBufferInfoEx_f = (SetConsoleScreenBufferInfoEx_t)GetProcAddress(hKernel32, "SetConsoleScreenBufferInfoEx"); bFuncChecked = true; } BOOL lbRc = FALSE; DEBUGTEST(BOOL lbWnd = FALSE); if (SetConsoleScreenBufferInfoEx_f) { lbRc = SetConsoleScreenBufferInfoEx_f(hConsoleOutput, lpConsoleScreenBufferInfoEx); // Win7 x64 - глюк. после вызова этой функции идет срыв размеров видимой области. DEBUGTEST(lbWnd =) SetConsoleWindowInfo(hConsoleOutput, TRUE, &lpConsoleScreenBufferInfoEx->srWindow); } return lbRc; }
void MConHandle::LogHandle(UINT evt, HANDLE h) { LONG i = (_InterlockedIncrement(&m_logidx) & (HANDLE_BUFFER_SIZE - 1)); m_log[i].evt = (Event::EventType)evt; DEBUGTEST(m_log[i].time = GetTickCount()); m_log[i].TID = GetCurrentThreadId(); m_log[i].h = h; }
void CTabStack::RecheckPassive() { if (mn_UpdatePos < mn_Used) { // Освободить все элементы за mn_UpdatePos int i = mn_UpdatePos; DEBUGTEST(int iPrev = mn_Used); while (i < mn_Used) { CTabID *pTab = mpp_Stack[i]; if (pTab) { _ASSERTE(pTab->Info.pVCon!=NULL); if (abRConTabs && pTab->Info.pVCon) { bool bVConValid = false, bPidValid = false, bPassive = false; // Only for RCon->tabs.m_Tabs we must to check, if tab is: // 'Still Alive' // 'Hidden' (Another started Far hides editor/viewer of parent Far) // 'Terminated' (Editor/viewer was closed or Far instance terminated) CVConGroup::CheckTabValid(pTab, bVConValid, bPidValid, bPassive); if (bPidValid) { if (bPassive) { // Пока оставить этот таб i++; continue; } } } // If we get here - tab was terminated if (abRConTabs) pTab->Info.Status = tisInvalid; #ifdef TAB_REF_PLACE pTab->DelPlace(m_rp); #endif // Kill this tab pTab->Release(); mpp_Stack[i] = NULL; } DEBUGTEST(iPrev = mn_Used); PRAGMA_ERROR("FAIL. Нужно убрать из стека все NULL-ячейки"); TabDeleted(pUpdateLock, i); _ASSERTE(mn_Used < iPrev); } mn_Used = mn_UpdatePos; } }
void CSetPgStatus::UpdateStatusItems(HWND hDlg) { HWND hAvail = GetDlgItem(hDlg, lbStatusAvailable); _ASSERTE(hAvail!=NULL); INT_PTR iMaxAvail = -1, iCurAvail = SendMessage(hAvail, LB_GETCURSEL, 0, 0); DEBUGTEST(INT_PTR iCountAvail = SendMessage(hAvail, LB_GETCOUNT, 0, 0)); HWND hSeltd = GetDlgItem(hDlg, lbStatusSelected); _ASSERTE(hSeltd!=NULL); INT_PTR iMaxSeltd = -1, iCurSeltd = SendMessage(hSeltd, LB_GETCURSEL, 0, 0); DEBUGTEST(INT_PTR iCountSeltd = SendMessage(hSeltd, LB_GETCOUNT, 0, 0)); SendMessage(hAvail, LB_RESETCONTENT, 0, 0); SendMessage(hSeltd, LB_RESETCONTENT, 0, 0); StatusColInfo* pColumns = NULL; size_t nCount = CStatus::GetAllStatusCols(&pColumns); _ASSERTE(pColumns!=NULL); for (size_t i = 0; i < nCount; i++) { CEStatusItems nID = pColumns[i].nID; if ((nID == csi_Info) || (pColumns[i].sSettingName == NULL)) continue; if (gpSet->isStatusColumnHidden[nID]) { iMaxAvail = SendMessage(hAvail, LB_ADDSTRING, 0, (LPARAM)pColumns[i].sName); if (iMaxAvail >= 0) SendMessage(hAvail, LB_SETITEMDATA, iMaxAvail, nID); } else { iMaxSeltd = SendMessage(hSeltd, LB_ADDSTRING, 0, (LPARAM)pColumns[i].sName); if (iMaxSeltd >= 0) SendMessage(hSeltd, LB_SETITEMDATA, iMaxSeltd, nID); } } if (iCurAvail >= 0 && iMaxAvail >= 0) SendMessage(hAvail, LB_SETCURSEL, (iCurAvail <= iMaxAvail) ? iCurAvail : iMaxAvail, 0); if (iCurSeltd >= 0 && iMaxSeltd >= 0) SendMessage(hSeltd, LB_SETCURSEL, (iCurSeltd <= iMaxSeltd) ? iCurSeltd : iMaxSeltd, 0); }
int CDwmHelper::GetDwmClientRectTopOffset() { int nOffset = 0; DEBUGTEST(FrameDrawStyle dt = gpConEmu->DrawType()); if (!gpSet->isTabs) goto wrap; wrap: mn_DwmClientRectTopOffset = nOffset; return nOffset; }
// Vista+ only BOOL apiSetConsoleFontSize(HANDLE hOutput, int inSizeY, int inSizeX, const wchar_t *asFontName) { HMODULE hKernel = GetModuleHandle(L"kernel32.dll"); if (!hKernel) { _ASSERTE(hKernel!=NULL); return FALSE; } BOOL lbRc = FALSE; //typedef BOOL (WINAPI *PSetCurrentConsoleFontEx)(HANDLE /*hConsoleOutput*/, BOOL /*bMaximumWindow*/, MY_CONSOLE_FONT_INFOEX* /*lpConsoleCurrentFontEx*/); PSetCurrentConsoleFontEx SetCurrentConsoleFontEx = (PSetCurrentConsoleFontEx) GetProcAddress(hKernel, "SetCurrentConsoleFontEx"); //typedef BOOL (WINAPI *PGetCurrentConsoleFontEx)(HANDLE /*hConsoleOutput*/, BOOL /*bMaximumWindow*/, MY_CONSOLE_FONT_INFOEX* /*lpConsoleCurrentFontEx*/); PGetCurrentConsoleFontEx GetCurrentConsoleFontEx = (PGetCurrentConsoleFontEx) GetProcAddress(hKernel, "GetCurrentConsoleFontEx"); if (SetCurrentConsoleFontEx) // We have Vista { MY_CONSOLE_FONT_INFOEX cfi = {sizeof(cfi)}; //GetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfi); cfi.dwFontSize.X = inSizeX; cfi.dwFontSize.Y = inSizeY; lstrcpynW(cfi.FaceName, asFontName ? asFontName : L"Lucida Console", countof(cfi.FaceName)); HANDLE hConOut = GetStdHandle(STD_OUTPUT_HANDLE); lbRc = SetCurrentConsoleFontEx(hConOut, FALSE, &cfi); // Store for further comparison if (lbRc) { MY_CONSOLE_FONT_INFOEX cfiSet = {sizeof(cfiSet)}; if (GetCurrentConsoleFontEx && GetCurrentConsoleFontEx(hConOut, FALSE, &cfiSet)) { // Win10 can't set "Lucida Console 3x5" and we get "4x6" _ASSERTE(_abs(cfiSet.dwFontSize.X-cfi.dwFontSize.X)<=1 && _abs(cfiSet.dwFontSize.Y-cfi.dwFontSize.Y)<=1); g_LastSetConsoleFont = cfiSet; } else { DEBUGTEST(DWORD dwErr = GetLastError()); _ASSERTE(FALSE && "apiGetConsoleScreenBufferInfoEx failed"); g_LastSetConsoleFont = cfi; } } } return lbRc; }
CDownloader() { DEBUGTEST(gbAllowChkHeap = true); mb_AsyncMode = true; ZeroStruct(m_Proxy); szCmdStringFormat = NULL; ZeroStruct(mfn_Callback); ZeroStruct(m_CallbackLParam); mb_RequestTerminate = false; ZeroStruct(m_SI); m_SI.cb = sizeof(m_SI); ZeroStruct(m_PI); mb_Terminating = false; mh_PipeErrRead = mh_PipeErrWrite = mh_PipeErrThread = NULL; mn_PipeErrThreadId = 0; };
// Default constructor of the class. CGestures::CGestures() : _dwArguments(0), _inRotate(false) { DEBUGTEST(GESTUREINFO c = {sizeof(c)}); _isTabletPC = GetSystemMetrics(SM_TABLETPC); _isGestures = IsWindows7; if (_isGestures) { HMODULE hUser = GetModuleHandle(L"user32.dll"); _GetGestureInfo = (GetGestureInfo_t)GetProcAddress(hUser, "GetGestureInfo"); _SetGestureConfig = (SetGestureConfig_t)GetProcAddress(hUser, "SetGestureConfig"); _CloseGestureInfoHandle = (CloseGestureInfoHandle_t)GetProcAddress(hUser, "CloseGestureInfoHandle"); if (!_GetGestureInfo || !_SetGestureConfig || !_CloseGestureInfoHandle) _isGestures = false; } }
// // CDropSource::GiveFeedback // // Return either S_OK, or DRAGDROP_S_USEDEFAULTCURSORS to instruct OLE to use the // default mouse cursor images // HRESULT __stdcall CDropSource::GiveFeedback(DWORD dwEffect) { HRESULT hr = DRAGDROP_S_USEDEFAULTCURSORS; HCURSOR hCur = NULL; DEBUGTEST(HRESULT hrTest = S_FALSE); //-- пока CFSTR_DROPDESCRIPTION не заводится... //if ((gOSVer.dwMajorVersion < 6) || !mp_Callback) { if (dwEffect != DROPEFFECT_NONE) { if (dwEffect & DROPEFFECT_COPY) { if (!mh_CurCopy) mh_CurCopy = LoadCursor(g_hInstance, MAKEINTRESOURCE(IDC_COPY)); hCur = mh_CurCopy; } else if (dwEffect & DROPEFFECT_MOVE) { if (!mh_CurMove) mh_CurMove = LoadCursor(g_hInstance, MAKEINTRESOURCE(IDC_MOVE)); hCur = mh_CurMove; } else if (dwEffect & DROPEFFECT_LINK) { if (!mh_CurLink) mh_CurLink = LoadCursor(g_hInstance, MAKEINTRESOURCE(IDC_LINK)); hCur = mh_CurLink; } } else { hCur = LoadCursor(NULL, IDC_NO); } } gpConEmu->SetDragCursor(hCur); //if (hCur) { //SetCursor(hCur); hr = S_OK; //} if (mp_Callback) mp_Callback->DragFeedBack(dwEffect); return hr; }
PVOID FspAllocatePoolMustSucceed(POOL_TYPE PoolType, SIZE_T Size, ULONG Tag) { // !PAGED_CODE(); PVOID Result; LARGE_INTEGER Delay; for (ULONG i = 0, n = sizeof(Delays) / sizeof(Delays[0]);; i++) { Result = DEBUGTEST(99) ? ExAllocatePoolWithTag(PoolType, Size, Tag) : 0; if (0 != Result) return Result; Delay.QuadPart = n > i ? Delays[i] : Delays[n - 1]; KeDelayExecutionThread(KernelMode, FALSE, &Delay); } }
PVOID FspAllocateIrpMustSucceed(CCHAR StackSize) { // !PAGED_CODE(); PIRP Result; LARGE_INTEGER Delay; for (ULONG i = 0, n = sizeof(Delays) / sizeof(Delays[0]);; i++) { Result = DEBUGTEST(99) ? IoAllocateIrp(StackSize, FALSE) : 0; if (0 != Result) return Result; Delay.QuadPart = n > i ? Delays[i] : Delays[n - 1]; KeDelayExecutionThread(KernelMode, FALSE, &Delay); } }
// Vista+ only BOOL apiSetConsoleFontSize(HANDLE hOutput, int inSizeY, int inSizeX, const wchar_t *asFontName) { HMODULE hKernel = GetModuleHandle(L"kernel32.dll"); if (!hKernel) { _ASSERTE(hKernel!=NULL); return FALSE; } BOOL lbRc = FALSE; if (IsWin6()) // We have Vista { MY_CONSOLE_FONT_INFOEX cfi = {sizeof(cfi)}; //apiGetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfi); cfi.dwFontSize.X = inSizeX; cfi.dwFontSize.Y = inSizeY; lstrcpynW(cfi.FaceName, asFontName ? asFontName : L"Lucida Console", countof(cfi.FaceName)); HANDLE hConOut = GetStdHandle(STD_OUTPUT_HANDLE); lbRc = apiSetCurrentConsoleFontEx(hConOut, FALSE, &cfi); // Store for further comparison if (lbRc) { MY_CONSOLE_FONT_INFOEX cfiSet = {sizeof(cfiSet)}; if (apiGetCurrentConsoleFontEx(hConOut, FALSE, &cfiSet)) { // Win10 can't set "Lucida Console 3x5" and we get "4x6" _ASSERTE(_abs(cfiSet.dwFontSize.X-cfi.dwFontSize.X)<=1 && _abs(cfiSet.dwFontSize.Y-cfi.dwFontSize.Y)<=1); g_LastSetConsoleFont = cfiSet; } else { DEBUGTEST(DWORD dwErr = GetLastError()); _ASSERTE(FALSE && "apiGetConsoleScreenBufferInfoEx failed"); g_LastSetConsoleFont = cfi; } } } return lbRc; }
int CDwmHelper::GetDwmClientRectTopOffset() { int nOffset = 0; DEBUGTEST(FrameDrawStyle dt = gpConEmu->DrawType()); if (!gpSet->isTabs) goto wrap; // GetFrameHeight(), GetCaptionDragHeight(), GetTabsHeight() if (gpSet->isTabsInCaption) { //if (dt == fdt_Win8) { nOffset = gpConEmu->GetTabsHeight() + gpConEmu->GetFrameHeight() + gpConEmu->GetCaptionDragHeight(); } //else //{ // //mn_DwmClientRectTopOffset = // // (GetSystemMetrics(SM_CYCAPTION)+(IsGlass() ? 8 : 0) // // +(IsZoomed(ghWnd)?(GetSystemMetrics(SM_CYFRAME)-1):(GetSystemMetrics(SM_CYCAPTION)/2))); // nOffset = 0 // //+ (IsGlass() ? 8 : 0) // + gpConEmu->GetFrameHeight() //+ 2 // + gpConEmu->GetCaptionDragHeight() // + gpConEmu->GetTabsHeight(); //} } //else //{ // mn_DwmClientRectTopOffset = 0; // //GetSystemMetrics(SM_CYCAPTION)+(IsGlass() ? 8 : 0) // //+(GetSystemMetrics(SM_CYFRAME)-1); //} wrap: mn_DwmClientRectTopOffset = nOffset; return nOffset; }
static NTSTATUS FspFsvolLockControlRetry( PDEVICE_OBJECT FsvolDeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp, BOOLEAN CanWait) { PAGED_CODE(); NTSTATUS Result; PFILE_OBJECT FileObject = IrpSp->FileObject; FSP_FILE_NODE *FileNode = FileObject->FsContext; BOOLEAN Success; /* try to acquire the FileNode shared Main */ Success = DEBUGTEST(90) && FspFileNodeTryAcquireSharedF(FileNode, FspFileNodeAcquireMain, CanWait); if (!Success) return FspWqRepostIrpWorkItem(Irp, FspFsvolLockControlRetry, 0); /* perform oplock check; we are only implementing Win7 behavior */ Result = FspFileNodeOplockCheckAsync( FileNode, FspFileNodeAcquireMain, FspFsvolLockControlRetry, Irp); if (STATUS_PENDING == Result) return Result; if (!NT_SUCCESS(Result)) { FspFileNodeRelease(FileNode, Main); return Result; } ULONG IrpFlags = FspIrpFlags(Irp); IoSetTopLevelIrp(0); /* let the FSRTL package handle this one! */ Result = FspFileNodeProcessLockIrp(FileNode, Irp); FspFileNodeReleaseF(FileNode, IrpFlags); return Result | FSP_STATUS_IGNORE_BIT; }
void SetUserFriendlyFont(HWND hConWnd) { OSVERSIONINFO OSVer = {sizeof(OSVer)}; GetVersionEx(&OSVer); // Соответствующие функции появились только в API Vista // Win2k & WinXP - доступны только хаки, что не подходит if (OSVer.dwMajorVersion >= 6) { HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE); COORD crVisibleSize = {}; CONSOLE_SCREEN_BUFFER_INFO csbi = {}; if (GetConsoleScreenBufferInfo(hOutput, &csbi)) { crVisibleSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1; crVisibleSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1; } if ((crVisibleSize.X <= 0) && (crVisibleSize.Y <= 0)) { _ASSERTE((crVisibleSize.X > 0) && (crVisibleSize.Y > 0)); } else { int curSizeY, curSizeX; wchar_t sFontName[LF_FACESIZE]; if (apiGetConsoleFontSize(hOutput, curSizeY, curSizeX, sFontName) && curSizeY && curSizeX) { DEBUGTEST(COORD crLargest = MyGetLargestConsoleWindowSize(hOutput)); HMONITOR hMon = MonitorFromWindow(hConWnd, MONITOR_DEFAULTTOPRIMARY); MONITORINFO mi = {sizeof(mi)}; int nMaxX = 0, nMaxY = 0; if (GetMonitorInfo(hMon, &mi)) { nMaxX = mi.rcWork.right - mi.rcWork.left - 2*GetSystemMetrics(SM_CXSIZEFRAME) - GetSystemMetrics(SM_CYCAPTION); nMaxY = mi.rcWork.bottom - mi.rcWork.top - 2*GetSystemMetrics(SM_CYSIZEFRAME); } if ((nMaxX > 0) && (nMaxY > 0)) { int nFontX = nMaxX / crVisibleSize.X; int nFontY = nMaxY / crVisibleSize.Y; // Too large height? if (nFontY > 28) { nFontX = 28 * nFontX / nFontY; nFontY = 28; } // Evaluate default width for the font int nEvalX = EvaluateDefaultFontWidth(nFontY, sFontName); if (nEvalX > 0) { if ((nEvalX > nFontX) && (nFontX > 0)) nFontY = nFontX * nFontY / nEvalX; else nFontX = nEvalX; } // Look in the registry? HKEY hk; DWORD nRegSize = 0, nLen; if (!RegOpenKeyEx(HKEY_CURRENT_USER, L"Console", 0, KEY_READ, &hk)) { if (RegQueryValueEx(hk, L"FontSize", NULL, NULL, (LPBYTE)&nRegSize, &(nLen=sizeof(nRegSize))) || nLen!=sizeof(nRegSize)) nRegSize = 0; RegCloseKey(hk); } if (!nRegSize && !RegOpenKeyEx(HKEY_CURRENT_USER, L"Console\\%SystemRoot%_system32_cmd.exe", 0, KEY_READ, &hk)) { if (RegQueryValueEx(hk, L"FontSize", NULL, NULL, (LPBYTE)&nRegSize, &(nLen=sizeof(nRegSize))) || nLen!=sizeof(nRegSize)) nRegSize = 0; RegCloseKey(hk); } if ((HIWORD(nRegSize) > curSizeY) && (HIWORD(nRegSize) < nFontY) && (LOWORD(nRegSize) > curSizeX) && (LOWORD(nRegSize) < nFontX)) { nFontY = HIWORD(nRegSize); nFontX = LOWORD(nRegSize); } if ((nFontX > curSizeX) || (nFontY > curSizeY)) { apiSetConsoleFontSize(hOutput, nFontY, nFontX, sFontName); } } } } } }
HANDLE GetProcessHandleForDebug(DWORD nPID, LPDWORD pnErrCode = NULL) { _ASSERTE(gpSrv->DbgInfo.bDebuggerActive); HANDLE hProcess = NULL; DWORD nErrCode = 0; if ((nPID == gpSrv->dwRootProcess) && gpSrv->hRootProcess) { hProcess = gpSrv->hRootProcess; } else { CEDebugProcessInfo pi = {}; if (gpSrv->DbgInfo.pDebugTreeProcesses->Get(nPID, &pi) && pi.hProcess) { // Уже hProcess = pi.hProcess; } else { // Нужно открыть дескриптор процесса, это запущенный дочерний второго уровня DWORD dwFlags = PROCESS_QUERY_INFORMATION|SYNCHRONIZE; if (gpSrv->DbgInfo.bDebuggerActive || gpSrv->DbgInfo.bDebugProcessTree) dwFlags |= PROCESS_VM_READ; CAdjustProcessToken token; token.Enable(1, SE_DEBUG_NAME); // Сначала - пробуем "все права" // PROCESS_ALL_ACCESS (defined in new SDK) may fails on WinXP! hProcess = OpenProcess(MY_PROCESS_ALL_ACCESS, FALSE, nPID); if (!hProcess) { DEBUGTEST(nErrCode = GetLastError()); hProcess = OpenProcess(dwFlags, FALSE, nPID); if (!hProcess) { nErrCode = GetLastError(); } } token.Release(); if (nPID != gpSrv->dwRootProcess) { // Запомнить дескриптор _ASSERTE(pi.nPID == nPID); // уже должен быть pi.nPID = nPID; pi.hProcess = hProcess; gpSrv->DbgInfo.pDebugTreeProcesses->Set(nPID, pi); } } } if (pnErrCode) *pnErrCode = nErrCode; return hProcess; }
NTSTATUS FspFsvolQuerySecurityComplete( PIRP Irp, const FSP_FSCTL_TRANSACT_RSP *Response) { FSP_ENTER_IOC(PAGED_CODE()); if (!NT_SUCCESS(Response->IoStatus.Status)) { Irp->IoStatus.Information = 0; Result = Response->IoStatus.Status; FSP_RETURN(); } PFILE_OBJECT FileObject = IrpSp->FileObject; FSP_FILE_NODE *FileNode = FileObject->FsContext; SECURITY_INFORMATION SecurityInformation = IrpSp->Parameters.QuerySecurity.SecurityInformation; PVOID Buffer = Irp->AssociatedIrp.SystemBuffer; ULONG Length = IrpSp->Parameters.QuerySecurity.Length; PVOID SecurityBuffer = 0; FSP_FSCTL_TRANSACT_REQ *Request = FspIrpRequest(Irp); BOOLEAN Success; if (0 != FspIopRequestContext(Request, RequestFileNode)) { /* check that the security descriptor we got back is valid */ if (Response->Buffer + Response->Rsp.QuerySecurity.SecurityDescriptor.Size > (PUINT8)Response + Response->Size || !RtlValidRelativeSecurityDescriptor((PVOID)Response->Buffer, Response->Rsp.QuerySecurity.SecurityDescriptor.Size, 0)) { Irp->IoStatus.Information = 0; Result = STATUS_INVALID_SECURITY_DESCR; FSP_RETURN(); } FspIopRequestContext(Request, RequestSecurityChangeNumber) = (PVOID)FileNode->SecurityChangeNumber; FspIopRequestContext(Request, RequestFileNode) = 0; FspFileNodeReleaseOwner(FileNode, Full, Request); } Success = DEBUGTEST(90) && FspFileNodeTryAcquireExclusive(FileNode, Main); if (!Success) { FspIopRetryCompleteIrp(Irp, Response, &Result); FSP_RETURN(); } Success = !FspFileNodeTrySetSecurity(FileNode, Response->Buffer, Response->Rsp.QuerySecurity.SecurityDescriptor.Size, (ULONG)(UINT_PTR)FspIopRequestContext(Request, RequestSecurityChangeNumber)); Success = Success && FspFileNodeReferenceSecurity(FileNode, &SecurityBuffer, 0); FspFileNodeRelease(FileNode, Main); if (Success) { Result = FspQuerySecurityDescriptorInfo(SecurityInformation, Buffer, &Length, SecurityBuffer); FspFileNodeDereferenceSecurity(SecurityBuffer); } else { SecurityBuffer = (PVOID)Response->Buffer; Result = FspQuerySecurityDescriptorInfo(SecurityInformation, Buffer, &Length, SecurityBuffer); } Irp->IoStatus.Information = Length; FSP_LEAVE_IOC("FileObject=%p, SecurityInformation=%x", IrpSp->FileObject, IrpSp->Parameters.QuerySecurity.SecurityInformation); }
void SetUserFriendlyFont(HWND hConWnd, int newFontY = 0, int newFontX = 0) { // Соответствующие функции появились только в API Vista // Win2k & WinXP - доступны только хаки, что не подходит _ASSERTE(_WIN32_WINNT_VISTA==0x600); OSVERSIONINFOEXW osvi = {sizeof(osvi), HIBYTE(_WIN32_WINNT_VISTA), LOBYTE(_WIN32_WINNT_VISTA)}; DWORDLONG const dwlConditionMask = VerSetConditionMask(VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL), VER_MINORVERSION, VER_GREATER_EQUAL); if (!VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION, dwlConditionMask)) return; HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE); COORD crVisibleSize = {}; CONSOLE_SCREEN_BUFFER_INFO csbi = {}; if (GetConsoleScreenBufferInfo(hOutput, &csbi)) { crVisibleSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1; crVisibleSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1; } if ((crVisibleSize.X <= 0) || (crVisibleSize.Y <= 0)) { _ASSERTE((crVisibleSize.X > 0) && (crVisibleSize.Y > 0)); return; } int curSizeY = 0, curSizeX = 0; wchar_t sFontName[LF_FACESIZE] = L""; if (apiGetConsoleFontSize(hOutput, curSizeY, curSizeX, sFontName) && curSizeY && curSizeX) { if (newFontY <= 0 || newFontX <= 0) { DEBUGTEST(COORD crLargest = MyGetLargestConsoleWindowSize(hOutput)); HMONITOR hMon = MonitorFromWindow(hConWnd, MONITOR_DEFAULTTOPRIMARY); MONITORINFO mi = {sizeof(mi)}; int nMaxX = 0, nMaxY = 0; if (GetMonitorInfo(hMon, &mi)) { nMaxX = mi.rcWork.right - mi.rcWork.left - 2*GetSystemMetrics(SM_CXSIZEFRAME) - GetSystemMetrics(SM_CYCAPTION); nMaxY = mi.rcWork.bottom - mi.rcWork.top - 2*GetSystemMetrics(SM_CYSIZEFRAME); } if ((nMaxX > 0) && (nMaxY > 0)) { int nFontX = nMaxX / crVisibleSize.X; int nFontY = nMaxY / crVisibleSize.Y; // Too large height? if (nFontY > 28) { nFontX = 28 * nFontX / nFontY; nFontY = 28; } // Evaluate default width for the font int nEvalX = EvaluateDefaultFontWidth(nFontY, sFontName); if (nEvalX > 0) { if ((nEvalX > nFontX) && (nFontX > 0)) nFontY = nFontX * nFontY / nEvalX; else nFontX = nEvalX; } // Look in the registry? HKEY hk; DWORD nRegSize = 0, nLen; if (!RegOpenKeyEx(HKEY_CURRENT_USER, L"Console", 0, KEY_READ, &hk)) { if (RegQueryValueEx(hk, L"FontSize", NULL, NULL, (LPBYTE)&nRegSize, &(nLen=sizeof(nRegSize))) || nLen!=sizeof(nRegSize)) nRegSize = 0; RegCloseKey(hk); } if (!nRegSize && !RegOpenKeyEx(HKEY_CURRENT_USER, L"Console\\%SystemRoot%_system32_cmd.exe", 0, KEY_READ, &hk)) { if (RegQueryValueEx(hk, L"FontSize", NULL, NULL, (LPBYTE)&nRegSize, &(nLen=sizeof(nRegSize))) || nLen!=sizeof(nRegSize)) nRegSize = 0; RegCloseKey(hk); } if ((HIWORD(nRegSize) > curSizeY) && (HIWORD(nRegSize) < nFontY) && (LOWORD(nRegSize) > curSizeX) && (LOWORD(nRegSize) < nFontX)) { nFontY = HIWORD(nRegSize); nFontX = LOWORD(nRegSize); } if ((nFontX > curSizeX) || (nFontY > curSizeY)) { newFontY = nFontY; newFontX = nFontX; } } } } if ((newFontY > 0) && (newFontX > 0)) { if (!*sFontName) lstrcpyn(sFontName, L"Lucida Console", countof(sFontName)); apiSetConsoleFontSize(hOutput, newFontY, newFontX, sFontName); } }
// // Wrapper around WM_SETCONSOLEINFO. We need to create the // necessary section (file-mapping) object in the context of the // process which owns the console, before posting the message // BOOL SetConsoleInfo(HWND hwndConsole, CONSOLE_INFO *pci) { DWORD dwConsoleOwnerPid, dwCurProcId; PVOID ptrView = 0; DWORD dwLastError=0; WCHAR ErrText[255]; // // Retrieve the process which "owns" the console // dwCurProcId = GetCurrentProcessId(); DEBUGTEST(DWORD dwConsoleThreadId =) GetWindowThreadProcessId(hwndConsole, &dwConsoleOwnerPid); // We'll fail, if console was created by other process if (dwConsoleOwnerPid != dwCurProcId) { #ifdef _DEBUG // Wine related PROCESSENTRY32W pi = {}; GetProcessInfo(dwConsoleOwnerPid, &pi); if (lstrcmpi(pi.szExeFile, L"wineconsole.exe")!=0) { wchar_t szDbgMsg[512], szTitle[128]; szDbgMsg[0] = 0; GetModuleFileName(NULL, szDbgMsg, countof(szDbgMsg)); msprintf(szTitle, countof(szTitle), L"%s: PID=%u", PointToName(szDbgMsg), GetCurrentProcessId()); msprintf(szDbgMsg, countof(szDbgMsg), L"GetWindowThreadProcessId()\nPID=%u, TID=%u, %s\n%s", dwConsoleOwnerPid, dwConsoleThreadId, pi.szExeFile, szTitle); MessageBox(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL); } //_ASSERTE(dwConsoleOwnerPid == dwCurProcId); #endif return FALSE; } // // Create a SECTION object backed by page-file, then map a view of // this section into the owner process so we can write the contents // of the CONSOLE_INFO buffer into it // if (!ghConsoleSection) { ghConsoleSection = CreateFileMapping(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, gnConsoleSectionSize, 0); if (!ghConsoleSection) { dwLastError = GetLastError(); _wsprintf(ErrText, SKIPLEN(countof(ErrText)) L"Can't CreateFileMapping(ghConsoleSection). ErrCode=%i", dwLastError); MessageBox(NULL, ErrText, L"ConEmu", MB_OK|MB_ICONSTOP|MB_SETFOREGROUND); return FALSE; } _ASSERTE(OnShutdownConsole==NULL || OnShutdownConsole==ShutdownConsole); OnShutdownConsole = ShutdownConsole; } // // Copy our console structure into the section-object // ptrView = MapViewOfFile(ghConsoleSection, FILE_MAP_WRITE|FILE_MAP_READ, 0, 0, gnConsoleSectionSize); if (!ptrView) { dwLastError = GetLastError(); _wsprintf(ErrText, SKIPLEN(countof(ErrText)) L"Can't MapViewOfFile. ErrCode=%i", dwLastError); MessageBox(NULL, ErrText, L"ConEmu", MB_OK|MB_ICONSTOP|MB_SETFOREGROUND); } else { _ASSERTE(pci->Length==sizeof(CONSOLE_INFO)); //2010-09-19 что-то на XP стало окошко мелькать. // при отсылке WM_SETCONSOLEINFO консоль отображается :( BOOL lbWasVisible = IsWindowVisible(hwndConsole); RECT rcOldPos = {0}, rcAllMonRect = {0}; if (!lbWasVisible) { GetWindowRect(hwndConsole, &rcOldPos); // В много-мониторных конфигурациях координаты на некоторых могут быть отрицательными! rcAllMonRect = GetAllMonitorsWorkspace(); pci->AutoPosition = FALSE; pci->WindowPosX = rcAllMonRect.left - 1280; pci->WindowPosY = rcAllMonRect.top - 1024; } memcpy(ptrView, pci, pci->Length); //-V106 UnmapViewOfFile(ptrView); // Send console window the "update" message DEBUGTEST(LRESULT dwConInfoRc =) SendMessage(hwndConsole, WM_SETCONSOLEINFO, (WPARAM)ghConsoleSection, 0); DEBUGTEST(DWORD dwConInfoErr = GetLastError()); if (!lbWasVisible && IsWindowVisible(hwndConsole)) { //DEBUGTEST(Sleep(10)); apiShowWindow(hwndConsole, SW_HIDE); //SetWindowPos(hwndConsole, NULL, rcOldPos.left, rcOldPos.top, 0,0, SWP_NOSIZE|SWP_NOZORDER); // -- чтобы на некоторых системах не возникала проблема с позиционированием -> {0,0} // Issue 274: Окно реальной консоли позиционируется в неудобном месте SetWindowPos(hwndConsole, NULL, 0, 0, 0,0, SWP_NOSIZE|SWP_NOZORDER); } } return TRUE; }
bool CDpiForDialog::Attach(HWND hWnd, HWND hCenterParent, CDynDialog* apDlgTemplate) { mh_Dlg = hWnd; wchar_t szLog[100]; mn_TemplateFontSize = apDlgTemplate ? apDlgTemplate->GetFontPointSize() : 8; mh_OldFont = (HFONT)SendMessage(hWnd, WM_GETFONT, 0, 0); if ((mh_OldFont != NULL) && (GetObject(mh_OldFont, sizeof(mlf_InitFont), &mlf_InitFont) > 0)) { _wsprintf(szLog, SKIPLEN(countof(szLog)) L"CDpiForDialog(x%08X) Font='%s' lfHeight=%i Points=%u", (DWORD)(DWORD_PTR)hWnd, mlf_InitFont.lfFaceName, mlf_InitFont.lfHeight, mn_TemplateFontSize); } else { ZeroStruct(mlf_InitFont); mlf_InitFont.lfHeight = GetFontSizeForDpi(NULL, 96); lstrcpyn(mlf_InitFont.lfFaceName, L"MS Shell Dlg", countof(mlf_InitFont.lfFaceName)); mlf_InitFont.lfWeight = 400; mlf_InitFont.lfCharSet = DEFAULT_CHARSET; _wsprintf(szLog, SKIPLEN(countof(szLog)) L"CDpiForDialog(x%08X) DefaultFont='%s' lfHeight=%i Points=%u", (DWORD)(DWORD_PTR)hWnd, mlf_InitFont.lfFaceName, mlf_InitFont.lfHeight, mn_TemplateFontSize); } LogString(szLog); // Up to Windows 8 - OS will care of dialog scaling // And what will happens in Windows 8.1? // If `Per-monitor` dpi was choosed in the OS settings, // we need to re-scale our dialog manually! // But if one dpi was choosed for all monitors? CDpiAware::QueryDpiForMonitor(NULL, &m_InitDpi); // Whole desktop DPI (in most cases that will be Primary monitor DPI) m_CurDpi.SetDpi(m_InitDpi); if (!m_Items.Initialized()) m_Items.Init(8); bool bPerMonitor = CDpiAware::IsPerMonitorDpi(); DEBUGTEST(bPerMonitor = true); if (bPerMonitor) { // When Windows 8.1 is in per-monitor mode // and application is marked as per-monitor-dpi aware // Windows does not resize dialogs automatically. // Our resources are designed for standard 96 dpi. MArray<DlgItem>* p = NULL; if (m_Items.Get(m_CurDpi.Ydpi, &p) && p) delete p; p = LoadDialogItems(hWnd); m_Items.Set(m_CurDpi.Ydpi, p); DpiValue CurMonDpi; CDpiAware::QueryDpi(hCenterParent ? hCenterParent : hWnd, &CurMonDpi); // Need to resize the dialog? if (m_CurDpi.Ydpi != CurMonDpi.Ydpi) { if (!SetDialogDPI(CurMonDpi)) return false; } } else { m_CurDpi.SetDpi(m_InitDpi.Xdpi, m_InitDpi.Ydpi); } return true; }
HWND myGetConsoleWindow() { HWND hConWnd = NULL; // If we are in ConEmuHk than gfGetRealConsoleWindow may be set if (gfGetRealConsoleWindow) { hConWnd = gfGetRealConsoleWindow(); // If the function pointer was set - it must be proper function _ASSERTEX(hConWnd==NULL || isConsoleWindow(hConWnd)); return hConWnd; } // To avoid infinite loops (GetModuleHandleEx is not available in Win2k) _ASSERTE(ghWorkingModule != 0); DEBUGTEST(HMODULE hOurModule = (HMODULE)(DWORD_PTR)ghWorkingModule); WARNING("DANGER zone. If ConEmuHk unloads following may cause crashes"); if (!hkFunc.isConEmuHk()) { #ifdef _DEBUG static HMODULE hHookLib = NULL; if (!hHookLib) hHookLib = GetModuleHandle(WIN3264TEST(L"ConEmuHk.dll",L"ConEmuHk64.dll")); _ASSERTEX(hHookLib != hOurModule); #endif hConWnd = hkFunc.getConsoleWindow(); } if (!hConWnd) { hConWnd = GetConsoleWindow(); // Current process may be GUI and have no console at all if (!hConWnd) return NULL; // RealConsole handle is stored in the Window DATA if (!hkFunc.isConEmuHk()) { #ifdef _DEBUG wchar_t sClass[64] = L""; GetClassName(hConWnd, sClass, countof(sClass)); #endif // Regardless of GetClassName result, it may be VirtualConsoleClass HWND h = (HWND)GetWindowLongPtr(hConWnd, 0); if (h && IsWindow(h) && isConsoleWindow(h)) { hConWnd = h; } } } return hConWnd; #if 0 // Смысла звать GetProcAddress для "GetConsoleWindow" мало, все равно хукается typedef HWND (APIENTRY *FGetConsoleWindow)(); static FGetConsoleWindow fGetConsoleWindow = NULL; if (!fGetConsoleWindow) { HMODULE hKernel32 = GetModuleHandleA("kernel32.dll"); if (hKernel32) { fGetConsoleWindow = (FGetConsoleWindow)GetProcAddress(hKernel32, "GetConsoleWindow"); } } if (fGetConsoleWindow) hConWnd = fGetConsoleWindow(); return hConWnd; #endif }
// pvkKeys - 0-terminated VKKeys array bool CConEmuInside::SendVkKeySequence(HWND hWnd, WORD* pvkKeys) { bool bSent = false; //DWORD_PTR nRc1, nRc2; LRESULT lSendRc = 0; DWORD nErrCode = 0; if (!pvkKeys || !*pvkKeys) { _ASSERTE(pvkKeys && *pvkKeys); return false; } // Только для XP _ASSERTE(gnOsVer < 0x600); HWND hWorker1 = GetDlgItem(hWnd, 0xA005); if (!CheckClassName(hWorker1, L"WorkerW")) return false; HWND hReBar1 = GetDlgItem(hWorker1, 0xA005); if (!CheckClassName(hReBar1, L"ReBarWindow32")) return false; HWND hMenuBar = FindTopWindow(hReBar1, L"ToolbarWindow32"); if (!hMenuBar) return false; size_t k = 0; HWND hSend = hMenuBar; while (pvkKeys[k]) { // Prep send msg values UINT nMsg1 = (pvkKeys[k] == VK_F10) ? WM_SYSKEYDOWN : WM_KEYDOWN; DEBUGTEST(UINT nMsg2 = (pvkKeys[k] == VK_F10) ? WM_SYSKEYUP : WM_KEYUP); UINT vkScan = MapVirtualKey(pvkKeys[k], 0/*MAPVK_VK_TO_VSC*/); LPARAM lParam1 = 0x00000001 | (vkScan << 16); DEBUGTEST(LPARAM lParam2 = 0xC0000001 | (vkScan << 16)); // Post KeyDown&KeyUp if (pvkKeys[k] == VK_F10) { PostMessage(hMenuBar, WM_LBUTTONDOWN, 0, MAKELONG(5,5)); PostMessage(hMenuBar, WM_LBUTTONUP, 0, MAKELONG(5,5)); //lSendRc = PostMessage(hWnd, nMsg1, pvkKeys[k], lParam1) // && PostMessage(hWnd, nMsg2, pvkKeys[k], lParam2); Sleep(100); hSend = hMenuBar; } else { // Sequental keys send to "menu" control lSendRc = PostMessage(hSend, nMsg1, pvkKeys[k], lParam1); if (lSendRc) { Sleep(100); //lSendRc = PostMessage(hSend, nMsg2, pvkKeys[k], lParam2); //Sleep(100); } } if (lSendRc) { bSent = true; } else { // failed, may be ERROR_TIMEOUT? nErrCode = GetLastError(); bSent = false; break; } k++; } // SendMessageTimeout failed? _ASSERTE(bSent); UNREFERENCED_PARAMETER(nErrCode); return bSent; }
BOOL GetConsoleScreenBufferInfoCached(HANDLE hConsoleOutput, PCONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo, BOOL bForced /*= FALSE*/) { BOOL lbRc = FALSE; static DWORD s_LastCheckTick = 0; static CONSOLE_SCREEN_BUFFER_INFO s_csbi = {}; static HANDLE s_hConOut = NULL; //DWORD nTickDelta = 0; //const DWORD TickDeltaMax = 250; if (hConsoleOutput == NULL) { // Сброс s_hConOut = NULL; GetConsoleModeCached(NULL, NULL); return FALSE; } if (!lpConsoleScreenBufferInfo) { _ASSERTEX(lpConsoleScreenBufferInfo!=NULL); return FALSE; } #if 0 if (s_hConOut && (s_hConOut == hConsoleOutput)) { nTickDelta = GetTickCount() - s_LastCheckTick; if (nTickDelta <= TickDeltaMax) { if (bForced) { #ifdef _DEBUG lbRc = FALSE; #endif } else { *lpConsoleScreenBufferInfo = s_csbi; lbRc = TRUE; } } } #endif if (!lbRc) { CONSOLE_SCREEN_BUFFER_INFO csbi = {}; lbRc = GetConsoleScreenBufferInfo(hConsoleOutput, &csbi); DEBUGTEST(DWORD nBufErr = GetLastError()); *lpConsoleScreenBufferInfo = csbi; if (lbRc) { s_csbi = csbi; s_LastCheckTick = GetTickCount(); s_hConOut = hConsoleOutput; } } return lbRc; }
static NTSTATUS FspFsvolWriteNonCached( PDEVICE_OBJECT FsvolDeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp, BOOLEAN CanWait) { PAGED_CODE(); /* assert: either a top-level IRP or Paging I/O */ ASSERT(0 == FspIrpTopFlags(Irp) || FlagOn(Irp->Flags, IRP_PAGING_IO)); NTSTATUS Result; PFILE_OBJECT FileObject = IrpSp->FileObject; FSP_FILE_NODE *FileNode = FileObject->FsContext; FSP_FILE_DESC *FileDesc = FileObject->FsContext2; LARGE_INTEGER WriteOffset = IrpSp->Parameters.Write.ByteOffset; ULONG WriteLength = IrpSp->Parameters.Write.Length; ULONG WriteKey = IrpSp->Parameters.Write.Key; BOOLEAN WriteToEndOfFile = FILE_WRITE_TO_END_OF_FILE == WriteOffset.LowPart && -1L == WriteOffset.HighPart; BOOLEAN PagingIo = BooleanFlagOn(Irp->Flags, IRP_PAGING_IO); FSP_FSCTL_TRANSACT_REQ *Request; BOOLEAN Success; ASSERT(FileNode == FileDesc->FileNode); /* no MDL requests on the non-cached path */ if (FlagOn(IrpSp->MinorFunction, IRP_MN_MDL)) return STATUS_INVALID_PARAMETER; /* paging I/O cannot change the file size */ if (PagingIo && WriteToEndOfFile) return STATUS_INVALID_PARAMETER; /* stop CcWriteBehind from calling me! */ if (FspIoqStopped(FspFsvolDeviceExtension(FsvolDeviceObject)->Ioq)) return FspFsvolDeviceStoppedStatus(FsvolDeviceObject); /* probe and lock the user buffer */ Result = FspLockUserBuffer(Irp, WriteLength, IoReadAccess); if (!NT_SUCCESS(Result)) return Result; /* acquire FileNode exclusive Full */ Success = DEBUGTEST(90) && FspFileNodeTryAcquireExclusiveF(FileNode, FspFileNodeAcquireFull, CanWait); if (!Success) return FspWqRepostIrpWorkItem(Irp, FspFsvolWriteNonCached, 0); /* perform oplock check */ if (!PagingIo) { Result = FspFileNodeOplockCheckAsync( FileNode, FspFileNodeAcquireFull, FspFsvolWriteNonCached, Irp); if (STATUS_PENDING == Result) return Result; if (!NT_SUCCESS(Result)) { FspFileNodeRelease(FileNode, Full); return Result; } } /* check the file locks */ if (!PagingIo && !FsRtlCheckLockForWriteAccess(&FileNode->FileLock, Irp)) { FspFileNodeRelease(FileNode, Full); return STATUS_FILE_LOCK_CONFLICT; } /* if this is a non-cached transfer on a cached file then flush and purge the file */ if (!PagingIo && 0 != FileObject->SectionObjectPointer->DataSectionObject) { if (!CanWait) { FspFileNodeRelease(FileNode, Full); return FspWqRepostIrpWorkItem(Irp, FspFsvolWriteNonCached, 0); } Result = FspFileNodeFlushAndPurgeCache(FileNode, IrpSp->Parameters.Write.ByteOffset.QuadPart, IrpSp->Parameters.Write.Length, TRUE); if (!NT_SUCCESS(Result)) { FspFileNodeRelease(FileNode, Full); return Result; } } Request = FspIrpRequest(Irp); if (0 == Request) { /* create request */ Result = FspIopCreateRequestEx(Irp, 0, 0, FspFsvolWriteNonCachedRequestFini, &Request); if (!NT_SUCCESS(Result)) { FspFileNodeRelease(FileNode, Full); return Result; } } else { /* reuse existing request */ ASSERT(Request->Size == sizeof *Request); ASSERT(Request->Hint == (UINT_PTR)Irp); FspIopResetRequest(Request, FspFsvolWriteNonCachedRequestFini); RtlZeroMemory(&Request->Req, sizeof *Request - FIELD_OFFSET(FSP_FSCTL_TRANSACT_REQ, Req)); } Request->Kind = FspFsctlTransactWriteKind; Request->Req.Write.UserContext = FileNode->UserContext; Request->Req.Write.UserContext2 = FileDesc->UserContext2; Request->Req.Write.Offset = WriteOffset.QuadPart; Request->Req.Write.Length = WriteLength; Request->Req.Write.Key = WriteKey; Request->Req.Write.ConstrainedIo = !!PagingIo; FspFileNodeSetOwner(FileNode, Full, Request); FspIopRequestContext(Request, RequestIrp) = Irp; FSP_STATISTICS *Statistics = FspFsvolDeviceStatistics(FsvolDeviceObject); if (PagingIo) { FspStatisticsInc(Statistics, Base.UserFileWrites); FspStatisticsAdd(Statistics, Base.UserFileWriteBytes, WriteLength); FspStatisticsInc(Statistics, Base.UserDiskWrites); } else { FspStatisticsInc(Statistics, Specific.NonCachedWrites); FspStatisticsAdd(Statistics, Specific.NonCachedWriteBytes, WriteLength); FspStatisticsInc(Statistics, Specific.NonCachedDiskWrites); } return FSP_STATUS_IOQ_POST; }
CESERVER_REQ* ExecuteNewCmdOnCreate(CESERVER_CONSOLE_MAPPING_HDR* pSrvMap, HWND hConWnd, enum CmdOnCreateType aCmd, LPCWSTR asAction, LPCWSTR asFile, LPCWSTR asParam, DWORD* anShellFlags, DWORD* anCreateFlags, DWORD* anStartFlags, DWORD* anShowCmd, int mn_ImageBits, int mn_ImageSubsystem, HANDLE hStdIn, HANDLE hStdOut, HANDLE hStdErr) { bool bEnabled = false; if (!pSrvMap) { DEBUGTEST(static bool bWasEnabled = false); static DWORD nLastWasEnabledTick = 0; // Чтобы проверки слишком часто не делать if (!nLastWasEnabledTick || ((GetTickCount() - nLastWasEnabledTick) > 1000)) { CESERVER_CONSOLE_MAPPING_HDR *Info = (CESERVER_CONSOLE_MAPPING_HDR*)calloc(1,sizeof(*Info)); if (Info) { if (::LoadSrvMapping(hConWnd, *Info)) { _ASSERTE(Info->ComSpec.ConEmuExeDir[0] && Info->ComSpec.ConEmuBaseDir[0]); bEnabled = (Info->nLoggingType == glt_Processes); } free(Info); } nLastWasEnabledTick = GetTickCount(); } DEBUGTEST(bWasEnabled = bEnabled); } else { bEnabled = (pSrvMap->nLoggingType == glt_Processes); } // Если логирование не просили if (!bEnabled) { return NULL; } //szBaseDir[0] = 0; //// Проверим, а надо ли? //MFileMapping<CESERVER_CONSOLE_MAPPING_HDR> ConMap; //ConMap.InitName(CECONMAPNAME, (DWORD)FarHwnd); //CESERVER_CONSOLE_MAPPING_HDR* p = ConMap.Open(); //if (p && p->hConEmuRoot && isWindow(p->hConEmuRoot)) //{ //// bDosBoxAllowed = pInfo->bDosBox; //// wcscpy_c(szBaseDir, pInfo->sConEmuBaseDir); //// wcscat_c(szBaseDir, L"\\"); //if (p->nLoggingType != glt_Processes) // return NULL; //DWORD dwGuiProcessId = 0; //if (!ghConEmuWnd || !GetWindowThreadProcessId(ghConEmuWnd, &dwGuiProcessId)) // return NULL; //MFileMapping<ConEmuGuiMapping> GuiInfoMapping; //GuiInfoMapping.InitName(CEGUIINFOMAPNAME, dwGuiProcessId); //const ConEmuGuiMapping* pInfo = GuiInfoMapping.Open(); //if (!pInfo) // return NULL; //else if (pInfo->nProtocolVersion != CESERVER_REQ_VER) // return NULL; //else //{ // bDosBoxAllowed = pInfo->bDosBox; // wcscpy_c(szBaseDir, pInfo->sConEmuBaseDir); // wcscat_c(szBaseDir, L"\\"); // if (pInfo->nLoggingType != glt_Processes) // return NULL; //} //GuiInfoMapping.CloseMap(); CESERVER_REQ *pIn = NULL; int nActionLen = (asAction ? lstrlen(asAction) : 0)+1; int nFileLen = (asFile ? lstrlen(asFile) : 0)+1; int nParamLen = (asParam ? lstrlen(asParam) : 0)+1; pIn = ExecuteNewCmd(CECMD_ONCREATEPROC, sizeof(CESERVER_REQ_HDR) +sizeof(CESERVER_REQ_ONCREATEPROCESS)+(nActionLen+nFileLen+nParamLen)*sizeof(wchar_t)); pIn->OnCreateProc.nSourceBits = WIN3264TEST(32,64); //-V112 //pIn->OnCreateProc.bUnicode = TRUE; pIn->OnCreateProc.nImageSubsystem = mn_ImageSubsystem; pIn->OnCreateProc.nImageBits = mn_ImageBits; pIn->OnCreateProc.hStdIn = (unsigned __int64)hStdIn; pIn->OnCreateProc.hStdOut = (unsigned __int64)hStdOut; pIn->OnCreateProc.hStdErr = (unsigned __int64)hStdErr; if (aCmd == eShellExecute) wcscpy_c(pIn->OnCreateProc.sFunction, L"Shell"); else if (aCmd == eCreateProcess) wcscpy_c(pIn->OnCreateProc.sFunction, L"Create"); else if (aCmd == eInjectingHooks) wcscpy_c(pIn->OnCreateProc.sFunction, L"Inject"); else if (aCmd == eHooksLoaded) wcscpy_c(pIn->OnCreateProc.sFunction, L"HkLoad"); else if (aCmd == eSrvLoaded) wcscpy_c(pIn->OnCreateProc.sFunction, L"SrLoad"); else if (aCmd == eParmsChanged) wcscpy_c(pIn->OnCreateProc.sFunction, L"Changed"); else if (aCmd == eLoadLibrary) wcscpy_c(pIn->OnCreateProc.sFunction, L"LdLib"); else if (aCmd == eFreeLibrary) wcscpy_c(pIn->OnCreateProc.sFunction, L"FrLib"); else wcscpy_c(pIn->OnCreateProc.sFunction, L"Unknown"); pIn->OnCreateProc.nShellFlags = anShellFlags ? *anShellFlags : 0; pIn->OnCreateProc.nCreateFlags = anCreateFlags ? *anCreateFlags : 0; pIn->OnCreateProc.nStartFlags = anStartFlags ? *anStartFlags : 0; pIn->OnCreateProc.nShowCmd = anShowCmd ? *anShowCmd : 0; pIn->OnCreateProc.nActionLen = nActionLen; pIn->OnCreateProc.nFileLen = nFileLen; pIn->OnCreateProc.nParamLen = nParamLen; wchar_t* psz = pIn->OnCreateProc.wsValue; if (nActionLen > 1) _wcscpy_c(psz, nActionLen, asAction); psz += nActionLen; if (nFileLen > 1) _wcscpy_c(psz, nFileLen, asFile); psz += nFileLen; if (nParamLen > 1) _wcscpy_c(psz, nParamLen, asParam); psz += nParamLen; return pIn; }
// nTimeout - таймаут подключения HANDLE ExecuteOpenPipe(const wchar_t* szPipeName, wchar_t (&szErr)[MAX_PATH*2], const wchar_t* szModule, DWORD nServerPID, DWORD nTimeout, BOOL Overlapped /*= FALSE*/, HANDLE hStop /*= NULL*/) { HANDLE hPipe = NULL; DWORD dwErr = 0, dwMode = 0; BOOL fSuccess = FALSE; DWORD dwStartTick = GetTickCount(); DWORD nSleepError = 10; // допустимое количество обломов, отличных от ERROR_PIPE_BUSY. после каждого - Sleep(nSleepError); int nTries = 10; // nTimeout должен ограничивать ВЕРХНЮЮ границу времени ожидания _ASSERTE(EXECUTE_CMD_OPENPIPE_TIMEOUT >= nTimeout); DWORD nOpenPipeTimeout = nTimeout ? min(nTimeout,EXECUTE_CMD_OPENPIPE_TIMEOUT) : EXECUTE_CMD_OPENPIPE_TIMEOUT; _ASSERTE(nOpenPipeTimeout > 0); DWORD nWaitPipeTimeout = min(250,nOpenPipeTimeout); BOOL bWaitPipeRc = FALSE, bWaitCalled = FALSE; DWORD nWaitPipeErr = 0; DWORD nDuration = 0; DWORD nStopWaitRc = (DWORD)-1; #ifdef _DEBUG wchar_t szDbgMsg[512], szTitle[128]; #endif // WinXP SP1 и выше DEBUGTEST(BOOL lbServerIsDebugged = nServerPID ? IsProcessDebugged(nServerPID) : FALSE); _ASSERTE(LocalSecurity()!=NULL); // Try to open a named pipe; wait for it, if necessary. while (1) { hPipe = CreateFile( szPipeName, // pipe name GENERIC_READ|GENERIC_WRITE, 0, // no sharing LocalSecurity(), // default security attributes OPEN_EXISTING, // opens existing pipe (Overlapped ? FILE_FLAG_OVERLAPPED : 0), // default attributes NULL); // no template file dwErr = GetLastError(); // Break if the pipe handle is valid. if (hPipe != INVALID_HANDLE_VALUE) { _ASSERTE(hPipe); break; // OK, открыли } #ifdef _DEBUG if (gbPipeDebugBoxes) { szDbgMsg[0] = 0; GetModuleFileName(NULL, szDbgMsg, countof(szDbgMsg)); msprintf(szTitle, countof(szTitle), L"%s: PID=%u", PointToName(szDbgMsg), GetCurrentProcessId()); msprintf(szDbgMsg, countof(szDbgMsg), L"Can't open pipe, ErrCode=%u\n%s\nWait: %u,%u,%u", dwErr, szPipeName, bWaitCalled, bWaitPipeRc, nWaitPipeErr); int nBtn = ::MessageBox(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL|MB_RETRYCANCEL); if (nBtn == IDCANCEL) return NULL; } #endif nDuration = GetTickCount() - dwStartTick; if (hStop) { // Затребовано завершение приложения или еще что-то nStopWaitRc = WaitForSingleObject(hStop, 0); if (nStopWaitRc == WAIT_OBJECT_0) { return NULL; } } if (dwErr == ERROR_PIPE_BUSY) { if ((nTries > 0) && (nDuration < nOpenPipeTimeout)) { bWaitCalled = TRUE; // All pipe instances are busy, so wait for a while (not more 500 ms). bWaitPipeRc = WaitNamedPipe(szPipeName, nWaitPipeTimeout); nWaitPipeErr = GetLastError(); UNREFERENCED_PARAMETER(bWaitPipeRc); UNREFERENCED_PARAMETER(nWaitPipeErr); // -- 120602 раз они заняты (но живы), то будем ждать, пока не освободятся //nTries--; continue; } else { _ASSERTEX(dwErr != ERROR_PIPE_BUSY); } } // Сделаем так, чтобы хотя бы пару раз он попробовал повторить if ((nTries <= 0) || (nDuration > nOpenPipeTimeout)) { //if (pszErr) { msprintf(szErr, countof(szErr), L"%s.%u: CreateFile(%s) failed, code=0x%08X, Timeout", ModuleName(szModule), GetCurrentProcessId(), szPipeName, dwErr); _ASSERTEX(FALSE && "Pipe open failed with timeout!"); } return NULL; } else { nTries--; } // Может быть пайп еще не создан (в процессе срабатывания семафора) if (dwErr == ERROR_FILE_NOT_FOUND) { // Wait for a while (10 ms) Sleep(nSleepError); continue; } // Exit if an error other than ERROR_PIPE_BUSY occurs. // -- if (dwErr != ERROR_PIPE_BUSY) // уже проверено выше { //if (pszErr) { msprintf(szErr, countof(szErr), L"%s.%u: CreateFile(%s) failed, code=0x%08X", ModuleName(szModule), GetCurrentProcessId(), szPipeName, dwErr); } return NULL; } // Уже сделано выше //// All pipe instances are busy, so wait for 500 ms. //WaitNamedPipe(szPipeName, 500); //if (!WaitNamedPipe(szPipeName, 1000) ) //{ // dwErr = GetLastError(); // if (pszErr) // { // StringCchPrintf(pszErr, countof(pszErr), L"%s: WaitNamedPipe(%s) failed, code=0x%08X, WaitNamedPipe", // szModule ? szModule : L"Unknown", szPipeName, dwErr); // // Видимо это возникает в момент запуска (обычно для ShiftEnter - новая консоль) // // не сразу срабатывает GUI и RCon еще не создал Pipe для HWND консоли // _ASSERTE(dwErr == 0); // } // return NULL; //} } #ifdef _DEBUG DWORD nCurState = 0, nCurInstances = 0; BOOL bCurState = GetNamedPipeHandleState(hPipe, &nCurState, &nCurInstances, NULL, NULL, NULL, 0); #endif // The pipe connected; change to message-read mode. dwMode = CE_PIPE_READMODE; fSuccess = SetNamedPipeHandleState( hPipe, // pipe handle &dwMode, // new pipe mode NULL, // don't set maximum bytes NULL); // don't set maximum time #if 0 if (!fSuccess) { dwErr = GetLastError(); _ASSERTE(fSuccess); //if (pszErr) { msprintf(szErr, countof(szErr), L"%s.%u: SetNamedPipeHandleState(%s) failed, code=0x%08X", ModuleName(szModule), GetCurrentProcessId(), szPipeName, dwErr); #ifdef _DEBUG int nCurLen = lstrlen(szErr); msprintf(szErr+nCurLen, countof(szErr)-nCurLen, L"\nCurState: %u,x%08X,%u", bCurState, nCurState, nCurInstances); #endif } CloseHandle(hPipe); #ifdef _DEBUG if (gbPipeDebugBoxes) { szDbgMsg[0] = 0; GetModuleFileName(NULL, szDbgMsg, countof(szDbgMsg)); msprintf(szTitle, countof(szTitle), L"%s: PID=%u", PointToName(szDbgMsg), GetCurrentProcessId()); ::MessageBox(NULL, szErr, szTitle, MB_SYSTEMMODAL); } #endif return NULL; } #endif UNREFERENCED_PARAMETER(bWaitCalled); UNREFERENCED_PARAMETER(fSuccess); return hPipe; }
LRESULT CFrameHolder::OnPaint(HWND hWnd, HDC hdc, UINT uMsg) { if (hdc == NULL) { LRESULT lRc = 0; PAINTSTRUCT ps = {0}; hdc = BeginPaint(hWnd, &ps); if (hdc != NULL) { lRc = OnPaint(hWnd, hdc, uMsg); EndPaint(hWnd, &ps); } else { _ASSERTE(hdc != NULL); } return lRc; } #ifdef _DEBUG RECT rcClientReal = {}; GetClientRect(hWnd, &rcClientReal); MapWindowPoints(hWnd, NULL, (LPPOINT)&rcClientReal, 2); #endif // Если "завис" PostUpdate if (gpConEmu->mp_TabBar->NeedPostUpdate()) gpConEmu->mp_TabBar->Update(); // Go RECT wr, cr; RecalculateFrameSizes(); wr = gpConEmu->GetGuiClientRect(); #ifdef _DEBUG wchar_t szPaint[140]; _wsprintf(szPaint, SKIPCOUNT(szPaint) L"MainClient %s at {%i,%i}-{%i,%i} screen coords, size (%ix%i) calc (%ix%i)", (uMsg == WM_PAINT) ? L"WM_PAINT" : (uMsg == WM_PRINTCLIENT) ? L"WM_PRINTCLIENT" : L"UnknownMsg", LOGRECTCOORDS(rcClientReal), LOGRECTSIZE(rcClientReal), LOGRECTSIZE(wr)); DEBUGSTRPAINT(szPaint); #endif #if defined(CONEMU_TABBAR_EX) #ifdef RED_CLIENT_FILL HBRUSH h = CreateSolidBrush(RGB(255,0,0)); FillRect(hdc, &wr, h); DeleteObject(h); return 0; #endif #endif if (gpSet->isStatusBarShow) { int nHeight = gpSet->StatusBarHeight(); if (nHeight < (wr.bottom - wr.top)) { RECT rcStatus = {wr.left, wr.bottom - nHeight, wr.right, wr.bottom}; gpConEmu->mp_Status->PaintStatus(hdc, &rcStatus); wr.bottom = rcStatus.top; } } cr = wr; DEBUGTEST(FrameDrawStyle dt = gpConEmu->DrawType()); #if defined(CONEMU_TABBAR_EX) RECT tr = {}; if (!gpSet->isTabsInCaption) { _ASSERTE(gpConEmu->GetDwmClientRectTopOffset() == 0); // CheckIt, must be zero if (gpSet->isTabs) { RECT captrect = gpConEmu->CalcRect(CER_TAB, wr, CER_MAINCLIENT); //CalculateCaptionPosition(cr, &captrect); CalculateTabPosition(cr, captrect, &tr); PaintDC dc = {false}; RECT pr = {captrect.left, 0, captrect.right, captrect.bottom}; gpConEmu->BeginBufferedPaint(hdc, pr, dc); gpConEmu->mp_TabBar->PaintTabs(dc, captrect, tr); gpConEmu->EndBufferedPaint(dc, TRUE); } } else if (dt == fdt_Aero || dt == fdt_Win8) { _ASSERTE(gpSet->isTabsInCaption); int nOffset = gpConEmu->GetDwmClientRectTopOffset(); // "Рамка" расширена на клиентскую область, поэтому // нужно зарисовать заголовок черной кистью, иначе идет // искажение цвета для кнопок Min/Max/Close if (gpSet->isTabs) { RECT captrect = gpConEmu->CalcRect(CER_TAB, wr, CER_MAINCLIENT); //CalculateCaptionPosition(cr, &captrect); CalculateTabPosition(cr, captrect, &tr); PaintDC dc = {false}; RECT pr = {captrect.left, 0, captrect.right, captrect.bottom}; gpConEmu->BeginBufferedPaint(hdc, pr, dc); gpConEmu->mp_TabBar->PaintTabs(dc, captrect, tr); gpConEmu->EndBufferedPaint(dc, TRUE); // There is no "Glass" in Win8 mb_WasGlassDraw = IsWindows7 && !IsWindows8; } cr.top += nOffset; } #endif #ifdef _DEBUG int nWidth = (cr.right-cr.left); int nHeight = (cr.bottom-cr.top); #endif WARNING("Пока табы рисуем не сами и ExtendDWM отсутствует - дополнительные изыски с временным DC не нужны"); #if 0 if (!gpSet->isTabsInCaption) { //OnPaintClient(hdc/*, nWidth, nHeight*/); } else // Создадим временный DC, для удобства отрисовки в Glass-режиме и для фикса глюка DWM(?) см.ниже // В принципе, для режима Win2k/XP временный DC можно не создавать, если это будет тормозить { //_ASSERTE(FALSE && "Need to be rewritten"); HDC hdcPaint = CreateCompatibleDC(hdc); HBITMAP hbmp = CreateCompatibleBitmap(hdc, nWidth, nHeight); HBITMAP hOldBmp = (HBITMAP)SelectObject(hdcPaint, hbmp); //OnPaintClient(hdcPaint/*, nWidth, nHeight*/); if ((dt == fdt_Aero) || !(mb_WasGlassDraw && gpConEmu->isZoomed())) { BitBlt(hdc, cr.left, cr.top, nWidth, nHeight, hdcPaint, 0, 0, SRCCOPY); } else { //mb_WasGlassDraw = FALSE; // Какой-то странный глюк DWM. При отключении Glass несколько верхних строк // клиентской области оказываются "разрушенными" - у них остается атрибут "прозрачности" // хотя прозрачность (Glass) уже отключена. В результате эти строки - белесые BITMAPINFOHEADER bi = {sizeof(BITMAPINFOHEADER)}; bi.biWidth = cr.right-cr.left+1; bi.biHeight = GetFrameHeight()+1; bi.biPlanes = 1; bi.biBitCount = 32; COLORREF *pPixels = NULL; HDC hdcTmp = CreateCompatibleDC(hdc); HBITMAP hTmp = CreateDIBSection(hdcTmp, (BITMAPINFO*)&bi, DIB_RGB_COLORS, (void**)&pPixels, NULL, 0); if (hTmp == NULL) { _ASSERTE(hTmp == NULL); BitBlt(hdc, cr.left, cr.top, nWidth, nHeight, hdcPaint, 0, 0, SRCCOPY); } else { HBITMAP hOldTmp = (HBITMAP)SelectObject(hdcTmp, hTmp); BitBlt(hdcTmp, 0, 0, bi.biWidth, bi.biHeight, hdcPaint, 0, 0, SRCCOPY); int i = 0; for (int y = 0; y < bi.biHeight; y++) { for (int x = 0; x < bi.biWidth; x++) { pPixels[i++] |= 0xFF000000; } } BitBlt(hdc, cr.left, cr.top, bi.biWidth, bi.biHeight, hdcTmp, 0, 0, SRCCOPY); if (nHeight > bi.biHeight) BitBlt(hdc, cr.left, cr.top+bi.biHeight, nWidth, nHeight-bi.biHeight, hdcPaint, 0, bi.biHeight, SRCCOPY); SelectObject(hdcTmp, hOldTmp); DeleteObject(hbmp); } DeleteDC(hdcTmp); } SelectObject(hdcPaint, hOldBmp); DeleteObject(hbmp); DeleteDC(hdcPaint); } #endif return 0; }
static NTSTATUS FspFsvolWriteCached( PDEVICE_OBJECT FsvolDeviceObject, PIRP Irp, PIO_STACK_LOCATION IrpSp, BOOLEAN CanWait) { PAGED_CODE(); /* assert: must be top-level IRP */ ASSERT(0 == FspIrpTopFlags(Irp)); NTSTATUS Result; BOOLEAN Retrying = 0 != FspIrpRequest(Irp); PFILE_OBJECT FileObject = IrpSp->FileObject; FSP_FILE_NODE *FileNode = FileObject->FsContext; LARGE_INTEGER WriteOffset = IrpSp->Parameters.Write.ByteOffset; ULONG WriteLength = IrpSp->Parameters.Write.Length; BOOLEAN WriteToEndOfFile = FILE_WRITE_TO_END_OF_FILE == WriteOffset.LowPart && -1L == WriteOffset.HighPart; BOOLEAN SynchronousIo = BooleanFlagOn(FileObject->Flags, FO_SYNCHRONOUS_IO); FSP_FSCTL_FILE_INFO FileInfo; CC_FILE_SIZES FileSizes; FILE_END_OF_FILE_INFORMATION EndOfFileInformation; UINT64 WriteEndOffset; BOOLEAN ExtendingFile; BOOLEAN Success; /* should we defer the write? */ Success = DEBUGTEST(90) && CcCanIWrite(FileObject, WriteLength, CanWait, Retrying); if (!Success) { Result = FspWqCreateIrpWorkItem(Irp, FspFsvolWriteCached, 0); if (NT_SUCCESS(Result)) { IoMarkIrpPending(Irp); CcDeferWrite(FileObject, FspFsvolWriteCachedDeferred, Irp, 0, WriteLength, Retrying); return STATUS_PENDING; } /* if we are unable to defer we will go ahead and (try to) service the IRP now! */ } /* try to acquire the FileNode Main exclusive */ Success = DEBUGTEST(90) && FspFileNodeTryAcquireExclusiveF(FileNode, FspFileNodeAcquireMain, CanWait); if (!Success) return FspWqRepostIrpWorkItem(Irp, FspFsvolWriteCached, 0); /* perform oplock check */ Result = FspFileNodeOplockCheckAsync( FileNode, FspFileNodeAcquireMain, FspFsvolWriteCached, Irp); if (STATUS_PENDING == Result) return Result; if (!NT_SUCCESS(Result)) { FspFileNodeRelease(FileNode, Main); return Result; } /* check the file locks */ if (!FsRtlCheckLockForWriteAccess(&FileNode->FileLock, Irp)) { FspFileNodeRelease(FileNode, Main); return STATUS_FILE_LOCK_CONFLICT; } /* compute new file size */ ASSERT(FspTimeoutInfinity32 == FspFsvolDeviceExtension(FsvolDeviceObject)->VolumeParams.FileInfoTimeout); FspFileNodeGetFileInfo(FileNode, &FileInfo); if (WriteToEndOfFile) WriteOffset.QuadPart = FileInfo.FileSize; WriteEndOffset = WriteOffset.QuadPart + WriteLength; ExtendingFile = FileInfo.FileSize < WriteEndOffset; if (ExtendingFile && !CanWait) { /* need CanWait==TRUE for FspSendSetInformationIrp */ FspFileNodeRelease(FileNode, Main); return FspWqRepostIrpWorkItem(Irp, FspFsvolWriteCached, 0); } /* initialize cache if not already initialized! */ if (0 == FileObject->PrivateCacheMap) { FileSizes.AllocationSize.QuadPart = FileInfo.AllocationSize; FileSizes.FileSize.QuadPart = FileInfo.FileSize; FileSizes.ValidDataLength.QuadPart = MAXLONGLONG; Result = FspCcInitializeCacheMap(FileObject, &FileSizes, FALSE, &FspCacheManagerCallbacks, FileNode); if (!NT_SUCCESS(Result)) { FspFileNodeRelease(FileNode, Main); return Result; } } /* are we extending the file? */ if (ExtendingFile) { ASSERT(CanWait); /* send EndOfFileInformation IRP; this will also set TruncateOnClose, etc. */ EndOfFileInformation.EndOfFile.QuadPart = WriteEndOffset; Result = FspSendSetInformationIrp(FsvolDeviceObject/* bypass filters */, FileObject, FileEndOfFileInformation, &EndOfFileInformation, sizeof EndOfFileInformation); if (!NT_SUCCESS(Result)) { FspFileNodeRelease(FileNode, Main); return Result; } /* double-check that the cache still exists in case CcSetFileSizes failed */ if (0 == FileObject->SectionObjectPointer->SharedCacheMap) { FspFileNodeRelease(FileNode, Main); return STATUS_INSUFFICIENT_RESOURCES; // or STATUS_SECTION_TOO_BIG? } } /* * From this point forward we must jump to the CLEANUP label on failure. */ /* are we using the copy or MDL interface? */ if (!FlagOn(IrpSp->MinorFunction, IRP_MN_MDL)) { PVOID Buffer; Buffer = 0 == Irp->MdlAddress ? Irp->UserBuffer : MmGetSystemAddressForMdlSafe(Irp->MdlAddress, NormalPagePriority); if (0 == Buffer) { Result = STATUS_INSUFFICIENT_RESOURCES; goto cleanup; } Result = FspCcCopyWrite(FileObject, &WriteOffset, WriteLength, CanWait, Buffer); if (!NT_SUCCESS(Result) || STATUS_PENDING == Result) goto cleanup; Irp->IoStatus.Information = WriteLength; } else { Result = FspCcPrepareMdlWrite(FileObject, &WriteOffset, WriteLength, &Irp->MdlAddress, &Irp->IoStatus); if (!NT_SUCCESS(Result)) goto cleanup; ASSERT(STATUS_PENDING != Result); } /* update the current file offset if synchronous I/O */ if (SynchronousIo) FileObject->CurrentByteOffset.QuadPart = WriteEndOffset; /* mark the file object as modified (if not paging I/O) */ SetFlag(FileObject->Flags, FO_FILE_MODIFIED); FspFileNodeRelease(FileNode, Main); return STATUS_SUCCESS; cleanup: FspFileNodeRelease(FileNode, Main); if (STATUS_PENDING == Result) return FspWqRepostIrpWorkItem(Irp, FspFsvolWriteCached, 0); return Result; }
bool CAttachDlg::CanAttachWindow(HWND hFind, DWORD nSkipPID, CProcessData* apProcessData, CAttachDlg::AttachWndInfo& Info) { static bool bIsWin64 = IsWindows64(); ZeroStruct(Info); DWORD_PTR nStyle = GetWindowLongPtr(hFind, GWL_STYLE); DWORD_PTR nStyleEx = GetWindowLongPtr(hFind, GWL_EXSTYLE); if (!GetWindowThreadProcessId(hFind, &Info.nPID)) Info.nPID = 0; if (!Info.nPID) return false; bool lbCan = ((nStyle & (WS_VISIBLE/*|WS_CAPTION|WS_MAXIMIZEBOX*/)) == (WS_VISIBLE/*|WS_CAPTION|WS_MAXIMIZEBOX*/)); if (lbCan) { // Более тщательно стили проверить lbCan = ((nStyle & WS_MAXIMIZEBOX) == WS_MAXIMIZEBOX) || ((nStyle & WS_THICKFRAME) == WS_THICKFRAME); } if (lbCan && Info.nPID == GetCurrentProcessId()) lbCan = false; if (lbCan && Info.nPID == nSkipPID) lbCan = false; if (lbCan && (nStyle & WS_CHILD)) lbCan = false; if (lbCan && (nStyleEx & WS_EX_TOOLWINDOW)) lbCan = false; if (lbCan && gpConEmu->isOurConsoleWindow(hFind)) lbCan = false; if (lbCan && gpConEmu->mp_Inside && (hFind == gpConEmu->mp_Inside->mh_InsideParentRoot)) lbCan = false; GetClassName(hFind, Info.szClass, countof(Info.szClass)); GetWindowText(hFind, Info.szTitle, countof(Info.szTitle)); if (gpSetCls->isAdvLogging) { wchar_t szLogInfo[MAX_PATH*3]; _wsprintf(szLogInfo, SKIPLEN(countof(szLogInfo)) L"Attach:%s x%08X/x%08X/x%08X {%s} \"%s\"", Info.szExeName, LODWORD(hFind), nStyle, nStyleEx, Info.szClass, Info.szTitle); CVConGroup::LogString(szLogInfo); } if (!lbCan) return false; _wsprintf(Info.szPid, SKIPLEN(countof(Info.szPid)) L"%u", Info.nPID); const wchar_t sz32bit[] = L" [32]"; const wchar_t sz64bit[] = L" [64]"; HANDLE h; DEBUGTEST(DWORD nErr); bool lbExeFound = false; if (apProcessData) { lbExeFound = apProcessData->GetProcessName(Info.nPID, Info.szExeName, countof(Info.szExeName), Info.szExePathName, countof(Info.szExePathName), &Info.nImageBits); if (lbExeFound) { //ListView_SetItemText(hList, nItem, alc_File, szExeName); //ListView_SetItemText(hList, nItem, alc_Path, szExePathName); if (bIsWin64 && Info.nImageBits) { wcscat_c(Info.szPid, (Info.nImageBits == 64) ? sz64bit : sz32bit); } } } if (!lbExeFound) { Info.nImageBits = GetProcessBits(Info.nPID); if (bIsWin64 && Info.nImageBits) { wcscat_c(Info.szPid, (Info.nImageBits == 64) ? sz64bit : sz32bit); } h = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, Info.nPID); if (h && h != INVALID_HANDLE_VALUE) { MODULEENTRY32 mi = {sizeof(mi)}; if (Module32First(h, &mi)) { lstrcpyn(Info.szExeName, *mi.szModule ? mi.szModule : (wchar_t*)PointToName(mi.szExePath), countof(Info.szExeName)); lstrcpyn(Info.szExePathName, mi.szExePath, countof(Info.szExePathName)); lbExeFound = true; } else { if (bIsWin64) { wcscat_c(Info.szPid, sz64bit); } } CloseHandle(h); } else { #ifdef _DEBUG nErr = GetLastError(); _ASSERTE(nErr == 5 || (nErr == 299 && Info.nImageBits == 64)); #endif wcscpy_c(Info.szExeName, L"???"); } #if 0 //#ifdef _WIN64 -- no need to call TH32CS_SNAPMODULE32, simple TH32CS_SNAPMODULE will handle both if it can if (!lbExeFound) { h = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE|TH32CS_SNAPMODULE32, Info.nPID); if (h && h != INVALID_HANDLE_VALUE) { MODULEENTRY32 mi = {sizeof(mi)}; if (Module32First(h, &mi)) { //ListView_SetItemText(hList, nItem, alc_File, *mi.szModule ? mi.szModule : (wchar_t*)PointToName(mi.szExePath)); lstrcpyn(Info.szExeName, *mi.szModule ? mi.szModule : (wchar_t*)PointToName(mi.szExePath), countof(Info.szExeName)); //ListView_SetItemText(hList, nItem, alc_Path, mi.szExePath); lstrcpyn(Info.szExePathName, mi.szExePath, countof(Info.szExePathName)); } CloseHandle(h); } } #endif } if (!lbExeFound) { // Так можно получить только имя файла процесса PROCESSENTRY32 pi = {sizeof(pi)}; h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (h && h != INVALID_HANDLE_VALUE) { if (Process32First(h, &pi)) { do { if (pi.th32ProcessID == Info.nPID) { lstrcpyn(Info.szExeName, pi.szExeFile, countof(Info.szExeName)); break; } } while (Process32Next(h, &pi)); } } } wcscpy_c(Info.szType, isConsoleClass(Info.szClass) ? szTypeCon : szTypeGui); return true; }
// // IDataObject::SetData // HRESULT __stdcall CDataObject::SetData(FORMATETC *pFormatEtc, STGMEDIUM *pMedium, BOOL fRelease) { _ASSERTE(pMedium && pMedium->pUnkForRelease==NULL); #ifdef _DEBUG LPCWSTR pszName = GetFormatName(pFormatEtc->cfFormat, true); DWORD nData = (DWORD)-1; if (lstrcmp(pszName, L"IsShowingLayered")==0 || lstrcmp(pszName, L"IsShowingText")==0 || lstrcmp(pszName, L"DragContext")==0 || lstrcmp(pszName, L"UsingDefaultDragImage")==0 || lstrcmp(pszName, L"DragSourceHelperFlags")==0 || lstrcmp(pszName, L"DragWindow")==0 || lstrcmp(pszName, L"DisableDragText")==0 ) { LPDWORD pdw = (LPDWORD)GlobalLock(pMedium->hGlobal); if (pdw) { nData = *pdw; } GlobalUnlock(pMedium->hGlobal); } wchar_t szDbg[255]; _wsprintf(szDbg, SKIPLEN(countof(szDbg)) L"CDataObject::SetData {cfFormat=%s, lindex=%i, tymed=x%02X(%u)}, {tymed=x%02X}", GetFormatName(pFormatEtc->cfFormat), pFormatEtc->lindex, pFormatEtc->tymed, pFormatEtc->tymed, pMedium->tymed); if (nData != (DWORD)-1) { int nLen = lstrlen(szDbg); _wsprintf(szDbg+nLen, SKIPLEN(countof(szDbg)-nLen) L", Data=x%02X(%u)", nData, nData); } wcscat_c(szDbg, L"\n"); DEBUGSTRDATA(szDbg); #endif DEBUGTEST(bool bNew = false); LONG nIndex = LookupFormatEtc(pFormatEtc); if (nIndex >= 0) { if ((pMedium != &(m_Data[nIndex].StgMedium)) && (pMedium->hGlobal != &(m_Data[nIndex].StgMedium))) { if (m_Data[nIndex].fRelease) { ReleaseStgMedium(&m_Data[nIndex].StgMedium); } else { ZeroStruct(m_Data[nIndex].StgMedium); } } else { Assert((pMedium != &(m_Data[nIndex].StgMedium)) && (pMedium->hGlobal != &(m_Data[nIndex].StgMedium))); } } else // if (nIndex < 0) { DEBUGTEST(bNew = true); _ASSERTE(nIndex < 0); DragData newItem = {}; newItem.FormatEtc = *pFormatEtc; nIndex = m_Data.push_back(newItem); } m_Data[nIndex].fUsed = TRUE; m_Data[nIndex].fRelease = fRelease; m_Data[nIndex].StgMedium = *pMedium; return S_OK; }