コード例 #1
2
/*
=======================================
    进程启停
=======================================
*/
CR_API BOOL WINAPI
ProcessCtrl (
  __CR_IN__ DWORD   prcss_id,
  __CR_IN__ BOOL    suspend
    )
{
    HANDLE          snap;
    THREADENTRY32   te32;

    /* 取得指定进程的所有线程信息 */
    snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, prcss_id);
    if (snap == INVALID_HANDLE_VALUE)
        return (HLB_ERROR);

    /* 枚举线程 */
    te32.dwSize = sizeof(THREADENTRY32);
    if(!Thread32First(snap, &te32)) {
        CloseHandle(snap);
        return (HLB_ERROR);
    }

    do {
        if (te32.th32OwnerProcessID == prcss_id)
        {
            HANDLE  handle;

            handle = OpenThread(THREAD_SUSPEND_RESUME, FALSE,
                                te32.th32ThreadID);
            if (suspend)
                SuspendThread(handle);
            else
                ResumeThread(handle);
            CloseHandle(handle);
        }
    } while (Thread32Next(snap, &te32));

    CloseHandle(snap);
    return (HLB_OKAY);
}
コード例 #2
1
VOID * SocketExtension::GetExtensionFunction(SOCKET s, GUID * clasid)
{
	if (clasid == NULL || s == INVALID_SOCKET)
	{
		return NULL;
	}
	VOID* func = { 0 };
	DWORD size = 0;
	//
	WSATHREADID threadid;
	threadid.ThreadHandle = OpenThread(THREAD_ALL_ACCESS, FALSE, GetCurrentThreadId());
	threadid.Reserved = NULL;
	INT error = 0;
	if (LayeredServiceProvider_Current.NextProcTable.lpWSPIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, clasid,
		sizeof(GUID), &func, sizeof(VOID*), &size, NULL, NULL, &threadid, &error) == SOCKET_ERROR)
	{
		CloseHandle(threadid.ThreadHandle);
		return NULL;
	}
	CloseHandle(threadid.ThreadHandle);
	return func;
}
コード例 #3
1
ファイル: Utils.cpp プロジェクト: brock7/xdbg
_TEB* GetThreadTeb(DWORD tid)
{
	NTSTATUS ntStatus;
	if (NtQueryInformationThread == NULL)
		NtQueryInformationThread = (pNtQIT)GetProcAddress(GetModuleHandle("ntdll.dll"),
		"NtQueryInformationThread");

	if (NtQueryInformationThread == NULL) {
		MyTrace("%s(): cannot found NtQueryInformationThread()", __FUNCTION__);
		return 0;
	}

	HANDLE hThread = OpenThread(THREAD_QUERY_INFORMATION, FALSE, tid);
	UINT32 ThreadBasicInformation = 0;
	THREAD_BASIC_INFORMATION bi;
	ntStatus = NtQueryInformationThread(hThread, ThreadBasicInformation, &bi, sizeof(bi), NULL);
	XDbgCloseHandle(hThread);
	if (ntStatus != 0)
		return 0;

	return (_TEB*)bi.TebBaseAddress;
}
コード例 #4
0
ファイル: hook.c プロジェクト: pkesist/buildpal
//-------------------------------------------------------------------------
static VOID Freeze(PFROZEN_THREADS pThreads, UINT pos, UINT action)
{
    pThreads->pItems   = NULL;
    pThreads->capacity = 0;
    pThreads->size     = 0;
    EnumerateThreads(pThreads);

    if (pThreads->pItems != NULL)
    {
        UINT i;
        for (i = 0; i < pThreads->size; ++i)
        {
            HANDLE hThread = OpenThread(MH_THREAD_ACCESS, FALSE, pThreads->pItems[i]);
            if (hThread != NULL)
            {
                SuspendThread(hThread);
                ProcessThreadIPs(hThread, pos, action);
                CloseHandle(hThread);
            }
        }
    }
}
コード例 #5
0
ファイル: winal.c プロジェクト: kwolekr/phyros
void _CancelThread(pthread_t tid, int exitcode) {
	#ifdef _WIN32
		/*
		 * IMPORTANT TODO:
		 * TerminateThread() should NOT be used!!
		 * Termination with this function is abrupt and could severely damage the application
		 * (it could hold a critical section within a system library, for instance)
		 * Under Windows 2000, XP, and Server 2003, the stack isn't freed resulting in a leak.
		 *
		 *   GET PROPER EXITING EVENT CODE IN HERE ASAP!
		 *
		 */
		HANDLE hThread;
		hThread = OpenThread(THREAD_TERMINATE, 0, tid);
		if (hThread) {
			TerminateThread(hThread, exitcode);
			CloseHandle(hThread);
		}
	#else
		pthread_cancel(tid);
	#endif
}
コード例 #6
0
ファイル: threads.cpp プロジェクト: yueying/3DReconstruction
/**返回当前线程创建到退出消耗的CPU时间
*/
void mvg::synch::getCurrentThreadTimes(
	time_t			&creationTime,
	time_t			&exitTime,
	double			&cpuTime)
{
	MVG_START

	FILETIME	timCreat, timExit, timKernel, timUser;
	uint64_t	t;

	HANDLE threadHandle;

	// 根据ID得到当前线程的handle
	threadHandle = OpenThread(READ_CONTROL | THREAD_QUERY_INFORMATION, FALSE, GetCurrentThreadId());  // threadId);
	if (!threadHandle)	 THROW_EXCEPTION("Cannot open the thread with the given 'threadId'");

	if (!GetThreadTimes(threadHandle, &timCreat, &timExit, &timKernel, &timUser))
	{
		CloseHandle(threadHandle);
		THROW_EXCEPTION("Error accessing thread times!");
	}

	CloseHandle(threadHandle);

	t = (((uint64_t)timCreat.dwHighDateTime) << 32) | timCreat.dwLowDateTime;
	creationTime = (t - 116444736000000000ULL) / 10000000;

	t = (((uint64_t)timExit.dwHighDateTime) << 32) | timExit.dwLowDateTime;
	exitTime = (t - 116444736000000000ULL) / 10000000;

	// CPU时间是用户+内核
	int64_t	t1 = (((uint64_t)timKernel.dwHighDateTime) << 32) | timKernel.dwLowDateTime;
	int64_t	t2 = (((uint64_t)timUser.dwHighDateTime) << 32) | timUser.dwLowDateTime;

	cpuTime = ((double)(t1 + t2)) * 100e-9;	// FILETIME counts intervals of 100ns


	MVG_END
}
コード例 #7
0
ファイル: DarunGrim.cpp プロジェクト: LucaBongiorni/DarunGrim
BOOL DarunGrim::CreateIDACommandProcessorThread()
{
	if (IDACommandProcessorThreadId > 0)
	{
		HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, IDACommandProcessorThreadId);
		if (hThread)
		{
			CloseHandle(hThread);
		}
		else
		{
			IDACommandProcessorThreadId = -1;
		}
	}

	if (IDACommandProcessorThreadId == -1)
	{
		CreateThread(NULL, 0, IDACommandProcessorThread, (PVOID)this, 0, &IDACommandProcessorThreadId);
		return TRUE;
	}
	return FALSE;
}
コード例 #8
0
ファイル: w32_thread.c プロジェクト: noqisofon/libpyrope
w32_thread_t w32_thread_open( uint32_t   desired_access,
                              gboolean   inherit_handle,
                              uint32_t   thread_id
                              )
{
    w32_thread_t    ret_handle;

    if ( thread_id != 0 )
        return INVALID_HANDLE_VALUE;

    /*
     * desired_access には少なくとも STANDARD_RIGHTS_REQUIRED が含まれていなければならない。
     */
    ret_handle  = OpenThread( desired_access,
                              inherit_handle,
                              thread_id
                              );
    if ( ret_handle == NULL )
        return INVALID_HANDLE_VALUE;

    return ret_handle;
}
コード例 #9
0
ファイル: patchapi.cpp プロジェクト: caidongyun/libs
HTHREAD StartVMSessionPatching(unsigned PID)
{
#ifndef _WIN64
	if (IsRundll64Required(PID))
	{
		DWORD dwID = (DWORD)Call64BitKDCLIENT(kStartVMSessionPatching, PID);
		EnableDebugPrivilege();
		if(!dwID)
			return 0;
		else if (dwID == -1)
			return INVALID_HANDLE_VALUE;
		else
		{
			HANDLE h = OpenThread(THREAD_ALL_ACCESS, FALSE, dwID);
			if (!h || (h == INVALID_HANDLE_VALUE))	//Thread already finished
				return 0;
			return h;
		}
	}
#endif
	return StartPatcherThread(PID);
}
コード例 #10
0
/*
 * Opens a thread with the supplied identifier using the supplied permissions
 * and returns a HANDLE to the requestor
 *
 * req: TLV_TYPE_THREAD_ID    - The thread identifier to open
 * req: TLV_TYPE_THREAD_PERMS - Thre thread permissions to open with
 */
