Exemple #1
0
void Platform::EnumerateProcesses(
    bool allUsers, UserId const &uid,
    std::function<void(ProcessInfo const &info)> const &cb) {
  std::vector<DWORD> processes;
  DWORD bytesReturned;

  processes.resize(32);

  do {
    processes.resize(2 * processes.size());
    int rc = EnumProcesses(processes.data(), processes.size() * sizeof(DWORD),
                           &bytesReturned);
    if (!rc)
      return;
  } while (bytesReturned == processes.size() * sizeof(DWORD));
  processes.resize(bytesReturned / sizeof(DWORD));

  for (auto const &e : processes) {
    ProcessInfo info;

    if (!GetProcessInfo(e, info))
      continue;

    cb(info);
  }
}
Exemple #2
0
BOOL StartProgram( LPCTSTR pszCommandLine, int nShowWindow )
{
	CString strCommandLine = pszCommandLine;
	PROCESS_INFORMATION pi;
	ZeroMemory( &pi, sizeof(pi) );
	STARTUPINFO si;
	ZeroMemory( &si, sizeof(si) );
	si.cb = sizeof(si);
	si.dwFlags = STARTF_USESHOWWINDOW;
	si.wShowWindow = nShowWindow;

	SetLastError( ERROR_SUCCESS );
	BOOL res = CreateProcess( NULL, strCommandLine.GetBuffer(strCommandLine.GetLength()+1),
		NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi );
	LONG err = GetLastError();
	strCommandLine.ReleaseBuffer();

	if( !res || err != ERROR_SUCCESS )
	{
		TRACE( _T("Can't start process (err=%d, 0x%X): \"%s\", %s, %s"),
			err, err, strCommandLine,
			(res ? _T("OK") : _T("Error") ),
			GetProcessInfo( pi.hProcess ) );
	}

	if( res )
	{
		CloseHandle(pi.hThread);
		CloseHandle(pi.hProcess);
	}

	return res;
}
Exemple #3
0
void CConEmuInside::SetInsideParentWND(HWND hParent)
{
	mh_InsideParentWND = hParent;

	if (!hParent || (hParent == INSIDE_PARENT_NOT_FOUND))
	{
		mh_InsideParentRel = NULL;
	}
	else
	{
		ZeroStruct(m_InsideParentInfo);

		// Store basic information about parent process (reporting purposes)
		DWORD nPID = 0;
		if (GetWindowThreadProcessId(hParent, &nPID))
		{
			m_InsideParentInfo.ParentPID = nPID;

			PROCESSENTRY32W PInfo = {};
			if (GetProcessInfo(nPID, &PInfo))
			{
				m_InsideParentInfo.ParentParentPID = PInfo.th32ParentProcessID;
				wcscpy_c(m_InsideParentInfo.ExeName, PInfo.szExeFile);
			}
		}

		mh_InitialRoot = GetParentRoot();
	}
}
Exemple #4
0
//------------------------------------------------------
//  WndEnumCallBak - Функция обработки найденного окна
//------------------------------------------------------
BOOL CALLBACK INJECTOR::WndEnumCallBak(HWND Wnd, LPARAM Param)
{
	// Окно должно быть видимым и не иметь владельца
	if (pIsWindowVisible(Wnd) && !pGetWindow(Wnd, GW_OWNER))
	{
		// Получаем пид пресса которому принадлежит окно
		DWORD PID = 0;
		pGetWindowThreadProcessId(Wnd, &PID);
		if (PID)
		{
			PInjector Injector = (PInjector)Param;


			TProcessInfo Info;
			if (GetProcessInfo(Injector, PID, Info))
			{
				// Проверяем необходимость инжекта
				// Разрешаем инжект в 32 разрядной винде или в 32 разрядные процессы
				Inject(Injector, &Info);
			}

		}
    }

	return TRUE;
}
Exemple #5
0
void INJECTOR::InjectInChildProcesses(PInjector Injector, PProcessInfo Parent)
{
	// Функция инжектится в дочерние процессы
	// и параллельно роверяем список обработанных процессов
	PROCESSENTRY32 pe;
	pe.dwSize = sizeof(pe);
	HANDLE Snap = (HANDLE)pCreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0);
	if (Snap != INVALID_HANDLE_VALUE)
	{
		if (pProcess32First(Snap, &pe))
		{
			do
			{
				if (pe.th32ParentProcessID == Parent->PID)
				{
					TProcessInfo Info;
					if (GetProcessInfo(Injector, pe.th32ProcessID, Info))
						Inject(Injector, &Info);
				}

			} while( pProcess32Next(Snap, &pe ) );
		}
		pCloseHandle(Snap);
    }
 }
Exemple #6
0
HANDLE StartProgram( LPCTSTR pszCommandLine)
{
	CString strCommandLine = pszCommandLine;

	PROCESS_INFORMATION pi;
	ZeroMemory( &pi, sizeof(pi) );

	STARTUPINFO si;
	ZeroMemory( &si, sizeof(si) );
	si.cb = sizeof(si);
	si.dwFlags = 0;
	si.wShowWindow = 0;
	
	SetLastError( ERROR_SUCCESS );
	
	BOOL res = CreateProcess( NULL, (LPTSTR)(LPCTSTR)strCommandLine,
		NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi );

	LONG err = GetLastError();
	
	if( !res || err != ERROR_SUCCESS )
	{
		TRACE( _T("Can't start process (err=%d, 0x%X): \"%s\", %s, %s"),
			err, err, strCommandLine,
			(res ? _T("OK") : _T("Error") ),
			GetProcessInfo( pi.hProcess ) );
	}
	
	if( res )
	{
		CloseHandle(pi.hThread);
		return pi.hProcess;
	} else
		return INVALID_HANDLE_VALUE;
}
Exemple #7
0
BOOL
CmdStep(
    LPSTR             CmdBuf,
    HANDLE            hProcess,
    HANDLE            hThread,
    PEXCEPTION_RECORD ExceptionRecord
    )
{
    PPROCESS_INFO ThisProcess = GetProcessInfo( hProcess );
    if (!ThisProcess) {
        printf( "could not get process information\n" );
        return FALSE;
    }

    PTHREAD_INFO ThisThread = GetThreadInfo( hProcess, hThread );
    if (!ThisThread) {
        printf( "could not get thread information\n" );
        return FALSE;
    }

    SuspendAllThreads( ThisProcess, ThisThread );

    ULONG Address = GetNextOffset(
        ThisProcess->hProcess,
        (ULONG)ExceptionRecord->ExceptionAddress,
        TRUE
        );

    if (Address == (ULONG)-1) {
#ifdef _M_IX86
        CurrContext.EFlags |= 0x100;
        SetRegContext( ThisThread->hThread, &CurrContext );
        PBREAKPOINT_INFO bp = GetAvailBreakpoint( ThisProcess );
        if (bp) {
            bp->Flags   |= BPF_TRACE;
            bp->Address  = (ULONG)ExceptionRecord->ExceptionAddress;
            bp->Handler  = TraceBpHandler;
        }
#else
        printf( "could not trace the instruction\n" );
#endif
    } else {
        PBREAKPOINT_INFO bp = SetBreakpoint(
            ThisProcess,
            Address,
            0,
            NULL,
            TraceBpHandler
            );
        if (!bp) {
            printf( "could not trace the instruction\n" );
            return FALSE;
        }
    }

    return TRUE;
}
Exemple #8
0
bool GetProcessInfo(DWORD nPID, PROCESSENTRY32W* Info)
{
	struct cmp
	{
		static bool compare(PROCESSENTRY32W* p, LPARAM lParam)
		{
			return (p->th32ProcessID == LODWORD(lParam));
		};
	};
	return GetProcessInfo(cmp::compare, (LPARAM)nPID, Info);
}
Exemple #9
0
//! 覆写式创建
LoggerId CLogerManager::CreateLogger(std::string name,std::string path,int nLevel,bool display, bool monthdir, unsigned int limitsize)
{
	std::string _tmp;
	std::string _pid;
	GetProcessInfo(_tmp, _pid);
	if (name.length() == 0)
	{
		ShowColorText("log4z: create logger error, name is empty ! \r\n", LOG_LEVEL_FATAL);
		return -1;
	}
	TrimLogConfig(path);
	FixPath(path);

	LoggerId newID = -1;
	{
		std::map<std::string, LoggerId>::iterator iter = m_ids.find(name);
		if (iter != m_ids.end())
		{
			newID = iter->second;
		}
	}
	if (newID == -1)
	{
		if (m_lastId +1 >= LOG4Z_LOGGER_MAX)
		{
			ShowColorText("log4z: CreateLogger can not create|writeover, because loggerid need < LOGGER_MAX! \r\n", LOG_LEVEL_FATAL);
			return -1;
		}
		newID = ++ m_lastId;
		m_ids[name] = newID;
	}

	if (!path.empty())
	{
		m_loggers[newID]._path = path;
	}

	if (newID > LOG4Z_MAIN_LOGGER_ID)
	{
		m_loggers[newID]._name = name;
	}
	m_loggers[newID]._pid = _pid;
	m_loggers[newID]._level = nLevel;
	m_loggers[newID]._enable = true;
	m_loggers[newID]._display = display;
	m_loggers[newID]._monthdir = monthdir;
	m_loggers[newID]._limitsize = limitsize;
	if (limitsize == 0)
	{
		m_loggers[newID]._limitsize = 4000;
	}

	return newID;
}
Exemple #10
0
//////////////////////////////////////////////////////////////////////////
//! CLogerManager
//////////////////////////////////////////////////////////////////////////
CLogerManager::CLogerManager()
{
	m_bRuning = false;
	m_lastId = LOG4Z_MAIN_LOGGER_ID;
	GetProcessInfo(m_loggers[LOG4Z_MAIN_LOGGER_ID]._name, m_loggers[LOG4Z_MAIN_LOGGER_ID]._pid);
	m_ids[LOG4Z_MAIN_LOGGER_NAME] = LOG4Z_MAIN_LOGGER_ID;

	m_ullStatusTotalPushLog = 0;
	m_ullStatusTotalPopLog = 0;
	m_ullStatusTotalWriteFileCount = 0;
	m_ullStatusTotalWriteFileBytes = 0;
}
Exemple #11
0
static void removeDeadProcs( void ) {

    DWORD       i;

    for( i = 0; i < noGetUsedSize; i++ ) {
        if( !GetProcessInfo( noGetList[i], NULL ) ) {
            memmove( noGetList + i, noGetList + i + 1,
                        ( noGetUsedSize - i - 1 ) * sizeof( DWORD ) );
            i--;
            noGetUsedSize--;
        }
    }
}
Exemple #12
0
void Platform::EnumerateProcesses(
    bool allUsers, UserId const &uid,
    std::function<void(ProcessInfo const &info)> const &cb) {
  Host::Linux::ProcFS::EnumerateProcesses(allUsers, uid,
                                          [&](pid_t pid, uid_t uid) {
                                            ProcessInfo info;

                                            if (!GetProcessInfo(pid, info))
                                              return;

                                            cb(info);
                                          });
}
Exemple #13
0
bool cProcessDB::ConvertPid2Uniq(tNativePid native_pid, tUniqPid* puniq_pid, tAppId* papp_id)
{
	if (!puniq_pid)
		return false;
	if (!native_pid)
	{
		*puniq_pid = 0;
		return false;
	}
	tUniqPid uniq = GetUniq(native_pid);
	if (!uniq)
	{
		tNativePid parent_pid = 0;
		tUniqPid parent_uniq = 0;
		uint64 start_time = 0;
		GetProcessInfo(native_pid, &start_time, &parent_pid);
		ConvertPid2Uniq(parent_pid, &parent_uniq, NULL);
		if (start_time)
		{
			// search for this process in DB
			for (tUniqPid n=(tUniqPid)m_db.GetRecordCount()-1; n>0; n--)
			{
				RECORD rec;
				if (!m_db.GetRecord(n, &rec, sizeof(rec), NULL))
					break;
				if (0 == rec.start_time)
					continue;
				if (start_time - 1*(10^6) < rec.start_time)
					break;
				if (start_time + 1*(10^6) > rec.start_time)
					continue;
				if (native_pid != rec.native_pid)
					continue;
				uniq = n | UNIQ_PROC_ID_FLAG;
				break;
			}
		}
		if (!uniq)
		{
			// register new process
			if (!OnProcessStart(native_pid, parent_uniq, start_time, 0, &uniq))
				return false;
		}
	}
	*puniq_pid = uniq;
	
	// TODO: lookup AppID

	return true;
}
Exemple #14
0
/*
 * AppDebuggerErrMsg
 */
