void CWE114_Process_Control__w32_wchar_t_listen_socket_02_bad()
{
    wchar_t * data;
    wchar_t dataBuffer[100] = L"";
    data = dataBuffer;
    if(1)
    {
        {
#ifdef _WIN32
            WSADATA wsaData;
            int wsaDataInit = 0;
#endif
            int recvResult;
            struct sockaddr_in service;
            wchar_t *replace;
            SOCKET listenSocket = INVALID_SOCKET;
            SOCKET acceptSocket = INVALID_SOCKET;
            size_t dataLen = wcslen(data);
            do
            {
#ifdef _WIN32
                if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
                {
                    break;
                }
                wsaDataInit = 1;
#endif
                /* POTENTIAL FLAW: Read data using a listen socket */
                listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
                if (listenSocket == INVALID_SOCKET)
                {
                    break;
                }
                memset(&service, 0, sizeof(service));
                service.sin_family = AF_INET;
                service.sin_addr.s_addr = INADDR_ANY;
                service.sin_port = htons(TCP_PORT);
                if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
                {
                    break;
                }
                if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
                {
                    break;
                }
                acceptSocket = accept(listenSocket, NULL, NULL);
                if (acceptSocket == SOCKET_ERROR)
                {
                    break;
                }
                /* Abort on error or the connection was closed */
                recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(wchar_t) * (100 - dataLen - 1), 0);
                if (recvResult == SOCKET_ERROR || recvResult == 0)
                {
                    break;
                }
                /* Append null terminator */
                data[dataLen + recvResult / sizeof(wchar_t)] = L'\0';
                /* Eliminate CRLF */
                replace = wcschr(data, L'\r');
                if (replace)
                {
                    *replace = L'\0';
                }
                replace = wcschr(data, L'\n');
                if (replace)
                {
                    *replace = L'\0';
                }
            }
            while (0);
            if (listenSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(listenSocket);
            }
            if (acceptSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(acceptSocket);
            }
#ifdef _WIN32
            if (wsaDataInit)
            {
                WSACleanup();
            }
#endif
        }
    }
    {
        HMODULE hModule;
        /* POTENTIAL FLAW: If the path to the library is not specified, an attacker may be able to
         * replace his own file with the intended library */
        hModule = LoadLibraryW(data);
        if (hModule != NULL)
        {
            FreeLibrary(hModule);
            printLine("Library loaded and freed successfully");
        }
        else
        {
            printLine("Unable to load library");
        }
    }
}
Esempio n. 2
0
	bool Init(struct CET_Init* pInit)
	{
		bool result = false;
		nErrNumber = 0;
		//pszPluginKey = pInit->pRegKey;
		//ReloadConfig();
		HRESULT hrCoInitialized = CoInitialize(NULL);
		bCoInitialized = SUCCEEDED(hrCoInitialized);
		wchar_t FullPath[MAX_PATH*2+15]; FullPath[0] = 0;
		//if (ghModule)
		//{
		//	PVDSettings::FindFile(L"GdiPlus.dll", FullPath, sizeofarray(FullPath));
		//	hGDIPlus = LoadLibraryW(FullPath);
		//}
		//if (!hGDIPlus)
		hGDIPlus = LoadLibraryW(L"GdiPlus.dll");

		if (!hGDIPlus)
		{
			nErrNumber = PGE_DLL_NOT_FOUND;
		}
		else
		{
			DllGetFunction(hGDIPlus, GdiplusStartup);
			DllGetFunction(hGDIPlus, GdiplusShutdown);
			DllGetFunction(hGDIPlus, GdipCreateBitmapFromFile);
			DllGetFunction(hGDIPlus, GdipGetImageThumbnail);
			//DllGetFunction(hGDIPlus, GdipCreateBitmapFromFileICM);
			//DllGetFunction(hGDIPlus, GdipCreateBitmapFromStream);
			//DllGetFunction(hGDIPlus, GdipCreateBitmapFromStreamICM);
			DllGetFunction(hGDIPlus, GdipGetImageWidth);
			DllGetFunction(hGDIPlus, GdipGetImageHeight);
			DllGetFunction(hGDIPlus, GdipGetImagePixelFormat);
			//DllGetFunction(hGDIPlus, GdipBitmapLockBits);
			//DllGetFunction(hGDIPlus, GdipBitmapUnlockBits);
			DllGetFunction(hGDIPlus, GdipDisposeImage);
			DllGetFunction(hGDIPlus, GdipImageGetFrameCount);
			DllGetFunction(hGDIPlus, GdipImageSelectActiveFrame);
			DllGetFunction(hGDIPlus, GdipGetPropertyItemSize);
			DllGetFunction(hGDIPlus, GdipGetPropertyItem);
			DllGetFunction(hGDIPlus, GdipImageRotateFlip);
			DllGetFunction(hGDIPlus, GdipGetImageRawFormat);
			//DllGetFunction(hGDIPlus, GdipGetImageFlags);
			//DllGetFunction(hGDIPlus, GdipGetImagePalette);
			//DllGetFunction(hGDIPlus, GdipGetImagePaletteSize);
			DllGetFunction(hGDIPlus, GdipCreateFromHDC);
			DllGetFunction(hGDIPlus, GdipDeleteGraphics);
			DllGetFunction(hGDIPlus, GdipDrawImageRectRectI);
			//DllGetFunction(hGDIPlus, GdipCreateBitmapFromScan0);
			//DllGetFunction(hGDIPlus, GdipFillRectangleI);
			//DllGetFunction(hGDIPlus, GdipCreateSolidFill);
			//DllGetFunction(hGDIPlus, GdipDeleteBrush);
			//DllGetFunction(hGDIPlus, GdipCloneBitmapAreaI);
			//DllGetFunction(hGDIPlus, GdipSetImagePalette);

			if (GdiplusStartup && GdiplusShutdown && GdipCreateBitmapFromFile && GdipGetImageThumbnail
			        && GdipGetImageWidth && GdipGetImageHeight && GdipGetImagePixelFormat && GdipGetImageRawFormat
			        //&& GdipBitmapLockBits && GdipBitmapUnlockBits
			        && GdipDisposeImage && GdipImageGetFrameCount && GdipImageSelectActiveFrame
			        && GdipGetPropertyItemSize && GdipGetPropertyItem && GdipImageRotateFlip
			        //&& GdipGetImagePalette && GdipGetImagePaletteSize && GdipCloneBitmapAreaI && GdipGetImageFlags
			        && GdipCreateFromHDC && GdipDeleteGraphics && GdipDrawImageRectRectI
			        //&& GdipCreateBitmapFromScan0 && GdipFillRectangleI && GdipCreateSolidFill && GdipDeleteBrush
			        //&& GdipSetImagePalette
			  )
			{
				Gdiplus::GdiplusStartupInput gdiplusStartupInput;
				Gdiplus::Status lRc = GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
				result = (lRc == Gdiplus::Ok);

				if (!result)
				{
					nLastError = GetLastError();
					GdiplusShutdown(gdiplusToken); bTokenInitialized = false;
					nErrNumber = PGE_ERROR_BASE + (DWORD)lRc;
				}
				else
				{
					bTokenInitialized = true;
				}
			}
			else
			{
				nErrNumber = PGE_FUNCTION_NOT_FOUND;
			}

			if (!result)
				FreeLibrary(hGDIPlus);
		}

		if (result)
		{
			pInit->pContext = this;
			pInit->nModuleID = MODULE_GDIP;
		}

		return result;
	};
