VOID StartScreenSaver( IN PWLSESSION Session) { HKEY hKey = NULL, hCurrentUser = NULL; WCHAR szApplicationName[MAX_PATH]; WCHAR szCommandLine[MAX_PATH + 3]; DWORD bufferSize = sizeof(szApplicationName) - sizeof(WCHAR); DWORD dwType; STARTUPINFOW StartupInfo; PROCESS_INFORMATION ProcessInformation; HANDLE HandleArray[2]; LONG rc; DWORD Status; BOOL ret = FALSE; if (!ImpersonateLoggedOnUser(Session->UserToken)) { ERR("WL: ImpersonateLoggedOnUser() failed with error %lu\n", GetLastError()); goto cleanup; } rc = RegOpenCurrentUser(KEY_READ, &hCurrentUser); if (rc != ERROR_SUCCESS) { ERR("WL: RegOpenCurrentUser Error!\n"); goto cleanup; } rc = RegOpenKeyExW(hCurrentUser, L"Control Panel\\Desktop", 0, KEY_QUERY_VALUE, &hKey); if (rc != ERROR_SUCCESS) { ERR("WL: RegOpenKeyEx Error!\n"); goto cleanup; } rc = RegQueryValueExW(hKey, L"SCRNSAVE.EXE", 0, &dwType, (LPBYTE)szApplicationName, &bufferSize); if (rc != ERROR_SUCCESS || dwType != REG_SZ) { ERR("WL: RegQueryValueEx Error!\n"); goto cleanup; } if (bufferSize == 0) { ERR("WL: Buffer size is NULL!\n"); goto cleanup; } szApplicationName[bufferSize / sizeof(WCHAR)] = 0; /* Terminate the string */ if (wcslen(szApplicationName) == 0) { ERR("WL: Application Name length is zero!\n"); goto cleanup; } wsprintfW(szCommandLine, L"%s /s", szApplicationName); TRACE("WL: Executing %S\n", szCommandLine); ZeroMemory(&StartupInfo, sizeof(STARTUPINFOW)); ZeroMemory(&ProcessInformation, sizeof(PROCESS_INFORMATION)); StartupInfo.cb = sizeof(STARTUPINFOW); StartupInfo.dwFlags = STARTF_SCRNSAVER; /* FIXME: run the screen saver on the screen saver desktop */ ret = CreateProcessW(szApplicationName, szCommandLine, NULL, NULL, FALSE, 0, NULL, NULL, &StartupInfo, &ProcessInformation); if (!ret) { ERR("WL: Unable to start %S, error %lu\n", szApplicationName, GetLastError()); goto cleanup; } CloseHandle(ProcessInformation.hThread); SystemParametersInfoW(SPI_SETSCREENSAVERRUNNING, TRUE, NULL, 0); /* Wait the end of the process or some other activity */ ResetEvent(Session->hUserActivity); HandleArray[0] = ProcessInformation.hProcess; HandleArray[1] = Session->hUserActivity; Status = WaitForMultipleObjects(2, HandleArray, FALSE, INFINITE); if (Status == WAIT_OBJECT_0 + 1) { /* Kill the screen saver */ TerminateProcess(ProcessInformation.hProcess, 0); } SetEvent(Session->hEndOfScreenSaver); CloseHandle(ProcessInformation.hProcess); cleanup: RevertToSelf(); if (hKey) RegCloseKey(hKey); if (hCurrentUser) RegCloseKey(hCurrentUser); if (!ret) { PostMessageW(Session->SASWindow, WLX_WM_SAS, WLX_SAS_TYPE_SCRNSVR_ACTIVITY, 0); #ifndef USE_GETLASTINPUTINFO InterlockedExchange((LONG*)&Session->LastActivity, GetTickCount()); #endif } }
/* * ucmQueryCustomParameter * * Purpose: * * Query custom parameter and run it. * */ BOOL ucmQueryCustomParameter( VOID ) { BOOL cond = FALSE, bResult = FALSE; HKEY hKey = NULL; LPWSTR lpParameter = NULL; LRESULT lRet; DWORD dwSize = 0, dwType, dwFlag = 0; STARTUPINFOW startupInfo; PROCESS_INFORMATION processInfo; do { lRet = RegOpenKeyExW(HKEY_CURRENT_USER, T_AKAGI_KEY, 0, KEY_READ, &hKey); if ((lRet != ERROR_SUCCESS) || (hKey == NULL)) { break; } g_AkagiFlag = AKAGI_FLAG_KILO; dwType = REG_DWORD; dwSize = sizeof(DWORD); lRet = RegQueryValueExW(hKey, T_AKAGI_FLAG, NULL, &dwType, (LPBYTE)&dwFlag, &dwSize); if (lRet == ERROR_SUCCESS) { g_AkagiFlag = dwFlag; } dwSize = 0; lRet = RegQueryValueExW(hKey, T_AKAGI_PARAM, NULL, NULL, (LPBYTE)NULL, &dwSize); if (lRet != ERROR_SUCCESS) { break; } lpParameter = (LPWSTR)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwSize + 1); if (lpParameter == NULL) { break; } lRet = RegQueryValueExW(hKey, T_AKAGI_PARAM, NULL, NULL, (LPBYTE)lpParameter, &dwSize); if (lRet == ERROR_SUCCESS) { OutputDebugStringW(L"Akagi letter found"); OutputDebugStringW(lpParameter); RtlSecureZeroMemory(&startupInfo, sizeof(startupInfo)); RtlSecureZeroMemory(&processInfo, sizeof(processInfo)); startupInfo.cb = sizeof(startupInfo); GetStartupInfoW(&startupInfo); bResult = CreateProcessW(NULL, lpParameter, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo); if (bResult) { CloseHandle(processInfo.hProcess); CloseHandle(processInfo.hThread); } } HeapFree(GetProcessHeap(), 0, lpParameter); RegCloseKey(hKey); hKey = NULL; RegDeleteKey(HKEY_CURRENT_USER, T_AKAGI_KEY); } while (cond); if (hKey != NULL) { RegCloseKey(hKey); } return bResult; }
static int reg_add(WCHAR *key_name, WCHAR *value_name, BOOL value_empty, WCHAR *type, WCHAR separator, WCHAR *data, BOOL force) { LPWSTR p; HKEY root,subkey; if (!sane_path(key_name)) return 1; p = strchrW(key_name,'\\'); if (p) p++; root = path_get_rootkey(key_name); if (!root) { output_message(STRING_INVALID_KEY); return 1; } if (value_name && value_empty) { output_message(STRING_INVALID_CMDLINE); return 1; } if(RegCreateKeyW(root,p,&subkey)!=ERROR_SUCCESS) { output_message(STRING_INVALID_KEY); return 1; } if (value_name || value_empty || data) { DWORD reg_type; DWORD reg_count = 0; BYTE* reg_data = NULL; if (!force) { if (RegQueryValueExW(subkey, value_name, NULL, NULL, NULL, NULL) == ERROR_SUCCESS) { if (!ask_confirm(STRING_OVERWRITE_VALUE, value_name)) { RegCloseKey(subkey); output_message(STRING_CANCELLED); return 0; } } } reg_type = wchar_get_type(type); if (reg_type == ~0u) { RegCloseKey(subkey); output_message(STRING_UNSUPPORTED_TYPE, type); return 1; } if ((reg_type == REG_DWORD || reg_type == REG_DWORD_BIG_ENDIAN) && !data) { RegCloseKey(subkey); output_message(STRING_INVALID_CMDLINE); return 1; } if (!(reg_data = get_regdata(data, reg_type, separator, ®_count))) { RegCloseKey(subkey); return 1; } RegSetValueExW(subkey,value_name,0,reg_type,reg_data,reg_count); HeapFree(GetProcessHeap(),0,reg_data); } RegCloseKey(subkey); output_message(STRING_SUCCESS); return 0; }
static VOID FillServerAddesssCombo(PINFO pInfo) { HKEY hKey; WCHAR KeyName[] = L"Software\\Microsoft\\Terminal Server Client\\Default"; WCHAR Name[MAX_KEY_NAME]; LONG ret = ERROR_SUCCESS; DWORD size; INT i = 0; if (RegOpenKeyExW(HKEY_CURRENT_USER, KeyName, 0, KEY_READ, &hKey) == ERROR_SUCCESS) { while (ret == ERROR_SUCCESS) { size = MAX_KEY_NAME; ret = RegEnumValueW(hKey, i, Name, &size, NULL, NULL, NULL, NULL); if (ret == ERROR_SUCCESS) { size = MAX_KEY_NAME; if (RegQueryValueExW(hKey, Name, 0, NULL, NULL, &size) == ERROR_SUCCESS) { LPWSTR lpAddress = HeapAlloc(GetProcessHeap(), 0, size); if (lpAddress) { if (RegQueryValueExW(hKey, Name, 0, NULL, (LPBYTE)lpAddress, &size) == ERROR_SUCCESS) { SendDlgItemMessageW(pInfo->hGeneralPage, IDC_SERVERCOMBO, CB_ADDSTRING, 0, (LPARAM)lpAddress); } HeapFree(GetProcessHeap(), 0, lpAddress); } } } i++; } RegCloseKey(hKey); } if (LoadStringW(hInst, IDS_BROWSESERVER, Name, sizeof(Name) / sizeof(WCHAR))) { SendDlgItemMessageW(pInfo->hGeneralPage, IDC_SERVERCOMBO, CB_ADDSTRING, 0, (LPARAM)Name); } }
///////////////////////////////////////////////////////// // // DlgProc // // The DlgProc function is an application-defined // function that processes messages sent to the dialog // // Parameters: // HWND hwnd : [in] handle to dialog window // UINT uMsg : [in] message identifier // WPARAM wParam : [in] first message parameter // LPARAM lParam : [in] second message parameter // // Return Values: // The return value is the result of the // message processing and depends on the message sent // ///////////////////////////////////////////////////////// BOOL CALLBACK DlgProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM /* lParam */) { BOOL bReturn = FALSE; // the value to return switch (uMsg) { case WM_INITDIALOG: { // Initialize the COM if (FAILED(CoInitialize(NULL))) { MessageBoxW(NULL, L"Unable to initialize the COM library", gc_wszAppName, MB_OK | MB_ICONINFORMATION); PostMessage(hwnd, WM_CLOSE, 0, 0); break; } // Gather and show the information we're interested in // Check out if Microsoft Tablet PC Platform components of the // Microsoft Windows XP Professional Operating System are enabled int bTabletPC = GetSystemMetrics(SM_TABLETPC); SetDlgItemTextW(hwnd, IDC_TABLETPC, bTabletPC ? L"Available" : L"Not available"); // Get the version of the Text Services Framework components SInfo info; if (GetComponentInfo(CLSID_TF_ThreadMgr, info) == TRUE) { SetDlgItemTextW(hwnd, IDC_TSF, info.wchVersion); } // Find out the name and the version of the default handwriting recognizer // Create the enumerator for the installed recognizers IInkRecognizers* pIInkRecognizers = NULL; HRESULT hr = CoCreateInstance(CLSID_InkRecognizers, NULL, CLSCTX_INPROC_SERVER, IID_IInkRecognizers, (void **)&pIInkRecognizers); if (SUCCEEDED(hr)) { IInkRecognizer* pIInkRecognizer = NULL; // The first parameter is the language id, passing 0 means that the language // id will be retrieved using the user default-locale identifier hr = pIInkRecognizers->GetDefaultRecognizer(0, &pIInkRecognizer); if (SUCCEEDED(hr)) { // Get the recognizer's friendly name BSTR bstr; if (SUCCEEDED(pIInkRecognizer->get_Name(&bstr))) { SetDlgItemTextW(hwnd, IDC_HWR_NAME, bstr); SysFreeString(bstr); } else { SetDlgItemTextW(hwnd, IDC_HWR_NAME, L"Failed"); } // Get the recognizer's vendor info if (SUCCEEDED(pIInkRecognizer->get_Vendor(&bstr))) { SetDlgItemTextW(hwnd, IDC_HWR_VENDOR, bstr); SysFreeString(bstr); } else { SetDlgItemTextW(hwnd, IDC_HWR_VENDOR, L"Failed"); } // Release it pIInkRecognizer->Release(); pIInkRecognizer = NULL; } // Release the collection object pIInkRecognizers->Release(); pIInkRecognizers = NULL; } // Find out the name and the version of the default speech recognizer // Open key to find path of application HKEY hkeySpeech; if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, gc_wszSpeechKey, 0, KEY_READ, &hkeySpeech) == ERROR_SUCCESS) { // Query value of key to get the name of the component WCHAR wchValue[265]; ULONG cSize = sizeof(wchValue); if (RegQueryValueExW(hkeySpeech, L"DefaultDefaultTokenId", NULL, NULL, (BYTE*)wchValue, &cSize) == ERROR_SUCCESS) { int ndx = lstrlenW(L"HKEY_LOCAL_MACHINE\\"); int len = lstrlenW(wchValue); if (ndx < len && RegOpenKeyExW(HKEY_LOCAL_MACHINE, &wchValue[ndx], 0, KEY_READ, &hkeySpeech) == ERROR_SUCCESS) { cSize = sizeof(wchValue); if (RegQueryValueExW(hkeySpeech, NULL, NULL, NULL, (BYTE*)wchValue, &cSize) == ERROR_SUCCESS) { SetDlgItemTextW(hwnd, IDC_SPR_NAME, wchValue); } } } } // Find out which of the controls are installed and show their version info for (int i = 0, j = 0; i < NUM_CONTROLS; i++) { // Get the component info CLSID clsid; if (SUCCEEDED(CLSIDFromProgID(gc_wszProgId[i], &clsid)) && GetComponentInfo(clsid, info) == TRUE) { SetDlgItemTextW(hwnd, gc_uiCtrlId[j][0], info.wchName); SetDlgItemTextW(hwnd, gc_uiCtrlId[j][1], info.wchVersion); j++; } } // Done with the COM CoUninitialize(); break; } case WM_DESTROY: PostQuitMessage(0); break; case WM_COMMAND: switch (LOWORD(wParam)) { case IDCLOSE: // User clicked on the "Close" button in the dialog. case IDCANCEL: // User clicked the close button ([X]) in the caption // or pressed Alt+F4. DestroyWindow(hwnd); bReturn = TRUE; break; } break; } return bReturn; }
int uv_uptime(double* uptime) { BYTE stack_buffer[4096]; BYTE* malloced_buffer = NULL; BYTE* buffer = (BYTE*) stack_buffer; size_t buffer_size = sizeof(stack_buffer); DWORD data_size; PERF_DATA_BLOCK* data_block; PERF_OBJECT_TYPE* object_type; PERF_COUNTER_DEFINITION* counter_definition; DWORD i; for (;;) { LONG result; data_size = (DWORD) buffer_size; result = RegQueryValueExW(HKEY_PERFORMANCE_DATA, L"2", NULL, NULL, buffer, &data_size); if (result == ERROR_SUCCESS) { break; } else if (result != ERROR_MORE_DATA) { *uptime = 0; return uv_translate_sys_error(result); } buffer_size *= 2; /* Don't let the buffer grow infinitely. */ if (buffer_size > 1 << 20) { goto internalError; } uv__free(malloced_buffer); buffer = malloced_buffer = (BYTE*) uv__malloc(buffer_size); if (malloced_buffer == NULL) { *uptime = 0; return UV_ENOMEM; } } if (data_size < sizeof(*data_block)) goto internalError; data_block = (PERF_DATA_BLOCK*) buffer; if (wmemcmp(data_block->Signature, L"PERF", 4) != 0) goto internalError; if (data_size < data_block->HeaderLength + sizeof(*object_type)) goto internalError; object_type = (PERF_OBJECT_TYPE*) (buffer + data_block->HeaderLength); if (object_type->NumInstances != PERF_NO_INSTANCES) goto internalError; counter_definition = (PERF_COUNTER_DEFINITION*) (buffer + data_block->HeaderLength + object_type->HeaderLength); for (i = 0; i < object_type->NumCounters; i++) { if ((BYTE*) counter_definition + sizeof(*counter_definition) > buffer + data_size) { break; } if (counter_definition->CounterNameTitleIndex == 674 && counter_definition->CounterSize == sizeof(uint64_t)) { if (counter_definition->CounterOffset + sizeof(uint64_t) > data_size || !(counter_definition->CounterType & PERF_OBJECT_TIMER)) { goto internalError; } else { BYTE* address = (BYTE*) object_type + object_type->DefinitionLength + counter_definition->CounterOffset; uint64_t value = *((uint64_t*) address); *uptime = (double) (object_type->PerfTime.QuadPart - value) / (double) object_type->PerfFreq.QuadPart; uv__free(malloced_buffer); return 0; } } counter_definition = (PERF_COUNTER_DEFINITION*) ((BYTE*) counter_definition + counter_definition->ByteLength); } /* If we get here, the uptime value was not found. */ uv__free(malloced_buffer); *uptime = 0; return UV_ENOSYS; internalError: uv__free(malloced_buffer); *uptime = 0; return UV_EIO; }
/****************************************************************************** * SHDOCVW_GetShellInstanceObjectClassObject [Internal] * * Figure if there is a 'Shell Instance Object' conformant registry entry for * the given CLSID and if so create and return a corresponding ClassObject. * * PARAMS * rclsid [I] CLSID of the 'Shell Instance Object'. * riid [I] Desired interface. Only IClassFactory supported. * ppvClassObj [O] The corresponding ClassObject. * * RETURNS * Success: S_OK, * Failure: CLASS_E_CLASSNOTAVAILABLE */ HRESULT SHDOCVW_GetShellInstanceObjectClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppvClassObj) { WCHAR wszInstanceKey[] = { 'C','L','S','I','D','\\','{','0','0','0','0','0','0','0','0','-', '0','0','0','0','-','0','0','0','0','-','0','0','0','0','-','0','0','0','0','0','0','0','0', '0','0','0','0','}','\\','I','n','s','t','a','n','c','e', 0 }; const WCHAR wszCLSID[] = { 'C','L','S','I','D',0 }; const WCHAR wszInitPropertyBag[] = { 'I','n','i','t','P','r','o','p','e','r','t','y','B','a','g',0 }; WCHAR wszCLSIDInstance[CHARS_IN_GUID]; CLSID clsidInstance; HKEY hInstanceKey, hInitPropertyBagKey; DWORD dwType, cbBytes = sizeof(wszCLSIDInstance); IPropertyBag *pInitPropertyBag; HRESULT hr; LONG res; TRACE("(rclsid=%s, riid=%s, ppvClassObject=%p)\n", debugstr_guid(rclsid), debugstr_guid(riid), ppvClassObj); /* Figure if there is an 'Instance' subkey for the given CLSID and acquire a handle. */ if (!StringFromGUID2(rclsid, wszInstanceKey + 6, CHARS_IN_GUID) || !(wszInstanceKey[5+CHARS_IN_GUID]='\\') || /* Repair the null-termination. */ ERROR_SUCCESS != RegOpenKeyExW(HKEY_CLASSES_ROOT, wszInstanceKey, 0, KEY_READ, &hInstanceKey)) { /* If there is no 'Instance' subkey, then it's not a Shell Instance Object. */ return CLASS_E_CLASSNOTAVAILABLE; } if (RegQueryValueExW(hInstanceKey, wszCLSID, NULL, &dwType, (LPBYTE)wszCLSIDInstance, &cbBytes) != ERROR_SUCCESS || FAILED(CLSIDFromString(wszCLSIDInstance, &clsidInstance))) { /* 'Instance' should have a 'CLSID' value with a well-formed clsid-string. */ FIXME("Failed to infer instance CLSID! %s\n", debugstr_w(wszCLSIDInstance)); RegCloseKey(hInstanceKey); return CLASS_E_CLASSNOTAVAILABLE; } /* Try to open the 'InitPropertyBag' subkey. */ res = RegOpenKeyExW(hInstanceKey, wszInitPropertyBag, 0, KEY_READ, &hInitPropertyBagKey); RegCloseKey(hInstanceKey); if (res != ERROR_SUCCESS) { /* Besides 'InitPropertyBag's, shell instance objects might be initialized by streams. * So this case might not be an error. */ TRACE("No InitPropertyBag key found!\n"); return CLASS_E_CLASSNOTAVAILABLE; } /* If the construction succeeds, the new RegistryPropertyBag is responsible for closing * hInitProperyBagKey. */ hr = RegistryPropertyBag_Constructor(hInitPropertyBagKey, &IID_IPropertyBag, (LPVOID*)&pInitPropertyBag); if (FAILED(hr)) { RegCloseKey(hInitPropertyBagKey); return hr; } /* Construct an Instance Object Factory, which creates objects of class 'clsidInstance' * and asks them to initialize themselves with the help of the 'pInitiPropertyBag' */ hr = InstanceObjectFactory_Constructor(&clsidInstance, pInitPropertyBag, riid, ppvClassObj); IPropertyBag_Release(pInitPropertyBag); /* The factory will hold a reference the bag. */ return hr; }
void CDlgFileAssoc::ExtAssignDyn(LPWSTR extName, LPWSTR extCmd, int iconIndex) { HKEY hKey; DWORD len = 100; wchar_t buf[100]; wchar_t szKeyUpr[20]; wchar_t szKeyName[20]; wchar_t szKeyDesc[50]; wchar_t szKeyStr[50]; wcscpy(szKeyUpr, extName); wcsupr(szKeyUpr); wsprintf(szKeyName, L".%s", extName); wsprintf(szKeyStr, L"%s file", szKeyUpr); wsprintf(szKeyDesc, L"Nitrogen%sFile", szKeyUpr); RegCreateKeyExW(HKEY_CLASSES_ROOT, szKeyName, 0, NULL, REG_OPTION_NON_VOLATILE, 0, NULL, &hKey, NULL); if (RegQueryValueExW(hKey, NULL, NULL, NULL, (BYTE*)buf, &len) == ERROR_SUCCESS) { if (len > 0) { RegSetValueExW(hKey, L"Nitrogen backup", 0, REG_SZ, (BYTE*)buf, len); } } RegSetValueExW(hKey, NULL, 0, REG_SZ, (BYTE*)szKeyDesc, wcslen(szKeyDesc)*2+2); wchar_t oldSettings[100]; oldSettings[0] = 0; len = 100; if (RegQueryValueExW(hKey, L"Nitrogen backup", NULL, NULL, (BYTE*)buf, &len) == ERROR_SUCCESS) { wcscpy(oldSettings, buf); } RegCloseKey(hKey); RegCreateKeyExW(HKEY_CLASSES_ROOT, szKeyDesc, 0, NULL, REG_OPTION_NON_VOLATILE, 0, NULL, &hKey, NULL); RegSetValueExW(hKey, NULL, 0, REG_SZ, (BYTE*)szKeyStr, wcslen(szKeyStr)*2+2); RegCloseKey(hKey); wchar_t sIco[100]; wsprintf(sIco, L"%s\\DefaultIcon", szKeyDesc); RegCreateKeyExW(HKEY_CLASSES_ROOT, sIco, 0, NULL, REG_OPTION_NON_VOLATILE, 0, NULL, &hKey, NULL); wchar_t s[MAX_PATH]; wsprintf(s, L"%sNitrogen.exe,%i", player()->Path, iconIndex); RegSetValueExW(hKey, NULL, 0, REG_SZ, (BYTE*)s, wcslen(s)*2+2); RegCloseKey(hKey); wchar_t sCmd[100]; wsprintf(sCmd, L"%s\\Shell\\Open\\Command", szKeyDesc); RegCreateKeyExW(HKEY_CLASSES_ROOT, sCmd, 0, NULL, REG_OPTION_NON_VOLATILE, 0, NULL, &hKey, NULL); wsprintf(s, L"\"%sNitrogen.exe\" %s", player()->Path, extCmd); RegSetValueExW(hKey, NULL, 0, REG_SZ, (BYTE*)s, wcslen(s)*2+2); RegCloseKey(hKey); if (oldSettings[0] != 0) { HKEY hKeyIn; wchar_t PathShellExIn[MAX_PATH]; wsprintf(PathShellExIn, L"%s\\ShellEx", oldSettings); if (RegOpenKeyExW(HKEY_CLASSES_ROOT, PathShellExIn, 0, 0, &hKeyIn) == ERROR_SUCCESS) { wchar_t PathShellExOut[MAX_PATH]; wsprintf(PathShellExOut, L"%s\\ShellEx", szKeyDesc); HKEY hKeyOut; if (RegCreateKeyExW(HKEY_CLASSES_ROOT, PathShellExOut, 0, NULL, REG_OPTION_NON_VOLATILE, 0, NULL, &hKeyOut, NULL) == ERROR_SUCCESS) { RegCopyData(hKeyIn, hKeyOut); RegCloseKey(hKeyOut); } RegCloseKey(hKeyIn); } } }
HRESULT CMuxPhysicalAdapter::LoadConfiguration (VOID) { HKEY hkeyAdapterGuid; WCHAR szAdapterGuidKey[MAX_PATH+1]; WCHAR szAdapterGuid[MAX_PATH+1]; LPWSTR lpMiniportList; LPWSTR lpMiniport; LPWSTR lpMiniportGuid; DWORD dwDisp; CMuxVirtualMiniport *pMiniport; GUID guidMiniport; DWORD dwBytes; LONG lResult; TraceMsg( L"-->CMuxPhysicalAdapter::LoadConfiguration.\n" ); // // Build the registry key using the adapter guid under which // device IDs of the virtual miniports are stored. // StringFromGUID2( m_guidAdapter, szAdapterGuid, MAX_PATH+1 ); StringCchPrintfW ( szAdapterGuidKey, celems(szAdapterGuidKey), L"%s\\%s", c_szAdapterList, szAdapterGuid ); szAdapterGuidKey[MAX_PATH]='\0'; lResult = RegCreateKeyExW( HKEY_LOCAL_MACHINE, szAdapterGuidKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hkeyAdapterGuid, &dwDisp); if ( lResult == ERROR_SUCCESS ) { // // If dwDisp indicates that a new key is created then, we know there // is no virtual miniport currently listed underneath and we simply // return. // if ( dwDisp != REG_CREATED_NEW_KEY ) { dwBytes = 0; lResult = RegQueryValueExW( hkeyAdapterGuid, c_szUpperBindings, NULL, NULL, NULL, &dwBytes ); if(lResult != ERROR_SUCCESS) { // you may do something } //alloc lpMiniportList with dwBytes elements and initialzes each to be 0 lpMiniportList = (LPWSTR)calloc( dwBytes, 1 ); if ( lpMiniportList != NULL ) { lResult = RegQueryValueExW( hkeyAdapterGuid, c_szUpperBindings, NULL, NULL, (LPBYTE)lpMiniportList, &dwBytes ); if ( lResult == ERROR_SUCCESS ) { lpMiniport = lpMiniportList; #ifndef PASSTHRU_NOTIFY // // In case of mux, c_szUpperBindings is a REG_MULTI_SZ string. // lpMiniport[dwBytes-1] = '\0'; while ( wcslen(lpMiniport) ) { lpMiniportGuid = RemoveDevicePrefix( lpMiniport ); TraceMsg( L" Loading configuration for miniport %s...\n", lpMiniportGuid ); if ( lpMiniportGuid != NULL ) { CLSIDFromString( lpMiniportGuid, &guidMiniport ); // // Create an instance representing the virtual miniport. // #pragma prefast(suppress:8197, "The instance is freed in the destructor") pMiniport = new CMuxVirtualMiniport( m_pnc, &guidMiniport, &m_guidAdapter ); if ( pMiniport ) { // // Load any miniport specific configuration. // pMiniport->LoadConfiguration(); // // Save the miniport instance in a list. // m_MiniportList.Insert( pMiniport, guidMiniport ); } free( lpMiniportGuid ); } // // Get next miniport guid. // lpMiniport += wcslen(lpMiniport) + 1; } #else // // In case of the passthru driver, c_szUpperBindings is // a reg_sz string. // lpMiniportGuid = RemoveDevicePrefix( lpMiniport ); TraceMsg( L" Loading configuration for miniport %s...\n", lpMiniportGuid ); if ( lpMiniportGuid ) { CLSIDFromString( lpMiniportGuid, &guidMiniport ); // // Create an instance representing the virtual miniport. // pMiniport = new CMuxVirtualMiniport( m_pnc, &guidMiniport, &m_guidAdapter ); if ( pMiniport ) { // // Load any miniport specific configuration. // pMiniport->LoadConfiguration(); // // Save the miniport instance in a list. // m_MiniportList.Insert( pMiniport, guidMiniport ); } free( lpMiniportGuid ); } #endif } else { TraceMsg( L" Failed to read the registry value: %s.\n", c_szUpperBindings ); } free( lpMiniportList ); } else { lResult = ERROR_NOT_ENOUGH_MEMORY; } } RegCloseKey( hkeyAdapterGuid ); } else { TraceMsg( L" Failed to open the registry key: %s.\n", szAdapterGuidKey ); } TraceMsg( L"<--CMuxPhysicalAdapter::LoadConfiguration(HRESULT = %x).\n", HRESULT_FROM_WIN32(lResult) ); return HRESULT_FROM_WIN32(lResult); }
BOOL GetBootResourceList(HDEVINFO DeviceInfoSet, PSP_DEVINFO_DATA DeviceInfoData, PCM_RESOURCE_LIST *ppResourceList) { HKEY hDeviceKey = NULL; HKEY hConfigKey = NULL; LPBYTE lpBuffer = NULL; DWORD dwDataSize; LONG lError; BOOL ret = FALSE; *ppResourceList = NULL; hDeviceKey = SetupDiCreateDevRegKeyW(DeviceInfoSet, DeviceInfoData, DICS_FLAG_GLOBAL, 0, DIREG_DEV, NULL, NULL); if (!hDeviceKey) return FALSE; lError = RegOpenKeyExW(hDeviceKey, L"LogConf", 0, KEY_QUERY_VALUE, &hConfigKey); if (lError != ERROR_SUCCESS) goto done; /* Get the configuration data size */ lError = RegQueryValueExW(hConfigKey, L"BootConfig", NULL, NULL, NULL, &dwDataSize); if (lError != ERROR_SUCCESS) goto done; /* Allocate the buffer */ lpBuffer = HeapAlloc(GetProcessHeap(), 0, dwDataSize); if (lpBuffer == NULL) goto done; /* Retrieve the configuration data */ lError = RegQueryValueExW(hConfigKey, L"BootConfig", NULL, NULL, (LPBYTE)lpBuffer, &dwDataSize); if (lError == ERROR_SUCCESS) ret = TRUE; done: if (ret == FALSE && lpBuffer != NULL) HeapFree(GetProcessHeap(), 0, lpBuffer); if (hConfigKey) RegCloseKey(hConfigKey); if (hDeviceKey) RegCloseKey(hDeviceKey); if (ret == TRUE) *ppResourceList = (PCM_RESOURCE_LIST)lpBuffer; return ret; }
HRESULT NextValue(LPITEMIDLIST* ppidl) { WCHAR name[MAX_PATH]; DWORD cchName = _countof(name); DWORD type = 0; DWORD dataSize = 0; if (RegEnumValueW(m_hkey, m_idx++, name, &cchName, 0, &type, NULL, &dataSize)) return S_FALSE; REG_ENTRY_TYPE otype = REG_ENTRY_VALUE; DWORD entryBufferLength = FIELD_OFFSET(RegPidlEntry, entryName) + sizeof(WCHAR) + cchName * sizeof(WCHAR); #define MAX_EMBEDDED_DATA 32 BOOL copyData = dataSize <= MAX_EMBEDDED_DATA; if (copyData) { entryBufferLength += dataSize + sizeof(WCHAR); otype = REG_ENTRY_VALUE_WITH_CONTENT; } // allocate space for the terminator entryBufferLength += FIELD_OFFSET(SHITEMID, abID); RegPidlEntry* entry = (RegPidlEntry*) CoTaskMemAlloc(entryBufferLength); if (!entry) return E_OUTOFMEMORY; memset(entry, 0, entryBufferLength); entry->cb = FIELD_OFFSET(RegPidlEntry, entryName); entry->magic = REGISTRY_PIDL_MAGIC; entry->entryType = otype; entry->contentType = type; if (cchName > 0) { entry->entryNameLength = cchName * sizeof(WCHAR); StringCbCopyNW(entry->entryName, entryBufferLength, name, entry->entryNameLength); entry->cb += entry->entryNameLength + sizeof(WCHAR); } else { entry->entryNameLength = 0; entry->entryName[0] = 0; entry->cb += sizeof(WCHAR); } if (copyData) { PBYTE contentData = (PBYTE) ((PBYTE) entry + entry->cb); entry->contentsLength = dataSize; // In case it's an unterminated string, RegGetValue will add the NULL termination dataSize += sizeof(WCHAR); if (!RegQueryValueExW(m_hkey, name, NULL, NULL, contentData, &dataSize)) { entry->cb += entry->contentsLength + sizeof(WCHAR); } else { entry->contentsLength = 0; entry->cb += sizeof(WCHAR); } } if (ppidl) *ppidl = (LPITEMIDLIST) entry; return S_OK; }
EXPORT LONG WINAPI RegQueryValueExWStub(HKEY hKey, LPCWSTR lpValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData) {return RegQueryValueExW(hKey, lpValueName, lpReserved, lpType, lpData, lpcbData);}
/*********************************************************************** * drvGetDefaultCommConfigW (SERIALUI.@) * * Used by Win9x KERNEL to get the default config for a COMM port * FIXME: uses the wrong registry key... should use a digit, not * the comm port name. */ DWORD WINAPI drvGetDefaultCommConfigW( LPCWSTR lpszDevice, LPCOMMCONFIG lpCommConfig, LPDWORD lpdwSize) { HKEY hKeyReg, hKeyPort; WCHAR szKeyName[100]; DWORD r,dwSize,dwType; static const WCHAR fmt[] = {'%','s','\\','%','s',0 }; TRACE("(%s, %p, %p) *lpdwSize: %u\n", debugstr_w(lpszDevice), lpCommConfig, lpdwSize, lpdwSize ? *lpdwSize : 0); if ((!lpszDevice) || (!lpCommConfig) || (!lpdwSize)) { return ERROR_INVALID_PARAMETER; } if (*lpdwSize < sizeof (COMMCONFIG)) { *lpdwSize = sizeof (COMMCONFIG); return ERROR_INSUFFICIENT_BUFFER; } /* only "com1" - "com9" is allowed */ r = sizeof(comW) / sizeof(WCHAR); /* len of "com\0" */ lstrcpynW(szKeyName, lpszDevice, r); /* simulate a lstrcmpnW */ r--; if( lstrcmpiW(szKeyName, comW) || (lpszDevice[r] < '1') || (lpszDevice[r] > '9') || lpszDevice[r+1]) { return ERROR_BADKEY; } *lpdwSize = sizeof (COMMCONFIG); memset(lpCommConfig, 0 , sizeof (COMMCONFIG)); lpCommConfig->dwSize = sizeof (COMMCONFIG); lpCommConfig->wVersion = 1; lpCommConfig->dwProviderSubType = PST_RS232; r = RegConnectRegistryW(NULL, HKEY_LOCAL_MACHINE, &hKeyReg); if(r != ERROR_SUCCESS) return r; snprintfW(szKeyName, sizeof(szKeyName)/sizeof(WCHAR), fmt, lpszCommKey ,lpszDevice); r = RegOpenKeyW(hKeyReg, szKeyName, &hKeyPort); if(r == ERROR_SUCCESS) { dwSize = sizeof (DCB); dwType = 0; r = RegQueryValueExW( hKeyPort, lpszDCB, NULL, &dwType, (LPBYTE)&lpCommConfig->dcb, &dwSize); RegCloseKey(hKeyPort); if ((r!=ERROR_SUCCESS) || (dwType != REG_BINARY) || (dwSize != sizeof(DCB))) { RegCloseKey(hKeyReg); return ERROR_INVALID_PARAMETER; } } else { /* FIXME: default to a hardcoded commconfig */ lpCommConfig->dcb.DCBlength = sizeof(DCB); lpCommConfig->dcb.BaudRate = 9600; lpCommConfig->dcb.fBinary = TRUE; lpCommConfig->dcb.fParity = FALSE; lpCommConfig->dcb.ByteSize = 8; lpCommConfig->dcb.Parity = NOPARITY; lpCommConfig->dcb.StopBits = ONESTOPBIT; return ERROR_SUCCESS; } RegCloseKey(hKeyReg); return r; }
static void WinNT_PollThread(void *vparam) { CpuUsageThreadParams *param = (CpuUsageThreadParams*)vparam; DWORD dwBufferSize = 0, dwCount; BYTE *pBuffer = NULL; PERF_DATA_BLOCK *pPerfData = NULL; LONG res, lCount; PERF_OBJECT_TYPE *pPerfObj; PERF_COUNTER_DEFINITION *pPerfCounter; PERF_INSTANCE_DEFINITION *pPerfInstance; PERF_COUNTER_BLOCK *pPerfCounterBlock; DWORD dwObjectId, dwCounterId; WCHAR wszValueName[11], *pwszInstanceName; BYTE nCpuUsage; BOOL fSwitched, fFound, fIsFirst = FALSE; LARGE_INTEGER liPrevCounterValue = { 0 }, liCurrentCounterValue = { 0 }, liPrevPerfTime100nSec = { 0 }; /* init */ dwObjectId = 238; /*'Processor' object */ dwCounterId = 6; /* '% processor time' counter */ pwszInstanceName = L"_Total"; /* '_Total' instance */ _itot_s(dwObjectId, wszValueName, 10); fSwitched = WinNT_PerfStatsSwitch(_T("PerfOS"), FALSE); /* poll */ for (;;) { /* retrieve data for given object */ res = RegQueryValueExW(HKEY_PERFORMANCE_DATA, wszValueName, NULL, NULL, (BYTE*)pPerfData, &dwBufferSize); while (!pBuffer || res == ERROR_MORE_DATA) { pBuffer = (BYTE*)mir_realloc(pPerfData, dwBufferSize += 256); if (!pBuffer) break; pPerfData = (PERF_DATA_BLOCK*)pBuffer; res = RegQueryValueExW(HKEY_PERFORMANCE_DATA, wszValueName, NULL, NULL, pBuffer, &dwBufferSize); } if (res != ERROR_SUCCESS) break; /* find object in data */ fFound = FALSE; /* first object */ pPerfObj = (PERF_OBJECT_TYPE*)((BYTE*)pPerfData + pPerfData->HeaderLength); for (dwCount = 0; dwCount < pPerfData->NumObjectTypes; ++dwCount) { if (pPerfObj->ObjectNameTitleIndex == dwObjectId) { /* find counter in object data */ /* first counter */ pPerfCounter = (PERF_COUNTER_DEFINITION*)((BYTE*)pPerfObj + pPerfObj->HeaderLength); for (dwCount = 0; dwCount < (pPerfObj->NumCounters); ++dwCount) { if (pPerfCounter->CounterNameTitleIndex == dwCounterId) { /* find instance in counter data */ if (pPerfObj->NumInstances == PERF_NO_INSTANCES) { pPerfCounterBlock = (PERF_COUNTER_BLOCK*)((BYTE*)pPerfObj + pPerfObj->DefinitionLength); liCurrentCounterValue = *(LARGE_INTEGER*)((BYTE*)pPerfCounterBlock + pPerfCounter->CounterOffset); fFound = TRUE; } else { /* first instance */ pPerfInstance = (PERF_INSTANCE_DEFINITION*)((BYTE*)pPerfObj + pPerfObj->DefinitionLength); for (lCount = 0; lCount < (pPerfObj->NumInstances); ++lCount) { pPerfCounterBlock = (PERF_COUNTER_BLOCK*)((BYTE*)pPerfInstance + pPerfInstance->ByteLength); if (!mir_wstrcmpi(pwszInstanceName, (WCHAR*)((BYTE*)pPerfInstance + pPerfInstance->NameOffset))) { liCurrentCounterValue = *(LARGE_INTEGER*)((BYTE*)pPerfCounterBlock + pPerfCounter->CounterOffset); fFound = TRUE; break; } /* next instance */ pPerfInstance = (PPERF_INSTANCE_DEFINITION)((BYTE*)pPerfCounterBlock + pPerfCounterBlock->ByteLength); } } break; } /* next counter */ pPerfCounter = (PERF_COUNTER_DEFINITION*)((BYTE*)pPerfCounter + pPerfCounter->ByteLength); } break; } /* next object */ pPerfObj = (PERF_OBJECT_TYPE*)((BYTE*)pPerfObj + pPerfObj->TotalByteLength); } if (!fFound) break; /* calc val from data, we need two samplings * counter type: PERF_100NSEC_TIMER_INV * calc: time base=100Ns, value=100*(1-(data_diff)/(100NsTime_diff)) */ if (!fIsFirst) { nCpuUsage = (BYTE)((1.0 - (Li2Double(liCurrentCounterValue) - Li2Double(liPrevCounterValue)) / (Li2Double(pPerfData->PerfTime100nSec) - Li2Double(liPrevPerfTime100nSec)))*100.0 + 0.5); if (!CallBackAndWait(param, nCpuUsage)) break; } else fIsFirst = FALSE; /* store current sampling for next */ memcpy(&liPrevCounterValue, &liCurrentCounterValue, sizeof(LARGE_INTEGER)); memcpy(&liPrevPerfTime100nSec, &pPerfData->PerfTime100nSec, sizeof(LARGE_INTEGER)); } /* uninit */ if (pPerfData) mir_free(pPerfData); if (fSwitched) WinNT_PerfStatsSwitch(_T("PerfOS"), TRUE); /* return error for PollCpuUsage() if never succeeded */ if (param->hFirstEvent != NULL) SetEvent(param->hFirstEvent); mir_free(param); }
static VOID ModifyStatus(VOID) { LONG Ret; DWORD GlobalFlags; HKEY IFEOKey; WCHAR Buffer[11]; if (!OpenImageFileExecOptions(KEY_WRITE | KEY_READ, Image, &IFEOKey)) { return; } GlobalFlags = ReadSZFlagsFromRegistry(IFEOKey, L"GlobalFlag"); if (Set) { GlobalFlags |= FLG_HEAP_PAGE_ALLOCS; } else { GlobalFlags &= ~FLG_HEAP_PAGE_ALLOCS; } if (GlobalFlags != 0) { wsprintf(Buffer, L"0x%08x", GlobalFlags); Ret = RegSetValueExW(IFEOKey, L"GlobalFlag", 0, REG_SZ, (BYTE*)Buffer, (wcslen(Buffer) + 1) * sizeof(WCHAR)); if (Ret != ERROR_SUCCESS) { wprintf(L"MS: RegSetValueEx failed (%d)\n", Ret); } } else { Ret = RegDeleteValueW(IFEOKey, L"GlobalFlag"); if (Ret != ERROR_SUCCESS) { wprintf(L"MS: RegDeleteValue failed (%d)\n", Ret); } } if (Unset) { Ret = RegDeleteValueW(IFEOKey, L"PageHeapFlags"); if (Ret != ERROR_SUCCESS) { wprintf(L"MS: RegDeleteValue failed (%d)\n", Ret); } } else { DWORD PageHeapFlags; PageHeapFlags = ReadSZFlagsFromRegistry(IFEOKey, L"PageHeapFlags"); PageHeapFlags &= ~3; if (Full) { PageHeapFlags |= 1; } PageHeapFlags |= 2; wsprintf(Buffer, L"0x%x", PageHeapFlags); Ret = RegSetValueExW(IFEOKey, L"PageHeapFlags", 0, REG_SZ, (BYTE*)Buffer, (wcslen(Buffer) + 1) * sizeof(WCHAR)); if (Ret != ERROR_SUCCESS) { wprintf(L"MS: RegSetValueEx failed (%d)\n", Ret); } } if (Set) { DWORD Type, VerifierFlags, Len; VerifierFlags = 0; Len = VerifierFlags; if (RegQueryValueExW(IFEOKey, L"VerifierFlags", NULL, &Type, (BYTE *)&VerifierFlags, &Len) == ERROR_SUCCESS && Type == REG_DWORD && Len == sizeof(DWORD)) { VerifierFlags &= ~0x8001; /* RTL_VRF_FLG_FAST_FILL_HEAP | RTL_VRF_FLG_FULL_PAGE_HEAP */ } else { VerifierFlags = 0; } if (Full) { VerifierFlags |= 1; /* RTL_VRF_FLG_FULL_PAGE_HEAP */ } else { VerifierFlags |= 0x8000; /* RTL_VRF_FLG_FAST_FILL_HEAP */ } Ret = RegSetValueExW(IFEOKey, L"VerifierFlags", 0, REG_DWORD, (const BYTE *)&VerifierFlags, sizeof(DWORD)); if (Ret != ERROR_SUCCESS) { wprintf(L"MS: RegSetValueEx failed (%d)\n", Ret); } } wprintf(L"path: %s\n", ImageExecOptionsString); wprintf(L"\t%s: page heap %s\n", Image, (Set ? L"enabled" : L"disabled")); HeapFree(GetProcessHeap(), 0, Buffer); RegCloseKey(IFEOKey); }
VOID AddResourceItems( IN PDEVADVPROP_INFO dap, IN HWND hWndDevList) { HKEY hKey; WCHAR szBuffer[100]; WCHAR szDetail[100]; BYTE szData[512]; DWORD dwSize; PCM_RESOURCE_LIST ResourceList; LONG Result; ULONG ItemCount = 0, Index; wsprintf(szBuffer, L"SYSTEM\\CurrentControlSet\\Enum\\%s\\LogConf", dap->szDeviceID); Result = RegOpenKeyExW(HKEY_LOCAL_MACHINE, szBuffer, 0, KEY_READ, &hKey); if (Result != ERROR_SUCCESS) { /* failed to open device instance log conf dir */ return; } dwSize = sizeof(szData); Result = RegQueryValueExW(hKey, L"BootConfig", NULL, NULL, szData, &dwSize); RegCloseKey(hKey); if (Result != ERROR_SUCCESS) { /* failed to query resources */ return; } ResourceList = (PCM_RESOURCE_LIST)szData; for (Index = 0; Index < ResourceList->List[0].PartialResourceList.Count; Index++) { PCM_PARTIAL_RESOURCE_DESCRIPTOR Descriptor = &ResourceList->List[0].PartialResourceList.PartialDescriptors[Index]; if (Descriptor->Type == CmResourceTypeInterrupt) { if (LoadString(hDllInstance, IDS_RESOURCE_INTERRUPT, szBuffer, sizeof(szBuffer) / sizeof(szBuffer[0]))) { wsprintf(szDetail, L"0x%08x (%d)", Descriptor->u.Interrupt.Level, Descriptor->u.Interrupt.Vector); InsertListItem(hWndDevList, ItemCount, szBuffer, szDetail); ItemCount++; } } else if (Descriptor->Type == CmResourceTypePort) { if (LoadString(hDllInstance, IDS_RESOURCE_PORT, szBuffer, sizeof(szBuffer) / sizeof(szBuffer[0]))) { wsprintf(szDetail, L"%08lx - %08lx", Descriptor->u.Port.Start.LowPart, Descriptor->u.Port.Start.LowPart + Descriptor->u.Port.Length - 1); InsertListItem(hWndDevList, ItemCount, szBuffer, szDetail); ItemCount++; } } else if (Descriptor->Type == CmResourceTypeMemory) { if (LoadString(hDllInstance, IDS_RESOURCE_MEMORY_RANGE, szBuffer, sizeof(szBuffer) / sizeof(szBuffer[0]))) { wsprintf(szDetail, L"%08I64x - %08I64x", Descriptor->u.Memory.Start.QuadPart, Descriptor->u.Memory.Start.QuadPart + Descriptor->u.Memory.Length - 1); InsertListItem(hWndDevList, ItemCount, szBuffer, szDetail); ItemCount++; } } else if (Descriptor->Type == CmResourceTypeDma) { if (LoadString(hDllInstance, IDS_RESOURCE_DMA, szBuffer, sizeof(szBuffer) / sizeof(szBuffer[0]))) { wsprintf(szDetail, L"%08ld", Descriptor->u.Dma.Channel); InsertListItem(hWndDevList, ItemCount, szBuffer, szDetail); ItemCount++; } } } }
static UINT ITERATE_FindRelatedProducts(MSIRECORD *rec, LPVOID param) { MSIPACKAGE *package = (MSIPACKAGE*)param; WCHAR product[GUID_SIZE]; DWORD index = 0; DWORD attributes = 0; DWORD sz = GUID_SIZE; LPCWSTR upgrade_code; HKEY hkey = 0; UINT rc = ERROR_SUCCESS; MSIRECORD *uirow; upgrade_code = MSI_RecordGetString(rec,1); rc = MSIREG_OpenUpgradeCodesKey(upgrade_code, &hkey, FALSE); if (rc != ERROR_SUCCESS) return ERROR_SUCCESS; uirow = MSI_CreateRecord(1); attributes = MSI_RecordGetInteger(rec,5); while (rc == ERROR_SUCCESS) { rc = RegEnumValueW(hkey, index, product, &sz, NULL, NULL, NULL, NULL); TRACE("Looking at (%li) %s\n",index,debugstr_w(product)); if (rc == ERROR_SUCCESS) { WCHAR productid[GUID_SIZE]; LPCWSTR ver; LPCWSTR language; LPCWSTR action_property; DWORD check = 0x00000000; DWORD comp_ver = 0x00000000; DWORD sz = 0x100; HKEY hukey; INT r; unsquash_guid(product,productid); rc = MSIREG_OpenUserProductsKey(productid, &hukey, FALSE); if (rc != ERROR_SUCCESS) { rc = ERROR_SUCCESS; index ++; continue; } sz = sizeof(DWORD); RegQueryValueExW(hukey, INSTALLPROPERTY_VERSIONW, NULL, NULL, (LPBYTE)&check, &sz); /* check min */ ver = MSI_RecordGetString(rec,2); comp_ver = msi_version_str_to_dword(ver); r = check - comp_ver; if (r < 0 || (r == 0 && !(attributes & msidbUpgradeAttributesVersionMinInclusive))) { RegCloseKey(hukey); index ++; continue; } /* check max */ ver = MSI_RecordGetString(rec,3); comp_ver = msi_version_str_to_dword(ver); r = check - comp_ver; if (r > 0 || (r == 0 && !(attributes & msidbUpgradeAttributesVersionMaxInclusive))) { RegCloseKey(hukey); index ++; continue; } /* check language*/ sz = sizeof(DWORD); RegQueryValueExW(hukey, INSTALLPROPERTY_LANGUAGEW, NULL, NULL, (LPBYTE)&check, &sz); RegCloseKey(hukey); language = MSI_RecordGetString(rec,4); TRACE("Checking languages 0x%lx and %s\n", check, debugstr_w(language)); if (!check_language(check, language, attributes)) { index ++; continue; } action_property = MSI_RecordGetString(rec,7); append_productcode(package,action_property,productid); ui_actiondata(package,szFindRelatedProducts,uirow); } index ++; } RegCloseKey(hkey); msiobj_release( &uirow->hdr); return ERROR_SUCCESS; }
void RegElement::read() { string_value_.clear(); dword_value_ = 0; HKEY parent_key; LONG result = openKey(root_, path_, &parent_key); if (result != ERROR_SUCCESS) { return; } const std::wstring std_name = name_.toStdWString(); DWORD len; // get value size result = RegQueryValueExW (parent_key, std_name.c_str(), NULL, /* reserved */ &type_, /* output type */ NULL, /* output data */ &len); /* output length */ if (result != ERROR_SUCCESS) { RegCloseKey(parent_key); return; } // get value #ifndef UTILS_CXX11_MODE std::vector<wchar_t> buf; #else utils::WBufferArray buf; #endif buf.resize(len); result = RegQueryValueExW (parent_key, std_name.c_str(), NULL, /* reserved */ &type_, /* output type */ (LPBYTE)&buf[0], /* output data */ &len); /* output length */ buf.resize(len); if (result != ERROR_SUCCESS) { RegCloseKey(parent_key); return; } switch (type_) { case REG_EXPAND_SZ: case REG_SZ: { // expand environment strings wchar_t expanded_buf[MAX_PATH]; DWORD size = ExpandEnvironmentStringsW(&buf[0], expanded_buf, MAX_PATH); if (size == 0 || size > MAX_PATH) string_value_ = QString::fromWCharArray(&buf[0], buf.size()); else string_value_ = QString::fromWCharArray(expanded_buf, size); } break; case REG_NONE: case REG_BINARY: string_value_ = QString::fromWCharArray(&buf[0], buf.size() / 2); break; case REG_DWORD_BIG_ENDIAN: case REG_DWORD: if (buf.size() != sizeof(int)) return; memcpy((char*)&dword_value_, buf.data(), sizeof(int)); break; case REG_QWORD: { if (buf.size() != sizeof(int)) return; qint64 value; memcpy((char*)&value, buf.data(), sizeof(int)); dword_value_ = (int)value; break; } case REG_MULTI_SZ: default: break; } RegCloseKey(parent_key); // workaround with a bug string_value_ = QString::fromUtf8(string_value_.toUtf8()); return; }
int uv_cpu_info(uv_cpu_info_t** cpu_infos_ptr, int* cpu_count_ptr) { uv_cpu_info_t* cpu_infos; SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION* sppi; DWORD sppi_size; SYSTEM_INFO system_info; DWORD cpu_count, r, i; NTSTATUS status; ULONG result_size; int err; uv_cpu_info_t* cpu_info; cpu_infos = NULL; cpu_count = 0; sppi = NULL; uv__once_init(); GetSystemInfo(&system_info); cpu_count = system_info.dwNumberOfProcessors; cpu_infos = uv__calloc(cpu_count, sizeof *cpu_infos); if (cpu_infos == NULL) { err = ERROR_OUTOFMEMORY; goto error; } sppi_size = cpu_count * sizeof(*sppi); sppi = uv__malloc(sppi_size); if (sppi == NULL) { err = ERROR_OUTOFMEMORY; goto error; } status = pNtQuerySystemInformation(SystemProcessorPerformanceInformation, sppi, sppi_size, &result_size); if (!NT_SUCCESS(status)) { err = pRtlNtStatusToDosError(status); goto error; } assert(result_size == sppi_size); for (i = 0; i < cpu_count; i++) { WCHAR key_name[128]; HKEY processor_key; DWORD cpu_speed; DWORD cpu_speed_size = sizeof(cpu_speed); WCHAR cpu_brand[256]; DWORD cpu_brand_size = sizeof(cpu_brand); size_t len; len = _snwprintf(key_name, ARRAY_SIZE(key_name), L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\%d", i); assert(len > 0 && len < ARRAY_SIZE(key_name)); r = RegOpenKeyExW(HKEY_LOCAL_MACHINE, key_name, 0, KEY_QUERY_VALUE, &processor_key); if (r != ERROR_SUCCESS) { err = GetLastError(); goto error; } if (RegQueryValueExW(processor_key, L"~MHz", NULL, NULL, (BYTE*) &cpu_speed, &cpu_speed_size) != ERROR_SUCCESS) { err = GetLastError(); RegCloseKey(processor_key); goto error; } if (RegQueryValueExW(processor_key, L"ProcessorNameString", NULL, NULL, (BYTE*) &cpu_brand, &cpu_brand_size) != ERROR_SUCCESS) { err = GetLastError(); RegCloseKey(processor_key); goto error; } RegCloseKey(processor_key); cpu_info = &cpu_infos[i]; cpu_info->speed = cpu_speed; cpu_info->cpu_times.user = sppi[i].UserTime.QuadPart / 10000; cpu_info->cpu_times.sys = (sppi[i].KernelTime.QuadPart - sppi[i].IdleTime.QuadPart) / 10000; cpu_info->cpu_times.idle = sppi[i].IdleTime.QuadPart / 10000; cpu_info->cpu_times.irq = sppi[i].InterruptTime.QuadPart / 10000; cpu_info->cpu_times.nice = 0; len = WideCharToMultiByte(CP_UTF8, 0, cpu_brand, cpu_brand_size / sizeof(WCHAR), NULL, 0, NULL, NULL); if (len == 0) { err = GetLastError(); goto error; } assert(len > 0); /* Allocate 1 extra byte for the null terminator. */ cpu_info->model = uv__malloc(len + 1); if (cpu_info->model == NULL) { err = ERROR_OUTOFMEMORY; goto error; } if (WideCharToMultiByte(CP_UTF8, 0, cpu_brand, cpu_brand_size / sizeof(WCHAR), cpu_info->model, len, NULL, NULL) == 0) { err = GetLastError(); goto error; } /* Ensure that cpu_info->model is null terminated. */ cpu_info->model[len] = '\0'; } uv__free(sppi); *cpu_count_ptr = cpu_count; *cpu_infos_ptr = cpu_infos; return 0; error: /* This is safe because the cpu_infos array is zeroed on allocation. */ for (i = 0; i < cpu_count; i++) uv__free(cpu_infos[i].model); uv__free(cpu_infos); uv__free(sppi); return uv_translate_sys_error(err); }
static BOOL pendingRename() { static const WCHAR ValueName[] = {'P','e','n','d','i','n','g', 'F','i','l','e','R','e','n','a','m','e', 'O','p','e','r','a','t','i','o','n','s',0}; static const WCHAR SessionW[] = { 'S','y','s','t','e','m','\\', 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\', 'C','o','n','t','r','o','l','\\', 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0}; WCHAR *buffer=NULL; const WCHAR *src=NULL, *dst=NULL; DWORD dataLength=0; HKEY hSession=NULL; DWORD res; printf("Entered\n"); if ((res=RegOpenKeyExW(HKEY_LOCAL_MACHINE, SessionW, 0, KEY_ALL_ACCESS, &hSession)) !=ERROR_SUCCESS) { if (res==ERROR_FILE_NOT_FOUND) { printf("The key was not found - skipping\n"); res=TRUE; } else { printf("Couldn't open key, error %ld\n", res); res=FALSE; } goto end; } res=RegQueryValueExW(hSession, ValueName, NULL, NULL /* The value type does not really interest us, as it is not truely a REG_MULTI_SZ anyways */, NULL, &dataLength); if (res==ERROR_FILE_NOT_FOUND) { /* No value - nothing to do. Great! */ printf("Value not present - nothing to rename\n"); res=TRUE; goto end; } if (res!=ERROR_SUCCESS) { printf("Couldn't query value's length (%ld)\n", res); res=FALSE; goto end; } buffer=malloc(dataLength); if (buffer==NULL) { printf("Couldn't allocate %lu bytes for the value\n", dataLength); res=FALSE; goto end; } res=RegQueryValueExW(hSession, ValueName, NULL, NULL, (LPBYTE)buffer, &dataLength); if (res!=ERROR_SUCCESS) { printf("Couldn't query value after successfully querying before (%lu),\n" "please report to [email protected]\n", res); res=FALSE; goto end; } /* Make sure that the data is long enough and ends with two NULLs. This * simplifies the code later on. */ if (dataLength<2*sizeof(buffer[0]) || buffer[dataLength/sizeof(buffer[0])-1]!='\0' || buffer[dataLength/sizeof(buffer[0])-2]!='\0') { printf("Improper value format - doesn't end with NULL\n"); res=FALSE; goto end; } for(src=buffer; (src-buffer)*sizeof(src[0])<dataLength && *src!='\0'; src=dst+lstrlenW(dst)+1) { DWORD dwFlags=0; printf("processing next command\n"); dst=src+lstrlenW(src)+1; /* We need to skip the \??\ header */ if (src[0]=='\\' && src[1]=='?' && src[2]=='?' && src[3]=='\\') src+=4; if (dst[0]=='!') { dwFlags|=MOVEFILE_REPLACE_EXISTING; dst++; } if (dst[0]=='\\' && dst[1]=='?' && dst[2]=='?' && dst[3]=='\\') dst+=4; if (*dst!='\0') { /* Rename the file */ MoveFileExW(src, dst, dwFlags); } else { /* Delete the file or directory */ res = GetFileAttributesW (src); if (res != (DWORD)-1) { if ((res&FILE_ATTRIBUTE_DIRECTORY)==0) { /* It's a file */ DeleteFileW(src); } else { /* It's a directory */ RemoveDirectoryW(src); } } else { printf("couldn't get file attributes (%ld)\n", GetLastError()); } } } if ((res=RegDeleteValueW(hSession, ValueName))!=ERROR_SUCCESS) { printf("Error deleting the value (%lu)\n", GetLastError()); res=FALSE; } else res=TRUE; end: if (buffer!=NULL) free(buffer); if (hSession!=NULL) RegCloseKey(hSession); return res; }
static HRESULT WINAPI DEVENUM_IPropertyBag_Read( LPPROPERTYBAG iface, LPCOLESTR pszPropName, VARIANT* pVar, IErrorLog* pErrorLog) { LPVOID pData = NULL; DWORD received; DWORD type = 0; RegPropBagImpl *This = impl_from_IPropertyBag(iface); HRESULT res = S_OK; LONG reswin32; TRACE("(%p)->(%s, %p, %p)\n", This, debugstr_w(pszPropName), pVar, pErrorLog); if (!pszPropName || !pVar) return E_POINTER; reswin32 = RegQueryValueExW(This->hkey, pszPropName, NULL, NULL, NULL, &received); res = HRESULT_FROM_WIN32(reswin32); if (SUCCEEDED(res)) { pData = HeapAlloc(GetProcessHeap(), 0, received); /* work around a GCC bug that occurs here unless we use the reswin32 variable as well */ reswin32 = RegQueryValueExW(This->hkey, pszPropName, NULL, &type, pData, &received); res = HRESULT_FROM_WIN32(reswin32); } if (SUCCEEDED(res)) { res = E_INVALIDARG; /* assume we cannot coerce into right type */ TRACE("Read %d bytes (%s)\n", received, type == REG_SZ ? debugstr_w(pData) : "binary data"); switch (type) { case REG_SZ: switch (V_VT(pVar)) { case VT_LPWSTR: V_UNION(pVar, bstrVal) = CoTaskMemAlloc(received); memcpy(V_UNION(pVar, bstrVal), pData, received); res = S_OK; break; case VT_EMPTY: V_VT(pVar) = VT_BSTR; /* fall through */ case VT_BSTR: V_UNION(pVar, bstrVal) = SysAllocStringLen(pData, received/sizeof(WCHAR) - 1); res = S_OK; break; } break; case REG_DWORD: TRACE("REG_DWORD: %x\n", *(DWORD *)pData); switch (V_VT(pVar)) { case VT_EMPTY: V_VT(pVar) = VT_I4; /* fall through */ case VT_I4: case VT_UI4: V_UNION(pVar, ulVal) = *(DWORD *)pData; res = S_OK; break; } break; case REG_BINARY: { SAFEARRAYBOUND bound; void * pArrayElements; bound.lLbound = 0; bound.cElements = received; TRACE("REG_BINARY: len = %d\n", received); switch (V_VT(pVar)) { case VT_EMPTY: V_VT(pVar) = VT_ARRAY | VT_UI1; /* fall through */ case VT_ARRAY | VT_UI1: if (!(V_UNION(pVar, parray) = SafeArrayCreate(VT_UI1, 1, &bound))) res = E_OUTOFMEMORY; else res = S_OK; break; } if (res == E_INVALIDARG) break; res = SafeArrayAccessData(V_UNION(pVar, parray), &pArrayElements); if (FAILED(res)) break; CopyMemory(pArrayElements, pData, received); res = SafeArrayUnaccessData(V_UNION(pVar, parray)); break; } } if (res == E_INVALIDARG) FIXME("Variant type %x not supported for regtype %x\n", V_VT(pVar), type); } HeapFree(GetProcessHeap(), 0, pData); TRACE("<- %x\n", res); return res; }
LONG WINAPI MultiSzQuery( PMULTI_SZ pMultiSz, HKEY hKey, LPCWSTR pwszValueName ) { LONG lResult; DWORD dwType, cbData; LPBYTE lpData; /* Initialize the MULTI_SZ. */ MultiSzInit(pMultiSz); /* Compute the size of the value. */ cbData = 0; lResult = RegQueryValueExW( hKey, pwszValueName, NULL, &dwType, NULL, &cbData ); if (lResult != NO_ERROR) { return lResult; } if (dwType != REG_MULTI_SZ) { return ERROR_INVALID_DATA; } /* Allocate a buffer to hold the MULTI_SZ. */ lpData = RadiusAlloc(cbData); /* Get the value. */ lResult = RegQueryValueExW( hKey, pwszValueName, NULL, &dwType, lpData, &cbData ); if (lResult != NO_ERROR) { RadiusFree(lpData); return lResult; } if (dwType != REG_MULTI_SZ) { RadiusFree(lpData); return ERROR_INVALID_DATA; } /* Store the result. */ pMultiSz->pwszValue = (LPWSTR)lpData; pMultiSz->nChar = cbData / sizeof(WCHAR); return NO_ERROR; }
static VOID BuildVolatileEnvironment(IN PWLSESSION Session, IN HKEY hKeyCurrentUser) { WCHAR szPath[MAX_PATH + 1]; LPCWSTR wstr; SIZE_T size; WCHAR szEnvKey[MAX_PATH]; WCHAR szEnvValue[1024]; SIZE_T length; LPWSTR eqptr, endptr; DWORD dwDisp; LONG lError; HKEY hKeyVolatileEnv; HKEY hKeyShellFolders; DWORD dwType; DWORD dwSize; /* Create the 'Volatile Environment' key */ lError = RegCreateKeyExW(hKeyCurrentUser, L"Volatile Environment", 0, NULL, REG_OPTION_VOLATILE, KEY_WRITE, NULL, &hKeyVolatileEnv, &dwDisp); if (lError != ERROR_SUCCESS) { WARN("WL: RegCreateKeyExW() failed to create the volatile environment key (Error: %ld)\n", lError); return; } /* Parse the environment variables and add them to the volatile environment key */ if (Session->Profile->dwType == WLX_PROFILE_TYPE_V2_0 && Session->Profile->pszEnvironment != NULL) { wstr = Session->Profile->pszEnvironment; while (*wstr != UNICODE_NULL) { size = wcslen(wstr) + 1; eqptr = wcschr(wstr, L'='); if (eqptr != NULL) { endptr = eqptr; endptr--; while (iswspace(*endptr)) endptr--; length = (SIZE_T)(endptr - wstr + 1); wcsncpy(szEnvKey, wstr, length); szEnvKey[length] = 0; eqptr++; while (iswspace(*eqptr)) eqptr++; wcscpy(szEnvValue, eqptr); RegSetValueExW(hKeyVolatileEnv, szEnvKey, 0, REG_SZ, (LPBYTE)szEnvValue, (wcslen(szEnvValue) + 1) * sizeof(WCHAR)); } wstr += size; } } /* Set the 'APPDATA' environment variable */ lError = RegOpenKeyExW(hKeyCurrentUser, L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", 0, KEY_READ, &hKeyShellFolders); if (lError == ERROR_SUCCESS) { dwSize = (MAX_PATH + 1) * sizeof(WCHAR); lError = RegQueryValueExW(hKeyShellFolders, L"AppData", NULL, &dwType, (LPBYTE)szPath, &dwSize); if (lError == ERROR_SUCCESS) { TRACE("APPDATA path: %S\n", szPath); RegSetValueExW(hKeyVolatileEnv, L"APPDATA", 0, REG_SZ, (LPBYTE)szPath, (wcslen(szPath) + 1) * sizeof(WCHAR)); } RegCloseKey(hKeyShellFolders); } RegCloseKey(hKeyVolatileEnv); }
/*********************************************************************** * do_reg_operation * * Perform an add/delete registry operation depending on the flags. */ static BOOLEAN do_reg_operation(HANDLE KeyHandle, PUNICODE_STRING ValueName, PINFCONTEXT Context, ULONG Flags) { WCHAR EmptyStr = (WCHAR)0; ULONG Type; ULONG Size; if (Flags & FLG_ADDREG_DELVAL) /* deletion */ { #if 0 if (ValueName) { RegDeleteValueW( KeyHandle, ValueName ); } else { RegDeleteKeyW( KeyHandle, NULL ); } #endif return TRUE; } if (Flags & FLG_ADDREG_KEYONLY) return TRUE; #if 0 if (Flags & (FLG_ADDREG_NOCLOBBER | FLG_ADDREG_OVERWRITEONLY)) { BOOL exists = !RegQueryValueExW( hkey, value, NULL, NULL, NULL, NULL ); if (exists && (flags & FLG_ADDREG_NOCLOBBER)) return TRUE; if (!exists & (flags & FLG_ADDREG_OVERWRITEONLY)) return TRUE; } #endif switch (Flags & FLG_ADDREG_TYPE_MASK) { case FLG_ADDREG_TYPE_SZ: Type = REG_SZ; break; case FLG_ADDREG_TYPE_MULTI_SZ: Type = REG_MULTI_SZ; break; case FLG_ADDREG_TYPE_EXPAND_SZ: Type = REG_EXPAND_SZ; break; case FLG_ADDREG_TYPE_BINARY: Type = REG_BINARY; break; case FLG_ADDREG_TYPE_DWORD: Type = REG_DWORD; break; case FLG_ADDREG_TYPE_NONE: Type = REG_NONE; break; default: Type = Flags >> 16; break; } if (!(Flags & FLG_ADDREG_BINVALUETYPE) || (Type == REG_DWORD && SetupGetFieldCount (Context) == 5)) { PWCHAR Str = NULL; if (Type == REG_MULTI_SZ) { if (!SetupGetMultiSzFieldW (Context, 5, NULL, 0, &Size)) Size = 0; if (Size) { Str = (WCHAR*) RtlAllocateHeap (ProcessHeap, 0, Size * sizeof(WCHAR)); if (Str == NULL) return FALSE; SetupGetMultiSzFieldW (Context, 5, Str, Size, NULL); } if (Flags & FLG_ADDREG_APPEND) { if (Str == NULL) return TRUE; // append_multi_sz_value( hkey, value, str, size ); RtlFreeHeap (ProcessHeap, 0, Str); return TRUE; } /* else fall through to normal string handling */ } else { if (!SetupGetStringFieldW (Context, 5, NULL, 0, &Size)) Size = 0; if (Size) { Str = (WCHAR*) RtlAllocateHeap (ProcessHeap, 0, Size * sizeof(WCHAR)); if (Str == NULL) return FALSE; SetupGetStringFieldW (Context, 5, Str, Size, NULL); } } if (Type == REG_DWORD) { ULONG dw = Str ? wcstol (Str, NULL, 0) : 0; DPRINT("setting dword %wZ to %lx\n", ValueName, dw); #ifdef __ODYSSEY__ NtSetValueKey (KeyHandle, ValueName, 0, Type, (PVOID)&dw, sizeof(ULONG)); #else RegSetValueExW(KeyHandle, ValueName, 0, Type, (const UCHAR*)&dw, sizeof(ULONG)); #endif } else { DPRINT("setting value %wZ to %S\n", ValueName, Str); if (Str) { #ifdef __ODYSSEY__ NtSetValueKey (KeyHandle, ValueName, 0, Type, (PVOID)Str, Size * sizeof(WCHAR)); #else RegSetValueExW(KeyHandle, ValueName, 0, Type, (const UCHAR*)Str, Size * sizeof(WCHAR)); #endif } else { #ifdef __ODYSSEY__ NtSetValueKey (KeyHandle, ValueName, 0, Type, (PVOID)&EmptyStr, sizeof(WCHAR)); #else RegSetValueExW(KeyHandle, ValueName, 0, Type, (const UCHAR*)&EmptyStr, sizeof(WCHAR)); #endif } } RtlFreeHeap (ProcessHeap, 0, Str); } else /* get the binary data */ { PUCHAR Data = NULL; if (!SetupGetBinaryField (Context, 5, NULL, 0, &Size)) Size = 0; if (Size) { Data = (unsigned char*) RtlAllocateHeap (ProcessHeap, 0, Size); if (Data == NULL) return FALSE; DPRINT("setting binary data %wZ len %lu\n", ValueName, Size); SetupGetBinaryField (Context, 5, Data, Size, NULL); } #ifdef __ODYSSEY__ NtSetValueKey (KeyHandle, ValueName, 0, Type, (PVOID)Data, Size); #else RegSetValueExW(KeyHandle, ValueName, 0, Type, (const UCHAR*)Data, Size); #endif RtlFreeHeap (ProcessHeap, 0, Data); } return TRUE; }
///////////////////////////////////////////////////////// // // GetComponentInfo // // This helper function, provided with a component // ProgId, gathers the component's name and version // info and formats them into output strings // // Parameters: // CLSID clsid : [in] component's CLSID // SInfo& info : [in, out] a structure of buffers // to get the formatted strings into // // Return Values: // TRUE, if the function succeeds // FALSE, if it fails // ///////////////////////////////////////////////////////// BOOL GetComponentInfo(CLSID clsid, SInfo& info) { info.wchName[0] = info.wchVersion[0] = 0; // Format Registry Key string WCHAR wszKey[45] = L"CLSID\\"; // the key buffer should be large enough for a string // like "CLSID\{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}" // Convert CLSID to String UINT uPos = lstrlenW(wszKey); if (0 == StringFromGUID2(clsid, &wszKey[uPos], countof(wszKey) - uPos)) return FALSE; wszKey[countof(wszKey)-1] = 0; // Open key to find path of application HKEY hKeyRoot; if (RegOpenKeyExW(HKEY_CLASSES_ROOT, wszKey, 0, KEY_READ, &hKeyRoot) != ERROR_SUCCESS) return FALSE; // Query value of key to get the name of the component ULONG cSize = sizeof(info.wchName); // size of the buffer in bytes if (RegQueryValueExW(hKeyRoot, NULL, NULL, NULL, (BYTE*)info.wchName, &cSize) != ERROR_SUCCESS) { RegCloseKey(hKeyRoot); return FALSE; } info.wchName[countof(info.wchName) - 1] = 0; // Open the version info subkey UINT iVersionMaxLen = countof(info.wchVersion); HKEY hKey = NULL; if (RegOpenKeyExW(hKeyRoot, L"Version", 0, KEY_READ, &hKey) == ERROR_SUCCESS) { const WCHAR* pcwsVersion = L"version "; UINT iLen = lstrlenW(pcwsVersion); // Query value of key to get version string if (iLen < iVersionMaxLen) { // copy the "version " string including terminating 0 wcsncpy_s(info.wchVersion, iVersionMaxLen, pcwsVersion, iLen + 1); // get the version string cSize = (iVersionMaxLen - iLen) * sizeof(WCHAR); // the size is in bytes if (RegQueryValueExW(hKey, NULL, NULL, NULL, (BYTE*)&info.wchVersion[iLen], &cSize) == ERROR_SUCCESS) { info.wchVersion[iVersionMaxLen-1] = 0; } } RegCloseKey(hKey); } // Open InprocServer32 subkey to get the path to the component if (RegOpenKeyExW(hKeyRoot, L"InprocServer32", 0, KEY_READ, &hKey) == ERROR_SUCCESS) { // Query value of key to get the path string WCHAR wchPath[MAX_PATH]; cSize = sizeof(wchPath); if (RegQueryValueExW(hKey, NULL, NULL, NULL, (BYTE*)wchPath, &cSize) == ERROR_SUCCESS) { // Get the build number from the file version info DWORD dwHandle = 0; cSize = GetFileVersionInfoSizeW(wchPath, &dwHandle); // returns the size in bytes WCHAR* pwchFileVerInfo = NULL; if (cSize) { pwchFileVerInfo = (WCHAR*)new BYTE[cSize]; } if (NULL != pwchFileVerInfo) { // Retrieve version information for the file if (GetFileVersionInfoW(wchPath, 0, cSize, pwchFileVerInfo)) { // Get the default language id and code page number UINT *pdwLang; UINT cch = 0; if (VerQueryValueW(pwchFileVerInfo, L"\\VarFileInfo\\Translation", (void**)&pdwLang, &cch) == TRUE) { // Read the file description for the language and code page. const int MAX_SUBBLOCK = 40; WCHAR wchSubBlock[MAX_SUBBLOCK]; // large enough for the string StringCchPrintfExW(wchSubBlock, MAX_SUBBLOCK, NULL, NULL, STRSAFE_NULL_ON_FAILURE, L"\\StringFileInfo\\%04x%04x\\FileVersion", LOWORD(*pdwLang), HIWORD(*pdwLang)); WCHAR* pwchBuildVer = NULL; if ((VerQueryValueW(pwchFileVerInfo, wchSubBlock, (void**)&pwchBuildVer, &cch) == TRUE) && (NULL != pwchBuildVer)) { // Format the version string UINT iLen = (UINT)lstrlenW(info.wchVersion); if (0 < iLen) { if (iLen < iVersionMaxLen) { const WCHAR* pcwsBuild = L", build "; wcsncpy_s(info.wchVersion + iLen, iVersionMaxLen - iLen, pcwsBuild, iVersionMaxLen - iLen); iLen += lstrlenW(pcwsBuild); if (iLen < iVersionMaxLen) { wcsncpy_s(info.wchVersion + iLen, iVersionMaxLen - iLen, pwchBuildVer, iVersionMaxLen - iLen); } } } else { wcsncpy_s(info.wchVersion, iVersionMaxLen, pwchBuildVer, iVersionMaxLen); } info.wchVersion[iVersionMaxLen-1] = 0; } } } delete [] pwchFileVerInfo; } } RegCloseKey(hKey); } RegCloseKey(hKeyRoot); return TRUE; }
//--------------------------------------------------------------------------- HRESULT GetRegistryKeyValue( HKEY RootKey, const wchar_t * KeyName, const wchar_t * Name, VARIANT * Result) { HRESULT hr = E_FAIL; HKEY hkey; DWORD err; err = RegOpenKeyExW(RootKey,KeyName,0,KEY_READ,&hkey); if( err == ERROR_SUCCESS ){ DWORD ValueType, ValueSize, sLen; err = RegQueryValueExW(hkey,Name,NULL,&ValueType,NULL,&ValueSize); if( err == ERROR_SUCCESS ){ PBYTE pValueData = (PBYTE) malloc(ValueSize); if( pValueData == NULL ){ err = ERROR_NOT_ENOUGH_MEMORY; } else { err = RegQueryValueExW(hkey,Name,NULL,&ValueType,pValueData,&ValueSize); if( err == ERROR_SUCCESS ){ BSTR sValue = NULL; switch( ValueType ){ case REG_BINARY : break; case REG_DWORD : if( SUCCEEDED(VariantChangeTypeEx(Result,Result,0,0,VT_I4)) ){ V_I4(Result) = *(DWORD *) pValueData; hr = S_OK; } break; case REG_EXPAND_SZ : sLen = ExpandEnvironmentStringsW((LPCWSTR) pValueData,sValue,0); if( sLen == 0 ){ err = GetLastError(); } else { sValue = SysAllocStringLen(NULL,sLen - 1); if( sValue == NULL ){ err = ERROR_NOT_ENOUGH_MEMORY; } else { ExpandEnvironmentStringsW((LPCWSTR) pValueData,sValue,sLen); if( SUCCEEDED(VariantChangeTypeEx(Result,Result,0,0,VT_EMPTY)) ){ V_BSTR(Result) = sValue; V_VT(Result) = VT_BSTR; hr = S_OK; sValue = NULL; } SysFreeString(sValue); } } /*Val.resize(ExpandEnvironmentStringsW((LPCWSTR) pValueData,Val.c_str(),0) + 1); ExpandEnvironmentStringsW((LPCWSTR) pValueData,Val.c_str(),Val.strlen()); Val.resize(wcslen(Val.c_str()));*/ break; case REG_LINK : case REG_MULTI_SZ : case REG_NONE : case REG_RESOURCE_LIST : hr = E_FAIL; break; case REG_SZ : sLen = (DWORD) wcslen((LPCWSTR) pValueData); sValue = SysAllocStringLen(NULL,sLen); if( sValue == NULL ){ err = ERROR_NOT_ENOUGH_MEMORY; } else { if( SUCCEEDED(VariantChangeTypeEx(Result,Result,0,0,VT_EMPTY)) ){ V_BSTR(Result) = sValue; V_VT(Result) = VT_BSTR; hr = S_OK; sValue = NULL; } SysFreeString(sValue); } /*Val = (wchar_t *) pValueData;*/ break; } } free(pValueData); } } RegCloseKey(hkey); } SetLastError(err); return hr; }
static UINT ACTION_AppSearchReg(MSIPACKAGE *package, LPWSTR *appValue, MSISIGNATURE *sig) { static const WCHAR query[] = { 's','e','l','e','c','t',' ','*',' ', 'f','r','o','m',' ', 'R','e','g','L','o','c','a','t','o','r',' ', 'w','h','e','r','e',' ', 'S','i','g','n','a','t','u','r','e','_',' ','=',' ', '\'','%','s','\'',0}; LPWSTR keyPath = NULL, valueName = NULL; LPWSTR deformatted = NULL; LPWSTR ptr = NULL, end; int root, type; HKEY rootKey, key = NULL; DWORD sz = 0, regType; LPBYTE value = NULL; MSIRECORD *row; UINT rc; TRACE("%s\n", debugstr_w(sig->Name)); *appValue = NULL; row = MSI_QueryGetRecord( package->db, query, sig->Name ); if (!row) { TRACE("failed to query RegLocator for %s\n", debugstr_w(sig->Name)); return ERROR_SUCCESS; } root = MSI_RecordGetInteger(row,2); keyPath = msi_dup_record_field(row,3); valueName = msi_dup_record_field(row,4); type = MSI_RecordGetInteger(row,5); deformat_string(package, keyPath, &deformatted); switch (root) { case msidbRegistryRootClassesRoot: rootKey = HKEY_CLASSES_ROOT; break; case msidbRegistryRootCurrentUser: rootKey = HKEY_CURRENT_USER; break; case msidbRegistryRootLocalMachine: rootKey = HKEY_LOCAL_MACHINE; break; case msidbRegistryRootUsers: rootKey = HKEY_USERS; break; default: WARN("Unknown root key %d\n", root); goto end; } rc = RegOpenKeyW(rootKey, deformatted, &key); if (rc) { TRACE("RegOpenKeyW returned %d\n", rc); goto end; } rc = RegQueryValueExW(key, valueName, NULL, NULL, NULL, &sz); if (rc) { TRACE("RegQueryValueExW returned %d\n", rc); goto end; } /* FIXME: sanity-check sz before allocating (is there an upper-limit * on the value of a property?) */ value = msi_alloc( sz ); rc = RegQueryValueExW(key, valueName, NULL, ®Type, value, &sz); if (rc) { TRACE("RegQueryValueExW returned %d\n", rc); goto end; } /* bail out if the registry key is empty */ if (sz == 0) goto end; if ((regType == REG_SZ || regType == REG_EXPAND_SZ) && (ptr = strchrW((LPWSTR)value, '"')) && (end = strchrW(++ptr, '"'))) *end = '\0'; else ptr = (LPWSTR)value; switch (type & 0x0f) { case msidbLocatorTypeDirectory: rc = ACTION_SearchDirectory(package, sig, ptr, 0, appValue); break; case msidbLocatorTypeFileName: *appValue = app_search_file(ptr, sig); break; case msidbLocatorTypeRawValue: ACTION_ConvertRegValue(regType, value, sz, appValue); break; default: FIXME("unimplemented for type %d (key path %s, value %s)\n", type, debugstr_w(keyPath), debugstr_w(valueName)); } end: msi_free( value ); RegCloseKey( key ); msi_free( keyPath ); msi_free( valueName ); msi_free( deformatted ); msiobj_release(&row->hdr); return ERROR_SUCCESS; }
void GetInterfaceNameByIID(const GUID &aIID, BSTR *aName) { AssertPtrReturnVoid(aName); *aName = NULL; #if !defined(VBOX_WITH_XPCOM) LONG rc; LPOLESTR iidStr = NULL; if (StringFromIID(aIID, &iidStr) == S_OK) { HKEY ifaceKey; rc = RegOpenKeyExW(HKEY_CLASSES_ROOT, L"Interface", 0, KEY_QUERY_VALUE, &ifaceKey); if (rc == ERROR_SUCCESS) { HKEY iidKey; rc = RegOpenKeyExW(ifaceKey, iidStr, 0, KEY_QUERY_VALUE, &iidKey); if (rc == ERROR_SUCCESS) { /* determine the size and type */ DWORD sz, type; rc = RegQueryValueExW(iidKey, NULL, NULL, &type, NULL, &sz); if (rc == ERROR_SUCCESS && type == REG_SZ) { /* query the value to BSTR */ *aName = SysAllocStringLen(NULL, (sz + 1) / sizeof(TCHAR) + 1); rc = RegQueryValueExW(iidKey, NULL, NULL, NULL, (LPBYTE) *aName, &sz); if (rc != ERROR_SUCCESS) { SysFreeString(*aName); *aName = NULL; } } RegCloseKey(iidKey); } RegCloseKey(ifaceKey); } CoTaskMemFree(iidStr); } #else /* !defined (VBOX_WITH_XPCOM) */ nsresult rv; nsCOMPtr<nsIInterfaceInfoManager> iim = do_GetService(NS_INTERFACEINFOMANAGER_SERVICE_CONTRACTID, &rv); if (NS_SUCCEEDED(rv)) { nsCOMPtr<nsIInterfaceInfo> iinfo; rv = iim->GetInfoForIID(&aIID, getter_AddRefs(iinfo)); if (NS_SUCCEEDED(rv)) { const char *iname = NULL; iinfo->GetNameShared(&iname); char *utf8IName = NULL; if (RT_SUCCESS(RTStrCurrentCPToUtf8(&utf8IName, iname))) { PRTUTF16 utf16IName = NULL; if (RT_SUCCESS(RTStrToUtf16(utf8IName, &utf16IName))) { *aName = SysAllocString((OLECHAR *) utf16IName); RTUtf16Free(utf16IName); } RTStrFree(utf8IName); } } } #endif /* !defined (VBOX_WITH_XPCOM) */ }
/** * This function reads the configuration from the registry if it exists. * It is not an error if it doesn't exist. We will just use the default * values. * * @param configParams Points to the CONFIG_PARAMS structure to be filled * in. * * @return Success: Returns S_OK. * @return Failure: Returns HRESULT_CODE. */ HRESULT RegistryGetConfig( __inout PCONFIG_PARAMS configParams ) { HRESULT hr; LONG rcReg; HKEY hkey; TLevel(FUNC); TEnterMsg(("configParams=%p", configParams)); rcReg = RegOpenKeyW(HKEY_CURRENT_USER, REGSTR_PATH_NETTERM, &hkey); if (rcReg != ERROR_SUCCESS) { // // It's okay to fail. It could just mean we did not save the config // in the registry. // TWarn(("Failed to open registry key <%ws> (rc=%d).", REGSTR_PATH_NETTERM, rcReg)); rcReg = ERROR_SUCCESS; } else { DWORD dwType; DWORD dwSize; dwSize = sizeof(configParams->szRemoteAddr); if ((rcReg = RegQueryValueExW(hkey, REGSTR_VALUE_REMOTEADDR, NULL, &dwType, (LPBYTE)configParams->szRemoteAddr, &dwSize)) != ERROR_SUCCESS) { // // It's okay if the value doesn't exist. // TWarn(("Failed to get remote address from registry (rc=%d).", rcReg)); rcReg = ERROR_SUCCESS; } else if (dwType != REG_SZ) { rcReg = ERROR_INVALID_DATA; MsgPrintf(g_progName, MSGTYPE_ERR, rcReg, L"Invalid remote IP address."); } if (rcReg == ERROR_SUCCESS) { dwSize = sizeof(configParams->szRemotePort); if ((rcReg = RegQueryValueExW(hkey, REGSTR_VALUE_REMOTEPORT, NULL, &dwType, (LPBYTE)configParams->szRemotePort, &dwSize)) != ERROR_SUCCESS) { // // It's okay if the value doesn't exist. // TWarn(("Failed to get remote port from registry (rc=%d).", rcReg)); rcReg = ERROR_SUCCESS; } else if (dwType != REG_SZ) { rcReg = ERROR_INVALID_DATA; MsgPrintf(g_progName, MSGTYPE_ERR, rcReg, L"Invalid remote port."); } } if (rcReg == ERROR_SUCCESS) { dwSize = sizeof(configParams->szLocalPort); if ((rcReg = RegQueryValueExW(hkey, REGSTR_VALUE_LOCALPORT, NULL, &dwType, (LPBYTE)configParams->szLocalPort, &dwSize)) != ERROR_SUCCESS) { // // It's okay if the value doesn't exist. // TWarn(("Failed to get local port from registry (rc=%d).", rcReg)); rcReg = ERROR_SUCCESS; } else if (dwType != REG_SZ) { rcReg = ERROR_INVALID_DATA; MsgPrintf(g_progName, MSGTYPE_ERR, rcReg, L"Invalid local port."); } } RegCloseKey(hkey); } hr = HRESULT_FROM_WIN32(rcReg); TExitMsg(("=%x (remoteAddr=%ws,remotePort=%ws,localPort=%ws)", hr, configParams->szRemoteAddr, configParams->szRemotePort, configParams->szLocalPort)); return hr; } //RegistryGetConfig
static VOID StartShell(VOID) { WCHAR Shell[MAX_PATH]; TCHAR szMsg[RC_STRING_MAX_SIZE]; DWORD Type, Size; DWORD Value = 0; LONG rc; HKEY hKey; TRACE("()\n"); /* Safe Mode shell run */ rc = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\SafeBoot\\Option", 0, KEY_QUERY_VALUE, &hKey); if(rc == ERROR_SUCCESS) { Size = sizeof(Value); rc = RegQueryValueExW(hKey, L"UseAlternateShell", NULL, &Type, (LPBYTE)&Value, &Size); if(rc == ERROR_SUCCESS) { RegCloseKey(hKey); if(Type == REG_DWORD) { if(Value) { /* Safe Mode Alternate Shell required */ rc = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\SafeBoot", 0, KEY_READ, &hKey); if(rc == ERROR_SUCCESS) { Size = MAX_PATH * sizeof(WCHAR); rc = RegQueryValueExW(hKey, L"AlternateShell", NULL, &Type, (LPBYTE)Shell, &Size); if(rc == ERROR_SUCCESS) { RegCloseKey(hKey); if ((Type == REG_SZ) || (Type == REG_EXPAND_SZ)) { TRACE("Key located - %s\n", debugstr_w(Shell)); /* Try to run alternate shell */ if (TryToStartShell(Shell)) { TRACE("Alternate shell started (Safe Mode)\n"); return; } } else { WARN("Wrong type %lu (expected %u or %u)\n", Type, REG_SZ, REG_EXPAND_SZ); } } else { WARN("Alternate shell in Safe Mode required but not specified."); } } } } else { WARN("Wrong type %lu (expected %u)\n", Type, REG_DWORD); } } } /* Try to run shell in user key */ if (GetShell(Shell, HKEY_CURRENT_USER) && TryToStartShell(Shell)) { TRACE("Started shell from HKEY_CURRENT_USER\n"); return; } /* Try to run shell in local machine key */ if (GetShell(Shell, HKEY_LOCAL_MACHINE) && TryToStartShell(Shell)) { TRACE("Started shell from HKEY_LOCAL_MACHINE\n"); return; } /* Try default shell */ if (IsConsoleShell()) { if (GetSystemDirectory(Shell, MAX_PATH - 8)) wcscat(Shell, L"\\cmd.exe"); else wcscpy(Shell, L"cmd.exe"); } else { if (GetWindowsDirectory(Shell, MAX_PATH - 13)) wcscat(Shell, L"\\explorer.exe"); else wcscpy(Shell, L"explorer.exe"); } if (!TryToStartShell(Shell)) { WARN("Failed to start default shell %s\n", debugstr_w(Shell)); LoadString( GetModuleHandle(NULL), IDS_SHELL_FAIL, szMsg, sizeof(szMsg) / sizeof(szMsg[0])); MessageBox(0, szMsg, NULL, 0); } }