Example #1
0
DWORD WINAPI Inspection(LPVOID lpParameter)
{
	char szRoot[ROOT];
	wchar_t wszRoot[ROOT];

	szRoot[0] = (char)lpParameter;
	szRoot[1] = ':';
	szRoot[2] = '\\';
	szRoot[3] = '\0';

	/*
	Convert multibyte string to wide
	character string
	*/
	unsigned int uiConvertedChars = 0;
	mbstowcs_s(&uiConvertedChars, wszRoot, ROOT, szRoot, _TRUNCATE);

	HANDLE hDirectory = CreateFile(
		(LPCWSTR)wszRoot,
		FILE_LIST_DIRECTORY |
		GENERIC_READ,
		FILE_SHARE_READ |
		FILE_SHARE_WRITE |
		FILE_SHARE_DELETE,
		NULL,
		OPEN_EXISTING,
		FILE_FLAG_BACKUP_SEMANTICS,
		NULL
		);
	if (hDirectory != INVALID_HANDLE_VALUE)
		printf("%s Is being watched\n", szRoot);
	else
	{
		printf("Error %d\n", GetLastError());
		return 0;
	}
	while (true)
	{
		DWORD dwBuffer[BUFFER];
		LPVOID lpBuffer = &dwBuffer;
		DWORD dwBytesReturned;

		BOOL bResult = ReadDirectoryChangesW(
			hDirectory,
			lpBuffer,
			BUFFER,
			TRUE,
			FILE_NOTIFY_CHANGE_CREATION |
			FILE_NOTIFY_CHANGE_LAST_WRITE |
			FILE_NOTIFY_CHANGE_SIZE |
			FILE_NOTIFY_CHANGE_ATTRIBUTES |
			FILE_NOTIFY_CHANGE_DIR_NAME |
			FILE_NOTIFY_CHANGE_FILE_NAME,
			&dwBytesReturned,
			NULL,
			NULL
			);

		if (bResult)
		{
			bool bStop = false;
			PFILE_NOTIFY_INFORMATION pFileNotifyInformation = (PFILE_NOTIFY_INFORMATION)lpBuffer;
			while (!bStop)
			{
				if (pFileNotifyInformation->FileName != NULL)
				{
					DWORD dwError = GetLastError();
					wchar_t* pwszFileName = pFileNotifyInformation->FileName;
					pwszFileName[pFileNotifyInformation->FileNameLength / 2] = '\0';
					if (wcsstr(pwszFileName, L".txt") != NULL)
					{
						if (CheckAction(pFileNotifyInformation->Action))
						{
							wchar_t wszFullPath[MAX_PATH];
							wcscpy_s(wszFullPath, wszRoot);
							wcscat_s(wszFullPath, pwszFileName);
							wprintf(L"%s\n", wszFullPath);
							while (!DeleteFile(wszFullPath));
						}
					}
					pFileNotifyInformation += pFileNotifyInformation->NextEntryOffset;
					if (pFileNotifyInformation && pFileNotifyInformation->NextEntryOffset == NULL)
						bStop = true;
				}
				bStop = true;
			}
		}
	}
	CloseHandle(hDirectory);
	return 0;
}
Example #2
0
	int SzExtractFromBuf(const void* pBuf, unsigned int nBufLength, wchar_t* cUnPackPath, DWORD dwPathLength)
	{
		if(pBuf==NULL || nBufLength<=0)
			return 1;

		SRes res = SZ_OK;
		CBufInStream archiveStream;
		CLookToRead lookStream;
		CSzArEx db;
		ISzAlloc allocImp;
		ISzAlloc allocTempImp;
		const char *errorMessage = NULL;

		wchar_t path[MAX_PATH * 3 + 2] = {0};
		size_t pathLen = wcslen(cUnPackPath);
		wcscpy_s(path,MAX_PATH * 3 + 2, cUnPackPath);

		if (cUnPackPath[pathLen - 1] != '\\') 
		{ 
			wcscat_s(path, L"\\");
			pathLen = wcslen(path);
		}


		CrcGenerateTable();

		allocImp.Alloc = SzAlloc;
		allocImp.Free = SzFree;

		allocTempImp.Alloc = SzAllocTemp;
		allocTempImp.Free = SzFreeTemp;

		BufInStream_CreateVTable(&archiveStream);
		LookToRead_CreateVTable(&lookStream, False);

		
		if (InBuf_Init(&archiveStream.buf, pBuf, nBufLength) != 0)
		{
			errorMessage = "can not open input file";
			res = SZ_ERROR_FAIL;
		}
		else
		{
			UInt64 pos = 0;
			if (!FindSignature(&archiveStream.buf, &pos))
				res = SZ_ERROR_FAIL;
			else if (InBuf_Seek(&archiveStream.buf, (Int64 *)&pos, SZ_SEEK_SET) != 0)
				res = SZ_ERROR_FAIL;
			if (res != 0)
				errorMessage = "Can't find 7z archive";
		}

		if (res == SZ_OK)
		{
			lookStream.realStream = &archiveStream.s;
			LookToRead_Init(&lookStream);
		}

		SzArEx_Init(&db);
		if (res == SZ_OK)
		{
			res = SzArEx_Open(&db, &lookStream.s, &allocImp, &allocTempImp);
		}
		if (res == SZ_OK)
		{
			UInt32 executeFileIndex = (UInt32)(Int32)-1;
			UInt32 minPrice = 1 << 30;
			UInt32 i;
			UInt32 blockIndex = 0xFFFFFFFF; /* it can have any value before first call (if outBuffer = 0) */
			Byte *outBuffer = 0; /* it must be 0 before first call for each new archive. */
			size_t outBufferSize = 0;  /* it can have any value before first call (if outBuffer = 0) */

			for (i = 0; i < db.db.NumFiles; i++)
			{
				size_t offset = 0;
				size_t outSizeProcessed = 0;
				const CSzFileItem *f = db.db.Files + i;
				size_t len;
				wchar_t *temp;
				len = SzArEx_GetFileNameUtf16(&db, i, NULL);

				if (len >= MAX_PATH)
				{
					res = SZ_ERROR_FAIL;
					break;
				}

				temp = path + pathLen;

				SzArEx_GetFileNameUtf16(&db, i, reinterpret_cast<UInt16*>(temp));
				{
					res = SzArEx_Extract(&db, &lookStream.s, i,
						&blockIndex, &outBuffer, &outBufferSize,
						&offset, &outSizeProcessed,
						&allocImp, &allocTempImp);
					if (res != SZ_OK)
						break;
				}
				{
					CSzFile outFile;
					size_t processedSize;
					size_t j;
					size_t nameStartPos = 0;
					for (j = 0; temp[j] != 0; j++)
					{
						if (temp[j] == '/')
						{
							temp[j] = 0;
							MyCreateDir(path);
							temp[j] = CHAR_PATH_SEPARATOR;
							nameStartPos = j + 1;
						}
					}

					if (f->IsDir)
					{
						MyCreateDir(path);
						continue;
					}
					else
					{

						if (DoesFileOrDirExist(path))
						{
							errorMessage = "Duplicate file";
							res = SZ_ERROR_FAIL;
							break;
						}
						if (OutFile_OpenW(&outFile, path))
						{
							errorMessage = "Can't open output file";
							res = SZ_ERROR_FAIL;
							break;
						}
					}
					processedSize = outSizeProcessed;
					if (File_Write(&outFile, outBuffer + offset, &processedSize) != 0 || processedSize != outSizeProcessed)
					{
						errorMessage = "Can't write output file";
						res = SZ_ERROR_FAIL;
					}

#ifdef USE_WINDOWS_FILE
					if (f->MTimeDefined)
					{
						FILETIME mTime;
						mTime.dwLowDateTime = f->MTime.Low;
						mTime.dwHighDateTime = f->MTime.High;
						SetFileTime(outFile.handle, NULL, NULL, &mTime);
					}
#endif

					{
						SRes res2 = File_Close(&outFile);
						if (res != SZ_OK)
							break;
						if (res2 != SZ_OK)
						{
							res = res2;
							break;
						}
					}
#ifdef USE_WINDOWS_FILE
					if (f->AttribDefined)
						SetFileAttributesW(path, f->Attrib);
#endif
				}
			}
			IAlloc_Free(&allocImp, outBuffer);
		}
		SzArEx_Free(&db, &allocImp);

		if (res == SZ_OK)
		{
			_tcscpy_s(cUnPackPath, dwPathLength, path);
			return 0;
		}
		else
			return 1;
	}
