Example #1
0
DWORD WINAPI SearchWorkThreadMgrProc(LPVOID lpParm)
{
	CQuickSearchDlg * lpDlg = (CQuickSearchDlg *)lpParm;
	if (lpDlg == NULL)
	{
		lpDlg->NotifyStatusMsg(_T("线程的非法引用!请退出程序,然后重试。"));
		return ERROR_INVALID_PARAMETER;
	}
	if (!EnablePrivilege(SE_DEBUG_NAME, TRUE))
	{
		lpDlg->NotifyStatusMsg(_T("提权失败!"));
		return ERROR_ACCESS_DENIED;
	}
	for (int i = 0; lpDlg->GetSafeHwnd() == NULL && i < 10; i++)
		Sleep(100);

	lpDlg->NotifyStatusMsg(_T("就绪..."));
	while (TRUE)
	{
		TCHAR szMsg[nMSG_SIZE] = { 0 };
		ULONG nFoundedCont = 0;

		WaitForSingleObject(g_hSearchEvent, INFINITE);
		if (WaitForSingleObject(g_hQuitEvent, 50) == WAIT_OBJECT_0)
		{
			// 执行搜索之前检测有无退出信号
			break;
		}

		lpDlg->InitList();
		SEARCH_PROGRRESS_INFO spi[26] = { 0 };
		for (short i = 0; i < 26; i++)
		{
			spi[i].m_nFoundCount = 0;
			spi[i].m_nViewCount = 0;
			spi[i].m_lpDlg = lpDlg;
			spi[i].m_Update = update;
			ParseSearchObject(lpDlg->GetSearchString().GetBuffer(), spi[i].m_vecSearchStrings);
			lpDlg->GetSearchString().ReleaseBuffer();
		}

		g_nTotalFound = 0;			// 已经找到的数量
		g_nTotalView = 0;			// 已经查找了的数量
		CString strSearchStartPath(lpDlg->GetSearchLocation());
		short nSearchThreadIndex = 0;
		HANDLE hSearchThread[26] = { 0 };
		DWORD dwSeachThreadId[26] = { 0 };
		if (strSearchStartPath == _T("0"))
		{
			TCHAR szAllDriverLetters[100] = { 0 };
			DWORD len = GetLogicalDriveStrings(sizeof(szAllDriverLetters) / sizeof(TCHAR), szAllDriverLetters);
			for (TCHAR * lpszCurrentDriverLetter = szAllDriverLetters; *lpszCurrentDriverLetter; lpszCurrentDriverLetter += _tcslen(lpszCurrentDriverLetter) + 1)
			{
				// 创建搜索线程
				Sleep(nSearchThreadIndex * 1000);
				StringCchPrintf(spi[nSearchThreadIndex].m_szStartLocation, MAX_PATH - 1, _T("%C:"), lpszCurrentDriverLetter[0]);
				spi[nSearchThreadIndex].m_bFastMode = lpDlg->GetFastMode();
				hSearchThread[nSearchThreadIndex] = CreateThread(
					NULL,         // 使用默认的安全描述符
					0,            // 使用默认的栈大小
					(LPTHREAD_START_ROUTINE)SearchThreadProc,
					(LPVOID)(spi + nSearchThreadIndex),
					CREATE_SUSPENDED,						// 先挂起
					dwSeachThreadId + nSearchThreadIndex);	// 取得线程ID
				if (hSearchThread[nSearchThreadIndex])
				{
					if (spi[nSearchThreadIndex].m_bFastMode)
						if (!SetThreadPriority(hSearchThread[nSearchThreadIndex], THREAD_PRIORITY_TIME_CRITICAL))
							if (!SetThreadPriority(hSearchThread[nSearchThreadIndex], THREAD_PRIORITY_HIGHEST))
								if (!SetThreadPriority(hSearchThread[nSearchThreadIndex], THREAD_PRIORITY_ABOVE_NORMAL))
									if (!SetThreadPriority(hSearchThread[nSearchThreadIndex], THREAD_PRIORITY_HIGHEST))
										SetThreadPriority(hSearchThread[nSearchThreadIndex], THREAD_PRIORITY_NORMAL);
					ResumeThread(hSearchThread[nSearchThreadIndex]);
					SetThreadPriorityBoost(hSearchThread[nSearchThreadIndex], !spi[nSearchThreadIndex].m_bFastMode);	// 系统动态调整线程优先级选项
					nSearchThreadIndex++;
				}
			}
			WaitForMultipleObjects(nSearchThreadIndex, hSearchThread, TRUE, INFINITE);
			for (short i = 0; i < nSearchThreadIndex; i++)
			{
				if (hSearchThread[i])
					CloseHandle(hSearchThread[i]);
			}
		}
		else
		{
			// 创建搜索线程
			DWORD ThreadID = 0;
			StringCchPrintf(spi[0].m_szStartLocation, MAX_PATH - 1, _T("%s"), strSearchStartPath);
			spi[0].m_bFastMode = lpDlg->GetFastMode();
			hSearchThread[0] = CreateThread(
				NULL,         // 使用默认的安全描述符
				0,            // 使用默认的栈大小
				(LPTHREAD_START_ROUTINE)SearchThreadProc,
				(LPVOID)&spi[0],
				CREATE_SUSPENDED,						// 先挂起
				&ThreadID);	// 取得线程ID
			if (hSearchThread)
			{
				if (spi[0].m_bFastMode)
					if (!SetThreadPriority(hSearchThread[nSearchThreadIndex], THREAD_PRIORITY_TIME_CRITICAL))
						if (!SetThreadPriority(hSearchThread[nSearchThreadIndex], THREAD_PRIORITY_HIGHEST))
							if (!SetThreadPriority(hSearchThread[nSearchThreadIndex], THREAD_PRIORITY_ABOVE_NORMAL))
								if (!SetThreadPriority(hSearchThread[nSearchThreadIndex], THREAD_PRIORITY_HIGHEST))
									SetThreadPriority(hSearchThread[nSearchThreadIndex], THREAD_PRIORITY_NORMAL);
				ResumeThread(hSearchThread[nSearchThreadIndex]);
				SetThreadPriorityBoost(hSearchThread[nSearchThreadIndex], !spi[nSearchThreadIndex].m_bFastMode);	// 系统动态调整线程优先级选项

				WaitForSingleObject(hSearchThread[nSearchThreadIndex], INFINITE);
				CloseHandle(hSearchThread[nSearchThreadIndex]);
				nSearchThreadIndex++;
			}
		}
		if (g_vecCurrentFindData.size())
		{
			lpDlg->InitList();
			lpDlg->NotifyStatusMsg(_T("正在更新搜索结果列表,请稍候..."));
			lpDlg->UpdateList(g_vecCurrentFindData);
			ULONG nViewCount = 0, nFoundCount = 0;
			for (short i = 0; i < nSearchThreadIndex; i++)
			{
				nViewCount += spi[i].m_nViewCount;
				nFoundCount += spi[i].m_nFoundCount;
			}
			StringCchPrintf(szMsg, nMSG_SIZE - 1, _T("搜索完成,在%d个项目中共找到了%d个对象。"), nViewCount, nFoundCount);
			lpDlg->NotifyStatusMsg(szMsg);
		}
		else
		{
			lpDlg->NotifyStatusMsg(_T("未找到!"));
		}

		// 搜索完了,重置状态
		g_vecCurrentFindData.clear();
		std::vector<FIND_DATA> vecCurrentFindDataTemp;
		g_vecCurrentFindData.swap(vecCurrentFindDataTemp);
		g_hBrokenEvent ? ResetEvent(g_hBrokenEvent) : 0;
		g_hSearchEvent ? ResetEvent(g_hSearchEvent) : 0;

		if (WaitForSingleObject(g_hQuitEvent, 50) == WAIT_OBJECT_0)
		{
			// 搜索任务完成之后检测有无退出信号
			OutputDebugString(_T("Quiting..."));
			break;
		}
	}

	return 0;
}
/*
Name: ListenForClientConnection
Description: This function will have an infinite loop where it will wait forever for client connections. Once client connection is established.
			 It will process it in a fast way or religate the work to a thread and keeps waiting for new connections.
Parameters: - 
ReturnValue: 0 for success else error codes.
*/
int ListenForClientConnection()
{
	int nReturnValue = 0;
	struct addrinfo *structClientAddrInfo = NULL;
	SOCKET scClientSocket = INVALID_SOCKET;
	HANDLE hClientThread = NULL;
	DWORD dwClientThreadId = 0;
	char szMessage[1024] = { '\0' };

	LogMessage(LOG_DEBUG, "Started to listen for client connection");

	if (INVALID_SOCKET == scListenSocket)
	{
		LogMessage(LOG_ERROR, "Invalid listen socket");
		nReturnValue = ERR_INVALIDLISTENSOCKET;
		return nReturnValue;
	}

	LogMessage(LOG_INFO, "listening.........");
	nReturnValue = listen(scListenSocket, SOMAXCONN);
	if (nReturnValue == SOCKET_ERROR)
	{
		//printf_s("BHS:ERROR:listen failed with error %d\n", WSAGetLastError());
		sprintf_s(szMessage, 1024, "listen failed with error %d\n", WSAGetLastError());
		LogMessage(LOG_ERROR, szMessage);
		closesocket(scListenSocket);
		scListenSocket = INVALID_SOCKET;
		WSACleanup();
		nReturnValue = ERR_LISTENFAILURE;
		return nReturnValue;
	}

	LogMessage(LOG_INFO, "Initializing synchronization elements");

	InitializeCriticalSection(&mcriticalThreadSync);
	InitializeConditionVariable(&mcvThreadCount);

	LogMessage(LOG_INFO, "Going for infinite loop of accepts");
	while ((scClientSocket = accept(scListenSocket, NULL, NULL)) != INVALID_SOCKET)
	{

		//printf_s("BHS:INFO:Client connection established: \n");
		LogMessage(LOG_INFO, "Client connection established, Creating a thread to handle the connection");
		//printf_s("BHS:INFO:Creating a thread to handle the connection\n");
		
		hClientThread = CreateThread(NULL, 0, HandleClientRequestThread, scClientSocket, 0x00000004, &dwClientThreadId);

		EnterCriticalSection(&mcriticalThreadSync);


		if (nThread_Count >= nThreadPoolSize)
		{
			LogMessage(LOG_DEBUG, "Active thread count is more than thread pool size");
			SleepConditionVariableCS(&mcvThreadCount, &mcriticalThreadSync, INFINITE);
			LogMessage(LOG_DEBUG, "Got up from sleep(wait), now waking the creating thread to handle client request");
			
		}

		nThread_Count++;
		ResumeThread(hClientThread);

		LeaveCriticalSection(&mcriticalThreadSync);

		LogMessage(LOG_INFO, "Returning to wait for new client connections......");
		//printf_s("BHS:INFO:Returning to wait for new connections......\n");
	}

	if (scClientSocket == INVALID_SOCKET)
	{
		//printf_s("BHS:ERROR:Invalid client socket %d\n", WSAGetLastError());
		sprintf_s(szMessage, 1024, "Invalid client socket %d\n", WSAGetLastError());
		LogMessage(LOG_ERROR, szMessage);
		nReturnValue = ERR_INVALIDCLIENTSOCKET;
	}
	else
	{
		LogMessage(LOG_INFO, "Closing the client socket");
		closesocket(scClientSocket);
		scClientSocket = INVALID_SOCKET;
	}
	
	LogMessage(LOG_INFO, "Closing the listen socket");
	closesocket(scListenSocket);
	scListenSocket = INVALID_SOCKET;
	WSACleanup();

	DeleteCriticalSection(&mcriticalThreadSync);
	
	LogMessage(LOG_DEBUG, "Finished listening for client connection");
	return nReturnValue;
}
Example #3
0
int fork(void) {

	int rc;
	size_t stacksize;
	char modname[512];
	HANDLE  hProc,hThread, hArray[2];
	STARTUPINFO si;
	PROCESS_INFORMATION pi;
	SECURITY_ATTRIBUTES sa;
	DWORD dwCreationflags;
	unsigned int priority;
	HANDLE h64Parent,h64Child;

#ifndef _M_ALPHA
	unsigned long fork_stack_end;
#endif _M_ALPHA

	__fork_stack_begin =GETSTACKBASE();

#ifndef _M_ALPHA
	__fork_stack_end = &fork_stack_end;
#else
	__fork_stack_end = (unsigned long *)__asm("mov $sp, $0");
#endif /*_M_ALPHA*/

	h64Parent = h64Child = NULL;
	//
	// Create two inheritable events
	//
	sa.nLength = sizeof(sa);
	sa.lpSecurityDescriptor =0;
	sa.bInheritHandle = TRUE;
	if (!__hforkchild)
		__hforkchild = CreateEvent(&sa,TRUE,FALSE,NULL);
	if (!__hforkparent)
		__hforkparent = CreateEvent(&sa,TRUE,FALSE,NULL);

	rc = setjmp(__fork_context);

	if (rc) { // child
#ifdef  _M_IX86
		//
		// Restore old registration
		// -amol 2/2/97
		GETEXCEPTIONREGIST() = (struct _EXCEPTION_REGISTRATION_RECORD*)_old_exr;
#endif // _M_IX86
		SetEvent(__hforkchild);

		dprintf("Child ready to rumble\n");
		if(WaitForSingleObject(__hforkparent,FORK_TIMEOUT) != WAIT_OBJECT_0)
			ExitProcess(0xFFFF);

		CloseHandle(__hforkchild);
		CloseHandle(__hforkparent);
		__hforkchild = __hforkparent=0;

		//__asm { int 3};
		restore_fds();

		STR_environ = blk2short(environ);
		environ = short2blk(STR_environ);	/* So that we can free it */

		return 0;
	}
	copy_fds();
	memset(&si,0,sizeof(si));
	si.cb= sizeof(si);

	/*
	 * This f!@#!@% function returns the old value even if the std handles
	 * have been closed.
	 * Skip this step, since we know tcsh will do the right thing later.
	 * 
	si.hStdInput= GetStdHandle(STD_INPUT_HANDLE);
	si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
	si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
	*/

	if (!GetModuleFileName(GetModuleHandle(NULL),modname,512) ) {
		rc = GetLastError();
		return -1;
	}
	dwCreationflags = GetPriorityClass(GetCurrentProcess());
	priority = GetThreadPriority(GetCurrentThread());
	rc = CreateProcess(NULL,
						modname,
						NULL,
						NULL,
						TRUE,
						CREATE_SUSPENDED | dwCreationflags,
						NULL,
						NULL,
						&si,
						&pi);
	if (!rc)  {
		rc = GetLastError();
		return -1;
	}
	
	ResetEvent(__hforkchild);
	ResetEvent(__hforkparent);

	hProc = pi.hProcess;
	hThread = pi.hThread;


	__forked=1;
	/*
	 * Usage of events in the wow64 case:
	 *
	 * h64Parent : initially non-signalled
	 * h64Child  : initially non-signalled
	 *
	 *    1. Create the events, resume the child thread.
	 *    2. Child opens h64Parent to see if it is a child process in wow64
	 *    3. Child opens and sets h64Child to tell parent it's running. (This
	 *       step is needed because we can't copy to a process created in the
	 *       suspended state on wow64.)
	 *    4. Copy gForkData and then set h64Parent. This tells the child
	 *       that the parameters in the structure are trustworthy.
	 *    5. Wait for h64Child so that we know the child has created the stack
	 *       in dynamic memory.
	 *
	 *   The rest of the fork hack should now proceed as in x86
	 *
	 */
	if (bIsWow64Process) {

		// allocate the heap for the child. this can be done even when
		// the child is suspended. 
		// avoids inexplicable allocation failures in the child.
		if (VirtualAllocEx(hProc,
							__heap_base,
							__heap_size,
							MEM_RESERVE,
							PAGE_READWRITE) == NULL) {
			dprintf("virtual allocex failed %d\n",GetLastError());
			goto error;
		}
		if (VirtualAllocEx(hProc,
							__heap_base,
							__heap_size,
							MEM_COMMIT,
							PAGE_READWRITE) == NULL) {
			dprintf("virtual allocex2 failed %d\n",GetLastError());
			goto error;
		}

		// Do NOT expect existing events
		if (!CreateWow64Events(pi.dwProcessId,&h64Parent,&h64Child,FALSE)) {
			goto error;
		}
		ResumeThread(hThread);

		// wait for the child to tell us it is running
		//if (WaitForSingleObject(h64Child,FORK_TIMEOUT) != WAIT_OBJECT_0) {
		//	rc = GetLastError();
		//	goto error;
		//}
		hArray[0] = h64Child;
		hArray[1] = hProc;

		if (WaitForMultipleObjects(2,hArray,FALSE,FORK_TIMEOUT) != 
						WAIT_OBJECT_0){

			rc = GetLastError();
			goto error;
		}

	}
	//
	// Copy all the shared data
	//
	if (!WriteProcessMemory(hProc,&gForkData,&gForkData,
			sizeof(ForkData),&rc)) {
		goto error;
	}
	if (rc != sizeof(ForkData)) 
		goto error;

	if (!bIsWow64Process) {
		rc = ResumeThread(hThread);
	}
	// in the wow64 case, the child will be waiting  on h64parent again.
	// set it, and then wait for h64child. This will mean the child has
	// a stack set up at the right location.
	else {
		SetEvent(h64Parent);
		hArray[0] = h64Child;
		hArray[1] = hProc;

		if (WaitForMultipleObjects(2,hArray,FALSE,FORK_TIMEOUT) != 
						WAIT_OBJECT_0){

			rc = GetLastError();
			goto error;
		}
		CloseHandle(h64Parent);
		CloseHandle(h64Child);
		h64Parent = h64Child = NULL;
	}
	
	//
	// Wait for the child to start and init itself.
	// The timeout is so that we don't wait too long
	//
	hArray[0] = __hforkchild;
	hArray[1] = hProc;

	if (WaitForMultipleObjects(2,hArray,FALSE,FORK_TIMEOUT) != WAIT_OBJECT_0){

		int err = GetLastError(); // For debugging purposes
		dprintf("wait failed err %d\n",err);
		goto error;
	}

	// Stop the child again and copy the stack and heap
	//
	SuspendThread(hThread);

	if (!SetThreadPriority(hThread,priority) ) {
		priority =GetLastError();
	}

	// stack
	stacksize = (char*)__fork_stack_begin - (char*)__fork_stack_end;
	if (!WriteProcessMemory(hProc,(char *)__fork_stack_end,
								  (char *)__fork_stack_end,
								  (u_long)stacksize,
								  &rc)){
		goto error;
	}
	//
	// copy heap itself
	if (!WriteProcessMemory(hProc, (void*)__heap_base,(void*)__heap_base, 
						(DWORD)((char*)__heap_top-(char*)__heap_base),
						&rc)){
		goto error;
	}

	rc = fork_copy_user_mem(hProc);

	if(rc) {
		goto error;
	}

	// Release the child.
	SetEvent(__hforkparent);
	rc = ResumeThread(hThread);

	__forked=0;
    dprintf("forked process %d\n",pi.dwProcessId);
	start_sigchild_thread(hProc,pi.dwProcessId);
	close_copied_fds();

	CloseHandle(hThread);
	//
	// return process id to parent.
	return pi.dwProcessId;

error:
	__forked=0;
	SetEvent(__hforkparent);
	ResumeThread(hThread);
	CloseHandle(hProc);
	CloseHandle(hThread);
	if (h64Parent) {
		SetEvent(h64Parent); // don't let child block forever
		CloseHandle(h64Parent);
	}
	if (h64Child)
		CloseHandle(h64Child);
	return -1;
}
Example #4
0
JECT_EXTERN
unsigned WINAPI InjectDll(void *mpara)
{
    BOOL			bRet		= FALSE;
    LPVOID			funcBuff	= NULL;
    HANDLE			hRemote		= NULL;
    LPVOID			pBuff		= NULL;
    SIZE_T			cbSize		= sizeof(RemotePara);
    SIZE_T			cbCodeSize	= (LPBYTE)AfterThreadProc - (LPBYTE)ThreadProc;
    HMODULE			hNtdll;
    WCHAR			dll_name[VALUE_LEN+1];
    RemotePara		myPara;
    DWORD           os	   = GetOsVersion();
    PROCESS_INFORMATION pi = *(LPPROCESS_INFORMATION)mpara;

    if ( GetModuleFileNameW(dll_module,dll_name,VALUE_LEN) <=0 )
    {
        return bRet;
    }
    /* when tcmalloc enabled or MinGW x64 compile time,InjectDll crash on win8/8.1 */
#if !defined(ENABLE_TCMALLOC) && !defined(__MINGW64__)
    if ( os > 601 )
    {
#ifdef _LOGDEBUG
        logmsg("pic inject runing\n");
#endif
        return pic_inject(mpara,dll_name);
    }
#endif
    hNtdll = GetModuleHandleW(L"ntdll.dll");
    if (!hNtdll)
    {
        return bRet;
    }
    fzero(&myPara, sizeof(myPara));
    myPara.dwLoadLibraryAddr = (DWORD_PTR)GetProcAddress(hNtdll, "LdrLoadDll");
    myPara.dwRtlInitUnicodeString = (DWORD_PTR)GetProcAddress(hNtdll, "RtlInitUnicodeString");
    if ( (myPara.dwLoadLibraryAddr)&&(myPara.dwRtlInitUnicodeString) )
    {
        DWORD dwThreadId  = 0;
        wcsncpy(myPara.strDll,dll_name,VALUE_LEN);
        /* 在进程内分配空间 */
        pBuff = VirtualAllocEx(pi.hProcess, 0, cbSize+cbCodeSize, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
        funcBuff = ((BYTE *)pBuff+cbSize);
        /* 写入参数空间 */
        WriteProcessMemory(pi.hProcess, pBuff, (PVOID)&myPara, cbSize, NULL);
        /* 写入代码空间 */
        WriteProcessMemory(pi.hProcess, funcBuff, (PVOID)ThreadProc, cbCodeSize, NULL);
        hRemote = CreateRemoteThread(pi.hProcess,
                                     NULL,
                                     1024*1024,
                                     (LPTHREAD_START_ROUTINE)funcBuff,
                                     pBuff,
                                     CREATE_SUSPENDED,
                                     &dwThreadId);
        if (hRemote)
        {
            ResumeThread(hRemote);
            WaitForSingleObject(hRemote,1500);
            CloseHandle(hRemote);
        }
        if (pBuff)
        {
            VirtualFreeEx(pi.hProcess, pBuff, 0, MEM_RELEASE);
        }
        if (funcBuff)
        {
            VirtualFreeEx(pi.hProcess, funcBuff, 0, MEM_RELEASE);
        }
    }
    ResumeThread(pi.hThread);
    return bRet;
}
Example #5
0
int
pthread_create (pthread_t * tid,
                const pthread_attr_t * attr,
                void *(PTW32_CDECL *start) (void *), void *arg)
/*
 * ------------------------------------------------------
 * DOCPUBLIC
 *      This function creates a thread running the start function,
 *      passing it the parameter value, 'arg'. The 'attr'
 *      argument specifies optional creation attributes.
 *      The identity of the new thread is returned
 *      via 'tid', which should not be NULL.
 *
 * PARAMETERS
 *      tid
 *              pointer to an instance of pthread_t
 *
 *      attr
 *              optional pointer to an instance of pthread_attr_t
 *
 *      start
 *              pointer to the starting routine for the new thread
 *
 *      arg
 *              optional parameter passed to 'start'
 *
 *
 * DESCRIPTION
 *      This function creates a thread running the start function,
 *      passing it the parameter value, 'arg'. The 'attr'
 *      argument specifies optional creation attributes.
 *      The identity of the new thread is returned
 *      via 'tid', which should not be the NULL pointer.
 *
 * RESULTS
 *              0               successfully created thread,
 *              EINVAL          attr invalid,
 *              EAGAIN          insufficient resources.
 *
 * ------------------------------------------------------
 */
{
    pthread_t thread = { 0 };		// init to shut up MSVC2013: warning C4701 : potentially uninitialized local variable 'thread' used
    ptw32_thread_t * tp;
    ptw32_thread_t * sp;
    register pthread_attr_t a;
    HANDLE threadH = 0;
    int result = EAGAIN;
    int run = PTW32_TRUE;
    ThreadParms *parms = NULL;
    unsigned int stackSize;
    int priority;

    /*
     * Before doing anything, check that tid can be stored through
     * without invoking a memory protection error (segfault).
     * Make sure that the assignment below can't be optimised out by the compiler.
     * This is assured by conditionally assigning *tid again at the end.
     */
    tid->x = 0;

    if (NULL == (sp = (ptw32_thread_t *)pthread_self().p))
    {
        goto FAIL0;
    }

    if (attr != NULL)
    {
        a = *attr;
    }
    else
    {
        a = NULL;
    }

    thread = ptw32_new();
    if (thread.p == NULL)
    {
        goto FAIL0;
    }

    tp = (ptw32_thread_t *) thread.p;

    priority = tp->sched_priority;

    if ((parms = (ThreadParms *) malloc (sizeof (*parms))) == NULL)
    {
        goto FAIL0;
    }

    parms->tid = thread;
    parms->start = start;
    parms->arg = arg;

    /*
     * Threads inherit their initial sigmask and CPU affinity from their creator thread.
     */
#if defined(HAVE_SIGSET_T)
    tp->sigmask = sp->sigmask;
#endif
#if defined(HAVE_CPU_AFFINITY)
    tp->cpuset = sp->cpuset;
#endif

    if (a != NULL)
    {
#if defined(HAVE_CPU_AFFINITY)
        cpu_set_t none;
        cpu_set_t attr_cpuset;
        ((_sched_cpu_set_vector_*)&attr_cpuset)->_cpuset = a->cpuset;

        CPU_ZERO(&none);
        if (! CPU_EQUAL(&attr_cpuset, &none))
        {
            tp->cpuset = a->cpuset;
        }
#endif
        stackSize = (unsigned int)a->stacksize;
        tp->detachState = a->detachstate;
        priority = a->param.sched_priority;
        if (a->thrname != NULL)
            tp->name = _strdup(a->thrname);

#if (THREAD_PRIORITY_LOWEST > THREAD_PRIORITY_NORMAL)
        /* WinCE */
#else
        /* Everything else */

        /*
         * Thread priority must be set to a valid system level
         * without altering the value set by pthread_attr_setschedparam().
         */

        /*
         * PTHREAD_EXPLICIT_SCHED is the default because Win32 threads
         * don't inherit their creator's priority. They are started with
         * THREAD_PRIORITY_NORMAL (win32 value). The result of not supplying
         * an 'attr' arg to pthread_create() is equivalent to defaulting to
         * PTHREAD_EXPLICIT_SCHED and priority THREAD_PRIORITY_NORMAL.
         */
        if (PTHREAD_INHERIT_SCHED == a->inheritsched)
        {
            /*
             * If the thread that called pthread_create() is a Win32 thread
             * then the inherited priority could be the result of a temporary
             * system adjustment. This is not the case for POSIX threads.
             */
            priority = sp->sched_priority;
        }

#endif

    }
    else
    {
        /*
         * Default stackSize
         */
        stackSize = PTHREAD_STACK_MIN;
    }

    tp->state = run ? PThreadStateInitial : PThreadStateSuspended;

    tp->keys = NULL;

    /*
     * Threads must be started in suspended mode and resumed if necessary
     * after _beginthreadex returns us the handle. Otherwise we set up a
     * race condition between the creating and the created threads.
     * Note that we also retain a local copy of the handle for use
     * by us in case thread.p->threadH gets NULLed later but before we've
     * finished with it here.
     */

#if ! defined (PTW32_CONFIG_MINGW) || defined (__MSVCRT__) || defined (__DMC__)

    tp->threadH =
        threadH =
            (HANDLE) _beginthreadex ((void *) NULL,	/* No security info             */
                                     stackSize,		/* default stack size   */
                                     ptw32_threadStart,
                                     parms,
                                     (unsigned)
                                     CREATE_SUSPENDED,
                                     (unsigned *) &(tp->thread));

    if (threadH != 0)
    {
        if (a != NULL)
        {
            (void) ptw32_setthreadpriority (thread, SCHED_OTHER, priority);
        }

#if defined(HAVE_CPU_AFFINITY)

        SetThreadAffinityMask(tp->threadH, tp->cpuset);

#endif

        if (run)
        {
            ResumeThread (threadH);
        }
    }

#else

    {
        ptw32_mcs_local_node_t stateLock;

        /*
         * This lock will force pthread_threadStart() to wait until we have
         * the thread handle and have set the priority.
         */
        ptw32_mcs_lock_acquire(&tp->stateLock, &stateLock);

        tp->threadH =
            threadH =
                (HANDLE) _beginthread (ptw32_threadStart, stackSize,	/* default stack size   */
                                       parms);

        /*
         * Make the return code match _beginthreadex's.
         */
        if (threadH == (HANDLE) - 1L)
        {
            tp->threadH = threadH = 0;
        }
        else
        {
            if (!run)
            {
                /*
                 * beginthread does not allow for create flags, so we do it now.
                 * Note that beginthread itself creates the thread in SUSPENDED
                 * mode, and then calls ResumeThread to start it.
                 */
                SuspendThread (threadH);
            }

            if (a != NULL)
            {
                (void) ptw32_setthreadpriority (thread, SCHED_OTHER, priority);
            }

#if defined(HAVE_CPU_AFFINITY)

            SetThreadAffinityMask(tp->threadH, tp->cpuset);

#endif

        }

        ptw32_mcs_lock_release (&stateLock);
    }
#endif

    result = (threadH != 0) ? 0 : EAGAIN;

    /*
     * Fall Through Intentionally
     */

    /*
     * ------------
     * Failure Code
     * ------------
     */

FAIL0:
    if (result != 0)
    {
        ptw32_threadDestroy (thread);
        tp = NULL;

        if (parms != NULL)
        {
            free (parms);
        }
    }
    else
    {
        *tid = thread;
    }

#if defined(_UWIN)
    if (result == 0)
        pthread_count++;
#endif
    return (result);
}				/* pthread_create */
Example #6
0
/**
 * main
 *
 * executable entry point
 */
INT __cdecl main( INT argc, CHAR **argv )
{
    DWORD IDThread;

    int i;

    /* PAL initialization */
    if( (PAL_Initialize(argc, argv)) != 0 )
    {
        return( FAIL );
    }

    /* set the thread priority of the main to the highest possible value
       this will give the chance to the main thread to create all the
       other threads */
    if(!SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL))
    {
        DWORD dwError;

        dwError = GetLastError();
        Fail( "Unexpected SetThreadPriority() failure with error %d\n",
			  dwError );
    }

    printf( "Launching multiple threads, please wait...\n" );

    /* Create multiple threads. */
    for( i = 0; i < NUM_THREADS; i++ )
    {
        hThread[i] = CreateThread( NULL,         /* no security attributes */
                                   0,            /* use default stack size */
          (LPTHREAD_START_ROUTINE) ThreadFunc,   /* thread function */
                          (LPVOID) i,            /* pass thread index as */
                                                 /* function argument */
                                   CREATE_SUSPENDED, /* create suspended */
                                   &IDThread );  /* returns thread identifier */

        /* Check the return value for success. */
        if( hThread[i] == NULL )
        {
	        /*ERROR */
            DWORD dwError = GetLastError();
            Fail( "Unexpected CreateThread error %d\n",
                  dwError );
        }

        ResumeThread(hThread[i]);
    }

    /* Wait for all threads to finish */
    for (i = 0; i < NUM_THREADS; i++)
    {
        DWORD dwRet;

        dwRet = WaitForSingleObject( hThread[i], INFINITE );

        if( dwRet == WAIT_FAILED )
        {
            /* ERROR */
            DWORD dwError = GetLastError();
            Fail( "Unexpected WaitForSingleObject error %d\n",
                  dwError );
        }
    }

    /* make sure the thread processing times match the priorities */
    for( i=NUM_THREADS-1; i > 0; i-- )
    {
        if( nElapsedTime[i] >= nElapsedTime[i-1] )
        {
            /*
             * a lower-priority thread finished faster than a lower-priority
             * thread -- this shouldn't happen if the dummy thread function
             * is non-trivial in length
             */
            Fail( "Failed: processing time doesn't match thread priority\n" );
        }
    }

    PAL_Terminate();
    return PASS;
}
Example #7
0
unsigned int __stdcall SpkrThread(LPVOID Unused)
{
    int      i;
    DWORD    bufLen = ((N_SAMPLES * BITS_PER_SAMPLE) / 8);
    WAVEHDR* pWH;
    MMRESULT ret;
    int      played;
    MSG      tMsg;
    BOOL     bGotMsg ;
    int      n;
    bool     bDone ;
    static bool sLastRingerEnabled = false;
    OsStatus res;
    static bool bRunning = false ;
    HWAVEOUT hOut = NULL;

    // Verify that only 1 instance of the MicThread is running
    if (bRunning) 
    {
       ResumeThread(hMicThread);
       return 1 ;
    }
    else
    {
       bRunning = true ;
    }
    ResumeThread(hMicThread);


#ifdef OHISTORY /* [ */
    WAVEHDR* lastWH[OHISTORY];
    int      lastInd[OHISTORY];
    int      last = 0;

    for (i=0;i<OHISTORY;i++) 
    {
        lastWH[i] = 0;
        lastInd[i] = 0;
    }

    memset(histOut, 0xff, sizeof(histOut));
    lastOut = 0;
#endif /* OHISTORY ] */
    
    // Initialize headers
    for (i=0; i<N_OUT_BUFFERS; i++) 
    {
        hOutHdr[i] = hOutBuf[i] = NULL;
        pOutHdr[i] = NULL;
    }
    
    if (openSpeakerDevices(pWH, hOut))
    {
        // NOT using a sound card
        // Set up a 10ms timer to call back to this routine
        timeSetEvent(10, 0, TimerCallbackProc, GetCurrentThreadId(), TIME_PERIODIC);
    }

    played = 0;   
    bDone = false ;
    while (!bDone)
    {
        bGotMsg = GetMessage(&tMsg, NULL, 0, 0);
              
        // when switching devices, ringer to in-call we need to make 
        // sure any outstanding buffers are flushed
        if (sLastRingerEnabled != DmaTask::isRingerEnabled())
        {
            if (audioOutH)
            {
                waveOutReset(audioOutH);
            }
            if (audioOutCallH)
            {
                waveOutReset(audioOutCallH);
            }
        }

        if (bGotMsg) 
        {
            switch (tMsg.message) 
            {
            case WM_ALT_HEARTBEAT:
                res = MpMediaTask::signalFrameStart();
                switch (res) 
                {
                    case OS_SUCCESS:
                        frameCount++;
                        break;
                    case OS_LIMIT_REACHED:
                    case OS_WAIT_TIMEOUT:
                    case OS_ALREADY_SIGNALED:
                    default:
                        // Should bump missed frame statistic
                        break;
                }
                break ;
            case WOM_DONE:
                pWH = (WAVEHDR *) tMsg.wParam;
                n = (pWH->dwUser) & USER_BUFFER_MASK;
#ifdef OHISTORY /* [ */
                lastWH[last] = pWH;
                lastInd[last] = n;
                last = (last + 1) % OHISTORY;

                if (N_OUT_BUFFERS == played) {
                    osPrintf("after first %d buffers:", played + 1);
                    osPrintf("\nCall Backs:");
                    for (i=0; i<OHISTORY; i++) {
                        osPrintf("%c%3d", (0 == (i % 20)) ? '\n' : ' ',
                        histOut[i]);
                    }
                    osPrintf("\n\nMessages:");
                    for (i=0; i<OHISTORY; i++) {
                        osPrintf("%c%3d", (0 == (i % 20)) ? '\n' : ' ',
                        lastInd[i]);
                    }
                    osPrintf("\n");
                }
#endif /* OHISTORY ] */
                
                if (DmaTask::isOutputDeviceChanged())
                {                    
                    DmaTask::clearOutputDeviceChanged() ;
                    closeSpeakerDevices() ;
                    if (openSpeakerDevices(pWH, hOut))
                    {
                        timeSetEvent(10, 0, TimerCallbackProc, GetCurrentThreadId(), TIME_PERIODIC);                    
                    }
                    continue ;                    
                }

                hOut = selectSpeakerDevice() ;
                if (hOut)
                {
			        ret = waveOutUnprepareHeader(hOut, pWH, sizeof(WAVEHDR));
                    if (ret != MMSYSERR_NOERROR)
                    {
   				        showWaveError("waveOutUnprepareHeader", ret, played, __LINE__);
                    }
				    outPostUnprep(n, false);

				    pWH = outPrePrep(n, bufLen);

				    ret = waveOutPrepareHeader(hOut, pWH, sizeof(WAVEHDR));
                    if (ret != MMSYSERR_NOERROR)
                    {
   				        showWaveError("waveOutPrepareHeader", ret, played, __LINE__);
                    }
			    	ret = waveOutWrite(hOut, pWH, sizeof(WAVEHDR));
                    if (ret != MMSYSERR_NOERROR)
                    {
   				        showWaveError("waveOutWrite", ret, played, __LINE__);
                    }
                    played++;
			    }

                res = MpMediaTask::signalFrameStart();

                switch (res) 
                {
                case OS_SUCCESS:
                    frameCount++;
                    break;
#ifdef DEBUG_WINDOZE /* [ */
                case OS_LIMIT_REACHED:
                    // Should bump missed frame statistic
                    osPrintf(" Frame %d: OS_LIMIT_REACHED\n", frameCount);
                   break;
                case OS_WAIT_TIMEOUT:
                    // Should bump missed frame statistic
                    osPrintf(" Frame %d: OS_WAIT_TIMEOUT\n", frameCount);
                    break;
                case OS_ALREADY_SIGNALED:
                    // Should bump missed frame statistic
                    osPrintf(" Frame %d: OS_ALREADY_SIGNALED\n", frameCount);
                    break;
                default:
                    osPrintf("Frame %d, signalFrameStart() returned %d\n",
                            frameCount, res);
                    break;
#else /* DEBUG_WINDOZE ] [ */
                case OS_LIMIT_REACHED:
                case OS_WAIT_TIMEOUT:
                case OS_ALREADY_SIGNALED:
                default:
                    // Should bump missed frame statistic
                    break;
#endif /* DEBUG_WINDOZE ] */
                }
                break;
            case WOM_CLOSE:
                // Audio device was closed on us (doesn't happen as far as I
                // know)
                bDone = true ;
                break;
            default:                
                break;
            }
        } 
        else 
        {
            // Sky is falling, kick out so that we don't spin a high priority
            // thread.
            bDone = true ;
        }
      
        // record our last ringer state
        sLastRingerEnabled = DmaTask::isRingerEnabled();
    }

    closeSpeakerDevices() ;

    bRunning = false ;

    return 0;
}
Example #8
0
BaseType_t xPortStartScheduler( void )
{
void *pvHandle;
int32_t lSuccess = pdPASS;
xThreadState *pxThreadState;

	/* Install the interrupt handlers used by the scheduler itself. */
	vPortSetInterruptHandler( portINTERRUPT_YIELD, prvProcessYieldInterrupt );
	vPortSetInterruptHandler( portINTERRUPT_TICK, prvProcessTickInterrupt );

	/* Create the events and mutexes that are used to synchronise all the
	threads. */
	pvInterruptEventMutex = CreateMutex( NULL, FALSE, NULL );
	pvInterruptEvent = CreateEvent( NULL, FALSE, FALSE, NULL );

	if( ( pvInterruptEventMutex == NULL ) || ( pvInterruptEvent == NULL ) )
	{
		lSuccess = pdFAIL;
	}

	/* Set the priority of this thread such that it is above the priority of
	the threads that run tasks.  This higher priority is required to ensure
	simulated interrupts take priority over tasks. */
	pvHandle = GetCurrentThread();
	if( pvHandle == NULL )
	{
		lSuccess = pdFAIL;
	}

	if( lSuccess == pdPASS )
	{
		if( SetThreadPriority( pvHandle, THREAD_PRIORITY_NORMAL ) == 0 )
		{
			lSuccess = pdFAIL;
		}
		SetThreadPriorityBoost( pvHandle, TRUE );
		SetThreadAffinityMask( pvHandle, 0x01 );
	}

	if( lSuccess == pdPASS )
	{
		/* Start the thread that simulates the timer peripheral to generate
		tick interrupts.  The priority is set below that of the simulated
		interrupt handler so the interrupt event mutex is used for the
		handshake / overrun protection. */
		pvHandle = CreateThread( NULL, 0, prvSimulatedPeripheralTimer, NULL, 0, NULL );
		if( pvHandle != NULL )
		{
			SetThreadPriority( pvHandle, THREAD_PRIORITY_BELOW_NORMAL );
			SetThreadPriorityBoost( pvHandle, TRUE );
			SetThreadAffinityMask( pvHandle, 0x01 );
		}

		/* Start the highest priority task by obtaining its associated thread
		state structure, in which is stored the thread handle. */
		pxThreadState = ( xThreadState * ) *( ( uint32_t * ) pxCurrentTCB );
		ulCriticalNesting = portNO_CRITICAL_NESTING;

		/* Bump up the priority of the thread that is going to run, in the
		hope that this will assist in getting the Windows thread scheduler to
		behave as an embedded engineer might expect. */
		ResumeThread( pxThreadState->pvThread );

		/* Handle all simulated interrupts - including yield requests and
		simulated ticks. */
		prvProcessSimulatedInterrupts();
	}

	/* Would not expect to return from prvProcessSimulatedInterrupts(), so should
	not get here. */
	return 0;
}
Example #9
0
static void prvProcessSimulatedInterrupts( void )
{
uint32_t ulSwitchRequired, i;
xThreadState *pxThreadState;
void *pvObjectList[ 2 ];

	/* Going to block on the mutex that ensured exclusive access to the simulated
	interrupt objects, and the event that signals that a simulated interrupt
	should be processed. */
	pvObjectList[ 0 ] = pvInterruptEventMutex;
	pvObjectList[ 1 ] = pvInterruptEvent;

	/* Create a pending tick to ensure the first task is started as soon as
	this thread pends. */
	ulPendingInterrupts |= ( 1 << portINTERRUPT_TICK );
	SetEvent( pvInterruptEvent );

	xPortRunning = pdTRUE;

	for(;;)
	{
		WaitForMultipleObjects( sizeof( pvObjectList ) / sizeof( void * ), pvObjectList, TRUE, INFINITE );

		/* Used to indicate whether the simulated interrupt processing has
		necessitated a context switch to another task/thread. */
		ulSwitchRequired = pdFALSE;

		/* For each interrupt we are interested in processing, each of which is
		represented by a bit in the 32bit ulPendingInterrupts variable. */
		for( i = 0; i < portMAX_INTERRUPTS; i++ )
		{
			/* Is the simulated interrupt pending? */
			if( ulPendingInterrupts & ( 1UL << i ) )
			{
				/* Is a handler installed? */
				if( ulIsrHandler[ i ] != NULL )
				{
					/* Run the actual handler. */
					if( ulIsrHandler[ i ]() != pdFALSE )
					{
						ulSwitchRequired |= ( 1 << i );
					}
				}

				/* Clear the interrupt pending bit. */
				ulPendingInterrupts &= ~( 1UL << i );
			}
		}

		if( ulSwitchRequired != pdFALSE )
		{
			void *pvOldCurrentTCB;

			pvOldCurrentTCB = pxCurrentTCB;

			/* Select the next task to run. */
			vTaskSwitchContext();

			/* If the task selected to enter the running state is not the task
			that is already in the running state. */
			if( pvOldCurrentTCB != pxCurrentTCB )
			{
				/* Suspend the old thread. */
				pxThreadState = ( xThreadState *) *( ( uint32_t * ) pvOldCurrentTCB );
				SuspendThread( pxThreadState->pvThread );

				/* Obtain the state of the task now selected to enter the
				Running state. */
				pxThreadState = ( xThreadState * ) ( *( uint32_t *) pxCurrentTCB );
				ResumeThread( pxThreadState->pvThread );
			}
		}

		ReleaseMutex( pvInterruptEventMutex );
	}
}
void resume_thread(uint32_t tid)
{
    HANDLE thread_handle = open_thread(tid);
    ResumeThread(thread_handle);
    CloseHandle(thread_handle);
}
Example #11
0
int __cdecl main(int argc, char **argv)
{

    DWORD dwRet;
    DWORD dwRet1;
    bTestResult = FAIL;
    
    if ((PAL_Initialize(argc,argv)) != 0)
    {
        return(bTestResult);
    }

    /*
     * Create Critical Section Object
     */
    InitializeCriticalSection ( &CriticalSection );

    EnterCriticalSection ( &CriticalSection );

    hThread[0] = CreateThread(NULL,
                              0,
                              &ThreadTest1,
                              (LPVOID) 0,
                              CREATE_SUSPENDED,
                              &dwThreadId[0]);
    if (hThread[0] == NULL)
    {
        Trace("PALSUITE ERROR: CreateThread(%p, %d, %p, %p, %d, %p) call "
             "failed.\nGetLastError returned %d.\n", NULL, 0, &ThreadTest1,
             (LPVOID) 0, CREATE_SUSPENDED, &dwThreadId[0], GetLastError());
        LeaveCriticalSection(&CriticalSection);
        DeleteCriticalSection ( &CriticalSection );
        Fail("");
    }
    
    hThread[1] = CreateThread(NULL,
                              0,
                              &ThreadTest2,
                              (LPVOID) 0,
                              CREATE_SUSPENDED,
                              &dwThreadId[1]);
    if (hThread[1] == NULL)
    {
        Trace("PALSUITE ERROR: CreateThread(%p, %d, %p, %p, %d, %p) call "
             "failed.\nGetLastError returned %d.\n", NULL, 0, &ThreadTest2,
             (LPVOID) 0, CREATE_SUSPENDED, &dwThreadId[1], GetLastError());
        LeaveCriticalSection(&CriticalSection);

        dwRet = ResumeThread(hThread[0]);
        if (-1 == dwRet)
        {
            Trace("PALSUITE ERROR: ResumeThread(%p) call failed.\n"
                  "GetLastError returned '%d'.\n", hThread[0],
             GetLastError());
    }

        dwRet = WaitForSingleObject(hThread[0], 10000);
        if (WAIT_OBJECT_0 == dwRet)
        {
            Trace("PALSUITE ERROR: WaitForSingleObject(%p, %d) call "
                  "failed.  '%d' was returned instead of the expected '%d'.\n"
                  "GetLastError returned '%d'.\n", hThread[0], 10000, dwRet, 
                  WAIT_OBJECT_0, GetLastError());
        }

        if (0 == CloseHandle(hThread[0]))
        {
            Trace("PALSUITE NOTIFICATION: CloseHandle(%p) call failed.\n"
                  "GetLastError returned %d.  Not failing tests.\n", 
                  hThread[0], GetLastError());
        }

        DeleteCriticalSection(&CriticalSection);
        Fail("");
    }

    /* 
     * Set other thread priorities to be higher than ours & Sleep to ensure 
     * we give up the processor. 
     */
    dwRet = (DWORD) SetThreadPriority(hThread[0], 
                                      THREAD_PRIORITY_ABOVE_NORMAL);
    if (0 == dwRet)
    {
        Trace("PALSUITE ERROR: SetThreadPriority(%p, %d) call failed.\n"
              "GetLastError returned %d", hThread[0], 
              THREAD_PRIORITY_ABOVE_NORMAL, GetLastError());
    }
    
    dwRet = (DWORD) SetThreadPriority(hThread[1], 
                                      THREAD_PRIORITY_ABOVE_NORMAL);
    if (0 == dwRet)
    {
        Trace("PALSUITE ERROR: SetThreadPriority(%p, %d) call failed.\n"
              "GetLastError returned %d", hThread[1], 
              THREAD_PRIORITY_ABOVE_NORMAL, GetLastError());
    }

    dwRet = ResumeThread(hThread[0]);
    if (-1 == dwRet)
    {
        Trace("PALSUITE ERROR: ResumeThread(%p, %d) call failed.\n"
              "GetLastError returned %d", hThread[0], 
              GetLastError() );
    }
   
    dwRet = ResumeThread(hThread[1]); 
    if (-1 == dwRet)
    {
        Trace("PALSUITE ERROR: ResumeThread(%p, %d) call failed.\n"
              "GetLastError returned %d", hThread[0], 
              GetLastError());              
    }

    Sleep (0);

    LeaveCriticalSection (&CriticalSection);
    
    dwRet = WaitForSingleObject(hThread[0], 10000);
    dwRet1 = WaitForSingleObject(hThread[1], 10000);

    if ((WAIT_OBJECT_0 == dwRet) || 
        (WAIT_OBJECT_0 == dwRet1))
    {
        if ((1 == flags[0] && 0 == flags[1]) ||
            (0 == flags[0] && 1 == flags[1]))
        {
            bTestResult = PASS;
        }
        else 
        {
            bTestResult = FAIL;
            Trace ("PALSUITE ERROR: flags[%d] = {%d,%d}.  These values are"
                   "inconsistent.\nCriticalSection test failed.\n",
                   NUM_BLOCKING_THREADS, flags[0], flags[1]);
        }

        /* Fail the test if both threads returned WAIT_OBJECT_0 */
        if ((WAIT_OBJECT_0 == dwRet) && (WAIT_OBJECT_0 == dwRet1))
        {
            bTestResult = FAIL;
            Trace ("PALSUITE ERROR: WaitForSingleObject(%p, %d) and "
                   "WaitForSingleObject(%p, %d)\nboth returned dwRet = '%d'\n"
                   "One should have returned WAIT_TIMEOUT ('%d').\n", 
                   hThread[0], 10000, hThread[1], 10000, dwRet, WAIT_TIMEOUT);
        }        
    }
    else 
    {
        bTestResult = FAIL;
        Trace ("PALSUITE ERROR: WaitForSingleObject(%p, %d) and "
               "WaitForSingleObject(%p, %d)\nReturned dwRet = '%d' and\n"
               "dwRet1 = '%d' respectively.\n", hThread[0], 10000, hThread[1],
               10000, dwRet, dwRet1);
    }    

    if (WAIT_OBJECT_0 == dwRet)
    {
        if (0 == CloseHandle(hThread[0]))
        {
            Trace("PALSUITE NOTIFICATION: CloseHandle(%p) call failed.\n"
                  "GetLastError returned %d.  Not failing tests.\n", 
                  hThread[0], GetLastError());
        }
    }
    if (WAIT_OBJECT_0 == dwRet1)
    {
        if (0 == CloseHandle(hThread[1]))
        {
            Trace("PALSUITE NOTIFICATION: CloseHandle(%p) call failed.\n"
                  "GetLastError returned %d.  Not failing tests.\n", 
                  hThread[1], GetLastError());
        }
    }

    /* Leaking the CS on purpose, since there is still a thread 
       waiting on it */

    PAL_TerminateEx(bTestResult);
    return (bTestResult);
}
Example #12
0
bool cbDebugLoadLib(int argc, char* argv[])
{
    if(argc < 2)
    {
        dputs(QT_TRANSLATE_NOOP("DBG", "Error: you must specify the name of the DLL to load\n"));
        return false;
    }

    LoadLibThreadID = fdProcessInfo->dwThreadId;
    HANDLE LoadLibThread = ThreadGetHandle((DWORD)LoadLibThreadID);

    DLLNameMem = MemAllocRemote(0, strlen(argv[1]) + 1);
    ASMAddr = MemAllocRemote(0, 0x1000);

    if(!DLLNameMem || !ASMAddr)
    {
        dputs(QT_TRANSLATE_NOOP("DBG", "Error: couldn't allocate memory in debuggee"));
        return false;
    }

    if(!MemWrite(DLLNameMem, argv[1], strlen(argv[1])))
    {
        dputs(QT_TRANSLATE_NOOP("DBG", "Error: couldn't write process memory"));
        return false;
    }

    int size = 0;
    int counter = 0;
    duint LoadLibraryA = 0;
    char command[50] = "";
    char error[MAX_ERROR_SIZE] = "";

    GetFullContextDataEx(LoadLibThread, &backupctx);

    if(!valfromstring("kernel32:LoadLibraryA", &LoadLibraryA, false))
    {
        dputs(QT_TRANSLATE_NOOP("DBG", "Error: couldn't get kernel32:LoadLibraryA"));
        return false;
    }

    // Arch specific asm code
#ifdef _WIN64
    sprintf_s(command, "mov rcx, %p", DLLNameMem);
#else
    sprintf_s(command, "push %p", DLLNameMem);
#endif // _WIN64

    assembleat(ASMAddr, command, &size, error, true);
    counter += size;

#ifdef _WIN64
    sprintf_s(command, "mov rax, %p", LoadLibraryA);
    assembleat(ASMAddr + counter, command, &size, error, true);
    counter += size;
    sprintf_s(command, "call rax");
#else
    sprintf_s(command, "call %p", LoadLibraryA);
#endif // _WIN64

    assembleat(ASMAddr + counter, command, &size, error, true);
    counter += size;

    SetContextDataEx(LoadLibThread, UE_CIP, ASMAddr);
    auto ok = SetBPX(ASMAddr + counter, UE_SINGLESHOOT | UE_BREAKPOINT_TYPE_INT3, (void*)cbDebugLoadLibBPX);

    ThreadSuspendAll();
    ResumeThread(LoadLibThread);

    unlock(WAITID_RUN);

    return ok;
}
CodecError CCodec_BC6H::CInitializeBC6HLibrary()
{
    if (!m_LibraryInitialized)
    {
        // This is shared between BC7 also
        // and checked for initialization based on static flag
        // See the function for details.
        Quant_Init();

        // One time initialisation for quantizer and shaker
        // check this is ok to remove for when we are encoding 
        // should have no effect on decoding
        BC6H_init_ramps();


        for(DWORD i=0; i < BC6H_MAX_THREADS; i++)
        {
            m_encoder[i] = NULL;
        }

        // Create threaded encoder instances
        m_LiveThreads = 0;
        m_LastThread  = 0;
        m_NumEncodingThreads = min(m_NumThreads, BC6H_MAX_THREADS);
        if (m_NumEncodingThreads == 0) m_NumEncodingThreads = 1; 
        m_Use_MultiThreading = m_NumEncodingThreads > 1;

        g_BC6EncodeParameterStorage = new BC6HEncodeThreadParam[m_NumEncodingThreads];
        if(!g_BC6EncodeParameterStorage)
        {
            return CE_Unknown;
        }

        for (int i=0; i<m_NumEncodingThreads; i++)
            g_BC6EncodeParameterStorage[i].run = false;

        m_EncodingThreadHandle = new HANDLE[m_NumEncodingThreads];
        if(!m_EncodingThreadHandle)
        {
            delete[] g_BC6EncodeParameterStorage;
            g_BC6EncodeParameterStorage = NULL;

            return CE_Unknown;
        }

        for(int i=0; i < m_NumEncodingThreads; i++)
        {
            // Create single encoder instance
            CMP_BC6H_BLOCK_PARAMETERS user_options;

            user_options.bIsSigned      = m_bIsSigned;
            user_options.fQuality       = m_Quality;
            user_options.dwMask         = m_ModeMask;
            user_options.fExposure      = m_Exposure;
            user_options.bUsePatternRec = m_UsePatternRec;

            m_encoder[i] = new BC6HBlockEncoder(user_options);
                        
            // Cleanup if problem!
            if(!m_encoder[i])
            {

                delete[] g_BC6EncodeParameterStorage;
                g_BC6EncodeParameterStorage = NULL;

                delete[] m_EncodingThreadHandle;
                m_EncodingThreadHandle = NULL;

                for(int j=0; j<i; j++)
                {
                    delete m_encoder[j];
                    m_encoder[j] = NULL;
                }

                return CE_Unknown;
            }
            
            #ifdef USE_DBGTRACE
                DbgTrace(("Encoder[%d]:ModeMask %X, Quality %f\n",i,m_ModeMask,m_Quality));
            #endif
        }

        // Create the encoding threads in the suspended state
        for(int i=0; i<m_NumEncodingThreads; i++)
        {
            m_EncodingThreadHandle[i] = (HANDLE)_beginthreadex(NULL,
                                               0,
                                               BC6HThreadProcEncode,
                                               (void*)&g_BC6EncodeParameterStorage[i],
                                               CREATE_SUSPENDED,
                                               NULL);
            if(m_EncodingThreadHandle[i])
            {
                g_BC6EncodeParameterStorage[i].encoder = m_encoder[i];
                // Inform the thread that at the moment it doesn't have any work to do
                // but that it should wait for some and not exit
                g_BC6EncodeParameterStorage[i].run = FALSE;
                g_BC6EncodeParameterStorage[i].exit = FALSE;
                // Start the thread and have it wait for work
                ResumeThread(m_EncodingThreadHandle[i]);
                m_LiveThreads++;
            }
         }


        // Create single decoder instance
        m_decoder = new BC6HBlockDecoder();
        if(!m_decoder)
        {
            for(DWORD j=0; j<m_NumEncodingThreads; j++)
            {
                delete m_encoder[j];
                m_encoder[j] = NULL;
            }
            return CE_Unknown;
        }

        m_LibraryInitialized = true;
    }
    return CE_OK;
}
Example #14
0
DWORD CThread::Resume()
{
	return ResumeThread(m_hThread);
}
Example #15
0
LONG WINAPI DetourTransactionCommitEx(PVOID **pppFailedPointer)
{
    if (pppFailedPointer != NULL) {
        // Used to get the last error.
        *pppFailedPointer = s_ppPendingError;
    }
    if (s_nPendingThreadId != (LONG)GetCurrentThreadId()) {
        return ERROR_INVALID_OPERATION;
    }

    // If any of the pending operations failed, then we abort the whole transaction.
    if (s_nPendingError != NO_ERROR) {
        DETOUR_BREAK();
        DetourTransactionAbort();
        return s_nPendingError;
    }

    // Common variables.
    DetourOperation *o;
    DetourThread *t;
    BOOL freed = FALSE;

    // Insert or remove each of the detours.
    for (o = s_pPendingOperations; o != NULL; o = o->pNext) {
        if (o->fIsRemove) {
            CopyMemory(o->pbTarget,
                       o->pTrampoline->rbRestore,
                       o->pTrampoline->cbRestore);
#ifdef DETOURS_IA64
#error Feature not supported in this release.
#endif // DETOURS_IA64

#ifdef DETOURS_X86
            *o->ppbPointer = o->pbTarget;
#endif // DETOURS_X86

#ifdef DETOURS_X64
#error Feature not supported in this release.
#endif // DETOURS_X64

#ifdef DETOURS_ARM
#error Feature not supported in this release.
#endif // DETOURS_ARM
        }
        else {
            DETOUR_TRACE(("detours: pbTramp =%p, pbRemain=%p, pbDetour=%p, cbRestore=%d\n",
                          o->pTrampoline,
                          o->pTrampoline->pbRemain,
                          o->pTrampoline->pbDetour,
                          o->pTrampoline->cbRestore));

            DETOUR_TRACE(("detours: pbTarget=%p: "
                          "%02x %02x %02x %02x "
                          "%02x %02x %02x %02x "
                          "%02x %02x %02x %02x [before]\n",
                          o->pbTarget,
                          o->pbTarget[0], o->pbTarget[1], o->pbTarget[2], o->pbTarget[3],
                          o->pbTarget[4], o->pbTarget[5], o->pbTarget[6], o->pbTarget[7],
                          o->pbTarget[8], o->pbTarget[9], o->pbTarget[10], o->pbTarget[11]));

#ifdef DETOURS_IA64
#error Feature not supported in this release.


#endif // DETOURS_IA64

#ifdef DETOURS_X64
#error Feature not supported in this release.



#endif // DETOURS_X64

#ifdef DETOURS_X86
            PBYTE pbCode = detour_gen_jmp_immediate(o->pbTarget, o->pTrampoline->pbDetour);
            pbCode = detour_gen_brk(pbCode, o->pTrampoline->pbRemain);
            *o->ppbPointer = o->pTrampoline->rbCode;
#endif // DETOURS_X86

#ifdef DETOURS_ARM
#error Feature not supported in this release.


#endif // DETOURS_ARM

            DETOUR_TRACE(("detours: pbTarget=%p: "
                          "%02x %02x %02x %02x "
                          "%02x %02x %02x %02x "
                          "%02x %02x %02x %02x [after]\n",
                          o->pbTarget,
                          o->pbTarget[0], o->pbTarget[1], o->pbTarget[2], o->pbTarget[3],
                          o->pbTarget[4], o->pbTarget[5], o->pbTarget[6], o->pbTarget[7],
                          o->pbTarget[8], o->pbTarget[9], o->pbTarget[10], o->pbTarget[11]));

            DETOUR_TRACE(("detours: pbTramp =%p: "
                          "%02x %02x %02x %02x "
                          "%02x %02x %02x %02x "
                          "%02x %02x %02x %02x\n",
                          o->pTrampoline,
                          o->pTrampoline->rbCode[0], o->pTrampoline->rbCode[1],
                          o->pTrampoline->rbCode[2], o->pTrampoline->rbCode[3],
                          o->pTrampoline->rbCode[4], o->pTrampoline->rbCode[5],
                          o->pTrampoline->rbCode[6], o->pTrampoline->rbCode[7],
                          o->pTrampoline->rbCode[8], o->pTrampoline->rbCode[9],
                          o->pTrampoline->rbCode[10], o->pTrampoline->rbCode[11]));

#ifdef DETOURS_IA64
#error Feature not supported in this release.




























#endif // DETOURS_IA64
        }
    }

    // Update any suspended threads.
    for (t = s_pPendingThreads; t != NULL; t = t->pNext) {
        CONTEXT cxt;
        cxt.ContextFlags = CONTEXT_CONTROL;

#undef DETOURS_EIP
#undef DETOURS_EIP_TYPE

#ifdef DETOURS_X86
#define DETOURS_EIP         Eip
#define DETOURS_EIP_TYPE    DWORD
#endif // DETOURS_X86

#ifdef DETOURS_X64
#error Feature not supported in this release.

#endif // DETOURS_X64

#ifdef DETOURS_IA64
#error Feature not supported in this release.

#endif // DETOURS_IA64

#ifdef DETOURS_ARM
#error Feature not supported in this release.

#endif // DETOURS_ARM

        if (GetThreadContext(t->hThread, &cxt)) {
            for (DetourOperation *o = s_pPendingOperations; o != NULL; o = o->pNext) {
                if (o->fIsRemove) {
                    if (cxt.DETOURS_EIP >= (DETOURS_EIP_TYPE)(ULONG_PTR)o->pTrampoline &&
                        cxt.DETOURS_EIP < (DETOURS_EIP_TYPE)((ULONG_PTR)o->pTrampoline
                                                             + sizeof(o->pTrampoline))
                       ) {

                        cxt.DETOURS_EIP = (DETOURS_EIP_TYPE)
                            ((ULONG_PTR)o->pbTarget
                             + detour_align_from_trampoline(o->pTrampoline,
                                                            (BYTE)(cxt.DETOURS_EIP
                                                                   - (DETOURS_EIP_TYPE)(ULONG_PTR)
                                                                   o->pTrampoline)));

                        SetThreadContext(t->hThread, &cxt);
                    }
                }
                else {
                    if (cxt.DETOURS_EIP >= (DETOURS_EIP_TYPE)(ULONG_PTR)o->pbTarget &&
                        cxt.DETOURS_EIP < (DETOURS_EIP_TYPE)((ULONG_PTR)o->pbTarget
                                                             + o->pTrampoline->cbRestore)
                       ) {

                        cxt.DETOURS_EIP = (DETOURS_EIP_TYPE)
                            ((ULONG_PTR)o->pTrampoline
                             + detour_align_from_target(o->pTrampoline,
                                                        (BYTE)(cxt.DETOURS_EIP
                                                               - (DETOURS_EIP_TYPE)(ULONG_PTR)
                                                               o->pbTarget)));

                        SetThreadContext(t->hThread, &cxt);
                    }
                }
            }
        }
#undef DETOURS_EIP
    }

    // Restore all of the page permissions and flush the icache.
    HANDLE hProcess = GetCurrentProcess();
    for (o = s_pPendingOperations; o != NULL;) {
        // We don't care if this fails, because the code is still accessible.
        DWORD dwOld;
        VirtualProtect(o->pbTarget, o->pTrampoline->cbRestore, o->dwPerm, &dwOld);
        FlushInstructionCache(hProcess, o->pbTarget, o->pTrampoline->cbRestore);

        if (o->fIsRemove && o->pTrampoline) {
            detour_free_trampoline(o->pTrampoline);
            o->pTrampoline = NULL;
            freed = true;
        }

        DetourOperation *n = o->pNext;
        delete o;
        o = n;
    }
    s_pPendingOperations = NULL;

    // Free any trampoline regions that are now unused.
    if (freed && !s_fRetainRegions) {
        detour_free_unused_trampoline_regions();
    }

    // Make sure the trampoline pages are no longer writable.
    detour_runnable_trampoline_regions();

    // Resume any suspended threads.
    for (t = s_pPendingThreads; t != NULL;) {
        // There is nothing we can do if this fails.
        ResumeThread(t->hThread);

        DetourThread *n = t->pNext;
        delete t;
        t = n;
    }
    s_pPendingThreads = NULL;
    s_nPendingThreadId = 0;

    if (pppFailedPointer != NULL) {
        *pppFailedPointer = s_ppPendingError;
    }

    return s_nPendingError;
}
Example #16
0
void JThread::resume() {

  ResumeThread((HANDLE)hnd);

}
Example #17
0
/*
 * dmaStartup -- Start the threads that generate the 10ms interval signal,
 *      and that handle the audio input and output.
 */
