当前位置: 首页>>代码示例>>C++>>正文


C++ VirtualAllocEx函数代码示例

本文整理汇总了C++中VirtualAllocEx函数的典型用法代码示例。如果您正苦于以下问题:C++ VirtualAllocEx函数的具体用法?C++ VirtualAllocEx怎么用?C++ VirtualAllocEx使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了VirtualAllocEx函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: InjectDLL

bool InjectDLL(DWORD processID, const char* dllLocation)
{
    // gets a module handler which loaded by the process which
    // should be injected
    HMODULE hModule = GetModuleHandle("kernel32.dll");
    if (!hModule)
    {
        printf("ERROR: Can't get 'kernel32.dll' handle, ");
        printf("ErrorCode: %u\n", GetLastError());
        return false;
    }

    // gets the address of an exported function which can load DLLs
    FARPROC loadLibraryAddress = GetProcAddress(hModule, "LoadLibraryA");
    if (!loadLibraryAddress)
    {
        printf("ERROR: Can't get function 'LoadLibraryA' address, ");
        printf("ErrorCode: %u\n", GetLastError());
        return false;
    }

    // opens the process which should be injected
    HANDLE hProcess = OpenClientProcess(processID);
    if (!hProcess)
    {
        printf("Process [%u] '%s' open is failed.\n", processID, lookingProcessName);
        return false;
    }
    printf("\nProcess [%u] '%s' is opened.\n", processID, lookingProcessName);

    // gets the build number
    WORD buildNumber = GetBuildNumberFromProcess(hProcess);
    // error occured
    if (!buildNumber)
    {
        printf("Can't determine build number.\n");
        CloseHandle(hProcess);
        return false;
    }
    printf("Detected build number: %hu\n", buildNumber);

    // checks this build is supported or not
    HookEntry hookEntry;
    if (!GetOffsets(NULL, buildNumber, &hookEntry))
    {
        printf("ERROR: This build number is not supported.\n");
        CloseHandle(hProcess);
        return false;
    }

    // allocates memory for the DLL location string
    LPVOID allocatedMemoryAddress = VirtualAllocEx(hProcess, NULL, strlen(dllLocation), MEM_COMMIT, PAGE_READWRITE);
    if (!allocatedMemoryAddress)
    {
        printf("ERROR: Virtual memory allocation is failed, ");
        printf("ErrorCode: %u.\n", GetLastError());
        CloseHandle(hProcess);
        return false;
    }

    // writes the DLL location string to the process
    // so this is the parameter which will be passed to LoadLibraryA
    if (!WriteProcessMemory(hProcess, allocatedMemoryAddress, dllLocation, strlen(dllLocation), NULL))
    {
        printf("ERROR: Process memory writing is failed, ");
        printf("ErrorCode: %u\n", GetLastError());
        VirtualFreeEx(hProcess, allocatedMemoryAddress, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    // creates a thread that runs in the virtual address space of
    // the process which should be injected and gives the
    // parameter (allocatedMemoryAddress) to LoadLibraryA(loadLibraryAddress)
    HANDLE hRemoteThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)loadLibraryAddress, allocatedMemoryAddress, 0, NULL);
    if (!hRemoteThread)
    {
        printf("ERROR: Remote thread creation is failed, ");
        printf("ErrorCode: %u\n", GetLastError());
        VirtualFreeEx(hProcess, allocatedMemoryAddress, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    // waits until the DLL's main function returns
    WaitForSingleObject(hRemoteThread, INFINITE);

    // frees resources
    VirtualFreeEx(hProcess, allocatedMemoryAddress, 0, MEM_RELEASE);
    CloseHandle(hRemoteThread);
    CloseHandle(hProcess);

    return true;
}
开发者ID:Lordron,项目名称:SzimatSzatyor,代码行数:94,代码来源:szatyor.cpp

示例2: VirtualAlloc

/***********************************************************************
 *             VirtualAlloc   ([email protected])
 *
 * Reserves or commits a region of pages in virtual address space.
 *
 * PARAMS
 *  addr    [I] Address of region to reserve or commit.
 *  size    [I] Size of region.
 *  type    [I] Type of allocation.
 *  protect [I] Type of access protection.
 *
 * RETURNS
 *	Success: Base address of allocated region of pages.
 *	Failure: NULL.
 */
LPVOID WINAPI DECLSPEC_HOTPATCH VirtualAlloc( void *addr, SIZE_T size, DWORD type, DWORD protect )
{
    return VirtualAllocEx( GetCurrentProcess(), addr, size, type, protect );
}
开发者ID:wine-mirror,项目名称:wine,代码行数:19,代码来源:virtual.c

示例3: main

int main(int argc, char* argv[])
{
    DWORD dwProcessId = GetCurrentProcessId();
    char szProcessName[256] = {0};
    char szModuleName[MAX_PATH] = {0};

    for (int i = 1; i < argc; i++) {
        if (_stricmp(argv[i], "-pid") == 0 && i < (argc - 1)) {
            dwProcessId = atoi(argv[i + 1]);
        }

        if (_stricmp(argv[i], "-name") == 0 && i < (argc - 1)) {
            strcpy_s(szProcessName, argv[i + 1]);
        }

        if (_stricmp(argv[i], "-dll") == 0 && i < (argc - 1)) {
            strcpy_s(szModuleName, argv[i + 1]);
        }
    }

    if (strlen(szModuleName) == 0) {
        printf("Module name is required...\n");
        return 0;
    }

    if (strlen(szProcessName) == 0 && dwProcessId == GetCurrentProcessId()) {
        printf("Invalid parameters!\n");
        return 0;
    }

    if (strlen(szProcessName) > 0) {
        if (dwProcessId == GetCurrentProcessId()) { // Only change the processid if it's not already set
            dwProcessId = GetProcessIdFromProcessName(szProcessName);

            if (dwProcessId == GetCurrentProcessId()) {
                printf("Failed to obtain process \"%s\"...\n", szProcessName);
                return 0;
            }
        }
    }

    HMODULE hKernel = LoadLibraryA("kernel32.dll");
    DWORD64 dwLoadLibraryA = (DWORD64) GetProcAddress(hKernel, "LoadLibraryA") - (DWORD64) hKernel;
    printf("kernel32.dll: %016llX\n", hKernel);
    printf("LoadLibraryA: %016llX\n", dwLoadLibraryA);
    printf("Module Name: %s\n", szModuleName);
    char szCurrentModulePath[MAX_PATH] = {0};
    GetModuleFileNameA(GetModuleHandle(NULL), szCurrentModulePath, MAX_PATH);

    for (size_t i = strlen(szCurrentModulePath); i > 0; i--) {
        if (szCurrentModulePath[ i ] == '\\') {
            szCurrentModulePath[ i + 1 ] = 0;
            break;
        }
    }

    strcat_s(szCurrentModulePath, szModuleName);
    printf("Full Path: %s\n", szCurrentModulePath);
    DWORD dwFileAttributes = GetFileAttributesA(szCurrentModulePath);

    if (dwFileAttributes == INVALID_FILE_ATTRIBUTES && GetLastError() == ERROR_FILE_NOT_FOUND) {
        printf("File not found...\n");
        return 0;
    }

    printf("Injecting: %s\n", szCurrentModulePath);
    HMODULE hRemoteKernel = GetRemoteModuleHandleA(dwProcessId, "kernel32.dll");

    if (hRemoteKernel == NULL) {
        printf("Failed to locate kernel32 in remote process...\n");
        return 0;
    }

    printf("kernel32 (remote): 0x%016llX\n", hRemoteKernel);
    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessId);

    if (hProcess == INVALID_HANDLE_VALUE) {
        printf("Failed to locate remote process...\n");
        return 0;
    }

    LPVOID lpModuleName = VirtualAllocEx(hProcess, NULL, strlen(szCurrentModulePath) + 1, MEM_COMMIT, PAGE_EXECUTE_READWRITE);

    if (lpModuleName == NULL) {
        printf("Failed to allocate module name in remote process...\n");
        return 0;
    }

    if (WriteProcessMemory(hProcess, lpModuleName, szCurrentModulePath, strlen(szCurrentModulePath), NULL) == FALSE) {
        printf("Failed to write module name in remote process...\n");
        return 0;
    }

    DWORD64 dwRemoteLoadLibraryAddress = ((DWORD64)hRemoteKernel + dwLoadLibraryA);
    printf("LoadLibraryA (remote): %016llX\n", dwRemoteLoadLibraryAddress);
    HANDLE hThread = CreateRemoteThread(hProcess, 0, 0, (LPTHREAD_START_ROUTINE) dwRemoteLoadLibraryAddress, lpModuleName, 0, 0);
    printf("Injecting... ");
    WaitForSingleObject(hThread, INFINITE);
    printf("Injected!\n");
    return 0;
//.........这里部分代码省略.........
开发者ID:wyrover,项目名称:win-sys,代码行数:101,代码来源:main.cpp

示例4: if

void CodeInjectionPlayer::InjectCode()
{
	if (!opts.enable_code_injection)
		return;
	else if (next_request_time > GetTickCount())
		return;

	// Window is opened?
	HWND hwnd = FindWindow();
	if (hwnd == nullptr)
		return;

	// Msg Window is registered? (aka plugin is running?)
	HWND msgHwnd = ::FindWindow(message_window_class, nullptr);
	if (msgHwnd != nullptr)
		return;


	next_request_time = GetTickCount() + 30000;


	// Get the dll path
	char dll_path[1024] = { 0 };
	if (!GetModuleFileNameA(g_plugin.getInst(), dll_path, _countof(dll_path)))
		return;

	char *p = strrchr(dll_path, '\\');
	if (p == nullptr)
		return;

	p++;
	*p = '\0';

	size_t len = p - dll_path;

	mir_snprintf(p, 1024 - len, "listeningto\\%s.dll", dll_name);

	len = strlen(dll_path);

	// File exists?
	DWORD attribs = GetFileAttributesA(dll_path);
	if (attribs == 0xFFFFFFFF || !(attribs & FILE_ATTRIBUTE_ARCHIVE))
		return;

	// Do the code injection
	unsigned long pid;
	GetWindowThreadProcessId(hwnd, &pid);
	HANDLE hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION
		| PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, pid);
	if (hProcess == nullptr)
		return;

	char *_dll = (char *)VirtualAllocEx(hProcess, nullptr, len + 1, MEM_COMMIT, PAGE_READWRITE);
	if (_dll == nullptr) {
		CloseHandle(hProcess);
		return;
	}
	WriteProcessMemory(hProcess, _dll, dll_path, len + 1, nullptr);

	HMODULE hKernel32 = GetModuleHandleA("kernel32");
	HANDLE hLoadLibraryA = GetProcAddress(hKernel32, "LoadLibraryA");
	DWORD threadId;
	HANDLE hThread = CreateRemoteThread(hProcess, nullptr, 0, (LPTHREAD_START_ROUTINE)hLoadLibraryA, _dll, 0, &threadId);
	if (hThread == nullptr) {
		VirtualFreeEx(hProcess, _dll, len + 1, MEM_RELEASE);
		CloseHandle(hProcess);
		return;
	}
	WaitForSingleObject(hThread, INFINITE);
	CloseHandle(hThread);
	VirtualFreeEx(hProcess, _dll, len + 1, MEM_RELEASE);
	CloseHandle(hProcess);
}
开发者ID:tweimer,项目名称:miranda-ng,代码行数:73,代码来源:player.cpp

示例5: demoSuspendInjectResume

DWORD demoSuspendInjectResume(PCWSTR pszLibFile, DWORD dwProcessId)
{
	void *stub;
	unsigned long threadID, oldIP, oldprot;
	HANDLE hThread;
	CONTEXT ctx;

	DWORD stubLen = sizeof(sc);

	HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessId);
	if (hProcess == NULL)
	{
		wprintf(L"[-] Error: Could not open process for PID (%d).\n", dwProcessId);
		return(1);
	}
	DWORD LoadLibraryAddress = (DWORD)GetProcAddress(GetModuleHandle(L"kernel32.dll"), "LoadLibraryW");
	if (LoadLibraryAddress == NULL)
	{
		wprintf(L"[-] Error: Could not find LoadLibraryA function inside kernel32.dll library.\n");
		exit(1);
	}

	SIZE_T dwSize = (wcslen(pszLibFile) + 1) * sizeof(wchar_t);

	LPVOID lpDllAddr = VirtualAllocEx(hProcess, NULL, dwSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); 
	if (lpDllAddr == NULL)
	{
		wprintf(L"[-] Error: Could not allocate memory inside PID (%d).\n", dwProcessId);
		exit(1);
	}

	stub = VirtualAllocEx(hProcess, NULL, stubLen, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
	if (stub == NULL)
	{
		wprintf(L"[-] Error: Could not allocate memory for stub.\n");
		exit(1);
	}

	BOOL bStatus = WriteProcessMemory(hProcess, lpDllAddr, pszLibFile, dwSize, NULL);
	if (bStatus == 0)
	{
		wprintf(L"[-] Error: Could not write any bytes into the PID (%d) address space.\n", dwProcessId);
		return(1);
	}

	threadID = getThreadID(dwProcessId);
	hThread = OpenThread((THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_SUSPEND_RESUME), false, threadID);
	if (hThread != NULL)
	{
		SuspendThread(hThread);
	}
	else
		printf("could not open thread\n");

	ctx.ContextFlags = CONTEXT_CONTROL;
	GetThreadContext(hThread, &ctx);
	oldIP = ctx.Eip;
	ctx.Eip = (DWORD)stub;
	ctx.ContextFlags = CONTEXT_CONTROL;

	VirtualProtect(sc, stubLen, PAGE_EXECUTE_READWRITE, &oldprot);
	memcpy((void *)((unsigned long)sc + 1), &oldIP, 4);
	memcpy((void *)((unsigned long)sc + 8), &lpDllAddr, 4);
	memcpy((void *)((unsigned long)sc + 13), &LoadLibraryAddress, 4);

	WriteProcessMemory(hProcess, stub, sc, stubLen, NULL);
	SetThreadContext(hThread, &ctx);

	ResumeThread(hThread);

	Sleep(8000);

	VirtualFreeEx(hProcess, lpDllAddr, dwSize, MEM_DECOMMIT);
	VirtualFreeEx(hProcess, stub, stubLen, MEM_DECOMMIT);
	CloseHandle(hProcess);
	CloseHandle(hThread);

	return(0);
}
开发者ID:owen7500,项目名称:injectAllTheThings,代码行数:79,代码来源:t_suspendInjectResume.cpp

示例6: OpenProcess

bool ServerBrowser::InjectLibraryIntoProcess(DWORD dwProcessId, char * szLibraryPath)
{
        bool bReturn = true;

        // Open our target process
        HANDLE hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, dwProcessId);

        if(!hProcess) {
                // Failed to open the process
                MessageBoxA(NULL, "Failed to open the remote process.", NULL, NULL);
                return false;
        }

        // Get the length of the library path
        size_t sLibraryPathLen = (strlen(szLibraryPath) + 1);

        // Allocate the a block of memory in our target process for the library name
        void * pRemoteLibraryPath = VirtualAllocEx(hProcess, NULL, sLibraryPathLen, MEM_COMMIT, PAGE_READWRITE);

        // Write our library name to the allocated block of memory
        SIZE_T sBytesWritten = 0;
        WriteProcessMemory(hProcess, pRemoteLibraryPath, (void *)szLibraryPath, sLibraryPathLen, &sBytesWritten);

        if(sBytesWritten != sLibraryPathLen) {
                MessageBoxA(NULL, "Failed to write library path into remote process.", NULL, NULL);
                bReturn = false;
        } else {
                // Get the handle of Kernel32.dll
                HMODULE hKernel32 = GetModuleHandle(L"Kernel32");

                // Get the address of the LoadLibraryA function from Kernel32.dll
                FARPROC pfnLoadLibraryA = GetProcAddress(hKernel32, "LoadLibraryA");

                // Create a thread inside the target process to load our library
                HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)pfnLoadLibraryA, pRemoteLibraryPath, 0, NULL);

                if(hThread) {
                        // Wait for the created thread to end
                        WaitForSingleObject(hThread, INFINITE);

                        // Get the remote thread exit code
                        /*DWORD dwExitCode;
                        GetExitCodeThread(hThread, &dwExitCode);

                        if(dwExitCode != 0)
                        {
                                IVMessageBox("Failed to inject library into remote process. Cannot launch IV:MP.");
                                bReturn = false;
                        }*/

                        // Close our thread handle
                        CloseHandle(hThread);
                } else {
                        // Thread creation failed
                        MessageBoxA(NULL, "Failed to create remote thread in remote process.", NULL, NULL);
                        bReturn = false;
                }
        }

        // Free the allocated block of memory inside the target process
        VirtualFreeEx(hProcess, pRemoteLibraryPath, sizeof(pRemoteLibraryPath), MEM_RELEASE);

        // If the injection failed terminate the target process
        if(!bReturn)
                TerminateProcess(hProcess, 0);

        // Close our target process
        CloseHandle(hProcess);

        return bReturn;
}
开发者ID:Tonyx97,项目名称:vice-players,代码行数:71,代码来源:serverbrowser.cpp