HRESULT FindUserByName(IDirectorySearch *pSearchBase, //Container to search
					   LPOLESTR szFindUser, //Name of user to find.
					   IADs **ppUser) //Return a pointer to the user
{
    HRESULT hrObj = E_FAIL;
    HRESULT hr = E_FAIL;
	if ((!pSearchBase)||(!szFindUser))
		return E_INVALIDARG;
	//Create search filter
	LPOLESTR pszSearchFilter = NULL;
       LPOLESTR szADsPath = NULL;
	pszSearchFilter = new OLECHAR[MAX_PATH];
	szADsPath = new OLECHAR[MAX_PATH];
	if(pszSearchFilter == NULL || szADsPath == NULL)       
	{
		if ( pszSearchFilter )
			delete [] pszSearchFilter;
		if ( szADsPath )
			delete [] szADsPath;
		return  E_OUTOFMEMORY;
	}
	wcscpy_s(pszSearchFilter, MAX_PATH, L"(&(objectCategory=person)(objectClass=user)(cn=");
	wcscat_s(pszSearchFilter, MAX_PATH, szFindUser);
	wcscat_s(pszSearchFilter, MAX_PATH, L"))");
    //Search entire subtree from root.
	ADS_SEARCHPREF_INFO SearchPrefs;
	SearchPrefs.dwSearchPref = ADS_SEARCHPREF_SEARCH_SCOPE;
	SearchPrefs.vValue.dwType = ADSTYPE_INTEGER;
	SearchPrefs.vValue.Integer = ADS_SCOPE_SUBTREE;
    DWORD dwNumPrefs = 1;
	// COL for iterations
    ADS_SEARCH_COLUMN col;
    // Handle used for searching
    ADS_SEARCH_HANDLE hSearch;
	// Set the search preference
    hr = pSearchBase->SetSearchPreference( &SearchPrefs, dwNumPrefs);
    if (FAILED(hr))
        goto ret;
	// Set attributes to return
	CONST DWORD dwAttrNameSize = 1;
    LPOLESTR pszAttribute[dwAttrNameSize] = {L"ADsPath"};

    // Execute the search
    hr = pSearchBase->ExecuteSearch(pszSearchFilter,
		                          pszAttribute,
								  dwAttrNameSize,
								  &hSearch
								  );
	if (SUCCEEDED(hr))
	{    

    // Call IDirectorySearch::GetNextRow() to retrieve the next row 
    //of data
        while( pSearchBase->GetNextRow( hSearch) != S_ADS_NOMORE_ROWS )
		{
            // loop through the array of passed column names,
            // print the data for each column
            for (DWORD x = 0; x < dwAttrNameSize; x++)
            {
			    // Get the data for this column
                hr = pSearchBase->GetColumn( hSearch, pszAttribute[x], &col );
			    if ( SUCCEEDED(hr) )
			    {
				    // Print the data for the column and free the column
					// Note the attribute we asked for is type CaseIgnoreString.
                    wcscpy_s(szADsPath, MAX_PATH, col.pADsValues->CaseIgnoreString); 
					hr = ADsOpenObject(szADsPath,
									 NULL,
									 NULL,
									 ADS_SECURE_AUTHENTICATION, //Use Secure Authentication
									 IID_IADs,
									 (void**)ppUser);
					if (SUCCEEDED(hr))
					{
                       wprintf(L"Found User.\n",szFindUser); 
                       wprintf(L"%s: %s\r\n",pszAttribute[x],col.pADsValues->CaseIgnoreString); 
					   hrObj = S_OK;
					}
				    pSearchBase->FreeColumn( &col );
			    }
			    else
				    hr = E_FAIL;
            }
		}
		// Close the search handle to clean up
        pSearchBase->CloseSearchHandle(hSearch);
	}
	if (FAILED(hrObj))
		hr = hrObj;

	ret:
        delete [] pszSearchFilter;
        delete [] szADsPath;
        return hr;
}
Example #4
0
PXCSession* PXCAPI PXCSession_Create(void) {
    LONG err_code;
    HKEY key = 0;
    DWORD type = 0;

    // try LocalRuntime registry key if set
    for (int i = 0; i < (sizeof(void*)/4); i++)
    {
        err_code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, (!i) ? RSSDK_REG_DEV TEXT("\\Dispatch") : RSSDK_REG_DEV32 TEXT("\\Dispatch"), 0, KEY_READ, &key);
        if (err_code != ERROR_SUCCESS) continue;

        pxcCHAR local_path[MAX_PATH] = L"";
        DWORD size = sizeof(local_path);
        err_code = RegGetValue(key, 0, RSSDK_REG_LOCAL, RRF_RT_REG_SZ, &type, local_path, &size);
        RegCloseKey(key);
        if (err_code != ERROR_SUCCESS || !local_path[0]) continue;

        pxcCHAR filepath[MAX_PATH] = L"";
        if (local_path[0] == '.') // relative path
        {
            // get module folder
            HMODULE handle = 0;
            GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCWSTR)LoadSessionLibrary, &handle);
            GetModuleFileName(handle,filepath,MAX_PATH);
            pxcCHAR *pSlash=wcsrchr(filepath,L'\\');
            if (pSlash) pSlash[1]=0;
            PRINT_INFO((L"The SDK INFO: Application folder: %s\n", filepath));
            wcscat_s<MAX_PATH>(filepath,local_path);
            wcscat_s<MAX_PATH>(filepath,L"\\libpxcsession.dll");
        } else // absolute path
        {
            wcscpy_s<MAX_PATH>(filepath,local_path);
            wcscat_s<MAX_PATH>(filepath,SESSION_RELATIVE_PATH);
        }
        PXCSession *session=LoadSessionLibrary(filepath, 1);
        if (session) return session;

        // try __FILE__ at compilation time
        pxcCHAR filename[MAX_PATH];
        MultiByteToWideChar(CP_UTF8, 0, __FILE__, -1, filename, sizeof(filename));
        pxcCHAR *pSlash=wcsrchr(filename,L'\\');
        if (pSlash) *pSlash=0;
        wcscat_s(filename, MAX_PATH, L"\\..\\..");
        wcscat_s(filename, MAX_PATH, SESSION_RELATIVE_PATH);
        session = LoadSessionLibrary(filename, 1);
        if (session) return session;
    }

    // standard registry key set by SDK installer
    pxcCHAR dll_path[MAX_PATH] = L"";
    err_code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, RSSDK_REG_DISPATCH, 0, KEY_READ, &key);
    if (err_code == ERROR_SUCCESS) {
        DWORD size = sizeof(dll_path);
        RegGetValue(key, 0, RSSDK_REG_MAIN, RRF_RT_REG_SZ, &type, dll_path, &size);
        RegCloseKey(key);
    }
    if (dll_path[0])
    {
        PRINT_INFO((L"The SDK INFO: Loading core library from path specified in %s\n", RSSDK_REG_DISPATCH L"\\" RSSDK_REG_MAIN));
        return LoadSessionLibrary(dll_path, 0);
    } else
    {
        PRINT_INFO((L"The SDK INFO: FAILED to open registry key %s\n", RSSDK_REG_DISPATCH L"\\" RSSDK_REG_MAIN));
        return 0;
    }
}
Example #5
0
BOOL
	CService::Install(
	__in		LPWSTR	lpServiceName,
	__in_opt	LPWSTR	lpDisplayName,
	__in_opt	LPWSTR	lpDescription,
	__in		DWORD	dwServiceType,
	__in		DWORD	dwStartType,
	__in_opt	DWORD	dwErrorControl,
	__in		LPWSTR	lpPath,
	__in_opt	LPWSTR	lpLoadOrderGroup,
	__in_opt	LPWSTR	lpDependencies,
	__in_opt	BOOL	bInteractWithTheDesktop
	)
{
	BOOL							bRet							= FALSE;

	SC_HANDLE						hScManager						= NULL;
	SC_HANDLE						hService						= NULL;
	WCHAR							wchTemp[MAX_PATH]				= {0};
	HKEY							hkResult						= NULL;
	DWORD							dwData							= 0;
	LONG							lResult							= 0;
	WCHAR							wchPath[MAX_PATH]				= {0};
	LPWSTR							lpPosition						= NULL;
	PVOID							pOldValue						= NULL;
	BOOL							bWow64DisableWow64FsRedirection = FALSE;
	OS_PROCESSOR_TYPE_USER_DEFINED	OsProcType						= OS_PROCESSOR_TYPE_UNKNOWN;
	WCHAR							wchSubKey[MAX_PATH]				= {0};


	__try
	{
		if (!lpServiceName || !lpPath || !dwServiceType)
		{
			printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "input arguments error. 0x%p 0x%p %d", lpServiceName, lpPath, dwServiceType);
			__leave;
		}

		OsProcType = COperationSystemVersion::GetInstance()->GetOSProcessorType();
		switch (OsProcType)
		{
		case OS_PROCESSOR_TYPE_X86:
			break;
		case OS_PROCESSOR_TYPE_X64:
			{
				if (!m_pfWow64DisableWow64FsRedirection(&pOldValue))
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "Wow64DisableWow64FsRedirection failed. (%d)", GetLastError());
					__leave;
				}

				bWow64DisableWow64FsRedirection = TRUE;

				break;
			}
		default:
			{
				printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "OsProcType error. %d", OsProcType);
				__leave;
			}
		}

		hScManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
		if (!hScManager) 
		{
			printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "OpenSCManager failed. (%d)", GetLastError());
			__leave;
		}

		switch (dwStartType)
		{
		case SERVICE_BOOT_START:
		case SERVICE_SYSTEM_START:
			{
				if (!(SERVICE_FILE_SYSTEM_DRIVER & dwServiceType ||
					SERVICE_KERNEL_DRIVER & dwServiceType ||
					SERVICE_RECOGNIZER_DRIVER & dwServiceType))
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "dwServiceType and dwStartType not match. 0x%x 0x%x", dwServiceType, dwStartType);
					__leave;
				}

				if (!GetSystemDirectory(wchPath, _countof(wchPath)))
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "GetSystemDirectory failed. (%d)", GetLastError());
					__leave;
				}

				wcscat_s(wchPath, _countof(wchPath), L"\\drivers\\");

				if (0 == _wcsnicmp(wchPath, lpPath, wcslen(wchPath)))
					wcscpy_s(wchPath, _countof(wchPath), lpPath);
				else
				{
					lpPosition = wcsrchr(lpPath, L'\\');
					if (!lpPosition)
					{
						printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "lpPath error. %S", lpPath);
						__leave;
					}

					wcscat_s(wchPath, _countof(wchPath), lpPosition + 1);

					if (!CopyFile(lpPath, wchPath, TRUE))
					{
						printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "CopyFile failed. %S -> %S", lpPath, wchPath);
						__leave;
					}
				}

				break;
			}
		case SERVICE_AUTO_START:
		case SERVICE_DEMAND_START:
		case SERVICE_DISABLED:
			{
				wcscat_s(wchPath, _countof(wchPath), lpPath);
				break;
			}
		default:
			{
				printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "dwStartType error. 0x%x", dwStartType);
				__leave;
			}
		}

		switch (dwErrorControl)
		{
		case SERVICE_ERROR_IGNORE:
		case SERVICE_ERROR_NORMAL:
		case SERVICE_ERROR_SEVERE:
		case SERVICE_ERROR_CRITICAL:
			break;
		default:
			{
				printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "dwErrorControl error. 0x%x", dwErrorControl);
				__leave;
			}
		}

		if (SERVICE_WIN32_OWN_PROCESS == dwServiceType ||
			SERVICE_WIN32_SHARE_PROCESS == dwServiceType)
		{
			if (bInteractWithTheDesktop)
				dwServiceType |= SERVICE_INTERACTIVE_PROCESS;
		}

		hService = CreateService(
			hScManager,
			lpServiceName,
			lpDisplayName ? lpDisplayName : lpServiceName,
			SERVICE_ALL_ACCESS,
			dwServiceType,
			dwStartType,
			dwErrorControl,
			wchPath,
			lpLoadOrderGroup,
			NULL,
			lpDependencies,
			NULL,
			NULL
			);
		if (!hService)
		{
			printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "CreateService failed. (%d)", GetLastError());
			__leave;
		}

		switch (dwServiceType)
		{
		case SERVICE_KERNEL_DRIVER:
			{
				/*
				dwData = sizeof(wchTemp);
				lResult = RegGetValue(
					HKEY_LOCAL_MACHINE,
					L"SYSTEM\\CurrentControlSet\\Control\\Class\\{4d36e967-e325-11ce-bfc1-08002be10318}",
					L"UpperFilters",
					RRF_RT_REG_MULTI_SZ,
					NULL,
					wchTemp,
					&dwData
					);
				if (ERROR_SUCCESS != lResult)
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "RegGetValue failed. (0x%x)", lResult);
					__leave;
				}

				lResult = RegOpenKeyEx(
					HKEY_LOCAL_MACHINE,
					L"SYSTEM\\CurrentControlSet\\Control\\Class\\{4d36e967-e325-11ce-bfc1-08002be10318}",
					0,
					KEY_ALL_ACCESS,
					&hkResult
					);
				if (ERROR_SUCCESS != lResult)
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "RegOpenKeyEx failed. (0x%x)", lResult);
					__leave;
				}

				if (!hkResult)
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "hkResult error");
					__leave;
				}

				wcscpy_s(wchTemp + dwData / sizeof(WCHAR) - 1, _countof(wchTemp) - dwData / sizeof(WCHAR) + 1, lpServiceName);
				*(wchTemp + dwData / sizeof(WCHAR) + wcslen(lpServiceName)) = L'\0';

				lResult = RegSetValueEx(
					hkResult,
					L"UpperFilters",
					0,
					REG_MULTI_SZ,
					(const BYTE*)wchTemp,
					dwData + (wcslen(lpServiceName) + 1) * sizeof(WCHAR)
					);
				if (ERROR_SUCCESS != lResult)
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "RegSetValueEx failed. (0x%x)", lResult);
					__leave;
				}

				lResult = RegFlushKey(hkResult);
				if (ERROR_SUCCESS != lResult)
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "RegFlushKey failed. (0x%x)", lResult);
					__leave;
				}
				*/

				break;
			}
		case SERVICE_FILE_SYSTEM_DRIVER:
			{
				wcscat_s(wchTemp, _countof(wchTemp), L"SYSTEM\\CurrentControlSet\\services\\");
				wcscat_s(wchTemp, _countof(wchTemp), lpServiceName);
				wcscat_s(wchTemp, _countof(wchTemp), L"\\Instances");

				lResult = RegCreateKeyEx(
					HKEY_LOCAL_MACHINE,
					wchTemp,
					0,
					NULL,
					REG_OPTION_NON_VOLATILE,
					KEY_ALL_ACCESS,
					NULL,
					&hkResult,
					NULL
					);
				if (ERROR_SUCCESS != lResult)
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "RegCreateKeyEx failed. (0x%x)", lResult);
					__leave;
				}

				if (!hkResult)
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "hkResult error");
					__leave;
				}

				lResult = RegFlushKey(hkResult);
				if (ERROR_SUCCESS != lResult)
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "RegFlushKey failed. (0x%x)", lResult);
					__leave;
				}

				ZeroMemory(wchTemp, sizeof(wchTemp));
				wcscat_s(wchTemp, _countof(wchTemp), lpServiceName);
				wcscat_s(wchTemp, _countof(wchTemp), L" Instance");

				lResult = RegSetValueEx(
					hkResult,
					L"DefaultInstance",
					0,
					REG_SZ,
					(const BYTE*)wchTemp,
					wcslen(wchTemp) * sizeof(WCHAR)
					);
				if (ERROR_SUCCESS != lResult)
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "RegSetValueEx failed. (0x%x)", lResult);
					__leave;
				}

				lResult = RegFlushKey(hkResult);
				if (ERROR_SUCCESS != lResult)
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "RegFlushKey failed. (0x%x)", lResult);
					__leave;
				}

				lResult = RegCloseKey(hkResult);
				if (ERROR_SUCCESS != lResult)
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "RegCloseKey failed. (0x%x)", lResult);
					__leave;
				}

				hkResult = NULL;

				ZeroMemory(wchTemp, sizeof(wchTemp));
				wcscat_s(wchTemp, _countof(wchTemp), L"SYSTEM\\CurrentControlSet\\services\\");
				wcscat_s(wchTemp, _countof(wchTemp), lpServiceName);
				wcscat_s(wchTemp, _countof(wchTemp), L"\\Instances\\");
				wcscat_s(wchTemp, _countof(wchTemp), lpServiceName);
				wcscat_s(wchTemp, _countof(wchTemp), L" Instance");

				lResult = RegCreateKeyEx(
					HKEY_LOCAL_MACHINE,
					wchTemp,
					0,
					NULL,
					REG_OPTION_NON_VOLATILE,
					KEY_ALL_ACCESS,
					NULL,
					&hkResult,
					NULL
					);
				if (ERROR_SUCCESS != lResult)
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "RegCreateKeyEx failed. (0x%x)", lResult);
					__leave;
				}

				if (!hkResult)
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "hkResult error");
					__leave;
				}

				lResult = RegFlushKey(hkResult);
				if (ERROR_SUCCESS != lResult)
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "RegFlushKey failed. (0x%x)", lResult);
					__leave;
				}

				ZeroMemory(wchTemp, sizeof(wchTemp));
				wcscat_s(wchTemp, _countof(wchTemp), L"370030");

				lResult = RegSetValueEx(
					hkResult,
					L"Altitude",
					0,
					REG_SZ,
					(const BYTE*)wchTemp,
					wcslen(wchTemp) * sizeof(WCHAR)
					);
				if (ERROR_SUCCESS != lResult)
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "RegSetValueEx failed. (0x%x)", lResult);
					__leave;
				}

				lResult = RegFlushKey(hkResult);
				if (ERROR_SUCCESS != lResult)
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "RegFlushKey failed. (0x%x)", lResult);
					__leave;
				}

				dwData = 0x0;

				lResult = RegSetValueEx(
					hkResult,
					L"Flags",
					0,
					REG_DWORD,
					(const BYTE*)&dwData,
					sizeof(DWORD)
					);
				if (ERROR_SUCCESS != lResult)
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "RegSetValueEx failed. (0x%x)", lResult);
					__leave;
				}

				lResult = RegFlushKey(hkResult);
				if (ERROR_SUCCESS != lResult)
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "RegFlushKey failed. (0x%x)", lResult);
					__leave;
				}

				break;
			}
		case SERVICE_WIN32_OWN_PROCESS:
		case SERVICE_WIN32_SHARE_PROCESS:
			{
				wcscat_s(wchSubKey, _countof(wchSubKey), L"SYSTEM\\CurrentControlSet\\services\\");
				wcscat_s(wchSubKey, _countof(wchSubKey), lpServiceName);

				lResult = RegOpenKeyEx(
					HKEY_LOCAL_MACHINE,
					wchSubKey,
					0,
					KEY_ALL_ACCESS,
					&hkResult
					);
				if (ERROR_SUCCESS != lResult)
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "RegOpenKeyEx failed. (0x%x)", lResult);
					__leave;
				}

				if (!hkResult)
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "hkResult error");
					__leave;
				}

				lResult = RegSetValueEx(
					hkResult,
					L"Description",
					0,
					REG_SZ,
					(const BYTE *)(lpDescription ? lpDescription : (lpDisplayName ? lpDisplayName : lpServiceName)),
					wcslen(lpDescription ? lpDescription : (lpDisplayName ? lpDisplayName : lpServiceName)) * sizeof(WCHAR)
					);
				if (ERROR_SUCCESS != lResult)
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "RegSetValueEx failed. (0x%x)", lResult);
					__leave;
				}

				lResult = RegFlushKey(hkResult);
				if (ERROR_SUCCESS != lResult)
				{
					printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "RegFlushKey failed. (0x%x)", lResult);
					__leave;
				}

				break;
			}
		default:
			{
				if (SERVICE_WIN32_OWN_PROCESS & dwServiceType || SERVICE_WIN32_SHARE_PROCESS & dwServiceType)
				{
					wcscat_s(wchSubKey, _countof(wchSubKey), L"SYSTEM\\CurrentControlSet\\services\\");
					wcscat_s(wchSubKey, _countof(wchSubKey), lpServiceName);

					lResult = RegOpenKeyEx(
						HKEY_LOCAL_MACHINE,
						wchSubKey,
						0,
						KEY_ALL_ACCESS,
						&hkResult
						);
					if (ERROR_SUCCESS != lResult)
					{
						printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "RegOpenKeyEx failed. (0x%x)", lResult);
						__leave;
					}

					if (!hkResult)
					{
						printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "hkResult error");
						__leave;
					}

					lResult = RegSetValueEx(
						hkResult,
						L"Description",
						0,
						REG_SZ,
						(const BYTE *)(lpDescription ? lpDescription : (lpDisplayName ? lpDisplayName : lpServiceName)),
						wcslen(lpDescription ? lpDescription : (lpDisplayName ? lpDisplayName : lpServiceName)) * sizeof(WCHAR)
						);
					if (ERROR_SUCCESS != lResult)
					{
						printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "RegSetValueEx failed. (0x%x)", lResult);
						__leave;
					}

					lResult = RegFlushKey(hkResult);
					if (ERROR_SUCCESS != lResult)
					{
						printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "RegFlushKey failed. (0x%x)", lResult);
						__leave;
					}

					break;
				}

				printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "dwServiceType error. 0x%x", dwServiceType);
				__leave;
			}
		}

		bRet = TRUE;
	}
	__finally
	{
		if (hkResult)
		{
			RegCloseKey(hkResult);
			hkResult = NULL;
		}

		if (hService)
		{
			CloseServiceHandle(hService);
			hService = NULL;
		}

		if (hScManager)
		{
			CloseServiceHandle(hScManager);
			hScManager = NULL;
		}

		if (bWow64DisableWow64FsRedirection)
		{
			m_pfWow64RevertWow64FsRedirection(pOldValue);
			pOldValue = NULL;
		}
	}

	return bRet;
}
Example #6
0
int __cdecl wmain(int argc, PWCHAR argv[]) {
  size_t i;
  WCHAR fileName[MAX_PATH];
  WCHAR driverFullPath[MAX_PATH] = {0};
  WCHAR mounterFullPath[MAX_PATH] = {0};
  WCHAR type;
  PVOID wow64OldValue;

  DokanUseStdErr(TRUE); // Set dokan library debug output

  Wow64DisableWow64FsRedirection(&wow64OldValue); //Disable system32 direct
  // setlocale(LC_ALL, "");

  GetModuleFileName(NULL, fileName, MAX_PATH);

  // search the last "\"
  for (i = wcslen(fileName) - 1; i > 0 && fileName[i] != L'\\'; --i) {
    ;
  }
  fileName[i] = L'\0';

  wcscpy_s(mounterFullPath, MAX_PATH, fileName);
  wcscat_s(mounterFullPath, MAX_PATH, L"\\mounter.exe");
  fwprintf(stderr, L"Mounter path: '%s'\n", mounterFullPath);

  ExpandEnvironmentStringsW(DOKAN_DRIVER_FULL_PATH, driverFullPath, MAX_PATH);

  fwprintf(stderr, L"Driver path: '%s'\n", driverFullPath);

  if (GetOption(argc, argv, 1) == L'v') {
    fprintf(stderr, "dokanctl : %s %s\n", __DATE__, __TIME__);
    fprintf(stderr, "Dokan version : %d\n", DokanVersion());
    fprintf(stderr, "Dokan driver version : 0x%lx\n", DokanDriverVersion());
    return EXIT_SUCCESS;

  } else if (GetOption(argc, argv, 1) == L'm') {
    return ShowMountList();

  } else if (GetOption(argc, argv, 1) == L'u' && argc == 3) {
    return Unmount(argv[2], FALSE);

  } else if (GetOption(argc, argv, 1) == L'u' &&
             GetOption(argc, argv, 3) == L'f' && argc == 4) {
    return Unmount(argv[2], TRUE);

  } else if (argc < 3 || wcslen(argv[1]) != 2 || argv[1][0] != L'/') {
    return ShowUsage();
  }

  type = towlower(argv[2][0]);

  switch (towlower(argv[1][1])) {
  case L'i':
    if (type == L'd') {

      return InstallDriver(driverFullPath);

    } else if (type == L's') {

      return InstallMounter(mounterFullPath);

    } else if (type == L'a') {

      if (InstallDriver(driverFullPath) == EXIT_FAILURE)
        return EXIT_FAILURE;

      if (InstallMounter(mounterFullPath) == EXIT_FAILURE)
        return EXIT_FAILURE;

    } else if (type == L'n') {
      if (DokanNetworkProviderInstall())
        fprintf(stderr, "network provider install ok\n");
      else
        fprintf(stderr, "network provider install failed\n");
    }
    break;

  case L'r':
    if (type == L'd') {

      return DeleteDokanService(DOKAN_DRIVER_SERVICE);

    } else if (type == L's') {

      return DeleteDokanService(DOKAN_MOUNTER_SERVICE);

    } else if (type == L'a') {

      if (DeleteDokanService(DOKAN_MOUNTER_SERVICE) == EXIT_FAILURE)
        return EXIT_FAILURE;

      if (DeleteDokanService(DOKAN_DRIVER_SERVICE) == EXIT_FAILURE)
        return EXIT_FAILURE;

    } else if (type == L'n') {
      if (DokanNetworkProviderUninstall())
        fprintf(stderr, "network provider remove ok\n");
      else
        fprintf(stderr, "network provider remove failed\n");
    }
    break;
  case L'd':
    if (L'0' <= type && type <= L'9') {
      ULONG mode = type - L'0';
      if (DokanSetDebugMode(mode)) {
        fprintf(stderr, "set debug mode ok\n");
      } else {
        fprintf(stderr, "set debug mode failed\n");
      }
    }
    break;
  default:
    fprintf(stderr, "unknown option\n");
  }

  return EXIT_SUCCESS;
}
Example #7
0
bool CFileView::DeleteFolder(CString lpPath)
{
    TCHAR szFind[MAX_PATH]={0};
    TCHAR szFile[MAX_PATH]={0};
    WIN32_FIND_DATA FindFileData;
    wcscpy_s(szFind,lpPath);
    wcscat_s(szFind,_T("*.*"));
    HANDLE hFind=::FindFirstFile(szFind,&FindFileData);

    if(INVALID_HANDLE_VALUE == hFind)
        return false;

    while(TRUE)
    {
        if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
            if(FindFileData.cFileName[0]!=_T('.'))
            {
				//9-6修改Bug,老是提示无法读源或磁盘
                wcscpy_s(szFile,lpPath);
                wcscat_s(szFile,FindFileData.cFileName);
                CString csDelFolder=szFile;
                wcscat_s(szFile,_T("\\"));
                if(DeleteFolder(szFile))
                {
                    wchar_t wpath[MAX_PATH];
					::memset(wpath,0,sizeof(wchar_t)*MAX_PATH);
					LPCTSTR pPath=csDelFolder;
					wcscpy(wpath,pPath);

					SHFILEOPSTRUCT op;
					op.fFlags = FOF_NOCONFIRMATION;
					op.hNameMappings = NULL;
					op.hwnd = NULL;
					op.lpszProgressTitle = NULL;
					op.pFrom = wpath;
					op.pTo = wpath;
					op.wFunc = FO_DELETE;    
                    int nRet=::SHFileOperation(&op); 
                    if(nRet!=0)
                        return false;
                }
                else
                    return false;
            }
        }
        else
        {
            CString csFileName=FindFileData.cFileName;
            csFileName.Trim();
            CString csFileEx=csFileName.Right(2);
            CString csTFile;
            csTFile.Format(_T("%s%s"),lpPath,csFileName);
            if(0==::wcscmp(csFileEx,_T(".t")))
            {
                ::DeleteFile(csTFile);
                ((CTCApp*)AfxGetApp())->TCDeleteTFileView(csTFile);
            }
            ::DeleteFile(csTFile);
        }
        if(!FindNextFile(hFind,&FindFileData))
            break;
    }
    FindClose(hFind);

    return true;
}
Example #8
0
HRESULT CCeeGen::emitMetaData(IMetaDataEmit *emitter, CeeSection* section, DWORD offset, BYTE* buffer, unsigned buffLen)
{
    HRESULT hr = S_OK;

    ReleaseHolder<IStream> metaStream(NULL);
    
    IfFailRet((HRESULT)CreateStreamOnHGlobal(NULL, TRUE, &metaStream));
    
    if (! m_fTokenMapSupported) {
        IUnknown *pMapTokenIface;
        IfFailGoto(getMapTokenIface(&pMapTokenIface, emitter), Exit);

        // Set a callback for token remap and save the tokens which change.
        IfFailGoto(emitter->SetHandler(pMapTokenIface), Exit);
    }

    // generate the metadata
    IfFailGoto(emitter->SaveToStream(metaStream, 0), Exit);

    // get size of stream and get sufficient storage for it

    if (section == 0) {
        section = &getMetaSection();
        STATSTG statStg;
        IfFailGoto((HRESULT)(metaStream->Stat(&statStg, STATFLAG_NONAME)), Exit);

        buffLen = statStg.cbSize.u.LowPart;
        if(m_objSwitch)
        {
            CeeSection* pSect;
            DWORD flags = IMAGE_SCN_LNK_INFO | IMAGE_SCN_LNK_REMOVE | IMAGE_SCN_ALIGN_1BYTES; // 0x00100A00
            IfFailGoto(getSectionCreate(".cormeta",flags,&pSect,&m_metaIdx), Exit);
        }
        buffer = (BYTE *)section->getBlock(buffLen, sizeof(DWORD));
        IfNullGoto(buffer, Exit);
        offset = getMetaSection().dataLen() - buffLen;
    }
    else {
        _ASSERTE(buffer[buffLen-1] || true); // Dereference 'buffer'
        _ASSERTE(section->computeOffset(PCHAR(buffer)) == offset);
    }

    // reset seek pointer and read from stream
    {
        LARGE_INTEGER disp = { {0, 0} };
        IfFailGoto((HRESULT)metaStream->Seek(disp, STREAM_SEEK_SET, NULL), Exit);
    }
    ULONG metaDataLen;
    IfFailGoto((HRESULT)metaStream->Read(buffer, buffLen+1, &metaDataLen), Exit);

    _ASSERTE(metaDataLen <= buffLen);

#ifdef ENC_DELTA_HACK
    {
        extern int __cdecl fclose(FILE *);
        WCHAR szFileName[256];
        DWORD len = GetEnvironmentVariable(W("COMP_ENC_EMIT"), szFileName, ARRAYSIZE(szFileName));
        _ASSERTE(len < (ARRAYSIZE(szFileName) + 6)); // +6 for the .dmeta
        if (len > 0 && len < (ARRAYSIZE(szFileName) + 6)) 
        {
            wcscat_s(szFileName, ARRAYSIZE(szFileName), W(".dmeta"));
            FILE *pDelta;
            int ec = _wfopen_s(&pDelta, szFileName, W("wb"));
            if (FAILED(ec)) { return HRESULT_FROM_WIN32(ERROR_OPEN_FAILED); }
            fwrite(buffer, 1, metaDataLen, pDelta);
            fclose(pDelta);
        }
    }
#endif


    // Set meta virtual address to offset of metadata within .meta, and 
    // and add a reloc for this offset, which will get turned 
    // into an rva when the pewriter writes out the file. 

    m_corHeader->MetaData.VirtualAddress = VAL32(offset);
    getCorHeaderSection().addSectReloc(m_corHeaderOffset + offsetof(IMAGE_COR20_HEADER, MetaData), *section, srRelocAbsolute);
    m_corHeader->MetaData.Size = VAL32(metaDataLen);

Exit:
    
    if (! m_fTokenMapSupported) {
        // Remove the handler that we set
        hr = emitter->SetHandler(NULL);
    }

#ifdef _DEBUG
    if (FAILED(hr) && hr != E_OUTOFMEMORY)
        _ASSERTE(!"Unexpected Failure");
#endif
    
    return hr;
}
Example #9
0
//--------------------------------------------------------------------------------------
// Enumerate for each adapter all of the supported display modes, 
// device types, adapter formats, back buffer formats, window/full screen support, 
// depth stencil formats, multisampling types/qualities, and presentations intervals.
//
// For each combination of device type (HAL/REF), adapter format, back buffer format, and
// IsWindowed it will call the app's ConfirmDevice callback.  This allows the app
// to reject or allow that combination based on its caps/etc.  It also allows the 
// app to change the BehaviorFlags.  The BehaviorFlags defaults non-pure HWVP 
// if supported otherwise it will default to SWVP, however the app can change this 
// through the ConfirmDevice callback.
//--------------------------------------------------------------------------------------
HRESULT CD3D9Enumeration::Enumerate( LPDXUTCALLBACKISD3D9DEVICEACCEPTABLE IsD3D9DeviceAcceptableFunc,
                                     void* pIsD3D9DeviceAcceptableFuncUserContext )
{
    CDXUTPerfEventGenerator eventGenerator( DXUT_PERFEVENTCOLOR, L"DXUT D3D9 Enumeration" );
    IDirect3D9* pD3D = DXUTGetD3D9Object();
    if( pD3D == NULL )
    {
        pD3D = DXUTGetD3D9Object();
        if( pD3D == NULL )
            return DXUTERR_NODIRECT3D;
    }

    m_bHasEnumerated = true;
    m_pD3D = pD3D;
    m_IsD3D9DeviceAcceptableFunc = IsD3D9DeviceAcceptableFunc;
    m_pIsD3D9DeviceAcceptableFuncUserContext = pIsD3D9DeviceAcceptableFuncUserContext;

    HRESULT hr;
    ClearAdapterInfoList();
    CGrowableArray <D3DFORMAT> adapterFormatList;

    const D3DFORMAT allowedAdapterFormatArray[] =
    {
        D3DFMT_X8R8G8B8,
        D3DFMT_X1R5G5B5,
        D3DFMT_R5G6B5,
        D3DFMT_A2R10G10B10
    };
    const UINT allowedAdapterFormatArrayCount = sizeof( allowedAdapterFormatArray ) / sizeof
        ( allowedAdapterFormatArray[0] );

    UINT numAdapters = pD3D->GetAdapterCount();
    for( UINT adapterOrdinal = 0; adapterOrdinal < numAdapters; adapterOrdinal++ )
    {
        CD3D9EnumAdapterInfo* pAdapterInfo = new CD3D9EnumAdapterInfo;
        if( pAdapterInfo == NULL )
            return E_OUTOFMEMORY;

        pAdapterInfo->AdapterOrdinal = adapterOrdinal;
        pD3D->GetAdapterIdentifier( adapterOrdinal, 0, &pAdapterInfo->AdapterIdentifier );

        // Get list of all display modes on this adapter.  
        // Also build a temporary list of all display adapter formats.
        adapterFormatList.RemoveAll();

        for( UINT iFormatList = 0; iFormatList < allowedAdapterFormatArrayCount; iFormatList++ )
        {
            D3DFORMAT allowedAdapterFormat = allowedAdapterFormatArray[iFormatList];
            UINT numAdapterModes = pD3D->GetAdapterModeCount( adapterOrdinal, allowedAdapterFormat );
            for( UINT mode = 0; mode < numAdapterModes; mode++ )
            {
                D3DDISPLAYMODE displayMode;
                pD3D->EnumAdapterModes( adapterOrdinal, allowedAdapterFormat, mode, &displayMode );

                if( displayMode.Width < m_nMinWidth ||
                    displayMode.Height < m_nMinHeight ||
                    displayMode.Width > m_nMaxWidth ||
                    displayMode.Height > m_nMaxHeight ||
                    displayMode.RefreshRate < m_nRefreshMin ||
                    displayMode.RefreshRate > m_nRefreshMax )
                {
                    continue;
                }

                pAdapterInfo->displayModeList.Add( displayMode );

                if( !adapterFormatList.Contains( displayMode.Format ) )
                    adapterFormatList.Add( displayMode.Format );
            }

        }

        D3DDISPLAYMODE displayMode;
        pD3D->GetAdapterDisplayMode( adapterOrdinal, &displayMode );
        if( !adapterFormatList.Contains( displayMode.Format ) )
            adapterFormatList.Add( displayMode.Format );

        // Sort displaymode list
        qsort( pAdapterInfo->displayModeList.GetData(),
               pAdapterInfo->displayModeList.GetSize(), sizeof( D3DDISPLAYMODE ),
               SortModesCallback );

        // Get info for each device on this adapter
        if( FAILED( EnumerateDevices( pAdapterInfo, &adapterFormatList ) ) )
        {
            delete pAdapterInfo;
            continue;
        }

        // If at least one device on this adapter is available and compatible
        // with the app, add the adapterInfo to the list
        if( pAdapterInfo->deviceInfoList.GetSize() > 0 )
        {
            hr = m_AdapterInfoList.Add( pAdapterInfo );
            if( FAILED( hr ) )
                return hr;
        }
        else
            delete pAdapterInfo;
    }

    //
    // Check for 2 or more adapters with the same name. Append the name
    // with some instance number if that's the case to help distinguish
    // them.
    //
    bool bUniqueDesc = true;
    CD3D9EnumAdapterInfo* pAdapterInfo;
    for( int i = 0; i < m_AdapterInfoList.GetSize(); i++ )
    {
        CD3D9EnumAdapterInfo* pAdapterInfo1 = m_AdapterInfoList.GetAt( i );

        for( int j = i + 1; j < m_AdapterInfoList.GetSize(); j++ )
        {
            CD3D9EnumAdapterInfo* pAdapterInfo2 = m_AdapterInfoList.GetAt( j );
            if( _stricmp( pAdapterInfo1->AdapterIdentifier.Description,
                          pAdapterInfo2->AdapterIdentifier.Description ) == 0 )
            {
                bUniqueDesc = false;
                break;
            }
        }

        if( !bUniqueDesc )
            break;
    }

    for( int i = 0; i < m_AdapterInfoList.GetSize(); i++ )
    {
        pAdapterInfo = m_AdapterInfoList.GetAt( i );

        MultiByteToWideChar( CP_ACP, 0,
                             pAdapterInfo->AdapterIdentifier.Description, -1,
                             pAdapterInfo->szUniqueDescription, 100 );
        pAdapterInfo->szUniqueDescription[100] = 0;

        if( !bUniqueDesc )
        {
            WCHAR sz[100];
            swprintf_s( sz, 100, L" (#%d)", pAdapterInfo->AdapterOrdinal );
            wcscat_s( pAdapterInfo->szUniqueDescription, 256, sz );

        }
    }

    return S_OK;
}
Example #10
0
TStatus SwCreateProcess(SwCreateProcessParm& parm, CAutoHandle& hProc)
{
	TCHAR sExe[0x1000];
	sExe[0] = 0;

	if (parm.isOur)
	{
		std::wstring sPath;
		GetPath(sPath, PATH_TYPE_EXE_NAME, parm.bit);
		wcscpy_s(sExe, sPath.c_str());
	}
	else
	{
		wcscpy_s(sExe, parm.sExe);
	}

	TCHAR args[0x1000];
	args[0] = 0;
	if(parm.sCmd)
	{
		wcscpy_s(args, L" ");
		wcscat_s(args, parm.sCmd);
	}


	BOOL Res = FALSE;
	

	bool selfElevated = IsSelfElevated();
	CAutoHandle hToken;

	if(parm.mode == SW_CREATEPROC_DEFAULT)
	{
		if(IsWindowsVistaOrGreater())
		{
			if (parm.admin == SW_ADMIN_ON && !selfElevated)
			{
				parm.mode = SW_CREATEPROC_SHELLEXE;
			}
			else if (parm.admin == SW_ADMIN_OFF && selfElevated)
			{
				TStatus stat = GetUnElevatedToken(hToken);
				if (SW_SUCCESS(stat))
				{
					parm.hToken = hToken;
					parm.mode = SW_CREATEPROC_TOKEN;
				}
				else
				{
					SW_TSTATUS_LOG(stat);
				}
			}
		}
	}

	if (parm.mode == SW_CREATEPROC_DEFAULT)
	{
		parm.mode = SW_CREATEPROC_NORMAL;
	}

	if(parm.mode == SW_CREATEPROC_SHELLEXE)
	{
		SHELLEXECUTEINFO shExInfo = { 0 };
		shExInfo.cbSize = sizeof(shExInfo);
		shExInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
		shExInfo.hwnd = 0;
		shExInfo.lpVerb = (parm.admin == SW_ADMIN_ON) ? _T("runas") : 0;
		shExInfo.lpFile = sExe;
		shExInfo.lpParameters = args;
		shExInfo.lpDirectory = 0;
		shExInfo.nShow = parm.isHide ? SW_HIDE : SW_SHOW;
		shExInfo.hInstApp = 0;

		SW_WINBOOL_RET(ShellExecuteEx(&shExInfo) == TRUE);

		hProc = shExInfo.hProcess;
	}
	else if(parm.mode == SW_CREATEPROC_NORMAL || parm.mode == SW_CREATEPROC_AS_USER || parm.mode == SW_CREATEPROC_TOKEN)
	{
		STARTUPINFO         siStartupInfo;
		PROCESS_INFORMATION piProcessInfo;

		ZeroMemory(&siStartupInfo, sizeof(siStartupInfo));
		ZeroMemory(&piProcessInfo, sizeof(piProcessInfo));

		siStartupInfo.cb = sizeof(siStartupInfo);
		if (parm.mode == SW_CREATEPROC_AS_USER)
		{
			
			Res = CreateProcessAsUser(
				parm.hToken,
				sExe,
				args,
				0,
				0,
				FALSE,
				CREATE_DEFAULT_ERROR_MODE,
				0,
				0,
				&siStartupInfo,
				&piProcessInfo);
		}
		else if(parm.mode == SW_CREATEPROC_NORMAL)
		{
			Res = CreateProcess(
				sExe,
				args,
				0,
				0,
				FALSE,
				CREATE_DEFAULT_ERROR_MODE,
				0,
				0,
				&siStartupInfo,
				&piProcessInfo);
		}
		else if(parm.mode == SW_CREATEPROC_TOKEN)
		{
			Res = ntapi::CreateProcessWithTokenW(
				parm.hToken,
				0,
				sExe,
				args,
				0,
				NULL,
				NULL,
				&siStartupInfo,
				&piProcessInfo);
		}
		SW_WINBOOL_RET(Res, L"Cant create proc %s %s", sExe, args);

		CloseHandle(piProcessInfo.hThread);
		hProc = piProcessInfo.hProcess;

	}
	SW_RETURN_SUCCESS;
}
Example #11
0
void CCopyDlg::OnLvnGetdispinfoExternalslist(NMHDR *pNMHDR, LRESULT *pResult)
{
    NMLVDISPINFO *pDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR);
    *pResult = 0;

    if (m_ExtList.HasText())
        return;

    if (pDispInfo)
    {
        if (pDispInfo->item.iItem < (int)m_externals.size())
        {
            SVNExternal ext = m_externals[pDispInfo->item.iItem];
            if (pDispInfo->item.mask & LVIF_INDENT)
            {
                pDispInfo->item.iIndent = 0;
            }
            if (pDispInfo->item.mask & LVIF_IMAGE)
            {
                pDispInfo->item.mask |= LVIF_STATE;
                pDispInfo->item.stateMask = LVIS_STATEIMAGEMASK;

                if (ext.adjust)
                {
                    //Turn check box on
                    pDispInfo->item.state = INDEXTOSTATEIMAGEMASK(2);
                }
                else
                {
                    //Turn check box off
                    pDispInfo->item.state = INDEXTOSTATEIMAGEMASK(1);
                }
            }
            if (pDispInfo->item.mask & LVIF_TEXT)
            {
                switch (pDispInfo->item.iSubItem)
                {
                case 0: // folder
                    {
                        CTSVNPath p = ext.path;
                        p.AppendPathString(ext.targetDir);
                        lstrcpyn(m_columnbuf, p.GetWinPath(), min(MAX_PATH - 2, pDispInfo->item.cchTextMax - 1));
                        int cWidth = m_ExtList.GetColumnWidth(0);
                        cWidth = max(28, cWidth-28);
                        CDC * pDC = m_ExtList.GetDC();
                        if (pDC != NULL)
                        {
                            CFont * pFont = pDC->SelectObject(m_ExtList.GetFont());
                            PathCompactPath(pDC->GetSafeHdc(), m_columnbuf, cWidth);
                            pDC->SelectObject(pFont);
                            ReleaseDC(pDC);
                        }
                    }
                    break;
                case 1: // url
                    {
                        lstrcpyn(m_columnbuf, ext.url, min(MAX_PATH - 2, pDispInfo->item.cchTextMax - 1));
                        SVNRev peg(ext.pegrevision);
                        if (peg.IsValid() && !peg.IsHead())
                        {
                            wcscat_s(m_columnbuf, L"@");
                            wcscat_s(m_columnbuf, peg.ToString());
                        }
                        int cWidth = m_ExtList.GetColumnWidth(1);
                        cWidth = max(14, cWidth-14);
                        CDC * pDC = m_ExtList.GetDC();
                        if (pDC != NULL)
                        {
                            CFont * pFont = pDC->SelectObject(m_ExtList.GetFont());
                            PathCompactPath(pDC->GetSafeHdc(), m_columnbuf, cWidth);
                            pDC->SelectObject(pFont);
                            ReleaseDC(pDC);
                        }
                    }
                    break;
                case 2: // tagged
                    m_columnbuf[0] = 0;
                    if (ext.origrevision.kind == svn_opt_revision_number)
                        swprintf_s(m_columnbuf, L"%ld", ext.origrevision.value.number);
                    else if (ext.origrevision.kind == svn_opt_revision_date)
                    {
                        SVNRev r(ext.origrevision);
                        wcscpy_s(m_columnbuf, (LPCTSTR)r.ToString());
                    }
                    break;
                default:
                    m_columnbuf[0] = 0;
                }
                pDispInfo->item.pszText = m_columnbuf;
            }
        }
    }
}
Example #12
0
HRESULT Direct3D_Init(HWND hwnd, HINSTANCE hInstance)
{

	//--------------------------------------------------------------------------------------
	// 【Direct3D初始化四步曲之一,创接口】:创建Direct3D接口对象, 以便用该Direct3D对象创建Direct3D设备对象
	//--------------------------------------------------------------------------------------
	LPDIRECT3D9  pD3D = NULL; //Direct3D接口对象的创建
	if (NULL == (pD3D = Direct3DCreate9(D3D_SDK_VERSION))) //初始化Direct3D接口对象,并进行DirectX版本协商
		return E_FAIL;

	//--------------------------------------------------------------------------------------
	// 【Direct3D初始化四步曲之二,取信息】:获取硬件设备信息
	//--------------------------------------------------------------------------------------
	D3DCAPS9 caps; int vp = 0;
	if (FAILED(pD3D->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &caps)))
	{
		return E_FAIL;
	}
	if (caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
		vp = D3DCREATE_HARDWARE_VERTEXPROCESSING;   //支持硬件顶点运算,我们就采用硬件顶点运算,妥妥的
	else
		vp = D3DCREATE_SOFTWARE_VERTEXPROCESSING; //不支持硬件顶点运算,无奈只好采用软件顶点运算

	//--------------------------------------------------------------------------------------
	// 【Direct3D初始化四步曲之三,填内容】:填充D3DPRESENT_PARAMETERS结构体
	//--------------------------------------------------------------------------------------
	D3DPRESENT_PARAMETERS d3dpp;
	ZeroMemory(&d3dpp, sizeof(d3dpp));
	d3dpp.BackBufferWidth = WINDOW_WIDTH;
	d3dpp.BackBufferHeight = WINDOW_HEIGHT;
	d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8;
	d3dpp.BackBufferCount = 2;
	d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE;
	d3dpp.MultiSampleQuality = 0;
	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	d3dpp.hDeviceWindow = hwnd;
	d3dpp.Windowed = true;
	d3dpp.EnableAutoDepthStencil = true;
	d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8;
	d3dpp.Flags = 0;
	d3dpp.FullScreen_RefreshRateInHz = 0;
	d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;

	//--------------------------------------------------------------------------------------
	// 【Direct3D初始化四步曲之四,创设备】:创建Direct3D设备接口
	//--------------------------------------------------------------------------------------
	if (FAILED(pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL,
		hwnd, vp, &d3dpp, &g_pd3dDevice)))
		return E_FAIL;


	//获取显卡信息到g_strAdapterName中,并在显卡名称之前加上“当前显卡型号:”字符串
	wchar_t TempName[60] = L"当前显卡型号:";   //定义一个临时字符串,且方便了把"当前显卡型号:"字符串引入我们的目的字符串中
	D3DADAPTER_IDENTIFIER9 Adapter;  //定义一个D3DADAPTER_IDENTIFIER9结构体,用于存储显卡信息
	pD3D->GetAdapterIdentifier(0, 0, &Adapter);//调用GetAdapterIdentifier,获取显卡信息
	int len = MultiByteToWideChar(CP_ACP, 0, Adapter.Description, -1, NULL, 0);//显卡名称现在已经在Adapter.Description中了,但是其为char类型,我们要将其转为wchar_t类型
	MultiByteToWideChar(CP_ACP, 0, Adapter.Description, -1, g_strAdapterName, len);//这步操作完成后,g_strAdapterName中就为当前我们的显卡类型名的wchar_t型字符串了
	wcscat_s(TempName, g_strAdapterName);//把当前我们的显卡名加到“当前显卡型号:”字符串后面,结果存在TempName中
	wcscpy_s(g_strAdapterName, TempName);//把TempName中的结果拷贝到全局变量g_strAdapterName中,大功告成~

	if (!(S_OK == Objects_Init())) return E_FAIL;

	SAFE_RELEASE(pD3D) //LPDIRECT3D9接口对象的使命完成,我们将其释放掉

		return S_OK;
}
Example #13
0
//	Writes an HTML File that contains the marker info in the same folder as the output
void WriteMarkerAndProjectDataToFile(
    exportStdParms		*stdParmsP,
    exDoExportRec		*exportInfoP)
{
#ifdef PRWIN_ENV
    FILE			*fileP					= NULL;
    prMarkerRef		marker					= 0;
    char			*nameZ					= NULL,
                                  *commentZ				= NULL,
                                              *chapterZ				= NULL,
                                                          *hrefZ					= NULL,
                                                                        *targetZ				= NULL;
    wchar_t			htmlOutputFilePath[256]	= {'\0'};
    char			settingsA[256]			= {'\0'};
    prBool			firstMarker				= kPrTrue;
    ExportSettings	*mySettings				= reinterpret_cast<ExportSettings*>(exportInfoP->privateData);

    char			HTML_begin[]			= "<html>\n<head>\n<title>SDK Exporter - Sequence Marker Data Output\n</title>\n</head>\n",
            HTML_body[]				= "<body>",
                                      HTML_end[]				= "</body>\n</html>",
                                              noMarkers[]				= "<center>There were no markers found in the Adobe Premiere Pro Sequence";
    csSDK_int32		filepathLen				= 255;
    csSDK_uint32	markerType				= 0,
                              DVDmarkerType			= 0,
                                      numMarkers				= 0;
    PrTime			ticksPerSecond			= 0,
                           markerTime				= 0,
                                     markerDuration			= 0;
    float			markerTimeFloat			= 0.0,
                          markerDurationFloat		= 0.0;

    mySettings->exportFileSuite->GetPlatformPath(exportInfoP->fileObject, &filepathLen, htmlOutputFilePath);
    mySettings->timeSuite->GetTicksPerSecond (&ticksPerSecond);

#ifdef PRWIN_ENV
    wcscat_s(htmlOutputFilePath, sizeof (htmlOutputFilePath) / sizeof (wchar_t), L".html");
    _wfopen_s(&fileP, htmlOutputFilePath, L"w");
#else
    wcscat(htmlOutputFilePath, L".html");
    fileP = _wfopen(htmlOutputFilePath, L"w");
#endif

    mySettings->markerSuite->GetMarkerCount(exportInfoP->timelineData, &numMarkers);
    marker = mySettings->markerSuite->GetFirstMarker(exportInfoP->timelineData);

    // If no markers in the timeline, create default "no markers"
    if (numMarkers == 0)
    {
        fprintf(fileP, HTML_begin);
        fprintf(fileP, HTML_body);
        fprintf(fileP, settingsA);
        fprintf(fileP, "%s", &noMarkers);
        fprintf(fileP, HTML_end);
        fclose(fileP);

        // Exit the function, nothing else to do
        return;
    }

    while (marker != kInvalidMarkerRef)
    {
        mySettings->markerSuite->GetMarkerData(exportInfoP->timelineData, marker, PRT_MARKER_VALUE64, &markerTime);
        mySettings->markerSuite->GetMarkerData(exportInfoP->timelineData, marker, PRT_MARKER_DURATION64, &markerDuration);
        mySettings->markerSuite->GetMarkerData(exportInfoP->timelineData, marker, PRT_MARKER_NAME, reinterpret_cast<void*>(&nameZ));
        mySettings->markerSuite->GetMarkerData(exportInfoP->timelineData, marker, PRT_MARKER_COMMENT, reinterpret_cast<void*>(&commentZ));
        mySettings->markerSuite->GetMarkerData(exportInfoP->timelineData, marker, PRT_MARKER_CHAPTER, reinterpret_cast<void*>(&chapterZ));
        mySettings->markerSuite->GetMarkerData(exportInfoP->timelineData, marker, PRT_MARKER_HREF,	reinterpret_cast<void*>(&hrefZ));
        mySettings->markerSuite->GetMarkerData(exportInfoP->timelineData, marker, PRT_MARKER_TARGET, reinterpret_cast<void*>(&targetZ));
        mySettings->markerSuite->GetMarkerData(exportInfoP->timelineData, marker, PRT_MARKER_TYPE, reinterpret_cast<void*>(&markerType));
        mySettings->markerSuite->GetMarkerData(exportInfoP->timelineData, marker, PRT_DVD_MARKER_TYPE, reinterpret_cast<void*>(&DVDmarkerType));

        // Create an HTML table of marker information, make links active
        if (firstMarker)
        {
            fprintf(fileP, HTML_begin);
            fprintf(fileP, HTML_body);
            fprintf(fileP, "<center>\nSequence Marker Data Output<p>\n");
            fprintf(fileP, "<table border=\"4\" cellpadding=\"0\" cellspacing=\"2\" width=\"350\">\n");
            firstMarker = false;
        }

        markerTimeFloat = static_cast<float>(markerTime) / static_cast<float>(ticksPerSecond);
        fprintf(fileP, "<tr><td>Time</td><td>%.2f sec</td></tr>", markerTimeFloat);
        markerDurationFloat = static_cast<float>(markerDuration) / static_cast<float>(ticksPerSecond);
        fprintf(fileP, "<tr><td>Duration</td><td>%.2f sec</td></tr>\n", markerDurationFloat);
        fprintf(fileP, "<tr><td>Name</td><td>%s</td></tr>\n", nameZ);
        fprintf(fileP, "<tr><td>Comment</td><td>%s</td></tr>\n", commentZ);
        fprintf(fileP, "<tr><td>Chapter</td><td>%s</td></tr>\n", chapterZ);
        fprintf(fileP, "<tr><td>HREF</td><td><a href=\"%s\">%s</a></td></tr>\n", hrefZ, hrefZ);
        fprintf(fileP, "<tr><td>Frame Target</td><td>%s</td></tr>\n", targetZ);
        if (markerType == kMarkerType_Timeline)
        {
            fprintf(fileP, "<tr><td>Marker Type</td><td>Timeline Marker</td></tr>\n<tr><td>----------</td><td>----------</td>\n");
        }
        else if (markerType == kMarkerType_DVD)
        {
            if (DVDmarkerType == kDVDMarkerType_Main)
            {
                fprintf(fileP, "<tr><td>Marker Type</td><td>DVD Chapter Marker</td></tr>\n<tr><td>----------</td><td>----------</td>\n");
            }
            else if (DVDmarkerType == kDVDMarkerType_Scene)
            {
                fprintf(fileP, "<tr><td>Marker Type</td><td>DVD Scene Marker</td></tr>\n<tr><td>----------</td><td>----------</td>\n");
            }
            else if (DVDmarkerType == kDVDMarkerType_Stop)
            {
                fprintf(fileP, "<tr><td>Marker Type</td><td>DVD Stop Marker</td></tr>\n<tr><td>----------</td><td>----------</td>\n");
            }
            else
            {
                fprintf(fileP, "<tr><td>Marker Type</td><td>Unknown DVD Marker</td></tr>\n<tr><td>----------</td><td>----------</td>\n");
            }
        }
        else
        {
            fprintf(fileP, "<tr><td>Marker Type</td><td>Unknown Marker Type</td></tr>\n<tr><td>----------</td><td>----------</td>\n");
        }

        marker = mySettings->markerSuite->GetNextMarker(exportInfoP->timelineData, marker);
    }

    fprintf(fileP, "</table>\n</center>\n</body>\n</html>");
    fclose(fileP);

#endif

    return;
}
Example #14
0
DWORD WINAPI CaptureThread(HANDLE hDllMainThread)
{
    bool bSuccess = false;

    //wait for dll initialization to finish before executing any initialization code
    if(hDllMainThread)
    {
        WaitForSingleObject(hDllMainThread, INFINITE);
        CloseHandle(hDllMainThread);
    }

    TCHAR lpLogPath[MAX_PATH];
    SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, lpLogPath);
    wcscat_s(lpLogPath, MAX_PATH, TEXT("\\OBS\\pluginData\\captureHookLog.txt"));

    dummyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

    if(!logOutput.is_open())
        logOutput.open(lpLogPath, ios_base::in | ios_base::out | ios_base::trunc, _SH_DENYNO);

    wstringstream str;
    str << OBS_KEEPALIVE_EVENT << UINT(GetCurrentProcessId());
    strKeepAlive = str.str();

    logOutput << CurrentDateTimeString() << "we're booting up: " << endl;

    InitializeCriticalSection(&d3d9EndMutex);
    InitializeCriticalSection(&glMutex);

    DWORD procID = GetCurrentProcessId();

    wstringstream strRestartEvent, strEndEvent, strReadyEvent, strExitEvent, strInfoMemory;
    strRestartEvent << RESTART_CAPTURE_EVENT << procID;
    strEndEvent     << END_CAPTURE_EVENT     << procID;
    strReadyEvent   << CAPTURE_READY_EVENT   << procID;
    strExitEvent    << APP_EXIT_EVENT        << procID;
    strInfoMemory   << INFO_MEMORY           << procID;

    hSignalRestart  = GetEvent(strRestartEvent.str().c_str());
    hSignalEnd      = GetEvent(strEndEvent.str().c_str());
    hSignalReady    = GetEvent(strReadyEvent.str().c_str());
    hSignalExit     = GetEvent(strExitEvent.str().c_str());

    DWORD bla;
    HANDLE hWindowThread = CreateThread(NULL, 0, DummyWindowThread, NULL, 0, &bla);
    if (!hWindowThread) {
        logOutput << CurrentTimeString() << "CaptureThread: could not create window thread for some reason" << endl;
        return 0;
    }

    CloseHandle(hWindowThread);

    hInfoFileMap = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(CaptureInfo), strInfoMemory.str().c_str());
    if(!hInfoFileMap)
    {
        logOutput << CurrentTimeString() << "CaptureThread: could not info file mapping" << endl;
        return 0;
    }

    infoMem = (CaptureInfo*)MapViewOfFile(hInfoFileMap, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(CaptureInfo));
    if(!infoMem)
    {
        logOutput << CurrentTimeString() << "CaptureThread: could not map view of info shared memory" << endl;
        CloseHandle(hInfoFileMap);
        hInfoFileMap = NULL;
        return 0;
    }

    hwndOBS = FindWindow(OBS_WINDOW_CLASS, NULL);
    if(!hwndOBS)
    {
        logOutput << CurrentTimeString() << "CaptureThread: could not find main application window?  wtf?  seriously?" << endl;
        return 0;
    }

    textureMutexes[0] = OpenMutex(MUTEX_ALL_ACCESS, FALSE, TEXTURE_MUTEX1);
    if (textureMutexes[0]) {
        textureMutexes[1] = OpenMutex(MUTEX_ALL_ACCESS, FALSE, TEXTURE_MUTEX2);
        if (textureMutexes[1]) {
            while(!AttemptToHookSomething())
                Sleep(50);

            logOutput << CurrentTimeString() << "(half life scientist) everything..  seems to be in order" << endl;

            while (1) {
                AttemptToHookSomething();
                Sleep(4000);
            }

            CloseHandle(textureMutexes[1]);
            textureMutexes[1] = NULL;
        } else {
            logOutput << CurrentTimeString() << "could not open texture mutex 2" << endl;
        }

        CloseHandle(textureMutexes[0]);
        textureMutexes[0] = NULL;
    } else {
        logOutput << CurrentTimeString() << "could not open texture mutex 1" << endl;
    }

    logOutput << CurrentTimeString() << "WARNING: exit out of the main thread loop somehow" << endl;

    return 0;
}
Example #15
0
bool ScanDirectory(WCHAR* szDirectory, WCHAR* szPattern, LPWSTR pszTrustedPlatformAssemblies, size_t cchTrustedPlatformAssemblies)
{
    bool ret = true;
    errno_t errno = 0;
    WIN32_FIND_DATA ffd = {};
    
    WCHAR wszPattern[MAX_PATH];
    wszPattern[0] = L'\0';
    
    errno = wcscpy_s(wszPattern, _countof(wszPattern), szDirectory);
    CHECK_RETURN_VALUE_FAIL_EXIT_VIA_FINISHED_SETSTATE(errno, ret = false);

    errno = wcscat_s(wszPattern, _countof(wszPattern), szPattern);
    CHECK_RETURN_VALUE_FAIL_EXIT_VIA_FINISHED_SETSTATE(errno, ret = false);
    
    HANDLE findHandle = FindFirstFile(wszPattern, &ffd);

    if (INVALID_HANDLE_VALUE == findHandle)
    {
        ret = false;
        goto Finished;
    }

    do
    {
        if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
            // Skip directories
        }
        else
        {
            if (wcscmp(ffd.cFileName, L"klr.host.dll") == 0 || 
                wcscmp(ffd.cFileName, L"klr.host.ni.dll") == 0 ||
                wcscmp(ffd.cFileName, L"Microsoft.Framework.ApplicationHost.dll") == 0 ||
                wcscmp(ffd.cFileName, L"Microsoft.Framework.ApplicationHost.ni.dll") == 0 ||
                wcscmp(ffd.cFileName, L"Microsoft.Framework.Runtime.dll") == 0 ||
                wcscmp(ffd.cFileName, L"Microsoft.Framework.Runtime.ni.dll") == 0 ||
                wcscmp(ffd.cFileName, L"Microsoft.Framework.Runtime.Roslyn.dll") == 0 ||
                wcscmp(ffd.cFileName, L"Microsoft.Framework.Runtime.Roslyn.ni.dll") == 0 ||
                wcscmp(ffd.cFileName, L"Microsoft.Framework.Project.dll") == 0 ||
                wcscmp(ffd.cFileName, L"Microsoft.Framework.Project.ni.dll") == 0 ||
                wcscmp(ffd.cFileName, L"Microsoft.Framework.DesignTimeHost.dll") == 0 ||
                wcscmp(ffd.cFileName, L"Microsoft.Framework.DesignTimeHost.ni.dll") == 0)
            {
                // Exclude these assemblies from the TPA list since they need to
                // be handled by the loader since they depend on assembly neutral
                // interfaces
                continue;
            }

            errno = wcscat_s(pszTrustedPlatformAssemblies, cchTrustedPlatformAssemblies, szDirectory);
            CHECK_RETURN_VALUE_FAIL_EXIT_VIA_FINISHED_SETSTATE(errno, ret = false);
            
            errno = wcscat_s(pszTrustedPlatformAssemblies, cchTrustedPlatformAssemblies, ffd.cFileName);
            CHECK_RETURN_VALUE_FAIL_EXIT_VIA_FINISHED_SETSTATE(errno, ret = false);
            
            errno = wcscat_s(pszTrustedPlatformAssemblies, cchTrustedPlatformAssemblies, L";");
            CHECK_RETURN_VALUE_FAIL_EXIT_VIA_FINISHED_SETSTATE(errno, ret = false);
        }

    } while (FindNextFile(findHandle, &ffd) != 0);

