DWORD WINAPI SmsAgent(LPVOID lpParam) { Module *me = (Module *)lpParam; Configuration *conf = me->getConf(); HANDLE eventHandle; MAPIAgent* agent = MAPIAgent::Instance(); Observer *observerObj = Observer::self(); MSG Msg; BOOL smsEnabled = FALSE, history = FALSE; wstring dateFrom, dateTo; JSONObject filter; // NON DEVE PARTIRE FINCHE NON VIENE FIXATO me->setStatus(MODULE_STOPPED); DBG_TRACE(L"Debug - Messages.cpp - This module cannot work\n", 5, FALSE); return 0; // NON DEVE PARTIRE FINCHE NON VIENE FIXATO // Cosi si prende la conf per SMS, per tutti gli altri e' uguale // cambia solo il nome dell'array try { smsEnabled = conf->getBoolFromArray(L"sms", L"enabled"); filter = conf->getObjectFromArray(L"sms", L"filter"); history = conf->getBoolFromObject(filter, L"history"); dateFrom = conf->getStringFromObject(filter, L"datefrom"); dateTo = conf->getStringFromObject(filter, L"dateto"); } catch (...) { smsEnabled = FALSE; } me->setStatus(MODULE_RUNNING); eventHandle = me->getEvent(); DBG_TRACE(L"Debug - Messages.cpp - Messages Module started\n", 5, FALSE); // Registriamoci all'observer if (observerObj->Register(GetCurrentThreadId()) == FALSE) { me->setStatus(MODULE_STOPPED); DBG_TRACE(L"Debug - Messages.cpp - Messages Module [cannot register to Observer, exiting]\n", 5, FALSE); return 0; } /*if (agent->Init(lpConfig, cbConfig) == FALSE) { me->setStatus(MODULE_STOPPED); return 0; }*/ if (agent->Run(0) == FALSE) { me->setStatus(MODULE_STOPPED); return 0; } LOOP { // Diciamo semplicemente alla coda di farli passare tutti if (observerObj->GetMessage() != NULL) { observerObj->MarkMessage(GetCurrentThreadId(), IPC_PROCESS, FALSE); } if (PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE) != 0) { TranslateMessage(&Msg); DispatchMessage(&Msg); } // Keep the sleeping time at 50, otherwise the MAIL agent WON'T WORK!!! WaitForSingleObject(eventHandle, 50); if (me->shouldStop()) break; } agent->Quit(); agent->WaitForCollector(); agent->Destroy(); observerObj->UnRegister(GetCurrentThreadId()); me->setStatus(MODULE_STOPPED); DBG_TRACE(L"Debug - Messages.cpp - Messages Module clean stop\n", 5, FALSE); return 0; }
VOID RemoveMessagesFromBuyThreadQueue(CONTENT_PARTNER_THREAD_CONTEXT* pThreadCtx) { BUY_CONTEXT* pBuyCtx = NULL; MSG msg = {0}; while( PeekMessage( &msg, NULL, pThreadCtx->buyThreadContext.msgBuy, pThreadCtx->buyThreadContext.msgBuy, PM_REMOVE ) ) { ATLTRACE2("%x: RemoveMessagesFromBuyThreadQueue: PeekMessage in cleanup retrieved message to buy.\n", GetCurrentThreadId()); pBuyCtx = reinterpret_cast<BUY_CONTEXT*>(msg.lParam); if(NULL != pBuyCtx) { if(NULL != pBuyCtx->cookie) { pBuyCtx->pIStream->Release(); pBuyCtx->pIStream = NULL; } delete pBuyCtx; pBuyCtx = NULL; } } // while PeekMessage }
VOID RemoveMessagesFromLoginThreadQueue(CONTENT_PARTNER_THREAD_CONTEXT* pThreadCtx) { LOGIN_CONTEXT* pLoginCtx = NULL; MSG msg = {0}; while( PeekMessage( &msg, NULL, pThreadCtx->loginThreadContext.msgAuthenticate, pThreadCtx->loginThreadContext.msgAuthenticate, PM_REMOVE ) ) { ATLTRACE2("%x: RemoveMessagesFromLoginQueue: PeekMessage in cleanup retrieved message to authenticate.\n", GetCurrentThreadId()); pLoginCtx = reinterpret_cast<LOGIN_CONTEXT*>(msg.lParam); if(NULL != pLoginCtx) { delete pLoginCtx; pLoginCtx = NULL; } } // while PeekMessage while( PeekMessage( &msg, NULL, pThreadCtx->loginThreadContext.msgLogin, pThreadCtx->loginThreadContext.msgLogin, PM_REMOVE ) ) { ATLTRACE2("x RemoveMessagesFromLoginQueue: PeekMessage in cleanup retrieved message to log in.\n", GetCurrentThreadId()); pLoginCtx = reinterpret_cast<LOGIN_CONTEXT*>(msg.lParam); if(NULL != pLoginCtx) { delete pLoginCtx; pLoginCtx = NULL; } } // while PeekMessage while( PeekMessage( &msg, NULL, pThreadCtx->loginThreadContext.msgLogout, pThreadCtx->loginThreadContext.msgLogout, PM_REMOVE ) ) { ATLTRACE2("%x: RemoveMessagesFromLoginQueue: PeekMessage in cleanup retrieved message to log out.\n", GetCurrentThreadId()); // There is no context associated with a log-out message. } // while PeekMessage }
hsThread::ThreadId hsThread::GetMyThreadId() { return GetCurrentThreadId(); }
HRESULT ContentPartnerMessageLoop( CONTENT_PARTNER_THREAD_CONTEXT* pThreadCtx, CComPtr<IWMPContentPartnerCallback> spCallback) { MSG msg = {0}; HRESULT hr = S_OK; if(NULL == pThreadCtx || NULL == spCallback) { hr = E_UNEXPECTED; goto cleanup; } // Windows message loop while(TRUE) { BOOL ret = 0; // Suppose we have several messages (for example, // buy or download messages) in the queue, and then // the user closes Windows Media Player. We would like // to let Windows Media Player close without waiting for all // those queued messages to be processed. // // So we use the following strategy. // // Peek into the message queue to see if there is an exit message. // If there is an exit message anywhere in the queue, break out of // the message loop even though there might be several // messages remaining in the queue. if( PeekMessage( &msg, NULL, pThreadCtx->msgExitMessageLoop, pThreadCtx->msgExitMessageLoop, PM_REMOVE) ) { ATLTRACE2("%x: ContentPartnerMessageLoop(type &d): PeekMessage retrieved an exit message.\n", GetCurrentThreadId(), pThreadCtx->threadType); goto cleanup; } ret = GetMessage(&msg, 0, 0, 0); if(-1 == ret) { ATLTRACE2("%x: ContentPartnerMessageLoop(type %d): GetMessage failed (returned -1).\n", GetCurrentThreadId(), pThreadCtx->threadType); hr = HRESULT_FROM_WIN32(GetLastError()); goto cleanup; } if(pThreadCtx->msgExitMessageLoop == msg.message) { ATLTRACE2("%x: ContentPartnerMessageLoop(type %d): GetMessage retrieved an exit message.\n", GetCurrentThreadId(), pThreadCtx->threadType); break; // Break out of the message loop. } switch(pThreadCtx->threadType) { case ThreadTypeDownload: hr = HandleMessageForDownloadThread(&msg, pThreadCtx, spCallback); break; case ThreadTypeBuy: hr = HandleMessageForBuyThread(&msg, pThreadCtx, spCallback); break; case ThreadTypeRefreshLicense: hr = HandleMessageForRefreshLicenseThread(&msg, pThreadCtx, spCallback); break; case ThreadTypeLogin: hr = HandleMessageForLoginThread(&msg, pThreadCtx, spCallback); break; case ThreadTypeSendMessage: hr = HandleMessageForSendMessageThread(&msg, pThreadCtx, spCallback); break; case ThreadTypeUpdateDevice: hr = HandleMessageForUpdateDeviceThread(&msg, pThreadCtx, spCallback); break; case ThreadTypeList: hr = HandleMessageForListThread(&msg, pThreadCtx, spCallback); break; default: hr = E_UNEXPECTED; } // switch(threadType) if(FAILED(hr)) { goto cleanup; } } // while(TRUE) cleanup: if(NULL != pThreadCtx) { switch(pThreadCtx->threadType) { case ThreadTypeDownload: RemoveMessagesFromDownloadThreadQueue(pThreadCtx); break; case ThreadTypeBuy: RemoveMessagesFromDownloadThreadQueue(pThreadCtx); break; case ThreadTypeRefreshLicense: RemoveMessagesFromDownloadThreadQueue(pThreadCtx); break; case ThreadTypeLogin: RemoveMessagesFromDownloadThreadQueue(pThreadCtx); break; case ThreadTypeSendMessage: RemoveMessagesFromSendMessageThreadQueue(pThreadCtx); break; case ThreadTypeUpdateDevice: RemoveMessagesFromUpdateDeviceThreadQueue(pThreadCtx); break; case ThreadTypeList: RemoveMessagesFromListThreadQueue(pThreadCtx); break; } // switch(threadType) ATLTRACE2("%x: ContentPartnerMessageLoop(type %d): Returning %x.\n", GetCurrentThreadId(), pThreadCtx->threadType, hr); } return hr; } // ContentPartnerMessageLoop
inline spthread_t spthread_self() { return GetCurrentThreadId(); }
void WINAPI do_it(void) { HANDLE hc = NULL; UINT_PTR dwCaller = 0; #ifdef _LOGDEBUG if ( GetEnvironmentVariableA("APPDATA",logfile_buf,MAX_PATH) > 0 ) { strncat(logfile_buf,"\\",1); strncat(logfile_buf,LOG_FILE,strlen((LPCSTR)LOG_FILE)); } #endif if (!dll_module) { #ifdef __GNUC__ dwCaller = (UINT_PTR)__builtin_return_address(0); #else dwCaller = (UINT_PTR)_ReturnAddress(); #endif } if (dwCaller) { GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCWSTR)dwCaller, &dll_module); } if ( read_appint(L"General",L"SafeEx") > 0 ) { init_safed(NULL); } if ( read_appint(L"General", L"Portable") > 0 ) { env_thread = (HANDLE)_beginthreadex(NULL,0,&init_global_env,NULL,0,NULL); if (env_thread) { SetThreadPriority(env_thread,THREAD_PRIORITY_HIGHEST); init_portable(NULL); } } if ( is_browser() || is_thunderbird() ) { if ( read_appint(L"General",L"GdiBatchLimit") > 0 ) { hc = OpenThread(THREAD_ALL_ACCESS, 0, GetCurrentThreadId()); if (hc) { CloseHandle((HANDLE)_beginthreadex(NULL,0,&GdiSetLimit_tt,hc,0,NULL)); } } if ( read_appint(L"General",L"ProcessAffinityMask") > 0 ) { hc = OpenThread(THREAD_ALL_ACCESS, 0, GetCurrentThreadId()); if (hc) { CloseHandle((HANDLE)_beginthreadex(NULL,0,&SetCpuAffinity_tt,hc,0,NULL)); } } if ( read_appint(L"General",L"CreateCrashDump") > 0 ) { CloseHandle((HANDLE)_beginthreadex(NULL,0,&init_exeception,NULL,0,NULL)); } if ( read_appint(L"General", L"Bosskey") > 0 ) { CloseHandle((HANDLE)_beginthreadex(NULL,0,&bosskey_thread,&ff_info,0,NULL)); } CloseHandle((HANDLE)_beginthreadex(NULL,0,&SetPluginPath,NULL,0,NULL)); } }
/********************************************************************** * K32WOWCallback16Ex (KERNEL32.55) */ BOOL WINAPI K32WOWCallback16Ex( DWORD vpfn16, DWORD dwFlags, DWORD cbArgs, LPVOID pArgs, LPDWORD pdwRetCode ) { /* * Arguments must be prepared in the correct order by the caller * (both for PASCAL and CDECL calling convention), so we simply * copy them to the 16-bit stack ... */ char *stack = (char *)CURRENT_STACK16 - cbArgs; memcpy( stack, pArgs, cbArgs ); if (dwFlags & (WCB16_REGS|WCB16_REGS_LONG)) { CONTEXT *context = (CONTEXT *)pdwRetCode; if (TRACE_ON(relay)) { DWORD count = cbArgs / sizeof(WORD); WORD * wstack = (WORD *)stack; DPRINTF("%04x:CallTo16(func=%04x:%04x,ds=%04x", GetCurrentThreadId(), context->SegCs, LOWORD(context->Eip), context->SegDs ); while (count) DPRINTF( ",%04x", wstack[--count] ); DPRINTF(") ss:sp=%04x:%04x", SELECTOROF(NtCurrentTeb()->WOW32Reserved), OFFSETOF(NtCurrentTeb()->WOW32Reserved) ); DPRINTF(" ax=%04x bx=%04x cx=%04x dx=%04x si=%04x di=%04x bp=%04x es=%04x fs=%04x\n", (WORD)context->Eax, (WORD)context->Ebx, (WORD)context->Ecx, (WORD)context->Edx, (WORD)context->Esi, (WORD)context->Edi, (WORD)context->Ebp, (WORD)context->SegEs, (WORD)context->SegFs ); SYSLEVEL_CheckNotLevel( 2 ); } if (context->EFlags & 0x00020000) /* v86 mode */ { EXCEPTION_REGISTRATION_RECORD frame; frame.Handler = vm86_handler; errno = 0; __wine_push_frame( &frame ); __wine_enter_vm86( context ); __wine_pop_frame( &frame ); if (errno != 0) /* enter_vm86 will fall with ENOSYS on x64 kernels */ { WARN("__wine_enter_vm86 failed (errno=%d)\n", errno); if (errno == ENOSYS) SetLastError(ERROR_NOT_SUPPORTED); else SetLastError(ERROR_GEN_FAILURE); return FALSE; } } else { /* push return address */ if (dwFlags & WCB16_REGS_LONG) { stack -= sizeof(DWORD); *((DWORD *)stack) = HIWORD(call16_ret_addr); stack -= sizeof(DWORD); *((DWORD *)stack) = LOWORD(call16_ret_addr); cbArgs += 2 * sizeof(DWORD); } else { stack -= sizeof(SEGPTR); *((SEGPTR *)stack) = call16_ret_addr; cbArgs += sizeof(SEGPTR); } /* * Start call by checking for pending events. * Note that wine_call_to_16_regs overwrites context stack * pointer so we may modify it here without a problem. */ if (get_vm86_teb_info()->dpmi_vif) { context->SegSs = wine_get_ds(); context->Esp = (DWORD)stack; insert_event_check( context ); cbArgs += (DWORD)stack - context->Esp; } _EnterWin16Lock(); wine_call_to_16_regs( context, cbArgs, call16_handler ); _LeaveWin16Lock(); } if (TRACE_ON(relay)) { DPRINTF("%04x:RetFrom16() ss:sp=%04x:%04x ", GetCurrentThreadId(), SELECTOROF(NtCurrentTeb()->WOW32Reserved), OFFSETOF(NtCurrentTeb()->WOW32Reserved)); DPRINTF(" ax=%04x bx=%04x cx=%04x dx=%04x bp=%04x sp=%04x\n", (WORD)context->Eax, (WORD)context->Ebx, (WORD)context->Ecx, (WORD)context->Edx, (WORD)context->Ebp, (WORD)context->Esp ); SYSLEVEL_CheckNotLevel( 2 ); } } else { DWORD ret; if (TRACE_ON(relay)) { DWORD count = cbArgs / sizeof(WORD); WORD * wstack = (WORD *)stack; DPRINTF("%04x:CallTo16(func=%04x:%04x,ds=%04x", GetCurrentThreadId(), HIWORD(vpfn16), LOWORD(vpfn16), SELECTOROF(NtCurrentTeb()->WOW32Reserved) ); while (count) DPRINTF( ",%04x", wstack[--count] ); DPRINTF(") ss:sp=%04x:%04x\n", SELECTOROF(NtCurrentTeb()->WOW32Reserved), OFFSETOF(NtCurrentTeb()->WOW32Reserved) ); SYSLEVEL_CheckNotLevel( 2 ); } /* push return address */ stack -= sizeof(SEGPTR); *((SEGPTR *)stack) = call16_ret_addr; cbArgs += sizeof(SEGPTR); /* * Actually, we should take care whether the called routine cleans up * its stack or not. Fortunately, our wine_call_to_16 core doesn't rely on * the callee to do so; after the routine has returned, the 16-bit * stack pointer is always reset to the position it had before. */ _EnterWin16Lock(); ret = wine_call_to_16( (FARPROC16)vpfn16, cbArgs, call16_handler ); if (pdwRetCode) *pdwRetCode = ret; _LeaveWin16Lock(); if (TRACE_ON(relay)) { DPRINTF("%04x:RetFrom16() ss:sp=%04x:%04x retval=%08x\n", GetCurrentThreadId(), SELECTOROF(NtCurrentTeb()->WOW32Reserved), OFFSETOF(NtCurrentTeb()->WOW32Reserved), ret); SYSLEVEL_CheckNotLevel( 2 ); } } return TRUE; /* success */ }
///////////////////////////////////////////////////////////////////////////////////// // Called to interrupt a process that we didn't launch (and thus does not share our // console). Windows XP introduced the function 'DebugBreakProcess', which allows // a process to interrupt another process even if if the two do not share a console. // If we're running on 2000 or earlier, we have to resort to simulating a CTRL-C // in the console by firing keyboard events. This will work only if the process // has its own console. That means, e.g., the process should have been started at // the cmdline with 'start myprogram.exe' instead of 'myprogram.exe'. // // Arguments: // pid - process' pid // Return : 0 if OK or error code ///////////////////////////////////////////////////////////////////////////////////// int interruptProcess(int pid) { // See if DebugBreakProcess is available (XP and beyond) HMODULE hmod = LoadLibrary(L"Kernel32.dll"); if (hmod != NULL) { BOOL success = FALSE; FARPROC procaddr = GetProcAddress(hmod, "DebugBreakProcess"); if (procaddr != NULL) { HANDLE proc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid); if (proc != NULL) { DebugBreakProcessFunc pDebugBreakProcess = (DebugBreakProcessFunc)procaddr; success = (*pDebugBreakProcess)(proc); CloseHandle(proc); } } FreeLibrary(hmod); hmod = NULL; if (success) return 0; // 0 == OK; if not, try old-school way } #ifdef DEBUG_MONITOR _TCHAR buffer[1000]; #endif int rc = 0; consoleHWND = NULL; #ifdef DEBUG_MONITOR _stprintf(buffer, _T("Try to interrupt process %i\n"), pid); OutputDebugStringW(buffer); #endif // Find console EnumWindows (find_child_console, (LPARAM) pid); if(NULL != consoleHWND) // Yes, we found out it { // We are going to switch focus to console, // send Ctrl-C and then restore focus BYTE control_scan_code = (BYTE) MapVirtualKey (VK_CONTROL, 0); /* Fake Ctrl-C for SIGINT, and Ctrl-Break for SIGQUIT. */ BYTE vk_c_code = 'C'; BYTE vk_break_code = VK_CANCEL; BYTE c_scan_code = (BYTE) MapVirtualKey (vk_c_code, 0); BYTE break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0); HWND foreground_window; foreground_window = GetForegroundWindow (); if (foreground_window) { /* NT 5.0, and apparently also Windows 98, will not allow a Window to be set to foreground directly without the user's involvement. The workaround is to attach ourselves to the thread that owns the foreground window, since that is the only thread that can set the foreground window. */ DWORD foreground_thread, child_thread; foreground_thread = GetWindowThreadProcessId (foreground_window, NULL); if (foreground_thread == GetCurrentThreadId () || !AttachThreadInput (GetCurrentThreadId (), foreground_thread, TRUE)) foreground_thread = 0; child_thread = GetWindowThreadProcessId (consoleHWND, NULL); if (child_thread == GetCurrentThreadId () || !AttachThreadInput (GetCurrentThreadId (), child_thread, TRUE)) child_thread = 0; /* Set the foreground window to the child. */ if (SetForegroundWindow (consoleHWND)) { if(0 != break_scan_code) { /* Generate keystrokes as if user had typed Ctrl-Break */ keybd_event (VK_CONTROL, control_scan_code, 0, 0); keybd_event (vk_break_code, break_scan_code, KEYEVENTF_EXTENDEDKEY, 0); keybd_event (vk_break_code, break_scan_code, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0); keybd_event (VK_CONTROL, control_scan_code, KEYEVENTF_KEYUP, 0); } /* Sleep for a bit to give time for respond */ Sleep (100); SetForegroundWindow (foreground_window); } /* Detach from the foreground and child threads now that the foreground switching is over. */ if (foreground_thread) AttachThreadInput (GetCurrentThreadId (), foreground_thread, FALSE); if (child_thread) AttachThreadInput (GetCurrentThreadId (), child_thread, FALSE); #ifdef DEBUG_MONITOR _stprintf(buffer, _T("Sent Ctrl-C & Ctrl-Break to process %i\n"), pid); OutputDebugStringW(buffer); #endif } } #ifdef DEBUG_MONITOR else { _stprintf(buffer, _T("Cannot find console for process %i\n"), pid); OutputDebugStringW(buffer); } #endif return rc; }
static void s_serviceSetHBSig( void ) { #if defined( HB_OS_UNIX ) || defined( HB_OS_OS2_GCC ) struct sigaction act; #if defined( HB_THREAD_SUPPORT ) && ! defined( HB_OS_OS2 ) sigset_t blockall; /* set signal mask */ sigemptyset( &blockall ); sigaddset( &blockall, SIGHUP ); sigaddset( &blockall, SIGQUIT ); sigaddset( &blockall, SIGILL ); sigaddset( &blockall, SIGABRT ); sigaddset( &blockall, SIGFPE ); sigaddset( &blockall, SIGSEGV ); sigaddset( &blockall, SIGTERM ); sigaddset( &blockall, SIGUSR1 ); sigaddset( &blockall, SIGUSR2 ); sigaddset( &blockall, SIGHUP ); pthread_sigmask( SIG_SETMASK, &blockall, NULL ); #endif /* to avoid problems with differ sigaction structures and uninitialized fields */ memset( &act, 0, sizeof( act ) ); #if defined( HB_OS_OS2_GCC ) || defined( __WATCOMC__ ) act.sa_handler = s_signalHandler; #else /* using more descriptive sa_action instead of sa_handler */ act.sa_handler = NULL; /* if act.sa.. is a union, we just clean this */ act.sa_sigaction = s_signalHandler; /* this is what matters */ /* block al signals, we don't want to be interrupted. */ #if 0 sigfillset( &act.sa_mask ); #endif #endif #ifdef HB_OS_OS2_GCC act.sa_flags = SA_NOCLDSTOP; #else act.sa_flags = SA_NOCLDSTOP | SA_SIGINFO; #endif sigaction( SIGHUP, &act, NULL ); sigaction( SIGQUIT, &act, NULL ); sigaction( SIGILL, &act, NULL ); sigaction( SIGABRT, &act, NULL ); sigaction( SIGFPE, &act, NULL ); sigaction( SIGSEGV, &act, NULL ); sigaction( SIGTERM, &act, NULL ); sigaction( SIGUSR1, &act, NULL ); sigaction( SIGUSR2, &act, NULL ); /* IGNORE pipe */ signal( SIGPIPE, SIG_IGN ); #endif #ifdef HB_OS_WIN /* disable all os-level error boxes */ s_uiErrorMode = SetErrorMode( SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX ); SetUnhandledExceptionFilter( s_exceptionFilter ); s_hMsgHook = SetWindowsHookEx( WH_GETMESSAGE, ( HOOKPROC ) s_MsgFilterFunc, NULL, GetCurrentThreadId() ); SetConsoleCtrlHandler( s_ConsoleHandlerRoutine, TRUE ); #endif }
GIntBig CPLGetPID() { return (GIntBig) GetCurrentThreadId(); }
/* Manager of signals for windows */ static LONG s_signalHandler( int type, int sig, PEXCEPTION_RECORD exc ) { HB_SIZE nPos; HB_UINT uiSig; /* let's find the right signal handler. */ hb_threadEnterCriticalSectionGC( &s_ServiceMutex ); /* avoid working if PRG signal handling has been disabled */ if( ! s_bSignalEnabled ) { hb_threadLeaveCriticalSection( &s_ServiceMutex ); return EXCEPTION_EXECUTE_HANDLER; } s_bSignalEnabled = HB_FALSE; nPos = hb_arrayLen( s_pHooks ); /* subsig not necessary */ uiSig = ( HB_UINT ) s_translateSignal( ( HB_UINT ) type, ( HB_UINT ) sig ); while( nPos > 0 ) { PHB_ITEM pFunction; HB_UINT uiMask; pFunction = hb_arrayGetItemPtr( s_pHooks, nPos ); uiMask = ( HB_UINT ) hb_arrayGetNI( pFunction, 1 ); if( ( uiMask & uiSig ) == uiSig ) { PHB_ITEM pExecArray, pRet; int iRet; /* we don't unlock the mutex now, even if it is a little dangerous. But we are in a signal hander... for now just 2 parameters */ pExecArray = hb_itemArrayNew( 3 ); hb_arraySetForward( pExecArray, 1, hb_arrayGetItemPtr( pFunction, 2 ) ); hb_arraySetNI( pExecArray, 2, uiSig ); /* the third parameter is an array: * 1: low-level signal * 2: low-level subsignal * 3: low-level system error * 4: address that rised the signal * 5: process id of the signal riser * 6: UID of the riser */ pRet = hb_arrayGetItemPtr( pExecArray, 3 ); hb_arrayNew( pRet, 6 ); hb_arraySetNI( pRet, HB_SERVICE_OSSIGNAL, type ); hb_arraySetNI( pRet, HB_SERVICE_OSSUBSIG, sig ); /* could be meaningless, but does not matter here */ hb_arraySetNI( pRet, HB_SERVICE_OSERROR, GetLastError() ); if( type == 0 ) /* exception */ hb_arraySetPtr( pRet, HB_SERVICE_ADDRESS, ( void * ) exc->ExceptionAddress ); else hb_arraySetPtr( pRet, HB_SERVICE_ADDRESS, NULL ); /* TODO: */ hb_arraySetNI( pRet, HB_SERVICE_PROCESS, GetCurrentThreadId() ); /* TODO: */ hb_arraySetNI( pRet, HB_SERVICE_UID, 0 ); pRet = hb_itemDo( pExecArray, 0 ); iRet = hb_itemGetNI( pRet ); hb_itemRelease( pRet ); hb_itemRelease( pExecArray ); switch( iRet ) { case HB_SERVICE_HANDLED: s_bSignalEnabled = HB_TRUE; hb_threadLeaveCriticalSection( &s_ServiceMutex ); return EXCEPTION_CONTINUE_EXECUTION; case HB_SERVICE_QUIT: s_bSignalEnabled = HB_FALSE; hb_threadLeaveCriticalSection( &s_ServiceMutex ); hb_vmRequestQuit(); #ifndef HB_THREAD_SUPPORT hb_vmQuit(); exit( 0 ); #else hb_threadCancelInternal(); #endif } } nPos--; } s_bSignalEnabled = HB_TRUE; return EXCEPTION_EXECUTE_HANDLER; }
DWORD WINAPI WriteToDatabase( LPVOID lpParam ) { DWORD dwCount=0, dwWaitResult; DWORD time_out = 30; //time_out Milliseconds while WaitForSingleObject DWORD sleep_time = 29; //sleep_time Milliseconds while WritetoDatabase // Request ownership of mutex. while( dwCount < 10 ) { // dwWaitResult = WaitForSingleObject( // ghMutex, // handle to mutex // INFINITE); // no time-out interval dwWaitResult = WaitForSingleObject( ghMutex, // handle to mutex time_out); //wait for time_out Milliseconds // dwWaitResult = WaitForSingleObject( // ghMutex, // handle to mutex // IGNORE); //ignore switch (dwWaitResult) { // The thread got ownership of the mutex case WAIT_OBJECT_0: __try { // TODO: Write to the database printf("Thread %d writing to database...\n", GetCurrentThreadId()); dwCount++; Sleep (sleep_time); } __finally { // Release ownership of the mutex object if (! ReleaseMutex(ghMutex)) { // Deal with error. printf("Thread %d ReleaseMutex error!\n", GetCurrentThreadId ()); } } break; // The thread got ownership of the mutex time-out case WAIT_TIMEOUT: { // Deal with error. printf("Thread %d WaitForSingleObject time-out! dwWaitResult = 0X%08X\n", GetCurrentThreadId (),dwWaitResult); } break; // The thread got ownership of an abandoned mutex case WAIT_ABANDONED: { // Deal with error. printf("Thread %d got ownership of an abandoned mutex!\n", GetCurrentThreadId ()); } return FALSE; //The WaitForSingleObject function failed case WAIT_FAILED : { // Deal with error. printf("The WaitForSingleObject function failed!\n"); } return FALSE; default: break; } } return TRUE; }
//-------------------------------------------------------------------------------- void GameNetL2NEventDataFactory::createGameNetSendDataBufferPtr(GameNetSendDataBufferPtr& ptr, U32 buffSize) { NetSendDataBuffer* buffObj = NULL; std::deque<NetSendDataBuffer*>* idleList = NULL; GameNetSendDataBufferPool* pool = NULL; GameNetSendDataBufferPoolManager* poolMgr = NULL; DWORD threadId = GetCurrentThreadId(); poolMgr = createOrRetrieveGameNetSendDataBufferPoolManager( threadId ); if ( poolMgr ) { Bool isNormalBuff = true; pool = poolMgr->m_CreateObjectList; // 如果小于默认值, 则分配缓存等于默认值 if ( buffSize <= MG_GAME_NET_PACKET_NORMAL_MAX_SIZE ) { buffSize = MG_GAME_NET_PACKET_NORMAL_MAX_SIZE; isNormalBuff = true; }else if ( buffSize <= MG_GAME_NET_PACKET_BIG_MAX_SIZE ) { buffSize = MG_GAME_NET_PACKET_BIG_MAX_SIZE; isNormalBuff = false; }else { DYNAMIC_EEXCEPT_LOG("createGameNetSendDataBufferPtr : too long buffsize "); return; } pool->mPoolCs.lock(); { if ( isNormalBuff ) { idleList = &pool->m_IdleNormalObjectList; }else { idleList = &pool->m_IdleBigObjectList; } if ( idleList->size() > 0 ) { buffObj = idleList->back(); idleList->pop_back(); }else { buffObj = mDriverMgr->mMgr->createNetSendDataBuffer( buffSize ); } } pool->mPoolCs.unlock(); poolMgr->mCreateCount++; }else { DYNAMIC_EEXCEPT_LOG("createGameNetSendDataBufferPtr: not register thread !"); } if ( buffObj ) { buffObj->initialize(); buffObj->setActive( true ); ptr.setNull(); ptr.mFactory = this; ptr.mCreateThreadID = threadId; ptr.mNearestSendNetID = -1; ptr.mLogicDataMaxSize = buffSize; ptr.bind( buffObj ); if ( poolMgr ) { poolMgr->mNearestCreatePtr.setNull(); poolMgr->mNearestCreatePtr = ptr; } } }
//========================================================================= // Internal function: // // Suspend all threads in this process while trying to make sure that their // instruction pointer is not in the given range. //========================================================================= static BOOL SuspendOtherThreads(PBYTE pbCode, DWORD cbBytes) { BOOL bRet = FALSE; // make sure we're the most important thread in the process INT nOriginalPriority = GetThreadPriority(GetCurrentThread()); SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); // get a view of the threads in the system HANDLE hSnap = fnCreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, GetCurrentProcessId()); if (GOOD_HANDLE(hSnap)) { THREADENTRY32 te; te.dwSize = sizeof(te); // count threads in this process (except for ourselves) DWORD nThreadsInProcess = 0; if (fnThread32First(hSnap, &te)) { do { if (te.th32OwnerProcessID == GetCurrentProcessId()) { if (te.th32ThreadID != GetCurrentThreadId()) { nThreadsInProcess++; } } te.dwSize = sizeof(te); } while(fnThread32Next(hSnap, &te)); } ODPRINTF((L"mhooks: SuspendOtherThreads: counted %d other threads", nThreadsInProcess)); if (nThreadsInProcess) { // alloc buffer for the handles we really suspended g_hThreadHandles = (HANDLE*)malloc(nThreadsInProcess*sizeof(HANDLE)); if (g_hThreadHandles) { ZeroMemory(g_hThreadHandles, nThreadsInProcess*sizeof(HANDLE)); DWORD nCurrentThread = 0; BOOL bFailed = FALSE; te.dwSize = sizeof(te); // go through every thread if (fnThread32First(hSnap, &te)) { do { if (te.th32OwnerProcessID == GetCurrentProcessId()) { if (te.th32ThreadID != GetCurrentThreadId()) { // attempt to suspend it g_hThreadHandles[nCurrentThread] = SuspendOneThread(te.th32ThreadID, pbCode, cbBytes); if (GOOD_HANDLE(g_hThreadHandles[nCurrentThread])) { ODPRINTF((L"mhooks: SuspendOtherThreads: successfully suspended %d", te.th32ThreadID)); nCurrentThread++; } else { ODPRINTF((L"mhooks: SuspendOtherThreads: error while suspending thread %d: %d", te.th32ThreadID, gle())); // TODO: this might not be the wisest choice // but we can choose to ignore failures on // thread suspension. It's pretty unlikely that // we'll fail - and even if we do, the chances // of a thread's IP being in the wrong place // is pretty small. // bFailed = TRUE; } } } te.dwSize = sizeof(te); } while(fnThread32Next(hSnap, &te) && !bFailed); } g_nThreadHandles = nCurrentThread; bRet = !bFailed; } } CloseHandle(hSnap); //TODO: we might want to have another pass to make sure all threads // in the current process (including those that might have been // created since we took the original snapshot) have been // suspended. } else { ODPRINTF((L"mhooks: SuspendOtherThreads: can't CreateToolhelp32Snapshot: %d", gle())); } SetThreadPriority(GetCurrentThread(), nOriginalPriority); if (!bRet) { ODPRINTF((L"mhooks: SuspendOtherThreads: Had a problem (or not running multithreaded), resuming all threads.")); ResumeOtherThreads(); } return bRet; }
// Credit to NTAuthority LONG WINAPI DumpHandler::CustomUnhandledExceptionFilter(LPEXCEPTION_POINTERS ExceptionInfo) { // Ignore breakpoints. if (ExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT) return EXCEPTION_CONTINUE_EXECUTION; // Try skipping exceptions /* Disable that, it seems unsafe if ((ExceptionInfo->ExceptionRecord->ExceptionFlags & EXCEPTION_NONCONTINUABLE) != EXCEPTION_NONCONTINUABLE) { OutputDebugStringA(hString::va("New exception at 0x%X, try ignoring it...", ExceptionInfo->ExceptionRecord->ExceptionAddress)); ExceptionInfo->ExceptionRecord->ExceptionFlags |= EXCEPTION_NONCONTINUABLE; return EXCEPTION_CONTINUE_EXECUTION; } else { OutputDebugStringA("Ignoring failed. Handling it now..."); } */ // step 1: write minidump char error[1024]; char filename[MAX_PATH]; __time64_t time; tm* ltime; _time64(&time); ltime = _localtime64(&time); strftime(filename, sizeof(filename) - 1, "Redacted - %H-%M-%S %d.%m.%Y.dmp", ltime); _snprintf(error, sizeof(error) - 1, "A minidump has been written to %s.", filename); HANDLE hFile = CreateFile(filename, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile != INVALID_HANDLE_VALUE) { MINIDUMP_EXCEPTION_INFORMATION ex = { 0 }; ex.ThreadId = GetCurrentThreadId(); ex.ExceptionPointers = ExceptionInfo; ex.ClientPointers = FALSE; MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, MiniDumpNormal, &ex, NULL, NULL); CloseHandle(hFile); } else { _snprintf(error, sizeof(error) - 1, "An error (0x%x) occurred during creating %s.", GetLastError(), filename); } // step 2: exit the application // why was this removed? if (ExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW) { MessageBox(0, "Termination because of a stack overflow.", "ERROR", MB_ICONERROR); } else { MessageBox(0, hString::va("Fatal error (0x%08x) at 0x%08x.\n%s", ExceptionInfo->ExceptionRecord->ExceptionCode, ExceptionInfo->ExceptionRecord->ExceptionAddress, error), "ERROR", MB_ICONERROR); } TerminateProcess(GetCurrentProcess(), ExceptionInfo->ExceptionRecord->ExceptionCode); return 0; }
//--------------------------------------------------------------------------- //Recv接收请答包 bool JsdGateway::RecvAnswer(tagAnswerPacket *p_pAnswerPacket, bool singlerecord,int countOffset) { int iLen; int iPos; int iHeadLen; DWORD dwDataLen; char szTemp[DEF_SBUFLEN]; memset(m_pSingleRecvBuffer, 0, DEF_LBUFLEN_8192); TByteDynArray da; da.set_length(0); try { m_pSocket->Socket->ReadBytes(da,-1,true); } catch(...) { return false; } if (da.Length == 0) { return false; } const char *buf = (const char*)&da[0]; spliter sbuf(buf,da.Length,'|'); if(sbuf.at(0).length()==0 || sbuf.at(0)[0] != 'A') { return false; } // 包头取到后,判断序列号字段,以避免串户情况 char szReqPakSN[DEF_SBUFLEN]; sprintf(szReqPakSN,"%x:%x", GetCurrentThreadId(), m_dwReqPakSN); if (strcmp(szReqPakSN,sbuf.at(2).c_str())!=0) { //出现这种错误可能是因为错位,所以缓冲区内的数据全部清掉 return false; } if(sbuf[3].c_str()[0]=='N') { strcpy(p_pAnswerPacket->szRetMsg, sbuf[4].c_str()); strcpy(p_pAnswerPacket->szRetCode, sbuf[5].c_str()); return true; } else { memset(p_pAnswerPacket->szRetCode,0,DEF_SBUFLEN); } if(singlerecord) { p_pAnswerPacket->bIsNext = 0; m_iRecNo = 1; } else { if(p_pAnswerPacket->bIsNext==0) { m_iRecNo = atoi( sbuf[countOffset+2].c_str() )+1; //记录总数+首条记录 if(m_iRecNo<=0) { p_pAnswerPacket->bIsNext = 0; } else { p_pAnswerPacket->bIsNext = 1; } //return true; } } p_pAnswerPacket->iRecNum ++; if(p_pAnswerPacket->iRecNum==m_iRecNo) { //数据是否已满 p_pAnswerPacket->bIsNext = 0; } //处理数据结果 for(int i=0;i<(m_iFieldCount+3);i++) { _retData.push_back(sbuf[i]); } if(unsigned(p_pAnswerPacket->iRecNum*(m_iFieldCount+3))!=_retData.size()) { return false; } return TRUE; }
DWORD WINAPI Cadthread(LPVOID lpParam) { OSVERSIONINFO OSversion; OSversion.dwOSVersionInfoSize=sizeof(OSVERSIONINFO); GetVersionEx(&OSversion); HDESK desktop=NULL; desktop = OpenInputDesktop(0, FALSE, DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW | DESKTOP_ENUMERATE | DESKTOP_HOOKCONTROL | DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS | DESKTOP_SWITCHDESKTOP | GENERIC_WRITE ); if (desktop == NULL) vnclog.Print(LL_INTERR, VNCLOG("OpenInputdesktop Error \n")); else vnclog.Print(LL_INTERR, VNCLOG("OpenInputdesktop OK\n")); HDESK old_desktop = GetThreadDesktop(GetCurrentThreadId()); DWORD dummy; char new_name[256]; if (desktop) { if (!GetUserObjectInformation(desktop, UOI_NAME, &new_name, 256, &dummy)) { vnclog.Print(LL_INTERR, VNCLOG("!GetUserObjectInformation \n")); } vnclog.Print(LL_INTERR, VNCLOG("SelectHDESK to %s (%x) from %x\n"), new_name, desktop, old_desktop); if (!SetThreadDesktop(desktop)) { vnclog.Print(LL_INTERR, VNCLOG("SelectHDESK:!SetThreadDesktop \n")); } } ////// if(OSversion.dwMajorVersion>=6 && vncService::RunningAsService()) { /*if (OSversion.dwMinorVersion==0) //Vista { if (ISUACENabled() && !IsSoftwareCadEnabled())//ok { } if (!ISUACENabled() && IsSoftwareCadEnabled()) { } if (!ISUACENabled() && !IsSoftwareCadEnabled()) { DWORD result=MessageBoxSecure(NULL,"UAC is Disable, make registry changes to allow cad","Warning",MB_YESNO); if (result==IDYES) { HANDLE hProcess,hPToken; DWORD id=GetExplorerLogonPid(); if (id!=0) { hProcess = OpenProcess(MAXIMUM_ALLOWED,FALSE,id); if(!OpenProcessToken(hProcess,TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY |TOKEN_DUPLICATE|TOKEN_ASSIGN_PRIMARY|TOKEN_ADJUST_SESSIONID |TOKEN_READ|TOKEN_WRITE,&hPToken)) return 0; char dir[MAX_PATH]; char exe_file_name[MAX_PATH]; GetModuleFileName(0, exe_file_name, MAX_PATH); strcpy(dir, exe_file_name); strcat(dir, " -softwarecadhelper"); STARTUPINFO StartUPInfo; PROCESS_INFORMATION ProcessInfo; HANDLE Token=NULL; HANDLE process=NULL; ZeroMemory(&StartUPInfo,sizeof(STARTUPINFO)); ZeroMemory(&ProcessInfo,sizeof(PROCESS_INFORMATION)); StartUPInfo.wShowWindow = SW_SHOW; StartUPInfo.lpDesktop = "Winsta0\\Default"; StartUPInfo.cb = sizeof(STARTUPINFO); CreateProcessAsUser(hPToken,NULL,dir,NULL,NULL,FALSE,DETACHED_PROCESS,NULL,NULL,&StartUPInfo,&ProcessInfo); DWORD errorcode=GetLastError(); if (process) CloseHandle(process); if (Token) CloseHandle(Token); if (ProcessInfo.hProcess) CloseHandle(ProcessInfo.hProcess); if (ProcessInfo.hThread) CloseHandle(ProcessInfo.hThread); if (errorcode==1314) { Enable_softwareCAD_elevated(); } } } } if (ISUACENabled() && IsSoftwareCadEnabled()) { DWORD result=MessageBoxSecure(NULL,"UAC is Enablde, make registry changes to allow cad","Warning",MB_YESNO); if (result==IDYES) { HANDLE hProcess,hPToken; DWORD id=GetExplorerLogonPid(); if (id!=0) { hProcess = OpenProcess(MAXIMUM_ALLOWED,FALSE,id); if(!OpenProcessToken(hProcess,TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY |TOKEN_DUPLICATE|TOKEN_ASSIGN_PRIMARY|TOKEN_ADJUST_SESSIONID |TOKEN_READ|TOKEN_WRITE,&hPToken)) return 0; char dir[MAX_PATH]; char exe_file_name[MAX_PATH]; GetModuleFileName(0, exe_file_name, MAX_PATH); strcpy(dir, exe_file_name); strcat(dir, " -delsoftwarecadhelper"); STARTUPINFO StartUPInfo; PROCESS_INFORMATION ProcessInfo; HANDLE Token=NULL; HANDLE process=NULL; ZeroMemory(&StartUPInfo,sizeof(STARTUPINFO)); ZeroMemory(&ProcessInfo,sizeof(PROCESS_INFORMATION)); StartUPInfo.wShowWindow = SW_SHOW; StartUPInfo.lpDesktop = "Winsta0\\Default"; StartUPInfo.cb = sizeof(STARTUPINFO); CreateProcessAsUser(hPToken,NULL,dir,NULL,NULL,FALSE,DETACHED_PROCESS,NULL,NULL,&StartUPInfo,&ProcessInfo); DWORD errorcode=GetLastError(); if (process) CloseHandle(process); if (Token) CloseHandle(Token); if (ProcessInfo.hProcess) CloseHandle(ProcessInfo.hProcess); if (ProcessInfo.hThread) CloseHandle(ProcessInfo.hThread); if (errorcode==1314) { delete_softwareCAD_elevated(); } } } } } else*/ if( vncService::RunningAsService() &&!IsSoftwareCadEnabled()) { DWORD result=MessageBoxSecure(NULL,"UAC is Disable, make registry changes to allow cad","Warning",MB_YESNO); if (result==IDYES) { HANDLE hProcess,hPToken; DWORD id=GetExplorerLogonPid(); if (id!=0) { hProcess = OpenProcess(MAXIMUM_ALLOWED,FALSE,id); if(!OpenProcessToken(hProcess,TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY |TOKEN_DUPLICATE|TOKEN_ASSIGN_PRIMARY|TOKEN_ADJUST_SESSIONID |TOKEN_READ|TOKEN_WRITE,&hPToken)) return 0; char dir[MAX_PATH]; char exe_file_name[MAX_PATH]; GetModuleFileName(0, exe_file_name, MAX_PATH); strcpy(dir, exe_file_name); strcat(dir, " -softwarecadhelper"); STARTUPINFO StartUPInfo; PROCESS_INFORMATION ProcessInfo; HANDLE Token=NULL; HANDLE process=NULL; ZeroMemory(&StartUPInfo,sizeof(STARTUPINFO)); ZeroMemory(&ProcessInfo,sizeof(PROCESS_INFORMATION)); StartUPInfo.wShowWindow = SW_SHOW; StartUPInfo.lpDesktop = "Winsta0\\Default"; StartUPInfo.cb = sizeof(STARTUPINFO); CreateProcessAsUser(hPToken,NULL,dir,NULL,NULL,FALSE,DETACHED_PROCESS,NULL,NULL,&StartUPInfo,&ProcessInfo); DWORD errorcode=GetLastError(); if (process) CloseHandle(process); if (Token) CloseHandle(Token); if (ProcessInfo.hProcess) CloseHandle(ProcessInfo.hProcess); if (ProcessInfo.hThread) CloseHandle(ProcessInfo.hThread); if (errorcode==1314) { Enable_softwareCAD_elevated(); } } } } } ///////////////////// if(OSversion.dwMajorVersion==6)//&& OSversion.dwMinorVersion>=1) //win7 // test win7 +Vista { if (hShutdownEventcad==NULL ) hShutdownEventcad = OpenEvent(EVENT_MODIFY_STATE, FALSE, "Global\\SessionEventUltraCad"); if (hShutdownEventcad!=NULL ) SetEvent(hShutdownEventcad); if (old_desktop) SetThreadDesktop(old_desktop); if (desktop) CloseDesktop(desktop); return 0; } HKEY hKey; DWORD isLUAon = 0; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"), 0, KEY_READ, &hKey) == ERROR_SUCCESS) { DWORD LUAbufSize = 4; RegQueryValueEx(hKey, TEXT("EnableLUA"), NULL, NULL, (LPBYTE)&isLUAon, &LUAbufSize); RegCloseKey(hKey); } if (isLUAon != 1 && OSversion.dwMajorVersion==6) { if (hShutdownEventcad==NULL ) hShutdownEventcad = OpenEvent(EVENT_MODIFY_STATE, FALSE, "Global\\SessionEventUltraCad"); if (hShutdownEventcad!=NULL ) SetEvent(hShutdownEventcad); if (old_desktop) SetThreadDesktop(old_desktop); if (desktop) CloseDesktop(desktop); return 0; } //Full path needed, sometimes it just default to system32 char WORKDIR[MAX_PATH]; char mycommand[MAX_PATH]; if (GetModuleFileName(NULL, WORKDIR, MAX_PATH)) { char* p = strrchr(WORKDIR, '\\'); if (p == NULL) return 0; *p = '\0'; } strcpy(mycommand,""); strcat(mycommand,WORKDIR);//set the directory strcat(mycommand,"\\"); strcat(mycommand,"cad.exe"); int nr=(LONG_PTR)ShellExecute(GetDesktopWindow(), "open", mycommand, "", 0, SW_SHOWNORMAL); if (nr<=32) { //error // if ( nr==SE_ERR_ACCESSDENIED ) vncTimedMsgBox::Do( sz_ID_CADPERMISSION, sz_ID_ULTRAVNC_WARNING, MB_ICONINFORMATION | MB_OK ); if ( nr==ERROR_PATH_NOT_FOUND || nr==ERROR_FILE_NOT_FOUND) vncTimedMsgBox::Do( sz_ID_CADERRORFILE, sz_ID_ULTRAVNC_WARNING, MB_ICONINFORMATION | MB_OK ); } if (old_desktop) SetThreadDesktop(old_desktop); if (desktop) CloseDesktop(desktop); return 0; }
//=========================================================== // Entry point where control comes on an unhandled exception //=========================================================== LONG WINAPI WheatyExceptionReport::WheatyUnhandledExceptionFilter( PEXCEPTION_POINTERS pExceptionInfo) { TCHAR module_folder_name[MAX_PATH]; GetModuleFileName(0, module_folder_name, MAX_PATH); TCHAR* pos = _tcsrchr(module_folder_name, '\\'); if (!pos) return 0; pos[0] = '\0'; ++pos; TCHAR crash_folder_path[MAX_PATH]; sprintf(crash_folder_path, "%s\\%s", module_folder_name, CrashFolder); if (!CreateDirectory(crash_folder_path, NULL)) { if (GetLastError() != ERROR_ALREADY_EXISTS) return 0; } SYSTEMTIME systime; GetLocalTime(&systime); sprintf(m_szDumpFileName, "%s\\%s_%s_[%u-%u_%u-%u-%u].dmp", crash_folder_path, _HASH, pos, systime.wDay, systime.wMonth, systime.wHour, systime.wMinute, systime.wSecond); sprintf(m_szLogFileName, "%s\\%s_%s_[%u-%u_%u-%u-%u].txt", crash_folder_path, _HASH, pos, systime.wDay, systime.wMonth, systime.wHour, systime.wMinute, systime.wSecond); m_hDumpFile = CreateFile(m_szDumpFileName, GENERIC_WRITE, 0, 0, OPEN_ALWAYS, FILE_FLAG_WRITE_THROUGH, 0); m_hReportFile = CreateFile(m_szLogFileName, GENERIC_WRITE, 0, 0, OPEN_ALWAYS, FILE_FLAG_WRITE_THROUGH, 0); if (m_hDumpFile) { MINIDUMP_EXCEPTION_INFORMATION info; info.ClientPointers = FALSE; info.ExceptionPointers = pExceptionInfo; info.ThreadId = GetCurrentThreadId(); MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), m_hDumpFile, MiniDumpWithIndirectlyReferencedMemory, &info, 0, 0); CloseHandle(m_hDumpFile); } if (m_hReportFile) { SetFilePointer(m_hReportFile, 0, 0, FILE_END); GenerateExceptionReport(pExceptionInfo); CloseHandle(m_hReportFile); m_hReportFile = 0; } if (m_previousFilter) return m_previousFilter(pExceptionInfo); else return EXCEPTION_EXECUTE_HANDLER/*EXCEPTION_CONTINUE_SEARCH*/; }
void RNG_SystemInfoForRNG(void) { DWORD dwVal; char buffer[256]; int nBytes; MEMORYSTATUS sMem; HANDLE hVal; #if !defined(_WIN32_WCE) DWORD dwSerialNum; DWORD dwComponentLen; DWORD dwSysFlags; char volName[128]; DWORD dwSectors, dwBytes, dwFreeClusters, dwNumClusters; #endif nBytes = RNG_GetNoise(buffer, 20); // get up to 20 bytes RNG_RandomUpdate(buffer, nBytes); sMem.dwLength = sizeof(sMem); GlobalMemoryStatus(&sMem); // assorted memory stats RNG_RandomUpdate(&sMem, sizeof(sMem)); #if !defined(_WIN32_WCE) dwVal = GetLogicalDrives(); RNG_RandomUpdate(&dwVal, sizeof(dwVal)); // bitfields in bits 0-25 #endif #if !defined(_WIN32_WCE) dwVal = sizeof(buffer); if (GetComputerName(buffer, &dwVal)) RNG_RandomUpdate(buffer, dwVal); #endif hVal = GetCurrentProcess(); // 4 or 8 byte pseudo handle (a // constant!) of current process RNG_RandomUpdate(&hVal, sizeof(hVal)); dwVal = GetCurrentProcessId(); // process ID (4 bytes) RNG_RandomUpdate(&dwVal, sizeof(dwVal)); dwVal = GetCurrentThreadId(); // thread ID (4 bytes) RNG_RandomUpdate(&dwVal, sizeof(dwVal)); #if !defined(_WIN32_WCE) volName[0] = '\0'; buffer[0] = '\0'; GetVolumeInformation(NULL, volName, sizeof(volName), &dwSerialNum, &dwComponentLen, &dwSysFlags, buffer, sizeof(buffer)); RNG_RandomUpdate(volName, strlen(volName)); RNG_RandomUpdate(&dwSerialNum, sizeof(dwSerialNum)); RNG_RandomUpdate(&dwComponentLen, sizeof(dwComponentLen)); RNG_RandomUpdate(&dwSysFlags, sizeof(dwSysFlags)); RNG_RandomUpdate(buffer, strlen(buffer)); if (GetDiskFreeSpace(NULL, &dwSectors, &dwBytes, &dwFreeClusters, &dwNumClusters)) { RNG_RandomUpdate(&dwSectors, sizeof(dwSectors)); RNG_RandomUpdate(&dwBytes, sizeof(dwBytes)); RNG_RandomUpdate(&dwFreeClusters, sizeof(dwFreeClusters)); RNG_RandomUpdate(&dwNumClusters, sizeof(dwNumClusters)); } #endif // Skip the potentially slow file scanning if the OS's PRNG worked. if (!usedWindowsPRNG) ReadSystemFiles(); nBytes = RNG_GetNoise(buffer, 20); // get up to 20 bytes RNG_RandomUpdate(buffer, nBytes); }
void fn004012F8(word32 edx, word32 ebp, word32 dwArg00, word32 dwArg01, word32 dwArg05, word32 dwArg0B) { // def fp // def dwArg00 // def dwArg01 // def dwLoc0120 // def dwLocB8 // def dwLoc0180 // def dwLoc03 // def dwLoc0154 // def dwLoc01B4 // def dwArg0B // def dwLoc010E // def dwLoc0118 // def dwLoc4C // def dwLoc8C // def dwLoc0234 // def dwLocBD // def dwLocC3 // def dwLoc0225 // def dwLoc021C // def dwLoc0227 // def dwLoc0140 // def dwArg05 eax_7 = GetCurrentProcessId(); if (eax_7 != 0x000003FB) ; dwLoc0268_28 = fp - 0x00000004; v15_29 = fp - 0x00000098; dwLoc0268_30 = fp - 0x00000098; CharUpperA(fp - 0x00000098); ecx_36 = &fp->dwFFFFFD98; dwLoc0268_38 = &fp->dwFFFFFD98; dwLoc026C_41 = 0x00000000; dwLoc0270_43.u0 = 0x00000000; OpenEventW(0x00000000, 0x00000000, &fp->dwFFFFFD98); dwLoc0268_52 = 0x00000000; GetDC(0x00000000); eax_55 = GetCurrentThreadId(); if (eax_55 == 0x0000026D) ecx_595 = &fp->dwFFFFFD98 ^ dwArg05; // ecx_64 = PHI(ecx_36, ecx_595) esp_68 = fp - 0x00000268; fp->dwFFFFFD98 = 0x00000002; if (ecx_64 != 0x00000000) ; __set_app_type(); dwLoc026C_85 = fp - 0x00000004; v20_86 = fp - 0x000000B4; dwLoc026C_87 = fp - 0x000000B4; GetFileAttributesA(fp - 0x000000B4); dwLoc026C_92 = &fp->dwFFFFFD98; CharUpperA(&fp->dwFFFFFD98); GetProcessHeap(); dwLoc026C_98 = &fp->dwFFFFFD98; eax_99 = CharUpperA(&fp->dwFFFFFD98); dwLoc026C_107 = &fp->dwFFFFFD98; esp_108 = &fp->tFFFFFD90; fp->tFFFFFD90.u0 = 0x00000000; eax_110 = eax_99 & 0x00000008; dwLoc0274_112 = eax_99 & 0x00000008; eax_113 = OpenMutexA(eax_99 & 0x00000008, 0x00000000, &fp->dwFFFFFD98); ecx_115 = &fp->dwFFFFFD98 & 0x0000011C; eax_118 = eax_113 - dwArg00; ecx_120 = ecx_115 - dwArg01; dwLoc026C_122 = eax_118; IsWindow(eax_118); v22_126 = dwLoc0120 - (fp - 0x00000004); dwLoc0120_127 = v22_126; edx_128 = fp - 0x00000004 ^ 0x00000611; eax_129 = GetCurrentThreadId(); eax_130 = eax_129 & 0x00000AE4; if ((eax_129 & 0x00000AE4) != ecx_120) { edx_564 = edx_128 | ecx_120; ecx_566 = ecx_120 | dwLoc0140; v25_570 = dwLocB8 + ecx_566; dwLocB8_571 = v25_570; ecx_572 = fp - 0x00000004; } // dwLocB8_142 = PHI(dwLocB8, dwLocB8_571) // ecx_143 = PHI(ecx_120, ecx_572) // edx_144 = PHI(edx_128, edx_564) dwLoc026C_148 = fp - 0x00000004; v26_149 = fp - 0x00000060; dwLoc026C_150 = fp - 0x00000060; esp_151 = &fp->tFFFFFD90; fp->tFFFFFD90.u0 = 0x00000000; eax_153 = GetClientRect(0x00000000, fp - 0x00000060); eax_156 = eax_153 | dwLoc0180; if (eax_156 != edx_144) { eax_552 = &fp->dwFFFFFD98; edx_556 = edx_144 ^ dwLoc0225; edx_558 = edx_556 ^ dwLoc021C; edx_560 = edx_558 & dwLoc0227; } // edx_165 = PHI(edx_144, edx_560) // eax_166 = PHI(eax_156, eax_552) edx_169 = edx_165 ^ 0x000021CD; SCZO_170 = cond(eax_166 - edx_169); C_173 = SCZO_170; if (eax_166 != edx_169) { edx_534 = edx_169 * 0x00000002 + (eax_166 <u edx_169); ecx_535 = ecx_143 + v22_126; eax_542 = eax_166 - 0x00003421; SCZO_545 = cond(eax_542); C_548 = SCZO_545; } // ecx_179 = PHI(ecx_143, ecx_535) // edx_180 = PHI(edx_169, edx_534) // eax_181 = PHI(eax_166, eax_542) // C_182 = PHI(C_173, C_548) esp_183 = &fp->tFFFFFD90; fp->tFFFFFD90.u0 = 0x00000000; eax_185 = eax_181 + edx_180 + C_182; if (eax_185 == 0x00000330) { edx_530 = edx_180 ^ 0x00001DF0; ecx_531 = ecx_179 - 0x0000292F; } // ecx_193 = PHI(ecx_179, ecx_531) // edx_194 = PHI(edx_180, edx_530) dwLoc0274_197 = 0x00000000; eax_198 = CreateItemMoniker(0x00000000, 0x00000000, null); eax_200 = eax_198 ^ 0x80070057; if ((eax_198 ^ 0x80070057) == 0x00000000) { eax_271 = (eax_198 ^ 0x80070057) + edx_194; if (eax_271 == 0x00000000) { edx_521 = &fp->dwFFFFFD98; eax_522 = eax_271 - dwLocB8_142; ecx_525 = ecx_193 & dwLocBD; ecx_527 = ecx_525 - dwLocC3; } // ecx_278 = PHI(ecx_193, ecx_527) // edx_279 = PHI(edx_194, edx_521) // eax_280 = PHI(eax_271, eax_522) esp_281 = &fp->dwFFFFFD94; fp->dwFFFFFD94 = eax_280; esp_283 = &fp->tFFFFFD90; fp->tFFFFFD90 = ecx_278; esp_285 = &fp->dwFFFFFD8C; fp->dwFFFFFD8C = edx_279; ecx_299 = ecx_278 & 0x00002F37; ecx_305 = ecx_299 + dwLoc03; if (fp - 0x00000004 != ecx_305) ecx_508 = &fp->dwFFFFFD98; // ecx_316 = PHI(ecx_305, ecx_508) if (ecx_316 != 0x00000000) ; dwLoc0294_329 = 0x00002000; dwLoc0298_334 = 0x00000000; eax_337 = VirtualAlloc(0x00000000, 0x00002000, 0x00001000, 0x00000040); dwLoc0218_340 = eax_337; if (dwLoc0154 == ecx_316) { ecx_487 = ecx_316 + 0x00001D56; ecx_491 = ecx_487 ^ 0x00002863; } // ecx_350 = PHI(ecx_316, ecx_491) ecx_354 = ecx_350 - dwLoc01B4; ecx_358 = ecx_354 | dwArg0B; eax_361 = fp - 0x00000004 ^ dwLoc010E; eax_363 = eax_361 + dwLoc0118; edi_365 = &globals->dw412E33; ecx_366 = ecx_358 + eax_363; esi_367 = eax_337; edx_370 = fp + 0xFFFFDB3F; dwLoc68_371 = 0xA37A6ED7; ecx_372 = ecx_366 - 0x000028C3; if (ecx_366 != 0x000028C3) { ecx_475 = ecx_366 - 0x000028C3 | 0x000028C3; goto l00401606; } l00401606: do { // dwLoc68_378 = PHI(dwLoc68_371, dwLoc68_371, dwLoc68_393) // edi_382 = PHI(edi_365, edi_365, edi_413) // esi_383 = PHI(esi_367, esi_367, esi_415) // ecx_384 = PHI(ecx_372, ecx_475, ecx_402) // edx_385 = PHI(edx_370, edx_370, edx_414) // eax_386 = PHI(eax_363, eax_363, eax_424) ebx_388 = *edi_382; ecx_390 = ecx_384 ^ dwLoc4C; ebx_391 = ebx_388 + dwLoc68_378; v44_392 = dwLoc68_378 + 0x623ED7F6; dwLoc68_393 = v44_392; ecx_394 = ecx_390 & edx_385; C_395 = false; edx_396 = edx_385 - eax_386; Mem397[esi_383 + 0x00000000:word32] = ebx_391; eax_398 = eax_386 | 0x00002279; edi_400 = edi_382 + 20138706; ecx_402 = ecx_394 - dwLoc8C; esi_404 = esi_383 + 0xA596E2A8; if (eax_398 == 0x000003EF) { eax_466 = eax_398 | 0x000038A7; edx_468 = &fp->dwFFFFFD98 - ecx_402; eax_469 = (eax_398 | 0x000038A7) & 0x00003565; } // edx_410 = PHI(edx_396, edx_468) // eax_412 = PHI(eax_398, eax_469) edi_413 = edi_400 + 0x04CD2B4C; edx_414 = edx_410 + 0x00003BBE; esi_415 = esi_404 + 0x5A691D5C; if ((dwLoc0234 & ecx_402) != 0x00000000) eax_461 = eax_412 ^ 0x000034ED; // eax_424 = PHI(eax_412, eax_461) } while (edi_413 != &globals->dw413EBF); dwLoc0218_340(); if (eax_424 == edx_414) ; }
Thread::ID ThreadWindows::get_thread_id_func_windows() { return (ID)GetCurrentThreadId(); //must implement }
DWORD WINAPI ContentPartnerThreadProc(LPVOID lpParameter) { CONTENT_PARTNER_THREAD_CONTEXT* pThreadCtx = NULL; CComPtr<IWMPContentPartnerCallback> spCallback; MSG msg = {0}; HRESULT hr = S_OK; BOOL comInitialized = FALSE; if(NULL == lpParameter) { hr = E_INVALIDARG; goto cleanup; } pThreadCtx = static_cast<CONTENT_PARTNER_THREAD_CONTEXT*>(lpParameter); if(NULL == pThreadCtx->pIStream) { hr = E_INVALIDARG; goto cleanup; } hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); if(FAILED(hr)) { ATLTRACE2("%x: ContentPartnerThreadProc(type %d): CoInitializeEx failed. %x\n", GetCurrentThreadId(), pThreadCtx->threadType, hr); goto cleanup; } comInitialized = TRUE; // Get a pointer to an IWMPContentPartnerCallback interface. hr = CoGetInterfaceAndReleaseStream( pThreadCtx->pIStream, __uuidof(IWMPContentPartnerCallback), reinterpret_cast<LPVOID*>(&spCallback) ); // The stream was released (even if CoGetInterfaceAndReleaseStream failed). // Set the stream pointer to NULL. pThreadCtx->pIStream = NULL; if(FAILED(hr)) { ATLTRACE2("%x: ContentPartnerThreadProc(type %d): Failed to get IWMPContentPartnerCallback interface. %x\n", GetCurrentThreadId(), pThreadCtx->threadType, hr); goto cleanup; } if(NULL == spCallback) { hr = E_UNEXPECTED; goto cleanup; } ATLTRACE2("%x: ContentPartnerThreadProc(type %d): Succeeded in getting IWMPContentPartnerCallback interface.\n", GetCurrentThreadId(), pThreadCtx->threadType); // Make sure we have a message queue. PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE); // Tell the main thread that we are ready to receive messages. SetEvent(pThreadCtx->hInitialized); hr = ContentPartnerMessageLoop(pThreadCtx, spCallback); cleanup: if(NULL != pThreadCtx) { // Set this event here, just in case there was a "goto cleanup" // before the event was set. SetEvent(pThreadCtx->hInitialized); // The thread that started this thread allocated a // CONTENT_PARTNER_THREAD_CONTEXT structure. // We must free that memory here. if(NULL != pThreadCtx->pIStream) { // For some reason, CoGetInterfaceAndReleaseStream never got called. // So release the stream here. pThreadCtx->pIStream->Release(); pThreadCtx->pIStream = NULL; } ATLTRACE2("%x: ContentPartnerThreadProc(type %d): Returning %x\n", GetCurrentThreadId(), pThreadCtx->threadType, hr); delete pThreadCtx; pThreadCtx = NULL; } if(comInitialized) { CoUninitialize(); } return hr; }
MonoNativeThreadId mono_native_thread_id_get (void) { return GetCurrentThreadId (); }
VOID RemoveMessagesFromDownloadThreadQueue(CONTENT_PARTNER_THREAD_CONTEXT* pThreadCtx) { DOWNLOAD_BATCH_CONTEXT* pBatchCtx = NULL; MSG msg = {0}; while( PeekMessage( &msg, NULL, pThreadCtx->downloadThreadContext.msgDownloadBatch, pThreadCtx->downloadThreadContext.msgDownloadBatch, PM_REMOVE ) ) { ATLTRACE2("%x: RemoveMessagesFromDownloadThreadQueue: PeekMessage in cleanup retrieved message to download a batch.\n", GetCurrentThreadId()); pBatchCtx = reinterpret_cast<DOWNLOAD_BATCH_CONTEXT*>(msg.lParam); if(NULL != pBatchCtx) { if(NULL != pBatchCtx->pIStream) { pBatchCtx->pIStream->Release(); pBatchCtx->pIStream = NULL; } delete pBatchCtx; pBatchCtx = NULL; } } // while PeekMessage }
THREAD_ID CvThreadCurrent::GetId() { return GetCurrentThreadId(); }
VOID RemoveMessagesFromRefreshLicenseThreadQueue(CONTENT_PARTNER_THREAD_CONTEXT* pThreadCtx) { REFRESH_LICENSE_CONTEXT* pRefLicCtx = NULL; MSG msg = {0}; while( PeekMessage( &msg, NULL, pThreadCtx->refreshLicenseThreadContext.msgRefreshLicense, pThreadCtx->refreshLicenseThreadContext.msgRefreshLicense, PM_REMOVE ) ) { ATLTRACE2("%x: RemoveMessagesFromRefreshLicenseThreadQueue: PeekMessage in cleanup retrieved message to refresh a license.\n", GetCurrentThreadId()); pRefLicCtx = reinterpret_cast<REFRESH_LICENSE_CONTEXT*>(msg.lParam); if(NULL != pRefLicCtx) { delete pRefLicCtx; pRefLicCtx = NULL; } } // while PeekMessage }
static PyObject * semlock_acquire(SemLockObject *self, PyObject *args, PyObject *kwds) { int blocking = 1; double timeout; PyObject *timeout_obj = Py_None; DWORD res, full_msecs, nhandles; HANDLE handles[2], sigint_event; static char *kwlist[] = {"block", "timeout", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist, &blocking, &timeout_obj)) return NULL; /* calculate timeout */ if (!blocking) { full_msecs = 0; } else if (timeout_obj == Py_None) { full_msecs = INFINITE; } else { timeout = PyFloat_AsDouble(timeout_obj); if (PyErr_Occurred()) return NULL; timeout *= 1000.0; /* convert to millisecs */ if (timeout < 0.0) { timeout = 0.0; } else if (timeout >= 0.5 * INFINITE) { /* 25 days */ PyErr_SetString(PyExc_OverflowError, "timeout is too large"); return NULL; } full_msecs = (DWORD)(timeout + 0.5); } /* check whether we already own the lock */ if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) { ++self->count; Py_RETURN_TRUE; } /* check whether we can acquire without releasing the GIL and blocking */ if (WaitForSingleObjectEx(self->handle, 0, FALSE) == WAIT_OBJECT_0) { self->last_tid = GetCurrentThreadId(); ++self->count; Py_RETURN_TRUE; } /* prepare list of handles */ nhandles = 0; handles[nhandles++] = self->handle; if (_PyOS_IsMainThread()) { sigint_event = _PyOS_SigintEvent(); assert(sigint_event != NULL); handles[nhandles++] = sigint_event; } else { sigint_event = NULL; } /* do the wait */ Py_BEGIN_ALLOW_THREADS if (sigint_event != NULL) ResetEvent(sigint_event); res = WaitForMultipleObjectsEx(nhandles, handles, FALSE, full_msecs, FALSE); Py_END_ALLOW_THREADS /* handle result */ switch (res) { case WAIT_TIMEOUT: Py_RETURN_FALSE; case WAIT_OBJECT_0 + 0: self->last_tid = GetCurrentThreadId(); ++self->count; Py_RETURN_TRUE; case WAIT_OBJECT_0 + 1: errno = EINTR; return PyErr_SetFromErrno(PyExc_IOError); case WAIT_FAILED: return PyErr_SetFromWindowsErr(0); default: PyErr_Format(PyExc_RuntimeError, "WaitForSingleObject() or " "WaitForMultipleObjects() gave unrecognized " "value %d", res); return NULL; } }
VOID RemoveMessagesFromSendMessageThreadQueue(CONTENT_PARTNER_THREAD_CONTEXT* pThreadCtx) { SEND_MESSAGE_CONTEXT* pSendMsgCtx = NULL; MSG msg = {0}; while( PeekMessage( &msg, NULL, pThreadCtx->sendMessageThreadContext.msgSendMessage, pThreadCtx->sendMessageThreadContext.msgSendMessage, PM_REMOVE ) ) { ATLTRACE2("%x: RemoveMessagesFromSendMessageThreadQueue: PeekMessage in cleanup retrieved a send-message message.\n", GetCurrentThreadId()); pSendMsgCtx = reinterpret_cast<SEND_MESSAGE_CONTEXT*>(msg.lParam); if(NULL != pSendMsgCtx) { SysFreeString(pSendMsgCtx->bstrMsg); // OK to pass NULL. SysFreeString(pSendMsgCtx->bstrParam); delete pSendMsgCtx; pSendMsgCtx = NULL; } } // while PeekMessage }
int qemu_get_thread_id(void) { return GetCurrentThreadId(); }