Esempio n. 3
0
bool CCommonWidget::winEvent (MSG* msg, long *result)
{
	switch(msg->message)
	{
		case WM_INPUTLANGCHANGEREQUEST:
			{
				HKL hkl = (HKL)msg->lParam;  
				//激活对应输入法
				ActivateKeyboardLayout(hkl, KLF_REPLACELANG);

				//不允许默认处理,否则某些输入法会导致程序卡死
				*result = 0;
			}
			return true;

		case WM_GETMINMAXINFO:
			{
				MINMAXINFO *mmi = (MINMAXINFO *)msg->lParam;
				const QRect rect = QApplication::desktop()->availableGeometry();
				RECT clientRect,wndRect;
				POINT point = {0,0};
				::GetClientRect(winId(),&clientRect);
				::ClientToScreen(winId(),&point);
				::OffsetRect(&clientRect,point.x,point.y);
				::GetWindowRect(winId(),&wndRect);
				if(clientRect.right - clientRect.left > 0)
				{
					int leftOffset = clientRect.left - wndRect.left;
					int topOffset = clientRect.top - wndRect.top;
					int rightOffset = wndRect.right - clientRect.right;
					int bottomOffset = wndRect.bottom - clientRect.bottom;
					m_oMaxMargins.setLeft(leftOffset);
					m_oMaxMargins.setTop(topOffset);
					m_oMaxMargins.setRight(rightOffset);
					m_oMaxMargins.setBottom(bottomOffset);
					mmi->ptMaxPosition.x = rect.left() - leftOffset;
					mmi->ptMaxPosition.y = rect.top()  - topOffset;
					mmi->ptMaxSize.x = rect.width() + leftOffset + rightOffset;
					mmi->ptMaxSize.y = rect.height() + topOffset + bottomOffset;
					mmi->ptMaxTrackSize.x = mmi->ptMaxSize.x;
					mmi->ptMaxTrackSize.y = mmi->ptMaxSize.y;
				}
				else
				{
					mmi->ptMaxPosition.x = rect.left() - m_oMaxMargins.left();
					mmi->ptMaxPosition.y = rect.top()  - m_oMaxMargins.top();
					mmi->ptMaxSize.x = rect.width() + m_oMaxMargins.left() + m_oMaxMargins.right();
					mmi->ptMaxSize.y = rect.height() + m_oMaxMargins.top() + m_oMaxMargins.bottom();
					mmi->ptMaxTrackSize.x = mmi->ptMaxSize.x;
					mmi->ptMaxTrackSize.y = mmi->ptMaxSize.y;
				}
			}
			break;

		case WM_NCHITTEST:
			{
				QPoint absPos(LOWORD(msg->lParam), HIWORD(msg->lParam));
				QPoint pos = mapFromGlobal(absPos);
				int x = pos.x();
				int y = pos.y();
				int w = width();
				int h = height();
				if(x >= 0 && x <= w && y >= 0 && y <= h)
				{
					if((m_lWndFlag & enum_GGWndResizeHint) && !isMaximized() && !isMinimized())
					{
						if(x < DEF_NOCLIENT_SIZE)
						{
							if(y < DEF_NOCLIENT_SIZE)
							{
								*result = HTTOPLEFT;
							}
							else if(y > h - DEF_NOCLIENT_SIZE)
							{
								*result = HTBOTTOMLEFT;
							}
							else
							{
								*result = HTLEFT;
							}
						}
						else if(x > w - DEF_NOCLIENT_SIZE)
						{
							if(y < DEF_NOCLIENT_SIZE)
							{
								*result = HTTOPRIGHT;
							}
							else if(y > h - DEF_NOCLIENT_SIZE)
							{
								*result = HTBOTTOMRIGHT;
							}
							else
							{
								*result = HTRIGHT;
							}
						}
						else if(y < DEF_NOCLIENT_SIZE)
						{
							*result = HTTOP;
						}
						else if(y > h - DEF_NOCLIENT_SIZE)
						{
							*result = HTBOTTOM;
						}
						else if(y < TITLE_HEIGHT)
						{
							if(m_pTitleLabel)
							{
								const QRect rcTitle = m_pTitleLayout->geometry();
								if(x > rcTitle.x() && x < rcTitle.right() && y > rcTitle.y() && y < rcTitle.bottom())
								{
									*result = HTCAPTION;
								}
								else
								{
									*result = HTCLIENT;
								}
							}
							else
							{
								*result = HTCLIENT;
							}
						}
						else
						{
							*result = HTCLIENT;
						}
					}
					else
					{
						if(y < TITLE_HEIGHT)
						{
							if(m_pTitleLabel)
							{
								const QRect rcTitle = m_pTitleLayout->geometry();
								if(x > rcTitle.x() && x < rcTitle.right() && y > rcTitle.y() && y < rcTitle.bottom())
								{
									*result = HTCAPTION;
								}
								else
								{
									*result = HTCLIENT;
								}
							}
							else
							{
								*result = HTCLIENT;
							}
						}
						else
						{
							*result = HTCLIENT;
						}
					}
				}
				else
				{
					return false;
				}
			}
			return true;

		case WM_NCLBUTTONDBLCLK:
			{
				BOOL bCaption = FALSE;
				if((m_lWndFlag & (enum_GGWndResizeHint | enum_GGWndMaximizeButtonHint)))
				{
					QPoint absPos(LOWORD(msg->lParam), HIWORD(msg->lParam));
					QPoint pos = mapFromGlobal(absPos);
					int x = pos.x();
					int y = pos.y();
					int w = width();
					int h = height();
					if(y < TITLE_HEIGHT && x >= DEF_NOCLIENT_SIZE && x <= w - DEF_NOCLIENT_SIZE)
					{
						if(m_pTitleLabel)
						{
							const QRect rcTitle = m_pTitleLayout->geometry();
							if(x > rcTitle.x() && x < rcTitle.right() && y > rcTitle.y() && y < rcTitle.bottom())
							{
								bCaption = TRUE;
							}
						}
					}
				}

				if(bCaption)
				{
					if(isMaximized())
					{
						showNormal();
					}
					else if(isMinimized())
					{
						showNormal();
					}
					else
					{
						showMaximized();
					}
				}
			}
			return true;

		case WM_NCLBUTTONDOWN:
			if(isMaximized())
			{
				if(!COSInfo::IsAboveWinXP())
					return true;
			}
			break;

		case WM_NCCALCSIZE:
			if(msg->wParam)
			{
				NCCALCSIZE_PARAMS* lpncsp = (NCCALCSIZE_PARAMS*)msg->lParam;
				if(lpncsp->rgrc[0].right - lpncsp->rgrc[0].left > 10)
				{
					lpncsp->rgrc[0].left += 1;
					lpncsp->rgrc[0].top += 1;
					lpncsp->rgrc[0].right -= 1;
					lpncsp->rgrc[0].bottom -= 1;
				}
				//*result = WVR_ALIGNTOP | WVR_ALIGNLEFT | WVR_ALIGNBOTTOM | WVR_ALIGNRIGHT;
			}
			*result = 0;
			return true;

		case WM_ACTIVATE:
			{
				MARGINS margins = {-1};
				HINSTANCE hInst = LoadLibraryW(L"dwmapi.dll");
				if (hInst)
				{
					typedef HRESULT (WINAPI * TmpFun)(HWND,MARGINS*);
					TmpFun DwmExtendFrameIntoClientArea = (TmpFun)::GetProcAddress(hInst, "DwmExtendFrameIntoClientArea");
					if (DwmExtendFrameIntoClientArea)
					{
						DwmExtendFrameIntoClientArea(winId(),&margins);
					}
					FreeLibrary(hInst);
				}
				::SetWindowLongA(winId(),GWL_EXSTYLE, WS_EX_LEFT);
			}
			break;

		case WM_NCACTIVATE:
		case 0x00AE:
		case 0x00AF:
			*result = 0;
			return false;
	}

	return false;
}
Esempio n. 4
0
CWindowsVersion::CWindowsVersion()
{
	m_osv.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  
    if(!GetVersionEx(&m_osv))
    {
        ASSERT(0);
        // make sure nothing bad will happen trying to interpret OSVERSIONINFO
        memset((void*)&m_osv, 0, sizeof(m_osv));
    }
    else
    {
        switch(m_osv.dwPlatformId)
        {
        case VER_PLATFORM_WIN32s: //Win32s on Windows 3.1. 
            m_winVer = WV_32S;
            break;

        case VER_PLATFORM_WIN32_WINDOWS: //WIN32 on 95 or 98 or ME
            if(m_osv.dwMinorVersion == 0)
            {
                m_winVer = WV_95;
            }
            else if(m_osv.dwMinorVersion == 10)
            {
                m_winVer = WV_98;
            }
            if(m_osv.dwMinorVersion == 90)
            {
                m_winVer = WV_ME;
            }
            break;

        case VER_PLATFORM_WIN32_NT: //Win32 on Windows NT. 

            if(m_osv.dwMajorVersion == 4) 
            {
                m_winVer = WV_NT4;
            }
            else if(m_osv.dwMajorVersion >= 5)
            {
                m_winVer = WV_2K;
            }
            break;

        default: 
            m_winVer = WV_UNKNOWN;
            break;
        }
    }

    // get the language
    m_UILang = 0;
    switch(m_winVer)
    {
    case WV_2K:
        {
        // Disable this section to emulate Windows NT before Windows 2000, when testing
        // on Windows 2000
        // Use GetUserDefaultUILanguage to find the user's prefered UI language

        // Declare function pointer
        LANGID (WINAPI *pfnGetUserDefaultUILanguage) () = NULL ;

        HMODULE hMKernel32 = LoadLibraryW(L"kernel32.dll") ;
        
        pfnGetUserDefaultUILanguage = 
            (unsigned short (WINAPI *)(void)) 
                GetProcAddress(hMKernel32, "GetUserDefaultUILanguage") ;

        if(NULL != pfnGetUserDefaultUILanguage)
            m_UILang = pfnGetUserDefaultUILanguage() ;
        }
        break;
    case WV_NT4:
        {
            // Running on Windows NT 4.0 or earlier. Get UI language
            // from locale of .default user in registry:
            // HKEY_USERS\.DEFAULT\Control Panel\International\Locale
            CRegKeyEx key;
            if(ERROR_SUCCESS == key.Open(HKEY_USERS, _T(".DEFAULT\\Control Panel\\International"), KEY_READ))
            {
                CString value = key.QueryValueString(_T("Locale"));
                m_UILang = (LANGID)_tcstol(value,NULL,16);
            };
            
        }
        break;
    case WV_95:
    case WV_98:
    case WV_ME:
        {
            // Running on Windows 9x. Get the system UI language from registry:
            CRegKeyEx key;
            if(ERROR_SUCCESS == key.Open(HKEY_USERS, _T(".Default\\Control Panel\\desktop\\ResourceLocale"), KEY_READ))
            {
                CString value = key.QueryValueString(_T(""));
                m_UILang = (LANGID)_tcstol(value, 0, 16);
            };
            
        }
        break;
    }
	// get the common controls dll version
	m_comCtl32Version = GetDllVersion(_T("comctl32.dll"));
}
Esempio n. 5
0
NS_IMETHODIMP
LSPAnnotationGatherer::Run()
{
  PR_SetCurrentThreadName("LSP Annotator");

  mThread = NS_GetCurrentThread();

  DWORD size = 0;
  int err;
  // Get the size of the buffer we need
  if (SOCKET_ERROR != WSCEnumProtocols(nullptr, nullptr, &size, &err) ||
      err != WSAENOBUFS) {
    // Er, what?
    NS_NOTREACHED("WSCEnumProtocols suceeded when it should have failed ...");
    return NS_ERROR_FAILURE;
  }

  auto byteArray = MakeUnique<char[]>(size);
  WSAPROTOCOL_INFOW* providers =
    reinterpret_cast<WSAPROTOCOL_INFOW*>(byteArray.get());

  int n = WSCEnumProtocols(nullptr, providers, &size, &err);
  if (n == SOCKET_ERROR) {
    // Lame. We provided the right size buffer; we'll just give up now.
    NS_WARNING("Could not get LSP list");
    return NS_ERROR_FAILURE;
  }

  nsCString str;
  for (int i = 0; i < n; i++) {
    AppendUTF16toUTF8(nsDependentString(providers[i].szProtocol), str);
    str.AppendLiteral(" : ");
    str.AppendInt(providers[i].iVersion);
    str.AppendLiteral(" : ");
    str.AppendInt(providers[i].iAddressFamily);
    str.AppendLiteral(" : ");
    str.AppendInt(providers[i].iSocketType);
    str.AppendLiteral(" : ");
    str.AppendInt(providers[i].iProtocol);
    str.AppendLiteral(" : ");
    str.AppendPrintf("0x%x", providers[i].dwServiceFlags1);
    str.AppendLiteral(" : ");
    str.AppendPrintf("0x%x", providers[i].dwProviderFlags);
    str.AppendLiteral(" : ");

    wchar_t path[MAX_PATH];
    int pathLen = MAX_PATH;
    if (!WSCGetProviderPath(&providers[i].ProviderId, path, &pathLen, &err)) {
      AppendUTF16toUTF8(nsDependentString(path), str);
    }

    str.AppendLiteral(" : ");
    // If WSCGetProviderInfo is available, we should call it to obtain the
    // category flags for this provider. When present, these flags inform
    // Windows as to which order to chain the providers.
    nsModuleHandle ws2_32(LoadLibraryW(L"ws2_32.dll"));
    if (ws2_32) {
      decltype(WSCGetProviderInfo)* pWSCGetProviderInfo =
        reinterpret_cast<decltype(WSCGetProviderInfo)*>(
            GetProcAddress(ws2_32, "WSCGetProviderInfo"));
      if (pWSCGetProviderInfo) {
        DWORD categoryInfo;
        size_t categoryInfoSize = sizeof(categoryInfo);
        if (!pWSCGetProviderInfo(&providers[i].ProviderId,
                                 ProviderInfoLspCategories,
                                 (PBYTE)&categoryInfo, &categoryInfoSize, 0,
                                 &err)) {
          str.AppendPrintf("0x%x", categoryInfo);
        }
      }
    }

    str.AppendLiteral(" : ");
    if (providers[i].ProtocolChain.ChainLen <= BASE_PROTOCOL) {
      // If we're dealing with a catalog entry that identifies an individual
      // base or layer provider, log its provider GUID.
      RPC_CSTR provIdStr = nullptr;
      if (UuidToStringA(&providers[i].ProviderId, &provIdStr) == RPC_S_OK) {
        str.Append(reinterpret_cast<char*>(provIdStr));
        RpcStringFreeA(&provIdStr);
      }
    }

    if (i + 1 != n) {
      str.AppendLiteral(" \n ");
    }
  }

  mString = str;
  NS_DispatchToMainThread(NewRunnableMethod(this, &LSPAnnotationGatherer::Annotate));
  return NS_OK;
}
Esempio n. 6
0
BOOL LoadInstallableVDD(VOID)
{
#define ERROR_MEMORYVDD L"Insufficient memory to load installable Virtual Device Drivers."
#define ERROR_REGVDD    L"Virtual Device Driver format in the registry is invalid."
#define ERROR_LOADVDD   L"An installable Virtual Device Driver failed Dll initialization."

    BOOL  Success = TRUE;
    LONG  Error   = 0;
    DWORD Type    = 0;
    DWORD BufSize = 0;

    HKEY    hVDDKey;
    LPCWSTR VDDKeyName   = L"SYSTEM\\CurrentControlSet\\Control\\VirtualDeviceDrivers";
    LPWSTR  VDDValueName = L"VDD";
    LPWSTR  VDDList      = NULL;

    HANDLE hVDD;

    /* Try to open the VDD registry key */
    Error = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
                          VDDKeyName,
                          0,
                          KEY_QUERY_VALUE,
                          &hVDDKey);
    if (Error == ERROR_FILE_NOT_FOUND)
    {
        /* If the key just doesn't exist, don't do anything else */
        return TRUE;
    }
    else if (Error != ERROR_SUCCESS)
    {
        /* The key exists but there was an access error: display an error and quit */
        DisplayMessage(ERROR_REGVDD);
        return FALSE;
    }

    /*
     * Retrieve the size of the VDD registry value
     * and check that it's of REG_MULTI_SZ type.
     */
    Error = RegQueryValueExW(hVDDKey,
                             VDDValueName,
                             NULL,
                             &Type,
                             NULL,
                             &BufSize);
    if (Error == ERROR_FILE_NOT_FOUND)
    {
        /* If the value just doesn't exist, don't do anything else */
        Success = TRUE;
        goto Quit;
    }
    else if (Error != ERROR_SUCCESS || Type != REG_MULTI_SZ)
    {
        /*
         * The value exists but there was an access error or
         * is of the wrong type: display an error and quit.
         */
        DisplayMessage(ERROR_REGVDD);
        Success = FALSE;
        goto Quit;
    }

    /* Allocate the buffer */
    BufSize = (BufSize < 2*sizeof(WCHAR) ? 2*sizeof(WCHAR) : BufSize);
    VDDList = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, BufSize);
    if (VDDList == NULL)
    {
        DisplayMessage(ERROR_MEMORYVDD);
        Success = FALSE;
        goto Quit;
    }

    /* Retrieve the list of VDDs to load */
    if (RegQueryValueExW(hVDDKey,
                         VDDValueName,
                         NULL,
                         NULL,
                         (LPBYTE)VDDList,
                         &BufSize) != ERROR_SUCCESS)
    {
        DisplayMessage(ERROR_REGVDD);
        Success = FALSE;
        goto Quit;
    }

    /* Load the VDDs */
    VDDValueName = VDDList;
    while (*VDDList)
    {
        DPRINT1("Loading VDD '%S'...", VDDList);
        hVDD = LoadLibraryW(VDDList);
        if (hVDD == NULL)
        {
            DbgPrint("Failed\n");
            DisplayMessage(ERROR_LOADVDD);
        }
        else
        {
            DbgPrint("Succeeded\n");
        }
        /* Go to next string */
        VDDList += wcslen(VDDList) + 1;
    }
    VDDList = VDDValueName;