示例7: InfiltrateDll

// 0 - OK, иначе - ошибка
// Здесь вызывается CreateRemoteThread
int InfiltrateDll(HANDLE hProcess, LPCWSTR asConEmuHk)
{
	int iRc = -150;

	//if (iRc != -150)
	//{
	//	InfiltrateProc(NULL); InfiltrateEnd();
	//}
	//const size_t cb = ((size_t)InfiltrateEnd) - ((size_t)InfiltrateProc);

	InfiltrateArg dat = {};
	HMODULE hKernel = NULL;
	HANDLE hThread = NULL;
	DWORD id = 0;
	LPTHREAD_START_ROUTINE pRemoteProc = NULL;
	PVOID pRemoteDat = NULL;
	CreateRemoteThread_t _CreateRemoteThread = NULL;
	char FuncName[20];
	void* ptrCode;
	size_t cbCode;

	//_ASSERTE("InfiltrateDll"==(void*)TRUE);

	cbCode = GetInfiltrateProc(&ptrCode);
	// Примерно, проверка размера кода созданного компилятором
	if (cbCode != WIN3264TEST(68,79))
	{
		_ASSERTE(cbCode == WIN3264TEST(68,79));
		iRc = -100;
		goto wrap;
	}

	if (lstrlen(asConEmuHk) >= (int)countof(dat.szConEmuHk))
	{
		iRc = -101;
		goto wrap;
	}

	// Исполняемый код загрузки библиотеки
	pRemoteProc = (LPTHREAD_START_ROUTINE) VirtualAllocEx(
		hProcess,	// Target process
		NULL,		// Let the VMM decide where
		cbCode,		// Size
		MEM_COMMIT,	// Commit the memory
		PAGE_EXECUTE_READWRITE); // Protections
	if (!pRemoteProc)
	{
		iRc = -102;
		goto wrap;
	}
	if (!WriteProcessMemory(
		hProcess,		// Target process
		(void*)pRemoteProc,	// Source for code
		ptrCode,		// The code
		cbCode,			// Code length
		NULL))			// We don't care
	{
		iRc = -103;
		goto wrap;
	}

	// Путь к нашей библиотеке
	lstrcpyn(dat.szConEmuHk, asConEmuHk, countof(dat.szConEmuHk));

	// Kernel-процедуры
	hKernel = LoadLibrary(L"Kernel32.dll");
	if (!hKernel)
	{
		iRc = -104;
		goto wrap;
	}

	// Избежать статической линковки и строки "CreateRemoteThread" в бинарнике
	FuncName[ 0] = 'C'; FuncName[ 2] = 'e'; FuncName[ 4] = 't'; FuncName[ 6] = 'R'; FuncName[ 8] = 'm';
	FuncName[ 1] = 'r'; FuncName[ 3] = 'a'; FuncName[ 5] = 'e'; FuncName[ 7] = 'e'; FuncName[ 9] = 'o';
	FuncName[10] = 't'; FuncName[12] = 'T'; FuncName[14] = 'r'; FuncName[16] = 'a';
	FuncName[11] = 'e'; FuncName[13] = 'h'; FuncName[15] = 'e'; FuncName[17] = 'd'; FuncName[18] = 0;
	_CreateRemoteThread = (CreateRemoteThread_t)GetProcAddress(hKernel, FuncName);

	// Functions for external process. MUST BE SAME ADDRESSES AS CURRENT PROCESS.
	// kernel32.dll компонуется таким образом, что всегда загружается по одному определенному адресу в памяти
	// Поэтому адреса процедур для приложений одинаковой битности совпадают (в разных процессах)
	dat._GetLastError = (GetLastError_t)GetProcAddress(hKernel, "GetLastError");
	dat._SetLastError = (SetLastError_t)GetProcAddress(hKernel, "SetLastError");
	dat._LoadLibraryW = (LoadLibraryW_t)GetLoadLibraryAddress(); // GetProcAddress(hKernel, "LoadLibraryW");
	if (!_CreateRemoteThread || !dat._LoadLibraryW || !dat._SetLastError || !dat._GetLastError)
	{
		iRc = -105;
		goto wrap;
	}
	else
	{
		// Проверим, что адреса этих функций действительно лежат в модуле Kernel32.dll
		// и не были кем-то перехвачены до нас.
		FARPROC proc[] = {(FARPROC)dat._GetLastError, (FARPROC)dat._SetLastError, (FARPROC)dat._LoadLibraryW};
		if (!CheckCallbackPtr(hKernel, countof(proc), proc, TRUE, TRUE))
		{
			// Если функции перехвачены - попытка выполнить код по этим адресам
//.........这里部分代码省略.........
开发者ID:NickLatysh,项目名称:conemu,代码行数:101,代码来源:InjectRemote.cpp

示例8: MapNewExecutableRegionInProcess

BOOL MapNewExecutableRegionInProcess(
		IN HANDLE TargetProcessHandle,
		IN HANDLE TargetThreadHandle,
		IN LPVOID NewExecutableRawImage)
{
	PROCESS_INFORMATION       BasicInformation;
	PIMAGE_SECTION_HEADER     SectionHeader;
	PIMAGE_DOS_HEADER         DosHeader;
	PIMAGE_NT_HEADERS         NtHeader64;
	DWORD_PTR                 dwImageBase;
	NtUnmapViewOfSection      pNtUnmapViewOfSection;
	LPVOID                    pImageBase;
	SIZE_T                    dwBytesWritten;
	SIZE_T                    dwBytesRead;
	int                       Count;
	PCONTEXT                  ThreadContext;
	BOOL                      Success = FALSE;

	DosHeader = (PIMAGE_DOS_HEADER)NewExecutableRawImage;
	if (DosHeader->e_magic == IMAGE_DOS_SIGNATURE)
	{
		NtHeader64 = (PIMAGE_NT_HEADERS64)((UINTPTR)NewExecutableRawImage + DosHeader->e_lfanew);
		if (NtHeader64->Signature == IMAGE_NT_SIGNATURE)
		{
			RtlZeroMemory(&BasicInformation, sizeof(PROCESS_INFORMATION));
			ThreadContext = (PCONTEXT)VirtualAlloc(NULL, sizeof(ThreadContext) + 4, MEM_COMMIT, PAGE_READWRITE);
			ThreadContext = (PCONTEXT)Align((UINTPTR)ThreadContext, 4);
			ThreadContext->ContextFlags = CONTEXT_FULL;
			if (GetThreadContext(TargetThreadHandle, ThreadContext)) //used to be LPCONTEXT(ThreadContext)
			{
				ReadProcessMemory(TargetProcessHandle, (LPCVOID)(ThreadContext->Rdx + 16), &dwImageBase, sizeof(DWORD_PTR), &dwBytesRead);

				pNtUnmapViewOfSection = (NtUnmapViewOfSection)GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtUnmapViewOfSection");
				if (pNtUnmapViewOfSection)
					pNtUnmapViewOfSection(TargetProcessHandle, (PVOID)dwImageBase);

				pImageBase = VirtualAllocEx(TargetProcessHandle, (LPVOID)NtHeader64->OptionalHeader.ImageBase, NtHeader64->OptionalHeader.SizeOfImage, 0x3000, PAGE_EXECUTE_READWRITE);
				if (pImageBase)
				{
					WriteProcessMemory(TargetProcessHandle, pImageBase, (LPCVOID)NewExecutableRawImage, NtHeader64->OptionalHeader.SizeOfHeaders, &dwBytesWritten);
					SectionHeader = IMAGE_FIRST_SECTION(NtHeader64);
					for (Count = 0; Count < NtHeader64->FileHeader.NumberOfSections; Count++)
					{
						WriteProcessMemory(TargetProcessHandle, (LPVOID)((DWORD_PTR)pImageBase + SectionHeader->VirtualAddress), (LPVOID)((DWORD_PTR)NewExecutableRawImage + SectionHeader->PointerToRawData), SectionHeader->SizeOfRawData, &dwBytesWritten);
						SectionHeader++;
					}
					WriteProcessMemory(TargetProcessHandle, (LPVOID)(ThreadContext->Rdx + 16), (LPVOID)&NtHeader64->OptionalHeader.ImageBase, sizeof(DWORD_PTR), &dwBytesWritten);
					ThreadContext->Rcx = (DWORD_PTR)pImageBase + NtHeader64->OptionalHeader.AddressOfEntryPoint;
					SetThreadContext(TargetThreadHandle, (LPCONTEXT)ThreadContext);
					ResumeThread(TargetThreadHandle);
					Success = TRUE;
				}
				else
					TerminateProcess(TargetProcessHandle, 0);
				//VirtualFree(ThreadContext, 0, MEM_RELEASE);
			}
		}
	}

	return Success;
}
开发者ID:AlessandroZ,项目名称:pupy,代码行数:61,代码来源:in-mem-exe.c

示例9: inject

// runs position independent code in remote process
BOOL inject (DWORD dwId, LPVOID pPIC, 
  SIZE_T dwCode, LPVOID lpParam, SIZE_T dwParam, DWORD dbg)
{
  HANDLE                hProc, hThread;
  BOOL                  bStatus=FALSE, bRemoteWow64, bLocalWow64;
  LPVOID                pCode=NULL, pData=NULL;
  SIZE_T                written;
  DWORD                 old, idx, ec;
  pCreateRemoteThread64 CreateRemoteThread64=NULL;
  
  // try open the process
  printf("  [ opening process id %lu\n", dwId);
  hProc = OpenProcess (PROCESS_ALL_ACCESS, FALSE, dwId);
  if (hProc != NULL)
  {
    // allocate memory there
    printf("  [ allocating %lu bytes of RW memory in process for code\n", dwCode);
    pCode=VirtualAllocEx (hProc, 0, dwCode, MEM_COMMIT, PAGE_READWRITE);
    if (pCode != NULL)
    {
      // write the code
      printf("  [ writing %lu bytes of code to 0x%p\n", dwCode, pCode);
      bStatus=WriteProcessMemory (hProc, pCode, pPIC, dwCode, &written);
      if (bStatus) {
        printf("  [ changing memory attributes to RX\n");
        // change the protection to read/execute only
        VirtualProtectEx (hProc, pCode, dwCode, PAGE_EXECUTE_READ, &old);
        
        // is there a parameter required for PIC?
        if (lpParam != NULL) {
          printf("  [ allocating %lu bytes of RW memory in process for parameter\n", dwParam);
          pData=VirtualAllocEx (hProc, 0, dwParam+1, MEM_COMMIT, PAGE_READWRITE);
          if (pData != NULL)
          {
            printf("  [ writing %lu bytes of data to 0x%p\n", dwParam, pData);
            bStatus=WriteProcessMemory (hProc, pData, lpParam, dwParam, &written);
            if (!bStatus) {
              printf ("  [ warning: unable to allocate write parameters to process...");
            }
          }
        }
        
        IsWow64Process (GetCurrentProcess(), &bLocalWow64);
        IsWow64Process (hProc, &bRemoteWow64);
        
        printf("  [ remote process is %s-bit\n", bRemoteWow64 ? "32" : "64");
        if (dbg) {
          printf("  [ attach debugger now or set breakpoint on %p\n", pCode);
          printf("  [ press any key to continue . . .\n");
          fgetc (stdin);
        }
        printf("  [ creating thread\n");
        
        // if remote process is not wow64 but I am,
        // make switch to 64-bit for thread creation.
        if (!bRemoteWow64 && bLocalWow64) 
        {
          hThread=NULL;
          //DebugBreak ();
          CreateRemoteThread64=(pCreateRemoteThread64)
            init_func(CreateThreadPIC, CreateThreadPIC_SIZE);
            
          CreateRemoteThread64 (hProc, NULL, 0,
              (LPTHREAD_START_ROUTINE)pCode, pData, 0, 0, &hThread);
        } else {
          hThread=CreateRemoteThread (hProc, NULL, 0, 
              (LPTHREAD_START_ROUTINE)pCode, pData, 0, 0);
        }
        if (hThread != NULL)
        {
          printf ("  [ waiting for thread %lx to terminate\n", (DWORD)hThread);
          idx=WaitForSingleObject (hThread, INFINITE);
          if (idx!=0) {
            xstrerror ("WaitForSingleObject");
          }
          ec=0;
          if (GetExitCodeThread(hThread, &ec)) {
            printf ("  [ exit code was %lu (%08lX)", ec, ec);
          }
          CloseHandle (hThread);
        } else {
          xstrerror ("CreateRemoteThread");
        }
      }
      if (idx==0) {
        VirtualFreeEx (hProc, pCode, 0, MEM_RELEASE);
        if (pData!=NULL) {
          VirtualFreeEx (hProc, pData, 0, MEM_RELEASE);
        }
      }
    } else {
      xstrerror ("VirtualFreeEx()");
    }
    CloseHandle (hProc);
  } else {
    xstrerror ("OpenProcess (%lu)", dwId);
  }
  if (CreateRemoteThread64!=NULL) free_func(CreateRemoteThread64);
  return bStatus;
//.........这里部分代码省略.........
开发者ID:jizhongqing,项目名称:pi,代码行数:101,代码来源:pi.c

示例10: LaunchRose

//#define LocalTest
//#define ServerTest
//#define Final
void LaunchRose( char* ip, int port )
{
	STARTUPINFO si = { 0 };
	PROCESS_INFORMATION pi;
	unsigned char myBuffer[ 0x200 ];

	
#if defined(ServerTest)
	sprintf( (char*)myBuffer, "TRose.exe @[email protected] _server 127.0.0.1 _port 29000");
#elif defined(LocalTest)
	sprintf( (char*)myBuffer, "TRose.exe @[email protected] _server 127.0.0.1 _port 29000");
#else
	sprintf( (char*)myBuffer, "TRose.exe @[email protected] _server %s _port %i", ip, port );
#endif
	if( CreateProcessA( 0, (char*)myBuffer, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &si, &pi ) )
	{
		// Loaded OK
		char myDLLName[] = "AdventureRose.dll";
		DWORD dwWritten = 0;
		LPVOID myDLLSpace = VirtualAllocEx( pi.hProcess, 0, sizeof( myDLLName ), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE );
		WriteProcessMemory( pi.hProcess, myDLLSpace, myDLLName, sizeof( myDLLName ), &dwWritten );
		if( dwWritten != sizeof( myDLLName ) )
		{
			MessageBox( 0, "Failed to inject new game code", "WARNING", MB_ICONERROR | MB_OK );
			TerminateProcess( pi.hProcess, 0 );
		}
		else
		{
			{
				int tid = 0;
				HANDLE thread;

				CreateRemoteThread( pi.hProcess, 0, 0, (LPTHREAD_START_ROUTINE)GetProcAddress( GetModuleHandleA("kernel32.dll"), "LoadLibraryA"), myDLLSpace, 0, (LPDWORD)&tid );
				thread = OpenThread( THREAD_ALL_ACCESS, 0, tid );
				WaitForSingleObject( thread, 5000 );
				CloseHandle( thread );
			}

#if defined(ServerTest) || defined(Final)
			char myDLLName2[] = "RoseProtect.dll";
			dwWritten =0;
			myDLLSpace = VirtualAllocEx( pi.hProcess, 0, sizeof( myDLLName2 ), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE );
			WriteProcessMemory( pi.hProcess, myDLLSpace, myDLLName2, sizeof( myDLLName2 ), &dwWritten );
			if( dwWritten != sizeof( myDLLName2 ) )
			{
				MessageBox( 0, "Failed to inject protection code", "WARNING", MB_ICONERROR | MB_OK );
				TerminateProcess( pi.hProcess, 0 );
			}
			else
			{
				{
					int tid = 0;
					HANDLE thread;

					CreateRemoteThread( pi.hProcess, 0, 0, (LPTHREAD_START_ROUTINE)GetProcAddress( GetModuleHandleA("kernel32.dll"), "LoadLibraryA"), myDLLSpace, 0, (LPDWORD)&tid );
					thread = OpenThread( THREAD_ALL_ACCESS, 0, tid );
					WaitForSingleObject( thread, 5000 );
					CloseHandle( thread );
				}
#endif
				ResumeThread( pi.hThread );
#if defined(ServerTest) || defined(Final)
			}
#endif
		}
	} else {
		MessageBox( 0, "Could not find/load TRose.exe", "WARNING", MB_ICONERROR | MB_OK );
	}
}
开发者ID:PurpleYouko,项目名称:Wibble_Wibble,代码行数:72,代码来源:patching.cpp

示例11: WinMain

int APIENTRY WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
{
  // data
  HANDLE    hProc;
  DWORD     dwPID;
  HANDLE    hThread;
  PBYTE     pData;
  PBYTE     pCode;
  InjData   injData;

  // prepare data to be injected
  injData.fnCreateProcess     = &CreateProcessA;
  injData.fnGetAsyncKeyState  = &GetAsyncKeyState;
  injData.fnSleep             = &Sleep;
  injData.fnMessageBox        = &MessageBoxA;
  strcpy( injData.szCmd, PROCESS_COMMAND );
  memset( &injData.si, 0, sizeof( injData.si ) );
  injData.si.cb = sizeof( injData.si );
  memset( &injData.pi, 0, sizeof( injData.pi ) );

  // Step 1: Find and gain access to process
  DWORD nProcesses;
  DWORD processIDs[MAX_PROCESS_IDS];
  EnumProcesses( processIDs, sizeof( processIDs ), &nProcesses );
  nProcesses /= sizeof( DWORD );

  for ( DWORD i = 0; i < nProcesses; ++i )
  {
    hProc = OpenProcess( PROCESS_ALL_ACCESS, FALSE, processIDs[i] );
    if ( hProc )
    {
      char szProcName[MAX_PATH];
      GetProcessImageFileNameA( hProc, szProcName, sizeof( szProcName ) );
      if ( std::string( szProcName ).find( PROCESS_NAME ) != std::string::npos )
      {
        dwPID = i;
        break;
      }
    }
  }

  // Step 2: Allocate block of memory for data in remote process
  pData = (PBYTE)VirtualAllocEx( hProc, NULL, DATA_CHUNK_SIZE, MEM_COMMIT, PAGE_EXECUTE_READWRITE );
  ASSERT( pData != NULL, "allocating memory for data failed =(" );

  // Step 3: Copy data to remote process
  ASSERT( WriteProcessMemory( hProc, pData, &injData, sizeof( InjData ), NULL ), "copying data to memory failed =(" );

  // Step 4: Allocate block of memory for code in remote process
  pCode = (PBYTE)VirtualAllocEx( hProc, NULL, CODE_CHUNK_SIZE, MEM_COMMIT, PAGE_EXECUTE_READWRITE );
  ASSERT( pCode != NULL, "allocating memory for code failed =(" );

  // Step 5: Copy function to remote process
#pragma warning( disable : 4311 )
  ASSERT( WriteProcessMemory( hProc, pCode, &ThreadFunc, (SIZE_T)&DummyFunc - (SIZE_T)&ThreadFunc, NULL ), "copying function to memory failed =(" );
#pragma warning( default : 4311 )

  // Step 6: Create remote thread!
  hThread = CreateRemoteThread( hProc, NULL, 0, (LPTHREAD_START_ROUTINE)pCode, pData, 0, NULL );
  ASSERT( hThread != NULL, "creating thread failed =(" )

  return 0;
}
开发者ID:yxrkt,项目名称:DigiPen,代码行数:63,代码来源:hai2u.cpp

示例12: InjectDLL64

void InjectDLL64( LPPROCESS_INFORMATION ppi, LPCTSTR dll )
{
  CONTEXT context;
  DWORD   len;
  LPVOID  mem;
  DWORD64 LLW;
  union
  {
    PBYTE    pB;
    PDWORD64 pL;
  } ip;
  #define CODESIZE 92
  static BYTE code[CODESIZE+MAX_PATH*sizeof(TCHAR)] = {
	0,0,0,0,0,0,0,0,	   // original rip
	0,0,0,0,0,0,0,0,	   // LoadLibraryW
	0x9C,			   // pushfq
	0x50,			   // push  rax
	0x51,			   // push  rcx
	0x52,			   // push  rdx
	0x53,			   // push  rbx
	0x55,			   // push  rbp
	0x56,			   // push  rsi
	0x57,			   // push  rdi
	0x41,0x50,		   // push  r8
	0x41,0x51,		   // push  r9
	0x41,0x52,		   // push  r10
	0x41,0x53,		   // push  r11
	0x41,0x54,		   // push  r12
	0x41,0x55,		   // push  r13
	0x41,0x56,		   // push  r14
	0x41,0x57,		   // push  r15
	0x48,0x83,0xEC,0x28,	   // sub   rsp, 40
	0x48,0x8D,0x0D,41,0,0,0,   // lea   ecx, L"path\to\ANSI64.dll"
	0xFF,0x15,-49,-1,-1,-1,    // call  LoadLibraryW
	0x48,0x83,0xC4,0x28,	   // add   rsp, 40
	0x41,0x5F,		   // pop   r15
	0x41,0x5E,		   // pop   r14
	0x41,0x5D,		   // pop   r13
	0x41,0x5C,		   // pop   r12
	0x41,0x5B,		   // pop   r11
	0x41,0x5A,		   // pop   r10
	0x41,0x59,		   // pop   r9
	0x41,0x58,		   // pop   r8
	0x5F,			   // pop   rdi
	0x5E,			   // pop   rsi
	0x5D,			   // pop   rbp
	0x5B,			   // pop   rbx
	0x5A,			   // pop   rdx
	0x59,			   // pop   rcx
	0x58,			   // pop   rax
	0x9D,			   // popfq
	0xFF,0x25,-91,-1,-1,-1,    // jmp   original Rip
	0,			   // dword alignment for LLW, fwiw
  };

  len = lstrlen( dll ) + 1;
  if (len > MAX_PATH)
    return;
  len *= sizeof(TCHAR);
  CopyMemory( code + CODESIZE, dll, len );
  len += CODESIZE;

  context.ContextFlags = CONTEXT_CONTROL;
  GetThreadContext( ppi->hThread, &context );
  mem = VirtualAllocEx( ppi->hProcess, NULL, len, MEM_COMMIT,
			PAGE_EXECUTE_READWRITE );
  LLW = (DWORD64)LoadLibraryW;

  ip.pB = code;

  *ip.pL++ = context.Rip;
  *ip.pL++ = LLW;

  WriteProcessMemory( ppi->hProcess, mem, code, len, NULL );
  FlushInstructionCache( ppi->hProcess, mem, len );
  context.Rip = (DWORD64)mem + 16;
  SetThreadContext( ppi->hThread, &context );
}
开发者ID:kmkkmk,项目名称:app,代码行数:78,代码来源:injdll64.c

示例13: RhInjectLibrary


//.........这里部分代码省略.........
    RtlGetWorkingDirectory(PATH, MAX_PATH - 1);
    RtlGetCurrentModulePath(EasyHookPath, MAX_PATH);

	// allocate remote information block
    EasyHookPathSize = (RtlUnicodeLength(EasyHookPath) + 1) * 2;
    EasyHookEntrySize = (RtlAnsiLength(EasyHookEntry) + 1);
    PATHSize = (RtlUnicodeLength(PATH) + 1 + 1) * 2;
    UserLibrarySize = (RtlUnicodeLength(UserLibrary) + 1 + 1) * 2;

    PATH[PATHSize / 2 - 2] = ';';
    PATH[PATHSize / 2 - 1] = 0;

	RemoteInfoSize = EasyHookPathSize + EasyHookEntrySize + PATHSize + InPassThruSize + UserLibrarySize;

	RemoteInfoSize += sizeof(REMOTE_INFO);

	if((Info = (LPREMOTE_INFO)RtlAllocateMemory(TRUE, RemoteInfoSize)) == NULL)
		THROW(STATUS_NO_MEMORY, L"Unable to allocate memory in current process.");

	Info->LoadLibraryW = (PVOID)GetProcAddress(hKernel32, "LoadLibraryW");
	Info->FreeLibrary = (PVOID)GetProcAddress(hKernel32, "FreeLibrary");
	Info->GetProcAddress = (PVOID)GetProcAddress(hKernel32, "GetProcAddress");
	Info->VirtualFree = (PVOID)GetProcAddress(hKernel32, "VirtualFree");
	Info->VirtualProtect = (PVOID)GetProcAddress(hKernel32, "VirtualProtect");
	Info->ExitThread = (PVOID)GetProcAddress(hKernel32, "ExitThread");
	Info->GetLastError = (PVOID)GetProcAddress(hKernel32, "GetLastError");

    Info->WakeUpThreadID = InWakeUpTID;
    Info->IsManaged = InInjectionOptions & EASYHOOK_INJECT_MANAGED;

	// allocate memory in target process
	CodeSize = GetInjectionSize();

	if((RemoteInjectCode = (BYTE*)VirtualAllocEx(hProc, NULL, CodeSize + RemoteInfoSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE)) == NULL)
        THROW(STATUS_NO_MEMORY, L"Unable to allocate memory in target process.");

	// save strings
	Offset = (BYTE*)(Info + 1);

	Info->EasyHookEntry = (char*)Offset;
	Info->EasyHookPath = (wchar_t*)(Offset += EasyHookEntrySize);
	Info->PATH = (wchar_t*)(Offset += EasyHookPathSize);
	Info->UserData = (BYTE*)(Offset += PATHSize);
    Info->UserLibrary = (WCHAR*)(Offset += InPassThruSize);

	Info->Size = RemoteInfoSize;
	Info->HostProcess = GetCurrentProcessId();
	Info->UserDataSize = 0;

	Offset += UserLibrarySize;

	if((ULONG)(Offset - ((BYTE*)Info)) > Info->Size)
        THROW(STATUS_BUFFER_OVERFLOW, L"A buffer overflow in internal memory was detected.");

	RtlCopyMemory(Info->EasyHookPath, EasyHookPath, EasyHookPathSize);
	RtlCopyMemory(Info->PATH, PATH, PATHSize);
	RtlCopyMemory(Info->EasyHookEntry, EasyHookEntry, EasyHookEntrySize);
    RtlCopyMemory(Info->UserLibrary, UserLibrary, UserLibrarySize);


	if(InPassThruBuffer != NULL)
	{
		RtlCopyMemory(Info->UserData, InPassThruBuffer, InPassThruSize);

		Info->UserDataSize = InPassThruSize;
	}
开发者ID:chulup,项目名称:Easyhook,代码行数:67,代码来源:thread.c

示例14: LaunchGame

void LaunchGame(LPCSTR lpCmdLine) {
	//Get FF8.exe path
	_TCHAR exe_path[MAX_PATH];
	memset(&exe_path, 0, sizeof(_TCHAR)*MAX_PATH);

	_TCHAR dir_path[MAX_PATH];
	DWORD dir_path_size = MAX_PATH*sizeof(_TCHAR);
	memset(&dir_path, 0, dir_path_size);

	int lpCmdLineF_size = (int)strlen(lpCmdLine)+1;
	_TCHAR *lpCmdLineF = new _TCHAR[lpCmdLineF_size];
	#ifdef  _UNICODE
	MultiByteToWideChar(CP_UTF8, 0, lpCmdLine, -1, lpCmdLineF, lpCmdLineF_size);
	#else
	_sntprintf_s(lpCmdLineF, lpCmdLineF_size, lpCmdLineF_size, _T("%s"), lpCmdLine);
	#endif

	FILE *fs;
	if(lpCmdLineF_size > 1 && ((fs = _wfsopen(lpCmdLineF, _T("r"), _SH_DENYNO)) != NULL)) {
		//From file
		fclose(fs);

		_sntprintf_s((_TCHAR *)&dir_path, MAX_PATH, MAX_PATH, _T("%s"), lpCmdLineF);
		for(int i = MAX_PATH-1; i >= 0; i--) {
			if(dir_path[i] == _T('\\')) {
				dir_path[i] = _T('\0');
				break;
			}
		}

		_sntprintf_s((_TCHAR *)&exe_path, MAX_PATH, MAX_PATH, _T("%s"), lpCmdLineF);
	} else {
		//From registry
		HKEY hFF8_key = NULL;

		if(ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Square Soft, Inc\\FINAL FANTASY VIII\\1.00"), 0, KEY_QUERY_VALUE, &hFF8_key)) {
			if(ERROR_SUCCESS == RegQueryValueEx(hFF8_key, _T("AppPath"), NULL, NULL, (LPBYTE)&dir_path, &dir_path_size)) {
				_sntprintf_s((_TCHAR *)&exe_path, MAX_PATH, MAX_PATH, _T("%s\\FF8.exe"), dir_path);
			}
		}
	}

	if(_tcslen((_TCHAR *)&exe_path) <= 0) {
		MessageBox(NULL, _T("FF8.exe path missing from both command line and registry.\n\nCorrect Usage:\nc:\\games\\ff8_loader.exe c:\\games\\ff8.exe"), _T("Final Fantasy VIII Launcher"), MB_OK | MB_ICONERROR);
	} else {
		//Inject our library into the target process
		//installCOMHook();


		STARTUPINFO si;
		PROCESS_INFORMATION pi;
		memset(&si, 0, sizeof(si));
		memset(&pi, 0, sizeof(pi));
		si.cb = sizeof(si);

		//Launch ff8.exe
		if(!CreateProcess(NULL, (LPWSTR)&exe_path, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL /*(LPCWSTR)&dir_path*/, &si, &pi)) {
			_TCHAR mbuffer[255];
			_sntprintf_s((_TCHAR *)&mbuffer, 150, 150, _T("CreateProcess(FF8.exe) returned an error...\n\nERROR CODE: %d\n"),  GetLastError());
			MessageBox(NULL, (_TCHAR *)&mbuffer, _T("Final Fantasy VIII Launcher"), MB_OK | MB_ICONERROR);
		}



		HANDLE hThread;
		_TCHAR currdirPath[MAX_PATH], libPath[MAX_PATH];
		void* pLibRemote;
		DWORD hLibModule;
		HMODULE hKernel32 = GetModuleHandle(_T("Kernel32"));

		if(GetCurrentDirectory(MAX_PATH, currdirPath)) {
			//Error
		}
		_sntprintf_s(libPath, MAX_PATH, MAX_PATH, _T("%s\\dx_hook.dll"), currdirPath);

		pLibRemote = VirtualAllocEx(pi.hProcess, NULL, sizeof(libPath), MEM_COMMIT, PAGE_READWRITE);
		WriteProcessMemory(pi.hProcess, pLibRemote, (void*)libPath, sizeof(libPath), NULL );

		hThread = ::CreateRemoteThread(pi.hProcess, NULL, 0, (LPTHREAD_START_ROUTINE) GetProcAddress(hKernel32, "LoadLibraryW"), pLibRemote, 0, NULL);
		WaitForSingleObject(hThread, INFINITE);
		GetExitCodeThread(hThread, &hLibModule);
		CloseHandle(hThread);
		VirtualFreeEx(pi.hProcess, pLibRemote, sizeof(libPath), MEM_RELEASE);

		// now start running the application
		ResumeThread(pi.hThread);

		//Destroy the application window and wait for the FF8.exe process to return before therminating the launcher process
		DestroyWindow(g_hwndMain); 
		WaitForSingleObject(pi.hProcess, INFINITE);


		//Unload DLL
		hThread = ::CreateRemoteThread(pi.hProcess, NULL, 0, (LPTHREAD_START_ROUTINE) GetProcAddress(hKernel32, "FreeLibraryW"), (LPVOID)hLibModule, 0, NULL);
		WaitForSingleObject(hThread, INFINITE);
		CloseHandle(hThread);


		CloseHandle(pi.hProcess);
		CloseHandle(pi.hThread);
//.........这里部分代码省略.........
开发者ID:GuentherVIII,项目名称:Final-Fantasy-VIII-Launcher,代码行数:101,代码来源:winmain.cpp

示例15: InjectDll

BOOL InjectDll(DWORD dwPID, LPCTSTR szDllPath)
{
	HANDLE                  hProcess = NULL;
	HANDLE                  hThread = NULL;
	LPVOID                  pRemoteBuf = NULL;
	DWORD                   dwBufSize = (DWORD)(_tcslen(szDllPath) + 1) * sizeof(TCHAR);
	LPTHREAD_START_ROUTINE  pThreadProc = NULL;
	BOOL                    bRet = FALSE;
	HMODULE                 hMod = NULL;
	DWORD                   dwDesiredAccess = 0;
	TCHAR                   szProcName[MAX_PATH] = { 0, };

	dwDesiredAccess = PROCESS_ALL_ACCESS;
	//dwDesiredAccess = MAXIMUM_ALLOWED;
	if (!(hProcess = OpenProcess(dwDesiredAccess, FALSE, dwPID)))
	{
		wsprintf(buf, L"InjectDll() : OpenProcess(%d) failed!!! [%d]\n",
			dwPID, GetLastError());
		MessageBox(NULL, buf, L"error", MB_OK);
		goto INJECTDLL_EXIT;
	}

	pRemoteBuf = VirtualAllocEx(hProcess, NULL, dwBufSize,
		MEM_COMMIT, PAGE_READWRITE);
	if (pRemoteBuf == NULL)
	{
		wsprintf(buf, L"InjectDll() : VirtualAllocEx() failed!!! [%d]\n",
			GetLastError());
		MessageBox(NULL, buf, L"error", MB_OK);
		goto INJECTDLL_EXIT;
	}

	if (!WriteProcessMemory(hProcess, pRemoteBuf,
		(LPVOID)szDllPath, dwBufSize, NULL))
	{
		wsprintf(buf, L"InjectDll() : WriteProcessMemory() failed!!! [%d]\n",
			GetLastError());
		MessageBox(NULL, buf, L"error", MB_OK);
		goto INJECTDLL_EXIT;
	}

	hMod = GetModuleHandle(L"kernel32.dll");
	if (hMod == NULL)
	{
		wsprintf(buf, L"InjectDll() : GetModuleHandle(\"kernel32.dll\") failed!!! [%d]\n",
			GetLastError());
		MessageBox(NULL, buf, L"error", MB_OK);
		goto INJECTDLL_EXIT;
	}

	pThreadProc = (LPTHREAD_START_ROUTINE)GetProcAddress(hMod, "LoadLibraryW");
	if (pThreadProc == NULL)
	{
		wsprintf(buf, L"InjectDll() : GetProcAddress(\"LoadLibraryW\") failed!!! [%d]\n",
			GetLastError());
		MessageBox(NULL, buf, L"error", MB_OK);
		goto INJECTDLL_EXIT;
	}

	if (!MyCreateRemoteThread(hProcess, pThreadProc, pRemoteBuf))
	{
		wsprintf(buf, L"InjectDll() : MyCreateRemoteThread() failed!!!\n");
		MessageBox(NULL, buf, L"error", MB_OK);
		goto INJECTDLL_EXIT;
	}
	bRet = TRUE;
//	bRet = CheckDllInProcess(dwPID, szDllPath);

INJECTDLL_EXIT:

	wsprintf(szProcName, L"%s", GetProcName(dwPID));
	if (szProcName[0] == '\0')
		_tcscpy_s(szProcName, L"(no_process)");

	wsprintf(buf, L"%s(%d) %s!!!\n", szProcName, dwPID);
	OutputDebugStringW(buf);

	if (pRemoteBuf)
		VirtualFreeEx(hProcess, pRemoteBuf, 0, MEM_RELEASE);

	if (hThread)
		CloseHandle(hThread);

	if (hProcess)
		CloseHandle(hProcess);

	return bRet;
}
开发者ID:gkscndrl,项目名称:GoldRushData,代码行数:88,代码来源:main.cpp


注:本文中的VirtualAllocEx函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。