DWORD request_sys_process_thread_open(Remote *remote, Packet *packet)
{
	Packet *response = packet_create_response(packet);
	HANDLE handle = NULL;
	DWORD result = ERROR_SUCCESS;
	DWORD threadId;
	DWORD perms;

	// Get the parameters
	threadId = packet_get_tlv_value_uint(packet, TLV_TYPE_THREAD_ID);
	perms    = packet_get_tlv_value_uint(packet, TLV_TYPE_THREAD_PERMS);

	do
	{
		// Validate parameters
		if (!threadId)
		{
			result = ERROR_INVALID_PARAMETER;
			break;
		}

		// Open the thread
		if (!(handle = OpenThread(perms, FALSE, threadId)))
		{
			result = GetLastError();
			break;
		}

		// Add the handle to the response packet
		packet_add_tlv_uint(response, TLV_TYPE_THREAD_HANDLE, 
				(DWORD)handle);

	} while (0);

	packet_transmit_response(result, remote, response);

	return ERROR_SUCCESS;
}
コード例 #11
0
//////////////////////////////////////////////////////////////////////////
//
// ¸ðµç ¾²·¹µå¸¦ °¡µ¿½ÃŲ´Ù
//
//////////////////////////////////////////////////////////////////////////
void CRawHookMgr::ResumeAllThread()
{
	// ¸ðµç ¾²·¹µåµéÀÇ ½º³À¼¦À» ¸¸µì´Ï´Ù.
	HANDLE hThreadSnap = INVALID_HANDLE_VALUE;
	hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, GetCurrentProcessId());

	if(hThreadSnap == INVALID_HANDLE_VALUE) return;


	THREADENTRY32 te32;
	memset(&te32, 0,sizeof(THREADENTRY32));
	te32.dwSize = sizeof(THREADENTRY32);

	// ÇöÀç ÇÁ·Î¼¼½ºID¿Í ¾²·¹µåID
	DWORD dwCurPID = GetCurrentProcessId();
	DWORD dwCurTID = GetCurrentThreadId();

	// ¾²·¹µå ¼øȸ
	BOOL bNext = Thread32First(hThreadSnap, &te32);
	while(bNext)
	{
		if( te32.th32OwnerProcessID == dwCurPID && te32.th32ThreadID != dwCurTID )
		{
			// ¾²·¹µå Á¤Áö
			HANDLE hThread = OpenThread(THREAD_SUSPEND_RESUME, FALSE, te32.th32ThreadID);
			if(hThread)
			{
				ResumeThread(hThread);
				//CloseHandle(hThread);
			}
		}

		bNext = Thread32Next(hThreadSnap, &te32);
	}
	CloseHandle (hThreadSnap);

	m_bIsAllThreadSuspended = FALSE;
}
コード例 #12
0
ファイル: thread.cpp プロジェクト: FantomKnight/nucleuscoop
	void ScopedThreadExclusive::Freeze(
		const std::vector<DWORD>& threads, const std::vector<uintptr_t>& oldIPs, const std::vector<uintptr_t>& newIPs)
	{
		assert(("ScopedThreadExclusive::freeze", (oldIPs.size() == newIPs.size())));

		static const DWORD ThreadAccess 
			= THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION | THREAD_SET_CONTEXT;

		for (size_t i = 0, count = threads.size(); i < count; ++i)
		{
			DWORD tid = threads[i];
			ScopedHandle hThread = OpenThread(ThreadAccess, FALSE, tid);
			SuspendThread(hThread);

			// 書き換え範囲内でスレッドが停止した場合は、トランポリン関数に制御を移す
			CONTEXT c = { 0 };
			c.ContextFlags = CONTEXT_CONTROL;
			if (!GetThreadContext(hThread, &c))
			{
				return;
			}

#if defined _M_X64
			DWORD64& ip = c.Rip;
#elif defined _M_IX86
			DWORD& ip = c.Eip;
#endif
			for (size_t i = 0; i < oldIPs.size(); ++i)
			{
				if (ip == oldIPs[ i ])
				{
					ip = newIPs[ i ];
					SetThreadContext(hThread, &c);
					break;
				}
			}
		}
	}