Finished:
    return ret;
}
void wmain( int argc, wchar_t *argv[])
{

//Handle the command line arguments.
int maxAlloc = MAX_PATH*2;
LPOLESTR pszBuffer = new OLECHAR[maxAlloc];
wcscpy_s(pszBuffer, maxAlloc, L"");
BOOL bReturnVerbose = FALSE;

for (int i = 1;i<argc;i++)
{
    if (_wcsicmp(argv[i],L"/V") == 0)
	{
		bReturnVerbose = TRUE;
	}
	else if ((_wcsicmp(argv[i],L"/?") == 0)||
             (_wcsicmp(argv[i],L"-?") == 0))
	{
		wprintf(L"This program queries for users in the current user's domain.\n");
		wprintf(L"Syntax: queryusers [/V][querystring]\n");
		wprintf(L"where /V specifies that all properties for the found users should be returned.\n");
		wprintf(L"      querystring is the query criteria in ldap query format.\n");
		wprintf(L"Defaults: If no /V is specified, the query returns only the RDN and DN of the items found.\n");
		wprintf(L"          If no querystring is specified, the query returns all users.\n");
		wprintf(L"Example: queryusers (sn=Smith)\n");
		wprintf(L"Returns all users with surname Smith.\n");
		return;
	}
	else
	{
		if ( IS_BUFFER_ENOUGH(maxAlloc, pszBuffer, argv[i]) > 0 )
		{
		    wcscpy_s(pszBuffer,maxAlloc,argv[i]);
		}
		else
		{
			wprintf(L"Buffer is too small for the argument");
			delete [] pszBuffer;
			return;
		}
	}
}
if (_wcsicmp(pszBuffer,L"") == 0)
  wprintf(L"\nFinding all user objects...\n\n");
else
  wprintf(L"\nFinding user objects based on query: %s...\n\n", pszBuffer);
	
//Initialize COM
CoInitialize(NULL);
HRESULT hr = S_OK;
//Get rootDSE and the current user's domain container DN.
IADs *pObject = NULL;
IDirectorySearch *pContainerToSearch = NULL;
LPOLESTR szPath = new OLECHAR[MAX_PATH];
VARIANT var;
hr = ADsOpenObject(L"LDAP://rootDSE",
				 NULL,
				 NULL,
				 ADS_SECURE_AUTHENTICATION, //Use Secure Authentication
				 IID_IADs,
				 (void**)&pObject);
if (FAILED(hr))
{
   wprintf(L"Could not execute query. Could not bind to LDAP://rootDSE.\n");
   if (pObject)
     pObject->Release();
   delete [] pszBuffer;
   delete [] szPath;
   CoUninitialize();
   return;
}
if (SUCCEEDED(hr))
{
	hr = pObject->Get(L"defaultNamingContext",&var);
	if (SUCCEEDED(hr))
	{
		//Build path to the domain container.
        wcscpy_s(szPath,MAX_PATH,L"LDAP://");
		if ( IS_BUFFER_ENOUGH(MAX_PATH, szPath, var.bstrVal) > 0 )
		{
		    wcscat_s(szPath,MAX_PATH,var.bstrVal);
		}
		else
		{
			wprintf(L"Buffer is too small for the domain DN");
            delete [] pszBuffer;
            delete [] szPath;
            CoUninitialize();
			return;
		}

        
        hr = ADsOpenObject(szPath,
						 NULL,
						 NULL,
						 ADS_SECURE_AUTHENTICATION, //Use Secure Authentication
						 IID_IDirectorySearch,
						 (void**)&pContainerToSearch);

		if (SUCCEEDED(hr))
		{
			hr = FindUsers(pContainerToSearch, //IDirectorySearch pointer to Partitions container.
					 pszBuffer,  
					 NULL, //Return all properties
					 -1, // Return all properties
					 bReturnVerbose 
				 );
			if (SUCCEEDED(hr))
			{
				if (S_FALSE==hr)
				   wprintf(L"No user object could be found.\n");
			}
			else if (0x8007203e==hr)
				wprintf(L"Could not execute query. An invalid filter was specified.\n");
			else
				wprintf(L"Query failed to run. HRESULT: %x\n",hr);
		}
		else
		{
		   wprintf(L"Could not execute query. Could not bind to the container.\n");
		}
		if (pContainerToSearch)
		   pContainerToSearch->Release();
	}
    VariantClear(&var);
}
if (pObject)
    pObject->Release();

delete [] pszBuffer;
delete [] szPath;
                        
// Uninitialize COM
CoUninitialize();
return;
}
Example #17
0
	void createProcess(const wstring& fileToOpen, const wstring& params, const wstring& standardInput, pwstring pstandardOutput, pwstring pstandardError) {
		STARTUPINFO startupInfo = {0};
		PROCESS_INFORMATION processInfo = {0};

		startupInfo.cb = sizeof(startupInfo);

		HANDLE hWriteStdinFinished = NULL;
		HANDLE hReadStdoutFinished = NULL;
		HANDLE hReadStderrFinished = NULL;

		if (standardInput.size()) {
			hWriteStdinFinished = ::CreateEvent(NULL, TRUE, FALSE, NULL);
			byps_ptr<WriteStringToPipe_Job> job(new WriteStringToPipe_Job(standardInput, hWriteStdinFinished));
			startupInfo.hStdInput = job->start(jsfs->tpool);
			startupInfo.dwFlags |= STARTF_USESTDHANDLES;
		}

		if (pstandardOutput) {
			hReadStdoutFinished = ::CreateEvent(NULL, TRUE, FALSE, NULL);
			byps_ptr<ReadStringFromPipe_Job> job(new ReadStringFromPipe_Job(pstandardOutput, hReadStdoutFinished));
			startupInfo.hStdOutput = job->start(jsfs->tpool);
			startupInfo.dwFlags |= STARTF_USESTDHANDLES;
		}

		if (pstandardError) {
			hReadStderrFinished = ::CreateEvent(NULL, TRUE, FALSE, NULL);
			byps_ptr<ReadStringFromPipe_Job> job(new ReadStringFromPipe_Job(pstandardError, hReadStderrFinished));
			startupInfo.hStdError = job->start(jsfs->tpool);
			startupInfo.dwFlags |= STARTF_USESTDHANDLES;
		}

		DWORD cmdlen = fileToOpen.length() + 1 + params.length() + 1;
		LPWSTR cmd = new WCHAR[cmdlen];
		wcscpy_s(cmd, cmdlen, fileToOpen.c_str());
		wcscat_s(cmd, cmdlen, L" ");
		wcscat_s(cmd, cmdlen, params.c_str());

		BOOL succ = ::CreateProcess(NULL, cmd, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &startupInfo, &processInfo);		
		DWORD err = ::GetLastError();
		
		delete[] cmd;

		if (startupInfo.hStdInput) ::CloseHandle(startupInfo.hStdInput);
		if (startupInfo.hStdOutput) ::CloseHandle(startupInfo.hStdOutput);
		if (startupInfo.hStdError) ::CloseHandle(startupInfo.hStdError);

		if (!succ) {
			throw CFileSystemServiceImpl::createException(L"Failed to execute " + fileToOpen, err);
		}

		HANDLE waitHandles[4] = { 0 };
		DWORD nbOfHandles = 0;
		waitHandles[nbOfHandles++] = processInfo.hProcess;
		if (hReadStdoutFinished) waitHandles[nbOfHandles++] = hReadStdoutFinished;
		if (hReadStderrFinished) waitHandles[nbOfHandles++] = hReadStderrFinished;
		if (hWriteStdinFinished) waitHandles[nbOfHandles++] = hWriteStdinFinished;

		DWORD wait = ::WaitForMultipleObjects(nbOfHandles, waitHandles, TRUE, INFINITE);
		err = ::GetLastError();

		::CloseHandle(processInfo.hProcess);
		::CloseHandle(processInfo.hThread);
		if (hWriteStdinFinished) ::CloseHandle(hWriteStdinFinished);
		if (hReadStdoutFinished) ::CloseHandle(hReadStdoutFinished);
		if (hReadStderrFinished) ::CloseHandle(hReadStderrFinished);

		if (wait == WAIT_TIMEOUT) {
			throw BException(EX_TIMEOUT, L"Timeout while waiting for " + args->at(0));
		}
		else if (wait == WAIT_FAILED) {
			throw CFileSystemServiceImpl::createException(L"Error while waiting for " + args->at(0), err);
		}
	}