Quit:
    if (VDDList) HeapFree(GetProcessHeap(), 0, VDDList);
    RegCloseKey(hVDDKey);
    return Success;
}
Esempio n. 7
0
static HRESULT register_server(BOOL do_register)
{
    HRESULT hres;
    HMODULE hAdvpack;
    HRESULT (WINAPI *pRegInstall)(HMODULE hm, LPCSTR pszSection, const STRTABLEA* pstTable);
    STRTABLEA strtable;
    STRENTRYA pse[35];
    static CLSID const *clsids[35];
    unsigned int i = 0;

    static const WCHAR wszAdvpack[] = {'a','d','v','p','a','c','k','.','d','l','l',0};

    TRACE("(%x)\n", do_register);

    INF_SET_CLSID(AboutProtocol);
    INF_SET_CLSID(CAnchorBrowsePropertyPage);
    INF_SET_CLSID(CBackgroundPropertyPage);
    INF_SET_CLSID(CCDAnchorPropertyPage);
    INF_SET_CLSID(CCDGenericPropertyPage);
    INF_SET_CLSID(CDocBrowsePropertyPage);
    INF_SET_CLSID(CDwnBindInfo);
    INF_SET_CLSID(CHiFiUses);
    INF_SET_CLSID(CHtmlComponentConstructor);
    INF_SET_CLSID(CImageBrowsePropertyPage);
    INF_SET_CLSID(CInlineStylePropertyPage);
    INF_SET_CLSID(CPeerHandler);
    INF_SET_CLSID(CRecalcEngine);
    INF_SET_CLSID(CSvrOMUses);
    INF_SET_CLSID(CrSource);
    INF_SET_CLSID(ExternalFrameworkSite);
    INF_SET_CLSID(HTADocument);
    INF_SET_CLSID(HTMLDocument);
    INF_SET_CLSID(HTMLLoadOptions);
    INF_SET_CLSID(HTMLPluginDocument);
    INF_SET_CLSID(HTMLPopup);
    INF_SET_CLSID(HTMLPopupDoc);
    INF_SET_CLSID(HTMLServerDoc);
    INF_SET_CLSID(HTMLWindowProxy);
    INF_SET_CLSID(IImageDecodeFilter);
    INF_SET_CLSID(IImgCtx);
    INF_SET_CLSID(IntDitherer);
    INF_SET_CLSID(JSProtocol);
    INF_SET_CLSID(MHTMLDocument);
    INF_SET_CLSID(MailtoProtocol);
    INF_SET_CLSID(ResProtocol);
    INF_SET_CLSID(Scriptlet);
    INF_SET_CLSID(SysimageProtocol);
    INF_SET_CLSID(TridentAPI);
    INF_SET_ID(LIBID_MSHTML);

    for(i=0; i < sizeof(pse)/sizeof(pse[0]); i++) {
        pse[i].pszValue = heap_alloc(39);
        sprintf(pse[i].pszValue, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
                clsids[i]->Data1, clsids[i]->Data2, clsids[i]->Data3, clsids[i]->Data4[0],
                clsids[i]->Data4[1], clsids[i]->Data4[2], clsids[i]->Data4[3], clsids[i]->Data4[4],
                clsids[i]->Data4[5], clsids[i]->Data4[6], clsids[i]->Data4[7]);
    }

    strtable.cEntries = sizeof(pse)/sizeof(pse[0]);
    strtable.pse = pse;

    hAdvpack = LoadLibraryW(wszAdvpack);
    pRegInstall = (void *)GetProcAddress(hAdvpack, "RegInstall");

    hres = pRegInstall(hInst, do_register ? "RegisterDll" : "UnregisterDll", &strtable);

    for(i=0; i < sizeof(pse)/sizeof(pse[0]); i++)
        heap_free(pse[i].pszValue);

    if(FAILED(hres)) {
        ERR("RegInstall failed: %08x\n", hres);
        return hres;
    }

    if(do_register) {
        ITypeLib *typelib;

        static const WCHAR wszMSHTML[] = {'m','s','h','t','m','l','.','t','l','b',0};

        hres = LoadTypeLibEx(wszMSHTML, REGKIND_REGISTER, &typelib);
        if(SUCCEEDED(hres))
            ITypeLib_Release(typelib);
    }else {
        hres = UnRegisterTypeLib(&LIBID_MSHTML, 4, 0, LOCALE_SYSTEM_DEFAULT, SYS_WIN32);
    }

    if(FAILED(hres))
        ERR("typelib registration failed: %08x\n", hres);

    return hres;
}
Esempio n. 8
0
File: enum.c Progetto: jaykrell/j
int wmain()
{
    HMODULE Module;
    HANDLE File = { 0 };
    BYTE* MappedFile = { 0 };
    BYTE* MappedFile_End = { 0 };
    HANDLE FileMapping = { 0 };
    ULARGE_INTEGER FileSize;
    DWORD Error = { 0 };
    IMAGE_NT_HEADERS* NtHeaders = { 0 };
    IMAGE_DOS_HEADER* DosHeader = { 0 };
    size_t OffsetToPE = { 0 };
    IMAGE_RESOURCE_DIRECTORY* TopDirectory = { 0 };
    ULONG ResourcesSize = { 0 };

    Module = LoadLibraryW(L".\\notepad.exe");
    if (!EnumResourceTypesW(Module, EnumTypesProc, 0))
    {
        DWORD Error = GetLastError();
        wprintf(L"EnumResourceTypes failed %x\n", Error);
    }
    FreeLibrary(Module);

    File = CreateFileW(L".\\notepad.exe", GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
    if (INVALID_HANDLE_VALUE == File)
    {
        Error = GetLastError();
        wprintf(L"CreateFile fails with error: %u", Error);
        goto Exit;
    }

    FileSize.LowPart = GetFileSize(File, &FileSize.HighPart);
    if ((FileSize.LowPart == -1) && ((Error = GetLastError()) != 0))
    {
        wprintf(L"GetFileSize failed with error %u\n", Error);
        goto Exit;
    }
    if (FileSize.HighPart != 0)
    {
        wprintf(L"file too large\n");
        goto Exit;
    }
    if (FileSize.QuadPart <= (sizeof(IMAGE_DOS_HEADER) + sizeof(IMAGE_NT_HEADERS)))
    {
        wprintf(L"file too small\n");
        goto Exit;
    }
    
    FileMapping = CreateFileMappingW(File, NULL, PAGE_READONLY, 0, 0, NULL);
    if (FileMapping == NULL)
    {
        Error = GetLastError();
        wprintf(L"CreateFileMapping fails with error: %u", Error);
        goto Exit;
    }

    MappedFile = (BYTE*) MapViewOfFile(FileMapping, FILE_MAP_READ, 0, 0, 0);
    if (MappedFile == NULL)
        goto Exit;

    wprintf(L"MappedFile:%p\n", MappedFile);
    MappedFile_End = (MappedFile + FileSize.QuadPart);
    DosHeader = (IMAGE_DOS_HEADER*) MappedFile;
    if (DosHeader->e_magic != IMAGE_DOS_SIGNATURE)
    {
        wprintf(L"invalid file");
        goto Exit;
    }

    OffsetToPE = DosHeader->e_lfanew;
    if (OffsetToPE >= FileSize.QuadPart)
    {
        wprintf(L"invalid file");
        goto Exit;
    }
    if ((OffsetToPE + sizeof(IMAGE_NT_HEADERS)) >= FileSize.QuadPart)
    {
        wprintf(L"invalid file");
        goto Exit;
    }
    NtHeaders = (IMAGE_NT_HEADERS*) (MappedFile + OffsetToPE);
    if (NtHeaders->Signature != IMAGE_NT_SIGNATURE)
    {
        wprintf(L"invalid file");
        goto Exit;
    }
    if (NtHeaders->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC)
    {
        wprintf(L"invalid file");
        goto Exit;
    }
    if (NtHeaders->OptionalHeader.NumberOfRvaAndSizes < IMAGE_DIRECTORY_ENTRY_RESOURCE)
    {
        wprintf(L"no resources");
        goto Exit;
    }
    if (NtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress == 0)
    {
        wprintf(L"no resources");
        goto Exit;
    }
    if (NtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size == 0)
    {
        wprintf(L"no resources");
        goto Exit;
    }

    TopDirectory = (IMAGE_RESOURCE_DIRECTORY*) ImageDirectoryEntryToData(MappedFile, FALSE, IMAGE_DIRECTORY_ENTRY_RESOURCE, &ResourcesSize);
    if (TopDirectory == NULL)
    {
        wprintf(L"no resources");
        goto Exit;
    }
    DumpResourceDirectory(MappedFile, 0, TopDirectory, TopDirectory);
 
Exit:
    if (MappedFile != NULL)
        UnmapViewOfFile(MappedFile);

    if (FileMapping != NULL)
        CloseHandle(FileMapping);

    if ((File != NULL) && (File != INVALID_HANDLE_VALUE))
        CloseHandle(File);

    return 0;
}
Esempio n. 9
0
static void *_load_jvm_win32(const char **p_java_home)
{
    static char java_home[256] = "";

    wchar_t buf_loc[4096] = L"SOFTWARE\\JavaSoft\\Java Runtime Environment\\";
    wchar_t buf_vers[128];

    char strbuf[256];

    LONG r;
    DWORD lType;
    DWORD dSize = sizeof(buf_vers);
    HKEY hkey;

    r = RegOpenKeyExW(HKEY_LOCAL_MACHINE, buf_loc, 0, KEY_READ, &hkey);
    if (r != ERROR_SUCCESS) {
        BD_DEBUG(DBG_BDJ | DBG_CRIT, "Error opening registry key SOFTWARE\\JavaSoft\\Java Runtime Environment\\");
        return NULL;
    }

    r = RegQueryValueExW(hkey, L"CurrentVersion", NULL, &lType, (LPBYTE)buf_vers, &dSize);
    RegCloseKey(hkey);
    if (r != ERROR_SUCCESS) {
        BD_DEBUG(DBG_BDJ | DBG_CRIT, "CurrentVersion registry value not found");
        return NULL;
    }

    if (debug_mask & DBG_BDJ) {
        WideCharToMultiByte(CP_UTF8, 0, buf_vers, -1, strbuf, sizeof(strbuf), NULL, NULL);
        BD_DEBUG(DBG_BDJ, "JRE version: %s\n", strbuf);
    }
    wcscat(buf_loc, buf_vers);

    dSize = sizeof(buf_loc);
    r = RegOpenKeyExW(HKEY_LOCAL_MACHINE, buf_loc, 0, KEY_READ, &hkey);
    if (r != ERROR_SUCCESS) {
        BD_DEBUG(DBG_BDJ | DBG_CRIT, "Error opening JRE version-specific registry key");
        return NULL;
    }

    r = RegQueryValueExW(hkey, L"JavaHome", NULL, &lType, (LPBYTE)buf_loc, &dSize);

    if (r == ERROR_SUCCESS) {
        /* do not fail even if not found */
        WideCharToMultiByte(CP_UTF8, 0, buf_loc, -1, java_home, sizeof(java_home), NULL, NULL);
        *p_java_home = java_home;
        BD_DEBUG(DBG_BDJ, "JavaHome: %s\n", java_home);
    }

    dSize = sizeof(buf_loc);
    r = RegQueryValueExW(hkey, L"RuntimeLib", NULL, &lType, (LPBYTE)buf_loc, &dSize);
    RegCloseKey(hkey);

    if (r != ERROR_SUCCESS) {
        BD_DEBUG(DBG_BDJ | DBG_CRIT, "RuntimeLib registry value not found");
        return NULL;
    }

    void *result = LoadLibraryW(buf_loc);

    WideCharToMultiByte(CP_UTF8, 0, buf_loc, -1, strbuf, sizeof(strbuf), NULL, NULL);
    if (!result) {
        BD_DEBUG(DBG_BDJ | DBG_CRIT, "can't open library '%s'\n", strbuf);
    } else {
        BD_DEBUG(DBG_BDJ, "Using JRE library %s\n", strbuf);
    }

    return result;
}
Esempio n. 10
0
/*
 * @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;
}
Esempio n. 11
0
static BOOL
ViewTree_LoadTree(HKEY hKey, LPCWSTR pszKeyName, DWORD dwParentID)
{
    DWORD dwIndex;
    WCHAR szKeyName[64], szText[MAX_PATH], *pch;
    DWORD Size, Value;
    PVIEWTREE_ENTRY pAllocated;

    // resize s_ViewTreeEntries
    Size = (s_ViewTreeEntryCount + 1) * sizeof(VIEWTREE_ENTRY);
    pAllocated = (PVIEWTREE_ENTRY)realloc(s_ViewTreeEntries, Size);
    if (pAllocated == NULL)
        return FALSE;   // failure
    else
        s_ViewTreeEntries = pAllocated;

    PVIEWTREE_ENTRY pEntry = &s_ViewTreeEntries[s_ViewTreeEntryCount];

    // dwID, dwParentID, szKeyName
    pEntry->dwID = s_ViewTreeEntryCount;
    pEntry->dwParentID = dwParentID;
    lstrcpynW(pEntry->szKeyName, pszKeyName, _countof(pEntry->szKeyName));

    // Text, ResourceID
    pEntry->szText[0] = 0;
    pEntry->dwResourceID = 0;
    szText[0] = 0;
    Size = sizeof(szText);
    RegQueryValueExW(hKey, L"Text", NULL, NULL, LPBYTE(szText), &Size);
    if (szText[0] == L'@')
    {
        pch = wcsrchr(szText, L',');
        if (pch)
        {
            *pch = 0;
            dwIndex = abs(_wtoi(pch + 1));
            pEntry->dwResourceID = dwIndex;
        }
        HINSTANCE hInst = LoadLibraryW(&szText[1]);
        LoadStringW(hInst, dwIndex, szText, _countof(szText));
        FreeLibrary(hInst);
    }
    else
    {
        pEntry->dwResourceID = DWORD(-1);
    }
    lstrcpynW(pEntry->szText, szText, _countof(pEntry->szText));

    // Type
    szText[0] = 0;
    RegQueryValueExW(hKey, L"Type", NULL, NULL, LPBYTE(szText), &Size);
    if (lstrcmpiW(szText, L"checkbox") == 0)
        pEntry->dwType = AETYPE_CHECKBOX;
    else if (lstrcmpiW(szText, L"radio") == 0)
        pEntry->dwType = AETYPE_RADIO;
    else if (lstrcmpiW(szText, L"group") == 0)
        pEntry->dwType = AETYPE_GROUP;
    else
        return FALSE;   // failure

    pEntry->nIconID = -1;
    if (pEntry->dwType == AETYPE_GROUP)
    {
        // Bitmap (Icon)
        UINT nIconIndex = 0;
        Size = sizeof(szText);
        szText[0] = 0;
        RegQueryValueExW(hKey, L"Bitmap", NULL, NULL, LPBYTE(szText), &Size);

        WCHAR szExpanded[MAX_PATH];
        ExpandEnvironmentStringsW(szText, szExpanded, _countof(szExpanded));
        pch = wcsrchr(szExpanded, L',');
        if (pch)
        {
            *pch = 0;
            nIconIndex = abs(_wtoi(pch + 1));
        }
        pEntry->nIconID = ViewTree_AddIcon(szExpanded, nIconIndex);
    }

    if (pEntry->dwType == AETYPE_GROUP)
    {
        pEntry->hkeyRoot = NULL;
        pEntry->szRegPath[0] = 0;
        pEntry->szValueName[0] = 0;
        pEntry->dwCheckedValue = 0;
        pEntry->bHasUncheckedValue = FALSE;
        pEntry->dwUncheckedValue = 0;
        pEntry->dwDefaultValue = 0;
        pEntry->hItem = NULL;
        pEntry->bGrayed = FALSE;
        pEntry->bChecked = FALSE;
    }
    else
    {
        // HKeyRoot
        HKEY HKeyRoot = HKEY_CURRENT_USER;
        Size = sizeof(HKeyRoot);
        RegQueryValueExW(hKey, L"HKeyRoot", NULL, NULL, LPBYTE(&HKeyRoot), &Size);
        pEntry->hkeyRoot = HKeyRoot;

        // RegPath
        pEntry->szRegPath[0] = 0;
        Size = sizeof(szText);
        RegQueryValueExW(hKey, L"RegPath", NULL, NULL, LPBYTE(szText), &Size);
        lstrcpynW(pEntry->szRegPath, szText, _countof(pEntry->szRegPath));

        // ValueName
        pEntry->szValueName[0] = 0;
        Size = sizeof(szText);
        RegQueryValueExW(hKey, L"ValueName", NULL, NULL, LPBYTE(szText), &Size);
        lstrcpynW(pEntry->szValueName, szText, _countof(pEntry->szValueName));

        // CheckedValue
        Size = sizeof(Value);
        Value = 0x00000001;
        RegQueryValueExW(hKey, L"CheckedValue", NULL, NULL, LPBYTE(&Value), &Size);
        pEntry->dwCheckedValue = Value;

        // UncheckedValue
        Size = sizeof(Value);
        Value = 0x00000000;
        pEntry->bHasUncheckedValue = TRUE;
        if (RegQueryValueExW(hKey, L"UncheckedValue", NULL,
                             NULL, LPBYTE(&Value), &Size) != ERROR_SUCCESS)
        {
            pEntry->bHasUncheckedValue = FALSE;
        }
        pEntry->dwUncheckedValue = Value;

        // DefaultValue
        Size = sizeof(Value);
        Value = 0x00000001;
        RegQueryValueExW(hKey, L"DefaultValue", NULL, NULL, LPBYTE(&Value), &Size);
        pEntry->dwDefaultValue = Value;

        // hItem
        pEntry->hItem = NULL;

        // bGrayed, bChecked
        HKEY hkeyTarget;
        Value = pEntry->dwDefaultValue;
        pEntry->bGrayed = TRUE;
        if (RegOpenKeyExW(HKEY(pEntry->hkeyRoot), pEntry->szRegPath, 0,
                          KEY_READ, &hkeyTarget) == ERROR_SUCCESS)
        {
            Size = sizeof(Value);
            if (RegQueryValueExW(hkeyTarget, pEntry->szValueName, NULL, NULL,
                                 LPBYTE(&Value), &Size) == ERROR_SUCCESS)
            {
                pEntry->bGrayed = FALSE;
            }
            RegCloseKey(hkeyTarget);
        }
        pEntry->bChecked = (Value == pEntry->dwCheckedValue);
    }

    // Grayed (ReactOS extension)
    Size = sizeof(Value);
    Value = FALSE;
    RegQueryValueExW(hKey, L"Grayed", NULL, NULL, LPBYTE(&Value), &Size);
    if (!pEntry->bGrayed)
        pEntry->bGrayed = Value;

    BOOL bIsGroup = (pEntry->dwType == AETYPE_GROUP);
    dwParentID = pEntry->dwID;
    ++s_ViewTreeEntryCount;

    if (!bIsGroup)
        return TRUE;    // success

    // load the children
    dwIndex = 0;
    while (RegEnumKeyW(hKey, dwIndex, szKeyName,
                       _countof(szKeyName)) == ERROR_SUCCESS)
    {
        HKEY hkeyChild;
        if (RegOpenKeyExW(hKey, szKeyName, 0, KEY_READ,
                          &hkeyChild) != ERROR_SUCCESS)
        {
            ++dwIndex;
            continue;   // failure
        }

        ViewTree_LoadTree(hkeyChild, szKeyName, dwParentID);
        RegCloseKey(hkeyChild);

        ++dwIndex;
    }

    return TRUE;    // success
}
Esempio n. 12
0
static bool InitDbgHelp()
{
	static bool doinit = true;
	static bool ret = false;

	if(!doinit)
		return ret;

	doinit = false;

	HMODULE module = NULL;
	
	// can't reliably co-exist with dbghelp already being used in the process
	if(GetModuleHandleA("dbghelp.dll") != NULL)
	{
		ret = false;
		return false;
	}
	else
	{
		wchar_t path[MAX_PATH] = {0};
		GetModuleFileNameW(GetModuleHandleA("renderdoc.dll"), path, MAX_PATH-1);

		wchar_t *slash = wcsrchr(path, '\\');

		if(slash)
		{
			*slash = 0;
		}
		else
		{
			slash = wcsrchr(path, '/');

			if(slash == 0)
			{
				ret = false;
				return false;
			}

			*slash = 0;
		}

#if defined(WIN64)
		wcscat_s(path, L"/pdblocate/x64/dbghelp.dll");
#else
		wcscat_s(path, L"/pdblocate/x86/dbghelp.dll");
#endif

		module = LoadLibraryW(path);
	}

	if(!module)
	{
		RDCWARN("Couldn't open dbghelp.dll");
		ret = false;
		return false;
	}

	dynSymInitializeW = (PSYMINITIALIZEW)GetProcAddress(module, "SymInitializeW");
	dynSymEnumerateModules64W = (PSYMENUMERATEMODULES64W)GetProcAddress(module, "SymEnumerateModulesW64");
	dynSymGetModuleInfo64W = (PSYMGETMODULEINFO64W)GetProcAddress(module, "SymGetModuleInfoW64");
	
	if(!dynSymInitializeW ||
		!dynSymEnumerateModules64W ||
		!dynSymGetModuleInfo64W)
	{
		RDCERR("Couldn't get some dbghelp function");
		ret = false;
		return ret;
	}

	dynSymInitializeW(GetCurrentProcess(), L".", TRUE);
	
	HMODULE hModule = NULL;
	GetModuleHandleEx(
		GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
		(LPCTSTR)&dllLocator,
		&hModule);

	if(hModule != NULL)
	{
		MODULEINFO modinfo = { 0 };

		BOOL result = GetModuleInformation(GetCurrentProcess(), hModule, &modinfo, sizeof(modinfo));

		if(result != FALSE)
		{
			renderdocBase = modinfo.lpBaseOfDll;
			renderdocSize = modinfo.SizeOfImage;
		}
	}
		 
	ret = true;
	return ret;
}
Esempio n. 13
0
void CheckHook()
{
  ShimData *data = NULL;

  HANDLE datahandle = OpenFileMappingA(FILE_MAP_READ, FALSE, GLOBAL_HOOK_DATA_NAME);

  if(datahandle == NULL)
  {
    LOGPRINT(L"renderdocshim: can't open global data\n");
    return;
  }

  data = (ShimData *)MapViewOfFile(datahandle, FILE_MAP_READ, 0, 0, sizeof(ShimData));

  if(data == NULL)
  {
    CloseHandle(datahandle);
    LOGPRINT(L"renderdocshim: can't map global data\n");
    return;
  }

  if(data->pathmatchstring[0] == 0 || data->pathmatchstring[1] == 0 ||
     data->pathmatchstring[2] == 0 || data->pathmatchstring[3] == 0)
  {
    LOGPRINT(L"renderdocshim: invalid pathmatchstring: '");
    LOGPRINT(data->pathmatchstring);
    LOGPRINT(L"'\n");

    UnmapViewOfFile(data);
    CloseHandle(datahandle);
    return;
  }

  // no new[], need to use VirtualAlloc
  const int exepathLen = 1024;
  wchar_t *exepath = (wchar_t *)VirtualAlloc(NULL, exepathLen * sizeof(wchar_t),
                                             MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);

  if(exepath)
  {
    // no memset :).
    for(int i = 0; i < exepathLen; i++)
      exepath[i] = 0;

    GetModuleFileNameW(NULL, exepath, exepathLen - 1);

    // no str*cmp functions
    int find = FindStringOrdinal(FIND_FROMSTART, exepath, -1, data->pathmatchstring, -1, TRUE);

    if(find >= 0)
    {
      LOGPRINT(L"renderdocshim: Hooking into '");
      LOGPRINT(exepath);
      LOGPRINT(L"', based on '");
      LOGPRINT(data->pathmatchstring);
      LOGPRINT(L"'\n");

      HMODULE mod = LoadLibraryW(data->rdocpath);

      if(mod)
      {
        pINTERNAL_SetCaptureOptions setopts =
            (pINTERNAL_SetCaptureOptions)GetProcAddress(mod, "INTERNAL_SetCaptureOptions");
        pINTERNAL_SetLogFile setlogfile =
            (pINTERNAL_SetLogFile)GetProcAddress(mod, "INTERNAL_SetLogFile");
        pRENDERDOC_SetDebugLogFile setdebuglog =
            (pRENDERDOC_SetDebugLogFile)GetProcAddress(mod, "RENDERDOC_SetDebugLogFile");

        if(setopts)
          setopts((const CaptureOptions *)data->opts);

        if(setlogfile && data->logfile[0])
          setlogfile(data->logfile);

        if(setdebuglog && data->debuglog[0])
          setdebuglog(data->debuglog);
      }
    }
    else
    {
      LOGPRINT(L"renderdocshim: NOT Hooking into '");
      LOGPRINT(exepath);
      LOGPRINT(L"', based on '");
      LOGPRINT(data->pathmatchstring);
      LOGPRINT(L"'\n");
    }

    VirtualFree(exepath, 0, MEM_RELEASE);
  }
  else
  {
    LOGPRINT(L"renderdocshim: Failed to allocate exepath\n");
  }

  UnmapViewOfFile(data);
  CloseHandle(datahandle);
}
Esempio n. 14
0
bool
DeviceManagerD3D9::Init()
{
  WNDCLASSW wc;
  HRESULT hr;

  if (!GetClassInfoW(GetModuleHandle(NULL), kClassName, &wc)) {
      ZeroMemory(&wc, sizeof(WNDCLASSW));
      wc.hInstance = GetModuleHandle(NULL);
      wc.lpfnWndProc = ::DefWindowProc;
      wc.lpszClassName = kClassName;
      if (!RegisterClassW(&wc)) {
          NS_WARNING("Failed to register window class for DeviceManager.");
          return false;
      }
  }

  mFocusWnd = ::CreateWindowW(kClassName, L"D3D9Window", WS_OVERLAPPEDWINDOW,
                              CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL,
                              NULL, GetModuleHandle(NULL), NULL);

  if (!mFocusWnd) {
    NS_WARNING("Failed to create DeviceManagerD3D9 Window.");
    return false;
  }

  /* Create an Nv3DVUtils instance */ 
  if (!mNv3DVUtils) { 
    mNv3DVUtils = new Nv3DVUtils(); 
    if (!mNv3DVUtils) { 
      NS_WARNING("Could not create a new instance of Nv3DVUtils.\n"); 
    } 
  } 

  /* Initialize the Nv3DVUtils object */ 
  if (mNv3DVUtils) { 
    mNv3DVUtils->Initialize(); 
  } 

  HMODULE d3d9 = LoadLibraryW(L"d3d9.dll");
  Direct3DCreate9Func d3d9Create = (Direct3DCreate9Func)
    GetProcAddress(d3d9, "Direct3DCreate9");
  Direct3DCreate9ExFunc d3d9CreateEx = (Direct3DCreate9ExFunc)
    GetProcAddress(d3d9, "Direct3DCreate9Ex");
  
#ifdef USE_D3D9EX
  if (d3d9CreateEx) {
    hr = d3d9CreateEx(D3D_SDK_VERSION, getter_AddRefs(mD3D9Ex));
    if (SUCCEEDED(hr)) {
      mD3D9 = mD3D9Ex;
    }
  }
#endif

  if (!mD3D9) {
    if (!d3d9Create) {
      return false;
    }

    mD3D9 = dont_AddRef(d3d9Create(D3D_SDK_VERSION));

    if (!mD3D9) {
      return false;
    }
  }

  D3DADAPTER_IDENTIFIER9 ident;
  hr = mD3D9->GetAdapterIdentifier(D3DADAPTER_DEFAULT, 0, &ident);

  if (FAILED(hr)) {
    return false;
  }

  if (!PL_strncasecmp(ident.Driver, "nvumdshim.dll", PL_strlen(ident.Driver))) {
    // XXX - This is a device using NVidia Optimus. We have no idea how to do
    // interop here so let's fail and use BasicLayers. See bug 597320.
    return false;
  }

  D3DPRESENT_PARAMETERS pp;
  memset(&pp, 0, sizeof(D3DPRESENT_PARAMETERS));

  pp.BackBufferWidth = 1;
  pp.BackBufferHeight = 1;
  pp.BackBufferFormat = D3DFMT_A8R8G8B8;
  pp.SwapEffect = D3DSWAPEFFECT_DISCARD;
  pp.Windowed = TRUE;
  pp.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
  pp.hDeviceWindow = mFocusWnd;

  if (mD3D9Ex) {
    hr = mD3D9Ex->CreateDeviceEx(D3DADAPTER_DEFAULT,
                                 D3DDEVTYPE_HAL,
                                 mFocusWnd,
                                 D3DCREATE_FPU_PRESERVE |
                                 D3DCREATE_MULTITHREADED |
                                 D3DCREATE_MIXED_VERTEXPROCESSING,
                                 &pp,
                                 NULL,
                                 getter_AddRefs(mDeviceEx));
    if (SUCCEEDED(hr)) {
      mDevice = mDeviceEx;
    }

    D3DCAPS9 caps;
    if (mDeviceEx && mDeviceEx->GetDeviceCaps(&caps)) {
      if (LACKS_CAP(caps.Caps2, D3DCAPS2_DYNAMICTEXTURES)) {
        // XXX - Should we actually hit this we'll need a CanvasLayer that
        // supports static D3DPOOL_DEFAULT textures.
        NS_WARNING("D3D9Ex device not used because of lack of support for \
                   dynamic textures. This is unexpected.");
        mDevice = nullptr;
        mDeviceEx = nullptr;
      }
    }
  }
Esempio n. 15
0
Sys::DLLHandle Sys::LoadDLL(const wchar_t* path) 
{
	auto value = LoadLibraryW(path);
	return value;
}
static BOOL __apxLoadJvmDll(LPCWSTR szJvmDllPath)
{
    UINT errMode;
    WCHAR  jreAltPath[SIZ_PATHLEN];
    LPWSTR dllJvmPath = (LPWSTR)szJvmDllPath;
    DYNLOAD_FPTR_DECLARE(SetDllDirectoryW);

    if (!IS_INVALID_HANDLE(_st_sys_jvmDllHandle))
        return TRUE;    /* jvm.dll is already loaded */

    if (dllJvmPath && *dllJvmPath) {
        /* Explicit JVM path.
         * Check if provided argument is valid
         */
        if (GetFileAttributesW(dllJvmPath) == INVALID_FILE_ATTRIBUTES) {
            /* DAEMON-247: Invalid RuntimeLib explicitly specified is error.
             */
            apxLogWrite(APXLOG_MARK_DEBUG "Invalid RuntimeLib specified '%S'", dllJvmPath);
            return FALSE;
        }
    }
    else {
        dllJvmPath = apxGetJavaSoftRuntimeLib(NULL);
        if (!dllJvmPath)
            return FALSE;
    }
    if (GetFileAttributesW(dllJvmPath) == INVALID_FILE_ATTRIBUTES) {
        /* DAEMON-184: RuntimeLib registry key is invalid.
         * Check from Jre JavaHome directly
         */
        LPWSTR szJreHome = apxGetJavaSoftHome(NULL, TRUE);
        apxLogWrite(APXLOG_MARK_DEBUG "Invalid RuntimeLib '%S'", dllJvmPath);
        if (szJreHome) {
            apxLogWrite(APXLOG_MARK_DEBUG "Using Jre JavaHome '%S'", szJreHome);
            lstrlcpyW(jreAltPath, SIZ_PATHLEN, szJreHome);
            lstrlcatW(jreAltPath, SIZ_PATHLEN, L"\\bin\\server\\jvm.dll");
            dllJvmPath = jreAltPath;
        }
    }
    /* Suppress the not found system popup message */
    errMode = SetErrorMode(SEM_FAILCRITICALERRORS);

    apxLogWrite(APXLOG_MARK_DEBUG "loading jvm '%S'", dllJvmPath);
    _st_sys_jvmDllHandle = LoadLibraryExW(dllJvmPath, NULL, 0);
    if (IS_INVALID_HANDLE(_st_sys_jvmDllHandle) &&
        GetFileAttributesW(dllJvmPath) != INVALID_FILE_ATTRIBUTES) {
        /* There is a file but cannot be loaded.
         * Try to load the MSVCRTxx.dll before JVM.dll
         */
        WCHAR  jreBinPath[SIZ_PATHLEN];
        WCHAR  crtBinPath[SIZ_PATHLEN];
        DWORD  i, l = 0;

        lstrlcpyW(jreBinPath, SIZ_PATHLEN, dllJvmPath);
        for (i = lstrlenW(jreBinPath); i > 0, l < 2; i--) {
            if (jreBinPath[i] == L'\\' || jreBinPath[i] == L'/') {
                jreBinPath[i] = L'\0';
                lstrlcpyW(crtBinPath, SIZ_PATHLEN, jreBinPath);
                lstrlcatW(crtBinPath, SIZ_PATHLEN, MSVCRT71_DLLNAME);
                if (GetFileAttributesW(crtBinPath) != INVALID_FILE_ATTRIBUTES) {
                    if (LoadLibraryW(crtBinPath)) {
                        /* Found MSVCRTxx.dll
                         */
                        apxLogWrite(APXLOG_MARK_DEBUG "preloaded '%S'",
                                    crtBinPath);
                        break;
                    }
                }
                l++;
            }
        }
    }
    /* This shuldn't happen, but try to search in %PATH% */
    if (IS_INVALID_HANDLE(_st_sys_jvmDllHandle))
        _st_sys_jvmDllHandle = LoadLibraryExW(dllJvmPath, NULL,
                                              LOAD_WITH_ALTERED_SEARCH_PATH);

    if (IS_INVALID_HANDLE(_st_sys_jvmDllHandle)) {
        WCHAR  jreBinPath[SIZ_PATHLEN];
        DWORD  i, l = 0;

        lstrlcpyW(jreBinPath, SIZ_PATHLEN, dllJvmPath);
        DYNLOAD_FPTR_ADDRESS(SetDllDirectoryW, KERNEL32);
        for (i = lstrlenW(jreBinPath); i > 0, l < 2; i--) {
            if (jreBinPath[i] == L'\\' || jreBinPath[i] == L'/') {
                jreBinPath[i] = L'\0';
                DYNLOAD_CALL(SetDllDirectoryW)(jreBinPath);
                apxLogWrite(APXLOG_MARK_DEBUG "Setting DLL search path to '%S'",
                            jreBinPath);
                l++;
            }
        }
        _st_sys_jvmDllHandle = LoadLibraryExW(dllJvmPath, NULL, 0);
        if (IS_INVALID_HANDLE(_st_sys_jvmDllHandle))
            _st_sys_jvmDllHandle = LoadLibraryExW(dllJvmPath, NULL,
                                                  LOAD_WITH_ALTERED_SEARCH_PATH);
    }
    /* Restore the error mode signalization */
    SetErrorMode(errMode);
    if (IS_INVALID_HANDLE(_st_sys_jvmDllHandle)) {
        apxLogWrite(APXLOG_MARK_SYSERR);
        return FALSE;
    }
    DYNLOAD_FPTR_LOAD(JNI_GetDefaultJavaVMInitArgs, _st_sys_jvmDllHandle);
    DYNLOAD_FPTR_LOAD(JNI_CreateJavaVM,             _st_sys_jvmDllHandle);
    DYNLOAD_FPTR_LOAD(JNI_GetCreatedJavaVMs,        _st_sys_jvmDllHandle);
    DYNLOAD_FPTR_LOAD(JVM_DumpAllStacks,            _st_sys_jvmDllHandle);

    if (!DYNLOAD_FPTR(JNI_GetDefaultJavaVMInitArgs) ||
        !DYNLOAD_FPTR(JNI_CreateJavaVM) ||
        !DYNLOAD_FPTR(JNI_GetCreatedJavaVMs)) {
        apxLogWrite(APXLOG_MARK_SYSERR);
        FreeLibrary(_st_sys_jvmDllHandle);
        _st_sys_jvmDllHandle = NULL;
        return FALSE;
    }

    /* Real voodo ... */
    return TRUE;
}
Esempio n. 17
0
void *S_ntdlopen(const char *path) {
  wchar_t *pathw = Sutf8_to_wide(path);
  void *r = (void *)LoadLibraryW(pathw);
  free(pathw);
  return r;
}
HRESULT vboxDispKmtCallbacksInit(PVBOXDISPKMT_CALLBACKS pCallbacks)
{
    HRESULT hr = S_OK;

    memset(pCallbacks, 0, sizeof (*pCallbacks));

    pCallbacks->hGdi32 = LoadLibraryW(L"gdi32.dll");
    if (pCallbacks->hGdi32 != NULL)
    {
        bool bSupported = true;
        bool bSupportedWin8 = true;
        pCallbacks->pfnD3DKMTOpenAdapterFromHdc = (PFND3DKMT_OPENADAPTERFROMHDC)GetProcAddress(pCallbacks->hGdi32, "D3DKMTOpenAdapterFromHdc");
        Log((__FUNCTION__"pfnD3DKMTOpenAdapterFromHdc = %p\n", pCallbacks->pfnD3DKMTOpenAdapterFromHdc));
        bSupported &= !!(pCallbacks->pfnD3DKMTOpenAdapterFromHdc);

        pCallbacks->pfnD3DKMTOpenAdapterFromGdiDisplayName = (PFND3DKMT_OPENADAPTERFROMGDIDISPLAYNAME)GetProcAddress(pCallbacks->hGdi32, "D3DKMTOpenAdapterFromGdiDisplayName");
        Log((__FUNCTION__": pfnD3DKMTOpenAdapterFromGdiDisplayName = %p\n", pCallbacks->pfnD3DKMTOpenAdapterFromGdiDisplayName));
        bSupported &= !!(pCallbacks->pfnD3DKMTOpenAdapterFromGdiDisplayName);

        pCallbacks->pfnD3DKMTCloseAdapter = (PFND3DKMT_CLOSEADAPTER)GetProcAddress(pCallbacks->hGdi32, "D3DKMTCloseAdapter");
        Log((__FUNCTION__": pfnD3DKMTCloseAdapter = %p\n", pCallbacks->pfnD3DKMTCloseAdapter));
        bSupported &= !!(pCallbacks->pfnD3DKMTCloseAdapter);

        pCallbacks->pfnD3DKMTEscape = (PFND3DKMT_ESCAPE)GetProcAddress(pCallbacks->hGdi32, "D3DKMTEscape");
        Log((__FUNCTION__": pfnD3DKMTEscape = %p\n", pCallbacks->pfnD3DKMTEscape));
        bSupported &= !!(pCallbacks->pfnD3DKMTEscape);

        pCallbacks->pfnD3DKMTCreateDevice = (PFND3DKMT_CREATEDEVICE)GetProcAddress(pCallbacks->hGdi32, "D3DKMTCreateDevice");
        Log((__FUNCTION__": pfnD3DKMTCreateDevice = %p\n", pCallbacks->pfnD3DKMTCreateDevice));
        bSupported &= !!(pCallbacks->pfnD3DKMTCreateDevice);

        pCallbacks->pfnD3DKMTDestroyDevice = (PFND3DKMT_DESTROYDEVICE)GetProcAddress(pCallbacks->hGdi32, "D3DKMTDestroyDevice");
        Log((__FUNCTION__": pfnD3DKMTDestroyDevice = %p\n", pCallbacks->pfnD3DKMTDestroyDevice));
        bSupported &= !!(pCallbacks->pfnD3DKMTDestroyDevice);

        pCallbacks->pfnD3DKMTCreateContext = (PFND3DKMT_CREATECONTEXT)GetProcAddress(pCallbacks->hGdi32, "D3DKMTCreateContext");
        Log((__FUNCTION__": pfnD3DKMTCreateContext = %p\n", pCallbacks->pfnD3DKMTCreateContext));
        bSupported &= !!(pCallbacks->pfnD3DKMTCreateContext);

        pCallbacks->pfnD3DKMTDestroyContext = (PFND3DKMT_DESTROYCONTEXT)GetProcAddress(pCallbacks->hGdi32, "D3DKMTDestroyContext");
        Log((__FUNCTION__": pfnD3DKMTDestroyContext = %p\n", pCallbacks->pfnD3DKMTDestroyContext));
        bSupported &= !!(pCallbacks->pfnD3DKMTDestroyContext);

        pCallbacks->pfnD3DKMTRender = (PFND3DKMT_RENDER)GetProcAddress(pCallbacks->hGdi32, "D3DKMTRender");
        Log((__FUNCTION__": pfnD3DKMTRender = %p\n", pCallbacks->pfnD3DKMTRender));
        bSupported &= !!(pCallbacks->pfnD3DKMTRender);

        pCallbacks->pfnD3DKMTCreateAllocation = (PFND3DKMT_CREATEALLOCATION)GetProcAddress(pCallbacks->hGdi32, "D3DKMTCreateAllocation");
        Log((__FUNCTION__": pfnD3DKMTCreateAllocation = %p\n", pCallbacks->pfnD3DKMTCreateAllocation));
        bSupported &= !!(pCallbacks->pfnD3DKMTCreateAllocation);

        pCallbacks->pfnD3DKMTDestroyAllocation = (PFND3DKMT_DESTROYALLOCATION)GetProcAddress(pCallbacks->hGdi32, "D3DKMTDestroyAllocation");
        Log((__FUNCTION__": pfnD3DKMTDestroyAllocation = %p\n", pCallbacks->pfnD3DKMTDestroyAllocation));
        bSupported &= !!(pCallbacks->pfnD3DKMTDestroyAllocation);

        pCallbacks->pfnD3DKMTLock = (PFND3DKMT_LOCK)GetProcAddress(pCallbacks->hGdi32, "D3DKMTLock");
        Log((__FUNCTION__": pfnD3DKMTLock = %p\n", pCallbacks->pfnD3DKMTLock));
        bSupported &= !!(pCallbacks->pfnD3DKMTLock);

        pCallbacks->pfnD3DKMTUnlock = (PFND3DKMT_UNLOCK)GetProcAddress(pCallbacks->hGdi32, "D3DKMTUnlock");
        Log((__FUNCTION__": pfnD3DKMTUnlock = %p\n", pCallbacks->pfnD3DKMTUnlock));
        bSupported &= !!(pCallbacks->pfnD3DKMTUnlock);

        pCallbacks->pfnD3DKMTEnumAdapters = (PFND3DKMT_ENUMADAPTERS)GetProcAddress(pCallbacks->hGdi32, "D3DKMTEnumAdapters");
        Log((__FUNCTION__": pfnD3DKMTEnumAdapters = %p\n", pCallbacks->pfnD3DKMTEnumAdapters));
        /* this present starting win8 release preview only, so keep going if it is not available,
         * i.e. do not clear the bSupported on its absence */
        bSupportedWin8 &= !!(pCallbacks->pfnD3DKMTEnumAdapters);
#ifdef DEBUG_misha
        /* just a debug assertion to test it on win8 */
        Assert(pCallbacks->pfnD3DKMTEnumAdapters);
#endif

        pCallbacks->pfnD3DKMTOpenAdapterFromLuid = (PFND3DKMT_OPENADAPTERFROMLUID)GetProcAddress(pCallbacks->hGdi32, "D3DKMTOpenAdapterFromLuid");
        Log((__FUNCTION__": pfnD3DKMTOpenAdapterFromLuid = %p\n", pCallbacks->pfnD3DKMTOpenAdapterFromLuid));
        /* this present starting win8 release preview only, so keep going if it is not available,
         * i.e. do not clear the bSupported on its absence */
        bSupportedWin8 &= !!(pCallbacks->pfnD3DKMTOpenAdapterFromLuid);
#ifdef DEBUG_misha
        /* just a debug assertion to test it on win8 */
        Assert(pCallbacks->pfnD3DKMTOpenAdapterFromLuid);
        Assert(bSupportedWin8);
#endif

        /*Assert(bSupported);*/
        if (bSupported)
        {
            if (bSupportedWin8)
                pCallbacks->enmVersion = VBOXDISPKMT_CALLBACKS_VERSION_WIN8;
            else
                pCallbacks->enmVersion = VBOXDISPKMT_CALLBACKS_VERSION_VISTA_WIN7;
            return S_OK;
        }
        else
        {
            Log((__FUNCTION__": one of pfnD3DKMT function pointers failed to initialize\n"));
            hr = E_NOINTERFACE;
        }

        FreeLibrary(pCallbacks->hGdi32);
    }
    else
    {
        DWORD winEr = GetLastError();
        hr = HRESULT_FROM_WIN32(winEr);
        Assert(0);
        Assert(hr != S_OK);
        Assert(hr != S_FALSE);
        if (hr == S_OK || hr == S_FALSE)
            hr = E_FAIL;
    }

    return hr;
}
Esempio n. 19
0
BOOL CYYManager::InitFactory()
{
	WCHAR wzSelfPath[MAX_PATH]; 
	memset( wzSelfPath, 0, sizeof(wzSelfPath) );
	GetModuleFileNameW( NULL, wzSelfPath, sizeof(wzSelfPath) );
	LPWSTR lpInsertPos = wcsrchr( wzSelfPath, L'\\' );
	*lpInsertPos = L'\0';
	lstrcatW( wzSelfPath, L"\\pipFactory.dll" );
	m_hFactory = LoadLibraryW( wzSelfPath );
	if( m_hFactory == NULL ) return FALSE;

	m_pfnInitInterface = (PFN_INITYYINTERFACE)GetProcAddress( m_hFactory, "YYPIP_InitInterface" );
	if( m_pfnInitInterface == NULL ) return FALSE;

	m_pfnGetInterface = (PFN_GETYYINTERFACE)GetProcAddress( m_hFactory, "YYPIP_GetInterface" );
	if( m_pfnGetInterface == NULL ) return FALSE;

	//call factory init func
	if( m_pfnInitInterface() == -1 ) return FALSE;

	/////////////////////////////////////////////////////////////////////////
	//all game must be call this func to show yy window
	m_pfnRunService = (PFN_RUNSERVICE)m_pfnGetInterface( "YYPIP_RunService" );
	if( m_pfnRunService == NULL ) return FALSE;

	m_pfnLoadInGame = (PFN_LOADINGAME)m_pfnGetInterface( "YYPIP_LoadInGame" );
	if( m_pfnLoadInGame == NULL ) return FALSE;

	m_pfnFreeGame = (PFN_FREEINGAME)m_pfnGetInterface( "YYPIP_FreeInGame" );
	if( m_pfnFreeGame == NULL ) return FALSE;

	m_pfnCheckClient = (PFN_CHECKCLIENT)m_pfnGetInterface( "YYPIP_CheckYYClient" );
	if( m_pfnCheckClient == NULL ) return FALSE;

	m_pfnIsPipSuccess = (PFN_ISPIPSUCCESS)m_pfnGetInterface( "YYPIP_IsPipRunSuccess" );
	if( m_pfnIsPipSuccess == NULL ) return FALSE;

	/////////////////////////////////////////////////////////////////////////
	//sometimes call this func to show yy window
	m_pfnMouseInput = (PFN_MOUSEINPUT)m_pfnGetInterface( "YYPIP_MouseInput" );
	if( m_pfnMouseInput == NULL ) return FALSE;

	m_pfnSetMainWnd = (PFN_SETMAINWND)m_pfnGetInterface( "YYPIP_SetMainWnd" );
	if( m_pfnSetMainWnd == NULL ) return FALSE;

	m_pfnCreateUI = (PFN_CREATEUI)m_pfnGetInterface( "YYPIP_CreateUI" );
	if( m_pfnCreateUI == NULL ) return FALSE;

	m_pfnDestoryUI = (PFN_DESTORYUI)m_pfnGetInterface( "YYPIP_DestoryUI" );
	if( m_pfnDestoryUI == NULL ) return FALSE;

	m_pfnRenderGUI = (PFN_RENDERGUI)m_pfnGetInterface( "YYPIP_RenderGUI" );
	if( m_pfnRenderGUI == NULL ) return FALSE;

	m_pfnGameWndMsg = (PFN_GAMEWNDMSG)m_pfnGetInterface( "YYPIP_GameWndMessage" );
	if( m_pfnGameWndMsg == NULL ) return FALSE;


	/////////////////////////////////////////////////////////////////////////
	//game used yy voice channel
	m_pfnJoinChannel = (PFN_JOINCHANNEL)m_pfnGetInterface( "YYPIP_JoinChannel" );
	if( m_pfnJoinChannel == NULL ) return FALSE;

	m_pfnSetTeamAdmin = (PFN_SETTEAMADMIN)m_pfnGetInterface( "YYPIP_SetTeamAdmin" );
	if( m_pfnSetTeamAdmin == NULL ) return FALSE;

	m_pfnSetUserName = (PFN_SETUSERNAME)m_pfnGetInterface( "YYPIP_SetUserName" );
	if( m_pfnSetUserName == NULL ) return FALSE;

	m_pfnJoinTeam = (PFN_JOINTEAM)m_pfnGetInterface( "YYPIP_JoinTeam" );
	if( m_pfnJoinTeam == NULL ) return FALSE;

	m_pfnSetTeamDevice = (PFN_SETTEAMDEVICE)m_pfnGetInterface( "YYPIP_SetTeamDevice" );
	if( m_pfnSetTeamDevice == NULL ) return FALSE;

	m_pfnSetTeamVoice = (PFN_SETTEAMVOICE)m_pfnGetInterface( "YYPIP_SetTeamVoice" );
	if( m_pfnSetTeamVoice == NULL ) return FALSE;

	m_pfnLockTeamVoice = (PFN_LOCKTEAMVOICE)m_pfnGetInterface( "YYPIP_LockTeamVoice" );
	if( m_pfnLockTeamVoice == NULL ) return FALSE;


	/////////////////////////////////////////////////////////////////////////
	//game to channel yy voice window
	m_pfnGetPipShow = (PFN_GETPIPSHOW)m_pfnGetInterface( "YYPIP_GetPipShow" );
	if( m_pfnGetPipShow == NULL ) return FALSE;

	m_pfnSetPipShow = (PFN_SETPIPSHOW)m_pfnGetInterface( "YYPIP_SetPipShow" );
	if( m_pfnSetPipShow == NULL ) return FALSE;

	m_pfnSetMsgShow = (PFN_SETMSGSHOW)m_pfnGetInterface( "YYPIP_SetMsgShow" );
	if( m_pfnSetMsgShow == NULL ) return FALSE;

	m_pfnMouseShow = (PFN_SETMOUSESHOW)m_pfnGetInterface( "YYPIP_SetMouseShow" );
	if( m_pfnMouseShow == NULL ) return FALSE;

	m_pfnLockWnd = (PFN_LOCKWINDOW)m_pfnGetInterface( "YYPIP_LockWindow" );
	if( m_pfnLockWnd == NULL ) return FALSE;

	m_pfnMoveWnd = (PFN_MOVEWINDOW)m_pfnGetInterface( "YYPIP_MoveWindow" );
	if( m_pfnMoveWnd == NULL ) return FALSE;


	/////////////////////////////////////////////////////////////////////////
	//game to used open id func 
	m_pfnShowOpid = (PFN_SHOWOPENID)m_pfnGetInterface( "YYPIP_ShowOpenId" );
	if( m_pfnShowOpid == NULL ) return FALSE;

	m_pfnLoginSucceed = (PFN_LOGINSUCCEED)m_pfnGetInterface( "YYPIP_LoginSucceed" );
	if( m_pfnLoginSucceed == NULL ) return FALSE;

	m_pfnLoginFailure = (PFN_LOGINFAILURE)m_pfnGetInterface( "YYPIP_LoginFailure" );
	if( m_pfnLoginFailure == NULL ) return FALSE;

	m_pfnSetLoginKey = (PFN_SETLOGINKEY)m_pfnGetInterface( "YYPIP_SetLoginKey" );
	if( m_pfnSetLoginKey == NULL ) return FALSE;

	m_pfnSetCallBack = (PFN_SETCALLBACK)m_pfnGetInterface( "YYPIP_SetCallBackFunc" );
	if( m_pfnSetCallBack == NULL ) return FALSE;

	return TRUE;
}
HRESULT VBoxDispD3DOpen(VBOXDISPD3D *pD3D)
{
#ifdef VBOX_WDDM_WOW64
    pD3D->hD3DLib = LoadLibraryW(L"VBoxD3D9wddm-x86.dll");
#else
    pD3D->hD3DLib = LoadLibraryW(L"VBoxD3D9wddm.dll");
#endif
    if (!pD3D->hD3DLib)
    {
        DWORD winErr = GetLastError();
        WARN((__FUNCTION__": LoadLibraryW failed, winErr = (%d)", winErr));
        return E_FAIL;
    }

    do
    {
        pD3D->pfnDirect3DCreate9Ex = (PFNVBOXDISPD3DCREATE9EX)GetProcAddress(pD3D->hD3DLib, "Direct3DCreate9Ex");
        if (!pD3D->pfnDirect3DCreate9Ex)
        {
            WARN(("no Direct3DCreate9Ex"));
            break;
        }

        pD3D->pfnVBoxWineExD3DDev9CreateTexture = (PFNVBOXWINEEXD3DDEV9_CREATETEXTURE)GetProcAddress(pD3D->hD3DLib, "VBoxWineExD3DDev9CreateTexture");
        if (!pD3D->pfnVBoxWineExD3DDev9CreateTexture)
        {
            WARN(("no VBoxWineExD3DDev9CreateTexture"));
            break;
        }

        pD3D->pfnVBoxWineExD3DDev9CreateCubeTexture = (PFNVBOXWINEEXD3DDEV9_CREATECUBETEXTURE)GetProcAddress(pD3D->hD3DLib, "VBoxWineExD3DDev9CreateCubeTexture");
        if (!pD3D->pfnVBoxWineExD3DDev9CreateCubeTexture)
        {
            WARN(("no VBoxWineExD3DDev9CreateCubeTexture"));
            break;
        }

        pD3D->pfnVBoxWineExD3DDev9CreateVolumeTexture = (PFNVBOXWINEEXD3DDEV9_CREATEVOLUMETEXTURE)GetProcAddress(pD3D->hD3DLib, "VBoxWineExD3DDev9CreateVolumeTexture");
        if (!pD3D->pfnVBoxWineExD3DDev9CreateVolumeTexture)
        {
            WARN(("no VBoxWineExD3DDev9CreateVolumeTexture"));
            break;
        }

        pD3D->pfnVBoxWineExD3DDev9Flush = (PFNVBOXWINEEXD3DDEV9_FLUSH)GetProcAddress(pD3D->hD3DLib, "VBoxWineExD3DDev9Flush");
        if (!pD3D->pfnVBoxWineExD3DDev9Flush)
        {
            WARN(("no VBoxWineExD3DDev9Flush"));
            break;
        }

        pD3D->pfnVBoxWineExD3DDev9FlushToHost = (PFNVBOXWINEEXD3DDEV9_FLUSHTOHOST)GetProcAddress(pD3D->hD3DLib, "VBoxWineExD3DDev9FlushToHost");
        if (!pD3D->pfnVBoxWineExD3DDev9FlushToHost)
        {
            WARN(("no VBoxWineExD3DDev9FlushToHost"));
            break;
        }

        pD3D->pfnVBoxWineExD3DDev9Finish = (PFNVBOXWINEEXD3DDEV9_FINISH)GetProcAddress(pD3D->hD3DLib, "VBoxWineExD3DDev9Finish");
        if (!pD3D->pfnVBoxWineExD3DDev9Finish)
        {
            WARN(("no VBoxWineExD3DDev9Finish"));
            break;
        }

        pD3D->pfnVBoxWineExD3DDev9VolBlt = (PFNVBOXWINEEXD3DDEV9_VOLBLT)GetProcAddress(pD3D->hD3DLib, "VBoxWineExD3DDev9VolBlt");
        if (!pD3D->pfnVBoxWineExD3DDev9VolBlt)
        {
            WARN(("no VBoxWineExD3DDev9VolBlt"));
            break;
        }

        pD3D->pfnVBoxWineExD3DDev9VolTexBlt = (PFNVBOXWINEEXD3DDEV9_VOLTEXBLT)GetProcAddress(pD3D->hD3DLib, "VBoxWineExD3DDev9VolTexBlt");
        if (!pD3D->pfnVBoxWineExD3DDev9VolTexBlt)
        {
            WARN(("no VBoxWineExD3DDev9VolTexBlt"));
            break;
        }

        pD3D->pfnVBoxWineExD3DDev9Update = (PFNVBOXWINEEXD3DDEV9_UPDATE)GetProcAddress(pD3D->hD3DLib, "VBoxWineExD3DDev9Update");
        if (!pD3D->pfnVBoxWineExD3DDev9Update)
        {
            WARN(("no VBoxWineExD3DDev9Update"));
            break;
        }

        pD3D->pfnVBoxWineExD3DDev9Term = (PFNVBOXWINEEXD3DDEV9_TERM)GetProcAddress(pD3D->hD3DLib, "VBoxWineExD3DDev9Term");
        if (!pD3D->pfnVBoxWineExD3DDev9Term)
        {
            WARN(("no VBoxWineExD3DDev9Term"));
            break;
        }

        pD3D->pfnVBoxWineExD3DRc9SetShRcState = (PFNVBOXWINEEXD3DRC9_SETSHRCSTATE)GetProcAddress(pD3D->hD3DLib, "VBoxWineExD3DRc9SetShRcState");
        if (!pD3D->pfnVBoxWineExD3DRc9SetShRcState)
        {
            WARN(("no VBoxWineExD3DRc9SetShRcState"));
            break;
        }

        pD3D->pfnVBoxWineExD3DSwapchain9Present = (PFNVBOXWINEEXD3DSWAPCHAIN9_PRESENT)GetProcAddress(pD3D->hD3DLib, "VBoxWineExD3DSwapchain9Present");
        if (!pD3D->pfnVBoxWineExD3DSwapchain9Present)
        {
            WARN(("no VBoxWineExD3DSwapchain9Present"));
            break;
        }

        return S_OK;

    } while (0);

    VBoxDispD3DClose(pD3D);

    return E_FAIL;
}
Esempio n. 21
0
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;
    }
}
Esempio n. 22
0
//
// Function: LoadProviderPath
//
// Description:
//      This function retrieves the provider's DLL path, expands any environment
//      variables, loads the DLL, and retrieves it's WSPStartup function.
//
BOOL
LoadProviderPath(
    PROVIDER    *loadProvider,
    int         *lpErrno
    )
{
    int     rc;

    *lpErrno = 0;

    // Retrieve the provider path of the lower layer
    loadProvider->ProviderPathLen = MAX_PATH - 1;
    rc = WSCGetProviderPath(
           &loadProvider->NextProvider.ProviderId,
            loadProvider->ProviderPathW,
           &loadProvider->ProviderPathLen,
            lpErrno
            );
    if ( SOCKET_ERROR == rc )
    {
        dbgprint("LoadProviderPath: WSCGetProviderPath failed: %d", *lpErrno );
        goto cleanup;
    }

    rc = ExpandEnvironmentStringsW(
            loadProvider->ProviderPathW,
            loadProvider->LibraryPathW,
            MAX_PATH - 1
            );
    if ( ( 0 != rc ) && ( MAX_PATH-1 >= rc ) )
    {
        loadProvider->Module = LoadLibraryW( loadProvider->LibraryPathW );
        if ( NULL == loadProvider->Module )
        {
            dbgprint("LoadProviderPath: LoadLibraryW failed: %d", GetLastError() );
            goto cleanup;
        }
    }
    else if ( 0 == rc )
    {
        char    ProviderPathA[ MAX_PATH ],
                LibraryPathA[ MAX_PATH ];

        // No UNICODE so we must be on Win9x
        rc = WideCharToMultiByte( CP_ACP, 0,
                loadProvider->ProviderPathW,
                loadProvider->ProviderPathLen,
                ProviderPathA,
                MAX_PATH,
                NULL,
                NULL
                );
        if ( 0 == rc )
        {
            dbgprint("LoadProviderPath: WideCharToMultiByte failed: %d", GetLastError() );
            goto cleanup;
        }

        rc = ExpandEnvironmentStringsA(
                ProviderPathA,
                LibraryPathA,
                MAX_PATH - 1
                );
        if ( ( 0 == rc ) || ( MAX_PATH - 1 < rc ) )
        {
            dbgprint("LoadProviderPath: ExpandEnvironmentStringsA failed: %d", GetLastError() );
            goto cleanup;
        }

        loadProvider->Module = LoadLibraryA( LibraryPathA );
        if ( NULL == loadProvider->Module )
        {
            dbgprint("LoadProviderPath: LoadLibraryA failed: %d", GetLastError() );
            goto cleanup;
        }
    }

    // Retrieve the next provider's WSPSTartup function
    loadProvider->fnWSPStartup = (LPWSPSTARTUP) GetProcAddress(
            loadProvider->Module,
            "WSPStartup"
            );
    if ( NULL == loadProvider->fnWSPStartup )
    {
        dbgprint("LoadProviderPath: GetProcAddress failed: %d", GetLastError() );
        goto cleanup;
    }

    return TRUE;

cleanup:

    if ( *lpErrno == 0 )
        *lpErrno = GetLastError();
    return FALSE;
}
HRESULT GetVideoMemoryViaWMI( WCHAR* strInputDeviceID, DWORD* pdwAdapterRam )
{
	HRESULT hr;
	bool bGotMemory = false;
	HRESULT hrCoInitialize = S_OK;
	IWbemLocator* pIWbemLocator = nullptr;
	IWbemServices* pIWbemServices = nullptr;
	BSTR pNamespace = nullptr;

	*pdwAdapterRam = 0;
	hrCoInitialize = CoInitialize( 0 );

	hr = CoCreateInstance( CLSID_WbemLocator,
						   nullptr,
						   CLSCTX_INPROC_SERVER,
						   IID_IWbemLocator,
						   ( LPVOID* )&pIWbemLocator );
#ifdef PRINTF_DEBUGGING
	if( FAILED( hr ) ) wprintf( L"WMI: CoCreateInstance failed: 0x%0.8x\n", hr );
#endif

	if( SUCCEEDED( hr ) && pIWbemLocator )
	{
		// Using the locator, connect to WMI in the given namespace.
		pNamespace = SysAllocString( L"\\\\.\\root\\cimv2" );

		hr = pIWbemLocator->ConnectServer( pNamespace, nullptr, nullptr, 0L,
										   0L, nullptr, nullptr, &pIWbemServices );
#ifdef PRINTF_DEBUGGING
		if( FAILED( hr ) ) wprintf( L"WMI: pIWbemLocator->ConnectServer failed: 0x%0.8x\n", hr );
#endif
		if( SUCCEEDED( hr ) && pIWbemServices != 0 )
		{
			HINSTANCE hinstOle32 = nullptr;

			hinstOle32 = LoadLibraryW( L"ole32.dll" );
			if( hinstOle32 )
			{
				PfnCoSetProxyBlanket pfnCoSetProxyBlanket = nullptr;

				pfnCoSetProxyBlanket = ( PfnCoSetProxyBlanket )GetProcAddress( hinstOle32, "CoSetProxyBlanket" );
				if( pfnCoSetProxyBlanket != 0 )
				{
					// Switch security level to IMPERSONATE.
					pfnCoSetProxyBlanket( pIWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, nullptr,
										  RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, 0 );
				}

				FreeLibrary( hinstOle32 );
			}

			IEnumWbemClassObject* pEnumVideoControllers = nullptr;
			BSTR pClassName = nullptr;

			pClassName = SysAllocString( L"Win32_VideoController" );

			hr = pIWbemServices->CreateInstanceEnum( pClassName, 0,
													 nullptr, &pEnumVideoControllers );
#ifdef PRINTF_DEBUGGING
			if( FAILED( hr ) ) wprintf( L"WMI: pIWbemServices->CreateInstanceEnum failed: 0x%0.8x\n", hr );
#endif

			if( SUCCEEDED( hr ) && pEnumVideoControllers )
			{
				IWbemClassObject* pVideoControllers[10] = {0};
				DWORD uReturned = 0;
				BSTR pPropName = nullptr;

				// Get the first one in the list
				pEnumVideoControllers->Reset();
				hr = pEnumVideoControllers->Next( 5000,             // timeout in 5 seconds
												  10,                  // return the first 10
												  pVideoControllers,
												  &uReturned );
#ifdef PRINTF_DEBUGGING
				if( FAILED( hr ) ) wprintf( L"WMI: pEnumVideoControllers->Next failed: 0x%0.8x\n", hr );
				if( uReturned == 0 ) wprintf( L"WMI: pEnumVideoControllers uReturned == 0\n" );
#endif

				VARIANT var;
				if( SUCCEEDED( hr ) )
				{
					bool bFound = false;
					for( UINT iController = 0; iController < uReturned; iController++ )
					{
						if ( !pVideoControllers[iController] )
							continue;

						pPropName = SysAllocString( L"PNPDeviceID" );
						hr = pVideoControllers[iController]->Get( pPropName, 0L, &var, nullptr, nullptr );
#ifdef PRINTF_DEBUGGING
						if( FAILED( hr ) )
							wprintf( L"WMI: pVideoControllers[iController]->Get PNPDeviceID failed: 0x%0.8x\n", hr );
#endif
						if( SUCCEEDED( hr ) )
						{
							if( wcsstr( var.bstrVal, strInputDeviceID ) != 0 )
								bFound = true;
						}
						VariantClear( &var );
						if( pPropName ) SysFreeString( pPropName );

						if( bFound )
						{
							pPropName = SysAllocString( L"AdapterRAM" );
							hr = pVideoControllers[iController]->Get( pPropName, 0L, &var, nullptr, nullptr );
#ifdef PRINTF_DEBUGGING
							if( FAILED( hr ) )
								wprintf( L"WMI: pVideoControllers[iController]->Get AdapterRAM failed: 0x%0.8x\n",
										 hr );
#endif
							if( SUCCEEDED( hr ) )
							{
								bGotMemory = true;
								*pdwAdapterRam = var.ulVal;
							}
							VariantClear( &var );
							if( pPropName ) SysFreeString( pPropName );
							break;
						}
						SAFE_RELEASE( pVideoControllers[iController] );
					}
				}
				SAFE_RELEASE(pEnumVideoControllers);
			}

			if( pClassName )
				SysFreeString( pClassName );
		}

		if( pNamespace )
			SysFreeString( pNamespace );
		SAFE_RELEASE( pIWbemServices );
	}

	SAFE_RELEASE( pIWbemLocator );

	if( SUCCEEDED( hrCoInitialize ) )
		CoUninitialize();

	if( bGotMemory )
		return S_OK;
	else
		return E_FAIL;
}
Esempio n. 24
0
File: Main.cpp Progetto: 9tong/YDWE
/** \brief 主函数
 *
 * 主启动函数。负责调用启动DLL的启动函数
 */