コード例 #13
0
ファイル: MetroWindow.cpp プロジェクト: codepongo/iBurnMgr
MetroWindow::~MetroWindow()
{
	SafeRelease(&m_pDirect2dFactory);
	SafeRelease(&m_pRenderTarget);
	SafeRelease(&m_pMinButtonActiveBrush);
	SafeRelease(&m_pMetroButtonNsBrush);
	SafeRelease(&m_pMetroButtonLsBrush);
	SafeRelease(&m_pLightWhiteBrush);
	SafeRelease(&m_EdgeViewBrush);
	SafeRelease(&m_pCloseButtonClickBrush);
	SafeRelease(&m_pControlTextBrush);
	SafeRelease(&m_pDWriteTypography);
	SafeRelease(&m_pIDWriteFactory);
	SafeRelease(&m_pITextFormatTitle);
	SafeRelease(&m_pITextFormatContent);

	HANDLE hThread = OpenThread(DELETE, FALSE, this->iseThreadID);
	if (hThread)
	{
		TerminateThread(hThread, 0);
		CloseHandle(hThread);
	}
}
コード例 #14
0
static VOID
start_profiler_timer_event (void)
{
	g_return_if_fail (g_timer_main_thread == INVALID_HANDLE_VALUE && g_timer_event == 0);

	TIMECAPS timecaps;

	if (timeGetDevCaps (&timecaps, sizeof (timecaps)) != TIMERR_NOERROR)
		return;

	g_timer_main_thread = OpenThread (READ_CONTROL | THREAD_GET_CONTEXT, FALSE, GetCurrentThreadId ());
	if (g_timer_main_thread == NULL)
		return;

	if (timeBeginPeriod (1) != TIMERR_NOERROR)
		return;

	g_timer_event = timeSetEvent (1, 0, (LPTIMECALLBACK)timer_event_proc, (DWORD_PTR)g_timer_main_thread, TIME_PERIODIC | TIME_KILL_SYNCHRONOUS);
	if (g_timer_event == 0) {
		timeEndPeriod (1);
		return;
	}
}
コード例 #15
0
ファイル: psuspend.cpp プロジェクト: stormsw/psuspend
void thresume(DWORD processId)
{
	HANDLE hThreadSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);

	THREADENTRY32 threadEntry;
	threadEntry.dwSize = sizeof(THREADENTRY32);

	Thread32First(hThreadSnapshot, &threadEntry);

	do
	{
		if (threadEntry.th32OwnerProcessID == processId)
		{
			HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE,
				threadEntry.th32ThreadID);
			ResumeThread(hThread);
			//SuspendThread(hThread);
			CloseHandle(hThread);
		}
	} while (Thread32Next(hThreadSnapshot, &threadEntry));

	CloseHandle(hThreadSnapshot);
}
コード例 #16
0
ファイル: HangMonitor.cpp プロジェクト: Antonius32/Pale-Moon
void
Startup()
{
  // The hang detector only runs in chrome processes. If you change this,
  // you must also deal with the threadsafety of AnnotateCrashReport in
  // non-chrome processes!
  if (GoannaProcessType_Default != XRE_GetProcessType()) {
    return;
  }

  MOZ_ASSERT(!gMonitor, "Hang monitor already initialized");
  gMonitor = new Monitor("HangMonitor");

  Preferences::RegisterCallback(PrefChanged, kHangMonitorPrefName, nullptr);
  PrefChanged(nullptr, nullptr);

#ifdef REPORT_CHROME_HANGS
  Preferences::RegisterCallback(PrefChanged, kTelemetryPrefName, nullptr);
  winMainThreadHandle =
    OpenThread(THREAD_ALL_ACCESS, FALSE, GetCurrentThreadId());
  if (!winMainThreadHandle) {
    return;
  }
  gAnnotators = new std::set<Annotator*>();
#endif

  // Don't actually start measuring hangs until we hit the main event loop.
  // This potentially misses a small class of really early startup hangs,
  // but avoids dealing with some xpcshell tests and other situations which
  // start XPCOM but don't ever start the event loop.
  Suspend();

  gThread = PR_CreateThread(PR_USER_THREAD,
                            ThreadMain,
                            nullptr, PR_PRIORITY_LOW, PR_GLOBAL_THREAD,
                            PR_JOINABLE_THREAD, 0);
}
コード例 #17
0
ファイル: llwindebug.cpp プロジェクト: VirtualReality/Viewer
BOOL GetThreadCallStack(DWORD thread_id, LLSD& info)
{
    if(GetCurrentThreadId() == thread_id)
    {
        // Early exit for the current thread.
        // Suspending the current thread would be a bad idea.
        // Plus you can't retrieve a valid current thread context.
        return false;
    }

    HANDLE thread_handle = INVALID_HANDLE_VALUE; 
    thread_handle = OpenThread(THREAD_ALL_ACCESS, FALSE, thread_id);
    if(INVALID_HANDLE_VALUE == thread_handle)
    {
        return FALSE;
    }

    BOOL result = false;
    if(-1 != SuspendThread(thread_handle))
    {
        CONTEXT context_struct;
        context_struct.ContextFlags = CONTEXT_FULL;
        if(GetThreadContext(thread_handle, &context_struct))
        {
            Get_Call_Stack(NULL, &context_struct, info);
            result = true;
        }
        ResumeThread(thread_handle);
    }
    else
    {
        // Couldn't suspend thread.
    }

    CloseHandle(thread_handle);
    return result;
}
コード例 #18
0
		BOOL SuspendOtherThreads()
		{
			BOOL success = TRUE;

			auto myThreadId = GetCurrentThreadId();

			if (!myThreadId)
			{
				printError("myThreadId = GetThreadId");
				return FALSE;
			}

			auto threads = GetThreads(GetCurrentProcessId());

			if (threads.size() == 0)
				return FALSE;

			for (auto t : threads)
				if (t.th32ThreadID != myThreadId)
				{
					HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, false, t.th32ThreadID);
					if (!hThread)
					{
						printError("OpenThread");
						success = FALSE;
						continue;
					}
					if (-1 == SuspendThread(hThread))
					{
						printError("SuspendThread");
						success = FALSE;
					}
					CloseHandle(hThread);
				}

			return success;
		}