void AppDebuggerErrMsg( void *_info ) {

    ProcAttatchInfo *info = _info;
    char        buf[100];
    ProcStats   stats;

    if( GetProcessInfo( info->info.pid, &stats ) ) {
        RCsprintf( buf, STR_CANT_DEBUG_PROC_X_NAME, info->info.pid,
                   stats.name );
    } else {
        RCsprintf( buf, STR_CANT_DEBUG_PROC_X, info->info.pid );
    }
    MessageBox( MainHwnd, buf, AppName,
                MB_OK | MB_ICONEXCLAMATION | MB_SETFOREGROUND );
}
Exemple #15
0
CLINKAGE DWORD
ReadMemory(
    HANDLE  hProcess,
    PVOID   Address,
    PVOID   Buffer,
    ULONG   Length
    )
{
    ULONG cbRead,cb;
    BOOL rVal = ReadProcessMemory(
        hProcess,
        Address,
        Buffer,
        Length,
        &cbRead
        );
    if (!rVal) {
        return 0;
    }

    PPROCESS_INFO ThisProcess = GetProcessInfo( hProcess );
    if (!ThisProcess) {
        return 0;
    }

    //
    // make sure that the view of the va is correct
    // and does NOT show bp instructions where
    // breakpoints have been set
    //
    for (ULONG i=0; i<MAX_BREAKPOINTS; i++) {
        if (((ULONG)Address >= ThisProcess->Breakpoints[i].Address &&
            (ULONG)Address <  ThisProcess->Breakpoints[i].Address+BpSize) && (!ThisProcess->Breakpoints[i].Text)) {

                ULONG cb = ThisProcess->Breakpoints[i].Address - (ULONG)Address;
                CopyMemory(
                    (LPSTR)Buffer + cb,
                    &ThisProcess->Breakpoints[i].OriginalInstr,
                    BpSize
                    );
                break;

        }
    }

    return cbRead;
}
Exemple #16
0
bool GetProcessInfo(LPCWSTR asExeName, PROCESSENTRY32W* Info)
{
	struct cmp
	{
		static bool compare(PROCESSENTRY32W* p, LPARAM lParam)
		{
			LPCWSTR pszName1 = PointToName(p->szExeFile);
			LPCWSTR pszName2 = (LPCWSTR)lParam;
			int iCmp = lstrcmpi(pszName1, pszName2);
			return (iCmp == 0);
		};
	};
	LPCWSTR pszName = PointToName(asExeName);
	if (!pszName || !*pszName)
		return false;
	return GetProcessInfo(cmp::compare, (LPARAM)pszName, Info);
}
Exemple #17
0
void getWindowInfo(HWND ahWnd, wchar_t (&rsInfo)[1024], bool bProcessName /*= false*/, LPDWORD pnPID /*= NULL*/)
{
	DWORD nPID = 0;

	if (!ahWnd)
	{
		wcscpy_c(rsInfo, L"<NULL>");
	}
	else if (!IsWindow(ahWnd))
	{
		msprintf(rsInfo, countof(rsInfo), L"0x%08X: Invalid window handle", LODWORD(ahWnd));
	}
	else
	{
		wchar_t szClass[256], szTitle[512];
		wchar_t szProc[120] = L"";

		if (!GetClassName(ahWnd, szClass, 256)) wcscpy_c(szClass, L"<GetClassName failed>");
		if (!GetWindowText(ahWnd, szTitle, 512)) szTitle[0] = 0;

		if (bProcessName || pnPID)
		{
			if (GetWindowThreadProcessId(ahWnd, &nPID))
			{
				PROCESSENTRY32 pi = {};
				if (bProcessName && GetProcessInfo(nPID, &pi))
				{
					pi.szExeFile[100] = 0;
					msprintf(szProc, countof(szProc), L" - %s [%u]", pi.szExeFile, nPID);
				}
			}
		}

		msprintf(rsInfo, countof(rsInfo), L"0x%08X: %s - '%s'%s", LODWORD(ahWnd), szClass, szTitle, szProc);
	}

	if (pnPID)
		*pnPID = nPID;
}
Exemple #18
0
BOOL CALLBACK QueryEndDlgProc( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam )
{
    WORD        cmd;
    char        buf[100];
    HWND        lb;
    ProcNode    *procinfo;
    ProcStats   procstat;

    lparam = lparam;
    switch( msg ) {
    case WM_INITDIALOG:
        lb = GetDlgItem( hwnd, END_LIST );
        procinfo = GetNextOwnedProc( NULL );
        while( procinfo != NULL ) {
            if( GetProcessInfo( procinfo->procid, &procstat ) ) {
                RCsprintf( buf, STR_PROCESS_X_NAME, procinfo->procid,
                         procstat.name );
            } else {
                RCsprintf( buf, STR_PROCESS_X, procinfo->procid );
            }
            SendMessage( lb, LB_ADDSTRING, 0, (LPARAM)buf );
            procinfo = GetNextOwnedProc( procinfo );
        }
        break;
    case WM_COMMAND:
        cmd = LOWORD( wparam );
        switch( cmd ) {
        case END_YES:
        case END_NO:
            EndDialog( hwnd, cmd );
            break;
        }
        break;
    default:
        return( FALSE );
    }
    return( TRUE );
}
Exemple #19
0
void CConEmuInside::SetInsideParentWND(HWND hParent)
{
	mh_InsideParentWND = hParent;
	if (!hParent || (hParent == INSIDE_PARENT_NOT_FOUND))
	{
		mh_InsideParentRoot = NULL;
		mh_InsideParentRel = NULL;
	}
	else
	{
		// Store basic information about parent process (reporting purposes)
		DWORD nPID; PROCESSENTRY32W PInfo = {};
		if (GetWindowThreadProcessId(hParent, &nPID)
			&& GetProcessInfo(nPID, &PInfo))
		{
			m_InsideParentInfo.ParentPID = PInfo.th32ProcessID;
			m_InsideParentInfo.ParentParentPID = PInfo.th32ParentProcessID;
			wcscpy_c(m_InsideParentInfo.ExeName, PInfo.szExeFile);
		}
		else
		{
			ZeroStruct(m_InsideParentInfo);
		}

		// Detect top parent window, to call isMeForeground
		HWND hRootParent = hParent;
		while ((GetWindowLong(hRootParent, GWL_STYLE) & WS_CHILD) != 0)
		{
			HWND hNext = GetParent(hRootParent);
			if (!hNext)
				break;
			hRootParent = hNext;
		}
		mh_InsideParentRoot = hRootParent;
	}
}
Exemple #20
0
// -----------------------------------------------------------//
// Function:    CModifyMemoryDlg::InitInfo
// Param                
// Return  :    void   
// meaning :    ���n���M��
// -----------------------------------------------------------//
void   CModifyMemoryDlg::InitInfo()
{   
    // �񏡖{�����I�܌�
    ImproveTokenPrivilege();
    SetParentHwnd(m_hWnd);

    //ProcessList
    m_ProcessList.InsertColumn(0, "Name", LVCFMT_LEFT, 100);
    m_ProcessList.InsertColumn(1, "ProcessID", LVCFMT_LEFT, 100);
    m_ProcessList.InsertColumn(2, "ParenetPrcessID", LVCFMT_LEFT, 100);
    m_ProcessList.InsertColumn(3, "ModuleID", LVCFMT_LEFT, 100);
    m_ProcessList.InsertColumn(4, "ThreadCount", LVCFMT_LEFT, 100);
    m_ProcessList.SetExtendedStyle(LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES);
    // �񎟊l��Process�M��
    GetProcessInfo();
    // DataType
    m_CmbDataType.AddString(_T("BYTE(1����)"));
    m_CmbDataType.AddString(_T("SHORT(2����)"));
    m_CmbDataType.AddString(_T("INT(4����)"));
    m_CmbDataType.AddString(_T("FLOAT(4���ߕ��y�^)"));
    m_CmbDataType.AddString(_T("DOUBLE(8���ߕ��y�^)"));
    m_CmbDataType.AddString(_T("������"));
    m_CmbDataType.SetCurSel(0);
}
Exemple #21
0
/*
 * ThreadCtlProc
 */