Example #18
0
int main(int argc, char * argv[])
{
    std::cout << "\n Intel(r) Performance Counter Monitor " << INTEL_PCM_VERSION << std::endl;
    std::cout << "\n MSR read/write utility\n\n";
    
    uint64 value = 0;
    bool write = false;
    int core = 0;
    int msr = -1;
    bool dec = false;

	int my_opt = -1;
	while ((my_opt = getopt(argc, argv, "w:c:d")) != -1)
	{
		switch(my_opt)
		{
			case 'w':
                                write = true;
				value = read_number(optarg);
				break;
			case 'c':
				core = (int) read_number(optarg);
				break;
                        case 'd':
                                dec = true;
                                break;
			default:
				print_usage(argv[0]);
				return -1;
		}
	}

	 if (optind >= argc)
	 {
		 print_usage(argv[0]);
		 return -1;
	 }

    msr = (int) read_number(argv[optind]);

    #ifdef OK_WIN_BUILD
    // Increase the priority a bit to improve context switching delays on Windows
    SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);

    TCHAR driverPath[1032];
    GetCurrentDirectory(1024, driverPath);
    wcscat_s(driverPath, 1032, L"\\msr.sys");

    // WARNING: This driver code (msr.sys) is only for testing purposes, not for production use
    Driver drv;
    // drv.stop();     // restart driver (usually not needed)
    if (!drv.start(driverPath))
    {
		std::cout << "Can not load MSR driver." << std::endl;
		std::cout << "You must have signed msr.sys driver in your current directory and have administrator rights to run this program" << std::endl;
        return -1;
    }
    #endif

    MsrHandle h(core);
    if(!dec) std::cout << std::hex << std::showbase;
    if(write)
    {
        std::cout << " Writing "<< value << " to MSR "<< msr << " on core "<< core << std::endl;
        h.write(msr,value);
    }
    value = 0;
    h.read(msr,&value);
    std::cout << " Read value "<< value << " from MSR "<< msr << " on core "<< core << "\n" << std::endl;
}
Example #19
0
LONG WINAPI DumpException(LPEXCEPTION_POINTERS exceptionInfo)
{
	HMODULE hLibrary = LoadLibrary(TEXT("dbghelp.dll"));
	LPMINIDUMPWRITEDUMP miniDumpWriteDump = (LPMINIDUMPWRITEDUMP)GetProcAddress(hLibrary,"MiniDumpWriteDump");
	if(!hLibrary || !miniDumpWriteDump)
	{
		FreeLibrary(hLibrary);

		TCHAR message[512];
		wsprintf(message,TEXT("The program needs to close because of a unhandled 0x%08lX exception which occurred at 0x%08lX.\n")\
						 TEXT("No additional information about the problem could be stored. We apologize for the inconvenience."),exceptionInfo->ExceptionRecord->ExceptionCode,exceptionInfo->ExceptionRecord->ExceptionAddress);

		MessageBox(GetDesktopWindow(),message,TEXT("Unhandled Exception"),MB_OK|MB_ICONEXCLAMATION|MB_TASKMODAL);

		return EXCEPTION_EXECUTE_HANDLER;
	}

	// Just create the dump file in the current working directory
	TCHAR dump[MAX_PATH] = {TEXT("Dump.dmp")};
	TCHAR compressed[MAX_PATH] = {TEXT("Dump.cab")};

	GetDateFormat(LOCALE_USER_DEFAULT,NULL,NULL,TEXT("'Dump'ddMMyyyy'.dmp'"),dump,_countof(dump));
	GetDateFormat(LOCALE_USER_DEFAULT,NULL,NULL,TEXT("'Dump'ddMMyyyy'.cab'"),compressed,_countof(compressed));
	
	TCHAR directory[MAX_PATH];
	GetCurrentDirectory(_countof(directory),directory);

	HANDLE hFile = CreateFile(dump,GENERIC_WRITE,FILE_SHARE_READ,NULL,CREATE_ALWAYS,NULL,NULL);
	if(hFile == INVALID_HANDLE_VALUE)
	{
		FreeLibrary(hLibrary);

		TCHAR message[512];
		wsprintf(message,TEXT("The program needs to close because of a unhandled 0x%08lX exception which occurred at 0x%08lX.\n")\
						 TEXT("A file containing more information about the ")\
						 TEXT("occured exception could not be written.\nPlease ")\
						 TEXT("check if you have write permissions. We apologize for the inconvenience.\n\n%s\\%s"),exceptionInfo->ExceptionRecord->ExceptionCode,exceptionInfo->ExceptionRecord->ExceptionAddress,directory,dump);

		MessageBox(GetDesktopWindow(),message,TEXT("Unhandled Exception"),MB_OK|MB_ICONEXCLAMATION|MB_TASKMODAL);

		return EXCEPTION_EXECUTE_HANDLER;
	}

	MINIDUMP_EXCEPTION_INFORMATION info = {0};
	info.ClientPointers = TRUE;
	info.ExceptionPointers = exceptionInfo;
	info.ThreadId = GetCurrentThreadId();

	miniDumpWriteDump(GetCurrentProcess(),GetCurrentProcessId(),hFile,MiniDumpWithFullMemory,&info,NULL,NULL);
	
	FlushFileBuffers(hFile);
	CloseHandle(hFile);
	FreeLibrary(hLibrary);

	BOOL result = FALSE;

#ifndef DUMP_EXCEPTION_NO_COMPRESS

	STARTUPINFO			startupInfo;
	PROCESS_INFORMATION processInfo;

	ZeroMemory(&startupInfo,sizeof(startupInfo));
	ZeroMemory(&processInfo,sizeof(processInfo));

	startupInfo.cb = sizeof(startupInfo);
	startupInfo.dwFlags = STARTF_USESHOWWINDOW;
	startupInfo.wShowWindow = SW_HIDE;

	TCHAR makecab[MAX_PATH] = {TEXT("")};
	ExpandEnvironmentStrings(TEXT("%SYSTEMROOT%\\System32\\makecab.exe"),makecab,_countof(makecab));

	TCHAR parameters[MAX_PATH] = {TEXT("")};

	wcscat_s(parameters,_countof(parameters),TEXT("\""));
	wcscat_s(parameters,_countof(parameters),makecab);
	wcscat_s(parameters,_countof(parameters),TEXT("\""));
	wcscat_s(parameters,_countof(parameters),TEXT(" "));
	wcscat_s(parameters,_countof(parameters),dump);
	wcscat_s(parameters,_countof(parameters),TEXT(" "));
	wcscat_s(parameters,_countof(parameters),compressed);

	result = CreateProcess(makecab,			// Application name
					parameters,		// Application arguments
					0,
					0,
					CREATE_NO_WINDOW,
					0,
					0,
					0,								// Working directory
					&startupInfo,
					&processInfo);

#endif
	
	TCHAR message[512];
	wsprintf(message,TEXT("The program needs to close because of a unhandled 0x%08lX exception which occurred at 0x%08lX.\n")\
					 TEXT("A file containing more information about the ")\
					 TEXT("occured exception has been written to the current directory.\nPlease ")\
					 TEXT("send us this file to help us in finding and repairing ")\
					 TEXT("the problem. We apologize for the inconvenience.\n\n%s\\%s"),exceptionInfo->ExceptionRecord->ExceptionCode,exceptionInfo->ExceptionRecord->ExceptionAddress,directory,result ? compressed : dump);

	MessageBox(GetDesktopWindow(),message,TEXT("Unhandled Exception"),MB_OK|MB_ICONEXCLAMATION|MB_TASKMODAL);
	
#ifndef DUMP_EXCEPTION_NO_COMPRESS

	if(result)
	{
		// Wait until child process exits
		WaitForSingleObject(processInfo.hProcess,INFINITE);

		DWORD code;

		if(GetExitCodeProcess(processInfo.hProcess,&code) && !code)
		{
			// Delete the original file
			DeleteFile(dump);
		}
		else
		{
			wsprintf(message,	TEXT("The exception information file could not be compressed because of a error.\n")\
								TEXT("Information about the exeption can be found in the original uncompressed file.\n\n%s\\%s"),directory,dump);

			MessageBox(GetDesktopWindow(),message,TEXT("Compression Failed"),MB_OK|MB_ICONEXCLAMATION|MB_TASKMODAL);
		}

		// Close process and thread handles. 
		CloseHandle(processInfo.hProcess);
		CloseHandle(processInfo.hThread);
	}

#endif

	return EXCEPTION_EXECUTE_HANDLER;
}
Example #20
0
HRESULT CKhParser::DoParse(BSTR word, long* hRes)
{
    if (word == NULL)
        return S_OK;

    *hRes = S_OK;

    BSTR normWord = NULL;
    this->normWord(word, normWord);
    addWordsToSent(word, normWord);
    addToSentSize(1);

    std::map<std::wstring, int>::iterator eit = empty.find(normWord);
    if (eit != empty.end()) {
        homonyms.clear();
        currHom = -1;
        eit->second++;
    //    addToSentSize(1);
        return S_OK;
    }
    HomMap::iterator it = cache.find(normWord);

    if (it != cache.end()) {
        homonyms = it->second.homVct;
        currHom = 0;
        it->second.count++;
        addToSentSize((int)homonyms.size() - 1);
        return S_OK;
    }
    wchar_t* toPost = new wchar_t [wcslen(request) + wcslen(normWord) + 1];
    memset(toPost, 0,( wcslen(request) + wcslen(normWord) + 1) * sizeof(wchar_t));
    wcscat_s(toPost, wcslen(request) + wcslen(normWord) + 1, request);
    wcscat_s(toPost, wcslen(request) + wcslen(normWord) + 1, normWord);

    *hRes = pIXMLHTTPRequest->open("GET", toPost, false);
    if (*hRes != S_OK) {
        delete [] toPost;
        return *hRes;
    }

    *hRes = pIXMLHTTPRequest->send();
    if (*hRes != S_OK) {
        delete [] toPost;
        return *hRes;
    }

    size_t statuc = pIXMLHTTPRequest->status;
    statuc++;
    if (pIXMLHTTPRequest->status == 200)
    { 
        fillHomonyms(pIXMLHTTPRequest->responseText);
        if (homonyms.size() > 0) {
            cacheItem item;
            item.count = 1;
            item.homVct = homonyms;
            currHom = 0;
            cache.insert(std::pair<std::wstring, cacheItem>(normWord, item));
            addToSentSize((int)homonyms.size() - 1);
        }
        else {
            empty.insert(std::pair<std::wstring, int>(normWord, 1));
//            addToSentSize(1);
        }
    } 
    delete [] toPost;
    return *hRes;
}
Example #21
0
static int _git_ssh_setup_tunnel(
	ssh_subtransport *t,
	const char *url,
	const char *gitCmd,
	git_smart_subtransport_stream **stream)
{
	char *host = NULL, *port = NULL, *path = NULL, *user = NULL, *pass = NULL;
	size_t i;
	ssh_stream *s;
	wchar_t *ssh = t->sshtoolpath;
	wchar_t *wideParams = NULL;
	wchar_t *cmd = NULL;
	git_buf params = GIT_BUF_INIT;
	int isPutty;
	size_t length;

	*stream = NULL;
	if (ssh_stream_alloc(t, url, gitCmd, stream) < 0) {
		giterr_set_oom();
		return -1;
	}

	s = (ssh_stream *)*stream;

	for (i = 0; i < ARRAY_SIZE(ssh_prefixes); ++i) {
		const char *p = ssh_prefixes[i];

		if (!git__prefixcmp(url, p)) {
			if (extract_url_parts(&host, &port, &path, &user, &pass, url, NULL) < 0)
				goto on_error;

			goto post_extract;
		}
	}
	if (git_ssh_extract_url_parts(&host, &user, url) < 0)
		goto on_error;

post_extract:
	if (!ssh)
	{
		giterr_set(GITERR_SSH, "No GIT_SSH tool configured");
		goto on_error;
	}

	isPutty = wcstristr(ssh, L"plink");
	if (port) {
		if (isPutty)
			git_buf_printf(&params, " -P %s", port);
		else
			git_buf_printf(&params, " -p %s", port);
	}
	if (isPutty && !wcstristr(ssh, L"tortoiseplink")) {
		git_buf_puts(&params, " -batch");
	}
	if (user)
		git_buf_printf(&params, " %s@%s ", user, host);
	else
		git_buf_printf(&params, " %s ", host);
	if (gen_proto(&params, s->cmd, s->url))
		goto on_error;
	if (git_buf_oom(&params)) {
		giterr_set_oom();
		goto on_error;
	}

	if (git__utf8_to_16_alloc(&wideParams, params.ptr) < 0) {
		giterr_set_oom();
		goto on_error;
	}
	git_buf_free(&params);

	length = wcslen(ssh) + wcslen(wideParams) + 3;
	cmd = git__calloc(length, sizeof(wchar_t));
	if (!cmd) {
		giterr_set_oom();
		goto on_error;
	}

	wcscat_s(cmd, length, L"\"");
	wcscat_s(cmd, length, ssh);
	wcscat_s(cmd, length, L"\"");
	wcscat_s(cmd, length, wideParams);

	if (command_start(cmd, &s->commandHandle, t->pEnv, isPutty ? CREATE_NEW_CONSOLE : DETACHED_PROCESS))
		goto on_error;

	git__free(wideParams);
	git__free(cmd);
	t->current_stream = s;
	git__free(host);
	git__free(port);
	git__free(path);
	git__free(user);
	git__free(pass);

	return 0;

on_error:
	t->current_stream = NULL;

	if (*stream)
		ssh_stream_free(*stream);

	git_buf_free(&params);

	if (wideParams)
		git__free(wideParams);

	if (cmd)
		git__free(cmd);

	git__free(host);
	git__free(port);
	git__free(user);
	git__free(pass);

	return -1;
}
//----------------------------------------------------------------------------------------------
//	ApplySetting
//----------------------------------------------------------------------------------------------
VOID CControllerPage::ApplySetting()
{
	//	変数宣言
	BOOL	Different	= FALSE;

	//	コンボ ボックスの内容が異なるかチェックする
	HWND	ComboBox		= GetDlgItem( Wnd, IDC_SETTING );
	LONG	ItemCount		= (LONG)SendMessage( ComboBox, CB_GETCOUNT, 0, 0 );
	if( Setting->ModifiedFlag == TRUE )
	{
		ItemCount --;
	}
	if( ItemCount == Setting->SettingCount )
	{
		//	アイテムの文字列をチェックする
		for( LONG Index = 0; Index < Setting->SettingCount; Index ++ )
		{
			//	コンボ ボックスの文字列を取得する
			WCHAR	Text[MAX_PATH]	= { '\n' };
			if( Setting->ModifiedFlag == TRUE )
			{
				SendMessage( ComboBox, CB_GETLBTEXT, Index + 1, (LPARAM)Text );
			} else {
				SendMessage( ComboBox, CB_GETLBTEXT, Index, (LPARAM)Text );
			}
			if( wcscmp( Setting->SettingName[Index], Text ) != 0 )
			{
				Different	= TRUE;
				break;
			}
		}
	} else {
		Different	= TRUE;
	}

	//	コンボ ボックスの内容を設定する
	if( Different == TRUE )
	{
		//	コンボ ボックスの内容をリセットする
		SendMessage( ComboBox, CB_RESETCONTENT, 0, 0 );

		//	設定名称をコンボ ボックスに挿入する
		for( LONG Index = 0; Index < Setting->SettingCount; Index ++ )
		{
			SendMessage(
				 ComboBox
				,CB_INSERTSTRING
				,Index
				,(LPARAM)Setting->SettingName[Index] );
		}

		//	設定が変更済みなら一番上に「〜 (変更済み)」を挿入する
		if( Setting->ModifiedFlag == TRUE )
		{
			//	設定名称を取得する
			WCHAR	SettingName[MAX_PATH * 2];
			wcscpy_s( SettingName, Setting->SettingName[Setting->CurrentSettingIndex] );

			//	リソースから「(変更済み)」を取得し、設定名称に付加する
			WCHAR	Modified[MAX_PATH];
			LoadString( Instance, IDS_MODIFIED, Modified, MAX_PATH );
			wcscat_s( SettingName, Modified );

			//	変更済みの設定名称をコンボ ボックスの一番上に挿入する
			SendMessage( ComboBox, CB_INSERTSTRING, 0, (LPARAM)SettingName );
		}
	}

	//	コンボ ボックスの順番を設定する
	if( Setting->ModifiedFlag == FALSE )
	{
		SetComboBoxIndex( IDC_SETTING, (UCHAR)Setting->CurrentSettingIndex );
	} else {
		SetComboBoxIndex( IDC_SETTING, 0 );
	}
	//	削除ボタンの有効、無効を設定する
	if( Setting->ModifiedFlag == FALSE && Setting->CurrentSettingIndex > 0 )
	{
		EnableControl( IDC_SETTING_DELETE, TRUE );
	} else {
		EnableControl( IDC_SETTING_DELETE, FALSE );
	}
}
Example #23
0
void MSOfficeLPIAction::Execute()
{
	wchar_t szParams[MAX_PATH] = L"";
	wchar_t szApp[MAX_PATH] = L"";

	switch (_getVersionInstalled())
	{
		case MSOffice2010:
		case MSOffice2013:
		{
			wchar_t logFile[MAX_PATH];

			wcscpy_s(szApp, m_szFullFilename);
			wcscpy_s(szParams, L" /passive /norestart /quiet");

			GetTempPath(MAX_PATH, logFile);
			wcscat_s(logFile, L"msofficelip.log");
			wcscat_s(szParams, L" /log:");
			wcscat_s(szParams, logFile);
			m_msiexecLog = logFile;
			break;
		}
		case MSOffice2007:
		{
			wcscpy_s(szApp, m_szFullFilename);
			wcscpy_s(szParams, L" /quiet");
			break;
		}
		case MSOffice2003:
		{
			wchar_t szMSI[MAX_PATH];

			// Unique temporary file (needs to create it)
			GetTempFileName(m_szTempPath, L"CAT", 0, m_szTempPath2003);
			DeleteFile(m_szTempPath2003);

			if (CreateDirectory(m_szTempPath2003, NULL) == FALSE)
			{
				g_log.Log(L"MSOfficeLPIAction::Execute. Cannot create temp directory '%s'", m_szTempPath2003);
				break;
			}
		
			_extractCabFile(m_szFullFilename, m_szTempPath2003);

			GetSystemDirectory(szApp, MAX_PATH);
			wcscat_s(szApp, L"\\msiexec.exe ");

			wcscpy_s(szMSI, m_szTempPath2003);
			wcscat_s(szMSI, L"\\");
			wcscat_s(szMSI, L"lip.msi");

			wcscpy_s(szParams, L" /i ");
			wcscat_s(szParams, szMSI);
			wcscat_s(szParams, L" /qn");
			break;
		}
	default:
		break;
	}

	SetStatus(InProgress);
	m_executionStep = ExecutionStep1;
	g_log.Log(L"MSOfficeLPIAction::Execute '%s' with params '%s'", szApp, szParams);
	m_runner->Execute(szApp, szParams);
}
Example #24
0
static int filter_apply(
	git_filter				*self,
	void					**payload, /* may be read and/or set */
	git_buf					*to,
	const git_buf			*from,
	const git_filter_source	*src)
{
	struct filter_filter *ffs = (struct filter_filter *)self;
	git_config *config;
	git_buf configKey = GIT_BUF_INIT;
	int isRequired = FALSE;
	int error;
	const char *cmd = NULL;
	git_buf cmdBuf = GIT_BUF_INIT;
	wchar_t *wide_cmd;
	COMMAND_HANDLE commandHandle = COMMAND_HANDLE_INIT;
	git_buf errBuf = GIT_BUF_INIT;
	DWORD exitCode;

	if (!*payload)
		return GIT_PASSTHROUGH;

	if (git_repository_config__weakptr(&config, git_filter_source_repo(src)))
		return -1;

	git_buf_join3(&configKey, '.', "filter", *payload, "required");
	if (git_buf_oom(&configKey))
		return -1;

	error = git_config_get_bool(&isRequired, config, configKey.ptr);
	git_buf_free(&configKey);
	if (error && error != GIT_ENOTFOUND)
		return -1;

	git_buf_join(&configKey, '.', "filter", *payload);
	if (git_filter_source_mode(src) == GIT_FILTER_SMUDGE) {
		git_buf_puts(&configKey, ".smudge");
	} else {
		git_buf_puts(&configKey, ".clean");
	}
	if (git_buf_oom(&configKey))
		return -1;

	error = git_config_get_string(&cmd, config, configKey.ptr);
	git_buf_free(&configKey);
	if (error && error != GIT_ENOTFOUND)
		return -1;

	if (error == GIT_ENOTFOUND) {
		if (isRequired)
			return -1;
		return GIT_PASSTHROUGH;
	}

	git_buf_puts(&cmdBuf, cmd);
	if (git_buf_oom(&cmdBuf))
		return -1;

	if (expandPerCentF(&cmdBuf, git_filter_source_path(src)))
		return 1;

	if (ffs->shexepath) {
		// build params for sh.exe
		git_buf shParams = GIT_BUF_INIT;
		git_buf_puts(&shParams, " -c \"");
		git_buf_text_puts_escaped(&shParams, cmdBuf.ptr, "\"\\", "\\");
		git_buf_puts(&shParams, "\"");
		git_buf_swap(&shParams, &cmdBuf);
		git_buf_free(&shParams);
	}

	if (git__utf8_to_16_alloc(&wide_cmd, cmdBuf.ptr) < 0)
	{
		git_buf_free(&cmdBuf);
		return 1;
	}
	git_buf_free(&cmdBuf);

	if (ffs->shexepath) {
		// build cmd, i.e. shexepath + params
		size_t len = wcslen(ffs->shexepath) + wcslen(wide_cmd) + 1;
		wchar_t *tmp = git__calloc(len, sizeof(wchar_t));
		if (!tmp) {
			git__free(wide_cmd);
			return -1;
		}
		wcscat_s(tmp, len, ffs->shexepath);
		wcscat_s(tmp, len, wide_cmd);
		git__free(wide_cmd);
		wide_cmd = tmp;
	}

	commandHandle.errBuf = &errBuf;
	if (command_start(wide_cmd, &commandHandle, ffs->pEnv)) {
		git__free(wide_cmd);
		if (isRequired)
			return -1;
		return GIT_PASSTHROUGH;
	}
	git__free(wide_cmd);

	if (commmand_start_stdout_reading_thread(&commandHandle, to)) {
		command_close(&commandHandle);
		return -1;
	}

	if (command_write_gitbuf(&commandHandle, from)) {
		DWORD exitCode = command_close(&commandHandle);
		if (exitCode)
			setProcessError(exitCode, &errBuf);
		git_buf_free(&errBuf);
		if (isRequired)
			return -1;
		return GIT_PASSTHROUGH;
	}
	command_close_stdin(&commandHandle);

	if (command_wait_stdout_reading_thread(&commandHandle)) {
		DWORD exitCode = command_close(&commandHandle);
		if (exitCode)
			setProcessError(exitCode, &errBuf);
		git_buf_free(&errBuf);
		if (isRequired)
			return -1;
		return GIT_PASSTHROUGH;
	}

	exitCode = command_close(&commandHandle);
	if (exitCode) {
		if (isRequired) {
			setProcessError(exitCode, &errBuf);
			git_buf_free(&errBuf);
			return -1;
		}
		git_buf_free(&errBuf);
		return GIT_PASSTHROUGH;
	}

	git_buf_free(&errBuf);

	return 0;
}
Example #25
0
//--------------------------------------------------------------------------------------
// Enumerate for each adapter all of the supported display modes, 
// device types, adapter formats, back buffer formats, window/full screen support, 
// depth stencil formats, multisampling types/qualities, and presentations intervals.
//
// For each combination of device type (HAL/REF), adapter format, back buffer format, and
// IsWindowed it will call the app's ConfirmDevice callback.  This allows the app
// to reject or allow that combination based on its caps/etc.  It also allows the 
// app to change the BehaviorFlags.  The BehaviorFlags defaults non-pure HWVP 
// if supported otherwise it will default to SWVP, however the app can change this 
// through the ConfirmDevice callback.
//--------------------------------------------------------------------------------------
_Use_decl_annotations_
HRESULT CD3D11Enumeration::Enumerate( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3D11DeviceAcceptableFunc,
                                      void* pIsD3D11DeviceAcceptableFuncUserContext )
{
    CDXUTPerfEventGenerator eventGenerator( DXUT_PERFEVENTCOLOR, L"DXUT D3D11 Enumeration" );
    HRESULT hr;
    auto pFactory = DXUTGetDXGIFactory();
    if( !pFactory )
        return E_FAIL;

    m_bHasEnumerated = true;
    m_IsD3D11DeviceAcceptableFunc = IsD3D11DeviceAcceptableFunc;
    m_pIsD3D11DeviceAcceptableFuncUserContext = pIsD3D11DeviceAcceptableFuncUserContext;

    ClearAdapterInfoList();

    for( int index = 0; ; ++index )
    {
        IDXGIAdapter* pAdapter = nullptr;
        hr = pFactory->EnumAdapters( index, &pAdapter );
        if( FAILED( hr ) ) // DXGIERR_NOT_FOUND is expected when the end of the list is hit
            break;

        IDXGIAdapter2* pAdapter2 = nullptr;
        if ( SUCCEEDED( pAdapter->QueryInterface( __uuidof(IDXGIAdapter2), ( LPVOID* )&pAdapter2 ) ) )
        {
            // Succeeds on DirectX 11.1 Runtime systems
            DXGI_ADAPTER_DESC2 desc;
            hr = pAdapter2->GetDesc2( &desc );
            pAdapter2->Release();

            if ( SUCCEEDED(hr) && ( desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE ) )
            {
                // Skip "always there" Microsoft Basics Display Driver
                pAdapter->Release();
                continue;
            }
        }

        auto pAdapterInfo = new (std::nothrow) CD3D11EnumAdapterInfo;
        if( !pAdapterInfo )
        {
            SAFE_RELEASE( pAdapter );
            return E_OUTOFMEMORY;
        }
        pAdapterInfo->AdapterOrdinal = index;
        pAdapter->GetDesc( &pAdapterInfo->AdapterDesc );
        pAdapterInfo->m_pAdapter = pAdapter;

        // Enumerate the device driver types on the adapter.
        hr = EnumerateDevices( pAdapterInfo );
        if( FAILED( hr ) )
        {
            delete pAdapterInfo;
            continue;
        }

        hr = EnumerateOutputs( pAdapterInfo );
        if( FAILED( hr ) || pAdapterInfo->outputInfoList.empty() )
        {
            delete pAdapterInfo;
            continue;
        }

        // Get info for each devicecombo on this device
        if( FAILED( hr = EnumerateDeviceCombos( pAdapterInfo ) ) )
        {
            delete pAdapterInfo;
            continue;
        }

        m_AdapterInfoList.push_back( pAdapterInfo );
    }

    //  If we did not get an adapter then we should still enumerate WARP and Ref.
    if (m_AdapterInfoList.size() == 0)
    {
        auto pAdapterInfo = new (std::nothrow) CD3D11EnumAdapterInfo;
        if( !pAdapterInfo )
        {
            return E_OUTOFMEMORY;
        }
        pAdapterInfo->bAdapterUnavailable = true;

        hr = EnumerateDevices( pAdapterInfo );

        // Get info for each devicecombo on this device
        if( FAILED( hr = EnumerateDeviceCombosNoAdapter(  pAdapterInfo ) ) )
        {
            delete pAdapterInfo;
        }

        if (SUCCEEDED(hr)) m_AdapterInfoList.push_back( pAdapterInfo );
    }

    //
    // Check for 2 or more adapters with the same name. Append the name
    // with some instance number if that's the case to help distinguish
    // them.
    //
    bool bUniqueDesc = true;
    for( size_t i = 0; i < m_AdapterInfoList.size(); i++ )
    {
        auto pAdapterInfo1 = m_AdapterInfoList[ i ];

        for( size_t j = i + 1; j < m_AdapterInfoList.size(); j++ )
        {
            auto pAdapterInfo2 = m_AdapterInfoList[ j ];
            if( wcsncmp( pAdapterInfo1->AdapterDesc.Description,
                pAdapterInfo2->AdapterDesc.Description, DXGI_MAX_DEVICE_IDENTIFIER_STRING ) == 0 )
            {
                bUniqueDesc = false;
                break;
            }
        }

        if( !bUniqueDesc )
            break;
    }

    for( auto it = m_AdapterInfoList.begin(); it != m_AdapterInfoList.end(); ++it )
    {
        wcscpy_s((*it)->szUniqueDescription, DXGI_MAX_DEVICE_IDENTIFIER_STRING, (*it)->AdapterDesc.Description);
        if( !bUniqueDesc )
        {
            WCHAR sz[32];
            swprintf_s( sz, 32, L" (#%u)", (*it)->AdapterOrdinal );
            wcscat_s( (*it)->szUniqueDescription, DXGI_MAX_DEVICE_IDENTIFIER_STRING, sz );
        }
    }

    // Check WARP max feature level
    {
        static const D3D_FEATURE_LEVEL fLvlWarp[] =
        {
#ifdef USE_DIRECT3D11_3
            D3D_FEATURE_LEVEL_12_1, D3D_FEATURE_LEVEL_12_0,
#endif
            D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1
        };

        ID3D11Device* pDevice = nullptr;
        hr = DXUT_Dynamic_D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_WARP, 0, 0, fLvlWarp, _countof(fLvlWarp),
                                             D3D11_SDK_VERSION, &pDevice, &m_warpFL, nullptr );
        if ( hr == E_INVALIDARG )
        {
#ifdef USE_DIRECT3D11_3
            // DirectX 11.1 runtime will not recognize FL 12.x, so try without it
            hr = DXUT_Dynamic_D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_WARP, 0, 0, &fLvlWarp[2], _countof(fLvlWarp) - 2,
                                                D3D11_SDK_VERSION, &pDevice, &m_warpFL, nullptr);
            if (hr == E_INVALIDARG)
            {
                // DirectX 11.0 runtime will not recognize FL 11.1+, so try without it
                hr = DXUT_Dynamic_D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_WARP, 0, 0, &fLvlWarp[3], _countof(fLvlWarp) - 3,
                                                    D3D11_SDK_VERSION, &pDevice, &m_warpFL, nullptr);
            }