コード例 #19
0
void ListProcessThreads(DWORD dwOwnerPID)
{
    HANDLE hThreadSnap = INVALID_HANDLE_VALUE;
    THREADENTRY32 te32;

    hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);

    if (hThreadSnap == INVALID_HANDLE_VALUE)
        return;

    te32.dwSize = sizeof(THREADENTRY32);

    if (!Thread32First(hThreadSnap, &te32))
    {
        CloseHandle(hThreadSnap);
        return;
    }

    DWORD result = 0;
    do
    {
        if (te32.th32OwnerProcessID == dwOwnerPID)
        {
            printf("\n     THREAD ID = 0x%08X", te32.th32ThreadID);

            HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, te32.th32ThreadID);
            PTEB pTeb = GetTeb(hThread);
            printf("\n     TEB = %p\n", pTeb);

            CloseHandle(hThread);
        }
    } while (Thread32Next(hThreadSnap, &te32));

    printf("\n");
    CloseHandle(hThreadSnap);
}
コード例 #20
0
ファイル: Sound.cpp プロジェクト: godlyeh/CSOneSix
void HookSound()
{
	dwSoundFunction = Utility->FindPattern("hw.dll", "55 8B EC 83 EC 48 A1 ? ? ? ? 53", false);
	dwSoundRetAddr = dwSoundFunction + 0x1;

	Utility->DeleteLog("Sound.txt");
	Utility->Log("Sound.txt", "Sound Pointer: 0x%p (Module: 0x%p)\n", dwSoundFunction, Utility->CalcModuleOffset(dwSoundFunction));

	hExceptionHandler = AddVectoredExceptionHandler(TRUE, SoundExceptionHandler);

	HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, Utility->GetProcessThread()->th32ThreadID);
	GetThreadContext(hThread, &GameCTX);

	CONTEXT ctx; ZeroMemory(&ctx, sizeof(CONTEXT));
	ctx = { CONTEXT_DEBUG_REGISTERS };
	ctx.Dr0 = dwSoundFunction;
	ctx.Dr7 = 1;

	SuspendThread(hThread);
	SetThreadContext(hThread, &ctx);
	ResumeThread(hThread);

	CloseHandle(hThread);
}
コード例 #21
0
ファイル: windows.c プロジェクト: pyrovski/papi-rapl
void CALLBACK
_papi_hwd_timer_callback( UINT wTimerID, UINT msg,
						  DWORD dwUser, DWORD dw1, DWORD dw2 )
{
	_papi_hwi_context_t ctx;
	CONTEXT context;				   // processor specific context structure
	HANDLE threadHandle;
	BOOL error;
	ThreadInfo_t *t = NULL;

	ctx.ucontext = &context;

	// dwUser is the threadID passed by timeSetEvent
	// NOTE: This call requires W2000 or later
	threadHandle = OpenThread( THREAD_GET_CONTEXT, FALSE, dwUser );

	// retrieve the contents of the control registers only
	context.ContextFlags = CONTEXT_CONTROL;
	error = GetThreadContext( threadHandle, &context );
	CloseHandle( threadHandle );

	// pass a void pointer to cpu register data here
	_papi_hwi_dispatch_overflow_signal( ( void * ) ( &ctx ), NULL, 0, 0, &t );
}
コード例 #22
0
ファイル: EhTrace.cpp プロジェクト: K2/EhTrace
bool InstallThread(ULONG th32ThreadID, int reason)
{
	PExecutionBlock pCtx = NULL;

	pCtx = InitBlock(th32ThreadID);
	if (pCtx == NULL) {
		wprintf(L"unable to install thread %d (OOM?)\n", th32ThreadID);
		return false;
	}

	KnownThreadCount++;

	// OpenThreads for neighbor threads
	pCtx->hThr = OpenThread(THREAD_SET_CONTEXT | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, FALSE, th32ThreadID);

	// install branch tracing
	CONTEXT ContextRecord = { 0 };
	ContextRecord.ContextFlags = CONTEXT_ALL;

	wprintf(L"%d) attaching to thread ID: %d in process %d\n", reason, th32ThreadID, GetCurrentProcessId());

	if (!GetThreadContext(pCtx->hThr, &ContextRecord))
		wprintf(L"unable to get context on thread %d\n", th32ThreadID);

	// installed a thread
	EnterThreadTable(th32ThreadID, true);

	ContextRecord.EFlags |= 0x100;	// single step
	ContextRecord.Dr7 |= 0x300;		// setup branch tracing 

	if (!SetThreadContext(pCtx->hThr, &ContextRecord))
		wprintf(L"unable to set context on thread %d\n", th32ThreadID);


	return true;
}
コード例 #23
0
ファイル: mini-windows.c プロジェクト: AnthonyTruchet/mono
void
mono_runtime_setup_stat_profiler (void)
{
	static int inited = 0;
	TIMECAPS timecaps;

	if (inited)
		return;

	inited = 1;
	if (timeGetDevCaps (&timecaps, sizeof (timecaps)) != TIMERR_NOERROR)
		return;

	if ((win32_main_thread = OpenThread (READ_CONTROL | THREAD_GET_CONTEXT, FALSE, GetCurrentThreadId ())) == NULL)
		return;

	if (timeBeginPeriod (1) != TIMERR_NOERROR)
		return;

	if ((win32_timer = timeSetEvent (1, 0, (LPTIMECALLBACK)win32_time_proc, (DWORD_PTR)NULL, TIME_PERIODIC)) == 0) {
		timeEndPeriod (1);
		return;
	}
}
コード例 #24
0
void	CAPThread::SetPriority(NativeThread inThread, UInt32 inPriority, bool inFixedPriority)
{
#if TARGET_OS_MAC
	if(inThread != 0)
	{
		kern_return_t theError = 0;
		
		//	set whether or not this is a fixed priority thread
		if (inFixedPriority)
		{
			thread_extended_policy_data_t theFixedPolicy = { false };
			theError = thread_policy_set(pthread_mach_thread_np(inThread), THREAD_EXTENDED_POLICY, (thread_policy_t)&theFixedPolicy, THREAD_EXTENDED_POLICY_COUNT);
			AssertNoKernelError(theError, "CAPThread::SetPriority: failed to set the fixed-priority policy");
		}
		
		//	set the thread's absolute priority which is relative to the priority on which thread_policy_set() is called
		UInt32 theCurrentThreadPriority = getScheduledPriority(pthread_self(), CAPTHREAD_SET_PRIORITY);
        thread_precedence_policy_data_t thePrecedencePolicy = { static_cast<integer_t>(inPriority - theCurrentThreadPriority) };
		theError = thread_policy_set(pthread_mach_thread_np(inThread), THREAD_PRECEDENCE_POLICY, (thread_policy_t)&thePrecedencePolicy, THREAD_PRECEDENCE_POLICY_COUNT);
        AssertNoKernelError(theError, "CAPThread::SetPriority: failed to set the precedence policy");
		
		#if	Log_SetPriority
			DebugMessageN4("CAPThread::SetPriority: requsted: %lu spawning: %lu current: %lu assigned: %d", mPriority, mSpawningThreadPriority, theCurrentThreadPriority, thePrecedencePolicy.importance);
		#endif
    } 
#elif TARGET_OS_WIN32
	if(inThread != NULL)
	{
		HANDLE hThread = OpenThread(NULL, FALSE, inThread);
		if(hThread != NULL) {
			SetThreadPriority(hThread, inPriority);
			CloseHandle(hThread);
		}
	}
#endif
}
コード例 #25
0
ファイル: Utils.cpp プロジェクト: brock7/xdbg
DWORD GetProcessMainThread(DWORD dwProcID)
{
	DWORD dwMainThreadID = 0;
	ULONGLONG ullMinCreateTime = MAXULONGLONG;

	HANDLE hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
	if (hThreadSnap != INVALID_HANDLE_VALUE) {
		THREADENTRY32 th32;
		th32.dwSize = sizeof(THREADENTRY32);
		BOOL bOK = TRUE;
		for (bOK = Thread32First(hThreadSnap, &th32); bOK;
			bOK = Thread32Next(hThreadSnap, &th32)) {
			if (th32.th32OwnerProcessID == dwProcID) {
				HANDLE hThread = OpenThread(THREAD_QUERY_INFORMATION,
					TRUE, th32.th32ThreadID);
				if (hThread) {
					FILETIME afTimes[4] = { 0 };
					if (GetThreadTimes(hThread,
						&afTimes[0], &afTimes[1], &afTimes[2], &afTimes[3])) {
						ULONGLONG ullTest = MAKEULONGLONG(afTimes[0].dwLowDateTime,
							afTimes[0].dwHighDateTime);
						if (ullTest && ullTest < ullMinCreateTime) {
							ullMinCreateTime = ullTest;
							dwMainThreadID = th32.th32ThreadID; // let it be main... :)
						}
					}
					CloseHandle(hThread);
				}
			}
		}

		CloseHandle(hThreadSnap);
	}

	return (dwMainThreadID);
}
コード例 #26
0
ファイル: Breakpoint.cpp プロジェクト: Jerffffff/Combat-Arms
	void cBreakpoint::GetMainThreadFromCurrentProcess()
	{
		unsigned long uProcessId = GetCurrentProcessId();
		HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, uProcessId);

		if (!hSnapshot)
			return;

		THREADENTRY32 lpThread;

		lpThread.dwSize = sizeof(THREADENTRY32);

		if (Thread32First(hSnapshot, &lpThread))
		{
			do
			{
				if (lpThread.th32OwnerProcessID == uProcessId)
					break;
			} while (Thread32Next(hSnapshot, &lpThread));

			CloseHandle(hSnapshot);
			thread = OpenThread(THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_SUSPEND_RESUME, 1, lpThread.th32ThreadID);
		}
	}