BOOL CALLBACK ThreadCtlProc( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam )
{
    WORD                cmd;
    ThreadCtlInfo       *info;
    LRESULT             index;
    char                buf[200];
    DWORD               threadid;
    ThreadNode          *thread;
    ProcNode            *process;
    DWORD               susp_cnt;
    DWORD               rc;
    char                *action;

    info = (ThreadCtlInfo *)GET_DLGDATA( hwnd );
    switch( msg ) {
    case WM_INITDIALOG:
        info = MemAlloc( sizeof( ThreadCtlInfo ) );
        if( !GetProcessInfo( lparam, &info->procinfo ) ) {
             RCsprintf( buf, STR_CANT_GET_PROC_INFO, info->procid );
             MessageBox( hwnd, buf, AppName, MB_OK | MB_ICONEXCLAMATION );
             SendMessage( hwnd, WM_CLOSE, 0, 0 );
        }
        info->procid = lparam;
        ThreadDlg = hwnd;
        SET_DLGDATA( hwnd, info );
        fillThreadCtl( hwnd, &info->procinfo, buf );
        RCsprintf( buf, STR_THREAD_4_PROC_X, lparam );
        SetDlgItemText( hwnd, THREAD_PROC_NAME, buf );
        sprintf( buf, "(%s)", info->procinfo.name );
        SetDlgItemText( hwnd, THREAD_PROC_PATH, buf );
        SendDlgItemMessage( hwnd, THREAD_LIST, LB_SETCURSEL, 0, 0L );
        index = SendDlgItemMessage( hwnd, THREAD_LIST, LB_GETCURSEL, 0, 0L );
        if( index != LB_ERR ) {
            enableChoices( hwnd, TRUE );
        }
        fillThreadInfo( hwnd, &info->procinfo );
        break;
    case WM_COMMAND:
        cmd = LOWORD( wparam );
        if( cmd == THREAD_SUSPEND || cmd == THREAD_RESUME ||
            cmd == THREAD_KILL || cmd == THREAD_SET_PRIORITY ) {
            index = SendDlgItemMessage( hwnd, THREAD_LIST, LB_GETCURSEL, 0, 0L );
            if( index == LB_ERR ) {
                RCMessageBox( hwnd, STR_NO_SELECTED_THREAD, AppName, MB_OK | MB_ICONEXCLAMATION );
                break;
            }
            SendDlgItemMessage( hwnd, THREAD_LIST, LB_GETTEXT, (WPARAM)index, (LPARAM)(LPSTR)buf );
            threadid = getThreadId( buf );
            process = FindProcess( info->procinfo.pid );
            thread = FindThread( process, threadid );
        }
        switch( cmd ) {
        case IDOK:
            SendMessage( hwnd, WM_CLOSE, 0, 0L );
            break;
        case THREAD_REFRESH:
            RefreshInfo();
            if( GetProcessInfo( info->procid, &info->procinfo ) ) {
                fillThreadCtl( hwnd, &info->procinfo, buf );
                fillThreadInfo( hwnd, &info->procinfo );
            } else {
                action = AllocRCString( STR_REFRESH );
                RCMessageBox( hwnd, STR_CANT_REFRESH_THRD, action,
                              MB_OK | MB_ICONEXCLAMATION );
                FreeRCString( action );
            }
            break;
        case THREAD_SUSPEND:
            action = AllocRCString( STR_THREAD_SUSPEND );
            if( thread == NULL ) {
                RCsprintf( buf, STR_CANT_GET_HDL_4_THD_X, threadid );
                MessageBox( hwnd, buf, action, MB_OK | MB_ICONEXCLAMATION );
            } else {
                susp_cnt = SuspendThread( thread->threadhdl );
                if( susp_cnt == -1 ) {
                    RCsprintf( buf, STR_CANT_SUSPEND_THRD_X, threadid );
                    MessageBox( hwnd, buf, action, MB_ICONQUESTION | MB_OK );
                } else if( susp_cnt > 0 ) {
                    RCsprintf( buf, STR_THREAD_ALREADY_SUSP, threadid, susp_cnt );
                    index = MessageBox( hwnd, buf, action, MB_ICONQUESTION | MB_YESNO );
                    if( index == IDNO ) {
                        ResumeThread( thread->threadhdl );
                    }
                }
                SendMessage( hwnd, WM_COMMAND, THREAD_REFRESH, 0L );
            }
            FreeRCString( action );
            break;
        case THREAD_RESUME:
            action = AllocRCString( STR_RESUME );
            if( thread == NULL ) {
                RCsprintf( buf, STR_THREAD_NOT_RESUMED , threadid );
                MessageBox( hwnd, buf, action, MB_OK | MB_ICONEXCLAMATION );
            } else {
                susp_cnt = ResumeThread( thread->threadhdl );
                if( susp_cnt == -1 ) {
                    RCsprintf( buf, STR_CANT_RESUME_THRD_X, threadid );
                    MessageBox( hwnd, buf, action,
                                MB_ICONEXCLAMATION | MB_OK );
                } else if( susp_cnt == 0 ) {
                    RCsprintf( buf, STR_THRD_IS_NOT_SUSP, threadid );
                    MessageBox( hwnd, buf, action,
                                MB_ICONEXCLAMATION | MB_OK );
                } else if( susp_cnt > 1 ) {
                    RCsprintf( buf, STR_SUSP_COUNT_DECREMENTED,
                                threadid, susp_cnt );
                    MessageBox( hwnd, buf, action,
                                MB_ICONEXCLAMATION | MB_OK );
                }
                SendMessage( hwnd, WM_COMMAND, THREAD_REFRESH, 0L );
            }
            FreeRCString( action );
            break;
        case THREAD_KILL:
            action = AllocRCString( STR_KILL );
            if( thread == NULL ) {
                RCsprintf( buf, STR_THRD_NOT_TERMINATED, threadid );
                MessageBox( hwnd, buf, action, MB_OK | MB_ICONEXCLAMATION );
            } else if( GetRetCode( hwnd, RETCD_THREAD, thread->threadid, &rc ) ) {
                if( !TerminateThread( thread->threadhdl, rc ) ) {
                    RCsprintf( buf, STR_CANT_KILL_THRD_X, threadid );
                    MessageBox( hwnd, buf, action,
                                MB_OK | MB_ICONEXCLAMATION );
                }
                SendMessage( hwnd, WM_COMMAND, THREAD_REFRESH, 0L );
            }
            FreeRCString( action );
            break;
        case THREAD_SET_PRIORITY:
//          {
//              ThreadPriorityInfo      prinfo;
//
//              if( thread == NULL ) {
//                  sprintf( buf, "Unable to get a handle for thread %08X.\n",
//                           threadid );
//                  MessageBox( hwnd, buf, "Set Priority",
//                              MB_OK | MB_ICONEXCLAMATION );
//              } else {
//                  prinfo.procid = info->procid;
//                  prinfo.thread = thread;
//                  prinfo.priority = GetThreadPriority( thread->threadhdl );
//                  prinfo.procinfo = &info->procinfo;
//                  DialogBoxParam( Instance, "THREAD_PRIORITY_DLG", hwnd,
//                                  ThreadPriorityDlgProc, (DWORD)&prinfo );
//                  fillThreadInfo( hwnd, &info->procinfo );
//              }
//          }
//          break;
        case THREAD_LIST:
            if( HIWORD( wparam ) == LBN_SELCHANGE ) {
                fillThreadInfo( hwnd, &info->procinfo );
            }
            break;
        }
        break;
    case DR_TASK_LIST_CHANGE:
        /* make sure this process still exists */
//here  if( FindProcess( info->procid ) == NULL ) {
//here      SendDlgItemMessage( hwnd, THREAD_LIST, LB_RESETCONTENT, 0, 0L );
//here      enableChoices( hwnd, FALSE );
//here      info->proc = NULL;
//here  } else {
//here      fillThreadCtl( hwnd, info->proc, buf );
//here  }
        break;
    case WM_CLOSE:
        EndDialog( hwnd, 0 );
        break;
    case WM_DESTROY:
        MemFree( info );
        ThreadDlg = NULL;
        break;
    default:
        return( FALSE );
    }
    return( TRUE );
}
Exemple #22
0
/*
 * InitStatDialog
 */