OsStatus dmaStartup(int samplesPerFrame)
{
    if (!checkFormat(1, SAMPLES_PER_SEC, BITS_PER_SAMPLE))
    {
        osPrintf(" %3d channels, %5d samples/sec, %2d bits/sample: is NOT supported\n",
                1, SAMPLES_PER_SEC, BITS_PER_SAMPLE) ;

        // 12/16/2004: Allow thread to startup and attempt to open audio
        // channels.  It will likely fail, but the code down stream will
        // fire off alt heartbeat mechanism.
    }


    // start a thread to receive microphone input
    // mic thread will prime the device input queue
    hMicThread = (HANDLE)_beginthreadex(
            NULL,             // pointer to thread security attributes
            16000,            // initial thread stack size, in bytes
            MicThread,        // pointer to thread function
            (LPVOID) 0,       // argument for new thread
            CREATE_SUSPENDED, // creation flags
            (unsigned*)&dwMicThreadID    // pointer to returned thread identifier
    );

    assert(NULL != hMicThread);

    // start a thread to send audio out to the speaker
    // speaker thread will prime the device output queue
    hSpkrThread = (HANDLE)_beginthreadex(
            NULL,             // pointer to thread security attributes
            16000,            // initial thread stack size, in bytes
            SpkrThread,       // pointer to thread function
            (LPVOID) 0,       // argument for new thread
            CREATE_SUSPENDED, // creation flags
            (unsigned*)&dwSpkrThreadID    // pointer to returned thread identifier
    );

    assert(NULL != hSpkrThread);

    // All these threads were started with the SUSPENDED option so that
    // the following thread priority manipulations can happen without
    // yielding the CPU.  They will be resumed soon, but see the comment
    // next below...
    SetThreadPriority(hSpkrThread, THREAD_PRIORITY_TIME_CRITICAL);
    SetThreadPriority(hMicThread, THREAD_PRIORITY_TIME_CRITICAL);


    // Both the Microphone thread and the Speaker thread issue resume
    // commands for the other thread (Mic resumes Spkr, Spkr resumes Mic).
    // (Resuming a running thread is harmless).
    //
    // Exactly one of the two threads should be resumed here, and that one
    // will get the first opportunity to open its side of the audio device.
    // Once it has done so, it will issue the resume command for the other
    // thread, so that on systems with half-duplex audio devices we will be
    // consistent about which device will be opened and which will fail.
    //
    // Currently, we start the Speaker thread first, so that we will be
    // sure to open the output device on a half-duplex system.  If it is
    // decided that we want to open only the input device in such situations,
    // REPLACE the next statement with "ResumeThread(hMicThread);"

    ResumeThread(hSpkrThread);

    return OS_SUCCESS;
}
Example #18
0
void nt_execve(char *prog, char**args, char**envir ) {

	STARTUPINFO si;
	PROCESS_INFORMATION pi;
	HANDLE htemp;
	BOOL bRet;
    DWORD type=0;
	DWORD dwCreationflags;
	unsigned int priority;
	char *argv0;
	char *cmdstr, *cmdend ;
	char *originalPtr;
	unsigned int cmdsize,cmdlen;
    char *p2;
	char **savedargs;
	int retries=0;
	int hasdot =0;
	int is_winnt ;

	memset(&si,0,sizeof(si));
	savedargs = args;

	/* 
	 * This memory is not freed because we are exec()ed and will
	 * not be alive long.
	 */
	originalPtr = cmdstr= heap_alloc(MAX_PATH<<2);

	is_winnt = (gdwPlatform != VER_PLATFORM_WIN32_WINDOWS);


	cmdsize = MAX_PATH<<2;

	p2 = cmdstr;

	cmdlen = 0;
	cmdlen += copy_quote_and_fix_slashes(prog,cmdstr,&hasdot);

	p2 += cmdlen;

	/* If the command was not quoted ,
	  skip initial character we left for quote */
	if (*cmdstr != '"') {
		*cmdstr = 'A';
		cmdstr++; 
		cmdsize--;
	}
	*p2 = 0;
	cmdend = p2;


	if (!is_winnt){
		argv0 = NULL;
		goto win95_directly_here;
	}
	else {
		argv0 = heap_alloc(MAX_PATH); /* not freed */
		wsprintf(argv0,"%s",prog);
	}

retry:

	bRet=GetBinaryType(argv0,&type);
	dprintf("binary type for %s is %d\n",argv0,bRet);
	//
	// For NT, append .EXE and retry
	//
	if (is_winnt && !bRet ) {
        /* Don't append .EXE if it could be a script file */
		if (GetLastError() == ERROR_BAD_EXE_FORMAT){
			errno = ENOEXEC;
			if (!__nt_only_start_exes)
				try_shell_ex(args,1,FALSE); //can't throw on error
			return;
		}
		else if ( retries ){
			if (
				( (argv0[0] == '\\') ||(argv0[0] == '/') ) &&
				( (argv0[1] == '\\') ||(argv0[1] == '/') ) &&
				(!args[1])
			   )
				if (!__nt_only_start_exes)
					try_shell_ex(args,1,FALSE);
			errno  = ENOENT;
		}
		if (retries > 1){
			return;
		}
		// Try uppercase once and then lower case
		//
		if (!retries)
			wsprintf(argv0,"%s.exe",prog);
		else 
			wsprintf(argv0,"%s.EXE",prog); /* fix for clearcase */
		retries++;
		goto retry;
	}

win95_directly_here:

	si.cb = sizeof(STARTUPINFO);
	si.dwFlags = STARTF_USESTDHANDLES;
	htemp= (HANDLE)_get_osfhandle(0);
	DuplicateHandle(GetCurrentProcess(),htemp,GetCurrentProcess(),
						&si.hStdInput,0,TRUE,DUPLICATE_SAME_ACCESS);
	htemp= (HANDLE)_get_osfhandle(1);
	DuplicateHandle(GetCurrentProcess(),htemp,GetCurrentProcess(),
						&si.hStdOutput,0,TRUE,DUPLICATE_SAME_ACCESS);
	htemp= (HANDLE)_get_osfhandle(2);
	DuplicateHandle(GetCurrentProcess(),htemp,GetCurrentProcess(),
						&si.hStdError,0,TRUE,DUPLICATE_SAME_ACCESS);



	*args++; // the first arg is the command


	dprintf("nt_execve calling c_a_a_q");
	if(!concat_args_and_quote(args,&originalPtr,&cmdstr,&cmdlen,&cmdend,
				&cmdsize))
	{
        dprintf("concat_args_and_quote failed\n");
		heap_free(originalPtr);
		errno = ENOMEM;
		goto fail_return;
	}

	*cmdend = 0;

	dwCreationflags = GetPriorityClass(GetCurrentProcess());
	if (__nt_child_nohupped) {
		dwCreationflags |= DETACHED_PROCESS;
	}
	priority = GetThreadPriority(GetCurrentThread());

	(void)fix_path_for_child();

	if (is_winnt)
		dwCreationflags |= CREATE_SUSPENDED;


re_cp:
	dprintf("argv0 %s cmdstr %s\n",argv0,cmdstr);
	bRet = CreateProcessA(argv0, cmdstr,
			NULL, NULL,
			TRUE, // need this for redirecting std handles
			dwCreationflags,
			NULL, NULL,
			&si,
			&pi);
	if (!bRet){
		if (GetLastError() == ERROR_BAD_EXE_FORMAT) {
			if (!__nt_only_start_exes)
				try_shell_ex(savedargs,1,FALSE);
			errno  = ENOEXEC;
		}
		else if (GetLastError() == ERROR_INVALID_PARAMETER) {
			/* can't get invalid parameter, so this must be
			 *  the case when we exceed the command length limit.
			 */
			errno = ENAMETOOLONG;
		}
		else {
			errno  = ENOENT;
		}
		if (!is_winnt && !hasdot) { //append '.' to the end if needed
			lstrcat(cmdstr,".");
			hasdot=1;
			goto re_cp;
		}
	}
	else{
		int gui_app ;
		char guivar[50];

		if (GetEnvironmentVariable("TCSH_NOASYNCGUI",guivar,50))
			gui_app=0;
		else {
			if (is_winnt || hasdot)
				gui_app= is_gui(argv0);
			else
				gui_app = is_9x_gui(prog);
		}

		if (is_winnt && !SetThreadPriority(pi.hThread,priority) ) {
			priority =GetLastError();
		}
		if (is_winnt)
			ResumeThread(pi.hThread);
		errno= 0;
		
		if (__nt_really_exec||__nt_child_nohupped || gui_app){
			ExitProcess(0);
		}
		else {
			DWORD exitcode=0;
			WaitForSingleObject(pi.hProcess,INFINITE);
			(void)GetExitCodeProcess(pi.hProcess,&exitcode);
			CloseHandle(pi.hProcess);
			CloseHandle(pi.hThread);
			/*
			 * If output was redirected to /dev/clipboard,
			 * we need to close the pipe handles
			 */
			if (is_dev_clipboard_active) {
				CloseHandle((HANDLE)_get_osfhandle(0));
				CloseHandle((HANDLE)_get_osfhandle(1));
				CloseHandle((HANDLE)_get_osfhandle(2));
				CloseHandle(si.hStdInput);
				CloseHandle(si.hStdOutput);
				CloseHandle(si.hStdError);
				WaitForSingleObject(ghdevclipthread,60*1000);
			}
			ExitProcess(exitcode);
		}
	}
fail_return:
    CloseHandle(si.hStdInput);
    CloseHandle(si.hStdOutput);
    CloseHandle(si.hStdError);
    return;
}
Example #19
0
static int openSpeakerDevices(WAVEHDR*& pWH, HWAVEOUT& hOut)
{
    DWORD    bufLen = ((N_SAMPLES * BITS_PER_SAMPLE) / 8);
    int i ;
    MMRESULT ret;
    MSG tMsg;
    BOOL bSuccess ;    

	// set the different device ids
	gRingDeviceId = WAVE_MAPPER;
	gCallDeviceId = WAVE_MAPPER;


    // If either the ringer or call device is set to NONE, don't engage any audio devices
    if ((strcasecmp(DmaTask::getRingDevice(), "NONE") == 0) ||
        (strcasecmp(DmaTask::getCallDevice(), "NONE") == 0))
    {
        ResumeThread(hMicThread);
        return 1;
    }

    /*
     * Select in-call / ringer devices
     */
	int ii;
	WAVEOUTCAPS devcaps;
	int numberOfDevicesOnSystem = waveOutGetNumDevs();
	for(ii=0; ii<numberOfDevicesOnSystem; ii++)
    {
        waveOutGetDevCaps(ii,&devcaps,sizeof(WAVEOUTCAPS));
        if (strcmp(devcaps.szPname, DmaTask::getRingDevice())==0) 
        {
            gRingDeviceId = ii;
            osPrintf("SpkrThread: Selected ring device: %s\n",devcaps.szPname);
        }

		if (strcmp(devcaps.szPname, DmaTask::getCallDevice())==0) 
        {
            gCallDeviceId = ii;
            osPrintf("SpkrThread: Selected call device: %s\n",devcaps.szPname);
        }
    }

    /*
     * Open ringer device
     */ 
    if (!openAudioOut(gRingDeviceId, &audioOutH, 1, SAMPLES_PER_SEC, BITS_PER_SAMPLE))
    {
        osPrintf("SpkrThread: Failed to open ring audio output channel\n\n");
        ResumeThread(hMicThread);
        return 1;
    }

    do 
    {
        bSuccess = GetMessage(&tMsg, NULL, 0, 0) ;
    } while (bSuccess && (tMsg.message != WOM_OPEN)) ;


    /*
     * Open in-call device
     */
    if (!openAudioOut(gCallDeviceId,&audioOutCallH, 1, SAMPLES_PER_SEC, BITS_PER_SAMPLE))
    {
        osPrintf("SpkrThread: Failed to open call audio output channel\n\n");
        ResumeThread(hMicThread);
        return 1;
    }

    do 
    {
        bSuccess = GetMessage(&tMsg, NULL, 0, 0) ;
    } while (bSuccess && tMsg.message != WOM_OPEN) ;


    // Pre load some data    
    for (i=0; i<smSpkrQPreload; i++)
    {
        pWH = outPrePrep(i, bufLen);

        hOut = selectSpeakerDevice() ;
        if (hOut)
        {
            ret = waveOutPrepareHeader(hOut, pWH, sizeof(WAVEHDR));
            if (ret != MMSYSERR_NOERROR)
            {
                showWaveError("waveOutPrepareHeader", ret, i, __LINE__);
            }
	        ret = waveOutWrite(hOut, pWH, sizeof(WAVEHDR));
            if (ret != MMSYSERR_NOERROR)
            {
   	            showWaveError("waveOutWrite", ret, i, __LINE__);
            }
        }      
    }

    return 0 ;
}
Example #20
0
/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
UINT DeviceServiceEntry(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints)
{
	SMARTCARD_DEVICE* smartcard = NULL;
	size_t length;
	UINT error = CHANNEL_RC_NO_MEMORY;

	if (!sSmartcard)
	{
		wObject* obj;
		smartcard = (SMARTCARD_DEVICE*) calloc(1, sizeof(SMARTCARD_DEVICE));

		if (!smartcard)
		{
			WLog_ERR(TAG, "calloc failed!");
			return CHANNEL_RC_NO_MEMORY;
		}

		smartcard->device.type = RDPDR_DTYP_SMARTCARD;
		smartcard->device.name = "SCARD";
		smartcard->device.IRPRequest = smartcard_irp_request;
		smartcard->device.Init = smartcard_init;
		smartcard->device.Free = smartcard_free;
		smartcard->names = LinkedList_New();
		smartcard->rdpcontext = pEntryPoints->rdpcontext;
		length = strlen(smartcard->device.name);
		smartcard->device.data = Stream_New(NULL, length + 1);

		if (!smartcard->device.data || !smartcard->names)
		{
			WLog_ERR(TAG, "Stream_New failed!");
			goto fail;
		}

		Stream_Write(smartcard->device.data, "SCARD", 6);
		smartcard->IrpQueue = MessageQueue_New(NULL);

		if (!smartcard->IrpQueue)
		{
			WLog_ERR(TAG, "MessageQueue_New failed!");
			goto fail;
		}

		smartcard->CompletedIrpQueue = Queue_New(TRUE, -1, -1);

		if (!smartcard->CompletedIrpQueue)
		{
			WLog_ERR(TAG, "Queue_New failed!");
			goto fail;
		}

		smartcard->rgSCardContextList = ListDictionary_New(TRUE);

		if (!smartcard->rgSCardContextList)
		{
			WLog_ERR(TAG, "ListDictionary_New failed!");
			goto fail;
		}

		obj = ListDictionary_ValueObject(smartcard->rgSCardContextList);
		obj->fnObjectFree = smartcard_context_free;
		smartcard->rgOutstandingMessages = ListDictionary_New(TRUE);

		if (!smartcard->rgOutstandingMessages)
		{
			WLog_ERR(TAG, "ListDictionary_New failed!");
			goto fail;
		}

		if ((error = pEntryPoints->RegisterDevice(pEntryPoints->devman, &smartcard->device)))
		{
			WLog_ERR(TAG, "RegisterDevice failed!");
			goto fail;
		}

		smartcard->thread = CreateThread(NULL, 0,
		                                 smartcard_thread_func,
		                                 smartcard, CREATE_SUSPENDED, NULL);

		if (!smartcard->thread)
		{
			WLog_ERR(TAG, "ListDictionary_New failed!");
			error = ERROR_INTERNAL_ERROR;
			goto fail;
		}

		ResumeThread(smartcard->thread);
	}
	else
		smartcard = sSmartcard;

	if (pEntryPoints->device->Name)
		LinkedList_AddLast(smartcard->names, pEntryPoints->device->Name);

	sSmartcard = smartcard;
	return CHANNEL_RC_OK;
fail:
	smartcard_free_(smartcard);
	return error;
}
Example #21
0
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)((DWORD)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((DWORD)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;
}
void
SamplerThread::SuspendAndSampleAndResumeThread(PSLockRef aLock,
                                               TickSample& aSample)
{
  HANDLE profiled_thread = aSample.mPlatformData->ProfiledThread();
  if (profiled_thread == nullptr)
    return;

  // Context used for sampling the register state of the profiled thread.
  CONTEXT context;
  memset(&context, 0, sizeof(context));

  //----------------------------------------------------------------//
  // Suspend the samplee thread and get its context.

  static const DWORD kSuspendFailed = static_cast<DWORD>(-1);
  if (SuspendThread(profiled_thread) == kSuspendFailed) {
    return;
  }

  // SuspendThread is asynchronous, so the thread may still be running.
  // Call GetThreadContext first to ensure the thread is really suspended.
  // See https://blogs.msdn.microsoft.com/oldnewthing/20150205-00/?p=44743.

  // Using only CONTEXT_CONTROL is faster but on 64-bit it causes crashes in
  // RtlVirtualUnwind (see bug 1120126) so we set all the flags.
#if defined(GP_ARCH_amd64)
  context.ContextFlags = CONTEXT_FULL;
#else
  context.ContextFlags = CONTEXT_CONTROL;
#endif
  if (!GetThreadContext(profiled_thread, &context)) {
    ResumeThread(profiled_thread);
    return;
  }

  //----------------------------------------------------------------//
  // Sample the target thread.

  // WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
  //
  // The profiler's "critical section" begins here.  We must be very careful
  // what we do here, or risk deadlock.  See the corresponding comment in
  // platform-linux-android.cpp for details.

#if defined(GP_ARCH_amd64)
  aSample.mPC = reinterpret_cast<Address>(context.Rip);
  aSample.mSP = reinterpret_cast<Address>(context.Rsp);
  aSample.mFP = reinterpret_cast<Address>(context.Rbp);
#else
  aSample.mPC = reinterpret_cast<Address>(context.Eip);
  aSample.mSP = reinterpret_cast<Address>(context.Esp);
  aSample.mFP = reinterpret_cast<Address>(context.Ebp);
#endif

  aSample.mContext = &context;

  Tick(aLock, ActivePS::Buffer(aLock), aSample);

  //----------------------------------------------------------------//
  // Resume the target thread.

  ResumeThread(profiled_thread);

  // The profiler's critical section ends here.
  //
  // WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
}
Example #23
0
int DeviceServiceEntry(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints)
{
	char* name;
	char* path;
	int length, ck;
	RDPDR_SMARTCARD* device;
	SMARTCARD_DEVICE* smartcard;

	device = (RDPDR_SMARTCARD*) pEntryPoints->device;

	name = device->Name;
	path = device->Path;

	smartcard = (SMARTCARD_DEVICE*) calloc(1, sizeof(SMARTCARD_DEVICE));
	if (!smartcard)
		return -1;

	smartcard->device.type = RDPDR_DTYP_SMARTCARD;
	smartcard->device.name = "SCARD";
	smartcard->device.IRPRequest = smartcard_irp_request;
	smartcard->device.Init = smartcard_init;
	smartcard->device.Free = smartcard_free;

	length = strlen(smartcard->device.name);
	smartcard->device.data = Stream_New(NULL, length + 1);
	if (!smartcard->device.data)
		goto error_device_data;

	Stream_Write(smartcard->device.data, "SCARD", 6);

	smartcard->name = NULL;
	smartcard->path = NULL;

	if (path)
	{
		smartcard->path = path;
		smartcard->name = name;
	}
	else if (name)
	{
		if (1 == sscanf(name, "%d", &ck))
			smartcard->path = name;
		else
			smartcard->name = name;
	}

	smartcard->IrpQueue = MessageQueue_New(NULL);
	if (!smartcard->IrpQueue)
		goto error_irp_queue;

	smartcard->CompletedIrpQueue = Queue_New(TRUE, -1, -1);
	if (!smartcard->CompletedIrpQueue)
		goto error_completed_irp_queue;

	smartcard->rgSCardContextList = ListDictionary_New(TRUE);
	if (!smartcard->rgSCardContextList)
		goto error_context_list;

	ListDictionary_ValueObject(smartcard->rgSCardContextList)->fnObjectFree =
			(OBJECT_FREE_FN) smartcard_context_free;

	smartcard->rgOutstandingMessages = ListDictionary_New(TRUE);
	if (!smartcard->rgOutstandingMessages)
		goto error_outstanding_messages;

	smartcard->thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) smartcard_thread_func,
			smartcard, CREATE_SUSPENDED, NULL);
	if (!smartcard->thread)
		goto error_thread;

	pEntryPoints->RegisterDevice(pEntryPoints->devman, (DEVICE*) smartcard);

	ResumeThread(smartcard->thread);

	return 0;