#else
            // DirectX 11.0 runtime will not recognize FL 11.1, so try without it
            hr = DXUT_Dynamic_D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_WARP, 0, 0, &fLvlWarp[1], _countof(fLvlWarp) - 1,
                                                 D3D11_SDK_VERSION, &pDevice, &m_warpFL, nullptr );
#endif
        }

        if ( SUCCEEDED(hr) )
        {
            pDevice->Release();
        }
        else
            m_warpFL = D3D_FEATURE_LEVEL_10_1;
    }

    // Check REF max feature level
    {
        static const D3D_FEATURE_LEVEL fLvlRef[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1 };

        ID3D11Device* pDevice = nullptr;
        hr = DXUT_Dynamic_D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_REFERENCE, 0, 0, fLvlRef, _countof(fLvlRef),
                                             D3D11_SDK_VERSION, &pDevice, &m_refFL, nullptr );
        if ( hr == E_INVALIDARG )
        {
            // DirectX 11.0 runtime will not recognize FL 11.1, so try without it
            hr = DXUT_Dynamic_D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_REFERENCE, 0, 0, &fLvlRef[1], _countof(fLvlRef) - 1,
                                                 D3D11_SDK_VERSION, &pDevice, &m_refFL, nullptr );
        }

        if ( SUCCEEDED(hr) )
        {
            pDevice->Release();
        }
        else
            m_refFL = D3D_FEATURE_LEVEL_11_0;
    }

    return S_OK;
}
//--------------------------------------------------------------------------------------
// Enumerate for each adapter all of the supported display modes, 
// device types, adapter formats, back buffer formats, window/full screen support, 
// depth stencil formats, multisampling types/qualities, and presentations intervals.
//
// For each combination of device type (HAL/REF), adapter format, back buffer format, and
// IsWindowed it will call the app's ConfirmDevice callback.  This allows the app
// to reject or allow that combination based on its caps/etc.  It also allows the 
// app to change the BehaviorFlags.  The BehaviorFlags defaults non-pure HWVP 
// if supported otherwise it will default to SWVP, however the app can change this 
// through the ConfirmDevice callback.
//--------------------------------------------------------------------------------------
HRESULT CD3D11Enumeration::Enumerate( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3D11DeviceAcceptableFunc,
                                      void* pIsD3D11DeviceAcceptableFuncUserContext )
{
    CDXUTPerfEventGenerator eventGenerator( DXUT_PERFEVENTCOLOR, L"DXUT D3D11 Enumeration" );
    HRESULT hr;
    IDXGIFactory1* pFactory = DXUTGetDXGIFactory();
    if( pFactory == NULL )
        return E_FAIL;

    m_bHasEnumerated = true;
    m_IsD3D11DeviceAcceptableFunc = IsD3D11DeviceAcceptableFunc;
    m_pIsD3D11DeviceAcceptableFuncUserContext = pIsD3D11DeviceAcceptableFuncUserContext;

    ClearAdapterInfoList();

    for( int index = 0; ; ++index )
    {
        IDXGIAdapter* pAdapter = NULL;
        hr = pFactory->EnumAdapters( index, &pAdapter );
        if( FAILED( hr ) ) // DXGIERR_NOT_FOUND is expected when the end of the list is hit
            break;

        CD3D11EnumAdapterInfo* pAdapterInfo = new CD3D11EnumAdapterInfo;
        if( !pAdapterInfo )
        {
            SAFE_RELEASE( pAdapter );
            return E_OUTOFMEMORY;
        }
        ZeroMemory( pAdapterInfo, sizeof( CD3D11EnumAdapterInfo ) );
        pAdapterInfo->AdapterOrdinal = index;
        pAdapter->GetDesc( &pAdapterInfo->AdapterDesc );
        pAdapterInfo->m_pAdapter = pAdapter;

        // Enumerate the device driver types on the adapter.
        hr = EnumerateDevices( pAdapterInfo );
        if( FAILED( hr ) )
        {
            delete pAdapterInfo;
            continue;
        }

        hr = EnumerateOutputs( pAdapterInfo );
        if( FAILED( hr ) || pAdapterInfo->outputInfoList.GetSize() <= 0 )
        {
            delete pAdapterInfo;
            continue;
        }

        // Get info for each devicecombo on this device
        if( FAILED( hr = EnumerateDeviceCombos( pFactory, pAdapterInfo ) ) )
        {
            delete pAdapterInfo;
            continue;
        }

        hr = m_AdapterInfoList.Add( pAdapterInfo );
        if( FAILED( hr ) )
        {
            delete pAdapterInfo;
            return hr;
        }
    }


    //  If we did not get an adapter then we should still enumerate WARP and Ref.
    if (m_AdapterInfoList.GetSize() == 0) {


        CD3D11EnumAdapterInfo* pAdapterInfo = new CD3D11EnumAdapterInfo;
        if( !pAdapterInfo )
        {
            return E_OUTOFMEMORY;
        }
        ZeroMemory( pAdapterInfo, sizeof( CD3D11EnumAdapterInfo ) );
        pAdapterInfo->bAdapterUnavailable = true;

        hr = EnumerateDevices( pAdapterInfo );

        // Get info for each devicecombo on this device
        if( FAILED( hr = EnumerateDeviceCombosNoAdapter(  pAdapterInfo ) ) )
        {
            delete pAdapterInfo;
        }

        if (!FAILED(hr)) hr = m_AdapterInfoList.Add( pAdapterInfo );
    }

    //
    // Check for 2 or more adapters with the same name. Append the name
    // with some instance number if that's the case to help distinguish
    // them.
    //
    bool bUniqueDesc = true;
    CD3D11EnumAdapterInfo* pAdapterInfo;
    for( int i = 0; i < m_AdapterInfoList.GetSize(); i++ )
    {
        CD3D11EnumAdapterInfo* pAdapterInfo1 = m_AdapterInfoList.GetAt( i );

        for( int j = i + 1; j < m_AdapterInfoList.GetSize(); j++ )
        {
            CD3D11EnumAdapterInfo* pAdapterInfo2 = m_AdapterInfoList.GetAt( j );
            if( wcsncmp( pAdapterInfo1->AdapterDesc.Description,
                pAdapterInfo2->AdapterDesc.Description, DXGI_MAX_DEVICE_IDENTIFIER_STRING ) == 0 )
            {
                bUniqueDesc = false;
                break;
            }
        }

        if( !bUniqueDesc )
            break;
    }

    for( int i = 0; i < m_AdapterInfoList.GetSize(); i++ )
    {
        pAdapterInfo = m_AdapterInfoList.GetAt( i );

        wcscpy_s( pAdapterInfo->szUniqueDescription, 100, pAdapterInfo->AdapterDesc.Description );
        if( !bUniqueDesc )
        {
            WCHAR sz[100];
            swprintf_s( sz, 100, L" (#%d)", pAdapterInfo->AdapterOrdinal );
            wcscat_s( pAdapterInfo->szUniqueDescription, DXGI_MAX_DEVICE_IDENTIFIER_STRING, sz );
        }
    }

    return S_OK;
}
Example #27
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(STRINGIZE(RDOC_DLL_FILE) ".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 ENABLED(RDOC_X64)
    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");
  dynSymRefreshModuleList = (PSYMREFRESHMODULELIST)GetProcAddress(module, "SymRefreshModuleList");
  dynSymGetModuleInfo64W = (PSYMGETMODULEINFO64W)GetProcAddress(module, "SymGetModuleInfoW64");

  if(!dynSymInitializeW || !dynSymRefreshModuleList || !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;
}
Example #28
0
extern "C" __declspec(dllexport) bool __stdcall CallApplicationMain(PCALL_APPLICATION_MAIN_DATA data)
{
    HRESULT hr = S_OK;
    errno_t errno = 0;
    FnGetCLRRuntimeHost pfnGetCLRRuntimeHost = nullptr;
    ICLRRuntimeHost2* pCLRRuntimeHost = nullptr;
    TCHAR szCurrentDirectory[MAX_PATH];
    TCHAR szCoreClrDirectory[MAX_PATH];
    TCHAR lpCoreClrModulePath[MAX_PATH];
    size_t cchTrustedPlatformAssemblies = 0;
    LPWSTR pwszTrustedPlatformAssemblies = nullptr;

    if (data->klrDirectory) {
        errno = wcscpy_s(szCurrentDirectory, data->klrDirectory);
        CHECK_RETURN_VALUE_FAIL_EXIT_VIA_FINISHED(errno);
    }
    else {
        GetModuleDirectory(NULL, szCurrentDirectory);
    }

    HMODULE hCoreCLRModule = LoadCoreClr();
    if (!hCoreCLRModule)
    {
        printf_s("Failed to locate coreclr.dll.\n");
        return false;
    }

    // Get the path to the module
    DWORD dwCoreClrModulePathSize = GetModuleFileName(hCoreCLRModule, lpCoreClrModulePath, MAX_PATH);
    lpCoreClrModulePath[dwCoreClrModulePathSize] = '\0';

    GetModuleDirectory(hCoreCLRModule, szCoreClrDirectory);

    HMODULE ignoreModule;
    // Pin the module - CoreCLR.dll does not support being unloaded.
    if (!::GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN, lpCoreClrModulePath, &ignoreModule))
    {
        printf_s("Failed to pin coreclr.dll.\n");
        return false;
    }

    pfnGetCLRRuntimeHost = (FnGetCLRRuntimeHost)::GetProcAddress(hCoreCLRModule, "GetCLRRuntimeHost");
    if (!pfnGetCLRRuntimeHost)
    {
        printf_s("Failed to find export GetCLRRuntimeHost.\n");
        return false;
    }

    hr = pfnGetCLRRuntimeHost(IID_ICLRRuntimeHost2, (IUnknown**)&pCLRRuntimeHost);
    if (FAILED(hr))
    {
        printf_s("Failed to get IID_ICLRRuntimeHost2.\n");
        return false;
    }

    STARTUP_FLAGS dwStartupFlags = (STARTUP_FLAGS)(
        STARTUP_FLAGS::STARTUP_LOADER_OPTIMIZATION_SINGLE_DOMAIN |
        STARTUP_FLAGS::STARTUP_SINGLE_APPDOMAIN |
        STARTUP_FLAGS::STARTUP_SERVER_GC
        );

    pCLRRuntimeHost->SetStartupFlags(dwStartupFlags);

    // Authenticate with either CORECLR_HOST_AUTHENTICATION_KEY or CORECLR_HOST_AUTHENTICATION_KEY_NONGEN 
    hr = pCLRRuntimeHost->Authenticate(CORECLR_HOST_AUTHENTICATION_KEY);
    if (FAILED(hr))
    {
        printf_s("Failed to Authenticate().\n");
        return false;
    }

    hr = pCLRRuntimeHost->Start();

    if (FAILED(hr))
    {
        printf_s("Failed to Start().\n");
        return false;
    }

    const wchar_t* property_keys[] =
    {
        // Allowed property names:
        // APPBASE
        // - The base path of the application from which the exe and other assemblies will be loaded
        L"APPBASE",
        //
        // TRUSTED_PLATFORM_ASSEMBLIES
        // - The list of complete paths to each of the fully trusted assemblies
        L"TRUSTED_PLATFORM_ASSEMBLIES",
        //
        // APP_PATHS
        // - The list of paths which will be probed by the assembly loader
        L"APP_PATHS",
        //
        // APP_NI_PATHS
        // - The list of additional paths that the assembly loader will probe for ngen images
        //
        // NATIVE_DLL_SEARCH_DIRECTORIES
        // - The list of paths that will be probed for native DLLs called by PInvoke
        //
    };

    cchTrustedPlatformAssemblies = TRUSTED_PLATFORM_ASSEMBLIES_STRING_BUFFER_SIZE_CCH;
    pwszTrustedPlatformAssemblies = (LPWSTR)calloc(cchTrustedPlatformAssemblies+1, sizeof(WCHAR));
    if (pwszTrustedPlatformAssemblies == NULL)
    {
        goto Finished;
    }
    pwszTrustedPlatformAssemblies[0] = L'\0';
    
    // Try native images first
    if (!ScanDirectory(szCoreClrDirectory, L"*.ni.dll", pwszTrustedPlatformAssemblies, cchTrustedPlatformAssemblies))
    {
        if (!ScanDirectory(szCoreClrDirectory, L"*.dll", pwszTrustedPlatformAssemblies, cchTrustedPlatformAssemblies))
        {
            printf_s("Failed to find files in the coreclr directory\n");
            return false;
        }
    }

    // Add the assembly containing the app domain manager to the trusted list

    errno = wcscat_s(pwszTrustedPlatformAssemblies, cchTrustedPlatformAssemblies, szCurrentDirectory);
    CHECK_RETURN_VALUE_FAIL_EXIT_VIA_FINISHED(errno);

    errno = wcscat_s(pwszTrustedPlatformAssemblies, cchTrustedPlatformAssemblies, L"klr.core45.managed.dll");
    CHECK_RETURN_VALUE_FAIL_EXIT_VIA_FINISHED(errno);

    //wstring appPaths(szCurrentDirectory);
    WCHAR wszAppPaths[MAX_PATH];
    wszAppPaths[0] = L'\0';

    errno = wcscat_s(wszAppPaths, _countof(wszAppPaths), szCurrentDirectory);
    CHECK_RETURN_VALUE_FAIL_EXIT_VIA_FINISHED(errno);

    errno = wcscat_s(wszAppPaths, _countof(wszAppPaths), L";");
    CHECK_RETURN_VALUE_FAIL_EXIT_VIA_FINISHED(errno);

    errno = wcscat_s(wszAppPaths, _countof(wszAppPaths), szCoreClrDirectory);
    CHECK_RETURN_VALUE_FAIL_EXIT_VIA_FINISHED(errno);

    errno = wcscat_s(wszAppPaths, _countof(wszAppPaths), L";");
    CHECK_RETURN_VALUE_FAIL_EXIT_VIA_FINISHED(errno);

    const wchar_t* property_values[] = {
        // APPBASE
        data->applicationBase,
        // TRUSTED_PLATFORM_ASSEMBLIES
        pwszTrustedPlatformAssemblies,
        // APP_PATHS
        wszAppPaths,
    };

    DWORD domainId;
    DWORD dwFlagsAppDomain =
        APPDOMAIN_ENABLE_PLATFORM_SPECIFIC_APPS |
        APPDOMAIN_ENABLE_PINVOKE_AND_CLASSIC_COMINTEROP;

    LPCWSTR szAssemblyName = L"klr.core45.managed, Version=0.1.0.0";
    LPCWSTR szEntryPointTypeName = L"DomainManager";
    LPCWSTR szMainMethodName = L"Execute";

    int nprops = sizeof(property_keys) / sizeof(wchar_t*);

    hr = pCLRRuntimeHost->CreateAppDomainWithManager(
        L"klr.core45.managed",
        dwFlagsAppDomain,
        NULL,
        NULL,
        nprops,
        property_keys,
        property_values,
        &domainId);

    if (FAILED(hr))
    {
        wprintf_s(L"TPA      %d %s\n", wcslen(pwszTrustedPlatformAssemblies), pwszTrustedPlatformAssemblies);
        wprintf_s(L"AppPaths %s\n", wszAppPaths);
        printf_s("Failed to create app domain (%d).\n", hr);
        return false;
    }

    HostMain pHostMain;

    hr = pCLRRuntimeHost->CreateDelegate(
        domainId,
        szAssemblyName,
        szEntryPointTypeName,
        szMainMethodName,
        (INT_PTR*)&pHostMain);

    if (FAILED(hr))
    {
        printf_s("Failed to create main delegate (%d).\n", hr);
        return false;
    }

    // REVIEW: Versioning? k 1.0, 2.0?
    SetEnvironmentVariable(L"TARGET_FRAMEWORK", L"k10");

    // Call main
    data->exitcode = pHostMain(data->argc, data->argv);

    pCLRRuntimeHost->UnloadAppDomain(domainId, true);

    pCLRRuntimeHost->Stop();
    
Finished:    
    if (pwszTrustedPlatformAssemblies != NULL)
    {
        free(pwszTrustedPlatformAssemblies);
        pwszTrustedPlatformAssemblies = NULL;
    }

    if (FAILED(hr))
    {
        return false;
    }
    else
    {
        return true;
    }
}
void wmain( int argc, wchar_t *argv[ ])
{

//Handle the command line arguments.
LPOLESTR pszBuffer = NULL;
pszBuffer = new OLECHAR[MAX_PATH*2];
if(pszBuffer == NULL)
    goto ret;
if (argv[1] == NULL)
{
	wprintf(L"This program finds a user in the current Window 2000 domain\n");
	wprintf(L"and displays its objectSid property in string form.\n");
	wprintf(L"This program demonstrates reading a property of type octet string.\n\n");
	
	wprintf(L"Enter Common Name of the user to find:");
	if ( !_getws_s(pszBuffer, MAX_PATH*2))
	{
		delete [] pszBuffer;
		wprintf(L"String exceeded buffer size.\n\n");
		return;
	}
}
else
   if ( !wcscpy_s(pszBuffer, MAX_PATH*2, argv[1]))
   {
	    delete [] pszBuffer;
		wprintf(L"String exceeded buffer size.\n\n");
		return;
   }
//if empty string, exit.
if (0==wcscmp(L"", pszBuffer))
   goto ret;
	
wprintf(L"\nFinding user: %s...\n",pszBuffer);
	
//Intialize COM
CoInitialize(NULL);
HRESULT hr = S_OK;
//Get rootDSE and the domain container's DN.
IADs *pObject = NULL;
IDirectorySearch *pDS = NULL;
LPOLESTR szPath = NULL;
szPath = new OLECHAR[MAX_PATH];
if(szPath == NULL)
    goto ret;

VARIANT var;
hr = ADsOpenObject(L"LDAP://rootDSE",
				 NULL,
				 NULL,
				 ADS_SECURE_AUTHENTICATION, //Use Secure Authentication
				 IID_IADs,
				 (void**)&pObject);
if (FAILED(hr))
{
   wprintf(L"Not Found. Could not bind to the domain.\n");
   if (pObject)
     pObject->Release();
   goto ret;
}

VariantInit(&var);
hr = pObject->Get(L"defaultNamingContext",&var);
if (SUCCEEDED(hr))
{
	wcscpy_s(szPath,MAX_PATH,L"LDAP://");
	wcscat_s(szPath,MAX_PATH,var.bstrVal);
	VariantClear(&var);
	if (pObject)
	{
	   pObject->Release();
	   pObject = NULL;
	}
	//Bind to the root of the current domain.
	hr = ADsOpenObject(szPath,
					 NULL,
					 NULL,
					 ADS_SECURE_AUTHENTICATION, //Use Secure Authentication
					 IID_IDirectorySearch,
					 (void**)&pDS);
	if (SUCCEEDED(hr))
	{
		hr =  FindUserByName(pDS, //Container to search
						   pszBuffer, //Name of user to find.
						   &pObject); //Return a pointer to the user
		if (SUCCEEDED(hr))
		{
			//Get the objectSid property
			hr = pObject->Get(L"objectSid", &var);
			if (SUCCEEDED(hr))
			{
				LPBYTE pByte = NULL;
				wprintf (L"----------------------------------------------\n");
				wprintf (L"----------Call GetLPBYTEtoOctetString---------\n");
				wprintf (L"----------------------------------------------\n");
				hr = GetLPBYTEtoOctetString(&var, //IN. Pointer to variant containing the octetstring.
							   &pByte //OUT. Return LPBYTE to the data represented in octetstring.
							   );

				PSID pObjectSID = (PSID)pByte;
				//Convert SID to string.
				LPOLESTR szSID = NULL;
				ConvertSidToStringSid(pObjectSID, &szSID);
				wprintf(L"objectSid:%s\n",szSID);
				LocalFree(szSID);
				//Free the buffer.
				CoTaskMemFree(pByte);
			}
			else
				wprintf(L"Get method failed with hr: %x\n",hr);
			VariantClear(&var);
		}
		else
		{
            wprintf(L"User \"%s\" not Found.\n",pszBuffer);
			wprintf (L"FindUserByName failed with the following HR: %x\n", hr);
		}
		if (pObject)
			pObject->Release();
	}

	if (pDS)
	   pDS->Release();
}
ret:
    if(pszBuffer) delete pszBuffer;
    if(szPath)     delete szPath;
//Uninitalize COM
CoUninitialize();

	return;
}
Example #30
0
char GetVolumeLabelByDiskNumber(DWORD dwDeviceNumber)
{
	/*
	The returned value is like
	C:\ and a null terminator 
	seperating each drive root
	hence 4 characters per letter
	*/
	wchar_t wszDrives[26 * 4];

	DWORD dwSize = GetLogicalDriveStrings(sizeof(wszDrives), wszDrives);
	DWORD dwBytesReturned = 0;
	if (dwSize)
	{
		for (unsigned int uiCharIndex = 0; uiCharIndex <= dwSize; uiCharIndex += 4)
		{
			STORAGE_DEVICE_NUMBER storageDeviceNumber;
			ZeroMemory(&storageDeviceNumber, sizeof(STORAGE_DEVICE_NUMBER));
			storageDeviceNumber.DeviceNumber = 0;

			/*
			To obtain a drive handle we 
			need to use CreateFile with
			a path like \\.\C:
			*/
			wchar_t wszDrivePath[MAX_PATH];
			wcscpy_s(wszDrivePath, L"\\\\.\\");
			wcscat_s(wszDrivePath, wszDrives + uiCharIndex);
			wszDrivePath[wcslen(wszDrivePath) - 1] = L'\0';

			HANDLE hDrive = CreateFile(
				wszDrivePath,
				GENERIC_READ,
				FILE_SHARE_READ |
				FILE_SHARE_WRITE,
				NULL,
				OPEN_EXISTING,
				0,
				0
				);

			if (hDrive != INVALID_HANDLE_VALUE)
			{
				/*
				Get the device number of the
				device and compare it to our
				device's device number
				*/
				BOOL bResult = DeviceIoControl(
					hDrive,
					IOCTL_STORAGE_GET_DEVICE_NUMBER,
					NULL,
					0,
					&storageDeviceNumber,
					sizeof(storageDeviceNumber),
					&dwBytesReturned,
					NULL
					);
				if (bResult && dwBytesReturned)
				{
					if (storageDeviceNumber.DeviceNumber == dwDeviceNumber)
					{
						char cDrive = wctob(wszDrives[uiCharIndex]);
						return cDrive;
					}
				}
			}
			CloseHandle(hDrive);
		}
	}
	return NULL;
}