コード例 #27
0
ファイル: ansicon.c プロジェクト: kmkkmk/app
//int _tmain( int argc, TCHAR* argv[] )
int main( void )
{
  STARTUPINFO si;
  PROCESS_INFORMATION pi;
  TCHAR*  cmd;
  BOOL	  option;
  BOOL	  opt_m;
  BOOL	  installed;
  HMODULE ansi;
  int	  rc = 0;

  int argc;
  LPWSTR* argv = CommandLineToArgvW( GetCommandLine(), &argc );

  if (argc > 1)
  {
    if (lstrcmp( argv[1], L"--help" ) == 0 ||
	(argv[1][0] == '-' && (argv[1][1] == '?' || argv[1][1] == 'h')) ||
	(argv[1][0] == '/' && argv[1][1] == '?'))
    {
      help();
      return rc;
    }
    if (lstrcmp( argv[1], L"--version" ) == 0)
    {
      _putws( L"ANSICON (" BITS L"-bit) version " PVERS L" (" PDATE L")." );
      return rc;
    }
  }

#if (MYDEBUG > 1)
  DEBUGSTR( NULL ); // create a new file
#endif

  option = (argc > 1 && argv[1][0] == '-');
  if (option && (towlower( argv[1][1] ) == 'i' ||
		 towlower( argv[1][1] ) == 'u'))
  {
    process_autorun( argv[1][1] );
    argv[1][1] = 'p';
  }

  get_original_attr();

  opt_m = FALSE;
  if (option && argv[1][1] == 'm')
  {
    WORD attr = 7;
    if (iswxdigit( argv[1][2] ))
    {
      attr = iswdigit( argv[1][2] ) ? argv[1][2] - '0'
				    : (argv[1][2] | 0x20) - 'a' + 10;
      if (iswxdigit( argv[1][3]))
      {
	attr <<= 4;
	attr |= iswdigit( argv[1][3] ) ? argv[1][3] - '0'
				       : (argv[1][3] | 0x20) - 'a' + 10;
      }
    }
    SetConsoleTextAttribute( hConOut, attr );

    opt_m = TRUE;
    ++argv;
    --argc;
    option = (argc > 1 && argv[1][0] == '-');
  }

  installed = (GetEnvironmentVariable( L"ANSICON", NULL, 0 ) != 0);

  if (option && argv[1][1] == 'p')
  {
    // If it's already installed, there's no need to do anything.
    if (installed)
      ;
    else if (GetParentProcessInfo( &pi ))
    {
      pi.hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, pi.dwProcessId );
      pi.hThread  = OpenThread(  THREAD_ALL_ACCESS,  FALSE, pi.dwThreadId  );
      SuspendThread( pi.hThread );
      if (!Inject( &pi ))
      {
	_putws( L"ANSICON: parent process type is not supported." );
	rc = 1;
      }
      ResumeThread( pi.hThread );
      CloseHandle( pi.hThread );
      CloseHandle( pi.hProcess );
    }
    else
    {
      _putws( L"ANSICON: could not obtain the parent process." );
      rc = 1;
    }
  }
  else
  {
    ansi = 0;
    if (!installed)
    {
      ansi = LoadLibrary( L"ANSI" BITS L".dll" );
      if (!ansi)
      {
	fputws( L"ANSICON: failed to load ANSI" BITS L".dll.\n", stderr );
	rc = 1;
      }
    }

    if (option && (argv[1][1] == 't' || argv[1][1] == 'T'))
    {
      BOOL title = (argv[1][1] == 'T');
      if (argc == 2)
      {
	argv[2] = L"-";
	++argc;
      }
      for (; argc > 2; ++argv, --argc)
      {
	if (title)
	  wprintf( L"==> %s <==\n", argv[2] );
	display( argv[2], title );
	if (title)
	  putwchar( '\n' );
      }
    }
    else
    {
      // Retrieve the original command line, skipping our name and the option.
      cmd = skip_spaces( skip_arg( skip_spaces( GetCommandLine() ) ) );
      if (opt_m)
	cmd = skip_spaces( skip_arg( cmd ) );

      if (cmd[0] == '-' && (cmd[1] == 'e' || cmd[1] == 'E'))
      {
	fputws( cmd + 3, stdout );
	if (cmd[1] == 'e')
	  putwchar( '\n' );
      }
      else if (!_isatty( 0 ) && *cmd == '\0')
      {
	display( L"-", FALSE );
      }
      else
      {
	if (*cmd == '\0')
	{
	  cmd = _wgetenv( L"ComSpec" );
	  if (cmd == NULL)
	    cmd = L"cmd";
	}

	ZeroMemory( &si, sizeof(si) );
	si.cb = sizeof(si);
	if (CreateProcess( NULL, cmd, NULL,NULL, TRUE, 0, NULL,NULL, &si, &pi ))
	{
	  BOOL	console = FALSE;
	  TCHAR name[MAX_PATH];
	  DWORD rc;
	  CoInitialize( NULL );
	  do
	  {
	    // When I first tried doing this, it took a little while to
	    // succeed.  Testing again shows it works immediately - perhaps the
	    // CoInitialize introduces enough of a delay.  Still, play it safe
	    // and keep trying.  And if you're wondering why I do it at all,
	    // ProcessType may detect GUI, even for a console process.	That's
	    // fine after injection (including -p), but not here.  We *need* to
	    // suspend our own execution whilst running the child, otherwise
	    // bad things happen (besides which, I want to restore the original
	    // attributes when the child exits).
	    if (GetModuleFileNameEx( pi.hProcess, NULL, name, lenof(name) ))
	    {
	      DWORD_PTR info;
	      info = SHGetFileInfo( name, 0, NULL, 0, SHGFI_EXETYPE );
	      if (info == 0x00004550) // console PE
		console = TRUE;
	      DEBUGSTR( L"%s", name );
	      DEBUGSTR( L"  %s (%p)", (console) ? L"Console" : L"Not console",
				      info );
	      break;
	    }
	    Sleep( 10 );
	  } while (GetExitCodeProcess( pi.hProcess, &rc ) &&
		   rc == STILL_ACTIVE);
	  CoUninitialize();
	  if (console)
	  {
	    SetConsoleCtrlHandler( (PHANDLER_ROUTINE)CtrlHandler, TRUE );
	    WaitForSingleObject( pi.hProcess, INFINITE );
	  }
	  CloseHandle( pi.hProcess );
	  CloseHandle( pi.hThread );
	}
	else
	{
	  *skip_arg( cmd ) = '\0';
	  wprintf( L"ANSICON: '%s' could not be executed.\n", cmd );
	  rc = 1;
	}
      }
    }

    if (ansi)
      FreeLibrary( ansi );
  }

  set_original_attr();
  return rc;
}
コード例 #28
0
bool
windows_suspend(DWORD pid)
{
	// make sure we haven't already suspended this process, then allocate
	// a SuspendedProcess object and add it to the hash table
	//
	SuspendedProcess* sp;
	int ret = suspended_processes.lookup(pid, sp);
	ASSERT(ret == -1);
	sp = new SuspendedProcess(11, hash_func);
	ASSERT(sp != NULL);
	ret = suspended_processes.insert(pid, sp);
	ASSERT(ret != -1);

	// we need to loop until iterating through the thread list for this
	// process shows that all threads are suspended
	//
	bool finished = false;
	while (!finished) {

		// assume we're going to succeed on this iteration until
		// proven otherwise
		//
		finished = true;

		// get the list of threads for this process
		//
		ExtArray<DWORD> tid_array;
		int num_tids = sys_info.GetTIDs(pid, tid_array);
		if (num_tids == 0) {
			// TODO: we need to handle this case!!!
			//
			EXCEPT("windows_suspend_process failed: can't get threads for pid %u",
			       pid);
		}

		// go through the thread list, calling SuspendThread on each
		//
		for (int i = 0; i < num_tids; i++) {

			// see if we already have a record for this thread
			//
			SuspendedThread* st;
			ret = sp->lookup(tid_array[i], st);
			if (ret == -1) {

				// no record yet; open up this thread's handle
				//
				HANDLE handle = OpenThread(THREAD_SUSPEND_RESUME, FALSE, tid_array[i]);
				if (handle == NULL) {

					// the thread probably exited; however, it may have called ResumeThread
					// or CreateThread first, so we'll have to loop again
					//
					finished = false;
					dprintf(D_FULLDEBUG,
					        "windows_suspend_process: OpenThread error: %u\n",
					        GetLastError());
					continue;
				}

				// now that we have a handle, create a record for this thread
				//
				st = new SuspendedThread;
				ASSERT(st != NULL);
				st->handle = handle;
				st->num_suspends = 0;
				ret = sp->insert(tid_array[i], st);
				ASSERT(ret != -1);
			}

			// now suspend the thread
			//
			DWORD result = SuspendThread(st->handle);
			if (result == (DWORD)-1) {

				// how can this happen? maybe the thread exited?
				//
				finished = false;
				dprintf(D_FULLDEBUG,
						"windows_suspend_process: SuspendThread error: %u\n",
						GetLastError());
				continue;
			}

			// if the thread was not suspended prior to our SuspendThread call,
			// it may have called CreateThread or ResumeThread so we need to loop
			// at least one more time
			//
			if (result == 0) {
				finished = false;
			}

			// keep track of how many suspends we've sent this thread
			//
			st->num_suspends++;
		}
	}

	return true;
}
コード例 #29
0
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);
}
コード例 #30
0
DWORD demoSuspendInjectResume64(PCWSTR pszLibFile, DWORD dwProcessId)
{
	void *stub;
	unsigned long threadID, oldprot;
	HANDLE hThread;
	CONTEXT ctx;

	DWORD64 stubLen = sizeof(sc);
	wprintf(TEXT("[+] Shellcode Length is: %d\n"), stubLen);

	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);
	}

	DWORD64 LoadLibraryAddress = (DWORD64)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, 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);
	}

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

	threadID = getThreadID(dwProcessId);
	hThread = OpenThread((THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_SUSPEND_RESUME), false, threadID);
	if (hThread != NULL)
	{
		SuspendThread(hThread);
	}
	else
		wprintf(L"[-] Could not open thread\n");

	ctx.ContextFlags = CONTEXT_CONTROL;
	GetThreadContext(hThread, &ctx);

	DWORD64 oldIP = ctx.Rip;
	ctx.Rip = (DWORD64)stub;
	ctx.ContextFlags = CONTEXT_CONTROL;

	memcpy(sc + 3, &oldIP, sizeof(oldIP));
	memcpy(sc + 41, &lpDllAddr, sizeof(lpDllAddr));
	memcpy(sc + 51, &LoadLibraryAddress, sizeof(LoadLibraryAddress));

#ifdef _DEBUG
	wprintf(TEXT("[+] Shellcode Launcher Code:\n\t"));
	for (int i = 0; i < stubLen; i++)
		wprintf(TEXT("%02x "), sc[i]);
	wprintf(TEXT("\n"));
#endif

	WriteProcessMemory(hProcess, (void *)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);
}