INT WINAPI WinMain(HINSTANCE currentInstance, HINSTANCE previousInstance, LPSTR pCommandLine, INT showType)
{
	INT exitCode = -1;

	/* 获得几个要加到Path的文件夹路径 */
	wchar_t binaryPath[MAX_PATH];
	wchar_t pathEnvironmentVariable[32767 /* http://msdn.microsoft.com/en-us/library/windows/desktop/ms683188.aspx */ ];
	std::wstring newPathEnvironmentVariable;

	// 当前exe路径
	GetModuleFileNameW(currentInstance, binaryPath, sizeof(binaryPath) / sizeof(binaryPath[0]));
	PathRemoveBlanksW(binaryPath);
	PathUnquoteSpacesW(binaryPath);
	PathRemoveBackslashW(binaryPath);

	// bin文件夹路径
	PathRemoveFileSpecW(binaryPath);
	PathAppendW(binaryPath, L"bin");

	// 拷贝到待增加路径字符串
	newPathEnvironmentVariable.append(binaryPath);

	// plugin文件夹路径
	PathRemoveFileSpecW(binaryPath);
	PathAppendW(binaryPath, L"plugin");

	// 拷贝到待增加路径字符串
	newPathEnvironmentVariable.append(L";");
	newPathEnvironmentVariable.append(binaryPath);

	/* 设置PATH环境变量 */
	// 获取环境变量
	pathEnvironmentVariable[0] = L'\0';
	DWORD length = GetEnvironmentVariableW(L"PATH", pathEnvironmentVariable, sizeof(pathEnvironmentVariable) / sizeof(pathEnvironmentVariable[0]));

	// 组合新环境变量
	if (length > 0)
		newPathEnvironmentVariable.append(L";");

	newPathEnvironmentVariable.append(pathEnvironmentVariable);

	// 拷贝回去
	wcscpy_s(pathEnvironmentVariable, newPathEnvironmentVariable.c_str());

	// 设置环境变量
	SetEnvironmentVariableW(L"PATH", pathEnvironmentVariable);

	/* 载入CRT的Dll,防止Dll冲突 */

	// 再次得到bin文件夹路径
	PathRemoveFileSpecW(binaryPath);
	PathAppendW(binaryPath, L"bin");

#ifdef _DEBUG
	PathAppendW(binaryPath, L"msvcr100d.dll");
	HMODULE msvcr100 = LoadLibraryW(binaryPath);

	PathRemoveFileSpecW(binaryPath);
	PathAppendW(binaryPath, L"msvcp100d.dll");
	HMODULE msvcp100 = LoadLibraryW(binaryPath);
#else
	PathAppendW(binaryPath, L"msvcr100.dll");
	HMODULE msvcr100 = LoadLibraryW(binaryPath);

	PathRemoveFileSpecW(binaryPath);
	PathAppendW(binaryPath, L"msvcp100.dll");
	HMODULE msvcp100 = LoadLibraryW(binaryPath);
#endif

	// 尝试载入YDWEStartup.dll
	HMODULE startupModule = LoadLibraryW(L"YDWEStartup.dll");
	if (startupModule)
	{
		TPFStartup pfStartup = (TPFStartup)GetProcAddress(startupModule, "YDWEStartup");
		if (pfStartup)
			exitCode = pfStartup(currentInstance, previousInstance, pCommandLine, showType);

		FreeLibrary(startupModule);
	}

	if (msvcp100)
		FreeLibrary(msvcp100);
	if (msvcr100)
		FreeLibrary(msvcr100);

	return exitCode;
}
Esempio n. 25
0
shared_ptr<rett> createAny(const boost::filesystem::path& libpath, const std::string& methodName)
{
	typedef void(*TGetAIFun)(shared_ptr<rett>&); 
	typedef void(*TGetNameFun)(char*); 

	char temp[150];

	TGetAIFun getAI = nullptr;
	TGetNameFun getName = nullptr;

#ifdef VCMI_ANDROID
	// this is awful but it seems using shared libraries on some devices is even worse
	const std::string filename = libpath.filename().string();
	if (filename == "libVCAI.so")
	{
		getName = (TGetNameFun)VCAI_GetAiName;
		getAI = (TGetAIFun)VCAI_GetNewAI;
	}
	else if (filename == "libStupidAI.so")
	{
		getName = (TGetNameFun)StupidAI_GetAiName;
		getAI = (TGetAIFun)StupidAI_GetNewBattleAI;
	}
	else if (filename == "libBattleAI.so")
	{
		getName = (TGetNameFun)BattleAI_GetAiName;
		getAI = (TGetAIFun)BattleAI_GetNewBattleAI;
	}
	else
		throw std::runtime_error("Don't know what to do with " + libpath.string() + " and method " + methodName);
#else // !VCMI_ANDROID
#ifdef VCMI_WINDOWS
	HMODULE dll = LoadLibraryW(libpath.c_str());
	if (dll)
	{
		getName = (TGetNameFun)GetProcAddress(dll, "GetAiName");
		getAI = (TGetAIFun)GetProcAddress(dll, methodName.c_str());
	}
#else // !VCMI_WINDOWS
	void *dll = dlopen(libpath.string().c_str(), RTLD_LOCAL | RTLD_LAZY);
	if (dll)
	{
		getName = (TGetNameFun)dlsym(dll, "GetAiName");
		getAI = (TGetAIFun)dlsym(dll, methodName.c_str());
	}
	else
        logGlobal->errorStream() << "Error: " << dlerror();
#endif // VCMI_WINDOWS
	if (!dll)
	{
		logGlobal->errorStream() << "Cannot open dynamic library ("<<libpath<<"). Throwing...";
		throw std::runtime_error("Cannot open dynamic library");
	}
	else if(!getName || !getAI)
	{
		logGlobal->errorStream() << libpath << " does not export method " << methodName;
#ifdef VCMI_WINDOWS
		FreeLibrary(dll);
#else
		dlclose(dll);
#endif
		throw std::runtime_error("Cannot find method " + methodName);
	}
#endif // VCMI_ANDROID

	getName(temp);
    logGlobal->infoStream() << "Loaded " << temp;

	shared_ptr<rett> ret;
	getAI(ret);
	if(!ret)
        logGlobal->errorStream() << "Cannot get AI!";

	return ret;
}
Esempio n. 26
0
DWORD
WINAPI
PropDialogHandler(IN LPVOID lpThreadParameter)
{
    // NOTE: lpThreadParameter corresponds to the client shared section handle.

    NTSTATUS Status = STATUS_SUCCESS;
    APPLET_PROC CPLFunc;

    /*
     * Do not launch more than once the console property dialog applet,
     * or (albeit less probable), if we are not initialized.
     */
    if (!ConsoleInitialized || AlreadyDisplayingProps)
    {
        /* Close the associated client shared section handle if needed */
        if (lpThreadParameter)
        {
            CloseHandle((HANDLE)lpThreadParameter);
        }
        return STATUS_UNSUCCESSFUL;
    }

    AlreadyDisplayingProps = TRUE;

    /* Load the Control Applet if needed */
    if (ConsoleApplet == NULL)
    {
        WCHAR szBuffer[MAX_PATH];

        GetSystemDirectoryW(szBuffer, MAX_PATH);
        wcscat(szBuffer, L"\\console.dll");
        ConsoleApplet = LoadLibraryW(szBuffer);
        if (ConsoleApplet == NULL)
        {
            DPRINT1("Failed to load console.dll\n");
            Status = STATUS_UNSUCCESSFUL;
            goto Quit;
        }
    }

    /* Load its main function */
    CPLFunc = (APPLET_PROC)GetProcAddress(ConsoleApplet, "CPlApplet");
    if (CPLFunc == NULL)
    {
        DPRINT1("Error: Console.dll misses CPlApplet export\n");
        Status = STATUS_UNSUCCESSFUL;
        goto Quit;
    }

    if (CPLFunc(NULL, CPL_INIT, 0, 0) == FALSE)
    {
        DPRINT1("Error: failed to initialize console.dll\n");
        Status = STATUS_UNSUCCESSFUL;
        goto Quit;
    }

    if (CPLFunc(NULL, CPL_GETCOUNT, 0, 0) != 1)
    {
        DPRINT1("Error: console.dll returned unexpected CPL count\n");
        Status = STATUS_UNSUCCESSFUL;
        goto Quit;
    }

    CPLFunc(NULL, CPL_DBLCLK, (LPARAM)lpThreadParameter, 0);
    CPLFunc(NULL, CPL_EXIT  , 0, 0);

Quit:
    AlreadyDisplayingProps = FALSE;
    return Status;
}
Esempio n. 27
0
wchar_t * UT_GetDefaultPrinterName()
{
	UT_uint32 iBufferSize = 128; // will become 2x bigger immediately in the loop
	wchar_t * pPrinterName = NULL; 
	DWORD rc;
	
	do
	{
		iBufferSize *= 2;

		if(pPrinterName)
			g_free(pPrinterName);
		
		pPrinterName = (wchar_t *) UT_calloc(sizeof(wchar_t),iBufferSize);
		UT_return_val_if_fail( pPrinterName, NULL );
		
		// the method of obtaining the name is version specific ...
		OSVERSIONINFOW osvi;
		DWORD iNeeded, iReturned, iBuffSize;
		LPPRINTER_INFO_5W pPrinterInfo;
		wchar_t* p;

		osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
		GetVersionExW(&osvi);

		if (osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
		{
			// get size of the buffer needed to call enum printers
			if (!EnumPrintersW(PRINTER_ENUM_DEFAULT,NULL,5,NULL,0,&iNeeded,&iReturned))
			{
				if ((rc = GetLastError()) != ERROR_INSUFFICIENT_BUFFER)
				{
					return NULL;
				}
			}

			// allocate the buffer
			if ((pPrinterInfo = (LPPRINTER_INFO_5W)LocalAlloc(LPTR,iNeeded)) == NULL)
			{
				rc = GetLastError();
			}
			else
			{
				// now get the default printer
				if (!EnumPrintersW(PRINTER_ENUM_DEFAULT,NULL,5,
								  (LPBYTE) pPrinterInfo,iNeeded,&iNeeded,&iReturned))
				{
					rc = GetLastError();
				}
				else
				{
					if (iReturned > 0)
					{
						// here we copy the name to our own buffer
						if ((DWORD) wcslen(pPrinterInfo->pPrinterName) > iBufferSize-1)
						{
							rc = ERROR_INSUFFICIENT_BUFFER;
						}
						else
						{
							wcscpy(pPrinterName,pPrinterInfo->pPrinterName);
							rc = ERROR_SUCCESS;
						}
					}
					else
					{
						*pPrinterName = '0';
						rc = ERROR_SUCCESS;
					}
				}

				LocalFree(pPrinterInfo);
			}
		}
		else if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
		{
			if (osvi.dwMajorVersion >= 5) /* Windows 2000 or later */
			{
				iBuffSize = iBufferSize;

				HMODULE hWinSpool = LoadLibraryW(L"winspool.drv");
				if (!hWinSpool)
					return NULL;

				HRESULT (WINAPI * fnGetDefaultPrinter)(LPWSTR, LPDWORD) =
					(HRESULT (WINAPI * )(LPWSTR, LPDWORD)) GetProcAddress(hWinSpool, GETDEFAULTPRINTER);
				
				if (!fnGetDefaultPrinter)
				{
					FreeLibrary(hWinSpool);
					return NULL;
				}

                bool i =false;
				if (!fnGetDefaultPrinter(pPrinterName,&iBuffSize))
                        i = true;
                         
                if(i)
					rc = GetLastError();
				else
					rc = ERROR_SUCCESS;

				FreeLibrary(hWinSpool);
			}
			else /* Windows NT 4.0 or earlier */
			{
				if (GetProfileStringW(L"windows",L"device",L"",pPrinterName,iBufferSize) == iBufferSize-1)
				{
					rc = ERROR_INSUFFICIENT_BUFFER;
				}
				else
				{
					p = pPrinterName;
					while (*p != '0' && *p !=L',')
						++p;
					*p = '0';

					rc = ERROR_SUCCESS;
				}
			}
		}
	}
	while (rc == ERROR_INSUFFICIENT_BUFFER);
	
	return pPrinterName;
}
Esempio n. 28
0
/*
** Implementation of LoadLibraryA - requires wide char conversion
** as WinCE uses LoadLibraryW
*/
RTEXP	HINSTANCE LoadLibraryA(const char *path) {
	wchar_t	wpath[BUFSIZ];
	MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, path, -1, wpath, BUFSIZ);
	return(LoadLibraryW(wpath));
}
Esempio n. 29
0
CCommonWidget::CCommonWidget(QWidget *parent, CommonWndFlags WndFlag, Qt::WindowFlags f)
	: QWidget(parent, f | Qt::FramelessWindowHint | Qt::WindowSystemMenuHint)
{
	m_lWndFlag = WndFlag;
	m_pTitleLabel = NULL;
	m_pCloseButton = NULL;
	m_pMaxButton = NULL;
	m_pRestoreButton = NULL;
	m_pMinButton = NULL;
	m_iRoundCornerSize = 6;
	if(m_lWndFlag & enum_GGWndResizeHint)
	{
		::SetWindowLongA(winId(),GWL_STYLE, WS_POPUP | WS_THICKFRAME | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_CLIPSIBLINGS | WS_CLIPCHILDREN);
		::SetWindowLongA(winId(),GWL_EXSTYLE, WS_EX_APPWINDOW);
	}
	else
	{
		::SetWindowLongA(winId(),GWL_STYLE, WS_POPUP | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SYSMENU | WS_CLIPSIBLINGS | WS_CLIPCHILDREN);
		if(m_lWndFlag & (enum_GGWndMinimizeButtonHint | enum_GGWndMaximizeButtonHint))
		{
			::SetWindowLongA(winId(),GWL_EXSTYLE, WS_EX_APPWINDOW);
		}
	}
	//::SetWindowPos(winId(),NULL,0,0,0,0, SWP_FRAMECHANGED | SWP_NOSIZE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);

  	BOOL bSetTheme = TRUE;
	OSVERSIONINFOW osinfo = {0};
	osinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
	if(::GetVersionExW(&osinfo))
	{
		if(osinfo.dwMajorVersion <= 5)
			bSetTheme = FALSE;
	}

	HRESULT hr = S_OK;
	//去Win7边框
	if(bSetTheme)
	{
		HINSTANCE hInst = LoadLibraryW(L"UxTheme.dll");
		if (hInst)
		{
			typedef HRESULT (WINAPI *PFUN_SetWindowTheme)(HWND, LPCWSTR, LPCWSTR);
			PFUN_SetWindowTheme pFun = (PFUN_SetWindowTheme)GetProcAddress(hInst, "SetWindowTheme");
			if (pFun)
				hr = pFun(winId(), L"", L"");        //去掉xp主题
			FreeLibrary(hInst);
		}
	
		hInst = LoadLibraryW(L"dwmapi.dll");
        if(hInst)
        {
            typedef HRESULT (WINAPI * TmpFun)(HWND,DWORD,LPCVOID,DWORD);
            TmpFun DwmSetWindowAttributeEX = (TmpFun)::GetProcAddress(hInst, "DwmSetWindowAttribute");
            if (DwmSetWindowAttributeEX)
            {
                DWORD dwAttr = 1;
				hr = DwmSetWindowAttributeEX(winId(),2,&dwAttr, 4);    //去掉vista特效
            }

			MARGINS margins = {-1};
			typedef HRESULT (WINAPI * TmpFun1)(HWND,MARGINS*);
			TmpFun1 DwmExtendFrameIntoClientArea = (TmpFun1)::GetProcAddress(hInst, "DwmExtendFrameIntoClientArea");
			if (DwmExtendFrameIntoClientArea)
			{
				DwmExtendFrameIntoClientArea(winId(),&margins);
			}
            FreeLibrary(hInst);
        }
	}
	//::SetWindowPos(winId(),NULL,0,0,0,0, SWP_FRAMECHANGED | SWP_NOSIZE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);

	if(m_lWndFlag & enum_GGWndSysBackground)
		setAttribute(Qt::WA_StyledBackground);

	if(m_lWndFlag & enum_GGWndNoActive)
		setAttribute(Qt::WA_ShowWithoutActivating);
}
Esempio n. 30
0
RBOOL
    rpHostCommonPlatformLib_load
    (
        RPNCHAR modulePath,
        RU32 moduleId
    )
{
    RBOOL isSuccess = FALSE;

    RU32 moduleIndex = 0;
    rpal_thread_func pEntry = NULL;
    rpHCPModuleContext* modContext = NULL;
    RPCHAR errorStr = NULL;

    OBFUSCATIONLIB_DECLARE( entrypoint, RP_HCP_CONFIG_MODULE_ENTRY );
    OBFUSCATIONLIB_DECLARE( recvMessage, RP_HCP_CONFIG_MODULE_RECV_MESSAGE );

    if( NULL != modulePath )
    {
        for( moduleIndex = 0; moduleIndex < RP_HCP_CONTEXT_MAX_MODULES; moduleIndex++ )
        {
            if( 0 == g_hcpContext.modules[ moduleIndex ].hThread )
            {
                // Found an empty spot
#ifdef RPAL_PLATFORM_WINDOWS
                g_hcpContext.modules[ moduleIndex ].hModule = LoadLibraryW( modulePath );
#elif defined( RPAL_PLATFORM_LINUX ) || defined( RPAL_PLATFORM_MACOSX )
                g_hcpContext.modules[ moduleIndex ].hModule = dlopen( modulePath, RTLD_NOW | RTLD_LOCAL );
#endif
                if( NULL != g_hcpContext.modules[ moduleIndex ].hModule )
                {
                    OBFUSCATIONLIB_TOGGLE( entrypoint );
#ifdef RPAL_PLATFORM_WINDOWS
                    pEntry = (rpal_thread_func)GetProcAddress( (HMODULE)g_hcpContext.modules[ moduleIndex ].hModule, 
                                                               (RPCHAR)entrypoint );
#elif defined( RPAL_PLATFORM_LINUX ) || defined( RPAL_PLATFORM_MACOSX )
                    pEntry = (rpal_thread_func)dlsym( g_hcpContext.modules[ moduleIndex ].hModule, (RPCHAR)entrypoint );
#endif
                    OBFUSCATIONLIB_TOGGLE( entrypoint );

                    if( NULL != pEntry )
                    {
                        modContext = &(g_hcpContext.modules[ moduleIndex ].context);

                        modContext->pCurrentId = &(g_hcpContext.currentId);
                        modContext->func_sendHome = doSend;
                        modContext->isTimeToStop = rEvent_create( TRUE );
                        modContext->rpalContext = rpal_Context_get();
                        modContext->isOnlineEvent = g_hcpContext.isCloudOnline;

                        if( NULL != modContext->isTimeToStop )
                        {
                            g_hcpContext.modules[ moduleIndex ].id = (RpHcp_ModuleId)moduleId;
                            g_hcpContext.modules[ moduleIndex ].isTimeToStop  = modContext->isTimeToStop;
                            OBFUSCATIONLIB_TOGGLE( recvMessage );
#ifdef RPAL_PLATFORM_WINDOWS
                            g_hcpContext.modules[ moduleIndex ].func_recvMessage = 
                                    (rpHCPModuleMsgEntry)GetProcAddress( (HMODULE)g_hcpContext.modules[ moduleIndex ].hModule,
                                                                         (RPCHAR)recvMessage );
#elif defined( RPAL_PLATFORM_LINUX ) || defined( RPAL_PLATFORM_MACOSX )
                            g_hcpContext.modules[ moduleIndex ].func_recvMessage = 
                                    (rpHCPModuleMsgEntry)dlsym( g_hcpContext.modules[ moduleIndex ].hModule, (RPCHAR)recvMessage );
#endif
                            OBFUSCATIONLIB_TOGGLE( recvMessage );
                            g_hcpContext.modules[ moduleIndex ].hThread = rpal_thread_new( pEntry, modContext );

                            if( 0 != g_hcpContext.modules[ moduleIndex ].hThread )
                            {
                                g_hcpContext.modules[ moduleIndex ].isOsLoaded = TRUE;
                                isSuccess = TRUE;
                                rpal_debug_info( "module %S successfully loaded manually.", modulePath );
                            }
                        }
                    }
                    else
                    {
#ifdef RPAL_PLATFORM_WINDOWS
                        FreeLibrary( (HMODULE)g_hcpContext.modules[ moduleIndex ].hModule );
#elif defined( RPAL_PLATFORM_LINUX ) || defined( RPAL_PLATFORM_MACOSX )
                        dlclose( g_hcpContext.modules[ moduleIndex ].hModule );
#endif
                        g_hcpContext.modules[ moduleIndex ].hModule = NULL;
                        rpal_debug_error( "Could not manually finding the entry point to a module!" );
                    }
                }
                else
                {
#if defined( RPAL_PLATFORM_LINUX ) || defined( RPAL_PLATFORM_MACOSX )
                    errorStr = dlerror();
#endif
                    rpal_debug_error( "Could not manually load module %S: %X %s", 
                                      modulePath, 
                                      rpal_error_getLast(), 
                                      errorStr );
                }

                break;
            }
        }
    }
    //forceCrash();
    return isSuccess;
}