static void InitStatDialog( HWND hwnd )
{
    int                 i;
    char                buff[256];
    ExceptDlgInfo       *info;
    syminfo             si;
    CreateRegListData   data;
    StatData            *statdata;
    RECT                c_rect;
    HWND                combo;

    info = StatGetExceptDlgInfo( hwnd );
    StatHdl = hwnd;
    statdata = MemAlloc( sizeof( StatData ) );

    /*
     * fill in source information
     */
    GetCurrAddr( &( statdata->curr_addr ), info->regs );
    if( FindWatSymbol( &( statdata->curr_addr ), &si, TRUE ) == FOUND ) {
        RCsprintf( buff, STR_SRC_INFO_FMT, si.linenum, si.filename );
        StatShowSymbols = TRUE;
        CheckDlgButton( hwnd, STAT_SYMBOLS, ( StatShowSymbols ) ? BST_CHECKED : BST_UNCHECKED );
    } else {
        RCsprintf( buff, STR_N_A );
        StatShowSymbols = FALSE;
        EnableWindow( GetDlgItem( hwnd, STAT_SYMBOLS ), FALSE );
    }
    SetDlgMonoFont( hwnd, STAT_SRC_INFO );
    SetDlgItemText( hwnd, STAT_SRC_INFO, buff );

#ifdef __NT__
    {
        ProcStats       procinfo;
        HWND            button;
        if( GetProcessInfo( info->procinfo->procid, &procinfo ) ) {
            RCsprintf( buff, STR_STATUS_4_PROC_X, info->procinfo->procid, procinfo.name );
            SetWindowText( hwnd, buff );
        }
        CopyRCString( STR_VIEW_MEM_HT_KEY, buff, sizeof( buff ) );
        SetDlgItemText( hwnd, STAT_SEG_MAP, buff );
        button = GetDlgItem( hwnd, STAT_STACK_TRACE );
        ShowWindow( button, SW_HIDE );
    }
#endif
    InstructionBackward( 2, &( statdata->curr_addr ) );
    for( i = STAT_DISASM_1;i <= STAT_DISASM_8; i++ ) {
        SetDlgCourierFont( hwnd, i );
    }
    DisplayAsmLines( hwnd, &( statdata->curr_addr ) );
    data.index = 0;
    data.parent = hwnd;
    data.max_len = 0;
    combo = GetDlgItem( hwnd, STAT_REGISTER_COMBO );
    MADRegSetWalk( MTK_ALL, CreateAllRegLists, &data );
    if( data.index == 1 ) {
        SendMessage( combo, CB_GETLBTEXT, (WPARAM)0, (LPARAM)buff );
        SetDlgItemText( hwnd, STAT_REGISTER_SET, buff );
        DestroyWindow( combo );
    } else {
        GetChildPos( hwnd, combo, &c_rect );
        SendMessage( combo, CB_SETCURSEL, (WPARAM)0, (LPARAM)0 );
        c_rect.right += data.max_len;
        c_rect.bottom += SendMessage( combo, CB_GETITEMHEIGHT, 0, 0 ) * ( data.index + 1);
        MoveWindow( combo, c_rect.left, c_rect.top, c_rect.right, c_rect.bottom, FALSE );
    }
    SetFocus( GetDlgItem( hwnd, IDOK ) );
    statdata->reg_set_index = 0;
    SetWindowLong(hwnd,DWL_USER,(LONG)statdata);
} /* InitStatDialog */
kern_return_t GetServerAttribute(AttributeType attrib, UInt32 /*tagSize*/,
                                            void* /*tags*/, unsigned int bufSize,
                                            unsigned int* attribSize, void** buffer)
{
    Assert(buffer != NULL);
    Assert(sAttributeBuffer != NULL);
    
    if ((attribSize == NULL) || (buffer == NULL))
        return SCParamErr;
    
    *attribSize = 0;
    //use the sAttributeBuffer memory to store the attribute. This buffer
    //should be big enough to store the largest attribute
    *buffer = sAttributeBuffer;
        
    if ((attrib.attribClass != kServerAttr) || (attrib.version != kCurrentVersion))
        return SCUnsupportedAttrib;
    
    kern_return_t theError = SCNoError;
        
    switch (attrib.attribKind)
    {
        case kDNSNameAttr:
        {
            if (bufSize >= sizeof(QTSServerDNSName))
            {
                *attribSize = sizeof(QTSServerDNSName);
                theError = GetServerName((QTSServerDNSName*)sAttributeBuffer);
            }
            else
                theError = SCBufferToSmall;
            break;
        }   
        case kProcessInfoAttr:
        {
            if (bufSize >= sizeof(QTSProcessInfoRec))
            {
                *attribSize = sizeof(QTSProcessInfoRec);
                theError = GetProcessInfo((QTSProcessInfoRec*)sAttributeBuffer);
            }
            else
                theError = SCBufferToSmall;
            break;
        }
        case kVersionAttr:
        {
            if (bufSize >= sizeof(QTSServerVersionRec))
            {
                *attribSize = sizeof(QTSServerVersionRec);
                theError = GetServerVersion((QTSServerVersionRec*)sAttributeBuffer);
            }
            else
                theError = SCBufferToSmall;
            break;
        }   
        case kStatusAttr:
        {
            if (bufSize >= sizeof(QTSServerStatusRec))
            {
                *attribSize = sizeof(QTSServerStatusRec);
                theError = GetServerStatusRec((QTSServerStatusRec*)sAttributeBuffer);
            }
            else
                theError = SCBufferToSmall;
            break;
        }   
        case kRefuseConnectionsAttr:
        {
            if (bufSize >= sizeof(QTSRefuseConnectionsRec))
            {
                *attribSize = sizeof(QTSRefuseConnectionsRec);
                theError = GetRefuseConnections((QTSRefuseConnectionsRec*)sAttributeBuffer);
            }
            else
                theError = SCBufferToSmall;
            break;
        }   
        case kHistoryAttr:
        {
            if (bufSize >= sizeof(QTSServerHistoryRec))
            {
                *attribSize = sizeof(QTSServerHistoryRec);
                theError = GetHistory((QTSServerHistoryRec*)sAttributeBuffer);
            }
            else
                theError = SCBufferToSmall;
            break;
        }
        default:
            theError = SCUnsupportedAttrib;
    }
    return theError;
}
Exemple #24
0
static void fillExceptionDlg( HWND hwnd, ExceptDlgInfo *info ) {

    char                buf[BUF_SIZE];
    char                fname[ FNAME_BUFLEN ];
    DWORD               line;
    ProcStats           stats;
    HWND                ctl;
    address             addr;

    GetCurrAddr(&addr,info->regs);
    SetDlgCourierFont( hwnd, INT_TASK_NAME );
    SetDlgCourierFont( hwnd, INT_TASK_PATH );
    SetDlgCourierFont( hwnd, INT_FAULT_TYPE );
    SetDlgCourierFont( hwnd, INT_CS_IP );
    SetDlgCourierFont( hwnd, INT_SOURCE_INFO );
    SetDlgCourierFont( hwnd, INT_SOURCE_INFO2 );

    RCsprintf( buf, STR_EXCEPTION_ENCOUNTERED, AppName );
    SetWindowText( hwnd, buf );

    CopyRCString( STR_PROCESS_NAME, buf, BUF_SIZE );
    SetDlgItemText( hwnd, INT_TASK_NAME_TEXT, buf );

    if( !info->dbinfo->u.Exception.dwFirstChance ) {
        if( ConfigData.exception_action == INT_CHAIN_TO_NEXT ) {
            ConfigData.exception_action = INT_TERMINATE;
        }
        ctl = GetDlgItem( hwnd, INT_CHAIN_TO_NEXT );
        EnableWindow( ctl, FALSE );
    }
    CheckDlgButton( hwnd, ConfigData.exception_action, BST_CHECKED );
    CopyRCString( STR_PROCESS_ID, buf, BUF_SIZE );
    SetDlgItemText( hwnd, INT_TASK_PATH_TEXT, buf );

    while( !GetProcessInfo( info->procinfo->procid, &stats ) ) {
        Sleep( 100 );
        RefreshInfo();
    }
    SetDlgItemText( hwnd, INT_TASK_NAME, stats.name );

    sprintf( buf, "%08lX", info->procinfo->procid );
    SetDlgItemText( hwnd, INT_TASK_PATH, buf );

    FormatException( buf, info->dbinfo->u.Exception.ExceptionRecord.ExceptionCode );
    SetDlgItemText( hwnd, INT_FAULT_TYPE, buf );

    if( info->threadinfo != NULL ) {
        strcpy( buf, "Fault " );
        MADRegSpecialName( MSR_IP, info->regs, MAF_FULL, BUF_SIZE - 7, buf+6 );
        SetDlgItemText( hwnd, INT_IP_NAME, buf );
        SetIp( hwnd, &addr );
    }
    if( info->got_dbginfo && GetLineNum( &addr,fname, FNAME_BUFLEN, &line ) ) {
        RCsprintf( buf, STR_LINE_X_OF, line );
        SetDlgItemText( hwnd, INT_SOURCE_INFO, buf );
        SetDlgItemText( hwnd, INT_SOURCE_INFO2, fname );
    } else {
        CopyRCString( STR_N_A, buf, BUF_SIZE );
        SetDlgItemText( hwnd, INT_SOURCE_INFO, buf );
        SetDlgItemText( hwnd, INT_SOURCE_INFO2, "" );
    }
}
Exemple #25
0
// Проверка окна переднего плана. Если оно принадлежит к хукаемым процесса - вставить хук.
bool CDefaultTerminal::CheckForeground(HWND hFore, DWORD nForePID, bool bRunInThread /*= true*/)
{
	if (!isDefaultTerminalAllowed())
		return false;

	bool lbRc = false;
	bool lbLocked = false;
	bool lbConHostLocked;
	DWORD nResult = 0;
	wchar_t szClass[MAX_PATH]; szClass[0] = 0;
	PROCESSENTRY32 prc;
	bool bMonitored = false;
	const wchar_t* pszMonitored = NULL;
	HANDLE hProcess = NULL;
	//int nBits = 0;
	//wchar_t szCmdLine[MAX_PATH*3];
	//wchar_t szName[64];
	//PROCESS_INFORMATION pi = {};
	//STARTUPINFO si = {sizeof(si)};
	//BOOL bStarted = FALSE;
	DWORD nErrCode = 0;
	int iHookerRc = -1;

	// Если главное окно еще не создано
	if (!mb_ReadyToHook)
	{
		// Сразу выходим
		goto wrap;
	}

	//_ASSERTE(gpConEmu->isMainThread());
	if (!hFore || !nForePID)
	{
		_ASSERTE(hFore && nForePID);
		goto wrap;
	}

	if (hFore == mh_LastWnd || hFore == mh_LastIgnoredWnd)
	{
		// Это окно уже проверялось
		lbRc = (hFore == mh_LastWnd);
		goto wrap;
	}

	if (bRunInThread && (hFore == mh_LastCall))
	{
		// Просто выйти. Это проверка на частые фоновые вызовы.
		goto wrap;
	}
	mh_LastCall = hFore;

	if (bRunInThread)
	{
		if (gpConEmu->isMainThread())
		{
			// Clear finished threads
			ClearThreads(false);
		}

		HANDLE hPostThread = NULL; DWORD nThreadId = 0;
		ThreadArg* pArg = (ThreadArg*)malloc(sizeof(ThreadArg));
		if (!pArg)
		{
			_ASSERTE(pArg);
			goto wrap;
		}
		pArg->pTerm = this;
		pArg->hFore = hFore;
		pArg->nForePID = nForePID;

		hPostThread = CreateThread(NULL, 0, PostCheckThread, pArg, 0, &nThreadId);
		_ASSERTE(hPostThread!=NULL);
		if (hPostThread)
		{
			m_Threads.push_back(hPostThread);
		}

		lbRc = (hPostThread != NULL); // вернуть OK?
		goto wrap;
	}

	EnterCriticalSection(&mcs);
	lbLocked = true;

	// Clear dead processes and windows
	ClearProcessed(false);

	// Check window class
	if (GetClassName(hFore, szClass, countof(szClass)))
	{
		if ((lstrcmp(szClass, VirtualConsoleClass) == 0)
			//|| (lstrcmp(szClass, L"#32770") == 0) // Ignore dialogs // -- Process dialogs too (Application may be dialog-based)
			|| isConsoleClass(szClass))
		{
			mh_LastIgnoredWnd = hFore;
			goto wrap;
		}
	}

	// Go and check
	if (!GetProcessInfo(nForePID, &prc))
	{
		mh_LastIgnoredWnd = hFore;
		goto wrap;
	}

	CharLowerBuff(prc.szExeFile, lstrlen(prc.szExeFile));

	if (lstrcmp(prc.szExeFile, L"csrss.exe") == 0)
	{
		// This is "System" process and may not be hooked
		mh_LastIgnoredWnd = hFore;
		goto wrap;
	}

	// Is it in monitored applications?
	pszMonitored = gpSet->GetDefaultTerminalAppsMSZ();
	if (pszMonitored)
	{
		// All strings are lower case
		const wchar_t* psz = pszMonitored;
		while (*psz)
		{
			if (_tcscmp(psz, prc.szExeFile) == 0)
			{
				bMonitored = true;
				break;
			}
			psz += _tcslen(psz)+1;
		}
	}

	// And how it is?
	if (!bMonitored)
	{
		mh_LastIgnoredWnd = hFore;
		goto wrap;
	}

	// Need to process
	for (INT_PTR i = m_Processed.size(); i--;)
	{
		if (m_Processed[i].nPID == nForePID)
		{
			bMonitored = false;
			break; // already hooked
		}
	}

	// May be hooked already?
	if (!bMonitored)
	{
		mh_LastWnd = hFore;
		lbRc = true;
		goto wrap;
	}

	_ASSERTE(isDefaultTerminalAllowed());

	TODO("Show status in status line?");

	lbConHostLocked = gpConEmu->LockConhostStart();
	iHookerRc = StartDefTermHooker(nForePID, hProcess, nResult, gpConEmu->ms_ConEmuBaseDir, nErrCode);
	if (lbConHostLocked) gpConEmu->UnlockConhostStart();
	if (iHookerRc != 0)
	{
		mh_LastIgnoredWnd = hFore;
		if (iHookerRc == -3)
			DisplayLastError(L"Failed to start hooking application!\nDefault terminal feature will not be available!", nErrCode);
		goto wrap;
	}

	//hProcess = OpenProcess(PROCESS_QUERY_INFORMATION|SYNCHRONIZE, FALSE, nForePID);
	//if (!hProcess)
	//{
	//	// Failed to hook
	//	mh_LastIgnoredWnd = hFore;
	//	goto wrap;
	//}

	//// Need to be hooked
	//nBits = GetProcessBits(nForePID, hProcess);
	//switch (nBits)
	//{
	//case 32:
	//	_wsprintf(szCmdLine, SKIPLEN(countof(szCmdLine)) L"\"%s\\%s\" /DEFTRM=%u",
	//		gpConEmu->ms_ConEmuBaseDir, L"ConEmuC.exe", nForePID);
	//	break;
	//case 64:
	//	_wsprintf(szCmdLine, SKIPLEN(countof(szCmdLine)) L"\"%s\\%s\" /DEFTRM=%u",
	//		gpConEmu->ms_ConEmuBaseDir, L"ConEmuC64.exe", nForePID);
	//	break;
	//}
	//if (!*szCmdLine)
	//{
	//	// Unsupported bitness?
	//	CloseHandle(hProcess);
	//	mh_LastIgnoredWnd = hFore;
	//	goto wrap;
	//}

	//// Prepare event
	//_wsprintf(szName, SKIPLEN(countof(szName)) CEDEFAULTTERMHOOK, nForePID);
	//SafeCloseHandle(mh_SignEvent);
	//mh_SignEvent = CreateEvent(LocalSecurity(), FALSE, FALSE, szName);
	//if (mh_SignEvent) SetEvent(mh_SignEvent); // May be excess, but if event already exists...

	//// Run hooker
	//si.dwFlags = STARTF_USESHOWWINDOW;
	//bStarted = CreateProcess(NULL, szCmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
	//if (!bStarted)
	//{
	//	DisplayLastError(L"Failed to start hooking application!\nDefault terminal feature will not be available!");
	//	CloseHandle(hProcess);
	//	mh_LastIgnoredWnd = hFore;
	//	goto wrap;
	//}
	//CloseHandle(pi.hThread);
	//// Waiting for result
	//WaitForSingleObject(pi.hProcess, INFINITE);
	//GetExitCodeProcess(pi.hProcess, &nResult);
	//CloseHandle(pi.hProcess);

	// And what?
	if ((nResult == (UINT)CERR_HOOKS_WAS_SET) || (nResult == (UINT)CERR_HOOKS_WAS_ALREADY_SET))
	{
		mh_LastWnd = hFore;
		ProcessInfo inf = {};
		inf.hProcess = hProcess;
		hProcess = NULL; // его закрывать НЕ нужно, сохранен в массиве
		inf.nPID = nForePID;
		//inf.bHooksSucceeded = (nResult == (UINT)CERR_HOOKS_WAS_ALREADY_SET);
		inf.nHookTick = GetTickCount();
		m_Processed.push_back(inf);
		lbRc = true;
		goto wrap;
	}
	// Failed, remember this
	CloseHandle(hProcess);
	mh_LastIgnoredWnd = hFore;
	_ASSERTE(lbRc == false);
wrap:
	if (lbLocked)
	{
		LeaveCriticalSection(&mcs);
	}
	return lbRc;
}
Exemple #26
0
//
//	Wrapper around WM_SETCONSOLEINFO. We need to create the
//  necessary section (file-mapping) object in the context of the
//  process which owns the console, before posting the message
//
BOOL SetConsoleInfo(HWND hwndConsole, CONSOLE_INFO *pci)
{
	DWORD   dwConsoleOwnerPid, dwCurProcId;
	PVOID   ptrView = 0;
	DWORD   dwLastError=0;
	WCHAR   ErrText[255];
	//
	//	Retrieve the process which "owns" the console
	//
	dwCurProcId = GetCurrentProcessId();
	
	DEBUGTEST(DWORD dwConsoleThreadId =)
	GetWindowThreadProcessId(hwndConsole, &dwConsoleOwnerPid);

	// We'll fail, if console was created by other process
	if (dwConsoleOwnerPid != dwCurProcId)
	{
		#ifdef _DEBUG
		// Wine related
		PROCESSENTRY32W pi = {};
		GetProcessInfo(dwConsoleOwnerPid, &pi);
		if (lstrcmpi(pi.szExeFile, L"wineconsole.exe")!=0)
		{
			wchar_t szDbgMsg[512], szTitle[128];
			szDbgMsg[0] = 0;
			GetModuleFileName(NULL, szDbgMsg, countof(szDbgMsg));
			msprintf(szTitle, countof(szTitle), L"%s: PID=%u", PointToName(szDbgMsg), GetCurrentProcessId());
			msprintf(szDbgMsg, countof(szDbgMsg), L"GetWindowThreadProcessId()\nPID=%u, TID=%u, %s\n%s",
				dwConsoleOwnerPid, dwConsoleThreadId,
				pi.szExeFile, szTitle);
			MessageBox(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL);
		}
		//_ASSERTE(dwConsoleOwnerPid == dwCurProcId);
		#endif

		return FALSE;
	}

	//
	// Create a SECTION object backed by page-file, then map a view of
	// this section into the owner process so we can write the contents
	// of the CONSOLE_INFO buffer into it
	//
	if (!ghConsoleSection)
	{
		ghConsoleSection = CreateFileMapping(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, gnConsoleSectionSize, 0);

		if (!ghConsoleSection)
		{
			dwLastError = GetLastError();
			_wsprintf(ErrText, SKIPLEN(countof(ErrText)) L"Can't CreateFileMapping(ghConsoleSection). ErrCode=%i", dwLastError);
			MessageBox(NULL, ErrText, L"ConEmu", MB_OK|MB_ICONSTOP|MB_SETFOREGROUND);
			return FALSE;
		}

		_ASSERTE(OnShutdownConsole==NULL || OnShutdownConsole==ShutdownConsole);
		OnShutdownConsole = ShutdownConsole;
	}

	//
	//	Copy our console structure into the section-object
	//
	ptrView = MapViewOfFile(ghConsoleSection, FILE_MAP_WRITE|FILE_MAP_READ, 0, 0, gnConsoleSectionSize);

	if (!ptrView)
	{
		dwLastError = GetLastError();
		_wsprintf(ErrText, SKIPLEN(countof(ErrText)) L"Can't MapViewOfFile. ErrCode=%i", dwLastError);
		MessageBox(NULL, ErrText, L"ConEmu", MB_OK|MB_ICONSTOP|MB_SETFOREGROUND);
	}
	else
	{
		_ASSERTE(pci->Length==sizeof(CONSOLE_INFO));
		//2010-09-19 что-то на XP стало окошко мелькать.
		// при отсылке WM_SETCONSOLEINFO консоль отображается :(
		BOOL lbWasVisible = IsWindowVisible(hwndConsole);
		RECT rcOldPos = {0}, rcAllMonRect = {0};

		if (!lbWasVisible)
		{
			GetWindowRect(hwndConsole, &rcOldPos);
			// В много-мониторных конфигурациях координаты на некоторых могут быть отрицательными!
			rcAllMonRect = GetAllMonitorsWorkspace();
			pci->AutoPosition = FALSE;
			pci->WindowPosX = rcAllMonRect.left - 1280;
			pci->WindowPosY = rcAllMonRect.top - 1024;
		}

		memcpy(ptrView, pci, pci->Length); //-V106
		UnmapViewOfFile(ptrView);

		//  Send console window the "update" message
		DEBUGTEST(LRESULT dwConInfoRc =)
		SendMessage(hwndConsole, WM_SETCONSOLEINFO, (WPARAM)ghConsoleSection, 0);

		DEBUGTEST(DWORD dwConInfoErr = GetLastError());

		if (!lbWasVisible && IsWindowVisible(hwndConsole))
		{
			//DEBUGTEST(Sleep(10));

			apiShowWindow(hwndConsole, SW_HIDE);
			//SetWindowPos(hwndConsole, NULL, rcOldPos.left, rcOldPos.top, 0,0, SWP_NOSIZE|SWP_NOZORDER);
			// -- чтобы на некоторых системах не возникала проблема с позиционированием -> {0,0}
			// Issue 274: Окно реальной консоли позиционируется в неудобном месте
			SetWindowPos(hwndConsole, NULL, 0, 0, 0,0, SWP_NOSIZE|SWP_NOZORDER);
		}
	}

	return TRUE;
}
Exemple #27
0
DWORD WINAPI DebugThread(LPVOID lpvParam)
{
	DWORD nWait = WAIT_TIMEOUT;
	//DWORD nExternalExitCode = -1;
	wchar_t szInfo[1024];

	if (gpSrv->DbgInfo.pszDebuggingCmdLine != NULL)
	{
		STARTUPINFO si = {sizeof(si)};
		PROCESS_INFORMATION pi = {};

		if (gpSrv->DbgInfo.bDebugProcessTree)
		{
			SetEnvironmentVariable(ENV_CONEMU_BLOCKCHILDDEBUGGERS_W, ENV_CONEMU_BLOCKCHILDDEBUGGERS_YES);
		}

		if (!CreateProcess(NULL, gpSrv->DbgInfo.pszDebuggingCmdLine, NULL, NULL, FALSE,
			NORMAL_PRIORITY_CLASS|CREATE_NEW_CONSOLE|
			DEBUG_PROCESS | (gpSrv->DbgInfo.bDebugProcessTree ? 0 : DEBUG_ONLY_THIS_PROCESS),
			NULL, NULL, &si, &pi))
		{
			DWORD dwErr = GetLastError();

			wchar_t szProc[64]; szProc[0] = 0;
			PROCESSENTRY32 pi = {sizeof(pi)};
			if (GetProcessInfo(gpSrv->dwRootProcess, &pi))
				_wcscpyn_c(szProc, countof(szProc), pi.szExeFile, countof(szProc));

			_wsprintf(szInfo, SKIPLEN(countof(szInfo)) L"Can't start debugging process. ErrCode=0x%08X\n", dwErr);
			lstrcpyn(szInfo+lstrlen(szInfo), gpSrv->DbgInfo.pszDebuggingCmdLine, 400);
			wcscat_c(szInfo, L"\n");
			_wprintf(szInfo);
			return CERR_CANTSTARTDEBUGGER;
		}

		gpSrv->hRootProcess = pi.hProcess;
		gpSrv->hRootThread = pi.hThread;
		gpSrv->dwRootProcess = pi.dwProcessId;
		gpSrv->dwRootThread = pi.dwThreadId;
		gpSrv->dwRootStartTime = GetTickCount();
	}


	/* ************************* */
	int iDbgIdx = 0, iAttachedCount = 0;
	while (true)
	{
		HANDLE hDbgProcess = NULL;
		DWORD  nDbgProcessID = 0;

		bool bFirstPID = ((iDbgIdx++) == 0);
		if (bFirstPID)
		{
			hDbgProcess = gpSrv->hRootProcess;
			nDbgProcessID = gpSrv->dwRootProcess;
		}
		else
		{
			// Взять из pDebugAttachProcesses
			if (!gpSrv->DbgInfo.pDebugAttachProcesses)
				break;
			if (!gpSrv->DbgInfo.pDebugAttachProcesses->pop_back(nDbgProcessID))
				break;
			hDbgProcess = GetProcessHandleForDebug(nDbgProcessID);
			if (!hDbgProcess)
			{
				_ASSERTE(hDbgProcess!=NULL && "Can't open debugging process handle");
				continue;
			}
		}
	

		_ASSERTE(hDbgProcess!=NULL && "Process handle must be opened");


		// Битность отладчика должна соответствовать битности приложения!
		if (IsWindows64())
		{
			int nBits = GetProcessBits(nDbgProcessID, hDbgProcess);
			if ((nBits == 32 || nBits == 64) && (nBits != WIN3264TEST(32,64)))
			{
				if (gpSrv->DbgInfo.pszDebuggingCmdLine != NULL)
				{
					_printf("Bitness of ConEmuC and debugging program does not match\n");
					if (bFirstPID)
						return CERR_CANTSTARTDEBUGGER;
					else
						continue;
				}

				wchar_t szExe[MAX_PATH+16];
				wchar_t szCmdLine[MAX_PATH*2];
				if (GetModuleFileName(NULL, szExe, countof(szExe)-16))
				{
					wchar_t* pszName = (wchar_t*)PointToName(szExe);
					_wcscpy_c(pszName, 16, (nBits == 32) ? L"ConEmuC.exe" : L"ConEmuC64.exe");
					_wsprintf(szCmdLine, SKIPLEN(countof(szCmdLine))
						L"\"%s\" /DEBUGPID=%u %s", szExe, nDbgProcessID,
						(gpSrv->DbgInfo.nDebugDumpProcess == 1) ? L"/DUMP" :
						(gpSrv->DbgInfo.nDebugDumpProcess == 2) ? L"/MINIDUMP" :
						(gpSrv->DbgInfo.nDebugDumpProcess == 3) ? L"/FULLDUMP" : L"");

					STARTUPINFO si = {sizeof(si)};
					PROCESS_INFORMATION pi = {};
					if (CreateProcess(NULL, szCmdLine, NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi))
					{
						// Ждать НЕ будем, сразу на выход

						//HANDLE hEvents[2] = {pi.hProcess, ghExitQueryEvent};
						//nWait = WaitForMultipleObjects(countof(hEvents), hEvents, FALSE, INFINITE);
						//if (nWait == WAIT_OBJECT_0)
						//{
						//	//GetExitCodeProcess(pi.hProcess, &nExternalExitCode);
						//	nExternalExitCode = 0;
						//}

						//CloseHandle(pi.hProcess);
						//CloseHandle(pi.hThread);

						//if (nExternalExitCode == 0)
						//{
						//	goto done;
						//}

						// Может там еще процессы в списке на дамп?
						continue;
					}
					else
					{
						DWORD dwErr = GetLastError();
						_wsprintf(szInfo, SKIPLEN(countof(szInfo)) L"Can't start external debugger '%s'. ErrCode=0x%08X\n",
							szCmdLine, dwErr);
						_wprintf(szInfo);
						if (bFirstPID)
							return CERR_CANTSTARTDEBUGGER;
						else
							continue;
					}
				}


				wchar_t szProc[64]; szProc[0] = 0;
				PROCESSENTRY32 pi = {sizeof(pi)};
				if (GetProcessInfo(nDbgProcessID, &pi))
					_wcscpyn_c(szProc, countof(szProc), pi.szExeFile, countof(szProc));

				_wsprintf(szInfo, SKIPLEN(countof(szInfo)) L"Bits are incompatible. Can't debug '%s' PID=%i\n",
					szProc[0] ? szProc : L"not found", nDbgProcessID);
				_wprintf(szInfo);
				if (bFirstPID)
					return CERR_CANTSTARTDEBUGGER;
				else
					continue;
			}
		}

		if (gpSrv->DbgInfo.pszDebuggingCmdLine == NULL)
		{
			if (!DebugActiveProcess(nDbgProcessID))
			{
				DWORD dwErr = GetLastError();

				wchar_t szProc[64]; szProc[0] = 0;
				PROCESSENTRY32 pi = {sizeof(pi)};
				if (GetProcessInfo(nDbgProcessID, &pi))
					_wcscpyn_c(szProc, countof(szProc), pi.szExeFile, countof(szProc));

				_wsprintf(szInfo, SKIPLEN(countof(szInfo)) L"Can't attach debugger to '%s' PID=%i. ErrCode=0x%08X\n",
					szProc[0] ? szProc : L"not found", nDbgProcessID, dwErr);
				_wprintf(szInfo);
				return CERR_CANTSTARTDEBUGGER;
			}
		}

		iAttachedCount++;
	}

	if (iAttachedCount == 0)
	{
		return CERR_CANTSTARTDEBUGGER;
	}
	/* **************** */

	// Дополнительная инициализация, чтобы закрытие дебагера (наш процесс) не привело
	// к закрытию "отлаживаемой" программы
	pfnDebugActiveProcessStop = (FDebugActiveProcessStop)GetProcAddress(GetModuleHandle(L"kernel32.dll"),"DebugActiveProcessStop");
	pfnDebugSetProcessKillOnExit = (FDebugSetProcessKillOnExit)GetProcAddress(GetModuleHandle(L"kernel32.dll"),"DebugSetProcessKillOnExit");

	if (pfnDebugSetProcessKillOnExit)
		pfnDebugSetProcessKillOnExit(FALSE/*KillOnExit*/);

	gpSrv->DbgInfo.bDebuggerActive = TRUE;
	PrintDebugInfo();
	SetEvent(gpSrv->DbgInfo.hDebugReady);
	

	while (nWait == WAIT_TIMEOUT)
	{
		ProcessDebugEvent();

		if (ghExitQueryEvent)
			nWait = WaitForSingleObject(ghExitQueryEvent, 0);
	}

//done:
	gbRootAliveLess10sec = FALSE;
	gbInShutdown = TRUE;
	gbAlwaysConfirmExit = FALSE;

	_ASSERTE(gbTerminateOnCtrlBreak==FALSE);

	if (!nExitQueryPlace) nExitQueryPlace = 12+(nExitPlaceStep);

	SetTerminateEvent(ste_DebugThread);
	return 0;
}
Exemple #28
0
/*
 * logFaultInfo
 */
