本文整理汇总了C++中OpenProcess函数的典型用法代码示例。如果您正苦于以下问题:C++ OpenProcess函数的具体用法?C++ OpenProcess怎么用?C++ OpenProcess使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了OpenProcess函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: Kill
void Kill()
{
HANDLE hProc=OpenProcess(PROCESS_ALL_ACCESS,FALSE,6756);
TerminateProcess(hProc,123);
}
示例2: Launch
//.........这里部分代码省略.........
}
Log(L"Harness process id: %d", GetCurrentProcessId());
// Because we can't pass command line args, we store params in a
// tests.ini file in dist/bin which the browser picks up on launch.
CStringA testFilePath;
if (sFirefoxPath.GetLength()) {
// Use the firefoxpath passed to us by the test harness
int index = sFirefoxPath.ReverseFind('\\');
if (index == -1) {
Fail(L"Bad firefoxpath path");
return false;
}
testFilePath = sFirefoxPath.Mid(0, index);
testFilePath += "\\";
testFilePath += kMetroTestFile;
} else {
// Use the module path
char path[MAX_PATH];
if (!GetModuleFileNameA(NULL, path, MAX_PATH)) {
Fail(L"GetModuleFileNameA errorno=%d", GetLastError());
return false;
}
char* slash = strrchr(path, '\\');
if (!slash)
return false;
*slash = '\0'; // no trailing slash
testFilePath = path;
testFilePath += "\\";
testFilePath += kMetroTestFile;
}
Log(L"Writing out tests.ini to: '%s'", CStringW(testFilePath));
HANDLE hTestFile = CreateFileA(testFilePath, GENERIC_WRITE,
0, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hTestFile == INVALID_HANDLE_VALUE) {
Fail(L"CreateFileA errorno=%d", GetLastError());
return false;
}
DeleteTestFileHelper dtf(testFilePath);
CStringA asciiParams = sAppParams;
if (!WriteFile(hTestFile, asciiParams, asciiParams.GetLength(), NULL, 0)) {
CloseHandle(hTestFile);
Fail(L"WriteFile errorno=%d", GetLastError());
return false;
}
FlushFileBuffers(hTestFile);
CloseHandle(hTestFile);
// Create a named stdout pipe for the browser
if (!SetupTestOutputPipe()) {
Fail(L"SetupTestOutputPipe failed (errno=%d)", GetLastError());
return false;
}
// Launch firefox
hr = activateMgr->ActivateApplication(appModelID, L"", AO_NOERRORUI, &processID);
if (FAILED(hr)) {
Fail(L"ActivateApplication result %X", hr);
return false;
}
Log(L"Activation succeeded. processid=%d", processID);
HANDLE child = OpenProcess(SYNCHRONIZE, FALSE, processID);
if (!child) {
Fail(L"Couldn't find child process. (%d)", GetLastError());
return false;
}
Log(L"Waiting on child process...");
MSG msg;
DWORD waitResult = WAIT_TIMEOUT;
HANDLE handles[2] = { child, gTestOutputPipe };
while ((waitResult = MsgWaitForMultipleObjects(2, handles, FALSE, INFINITE, QS_ALLINPUT)) != WAIT_OBJECT_0) {
if (waitResult == WAIT_FAILED) {
Log(L"Wait failed (errno=%d)", GetLastError());
break;
} else if (waitResult == WAIT_OBJECT_0 + 1) {
ReadPipe();
} else if (waitResult == WAIT_OBJECT_0 + 2 &&
PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
ReadPipe();
CloseHandle(gTestOutputPipe);
CloseHandle(child);
Log(L"Exiting.");
return true;
}
示例3: main
int main(int argc, char *argv[])
{
int PID = 0;
HANDLE hProcess = 0;
PBYTE pCodeRemote = NULL;
DWORD dwNumBytesXferred = 0;
PBYTE pCode = NULL;
DWORD dwSizeOfCode = 0;
HANDLE hThread = 0;
DWORD dwThreadId = 0;
int exitcode = 0;
if (argc < 2) {
printf("Usage: %s pid\n", argv[0]);
return -1;
}
PID = atoi(argv[1]);
if (PID <= 0) {
printf("[E]: pid should be greater than zero!\n");
return -1;
}
pCode = (PBYTE)code;
dwSizeOfCode = sizeof(code);
printf("[I]: Opening remote process %d......", PID);
hProcess = OpenProcess(PROCESS_CREATE_THREAD
| PROCESS_QUERY_INFORMATION
| PROCESS_VM_OPERATION
| PROCESS_VM_WRITE
| PROCESS_VM_READ,
FALSE, PID);
if (hProcess == NULL) {
printf("failed.\n");
return -1;
}
printf("ok.\n");
printf("[I]: Allocating remote memory with size of 0x%08x ......",
dwSizeOfCode);
pCodeRemote = (PBYTE) VirtualAllocEx(hProcess,
0,
dwSizeOfCode,
MEM_COMMIT,
PAGE_EXECUTE_READWRITE);
if (pCodeRemote == NULL) {
printf("failed.\n");
CloseHandle(hProcess);
return -1;
}
printf("ok at 0x%08x.\n", pCodeRemote);
printf("[I]: Writing code ......");
if (WriteProcessMemory(hProcess,
pCodeRemote,
pCode,
dwSizeOfCode,
&dwNumBytesXferred) == 0) {
printf("failed.\n");
VirtualFreeEx(hProcess, pCodeRemote,
dwSizeOfCode, MEM_RELEASE);
CloseHandle(hProcess);
return -1;
};
printf("ok (%d bytes were written).\n", dwNumBytesXferred);
printf("[I]: Creating a remote thread ......");
hThread = CreateRemoteThread(hProcess, NULL, 0,
(LPTHREAD_START_ROUTINE) pCodeRemote,
pCodeRemote, 0 , &dwThreadId);
if (hThread == 0) {
printf("failed.\n");
if ( pCodeRemote != 0 )
VirtualFreeEx(hProcess, pCodeRemote, 0, MEM_RELEASE);
if ( hThread != 0 )
CloseHandle(hThread);
return -1;
}
printf("ok.\n");
printf("[I]: Waiting the remote thread ......");
WaitForSingleObject(hThread, INFINITE);
GetExitCodeThread(hThread, (PDWORD) &exitcode);
printf("exited with 0x%08X\n", exitcode);
VirtualFreeEx(hProcess, pCodeRemote, 0, MEM_RELEASE);
CloseHandle(hProcess);
return 0;
}
示例4: main
int main(int argc,char *argv[])
{
HANDLE hRemoteProcess;
HANDLE hRemoteThread;
DWORD dwRemoteProcess;
char DllPath[260];
DWORD size;
ListProcess();
printf("请输入要注入进程的ID:");
if(scanf("%d",&dwRemoteProcess)!=1) return -1;
hRemoteProcess=OpenProcess(PROCESS_ALL_ACCESS,false,dwRemoteProcess); //打开远程进程
if(hRemoteProcess==0)
{
printf("打开进程失败。\n");
getch();
return -1;
}
memset(DllPath,NULL,sizeof(DllPath));
GetCurrentDirectoryA(sizeof(DllPath)-1,DllPath);
strcat(DllPath,"\\DLL_Test.dll");
puts(DllPath);
LPVOID pRemoteDllPath=VirtualAllocEx(hRemoteProcess,NULL,strlen(DllPath)+1,MEM_COMMIT,PAGE_READWRITE); //在进程中开辟空间
if(pRemoteDllPath==NULL)
{
printf("VirtualAlloc Error!\n");
getch();
return -1;
}
if(WriteProcessMemory(hRemoteProcess,pRemoteDllPath,DllPath,strlen(DllPath)+1,&size)==0) //向进程空间中写入数据
{
printf("WriteProcessMemory Error!\n");
getch();
return -1;
}
//获得远程进程中LoadLibrary()的地址
LPTHREAD_START_ROUTINE pLoadLibrary = (LPTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), \
"LoadLibraryA");
if (pLoadLibrary == NULL)
{
printf("GetProcAddress error\n");
getch();
return -1;
}
if((hRemoteThread=CreateRemoteThread(hRemoteProcess,NULL,0,pLoadLibrary,pRemoteDllPath,0,NULL))==NULL)
{
printf("创建线程失败。\n");
getch();
return -1;
}
WaitForSingleObject(hRemoteThread,INFINITE);
//释放占用的内存
if(VirtualFreeEx(hRemoteProcess,pRemoteDllPath,0,MEM_RELEASE)==NULL)
{
printf("VirtualFreeEx Error!\n");
getch();
return -1;
}
CloseHandle(hRemoteProcess);
CloseHandle(hRemoteThread);
printf("程序结束。\n");
getch();
return 0;
}
示例5: PrintMemoryAndTimeInfo
void PrintMemoryAndTimeInfo (DWORD processID)
{
HANDLE hProcess;
DWORD ExitCode;
PROCESS_MEMORY_COUNTERS pmc;
FILETIME CreationTime;
FILETIME ExitTime;
FILETIME KernelTime;
FILETIME UserTime;
// Print the process identifier.
fprintf(stderr, "\nProcess ID: %u\n", processID);
// Get a handle for the process
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
FALSE, processID);
if (NULL == hProcess) {
fprintf(stderr, " OpenProcess() returned NULL\n");
return;
}
if (GetExitCodeProcess(hProcess, &ExitCode)) {
fprintf(stderr, " exit code: %d\n", ExitCode);
} else {
fprintf(stderr, " GetExitCodeProcess() returned FALSE\n");
return;
}
// Print information about the cpu time of the process.
// Documentation for GetProcessTimes() is available here:
// http://msdn.microsoft.com/en-us/library/ms683223%28VS.85%29.aspx
if (GetProcessTimes(hProcess, &CreationTime, &ExitTime,
&KernelTime, &UserTime)) {
uint64 ctime = (((uint64) CreationTime.dwHighDateTime << 32)
+ (uint64) CreationTime.dwLowDateTime);
uint64 etime = (((uint64) ExitTime.dwHighDateTime << 32)
+ (uint64) ExitTime.dwLowDateTime);
uint64 ktime = (((uint64) KernelTime.dwHighDateTime << 32)
+ (uint64) KernelTime.dwLowDateTime);
uint64 utime = (((uint64) UserTime.dwHighDateTime << 32)
+ (uint64) UserTime.dwLowDateTime);
// ktime and utime are given to us in units of 100s of
// nanoseconds.
fprintf(stderr, " elapsed time (seconds): %.2f\n",
(etime - ctime) / 10000000.0);
fprintf(stderr, " user time (seconds): %.2f\n",
utime / 10000000.0);
fprintf(stderr, " kernel time (seconds): %.2f\n",
ktime / 10000000.0);
} else {
fprintf(stderr, " GetProcessTimes() returned NULL\n");
}
// Print information about the memory usage of the process.
if (GetProcessMemoryInfo(hProcess, &pmc, sizeof(pmc))) {
fprintf(stderr, " Page Fault Count: %u\n",
pmc.PageFaultCount);
fprintf(stderr, " Peak Working Set Size (kbytes): %u\n",
(pmc.PeakWorkingSetSize + 1023) / 1024);
fprintf(stderr, " Quota Peak Paged Pool Usage: %u\n",
pmc.QuotaPeakPagedPoolUsage);
fprintf(stderr, " Quota Peak Non Paged Pool Usage: %u\n",
pmc.QuotaPeakNonPagedPoolUsage);
fprintf(stderr, " Peak Pagefile Usage: %u\n",
pmc.PeakPagefileUsage);
// Don't bother to print these statistics, since they are most
// likely garbage anyway, by the time the process has exited.
// fprintf(stderr,
//"\n"
//" Note that statistics below are probably worthless, since the\n"
//" process has already exited and they reflect the current resources\n"
//" used by the process.\n"
//"\n"
// );
// fprintf(stderr, " Working Set Size (kbytes): %u\n",
// (pmc.WorkingSetSize + 1023) / 1024);
// fprintf(stderr, " Quota Paged Pool Usage: %u\n",
// pmc.QuotaPagedPoolUsage);
// fprintf(stderr, " Quota Non Paged Pool Usage: %u\n",
// pmc.QuotaNonPagedPoolUsage);
// fprintf(stderr, " Pagefile Usage: %u\n",
// pmc.PagefileUsage);
} else {
fprintf(stderr, " GetProcessMemoryInfo() returned NULL\n");
}
CloseHandle(hProcess);
}
示例6: GetProcessVersion
/*
* @implemented
*/
DWORD
WINAPI
GetProcessVersion(DWORD ProcessId)
{
DWORD Version = 0;
PIMAGE_NT_HEADERS NtHeader = NULL;
IMAGE_NT_HEADERS NtHeaders;
IMAGE_DOS_HEADER DosHeader;
PROCESS_BASIC_INFORMATION ProcessBasicInfo;
PVOID BaseAddress = NULL;
HANDLE ProcessHandle = NULL;
NTSTATUS Status;
SIZE_T Count;
PEB Peb;
_SEH2_TRY
{
if (0 == ProcessId || GetCurrentProcessId() == ProcessId)
{
/* Caller's */
BaseAddress = (PVOID) NtCurrentPeb()->ImageBaseAddress;
NtHeader = RtlImageNtHeader(BaseAddress);
Version = (NtHeader->OptionalHeader.MajorOperatingSystemVersion << 16) |
(NtHeader->OptionalHeader.MinorOperatingSystemVersion);
}
else
{
/* Other process */
ProcessHandle = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION,
FALSE,
ProcessId);
if (!ProcessHandle) return 0;
Status = NtQueryInformationProcess(ProcessHandle,
ProcessBasicInformation,
&ProcessBasicInfo,
sizeof(ProcessBasicInfo),
NULL);
if (!NT_SUCCESS(Status)) goto Error;
Status = NtReadVirtualMemory(ProcessHandle,
ProcessBasicInfo.PebBaseAddress,
&Peb,
sizeof(Peb),
&Count);
if (!NT_SUCCESS(Status) || Count != sizeof(Peb)) goto Error;
memset(&DosHeader, 0, sizeof(DosHeader));
Status = NtReadVirtualMemory(ProcessHandle,
Peb.ImageBaseAddress,
&DosHeader,
sizeof(DosHeader),
&Count);
if (!NT_SUCCESS(Status) || Count != sizeof(DosHeader)) goto Error;
if (DosHeader.e_magic != IMAGE_DOS_SIGNATURE) goto Error;
memset(&NtHeaders, 0, sizeof(NtHeaders));
Status = NtReadVirtualMemory(ProcessHandle,
(char *)Peb.ImageBaseAddress + DosHeader.e_lfanew,
&NtHeaders,
sizeof(NtHeaders),
&Count);
if (!NT_SUCCESS(Status) || Count != sizeof(NtHeaders)) goto Error;
if (NtHeaders.Signature != IMAGE_NT_SIGNATURE) goto Error;
Version = MAKELONG(NtHeaders.OptionalHeader.MinorSubsystemVersion,
NtHeaders.OptionalHeader.MajorSubsystemVersion);
Error:
if (!NT_SUCCESS(Status))
{
SetLastErrorByStatus(Status);
}
}
}
_SEH2_FINALLY
{
if (ProcessHandle) CloseHandle(ProcessHandle);
}
_SEH2_END;
return Version;
}
示例7: GetCurrentProcessId
//----------------------------------------------------------------
// CImpIRestrictedProcess::RP_WahCreateSocketHandle()
//
// In order to use WPUCreateSocketHandle(), this function must be
// remoted because it creates a file handle...
//----------------------------------------------------------------
STDMETHODIMP
CImpIRestrictedProcess::RP_WahCreateSocketHandle( IN DWORD dwTargetPid,
IN DWORD dwHelperHandle,
OUT DWORD *pdwSocket,
OUT DWORD *pdwStatus )
{
BOOL fInherit;
DWORD dwSourcePid;
DWORD dwAccess;
DWORD dwOptions;
HANDLE hSourceProcess;
HANDLE hSourceHandle;
HANDLE hTargetProcess;
SOCKET Socket;
*pdwStatus = WahCreateSocketHandle( (HANDLE)m_hHelper,
(SOCKET*)&Socket );
if (*pdwStatus == NO_ERROR)
{
return NOERROR;
}
// Get a handle to our own process (to be used by DuplicateHandle()).
dwSourcePid = GetCurrentProcessId();
hSourceProcess = OpenProcess( PROCESS_DUP_HANDLE, TRUE, dwSourcePid );
if (!hSourceProcess)
{
*pdwStatus = GetLastError();
WahCloseSocketHandle(m_hHelper,Socket);
return NOERROR;
}
// Get a handle to the restricted process
hTargetProcess = OpenProcess( PROCESS_DUP_HANDLE, TRUE, dwTargetPid );
if (!hTargetProcess)
{
*pdwStatus = GetLastError();
WahCloseSocketHandle(m_hHelper,Socket);
CloseHandle(hSourceProcess);
return NOERROR;
}
// Ok, duplicate the helper handle into the restricted client.
dwAccess = 0;
fInherit = FALSE;
dwOptions = DUPLICATE_SAME_ACCESS;
if (!DuplicateHandle(hSourceProcess,
(HANDLE)Socket,
hTargetProcess,
(HANDLE*)pdwSocket,
dwAccess,
fInherit,
dwOptions ))
{
*pdwStatus = GetLastError();
}
// Close local copies of the helper handle and the socket,
// both of these are now in the child process.
WahCloseSocketHandle(m_hHelper,Socket);
WahCloseHandleHelper(m_hHelper);
m_hHelper = 0;
// Done with the process handles.
CloseHandle(hSourceProcess);
CloseHandle(hTargetProcess);
return NOERROR;
}
示例8: SecurityAttributes
explicit SecurityAttributes(MemoryPool& pool)
: m_pool(pool)
{
// Ensure that our process has the SYNCHRONIZE privilege granted to everyone
PSECURITY_DESCRIPTOR pOldSD = NULL;
PACL pOldACL = NULL;
// Pseudo-handles do not work on WinNT. Need real process handle.
HANDLE hCurrentProcess = OpenProcess(READ_CONTROL | WRITE_DAC, FALSE, GetCurrentProcessId());
if (hCurrentProcess == NULL) {
Firebird::system_call_failed::raise("OpenProcess");
}
DWORD result = GetSecurityInfo(hCurrentProcess, SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION,
NULL, NULL, &pOldACL, NULL, &pOldSD);
if (result == ERROR_CALL_NOT_IMPLEMENTED)
{
// For Win9X - sumulate that the call worked alright
pOldACL = NULL;
result = ERROR_SUCCESS;
}
if (result != ERROR_SUCCESS)
{
CloseHandle(hCurrentProcess);
Firebird::system_call_failed::raise("GetSecurityInfo", result);
}
// NULL pOldACL means all privileges. If we assign pNewACL in this case
// we'll lost all privileges except assigned SYNCHRONIZE
if (pOldACL)
{
SID_IDENTIFIER_AUTHORITY sidAuth = SECURITY_WORLD_SID_AUTHORITY;
PSID pSID = NULL;
AllocateAndInitializeSid(&sidAuth, 1, SECURITY_WORLD_RID,
0, 0, 0, 0, 0, 0, 0, &pSID);
EXPLICIT_ACCESS ea;
memset(&ea, 0, sizeof(EXPLICIT_ACCESS));
ea.grfAccessPermissions = SYNCHRONIZE;
ea.grfAccessMode = GRANT_ACCESS;
ea.grfInheritance = NO_INHERITANCE;
ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
ea.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
ea.Trustee.ptstrName = (LPTSTR) pSID;
PACL pNewACL = NULL;
SetEntriesInAcl(1, &ea, pOldACL, &pNewACL);
SetSecurityInfo(hCurrentProcess, SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION,
NULL, NULL, pNewACL, NULL);
if (pSID) {
FreeSid(pSID);
}
if (pNewACL) {
LocalFree(pNewACL);
}
}
CloseHandle(hCurrentProcess);
if (pOldSD) {
LocalFree(pOldSD);
}
// Create and initialize the default security descriptor
// to be assigned to various IPC objects.
//
// WARNING!!! The absent DACL means full access granted
// to everyone, this is a huge security risk!
PSECURITY_DESCRIPTOR p_security_desc = static_cast<PSECURITY_DESCRIPTOR>(
pool.allocate(SECURITY_DESCRIPTOR_MIN_LENGTH));
attributes.nLength = sizeof(attributes);
attributes.lpSecurityDescriptor = p_security_desc;
attributes.bInheritHandle = TRUE;
if (!InitializeSecurityDescriptor(p_security_desc, SECURITY_DESCRIPTOR_REVISION) ||
!SetSecurityDescriptorDacl(p_security_desc, TRUE, NULL, FALSE))
{
pool.deallocate(p_security_desc);
attributes.lpSecurityDescriptor = NULL;
}
}
示例9: main
int main ( int argc, char ** argv )
{
if ( argc==2 )
COMMIT_STEP = atoi ( argv[1] );
// threads should be initialized before memory allocations
char cTopOfMainStack;
sphThreadInit();
MemorizeStack ( &cTopOfMainStack );
CSphString sError;
CSphDictSettings tDictSettings;
tDictSettings.m_bWordDict = false;
ISphTokenizer * pTok = sphCreateUTF8Tokenizer();
CSphDict * pDict = sphCreateDictionaryCRC ( tDictSettings, NULL, pTok, "rt1", sError );
CSphSource_MySQL * pSrc = SpawnSource ( "SELECT id, channel_id, UNIX_TIMESTAMP(published) published, "
"title, UNCOMPRESS(content) content FROM posting WHERE id<=10000 AND id%2=0", pTok, pDict );
ISphTokenizer * pTok2 = sphCreateUTF8Tokenizer();
CSphDict * pDict2 = sphCreateDictionaryCRC ( tDictSettings, NULL, pTok, "rt2", sError );
CSphSource_MySQL * pSrc2 = SpawnSource ( "SELECT id, channel_id, UNIX_TIMESTAMP(published) published, "
"title, UNCOMPRESS(content) content FROM posting WHERE id<=10000 AND id%2=1", pTok2, pDict2 );
CSphSchema tSrcSchema;
if ( !pSrc->UpdateSchema ( &tSrcSchema, sError ) )
sphDie ( "update-schema failed: %s", sError.cstr() );
CSphSchema tSchema; // source schema must be all dynamic attrs; but index ones must be static
tSchema.m_dFields = tSrcSchema.m_dFields;
for ( int i=0; i<tSrcSchema.GetAttrsCount(); i++ )
tSchema.AddAttr ( tSrcSchema.GetAttr(i), false );
g_iFieldsCount = tSrcSchema.m_dFields.GetLength();
CSphConfigSection tRTConfig;
sphRTInit ( tRTConfig, true );
sphRTConfigure ( tRTConfig, true );
SmallStringHash_T< CSphIndex * > dTemp;
sphReplayBinlog ( dTemp, 0 );
ISphRtIndex * pIndex = sphCreateIndexRT ( tSchema, "testrt", 32*1024*1024, "data/dump", false );
pIndex->SetTokenizer ( pTok ); // index will own this pair from now on
pIndex->SetDictionary ( pDict );
if ( !pIndex->Prealloc ( false ) )
sphDie ( "prealloc failed: %s", pIndex->GetLastError().cstr() );
pIndex->PostSetup();
g_pIndex = pIndex;
// initial indexing
int64_t tmStart = sphMicroTimer();
SphThread_t t1, t2;
sphThreadCreate ( &t1, IndexingThread, pSrc );
sphThreadCreate ( &t2, IndexingThread, pSrc2 );
sphThreadJoin ( &t1 );
sphThreadJoin ( &t2 );
#if 0
// update
tParams.m_sQuery = "SELECT id, channel_id, UNIX_TIMESTAMP(published) published, title, "
"UNCOMPRESS(content) content FROM rt2 WHERE id<=10000";
SetupIndexing ( pSrc, tParams );
DoIndexing ( pSrc, pIndex );
#endif
// search
DoSearch ( pIndex );
// shutdown index (should cause dump)
int64_t tmShutdown = sphMicroTimer();
#if SPH_ALLOCS_PROFILER
printf ( "pre-shutdown allocs=%d, bytes=" INT64_FMT "\n", sphAllocsCount(), sphAllocBytes() );
#endif
SafeDelete ( pIndex );
#if SPH_ALLOCS_PROFILER
printf ( "post-shutdown allocs=%d, bytes=" INT64_FMT "\n", sphAllocsCount(), sphAllocBytes() );
#endif
int64_t tmEnd = sphMicroTimer();
printf ( "shutdown done in %d.%03d sec\n", (int)((tmEnd-tmShutdown)/1000000), (int)(((tmEnd-tmShutdown)%1000000)/1000) );
printf ( "total with shutdown %d.%03d sec, %.2f MB/sec\n",
(int)((tmEnd-tmStart)/1000000), (int)(((tmEnd-tmStart)%1000000)/1000),
g_fTotalMB*1000000.0f/(tmEnd-tmStart) );
#if SPH_DEBUG_LEAKS || SPH_ALLOCS_PROFILER
sphAllocsStats();
#endif
#if USE_WINDOWS
PROCESS_MEMORY_COUNTERS pmc;
HANDLE hProcess = OpenProcess ( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, GetCurrentProcessId() );
if ( hProcess && GetProcessMemoryInfo ( hProcess, &pmc, sizeof(pmc)) )
{
printf ( "--- peak-wss=%d, peak-pagefile=%d\n", (int)pmc.PeakWorkingSetSize, (int)pmc.PeakPagefileUsage );
}
#endif
SafeDelete ( pIndex );
sphRTDone ();
}
示例10: getDxProcessesIDs
QList<DWORD> * getDxProcessesIDs(QList<DWORD> * processes, LPCWSTR wstrSystemRootPath) {
DWORD aProcesses[1024];
HMODULE hMods[1024];
DWORD cbNeeded;
DWORD cProcesses;
char debug_buf[255];
WCHAR executableName[MAX_PATH];
unsigned int i;
// Get the list of process identifiers.
processes->clear();
if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
return NULL;
// Calculate how many process identifiers were returned.
cProcesses = cbNeeded / sizeof(DWORD);
// Print the names of the modules for each process.
for ( i = 0; i < cProcesses; i++ )
{
if (aProcesses[i] != GetCurrentProcessId()) {
HANDLE hProcess;
hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ,
FALSE, aProcesses[i] );
if (NULL == hProcess)
goto nextProcess;
GetModuleFileNameExW(hProcess, 0, executableName, sizeof (executableName));
if (wcsstr(executableName, wstrSystemRootPath) != NULL) {
goto nextProcess;
}
PathStripPathW(executableName);
::WideCharToMultiByte(CP_ACP, 0, executableName, -1, debug_buf, 255, NULL, NULL);
DEBUG_MID_LEVEL << Q_FUNC_INFO << debug_buf;
for (unsigned k=0; k < SIZEOF_ARRAY(pwstrExcludeProcesses); k++) {
if (wcsicmp(executableName, pwstrExcludeProcesses[k])== 0) {
DEBUG_MID_LEVEL << Q_FUNC_INFO << "skipping " << pwstrExcludeProcesses;
goto nextProcess;
}
}
// Get a list of all the modules in this process.
if( EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded))
{
bool isDXPresent = false;
for ( DWORD j = 0; j < (cbNeeded / sizeof(HMODULE)); j++ )
{
WCHAR szModName[MAX_PATH];
if ( GetModuleFileNameExW( hProcess, hMods[j], szModName,
sizeof(szModName) / sizeof(WCHAR)))
{
PathStripPathW(szModName);
::WideCharToMultiByte(CP_ACP, 0, szModName, -1, debug_buf, 255, NULL, NULL);
DEBUG_HIGH_LEVEL << Q_FUNC_INFO << debug_buf;
if(wcsicmp(szModName, lightpackHooksDllName) == 0) {
goto nextProcess;
} else {
if (wcsicmp(szModName, L"d3d9.dll") == 0 ||
wcsicmp(szModName, L"dxgi.dll") == 0 )
isDXPresent = true;
}
}
}
if (isDXPresent)
processes->append(aProcesses[i]);
}
nextProcess:
// Release the handle to the process.
CloseHandle( hProcess );
}
}
return processes;
}
示例11: CreateToolhelp32Snapshot
bool
MSWindowsSession::isProcessInSession(const char* name, PHANDLE process = NULL)
{
// first we need to take a snapshot of the running processes
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot == INVALID_HANDLE_VALUE) {
LOG((CLOG_ERR "could not get process snapshot"));
throw XArch(new XArchEvalWindows());
}
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
// get the first process, and if we can't do that then it's
// unlikely we can go any further
BOOL gotEntry = Process32First(snapshot, &entry);
if (!gotEntry) {
LOG((CLOG_ERR "could not get first process entry"));
throw XArch(new XArchEvalWindows());
}
// used to record process names for debug info
std::list<std::string> nameList;
// now just iterate until we can find winlogon.exe pid
DWORD pid = 0;
while(gotEntry) {
// make sure we're not checking the system process
if (entry.th32ProcessID != 0) {
DWORD processSessionId;
BOOL pidToSidRet = ProcessIdToSessionId(
entry.th32ProcessID, &processSessionId);
if (!pidToSidRet) {
// if we can not acquire session associated with a specified process,
// simply ignore it
LOG((CLOG_ERR "could not get session id for process id %i", entry.th32ProcessID));
gotEntry = nextProcessEntry(snapshot, &entry);
continue;
}
else {
// only pay attention to processes in the active session
if (processSessionId == m_activeSessionId) {
// store the names so we can record them for debug
nameList.push_back(entry.szExeFile);
if (_stricmp(entry.szExeFile, name) == 0) {
pid = entry.th32ProcessID;
}
}
}
}
// now move on to the next entry (if we're not at the end)
gotEntry = nextProcessEntry(snapshot, &entry);
}
std::string nameListJoin;
for(std::list<std::string>::iterator it = nameList.begin();
it != nameList.end(); it++) {
nameListJoin.append(*it);
nameListJoin.append(", ");
}
LOG((CLOG_DEBUG "processes in session %d: %s",
m_activeSessionId, nameListJoin.c_str()));
CloseHandle(snapshot);
if (pid) {
if (process != NULL) {
// now get the process, which we'll use to get the process token.
LOG((CLOG_DEBUG "found %s in session %i", name, m_activeSessionId));
*process = OpenProcess(MAXIMUM_ALLOWED, FALSE, pid);
}
return true;
}
else {
LOG((CLOG_DEBUG "did not find %s in session %i", name, m_activeSessionId));
return false;
}
}
示例12: EjectDll
BOOL EjectDll(DWORD dwPID, LPCTSTR szDllPath)
{
BOOL bMore = FALSE, bFound = FALSE, bRet = FALSE;
HANDLE hSnapshot = INVALID_HANDLE_VALUE;
HANDLE hProcess = NULL;
HANDLE hThread = NULL;
MODULEENTRY32 me = { sizeof(me), };
LPTHREAD_START_ROUTINE pThreadProc = NULL;
HMODULE hMod = NULL;
DWORD dwDesiredAccess = 0;
TCHAR szProcName[MAX_PATH] = {0,};
if( INVALID_HANDLE_VALUE ==
(hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwPID)) )
{
_tprintf(L"EjectDll() : CreateToolhelp32Snapshot(%d) failed!!! [%d]\n",
dwPID, GetLastError());
goto EJECTDLL_EXIT;
}
bMore = Module32First(hSnapshot, &me);
for( ; bMore ; bMore = Module32Next(hSnapshot, &me) )
{
if( !_tcsicmp(me.szModule, szDllPath) ||
!_tcsicmp(me.szExePath, szDllPath) )
{
bFound = TRUE;
break;
}
}
if( !bFound )
{
_tprintf(L"EjectDll() : There is not %s module in process(%d) memory!!!\n",
szDllPath, dwPID);
goto EJECTDLL_EXIT;
}
dwDesiredAccess = PROCESS_ALL_ACCESS;
if( !(hProcess = OpenProcess(dwDesiredAccess, FALSE, dwPID)) )
{
_tprintf(L"EjectDll() : OpenProcess(%d) failed!!! [%d]\n",
dwPID, GetLastError());
goto EJECTDLL_EXIT;
}
hMod = GetModuleHandle(L"kernel32.dll");
if( hMod == NULL )
{
_tprintf(L"EjectDll() : GetModuleHandle(\"kernel32.dll\") failed!!! [%d]\n",
GetLastError());
goto EJECTDLL_EXIT;
}
pThreadProc = (LPTHREAD_START_ROUTINE)GetProcAddress(hMod, "FreeLibrary");
if( pThreadProc == NULL )
{
_tprintf(L"EjectDll() : GetProcAddress(\"FreeLibrary\") failed!!! [%d]\n",
GetLastError());
goto EJECTDLL_EXIT;
}
if( !MyCreateRemoteThread(hProcess, pThreadProc, me.modBaseAddr) )
{
_tprintf(L"EjectDll() : MyCreateRemoteThread() failed!!!\n");
goto EJECTDLL_EXIT;
}
bRet = TRUE;
EJECTDLL_EXIT:
_tcscpy_s(szProcName, GetProcName(dwPID));
_tprintf(L"%s(%d) %s!!! [%d]\n", szProcName, dwPID, bRet ? L"SUCCESS" : L"-->> FAILURE", GetLastError());
if( hThread )
CloseHandle(hThread);
if( hProcess )
CloseHandle(hProcess);
if( hSnapshot != INVALID_HANDLE_VALUE )
CloseHandle(hSnapshot);
return bRet;
}
示例13: 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)) )
{
_tprintf(L"InjectDll() : OpenProcess(%d) failed!!! [%d]\n",
dwPID, GetLastError());
goto INJECTDLL_EXIT;
}
pRemoteBuf = VirtualAllocEx(hProcess, NULL, dwBufSize,
MEM_COMMIT, PAGE_READWRITE);
if( pRemoteBuf == NULL )
{
_tprintf(L"InjectDll() : VirtualAllocEx() failed!!! [%d]\n",
GetLastError());
goto INJECTDLL_EXIT;
}
if( !WriteProcessMemory(hProcess, pRemoteBuf,
(LPVOID)szDllPath, dwBufSize, NULL) )
{
_tprintf(L"InjectDll() : WriteProcessMemory() failed!!! [%d]\n",
GetLastError());
goto INJECTDLL_EXIT;
}
hMod = GetModuleHandle(L"kernel32.dll");
if( hMod == NULL )
{
_tprintf(L"InjectDll() : GetModuleHandle(\"kernel32.dll\") failed!!! [%d]\n",
GetLastError());
goto INJECTDLL_EXIT;
}
pThreadProc = (LPTHREAD_START_ROUTINE)GetProcAddress(hMod, "LoadLibraryW");
if( pThreadProc == NULL )
{
_tprintf(L"InjectDll() : GetProcAddress(\"LoadLibraryW\") failed!!! [%d]\n",
GetLastError());
goto INJECTDLL_EXIT;
}
if( !MyCreateRemoteThread(hProcess, pThreadProc, pRemoteBuf) )
{
_tprintf(L"InjectDll() : MyCreateRemoteThread() failed!!!\n");
goto INJECTDLL_EXIT;
}
bRet = CheckDllInProcess(dwPID, szDllPath);
INJECTDLL_EXIT:
wsprintf(szProcName, L"%s", GetProcName(dwPID));
if( szProcName[0] == '\0' )
_tcscpy_s(szProcName, L"(no_process)");
_tprintf(L"%s(%d) %s!!! [%d]\n", szProcName, dwPID, bRet ? L"SUCCESS" : L"-->> FAILURE", GetLastError());
if( pRemoteBuf )
VirtualFreeEx(hProcess, pRemoteBuf, 0, MEM_RELEASE);
if( hThread )
CloseHandle(hThread);
if( hProcess )
CloseHandle(hProcess);
return bRet;
}
示例14: main
int
main(int argc, char *argv[]) /* Thread One */
{
DWORD dwThreadID;
HANDLE hProcess;
HANDLE hThread1, hThread2, hThread3, hThread4;
char szCommandLine[1024];
int i;
PARAMETERS myParameters;
INIT();
/* set exception handler */
strcpy(szCommandLine, "\0");
ThreadNr = 0;
InitializeArguments(&myParameters);
ParseArguments(argc, argv, &myParameters);
if (argc == 1) {
myParameters.bAll = TRUE;
}
// On initial call, no args are present; execute each subtest below
if (myParameters.bAll == TRUE) {
LaunchAllTests(argv, myParameters);
} else {
print("Entering thread with options:\n");
for (i = 1; i < argc; i++) {
if (!strncmp(argv[i], "/PID", 4)) {
strcat(szCommandLine, "/PID");
} else {
strcat(szCommandLine, argv[i]);
}
}
print("%s\n", szCommandLine);
do {
hThread1 = CreateThread(NULL, 0, &ThreadProc, &(myParameters.nSleepTime), 0,
&dwThreadID);
ExerciseThread(hThread1, myParameters);
WaitForSingleObject(hThread1, INFINITE);
ThreadNr++;
thread_proc_wait = TRUE;
hThread2 = CreateThread(NULL, 0, &ThreadProc, &(myParameters.nSleepTime), 0,
&dwThreadID);
while (!thread_proc_waiting) {
YIELD();
}
TerminateThread(hThread2, -1);
thread_proc_wait = FALSE;
thread_proc_waiting = FALSE;
ThreadNr++;
// ThreadProc2 calls ExitThread() immediately
hThread3 = CreateThread(NULL, 0, &ThreadProc2, &ThreadNr, 0, &dwThreadID);
WaitForSingleObject(hThread3, INFINITE);
ThreadNr++;
if (hThread1 != NULL) {
CloseHandle(hThread1);
}
if (hThread2 != NULL) {
CloseHandle(hThread2);
}
if (hThread3 != NULL) {
CloseHandle(hThread3);
}
} while (ThreadNr < MAX_THREADS);
if (myParameters.nPID != 0) {
// Prints out results in host PID
hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, myParameters.nPID);
if ((hProcess == NULL) && (myParameters.bVerbose == TRUE)) {
print("Error in OpenProcess(Code %d)\n", GetLastError());
}
hThread4 = CreateRemoteThread(hProcess, 0, 0, &ThreadProc,
&(myParameters.nSleepTime), 0, &dwThreadID);
if ((hThread4 == NULL) && (myParameters.bVerbose == TRUE)) {
print("Error in CreateRemoteThread(Code %d)\n", GetLastError());
}
WaitForSingleObject(hThread4, INFINITE);
if (hThread4 != NULL) {
CloseHandle(hThread4);
}
}
print("Exiting thread with options:\n");
print("%s\n", szCommandLine);
}
return 0;
}
示例15: RhInjectLibrary
//.........这里部分代码省略.........
ULONG UserLibrarySize;
ULONG PATHSize;
ULONG EasyHookPathSize;
ULONG EasyHookEntrySize;
ULONG Code;
SIZE_T BytesWritten;
WCHAR UserLibrary[MAX_PATH+1];
WCHAR PATH[MAX_PATH + 1];
WCHAR EasyHookPath[MAX_PATH + 1];
#ifdef _M_X64
CHAR* EasyHookEntry = "HookCompleteInjection";
#else
CHAR* EasyHookEntry = "[email protected]";
#endif
// validate parameters
if(InPassThruSize > MAX_PASSTHRU_SIZE)
THROW(STATUS_INVALID_PARAMETER_7, L"The given pass thru buffer is too large.");
if(InPassThruBuffer != NULL)
{
if(!IsValidPointer(InPassThruBuffer, InPassThruSize))
THROW(STATUS_INVALID_PARAMETER_6, L"The given pass thru buffer is invalid.");
}
else if(InPassThruSize != 0)
THROW(STATUS_INVALID_PARAMETER_7, L"If no pass thru buffer is specified, the pass thru length also has to be zero.");
if(InTargetPID == GetCurrentProcessId())
THROW(STATUS_NOT_SUPPORTED, L"For stability reasons it is not supported to inject into the calling process.");
// open target process
if((hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, InTargetPID)) == NULL)
{
if(GetLastError() == ERROR_ACCESS_DENIED)
THROW(STATUS_ACCESS_DENIED, L"Unable to open target process. Consider using a system service.")
else
THROW(STATUS_NOT_FOUND, L"The given target process does not exist!");
}
/*
Check bitness...
After this we can assume hooking a target that is running in the same
WOW64 level.
*/
#ifdef _M_X64
FORCE(RhIsX64Process(InTargetPID, &Is64BitTarget));
if(!Is64BitTarget)
THROW(STATUS_WOW_ASSERTION, L"It is not supported to directly hook through the WOW64 barrier.");
if(!GetFullPathNameW(InLibraryPath_x64, MAX_PATH, UserLibrary, NULL))
THROW(STATUS_INVALID_PARAMETER_5, L"Unable to get full path to the given 64-bit library.");
#else
FORCE(RhIsX64Process(InTargetPID, &Is64BitTarget));
if(Is64BitTarget)
THROW(STATUS_WOW_ASSERTION, L"It is not supported to directly hook through the WOW64 barrier.");
if(!GetFullPathNameW(InLibraryPath_x86, MAX_PATH, UserLibrary, NULL))
THROW(STATUS_INVALID_PARAMETER_4, L"Unable to get full path to the given 32-bit library.");
#endif
/*