error_thread:
	ListDictionary_Free(smartcard->rgOutstandingMessages);
error_outstanding_messages:
	ListDictionary_Free(smartcard->rgSCardContextList);
error_context_list:
	Queue_Free(smartcard->CompletedIrpQueue);
error_completed_irp_queue:
	MessageQueue_Free(smartcard->IrpQueue);
error_irp_queue:
	Stream_Free(smartcard->device.data, TRUE);
error_device_data:
	free(smartcard);
	return -1;
}
Example #24
0
BOOL APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
	PCHAR pszDllPath = "Accelerator.dll";

	CHAR szDllPath[1024];
    PCHAR pszFilePart = NULL;

	if (!GetFullPathName(pszDllPath, ARRAYSIZE(szDllPath), szDllPath, &pszFilePart)) 
	{
        MessageBoxA(NULL, "GetFullPathName Failed\n", "Error", MB_OK);
        return false;
    }

	HMODULE hDll = LoadLibraryEx(pszDllPath, NULL, DONT_RESOLVE_DLL_REFERENCES);
    if (hDll == NULL) 
	{
		MessageBoxA(NULL, "Failed to load dll\n", "Error", MB_OK);
        return false;
    }

	ExportContext ec;
    ec.fHasOrdinal1 = FALSE;
    ec.nExports = 0;
    DetourEnumerateExports(hDll, &ec, ExportCallback);
    FreeLibrary(hDll);

	if (!ec.fHasOrdinal1) 
	{
		MessageBoxA(NULL, "This dll does not export ordinal #1.\n", "Error", MB_OK);
        return false;
    }
	//////////////////////////////////////////////////////////////////////////////////
	STARTUPINFO si;
    PROCESS_INFORMATION pi;
    CHAR szCommand[2048];
    CHAR szExe[1024];
    CHAR szFullExe[1024] = "\0";
    PCHAR pszFileExe = NULL;

    ZeroMemory(&si, sizeof(si));
    ZeroMemory(&pi, sizeof(pi));
    si.cb = sizeof(si);

    szCommand[0] = L'\0';
	strcpy(szExe, "Natsu.exe");
	strcpy(szCommand, "Natsu.exe");
	//////////////////////////////////////////////////////////////////////////////////
	DWORD dwFlags = CREATE_DEFAULT_ERROR_MODE | CREATE_SUSPENDED;

    SetLastError(0);
    SearchPath(NULL, szExe, ".exe", ARRAYSIZE(szFullExe), szFullExe, &pszFileExe);
    if (!DetourCreateProcessWithDllEx(szFullExe[0] ? szFullExe : NULL, szCommand,
                                      NULL, NULL, TRUE, dwFlags, NULL, NULL,
                                      &si, &pi, szDllPath, NULL)) 
	{
        DWORD dwError = GetLastError();
		MessageBoxA(NULL, "DetourCreateProcessWithDllEx failed\n", "Error", MB_OK);
        
        if (dwError == ERROR_INVALID_HANDLE)
		{
#if DETOURS_64BIT
			MessageBoxA(NULL, " Can't detour a 32-bit target process from a 64-bit parent process.\n", "Error", MB_OK);
            
#else
			MessageBoxA(NULL, " Can't detour a 64-bit target process from a 32-bit parent process.\n", "Error", MB_OK);
#endif
        }
        ExitProcess(9009);
    }

    ResumeThread(pi.hThread);

    WaitForSingleObject(pi.hProcess, INFINITE);

    DWORD dwResult = 0;
    if (!GetExitCodeProcess(pi.hProcess, &dwResult)) 
	{
		MessageBoxA(NULL, "GetExitCodeProcess failed\n", "Error", MB_OK);
        return false;
    }

    return true;
}
Example #25
0
void CDialogInstall::LaunchInstallProcess()
{
	const bool isProcsesUserAdmin = Util::IsProcessUserAdmin();
	if (!isProcsesUserAdmin && (Platform::IsAtLeastWinVista() && !Util::CanProcessUserElevate()))
	{
		MessageBox(
			m_Window,
			L"Adminstrative privileges are required to install Rainmeter.\n\nClick OK to close setup.",
			L"Rainmeter Setup", MB_OK | MB_ICONERROR);
		PostMessage(m_Window, WM_CLOSE, 0, 0);
		return;
	}

	m_InstallProcessWaitThread = CreateThread(
		nullptr, 0, ElevatedProcessWaitThreadProc, nullptr, CREATE_SUSPENDED, nullptr);
	if (!m_InstallProcessWaitThread)
	{
		// TODO.
	}

	WCHAR exePath[MAX_PATH];
	GetModuleFileName(nullptr, exePath, _countof(exePath));

	HWND item = m_TabContents.GetControl(TabContents::Id_LanguageComboBox); 
	const LCID lcid = (LCID)ComboBox_GetItemData(item, ComboBox_GetCurSel(item));

	item = m_TabContents.GetControl(TabContents::Id_InstallationTypeComboBox); 
	const LPARAM typeData = ComboBox_GetItemData(item, ComboBox_GetCurSel(item));

	WCHAR targetPath[MAX_PATH];
	item = m_TabContents.GetControl(TabContents::Id_DestinationEdit);
	Edit_GetText(item, targetPath, _countof(targetPath));

	item = m_TabContents.GetControl(TabContents::Id_LaunchOnLoginCheckBox);
	const int launchOnLogin = Button_GetCheck(item) == BST_CHECKED ? 1 : 0;

	WCHAR params[512];
	wsprintf(
		params, L"OPT:%s|%ld|%hd|%hd|%d",
		targetPath, lcid, LOWORD(typeData), HIWORD(typeData), launchOnLogin);

	// Launch the installer process and, if needed, request elevation.
	SHELLEXECUTEINFO sei = {sizeof(sei)};
	sei.fMask = SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI | SEE_MASK_NOCLOSEPROCESS;
	sei.lpVerb = isProcsesUserAdmin ? L"open" : L"runas";
	sei.lpFile = exePath;
	sei.lpParameters = params;
	sei.hwnd = m_Window;
	sei.nShow = SW_NORMAL;

	if (!ShellExecuteEx(&sei) || !sei.hProcess)
	{
		MessageBox(m_Window,
			L"Adminstrative privileges are required to install Rainmeter.\n\nClick OK to close setup.",
			L"Rainmeter Setup", MB_OK | MB_ICONERROR);
		PostMessage(m_Window, WM_CLOSE, 0, 0);
		return;
	}

	m_InstallProcess = sei.hProcess;
	ResumeThread(m_InstallProcessWaitThread);
}
Example #26
0
int main(){
char filebytes[29000];
PROCESS_INFORMATION pi;
STARTUPINFO si;
 
printf("\n[*]Writing Bytes to an array");
filetoarray(filebytes,29000);
printf("\n[*]Done");
Sleep(500);
 
printf("\n\n[*]Modifying byte at given offest");
changebyte(filebytes,29000);
printf("\n[*]Done");
Sleep(500);
 
printf("\n\n[*]Writing to new myf.exe");
FILE *fp2;
fp2 = fopen("myf.exe","wb");
fwrite(filebytes,sizeof(filebytes[0]),sizeof(filebytes)/sizeof(filebytes[0]),fp2);
fclose(fp2);
printf("\n[*]Done");
 
Sleep(500);
 
printf("\n\n[*]Starting myf.exe as debuggee");
memset(&si,0,sizeof(si));
memset(&pi,0,sizeof(pi));
si.cb= sizeof(si);
if(CreateProcess("myf.exe",NULL,NULL,NULL,TRUE,DEBUG_PROCESS,NULL,NULL,&si,&pi)){
printf("\n[*]Process Created");
BOOL cont = TRUE;
while (cont)
{
DWORD continueStatus = DBG_CONTINUE;
DEBUG_EVENT de = {0};
if (!WaitForDebugEvent(&de, INFINITE))
{
break;
}
else{
switch (de.dwDebugEventCode)
{
 
case EXCEPTION_DEBUG_EVENT:
switch (de.u.Exception.ExceptionRecord.ExceptionCode)
{
case EXCEPTION_BREAKPOINT:
 
if((*(static_cast<unsigned int*>(de.u.Exception.ExceptionRecord.ExceptionAddress)))== -2082109099){
printf("\n\n[*]Reached Breakpoint");
//FACE THE MUSIC
 
CONTEXT c;
c.ContextFlags = CONTEXT_CONTROL|CONTEXT_FULL;
GetThreadContext(pi.hThread,&c);
printf("\nEIP : %0X",c.Eip);
SuspendThread(pi.hThread);
c.Eip--;
SetThreadContext(pi.hThread,&c);
DWORD sa = 0x401334;
BYTE ins=0x55;
WriteProcessMemory(pi.hProcess, (void*)sa, &ins, 1,NULL);
sa = 0x28FF0C;
ins=0x59;
WriteProcessMemory(pi.hProcess, (void*)sa, &ins, 1,NULL);
sa = 0x28FF10;
ins=0x9A;
WriteProcessMemory(pi.hProcess, (void*)sa, &ins, 1,NULL);
sa = 0x28FF11;
ins=0x13;
WriteProcessMemory(pi.hProcess, (void*)sa, &ins, 1,NULL);
ResumeThread(pi.hThread);
 
 
 
}
break;
default:
break;
}
break;
 
case EXIT_PROCESS_DEBUG_EVENT:
cont = FALSE;
break;
 
case CREATE_THREAD_DEBUG_EVENT:
continueStatus = DBG_CONTINUE;
break;
 
case CREATE_PROCESS_DEBUG_EVENT:
continueStatus = DBG_CONTINUE;
break;
 
case EXIT_THREAD_DEBUG_EVENT:
continueStatus = DBG_CONTINUE;
break;
 
 
}
ContinueDebugEvent(de.dwProcessId,de.dwThreadId,continueStatus);
}
}}
getch();
return 0;
}
Example #27
0
int main(int argc, char **argv, char **envp)
{
    uc_engine *uc;
    uc_err err;
	int ret;
	uc_hook hhc;
	uint32_t val;
	EmuStarterParam_t starter_params;
#ifdef _WIN32
	HANDLE th = (HANDLE)-1;
#else
	pthread_t th;
#endif

	// dynamically load shared library
#ifdef DYNLOAD
	uc_dyn_load(NULL, 0);
#endif

	// Initialize emulator in MIPS 32bit little endian mode
    printf("uc_open()\n");
	err = uc_open(UC_ARCH_MIPS, UC_MODE_MIPS32, &uc);
    if (err)
	{
        printf("Failed on uc_open() with error returned: %u\n", err);
        return err;
    }

	// map in a page of mem
	printf("uc_mem_map()\n");
	err = uc_mem_map(uc, addr, 0x1000, UC_PROT_ALL);
    if (err)
	{
        printf("Failed on uc_mem_map() with error returned: %u\n", err);
        return err;
    }

	// write machine code to be emulated to memory
	printf("uc_mem_write()\n");
    err = uc_mem_write(uc, addr, loop_test_code, sizeof(loop_test_code));
	if( err )
	{
        printf("Failed on uc_mem_write() with error returned: %u\n", err);
        return err;
    }
	
    // hook all instructions by having @begin > @end
	printf("uc_hook_add()\n");
    uc_hook_add(uc, &hhc, UC_HOOK_CODE, mips_codehook, NULL, 1, 0);
	if( err )
	{
        printf("Failed on uc_hook_add(code) with error returned: %u\n", err);
        return err;
    }
	
	
	// start background thread
	printf("---- Thread Starting ----\n");
	starter_params.uc = uc;
	starter_params.startAddr = addr;
	starter_params.endAddr = addr + sizeof(loop_test_code);

#ifdef _WIN32
	// create thread
	th = (HANDLE)_beginthreadex(NULL, 0, win32_emu_starter, &starter_params, CREATE_SUSPENDED, NULL);
	if(th == (HANDLE)-1)
	{
		printf("Failed on _beginthreadex() with error returned: %u\n", _errno());
		return -1;
	}
	// start thread
	ret = ResumeThread(th);
	if( ret == -1 )
	{
		printf("Failed on ResumeThread() with error returned: %u\n", _errno());
		return -2;
	}
	// wait 3 seconds
	Sleep(3 * 1000);
#else
	// add posix code to start the emu_starter() thread
	ret = pthread_create(&th, NULL, posix_emu_starter, &starter_params);
	if( ret )
	{
		printf("Failed on pthread_create() with error returned: %u\n", err);
		return -2;
	}
	// wait 3 seconds
	sleep(3);
#endif


	// Stop the thread after it has been let to run in the background for a while
	printf("---- Thread Stopping ----\n");
	printf("uc_emu_stop()\n");
	err = uc_emu_stop(uc);
	if( err )
	{
        printf("Failed on uc_emu_stop() with error returned: %u\n", err);
        return err;
    }
	test_passed_ok = true;
	

	// done executing, print some reg values as a test
	uc_reg_read(uc, UC_MIPS_REG_PC, &val);	printf("pc is %X\n", val);
	uc_reg_read(uc, UC_MIPS_REG_A0, &val);	printf("a0 is %X\n", val);
	
	// free resources
	printf("uc_close()\n");
	uc_close(uc);
	
	if( test_passed_ok )
		printf("\n\nTEST PASSED!\n\n");
	else
		printf("\n\nTEST FAILED!\n\n");

	// dynamically free shared library
#ifdef DYNLOAD
    uc_dyn_free();
#endif

	return 0;
}
Example #28
0
DWORD QueueUserAPCEx(PAPCFUNC pfnApc, HANDLE hThread, DWORD dwData)
     /*
      * ------------------------------------------------------
      * DOCPUBLIC
      *      Adds a user-mode asynchronous procedure call (APC) object
      *      to the APC queue of the specified thread AND sets this
      *      thread in alertarte state.
      *
      * PARAMETERS
      *      Uses the same parameters as QueueUserAPC.
      *
      * DESCRIPTION
      *      Adds a user-mode asynchronous procedure call (APC) object
      *      to the APC queue of the specified thread AND sets this
      *      thread in alertarte state.
      *
      * RESULTS
	  *		 1    Success
	  *      0    Failure
      * ------------------------------------------------------
      */
{
  DWORD cbReturned;

  /* trivial case */
  if (hThread == GetCurrentThread())
    {
      if (!QueueUserAPC(pfnApc, hThread, dwData))
        {
	      return 0;
        }

      SleepEx(0, TRUE);
      return 1;
    }

  if (INVALID_HANDLE_VALUE == hDevice
      /* && !QueueUserAPCEx_Init() */
      )
    {
      printf ("Can't get a handle to the ALERT driver\n");

      return 0;
    }

  /* probably not necessary */
  if (SuspendThread(hThread) == -1)
    {
      return 0;
    }

  /* Send the APC */
  if (!QueueUserAPC(pfnApc, hThread, dwData))
    {
      return 0;
    }

  /* Ensure the execution of the APC */
  if (DeviceIoControl (hDevice, (DWORD)IOCTL_ALERTDRV_SET_ALERTABLE2, &hThread, sizeof(HANDLE),
		NULL, 0, &cbReturned, 0))
    {
	}
  else
    {
      printf ("DeviceIoControl failed\n");
      return 0;
    }

  /* Here, we could even cancel suspended threads */
  ResumeThread(hThread);

  return 1;
}
Example #29
0
void gc_thread_run(gc_Thread* in_thread)
{
    ResumeThread(*(HANDLE*)in_thread->threadObj);
}
Example #30
0
void RS232::StartThread(){
	ResumeThread(myHThread);
}