static void logFaultInfo( ExceptDlgInfo *info ) {

    char        *str;
    char        buf[150];
    char        addr_buf[64];
    char        fname[ FNAME_BUFLEN ];
    DWORD       type;
    DWORD       line;
    msg_id      gptype;
    ProcStats   stats;

    logStrPrintf( "\n" );
    logPrintf( STR_OFFENDING_PROC_ULINE );
    logPrintf( STR_OFFENDING_PROC_INFO );
    logPrintf( STR_OFFENDING_PROC_ULINE );

    while( !GetProcessInfo( info->procinfo->procid, &stats ) ) {
        Sleep( 100 );
        RefreshInfo();
    }
    logPrintf( STR_OFFENDING_PROC_X, stats.name, info->procinfo->procid );
    type = info->dbinfo->u.Exception.ExceptionRecord.ExceptionCode;
    FormatException( buf, type );
    MADCliAddrToString( info->init_ip,
        MADTypeDefault( MTK_ADDRESS, MAF_FULL, NULL, &( info->init_ip ) ),
        MLK_CODE, addr_buf, 63 );
    logPrintf( STR_ERR_OCCURRED_AT_X_Y, buf, addr_buf );
    if( type == EXCEPTION_ACCESS_VIOLATION ) {
        if( info->dbinfo->u.Exception.ExceptionRecord.ExceptionInformation[0] ) {
            gptype = STR_LOG_INV_WRITE_TO;
        } else {
            gptype = STR_LOG_INV_READ_FROM;
        }
        logPrintf( gptype,
          info->dbinfo->u.Exception.ExceptionRecord.ExceptionInformation[1] );
    }
    str = SrchMsg( info->action, Actions, NULL );
    if( str != NULL ) {
        logStrPrintf( "%s\n", str );
    }

    logPrintf( STR_MODULES_LOADED );
    logModules( info->procinfo->procid, INDENT );
    logRegisters( info );
    logPrintf( STR_SOURCE_INFORMATION );
    if( info->got_dbginfo && GetLineNum( &info->init_ip, fname,
            FNAME_BUFLEN, &line ) ) {
        logPrintf( STR_LOG_LINE_X_OF_FILE, INDENT, "", line, fname );
    } else {
        logPrintf( STR_LOG_N_A, INDENT, "" );
    }
    logPrintf( STR_DISASSEMBLY );
    logDisasm( info );
    logStack( info );
#ifndef CHICAGO
    if( LogData.log_mem_manager ) {
        logMemManInfo( info->procinfo->procid );
    }
#endif
    if( LogData.log_mem_dmp ) {
        logMemDmp( info );
    }
}
Exemple #29
0
NTSTATUS RegistryCallback(IN PVOID CallbackContext, 
						  IN PVOID  Argument1, 
						  IN PVOID  Argument2)
{
	NTSTATUS            			  	ntStatus; 
	PDEVICE_CONTEXT 					pContext = (PDEVICE_CONTEXT) CallbackContext;
	REG_NOTIFY_CLASS 					Action   = (REG_NOTIFY_CLASS) Argument1;
	POBJECT_NAME_INFORMATION 			ObjectNameInfo;
	ULONG 								ReturnLength,ReturnLength1;
	UNICODE_STRING      				*path_str = NULL;
	UNICODE_STRING    				    *key = NULL;
	UNICODE_STRING   				    *value = NULL;
	UNICODE_STRING        				*data = NULL;
	UNICODE_STRING				        unicode_registry ;
	UNICODE_STRING        				KeyInformation;
	UNICODE_STRING 				       *unicode_test=NULL;
	ANSI_STRING 						key_ansi;
	ANSI_STRING 						value_ansi;
	ANSI_STRING 						temp_ansi;
	ANSI_STRING 						pathname_ansi;
	size_t 								size = 9;
	ProcessInformationFile 				process;
	ProcessInformation 					process_uni;
	char 								security_sbject[525];
	char 								droit[324];
	char								droit_temp[300];
	char 								buf_temp[1024];
	int 								bool =0;
	
	PAGED_CODE();
	if( ExGetPreviousMode() == KernelMode)
		return STATUS_SUCCESS;
		
	RtlZeroMemory(&security_sbject, sizeof(security_sbject));
	RtlZeroMemory(&droit, sizeof(droit));
	RtlZeroMemory(&droit_temp, sizeof(droit_temp));
	RtlZeroMemory(&buf_temp, sizeof(buf_temp));
	

	switch (Action) 
	{

		case RegNtPreDeleteKey:
			{

				PREG_DELETE_KEY_INFORMATION pInfo = (PREG_DELETE_KEY_INFORMATION) Argument2;
				__try{
						ntStatus = ObQueryNameString(pInfo->Object, (POBJECT_NAME_INFORMATION)key, 0, &ReturnLength);
						key = (PUNICODE_STRING)ExAllocatePoolWithTag(NonPagedPool, ReturnLength, 0);
						if (ntStatus == STATUS_INFO_LENGTH_MISMATCH)
						{	
							if (key)
							{
								ntStatus = ObQueryNameString(pInfo->Object, (POBJECT_NAME_INFORMATION)key, ReturnLength, &ReturnLength);
							}
							else
								return STATUS_SUCCESS;
						}
						
						process = GetProcessInfoFile();
						if(process.pid == 4)
						{
							sprintf(security_sbject,"system_u:system_r:system_t");
							RtlZeroMemory(&process.pathname, sizeof(process.pathname));
							sprintf(process.pathname, "System");
						}
						else
							GetSecurityContextSubject(process, security_sbject);
							
						GetSecurityContextSubject(process, security_sbject);
						RtlUnicodeStringToAnsiString(&key_ansi, key, TRUE);
						sprintf(droit,"delete ");
						bool = 1;
						
				}
				__except(EXCEPTION_EXECUTE_HANDLER)
				{
					ntStatus=GetExceptionCode();
					DbgPrint("Exception RegNtPreDeleteKey : %x\n", ntStatus);
				}
				
				ExFreePoolWithTag(key,0);
				break;
			}

		case RegNtPreCreateKeyEx:
			{
				PREG_CREATE_KEY_INFORMATION pInfo = (PREG_CREATE_KEY_INFORMATION) Argument2;
				__try{

					ntStatus = ObQueryNameString(pInfo->RootObject, (POBJECT_NAME_INFORMATION)path_str, 0, &ReturnLength);
					path_str = (PUNICODE_STRING)ExAllocatePoolWithTag(NonPagedPool, ReturnLength, 0);
					if (ntStatus == STATUS_INFO_LENGTH_MISMATCH)
					{
						if (path_str)
						{
							ntStatus = ObQueryNameString(pInfo->RootObject, (POBJECT_NAME_INFORMATION)path_str, ReturnLength, &ReturnLength);
						}
						else
								return STATUS_SUCCESS;
					}
					
					process_uni = GetProcessInfo();	
					if(process_uni.pid == 4)
								return STATUS_SUCCESS;
							else
								GetSecurityContextSubjectReg(process_uni.name,security_sbject);
							
					GetDroit(droit, pInfo);
					//sprintf(droit, "create_key_function %s", droit_temp);
					RtlUnicodeStringToAnsiString(&key_ansi, pInfo->CompleteName, TRUE);
					
					WriteInLog(droit,process_uni.pid, process_uni.name, process_uni.ppid , key_ansi.Buffer ,security_sbject , "system_u:object_r:registry_t", "registry",0,0);
				}
				__except(EXCEPTION_EXECUTE_HANDLER)
				{
					ntStatus=GetExceptionCode();
					DbgPrint("Exception RegNtPreCreateKeyEx : %x\n", ntStatus);
				}
				// ExFreePoolWithTag(path_str,0);
				break;
			}

		case RegNtSetValueKey:
			{
				PREG_SET_VALUE_KEY_INFORMATION pInfo = (PREG_SET_VALUE_KEY_INFORMATION) Argument2;
				
				__try{
					ntStatus = ObQueryNameString(pInfo->Object, (POBJECT_NAME_INFORMATION)key, 0, &ReturnLength);
					key = (PUNICODE_STRING)ExAllocatePoolWithTag(NonPagedPool, ReturnLength, 1);
					if (ntStatus == STATUS_INFO_LENGTH_MISMATCH)
					{
						if (key)
						{
							ntStatus = ObQueryNameString(pInfo->Object, (POBJECT_NAME_INFORMATION)key, ReturnLength, &ReturnLength);
							process_uni = GetProcessInfo();	
							
							if(process_uni.pid == 4)
								return STATUS_SUCCESS;
							else
								GetSecurityContextSubjectReg(process_uni.name,security_sbject);
							
							RtlUnicodeStringToAnsiString(&key_ansi, key, TRUE);
							sprintf(droit, "setvaluekey "); 
							DbgPrint("%wZ \n", pInfo->ValueName);
							WriteInLog(droit,process_uni.pid, process_uni.name, process_uni.ppid , key_ansi.Buffer ,security_sbject , "system_u:object_r:registry_t", "registry",0,0);
						}
					}
					if(key)
						ExFreePoolWithTag(key,1);
					
				}
				__except(EXCEPTION_EXECUTE_HANDLER)
				{
					ntStatus=GetExceptionCode();
					DbgPrint("Exception RegNtSetValueKey : %x\n", ntStatus);
				}
				break;
			}
		case RegNtQueryValueKey:
			{
				PREG_QUERY_VALUE_KEY_INFORMATION pInfo = (PREG_QUERY_VALUE_KEY_INFORMATION) Argument2;
				
				__try
				{
					ntStatus = ObQueryNameString(pInfo->Object, (POBJECT_NAME_INFORMATION)key, 0, &ReturnLength);
					key = (PUNICODE_STRING)ExAllocatePoolWithTag(NonPagedPool, ReturnLength, 1);
					if (ntStatus == STATUS_INFO_LENGTH_MISMATCH)
					{
						if (key)
						{
							ntStatus = ObQueryNameString(pInfo->Object, (POBJECT_NAME_INFORMATION)key, ReturnLength, &ReturnLength);
							
							process_uni = GetProcessInfo();	
							
							if(process_uni.pid == 4)
								return STATUS_SUCCESS;
							else
								GetSecurityContextSubjectReg(process_uni.name,security_sbject);
						
							switch(pInfo->KeyValueInformationClass)
							{
								case 0: {sprintf(droit, "KeyValueBasicInformation "); break;}
								case 1: {sprintf(droit, "KeyValueFullInformation "); break;}
								case 2: {sprintf(droit, "KeyValuePartialInformation "); break;}
								case 3: {sprintf(droit, "KeyValueFullInformationAlign64 "); break;}
								case 4: {sprintf(droit, "KeyValuePartialInformationAlign64 "); break;}
								case 5: {sprintf(droit, "MaxKeyValueInfoClass "); break;}
								default: break;
							}
							
							RtlUnicodeStringToAnsiString(&key_ansi, key, TRUE);

							// bool = 1;
						WriteInLog(droit,process_uni.pid, process_uni.name, process_uni.ppid , key_ansi.Buffer ,security_sbject , "system_u:object_r:registry_t", "registry",0,0);
							if(key)
								ExFreePoolWithTag(key,1);
						}
					}
				
				}
				__except(EXCEPTION_EXECUTE_HANDLER)
				{
					ntStatus=GetExceptionCode();
					DbgPrint("Exception : %x\n", ntStatus);
				}
	
				break;
			}
			
		case RegNtQueryKey:
			{
				PREG_QUERY_KEY_INFORMATION pInfo = (PREG_QUERY_KEY_INFORMATION) Argument2;
				
				__try{
					ntStatus = ObQueryNameString(pInfo->Object, (POBJECT_NAME_INFORMATION)key, 0, &ReturnLength);
					key = (PUNICODE_STRING)ExAllocatePoolWithTag(NonPagedPool, ReturnLength, 1);
					if (ntStatus == STATUS_INFO_LENGTH_MISMATCH)
					{
						if (key)
						{
							ntStatus = ObQueryNameString(pInfo->Object, (POBJECT_NAME_INFORMATION)key, ReturnLength, &ReturnLength);
					
							process_uni = GetProcessInfo();	
							
							if(process_uni.pid == 4)
								return STATUS_SUCCESS;
							else
								GetSecurityContextSubjectReg(process_uni.name,security_sbject);
													
							switch(pInfo->KeyInformationClass)
							{
								case 0: {sprintf(droit, "KeyBasicInformation "); break;}
								case 1: {sprintf(droit, "KeyNodeInformation "); break;}
								case 2: {sprintf(droit, "KeyFullInformation "); break;}
								case 3: {sprintf(droit, "KeyNameInformation "); break;}
								case 4: {sprintf(droit, "KeyCachedInformation "); break;}
								case 5: {sprintf(droit, "KeyFlagsInformation "); break;}
								case 6: {sprintf(droit, "KeyVirtualizationInformation "); break;}
								case 7: {sprintf(droit, "KeyHandleTagsInformation "); break;}
								case 8: {sprintf(droit, "MaxKeyInfoClass "); break;}
								default: break;
							}
							RtlUnicodeStringToAnsiString(&key_ansi, key, TRUE);
							// RtlUnicodeStringToAnsiString(&pathname_ansi, process_uni.pathname, TRUE);
							
							WriteInLog(droit,process_uni.pid, process_uni.name, process_uni.ppid , key_ansi.Buffer ,security_sbject , "system_u:object_r:registry_t", "registry",0,0);
							// bool = 1;
						
							// if(key)
								// ExFreePoolWithTag(key,1);
						}
					}
				}
				__except(EXCEPTION_EXECUTE_HANDLER)
				{
					ntStatus=GetExceptionCode();
					DbgPrint("Exception : %x\n", ntStatus);
				}
				
				break;
			}

		case RegNtPreOpenKeyEx:
			{
				PREG_CREATE_KEY_INFORMATION pInfo = (PREG_CREATE_KEY_INFORMATION) Argument2;
				
				__try{
					process_uni = GetProcessInfo();	
					if(process_uni.pid == 4)
							return STATUS_SUCCESS;
							
					RtlUnicodeStringToAnsiString(&pathname_ansi, process_uni.pathname, TRUE);
				
					GetSecurityContextSubjectReg(process_uni.name,security_sbject);
					GetDroit(droit, pInfo);
					//sprintf(droit, "open_key_function %s", droit_temp);
					RtlUnicodeStringToAnsiString(&key_ansi, pInfo->CompleteName, TRUE);
					// bool = 1;
					WriteInLog(droit,process_uni.pid, process_uni.name, process_uni.ppid , key_ansi.Buffer ,security_sbject , "system_u:object_r:registry_t", "registry",0,0);
					
				}
				__except(EXCEPTION_EXECUTE_HANDLER)
				{
					ntStatus=GetExceptionCode();
					DbgPrint("Exception : %x\n", ntStatus);
				}
				break;
			}	
			
		default:
			{
				break;
			}
	}
	
	if(bool == 1)
	{
		WriteInLog(droit, process.pid, process.pathname, process.ppid , key_ansi.Buffer ,security_sbject , "system_u:object_r:registry_t", "registry", 0,0);
		
	}


	return STATUS_SUCCESS;
}
Exemple #30
0
// Вызывается для инициализации из Settings::LoadSettings()
HWND CConEmuInside::InsideFindParent()
{
	bool bFirstStep = true;
	DWORD nParentPID = 0;

	if (!m_InsideIntegration)
	{
		return NULL;
	}

	if (mh_InsideParentWND)
	{
		if (IsWindow(mh_InsideParentWND))
		{
			if (m_InsideIntegration == ii_Simple)
			{
				if (mh_InsideParentRoot == NULL)
				{
					// Если еще не искали "корневое" окно
					HWND hParent = mh_InsideParentWND;
					while (hParent)
					{
						mh_InsideParentRoot = hParent;
						hParent = GetParent(hParent);
					}
				}
				// В этом режиме занимаем всю клиентскую область
				_ASSERTE(mh_InsideParentRel==NULL);
				mh_InsideParentRel = NULL;
			}

			_ASSERTE(mh_InsideParentWND!=NULL);
			goto wrap;
		}
		else
		{
			if (m_InsideIntegration == ii_Simple)
			{
				DisplayLastError(L"Specified window not found");
				mh_InsideParentWND = NULL;
				goto wrap;
			}
			_ASSERTE(IsWindow(mh_InsideParentWND));
			mh_InsideParentRoot = mh_InsideParentWND = mh_InsideParentRel = NULL;
		}
	}

	_ASSERTE(m_InsideIntegration!=ii_Simple);

	if (mn_InsideParentPID)
	{
		PROCESSENTRY32 pi = {sizeof(pi)};
		if ((mn_InsideParentPID == GetCurrentProcessId())
			|| !GetProcessInfo(mn_InsideParentPID, &pi))
		{
			DisplayLastError(L"Invalid parent process specified");
			m_InsideIntegration = ii_None;
			mh_InsideParentWND = NULL;
			goto wrap;
		}
		nParentPID = mn_InsideParentPID;
	}
	else
	{
		PROCESSENTRY32 pi = {sizeof(pi)};
		if (!GetProcessInfo(GetCurrentProcessId(), &pi) || !pi.th32ParentProcessID)
		{
			DisplayLastError(L"GetProcessInfo(GetCurrentProcessId()) failed");
			m_InsideIntegration = ii_None;
			mh_InsideParentWND = NULL;
			goto wrap;
		}
		nParentPID = pi.th32ParentProcessID;
	}

	EnumWindows(EnumInsideFindParent, nParentPID);
	if (!mh_InsideParentRoot)
	{
		int nBtn = MsgBox(L"Can't find appropriate parent window!\n\nContinue in normal mode?", MB_ICONSTOP|MB_YESNO|MB_DEFBUTTON2);
		if (nBtn != IDYES)
		{
			mh_InsideParentWND = INSIDE_PARENT_NOT_FOUND;
			return mh_InsideParentWND; // Закрыться!
		}
		// Продолжить в обычном режиме
		m_InsideIntegration = ii_None;
		mh_InsideParentWND = NULL;
		goto wrap;
	}


	HWND hExistConEmu;
	if ((hExistConEmu = InsideFindConEmu(mh_InsideParentRoot)) != NULL)
	{
		_ASSERTE(FALSE && "Continue to create tab in existing instance");
		// Если в проводнике уже есть ConEmu - открыть в нем новую вкладку
		gpSetCls->SingleInstanceShowHide = sih_None;
		LPCWSTR pszCmdLine = GetCommandLine();
		LPCWSTR pszCmd = StrStrI(pszCmdLine, L" /cmd ");
		gpConEmu->RunSingleInstance(hExistConEmu, pszCmd ? (pszCmd + 6) : NULL);

		mh_InsideParentWND = INSIDE_PARENT_NOT_FOUND;
		return mh_InsideParentWND; // Закрыться!
	}

	// Теперь нужно найти дочерние окна
	// 1. в которое будем внедряться
	// 2. по которому будем позиционироваться
	// 3. для синхронизации текущего пути
	InsideFindShellView(mh_InsideParentRoot);

RepeatCheck:
	if (!mh_InsideParentWND || (!mh_InsideParentRel && (m_InsideIntegration == ii_Explorer)))
	{
		wchar_t szAddMsg[128] = L"", szMsg[1024];
		if (bFirstStep)
		{
			bFirstStep = false;

			if (TurnExplorerTipPane(szAddMsg))
			{
				goto RepeatCheck;
			}
		}

		//MessageBox(L"Can't find appropriate shell window!", MB_ICONSTOP);
		_wsprintf(szMsg, SKIPLEN(countof(szMsg)) L"%sCan't find appropriate shell window!\nUnrecognized layout of the Explorer.\n\nContinue in normal mode?", szAddMsg);
		int nBtn = MsgBox(szMsg, MB_ICONSTOP|MB_YESNO|MB_DEFBUTTON2);

		if (nBtn != IDYES)
		{
			mh_InsideParentWND = INSIDE_PARENT_NOT_FOUND;
			return mh_InsideParentWND; // Закрыться!
		}
		m_InsideIntegration = ii_None;
		mh_InsideParentRoot = NULL;
		mh_InsideParentWND = NULL;
		goto wrap;
	}

wrap:
	if (!mh_InsideParentWND)
	{
		m_InsideIntegration = ii_None;
		mh_InsideParentRoot = NULL;
	}
	else
	{
		GetWindowThreadProcessId(mh_InsideParentWND, &mn_InsideParentPID);
		// Для мониторинга папки
		GetCurrentDirectory(countof(ms_InsideParentPath), ms_InsideParentPath);
		int nLen = lstrlen(ms_InsideParentPath);
		if ((nLen > 3) && (ms_InsideParentPath[nLen-1] == L'\\'))
		{
			ms_InsideParentPath[nLen-1] = 0;
		}
	}

	return mh_InsideParentWND;
}