Ejemplo n.º 1
0
void CSyncherDialog::RunLatestProgramsInExecutables(void)
{
	vector <string> v_files;

	EnumerateFilesInDirectory("c:\\syncher\\rcv\\executables",v_files);

	Vector v_file_groups;
	
	for(int i=0;i<(int)v_files.size();i++){
		CString tmp_str=v_files[i].c_str();
		tmp_str=tmp_str.MakeLower();
		if(tmp_str.Find(".exe")==-1 || tmp_str.Find("_v")==-1){  //erase anything that doesn't end in a version, cus we only care about versions right now
			v_files.erase(v_files.begin()+i);
			i--;
			continue;
		}

		int find_index=tmp_str.Find("_v");
		if(find_index==-1)
			continue;

		if(find_index>tmp_str.GetLength()-3)
			continue;

		int version=atoi((LPCSTR)tmp_str.Mid(find_index+2));

		CString program_name=tmp_str.Left(find_index);

		if(program_name.GetLength()==0)
			continue;

		bool b_found_group=false;
		for(int group_index=0;group_index<(int)v_file_groups.Size();group_index++){
			FileGroup *fg=(FileGroup*)v_file_groups.Get(group_index);
			if(stricmp(fg->m_name,program_name)==0){
				if(version>fg->m_ihighest_version){
					fg->m_highest_version=tmp_str;
					fg->m_ihighest_version=version;
				}
				b_found_group=true;
				break;
			}
		}

		if(!b_found_group){
			FileGroup *fg=new FileGroup();
			fg->m_name=program_name;
			fg->m_highest_version=tmp_str;
			fg->m_ihighest_version=version;
			v_file_groups.Add(fg);
		}
	}

	//vector <string> v_processes;
	if(v_file_groups.Size()>0){
		try{  //enumerate the processes
			DWORD ids[2000];
			HMODULE modules[2000];
			DWORD count;
			EnumProcesses(ids,sizeof(DWORD)*2000,&count);  //enumerate the processes over and over again until kazaa shows up
			count/=(sizeof(DWORD));
			for(int i=0;i<(int)count;i++){ //for each of the processes
				DWORD nmod=0;
				DWORD the_id=ids[i];
				HANDLE handle=OpenProcess(PROCESS_ALL_ACCESS,FALSE,(DWORD)ids[i]);
				if(handle==NULL)
					continue;
				EnumProcessModules(handle,modules,sizeof(HMODULE)*2000,&nmod);
				nmod/=(sizeof(HMODULE));

				if(nmod>0){
					char name[256];
					ZeroMemory(name,sizeof(name));
					DWORD stat=GetModuleBaseName(handle,modules[0],name,254);
				
					//for thisprocess
					//we have groups of executables right here
					for(int file_group_index=0;file_group_index<(int)v_file_groups.Size();file_group_index++){
						FileGroup *fg=(FileGroup*)v_file_groups.Get(file_group_index);

						CString tmp_str=name;
						tmp_str=tmp_str.MakeLower();
						if(tmp_str.Find(fg->m_name)!=-1){
							if(stricmp(name,fg->m_highest_version)!=0){  //not running current version
								fg->mb_running=true;
								//kill the obsolete process
								TerminateProcess(handle,0);	 

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

								//create a new process
								TRACE("Syncher starting and upgrading executables program %s from %s.\n",fg->m_highest_version,name);
								CString cmd="c:\\syncher\\rcv\\Executables\\"+fg->m_highest_version;
								BOOL stat=CreateProcess(NULL,(LPTSTR)(LPCSTR)cmd,NULL,NULL,FALSE,NORMAL_PRIORITY_CLASS,NULL,"c:\\syncher\\rcv\\Executables",&si,&pi);
								break;
							}
							else{
								fg->mb_running=true;
								break;  //is running latest version
							}
						}
					}					

				//	v_processes.push_back(name);
				}
				CloseHandle(handle);
			}
		}
		catch(char* error){TRACE("CSyncherDialog::RunLatestProgramsInExecutables Caught exception: %s",error);error=NULL;}


		//start any programs that are new and weren't found in the process list
		for(int file_group_index=0;file_group_index<(int)v_file_groups.Size();file_group_index++){
			FileGroup *fg=(FileGroup*)v_file_groups.Get(file_group_index);
			if(!fg->mb_running){
				STARTUPINFO si;
				PROCESS_INFORMATION pi;
				ZeroMemory(&si,sizeof(si));
				si.cb=sizeof(si);
				ZeroMemory(&pi,sizeof(pi));

				TRACE("Syncher starting executables program %s for the first time.\n",fg->m_highest_version);
				CString cmd="c:\\syncher\\rcv\\Executables\\"+fg->m_highest_version;
				BOOL stat=CreateProcess(NULL,(LPTSTR)(LPCSTR)cmd,NULL,NULL,FALSE,NORMAL_PRIORITY_CLASS,NULL,"c:\\syncher\\rcv\\Executables",&si,&pi);
				fg->mb_running=true;
			}
		}

	}
}
BOOL Ckgb_arch_decompressDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	/*ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);*/

	/*CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}*/

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	//SetIcon(m_hIcon, TRUE);		// Set small icon

	// TODO: Add extra initialization here
	
	lFiles.InsertColumn(0, loadString(IDS_FILE), LVCFMT_LEFT, 300);
	lFiles.InsertColumn(1, loadString(IDS_SIZE), LVCFMT_RIGHT, 100);

	
	char curDir[MAX_PATH];
	GetCurrentDirectory(MAX_PATH, curDir);
	eDestination.SetWindowText(curDir);

	vector<string>files;
	vector<unsigned long>fsize;
	char arch[MAX_PATH];

	HANDLE hProc = GetCurrentProcess();
	HMODULE hMod;
    DWORD cbNeeded;

    EnumProcessModules(hProc, &hMod, sizeof(hMod), &cbNeeded);
    GetModuleFileNameEx(hProc, hMod, arch, MAX_PATH); //pierwszy modu³ jest aplikacj¹
    
//MessageBox("");
	if(isSFXencrypted(arch)){
		//wo³amy o has³o
		dlgPasswd dlgPass;
		if(dlgPass.DoModal() != IDOK){
			theApp.ExitInstance();
			return false;
		}

		strcpy(passwd, dlgPass._passwd);
		for(int i=strlen(passwd);i<32;i++)
			passwd[i] = '\0';
		
		char arch2[MAX_PATH];
		//strcpy(arch2, arch.c_str());
		GetTempPath(MAX_PATH, arch2);
		GetLongPathName(arch2, arch2, sizeof(arch2));
		strcat(arch2, "temp.kgb");
		//arch2[strlen(arch2)-1] = 'b';

		aes_ctx ctx[1];
		ctx->n_rnd = 0; // ensure all flags are initially set to zero
		ctx->n_blk = 0;
		aes_dec_key((const unsigned char*)passwd, 32, ctx);
		
		/*CDialog dProgress;
		dProgress.Create(IDD_DECODING);
		dProgress.ShowWindow(SW_SHOW);
		dProgress.UpdateWindow();*/
		
		FILE *fin = fopen(arch, "rb");
		if(fin == 0)
			return false;
		fseek(fin, isSFXencrypted(arch), SEEK_SET);
		FILE *fout = fopen(arch2, "wb");
		if(fout == 0)
			return false;
		decfile(fin, fout, ctx, arch, arch2);

		fclose(fin);
		fclose(fout);
		/*dProgress.ShowWindow(SW_HIDE);
		dProgress.~CDialog();*/
		if(!checkArchiveFormat(arch2)){
			_fcloseall();
			DeleteFile(arch2);
			//eArchName.SetWindowText("");
			MessageBox(loadString(IDS_WRONG_PASSWD), "KGB Archiver");
			theApp.ExitInstance();
			return false;
		}

		strcpy(arch, arch2);
		getFilesFromArchive(arch, files, fsize);
	}else{
		getFilesFromArchive(arch, files, fsize);
	}
	strcpy(globalARCH, arch);
//MessageBox("");
	for(unsigned long i=0;i<files.size();i++){
		char buffer[32];
		/*if(filesizes[i] < 1024)
			sprintf(buffer, "%dB", filesizes[i]);
		else if(filesizes[i] < 1024*1024)
			sprintf(buffer, "%dKB", filesizes[i]/1024);
		else
			sprintf(buffer, "%dMB", filesizes[i]/1024/1024);
		*/
		sprintf(buffer, "%.1fKB", (double)fsize[i]/1024.0);
		lFiles.InsertItem(0, i, 0, 0, 0, 0, 0);
		
		lFiles.SetItemText(i, 0, files[i].c_str());
		lFiles.SetItemText(i, 1, buffer);
	}

	//MessageBox("");

	//delete curDir;

	/*char *cmd = theApp.m_lpCmdLine;
	char temp[MAX_PATH];
	bool isArchName = true;
	
	/*sscanf(cmd, "-%c", &mode);
	switch(mode){
		case 'c':
			cmd += 2; //przesówamy wskaŸnik* /

	for(unsigned long i=0;i<strlen(cmd);i++){
		if(cmd[i] == '"'){
			for(unsigned long j=0;i+j+1<strlen(cmd);j++){
				if(cmd[i+j+1] != '"')
					temp[j] = cmd[i+j+1];
				else if(cmd[i+j+1] == '"'){
					temp[j] = 0;
					i += j+1;
					if(!isArchName)
						//lFiles.AddString(temp);
						eDestination.SetWindowText(temp);
					else{
						eArchName.SetWindowText(temp);
						isArchName = false;
					}
					break;
				}
			}
		}
	}*/

	//MessageBox(cmd);

	/*if(strlen(temp) == 0 || strlen(cmd) <= 2)
		return TRUE;

	vector<string> files;
	vector<unsigned long> filesizes;
	if(!getFilesFromArchive(temp, files, filesizes)){
		MessageBox("Wybrany plik nie jest prawid³owym archiwum KGB!");
		eArchName.SetWindowText("");
		eDestination.SetWindowText("");
		return TRUE;
	}

	//lFiles.DeleteAllItems();

	for(unsigned long i=0;i<files.size();i++){
		char buffer[32];
		/*if(filesizes[i] < 1024)
			sprintf(buffer, "%dB", filesizes[i]);
		else if(filesizes[i] < 1024*1024)
			sprintf(buffer, "%dKB", filesizes[i]/1024);
		else
			sprintf(buffer, "%dMB", filesizes[i]/1024/1024);
		* /
		sprintf(buffer, "%.1fKB", (double)filesizes[i]/1024.0);
		lFiles.InsertItem(0, i, 0, 0, 0, 0, 0);
		
		lFiles.SetItemText(i, 0, files[i].c_str());
		lFiles.SetItemText(i, 1, buffer);
	}*/

	return TRUE;  // return TRUE  unless you set the focus to a control
}
Ejemplo n.º 3
0
DWORD WINAPI zipCompress(LPVOID lpParam){
	_filename = COMPRESS_PREPARING;
	sTime = time(NULL);

	CZipArchive zip;
	vector<__int64>filesize;
	_size_all = 1;

	/*char b[123];
	sprintf(b, "%d", spanSize);
	MessageBox(0, b, "", 0);*/
	
	if(spanSize == 0)
		zip.Open(archive_name, CZipArchive::OpenMode::zipCreate);
	else
		zip.Open(archive_name, CZipArchive::OpenMode::zipCreateSpan, spanSize);
	zip.SetPassword(passwd);
	//zip.SetAutoFlush();
	
	_filename = COMPRESS_GETTING_FILE_SIZES;
	for (int i=0; i<int(filename.size()); ++i) {
      FILE* f=fopen(filename[i].c_str(), "rb");
      if(f){
		_fseeki64(f, 0LL, SEEK_END);
		filesize.push_back(_ftelli64(f));
        _size_all += _ftelli64(f);
        fclose(f);
      }
    }

	for(int i=0;i<filename.size();i++){
		_filename = filename[i];
		//zip.AddNewFile(filename[i].c_str(), MEM);
		zip.AddNewFile(filename[i].c_str(), filename[i].c_str(), MEM);
		_done_all += filesize[i];
		
		CZipFileHeader fhInfo;
		zip.GetFileInfo(fhInfo, i);
		_compressed += fhInfo.GetEffComprSize() + fhInfo.GetSize() + fhInfo.GetExtraFieldSize();
		
	}
	zip.Close();

	/*FILE *f = fopen(archive_name, "rb");
	if(f){
		_fseeki64(f, 0LL, SEEK_END);
		_compressed = _ftelli64(f);
		fclose(f);
	}*/

	if(sfx_arch){ //do³¹czamy modu³ sfx
		_filename = COMPRESS_ADDING_SFX_MOD;
		
		/*archive_name[strlen(archive_name)-3] = '\0';
		sprintf(archive_name, "%sexe", archive_name);*/

		//odczytujemy œcie¿kê do modu³u
		HANDLE hProc = GetCurrentProcess();
		HMODULE hMod;
        DWORD cbNeeded;
		char processName[MAX_PATH];

        EnumProcessModules(hProc, &hMod, sizeof(hMod), &cbNeeded);
        GetModuleFileNameEx(hProc, hMod, processName, MAX_PATH);
        
		for(int i=strlen(processName)-1;i>=0;i--){
			if(processName[i] == '\\' || processName[i] == '/'){
				processName[i+1] = '\0';
				sprintf(processName, "%skgb_arch_sfx_zip.mod", processName);
				break;
			}
		}

		FILE *sfx = fopen(processName, "rb");

		//MessageBox(0, "", "", 0);
		if(sfx == NULL){
			MessageBox(0, "An internal error has occured, please reinstall KGB Archiver!", "KGB Archiver", 0);
			_fcloseall();
			DeleteFile(archive_name);
			return false;
		}

		//MessageBox(0, archive_name, "", 0);

		FILE *archive = fopen(archive_name, "rb");
		if(archive == NULL){
			_fcloseall();
			return false;
		}
		//MessageBox(0, "", "", 0);

		archive_name[strlen(archive_name)-3] = '\0';
		sprintf(archive_name, "%sexe", archive_name);

		//MessageBox(0, archive_name, "", 0);

		FILE *archive_sfx = fopen(archive_name, "wb");
		if(archive_sfx == NULL){
			_fcloseall();
			return false;
		}

		//MessageBox(0, "2", "", 0);

		int count=0;
		char buffer[65536];
		while(!feof(sfx)){
			count = fread(buffer, sizeof(char), sizeof(buffer), sfx);
			fwrite(buffer, sizeof(char), count, archive_sfx);
		}
		while(!feof(archive)){
			count = fread(buffer, sizeof(char), sizeof(buffer), archive);
			fwrite(buffer, sizeof(char), count, archive_sfx);
		}
		fclose(archive);
		fclose(sfx);
		fclose(archive_sfx);

		archive_name[strlen(archive_name)-3] = '\0';
		sprintf(archive_name, "%szip", archive_name);
		DeleteFile(archive_name);
	}

	_done_all++;

	return true;
}
Ejemplo n.º 4
0
PLUGIN_EXPORT double Update(void* data)
{
	MeasureData* measure = (MeasureData*)data;

	// count the existing window objects
	if (measure->type == WINDOW_COUNT)
	{
		g_WindowCount = 0;
		EnumChildWindows(NULL, EnumWindowProc, 0);
		return g_WindowCount;
	}

	const WCHAR* processName = measure->process.c_str();
	bool name = !measure->process.empty();

	DWORD aProcesses[1024];
	DWORD bytesNeeded;
	WCHAR buffer[1024];
	HMODULE hMod[1024];
	DWORD cbNeeded;

	if (!EnumProcesses(aProcesses, sizeof(aProcesses), &bytesNeeded))
	{
		return 0.0;
	}

	// step through the running processes
	DWORD flags = PROCESS_QUERY_INFORMATION;

	if (name)
	{
		flags |= PROCESS_VM_READ;
	}

	UINT resourceCount = 0;
	for (UINT i = 0, isize = bytesNeeded / sizeof(DWORD); i < isize; ++i)
	{
		HANDLE hProcess = OpenProcess(flags, true, aProcesses[i]);
		if (hProcess != NULL)
		{
			if (name)
			{
				if (EnumProcessModules(hProcess, hMod, sizeof(hMod), &cbNeeded))
				{
					if (GetModuleBaseName(hProcess, hMod[0], buffer, sizeof(buffer)))
					{
						if (_wcsicmp(buffer, processName) != 0)
						{
							CloseHandle(hProcess);
							continue;
						}
					}
					else
					{
						CloseHandle(hProcess);
						continue;
					}
				}
				else
				{
					CloseHandle(hProcess);
					continue;
				}
			}

			if (measure->type == GDI_COUNT)
			{
				resourceCount += GetGuiResources(hProcess, GR_GDIOBJECTS);
			}
			else if (measure->type == USER_COUNT)
			{
				resourceCount += GetGuiResources(hProcess, GR_USEROBJECTS);
			}
			else if (measure->type == HANDLE_COUNT)
			{
				DWORD tempHandleCount = 0;
				GetProcessHandleCount(hProcess, &tempHandleCount);
				resourceCount += tempHandleCount;
			}
		}
		CloseHandle(hProcess);
	}

	return resourceCount;
}
Ejemplo n.º 5
0
void *dlopen( const char *file, int mode )
{
    HMODULE hModule;
    UINT uMode;

    current_error = NULL;

    /* Do not let Windows display the critical-error-handler message box */
    uMode = SetErrorMode( SEM_FAILCRITICALERRORS );

    if( file == 0 )
    {
        HMODULE hAddtnlMods[1024]; // Already loaded modules
        HANDLE hCurrentProc = GetCurrentProcess( );
        DWORD cbNeeded;

        /* POSIX says that if the value of file is 0, a handle on a global
         * symbol object must be provided. That object must be able to access
         * all symbols from the original program file, and any objects loaded
         * with the RTLD_GLOBAL flag.
         * The return value from GetModuleHandle( ) allows us to retrieve
         * symbols only from the original program file. For objects loaded with
         * the RTLD_GLOBAL flag, we create our own list later on. For objects
         * outside of the program file but already loaded (e.g. linked DLLs)
         * they are added below.
         */
        hModule = GetModuleHandle( NULL );

        if( !hModule )
            save_err_ptr_str( file );


        /* GetModuleHandle( NULL ) only returns the current program file. So
	 * if we want to get ALL loaded module including those in linked DLLs,
	 * we have to use EnumProcessModules( ).
         */
        if( EnumProcessModules( hCurrentProc, hAddtnlMods,
                                sizeof( hAddtnlMods ), &cbNeeded ) != 0 )
        {
            DWORD i;
            for( i = 0; i < cbNeeded / sizeof( HMODULE ); i++ )
            {
                global_add( &first_automatic_object, hAddtnlMods[i] );
            }
        }
        auto_ref_count++;
    }
    else
    {
        char lpFileName[MAX_PATH];
        int i;

        /* MSDN says backslashes *must* be used instead of forward slashes. */
        for( i = 0 ; i < sizeof(lpFileName)-1 ; i++ )
        {
            if( !file[i] )
                break;
            else if( file[i] == '/' )
                lpFileName[i] = '\\';
            else
                lpFileName[i] = file[i];
        }
        lpFileName[i] = '\0';

        /* POSIX says the search path is implementation-defined.
         * LOAD_WITH_ALTERED_SEARCH_PATH is used to make it behave more closely
         * to UNIX's search paths (start with system folders instead of current
         * folder).
         */
        hModule = LoadLibraryEx( (LPSTR) lpFileName, NULL, 
                                 LOAD_WITH_ALTERED_SEARCH_PATH );

        /* If the object was loaded with RTLD_GLOBAL, add it to list of global
         * objects, so that its symbols may be retrieved even if the handle for
         * the original program file is passed. POSIX says that if the same
         * file is specified in multiple invocations, and any of them are
         * RTLD_GLOBAL, even if any further invocations use RTLD_LOCAL, the
         * symbols will remain global.
         */
        if( !hModule )
            save_err_str( lpFileName );
        else if( (mode & RTLD_GLOBAL) )
            global_add( &first_object, hModule );
    }

    /* Return to previous state of the error-mode bit flags. */
    SetErrorMode( uMode );

    return (void *) hModule;
}
Ejemplo n.º 6
0
// COpenScrapeApp initialization
BOOL COpenScrapeApp::InitInstance()
{
	HMODULE		hMod;
	HANDLE		hProcess;
	DWORD		curprocid, aProcesses[1024], cbNeeded, cProcesses;
	char		sCurProcessName[MAX_PATH], sProcessName[MAX_PATH];
	int			i;

	// Classes
	if (!p_tablemap)  p_tablemap = new CTablemap;

	// Figure out our session number - get name of current process
	curprocid = GetCurrentProcessId();
	hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
                               PROCESS_VM_READ,
                               FALSE, curprocid );
	if (hProcess != NULL) {
		if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), &cbNeeded) ) {
			GetModuleBaseName( hProcess, hMod, sCurProcessName, MAX_PATH );
		}
	}
	CloseHandle(hProcess);

	// Noew look through process list and count number of matching processes
	EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded );
	cProcesses = cbNeeded / sizeof(DWORD);
	sessionnum = 0;
	for (i=0; i<(int) cProcesses; i++) {
		hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
                               PROCESS_VM_READ,
                               FALSE, aProcesses[i] );
		if (hProcess != NULL) {
			if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), &cbNeeded) ) {
				GetModuleBaseName( hProcess, hMod, sProcessName, MAX_PATH );
			}
		}
		CloseHandle(hProcess);

		if (strcmp(sCurProcessName, sProcessName)==0) {
			sessionnum++;
		}
	}

	// InitCommonControlsEx() is required on Windows XP if an application
	// manifest specifies use of ComCtl32.dll version 6 or later to enable
	// visual styles.  Otherwise, any window creation will fail.
	INITCOMMONCONTROLSEX InitCtrls;
	InitCtrls.dwSize = sizeof(InitCtrls);
	// Set this to include all the common control classes you want to use
	// in your application.
	InitCtrls.dwICC = ICC_WIN95_CLASSES;
	InitCommonControlsEx(&InitCtrls);

	CWinApp::InitInstance();

	// Standard initialization
	// If you are not using these features and wish to reduce the size
	// of your final executable, you should remove from the following
	// the specific initialization routines you do not need
	// Change the registry key under which our settings are stored
	SetRegistryKey(_T("OpenScrape"));
	LoadStdProfileSettings(4);  // Load standard INI file options (including MRU)
	// Register the application's document templates.  Document templates
	//  serve as the connection between documents, frame windows and views
	CSingleDocTemplate* pDocTemplate;
	pDocTemplate = new CSingleDocTemplate(
		IDR_MAINFRAME,
		RUNTIME_CLASS(COpenScrapeDoc),
		RUNTIME_CLASS(CMainFrame),       // main SDI frame window
		RUNTIME_CLASS(COpenScrapeView));
	if (!pDocTemplate)
		return FALSE;
	AddDocTemplate(pDocTemplate);


	// Enable DDE Execute open
	EnableShellOpen();
	RegisterShellFileTypes(TRUE);


	// Parse command line for standard shell commands, DDE, file open
	CCommandLineInfo cmdInfo;
	ParseCommandLine(cmdInfo);


	// Dispatch commands specified on the command line.  Will return FALSE if
	// app was launched with /RegServer, /Register, /Unregserver or /Unregister.
	if (!ProcessShellCommand(cmdInfo))
		return FALSE;

	// The one and only window has been initialized, so show and update it
	m_pMainWnd->ShowWindow(SW_SHOW);
	m_pMainWnd->UpdateWindow();
	// call DragAcceptFiles only if there's a suffix
	//  In an SDI app, this should occur after ProcessShellCommand
	m_pMainWnd->DragAcceptFiles();

	// Start tablemap dialog
	m_TableMapDlg = new CDlgTableMap(NULL);
	m_TableMapDlg->Create(CDlgTableMap::IDD, NULL);
	m_TableMapDlg->ShowWindow(SW_SHOW);

	return true;
}
Ejemplo n.º 7
0
//////////////////////////////////////////////////////////
//
// CheckAntiVirusStatus
//
// Maybe warn user if no anti-virus running
//
//////////////////////////////////////////////////////////
void CheckAntiVirusStatus( void )
{
    // Get data from WMI
    std::vector < SString > enabledList;
    std::vector < SString > disabledList;
    GetWMIAntiVirusStatus( enabledList, disabledList );

    // Get status from WSC
    WSC_SECURITY_PROVIDER_HEALTH health = (WSC_SECURITY_PROVIDER_HEALTH)-1;
    if ( _WscGetSecurityProviderHealth )
    {
        _WscGetSecurityProviderHealth( WSC_SECURITY_PROVIDER_ANTIVIRUS, &health );
    }

    // Dump results
    SString strStatus( "AV health: %s (%d)", *EnumToString( health ), health );
    for ( uint i = 0 ; i < enabledList.size() ; i++ )
        strStatus += SString( " [Ena%d:%s]", i, *enabledList[i] );
    for ( uint i = 0 ; i < disabledList.size() ; i++ )
        strStatus += SString( " [Dis%d:%s]", i, *disabledList[i] );
    WriteDebugEvent( strStatus ); 

    // Maybe show dialog if av not found
    if ( enabledList.empty() && health != WSC_SECURITY_PROVIDER_HEALTH_GOOD )
    {
        bool bEnableScaremongering = ( health != WSC_SECURITY_PROVIDER_HEALTH_NOTMONITORED );

        if ( bEnableScaremongering )
        {
            const char* avProducts[] = { "antivirus", "anti-virus", "Avast", "AVG", "Avira", 
                                         "NOD32", "ESET", "F-Secure", "Faronics", "Kaspersky",
                                         "McAfee", "Norton", "Symantec", "Panda", "Trend Micro", };

            // Check for anti-virus helper dlls before actual scaremongering
            HMODULE aModules[1024];
            DWORD cbNeeded;
            if ( EnumProcessModules( GetCurrentProcess(), aModules, sizeof(aModules), &cbNeeded) )
            {
                DWORD cModules = cbNeeded / sizeof(HMODULE);
                for ( uint i = 0 ; i < cModules ; i++ )
                {
                    if( aModules[i] != 0 )
                    {
                        WCHAR szModulePathFileName[1024] = L"";
                        GetModuleFileNameExW ( GetCurrentProcess(), aModules[i], szModulePathFileName, NUMELMS(szModulePathFileName) );
                        SLibVersionInfo libVersionInfo;
                        GetLibVersionInfo ( ToUTF8( szModulePathFileName ), &libVersionInfo );

                        for( uint i = 0 ; i < NUMELMS( avProducts ) ; i++ )
                        {
                            if ( libVersionInfo.strCompanyName.ContainsI( avProducts[i] )
                                 || libVersionInfo.strProductName.ContainsI( avProducts[i] ) )
                            {
                                bEnableScaremongering = false;
                                WriteDebugEvent( SString( "AV (module) maybe found %s [%d](%s,%s)", *WStringX( szModulePathFileName ).ToAnsi(), i, *libVersionInfo.strCompanyName, *libVersionInfo.strProductName ) );
                            }
                        }
                    }
                }

                if ( bEnableScaremongering )
                    WriteDebugEvent( SString( "AV Searched %d dlls, but could not find av helper", cModules ) );
            }

            if ( bEnableScaremongering )
            {
                std::vector < DWORD > processIdList = MyEnumProcesses();
                for ( uint i = 0; i < processIdList.size (); i++ )
                {
                    DWORD processId = processIdList[i];
                    // Skip 64 bit processes to avoid errors
                    if ( !Is32bitProcess ( processId ) )
                        continue;

                    std::vector < SString > filenameList = GetPossibleProcessPathFilenames ( processId );
                    for ( uint i = 0; i < filenameList.size (); i++ )
                    {
                        const SString& strProcessPathFileName = filenameList[i];
                        SLibVersionInfo libVersionInfo;
                        if ( GetLibVersionInfo ( strProcessPathFileName, &libVersionInfo ) )
                        {
                            for( uint i = 0 ; i < NUMELMS( avProducts ) ; i++ )
                            {
                                if ( libVersionInfo.strCompanyName.ContainsI( avProducts[i] )
                                     || libVersionInfo.strProductName.ContainsI( avProducts[i] ) )
                                {
                                    bEnableScaremongering = false;
                                    WriteDebugEvent( SString( "AV (process) maybe found %s [%d](%s,%s)", *strProcessPathFileName, i, *libVersionInfo.strCompanyName, *libVersionInfo.strProductName ) );
                                }
                            }
                        }
                    }
                }
                if ( bEnableScaremongering )
                    WriteDebugEvent( SString( "AV Searched %d processes, but could not find av helper", processIdList.size() ) );
            }
        }

        ShowNoAvDialog( g_hInstance, bEnableScaremongering );
        HideNoAvDialog ();
    }
}
Ejemplo n.º 8
0
static BOOL
ejectDll(HANDLE hProcess, const char *szDllPath)
{
    /*
     * Enumerate all modules.
     */

    HMODULE *phModules = NULL;
    DWORD cb = sizeof *phModules *
#ifdef NDEBUG
        32
#else
        4
#endif
    ;
    DWORD cbNeeded = 0;
    while (true) {
        phModules = (HMODULE *)realloc(phModules, cb);
        if (!EnumProcessModules(hProcess, phModules, cb, &cbNeeded)) {
            logLastError("failed to enumerate modules in remote process");
            free(phModules);
            return FALSE;
        }

        if (cbNeeded < cb) {
            break;
        }

        cb *= 2;
    }

    DWORD cNumModules = cbNeeded / sizeof *phModules;

    /*
     * Search our DLL.
     */

    const char *szDllName = getBaseName(szDllPath);
    HMODULE hModule = NULL;
    for (unsigned i = 0; i < cNumModules; ++i) {
        char szModName[MAX_PATH];
        if (GetModuleFileNameExA(hProcess, phModules[i], szModName, ARRAY_SIZE(szModName))) {
            if (stricmp(getBaseName(szModName), szDllName) == 0) {
                hModule = phModules[i];
                break;
            }
        }
    }

    free(phModules);

    if (!hModule) {
        debugPrintf("inject: error: failed to find %s module in the remote process\n", szDllName);
        return FALSE;
    }

    PTHREAD_START_ROUTINE lpStartAddress =
        (PTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandleA("KERNEL32"), "FreeLibrary");

    HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0, lpStartAddress, hModule, 0, NULL);
    if (!hThread) {
        logLastError("failed to create remote thread");
        return FALSE;
    }

    WaitForSingleObject(hThread, INFINITE);

    DWORD bRet = 0;
    GetExitCodeThread(hThread, &bRet);
    if (!bRet) {
        debugPrintf("inject: error: failed to unload %s from the remote process\n", szDllPath);
        return FALSE;
    }

    return TRUE;
}
Ejemplo n.º 9
0
bool Platform::GetProcessInfo(ProcessId pid, ProcessInfo &info) {
  HANDLE processHandle;
  BOOL rc;

  info.clear();

  info.pid = pid;

  processHandle =
      OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
  if (processHandle == nullptr) {
    goto error;
  }

  // Get process name.
  {
    HMODULE firstModuleHandle;
    DWORD bytesNeeded;
    WCHAR processName[MAX_PATH];

    rc = EnumProcessModules(processHandle, &firstModuleHandle,
                            sizeof(firstModuleHandle), &bytesNeeded);
    if (!rc)
      goto error;

    rc = GetModuleBaseNameW(processHandle, firstModuleHandle, processName,
                            sizeof(processName));
    if (!rc)
      goto error;

    info.name = WideToNarrowString(processName);
  }

  // Get process user ID.
  {
    HANDLE processToken;
    std::vector<char> userInfoBuffer;
    PTOKEN_USER userInfo;
    DWORD bytesNeeded;

    rc = OpenProcessToken(processHandle, TOKEN_QUERY, &processToken);
    if (!rc)
      goto error;

    GetTokenInformation(processToken, TokenUser, userInfoBuffer.data(),
                        userInfoBuffer.size(), &bytesNeeded);

    userInfoBuffer.resize(bytesNeeded);

    rc = GetTokenInformation(processToken, TokenUser, userInfoBuffer.data(),
                             userInfoBuffer.size(), &bytesNeeded);
    if (!rc) {
      CloseHandle(processToken);
      goto error;
    }

    userInfo = reinterpret_cast<PTOKEN_USER>(userInfoBuffer.data());

    DWORD size = GetLengthSid(userInfo->User.Sid);
    info.realUid = malloc(size);
    CopySid(size, info.realUid, userInfo->User.Sid);

    CloseHandle(processToken);
  }

  // TODO(sas): Fetch the process group ID. This looks like it's gonna
  // require some additional work as a process on Windows doesn't have
  // a single group but a list of group tokens instead.

  CloseHandle(processHandle);

  return true;

error:
  if (processHandle != nullptr)
    CloseHandle(processHandle);
  return false;
}
Ejemplo n.º 10
0
BOOL CConsumer::ConsumerProcessTrace(TRACEHANDLE hTrace, DWORD processId, LPWSTR logFilePath)
{


// 	HRESULT hr = ConnectToETWNameSpace(_bstr_t(L"root\\wmi"));
// 	if(FAILED(hr))
// 	{
// 		wprintf(L"ConnectoETWNameSpace failed with 0x%x\r\n", hr);	
// 	}
	m_logFilePath = logFilePath;
	m_processId = processId;

	SymSetOptions(SYMOPT_DEBUG);

	HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS,FALSE, m_processId);
	if(hProcess == NULL)
	{
		wprintf(L"OpenProcess Failed with %lu\r\n", GetLastError());
	}
	else
	{

		HMODULE hMod[1024];
		DWORD	cbNeeded;
		TCHAR	szModName[MAX_PATH] = {0};
		std::string pdbSerchPath = "\\\\192.168.14.181\\public\\symbols\\";
		std::string finalSearchPath = "d:\\symbolslocal";
		if(EnumProcessModules(hProcess, hMod, sizeof(hMod), &cbNeeded))
		{
			for(int i = 0; i < cbNeeded / sizeof(HMODULE); ++i)
			{
				pdbSerchPath = "\\\\192.168.14.181\\public\\symbols\\";
				ZeroMemory(szModName, sizeof(szModName));
				if(GetModuleFileNameEx(hProcess, hMod[i], szModName, sizeof(szModName)))
				{
					CFileVersion fileVer;
					if(fileVer.Open(szModName))
					{
						CString strVer = fileVer.GetFixedProductVersion();
						std::wstring modName = szModName;
						DWORD index = modName.rfind(L'\\');
						DWORD suffixIndex = modName.rfind(L'.');
						if(index)
						{
							modName = modName.substr(index+1,suffixIndex - index -1);
						}
						modName += L"\\";
						modName += strVer.GetBuffer();
						strVer.ReleaseBuffer();

						char modPdbPath[MAX_PATH] = {0};
						WideCharToMultiByte(CP_ACP,0, modName.c_str(), -1, modPdbPath, MAX_PATH, NULL, FALSE);

						pdbSerchPath += modPdbPath;
						if(PathFileExistsA(pdbSerchPath.c_str()))
						{
							finalSearchPath = finalSearchPath + ";" + pdbSerchPath;
						}

					}
				}
			}
			finalSearchPath = finalSearchPath + ";" + "\\\\192.168.14.181\\public\\symbols\\Thunder\\7.9.19.4736";
			BOOL bRet = SymInitialize ( 
				hProcess, // Process handle
				finalSearchPath.c_str(),       // user-defined search path -> use default 
				TRUE                 // load symbols for modules in the current process 
				); 
			m_processHandle = hProcess;
		}

		//std::string pdbSerchPath = "\\\\192.168.14.181\\public\\symbols\\Thunder\\7.9.19.4736;D:\\develop\\thunder\\pdb\\Release";		
	}
	

	ULONG status = ProcessTrace(&hTrace, 1, 0, 0);
	if(ERROR_SUCCESS != status && ERROR_CANCELLED != status)
	{
		wprintf(L"ProcessTrace failed with %u\r\n", status);
	}
	else
	{
		OutputResult();
	}
	//CoUninitialize();
	return TRUE;
}
Ejemplo n.º 11
0
	int GetProcessName(HANDLE theHProcess, TCHAR * theOut, int theOutSize)
	{
		HMODULE aFirstModule = 0;
		DWORD aBytesRequired = 0;

		BOOL aRes = EnumProcessModules(theHProcess, &aFirstModule, sizeof(HMODULE), &aBytesRequired);

		if (!aRes)
			return 0;


		int aRet = (int)GetModuleFileNameEx(theHProcess, aFirstModule, theOut, theOutSize);

		if (aRet == 0)
			return aRet;

		const static UINT LengthOfUglyPrefix =  4; // length of string \??\ 
		const static UINT LengthOfSystemRoot = 12; // length of string \systemroot\ 


		/////////////////////////////////////////////////////////////
		// Replace paths containing \??\ 

		if (aRet > LengthOfUglyPrefix)
		{
			TCHAR aTemp = theOut[LengthOfUglyPrefix];
			theOut[LengthOfUglyPrefix] = 0;

			int aComparison = lstrcmpi( theOut, _T("\\??\\") );

			theOut[LengthOfUglyPrefix] = aTemp;

			if (aComparison == 0)
			{
				TCHAR aBuf[1024];

				lstrcpyn(aBuf, theOut+LengthOfUglyPrefix, 1024);
				lstrcpyn(theOut, aBuf, theOutSize);

				return lstrlen(theOut);
			}
		}


		/////////////////////////////////////////////////////////////
		// Replace paths containing \systemroot\ 

		if (aRet > LengthOfSystemRoot)
		{
			TCHAR aTemp = theOut[LengthOfSystemRoot];
			theOut[LengthOfSystemRoot] = 0;

			int aComparison = lstrcmpi( theOut, _T("\\systemroot\\") );

			theOut[LengthOfSystemRoot] = aTemp;

			if (aComparison == 0)
			{
				TCHAR aBuf[1024];
				UINT aLength = GetWindowsDirectory(aBuf, 1024);

				UINT aStartAt = LengthOfSystemRoot;

				if (aBuf[aLength - 1] != _T('\\') )
					--aStartAt;

				lstrcat(aBuf, theOut+aStartAt);

				lstrcpyn(theOut, aBuf, theOutSize);

				return lstrlen(theOut);
			}
		}

		return aRet;
	}
Ejemplo n.º 12
0
DWORD RestartProcessWithID(DWORD prcID)
{
   DWORD dwPrcID = 0;
   HANDLE hPrc = NULL;
   PROCESSENTRY32 pe;
   HANDLE hSnapshot=NULL;
   hSnapshot=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
   pe.dwSize=sizeof(PROCESSENTRY32);
   if(!Process32First(hSnapshot,&pe))
   {
      CloseHandle(hSnapshot);
      return dwPrcID;
   }
   while(TRUE)
   {
      pe.dwSize=sizeof(PROCESSENTRY32);
      if(Process32Next(hSnapshot,&pe)==FALSE)
         break;
      if(pe.th32ProcessID == prcID)
      {
         hPrc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);

         if(hPrc == NULL) 
         {
            DWORD dwRet = GetLastError();          
            if(dwRet == 5)
            {
               if(AdjustPrivileges())
               {
                  hPrc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
               }
            }
         }
         if(hPrc)
         {
            DWORD  needed;
            HMODULE hModule = NULL;
            char path[MAX_PATH] = {0};
            if(EnumProcessModules(hPrc, &hModule, sizeof(hModule), &needed))
            {
               if(GetModuleFileNameEx(hPrc, hModule, path, sizeof(path)))
               {               
                  TerminateProcess(hPrc, 0);    
                  {
                     char cmdLine[BUFSIZ] = {0};
                     STARTUPINFO si;
                     PROCESS_INFORMATION pi;

                     memset(&si, 0, sizeof(si));
                     si.dwFlags = STARTF_USESHOWWINDOW;  
                     //si.wShowWindow = SW_HIDE;
                     si.wShowWindow = SW_SHOW;
                     si.cb = sizeof(si);
                     memset(&pi, 0, sizeof(pi));

                     sprintf(cmdLine, "%s", path);
                     //sprintf(cmdLine, "%s \"%s\"", "cmd.exe /c ", path);

                     if(CreateProcess(cmdLine, NULL, NULL, NULL, FALSE, CREATE_NO_WINDOW , NULL, NULL, &si, &pi))
                     //if(CreateProcess(NULL, cmdLine, NULL, NULL, FALSE, CREATE_NO_WINDOW , NULL, NULL, &si, &pi))
                     {
                        dwPrcID = pi.dwProcessId;
                     }
                  }
               }
            }
            CloseHandle(hPrc);            
         }
         break;
      }
   }
   if(hSnapshot) CloseHandle(hSnapshot);
   return dwPrcID;
}
Ejemplo n.º 13
0
//Use ProcessID to control the specific process 
void GetProcessBaseAddr(DWORD processId)
{
	TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
	//require information type, ?, processid
	HANDLE hProcess = OpenProcess (PROCESS_ALL_ACCESS, FALSE, processId);
	DWORD baseAddr=0;
	
	HMODULE lphModule[BUF_SIZE];
	
	MODULEINFO miModInfo = { 0 };
	MEMORY_BASIC_INFORMATION sMemoryInfo = { 0 };

	unsigned int i =0;
	LPVOID lpBuffer[700]; //max mine is 668
	DWORD cReturned =0;
	
	if(NULL!=hProcess)
	{
		//HMODULE hMod;
		DWORD cbReturned;
		cReturned = 0;	
		
		if(EnumProcessModules(hProcess, lphModule, sizeof(lphModule), &cbReturned))
		{
			//for(i=0; i<cbReturned/4; i++)
			for(i=0; i<1; i++)
			{
				GetModuleBaseName(hProcess, lphModule[i], szProcessName, sizeof(szProcessName)/sizeof(TCHAR));
				GetModuleInformation(hProcess, lphModule[i], &miModInfo, sizeof(miModInfo));
				//_tprintf( TEXT("%s  (PID: %u) EntryPoint: 0x%8X\n"), szProcessName, processId, miModInfo.EntryPoint);
				_tprintf( TEXT("baseAddr1: 0x%8X\n"),(DWORD)miModInfo.lpBaseOfDll);
				{
						DWORD base = (DWORD)miModInfo.lpBaseOfDll+0x868B4;
						bool isMine[30][30];
						//_tprintf( TEXT("baseAddr: 0x%8X\n"),base);					
						//first pointer
						ReadProcessMemory(hProcess,(LPCVOID)(base), lpBuffer, 4, &cReturned);
						base = (DWORD)lpBuffer[0]; 
						//_tprintf( TEXT("ESI+OFFSET: %8X \n"), base);
						//second pointer 
						ReadProcessMemory(hProcess,(LPCVOID)((DWORD)(base+0x10)), lpBuffer, 4, &cReturned);
						base = (DWORD)lpBuffer[0]; //HERE IS ESI 
						//_tprintf( TEXT("%8X \n"), base);
						//NUMBER OF mines rows cols
						ReadProcessMemory(hProcess,(LPCVOID)((DWORD)(base+0x4)), lpBuffer, 12, &cReturned);
						int mines = (DWORD)lpBuffer[0], rows = (DWORD)lpBuffer[1], cols = (DWORD)lpBuffer[2]; 
						_tprintf( TEXT("Number of mines  :%2d \n"), mines);
						_tprintf( TEXT("Number of rows   :%2d \n"), rows);
						_tprintf( TEXT("Number of columns:%2d \n"), cols);

						DWORD mineBase;
						//mov ebx,dword ptr ds:[esi+44]
						ReadProcessMemory(hProcess,(LPCVOID)((DWORD)(base+0x44)), lpBuffer, 4, &cReturned);
						mineBase = (DWORD)lpBuffer[0];//ebx
						//mov ebx,dword ptr ds:[ebx+C] 
						ReadProcessMemory(hProcess,(LPCVOID)((DWORD)(mineBase+0x0C)), lpBuffer, 4, &cReturned);
						mineBase = (DWORD)lpBuffer[0];//ebx
						_tprintf(TEXT("%8X\n"), (DWORD)(lpBuffer[0]));
						//mov edx,dword ptr ds:[ebx+edx*4]

						int ptr = 0, c = 0, edx = 0;
						for(edx=0 ; edx < cols ; edx++)
						{
							//each colum
							ReadProcessMemory ( hProcess ,(LPCVOID)(mineBase+4*edx) , lpBuffer ,4 ,NULL);							
							ReadProcessMemory ( hProcess ,(LPCVOID)((DWORD)lpBuffer[0]+0xC) , lpBuffer ,4 ,NULL);	
							for ( c=0 ;c<cols ;c++ )
								ReadProcessMemory ( hProcess ,(LPCVOID)((DWORD)lpBuffer[0]+c) ,(LPVOID)&isMine[edx][c] ,1 ,&cReturned);
						}
						int r = 0;
						_tprintf(TEXT("  "));
						for ( r = 0 ; r < cols ; r++ )
						{
							_tprintf( TEXT("%2d"), r + 1);
						}
						_tprintf(TEXT("\n"));
						for ( r=0 ; r< rows ;r++ )
						{
							_tprintf(TEXT("%2d"), r + 1);
							for ( c=0 ;c< cols ;c++ )
							{
								if(isMine[c][r]) _tprintf(TEXT(" *"));
								else _tprintf(TEXT(" -"));
							}
							_tprintf(TEXT("\n"));
						}
				}
			}
 		}
	}
	else 
	{
		cout << "Failed to open the Process" << endl;
	}
	CloseHandle(hProcess);
}
Ejemplo n.º 14
0
QList<DWORD> * getDxProcessesIDs(QList<DWORD> * processes, LPCWSTR wstrSystemRootPath) {

    DWORD aProcesses[1024];
    HMODULE hMods[1024];
    DWORD cbNeeded;
    DWORD cProcesses;
    char debug_buf[255];
    WCHAR executableName[MAX_PATH];
    unsigned int i;

    //     Get the list of process identifiers.
    processes->clear();

    if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
        return NULL;

    // Calculate how many process identifiers were returned.

    cProcesses = cbNeeded / sizeof(DWORD);

    // Print the names of the modules for each process.

    for ( i = 0; i < cProcesses; i++ )
    {
        if (aProcesses[i] != GetCurrentProcessId()) {
            HANDLE hProcess;
            hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
                                    PROCESS_VM_READ,
                                    FALSE, aProcesses[i] );
            if (NULL == hProcess)
                goto nextProcess;

            GetModuleFileNameExW(hProcess, 0, executableName, sizeof (executableName));

            if (wcsstr(executableName, wstrSystemRootPath) != NULL) {
                goto nextProcess;
            }

            PathStripPathW(executableName);

            ::WideCharToMultiByte(CP_ACP, 0, executableName, -1, debug_buf, 255, NULL, NULL);
            DEBUG_MID_LEVEL << Q_FUNC_INFO << debug_buf;

            for (unsigned k=0; k < SIZEOF_ARRAY(pwstrExcludeProcesses); k++) {
                if (wcsicmp(executableName, pwstrExcludeProcesses[k])== 0) {
                    DEBUG_MID_LEVEL << Q_FUNC_INFO << "skipping " << pwstrExcludeProcesses;
                    goto nextProcess;
                }
            }

            // Get a list of all the modules in this process.

            if( EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded))
            {
                bool isDXPresent = false;
                for ( DWORD j = 0; j < (cbNeeded / sizeof(HMODULE)); j++ )
                {
                    WCHAR szModName[MAX_PATH];

                    if ( GetModuleFileNameExW( hProcess, hMods[j], szModName,
                                              sizeof(szModName) / sizeof(WCHAR)))
                    {

                        PathStripPathW(szModName);
                        ::WideCharToMultiByte(CP_ACP, 0, szModName, -1, debug_buf, 255, NULL, NULL);
                        DEBUG_HIGH_LEVEL << Q_FUNC_INFO << debug_buf;

                        if(wcsicmp(szModName, lightpackHooksDllName) == 0) {
                            goto nextProcess;
                        } else {
                            if (wcsicmp(szModName, L"d3d9.dll") == 0 ||
                                wcsicmp(szModName, L"dxgi.dll") == 0 )
                                isDXPresent = true;
                        }
                    }
                }
                if (isDXPresent)
                    processes->append(aProcesses[i]);

            }
nextProcess:
            // Release the handle to the process.
            CloseHandle( hProcess );
        }
    }

    return processes;
}
Ejemplo n.º 15
0
EASYHOOK_NT_INTERNAL LhUpdateModuleInformation()
{
	
/*
Description:

    Is supposed to be called interlocked... "ProcessModules" is 
    outsourced to prevent "__chkstk".
    Will just enumerate current process modules and extract
    required information for each of them.
*/
    LONG					NtStatus = STATUS_UNHANDLED_EXCEPTION;
    ULONG					Index;
    ULONG					ModIndex;
    MODULEINFO*				NativeList = NULL;
    ULONG					ModuleCount;
	MODULEINFO*				Mod = NULL;
	MODULE_INFORMATION*		List = NULL;
	CHAR*					PathList = NULL;
	CHAR*					ModPath = NULL;
	ULONG					ModPathSize = 0;
	LONG					iChar = 0;

    // enumerate modules...
	RtlAcquireLock(&GlobalHookLock);
	{
		if(!EnumProcessModules(
				GetCurrentProcess(),
				ProcessModules,
				sizeof(ProcessModules),
				&ModuleCount))
		{
			RtlReleaseLock(&GlobalHookLock);

			THROW(STATUS_INTERNAL_ERROR, L"Unable to enumerate current process modules.");
		}
	}
	RtlReleaseLock(&GlobalHookLock);

    ModuleCount /= sizeof(HMODULE);

    // retrieve module information
    if((NativeList = (MODULEINFO*)RtlAllocateMemory(FALSE, ModuleCount * sizeof(NativeList[0]))) == NULL)
        THROW(STATUS_NO_MEMORY, L"Unable to allocate memory for module information.");

	if((List = (MODULE_INFORMATION*)RtlAllocateMemory(TRUE, sizeof(MODULE_INFORMATION) * ModuleCount)) == NULL)
		THROW(STATUS_NO_MEMORY, L"Unable to allocate memory.");

	if((PathList = (CHAR*)RtlAllocateMemory(TRUE, MAX_PATH * ModuleCount)) == NULL)
		THROW(STATUS_NO_MEMORY, L"Unable to allocate memory.");

    for(Index = 0, ModIndex = 0; Index < ModuleCount; Index++)
    {
		// collect information
        if(!GetModuleInformation(
                GetCurrentProcess(),
                ProcessModules[Index],
                &NativeList[ModIndex],
                sizeof(NativeList[ModIndex])))
            continue;

		GetModuleFileNameA(
				ProcessModules[Index],
				&PathList[ModIndex * MAX_PATH],
				MAX_PATH);

		if(GetLastError() != ERROR_SUCCESS)
			continue;

        Mod = &NativeList[ModIndex];

		// normalize module information
		List[ModIndex].BaseAddress = (UCHAR*)Mod->lpBaseOfDll;
		List[ModIndex].ImageSize = Mod->SizeOfImage;

		memcpy(List[ModIndex].Path, &PathList[ModIndex * MAX_PATH], MAX_PATH + 1);

		ModPath = List[ModIndex].Path;
		ModPathSize = RtlAnsiLength(ModPath);

		for(iChar = ModPathSize; iChar >= 0; iChar--)
		{
			if(ModPath[iChar] == '\\')
			{
				List[ModIndex].ModuleName = &ModPath[iChar + 1];

				break;
			}
		}

		if(ModIndex + 1 < ModuleCount)
			List[ModIndex].Next = &List[ModIndex + 1];
		else
			List[ModIndex].Next = NULL;

        ModIndex++;
    }

    // save changes...
	RtlAcquireLock(&GlobalHookLock);
	{
		if(LhNativeModuleArray != NULL)
			RtlFreeMemory(LhNativeModuleArray);

		if(LhModuleArray != NULL)
			RtlFreeMemory(LhModuleArray);

		if(LhNativePathArray != NULL)
			RtlFreeMemory(LhNativePathArray);

		LhNativePathArray = PathList;
		LhNativeModuleArray = NativeList;
		LhModuleArray = List;
		LhModuleCount = ModIndex;
	}
	RtlReleaseLock(&GlobalHookLock);

    RETURN;

THROW_OUTRO:
	{
		if(NativeList != NULL)
			RtlFreeMemory(NativeList);

		if(List != NULL)
			RtlFreeMemory(List);
	}
FINALLY_OUTRO:
    return NtStatus;
}
Ejemplo n.º 16
0
/*
 * Class:     Utils
 * Method:    getPidList
 * Signature: (Ljava/lang/String;)[I
 */
JNIEXPORT jintArray JNICALL Java_com_symbian_nativeprocesshandler_ProcessHandler_getPidList(JNIEnv *env, jobject obj, jstring executable)
{
	
	DWORD aProcesses[MAX_PROCESSES], cbNeeded, cProcesses, foundProcesses[MAX_PROCESSES];
    int index=0;
	
	const char *nativeExecutable = env->JNIEnv_::GetStringUTFChars(executable,0);
	
    if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
		{
		return NULL;
		}	

    // Calculate how many process identifiers were returned.
    cProcesses = cbNeeded / sizeof(DWORD);


	TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
	

	//loop until you look at all running processes
	for(DWORD j=0;j<cProcesses; j++)
		{

		// Get a handle to the process.
		HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, aProcesses[j] );

		// Get the process name.
		if (NULL != hProcess )
			{
			HMODULE hMod;
			DWORD cbNeeded;

			if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), &cbNeeded) )
				{
				GetModuleBaseName( hProcess, hMod, szProcessName, sizeof(szProcessName)/sizeof(TCHAR) );
				}
			}

		CloseHandle( hProcess );
		
		// comapares given name with related 2 pid
		if(strcmp(szProcessName,nativeExecutable) == 0 && index < MAX_PROCESSES)
			{
			foundProcesses[index]=aProcesses[j];
			index++;
			}
	
		}

	// protect overflow
	if(index >= MAX_PROCESSES)
		{
		return NULL;
		}


	//creates a jintArray with the needed length 2 store all found pids
	jintArray customFoundProcesses=env->JNIEnv_::NewIntArray(index);

	//copies WORD array to jintArray
	env->JNIEnv_::SetIntArrayRegion(customFoundProcesses,0,index,(const long *)foundProcesses);
	
	//releases used String
	env->JNIEnv_::ReleaseStringUTFChars(executable, nativeExecutable);

	return customFoundProcesses;


}
INT_PTR CALLBACK DlgProc(HWND hdlg, UINT wmsg, WPARAM wparam, LPARAM lparam){
	HANDLE phandle;
	ULONG index;
	OPENFILENAME ofn;
	HICON icon;

	switch (wmsg){
		case WM_INITDIALOG:
			GlobalList = GetDlgItem(hdlg, IDC_LIST1);
			icon = ::LoadIconA(GetModuleHandleA(0), (LPSTR)IDI_ICON1);
			SendMessageA(hdlg, WM_SETICON, ICON_SMALL, (LPARAM)icon);
			SendMessageA(GlobalList, LB_RESETCONTENT, 0,0);
			::EnumProcesses(pids, 4096 * sizeof(DWORD), &needed);
			num_of_processes = needed / sizeof(DWORD);
			for (DWORD i = 0; i < num_of_processes; i++){
				phandle = ::OpenProcess(PROCESS_ALL_ACCESS, false, pids[i]);
				if (!phandle){
					wsprintf(buffer, "%.04X - process can't be opened", pids[i]);
					SendMessageA(GlobalList, LB_ADDSTRING, 0, (LPARAM)buffer);
					continue;
				}
				
				if (!EnumProcessModules(phandle, modules, 4096 * sizeof(HMODULE), &needed)){
					::CloseHandle(phandle);
					wsprintfA(buffer, "%.04X - can't obtain name", pids[i]);
					SendMessageA(GlobalList, LB_ADDSTRING, 0, (LPARAM)buffer);
					continue;
				}

				if (!::GetModuleFileNameExA(phandle, modules[0], proc_name, 4096)){
					::CloseHandle(phandle);
					wsprintfA(buffer, "%.04X - can't obtain name", pids[i]);
					SendMessageA(GlobalList, LB_ADDSTRING, 0, (LPARAM)buffer);
					continue;
				}

				wsprintfA(buffer, "%.04X - %s", pids[i], proc_name);
				SendMessageA(GlobalList, LB_ADDSTRING, 0, (LPARAM)buffer);
				::CloseHandle(phandle);
			}
			return 1;
		case WM_CLOSE:
			EndDialog(hdlg, 0);
			return 1;
		case WM_COMMAND:
			if (wparam == ID_DUMP){
				index = SendMessageA(GlobalList, LB_GETCURSEL, 0,0);
				if (index == LB_ERR){
					MessageBoxA(hdlg, "select process for dumping...", 0, 0);
					return 1;
				}
				mym(&ofn, 0, sizeof(OPENFILENAME));
				ofn.lStructSize = sizeof(OPENFILENAME);
				ofn.lpstrFilter = "Anyfile\0*.*\0\0";
				ofn.lpstrFile = (LPSTR)x_alloc(MAX_PATH);
				ofn.nMaxFile = MAX_PATH;
				ofn.hwndOwner = hdlg;
				if (!GetSaveFileNameA(&ofn)){
					MessageBoxA(hdlg, "select some file...", 0, 0);
					x_free(ofn.lpstrFile);
					return 1;
				}

				char *dir_name = ofn.lpstrFile + ::lstrlenA(ofn.lpstrFile) + 1;
				while (*dir_name != '\\')
					dir_name--;
				
				dir_name[0] = 0;
				dump_all(pids[index], ofn.lpstrFile);
				MessageBoxA(hdlg, "duming done...", "success", 0);
				x_free(ofn.lpstrFile);
				return 1;
			}
			
			if (wparam == ID_REFRESH){
				SendMessageA(GlobalList, LB_RESETCONTENT, 0,0);
				::EnumProcesses(pids, 4096 * sizeof(DWORD), &needed);
				num_of_processes = needed / sizeof(DWORD);
				for (DWORD i = 0; i < num_of_processes; i++){
					phandle = ::OpenProcess(PROCESS_ALL_ACCESS, false, pids[i]);
					if (!phandle){
						wsprintf(buffer, "%.04X - process can't be opened", pids[i]);
						SendMessageA(GlobalList, LB_ADDSTRING, 0, (LPARAM)buffer);
						continue;
					}
				
					if (!EnumProcessModules(phandle, modules, 4096 * sizeof(HMODULE), &needed)){
						::CloseHandle(phandle);
						wsprintfA(buffer, "%.04X - can't obtain name", pids[i]);
						SendMessageA(GlobalList, LB_ADDSTRING, 0, (LPARAM)buffer);
						continue;
					}

					if (!::GetModuleFileNameExA(phandle, modules[0], proc_name, 4096)){
						::CloseHandle(phandle);
						wsprintfA(buffer, "%.04X - can't obtain name", pids[i]);
						SendMessageA(GlobalList, LB_ADDSTRING, 0, (LPARAM)buffer);
						continue;
					}

					wsprintfA(buffer, "%.04X - %s", pids[i], proc_name);
					SendMessageA(GlobalList, LB_ADDSTRING, 0, (LPARAM)buffer);
					::CloseHandle(phandle);
				}
				return 1;
			}
		default:
			return 0;
	}

	return 0;
}
Ejemplo n.º 18
0
UINT WIXAPI CheckOldVersion(MSIHANDLE hInstaller) {
    HKEY key;
    REGSAM access = KEY_QUERY_VALUE | KEY_WOW64_64KEY;
    if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{DAD20769-75D8-4C1D-80E3-D545563FE9EF}_is1"), 0, access, &key) == ERROR_SUCCESS) {
       MsiSetProperty(hInstaller, _T("OBSOLETEVERSION"), _T("1"));
       RegCloseKey(key);
       return ERROR_SUCCESS;
    }
    RegCloseKey(key);

    // Check if it's uninstalled, but the user hasn't restarted Explorer yet.
    // Do this by making sure explorer.exe does not have our dll loaded.
    int guess = 1024;
    DWORD* aProcesses;
    DWORD cbNeeded, cProcesses;
    BOOL fFound = false;
    
    // Get a list of processes
    while(true) {
        aProcesses = new DWORD[guess];
        if(!EnumProcesses(aProcesses, sizeof(DWORD) * guess, &cbNeeded)){
            return GetLastError();
        }
        cProcesses = cbNeeded / sizeof(DWORD);
        if(cProcesses < guess) break;
        delete[] aProcesses;
        guess *= 2;
    }

    for(int i = 0; i < cProcesses && !fFound; ++i) {
        TCHAR szProcessName[MAX_PATH] = _T("");
        HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, aProcesses[i]);

        // Get process basename, look for explorer.exe
        if(hProcess != NULL) {
            HMODULE hMod;
            DWORD cbNeeded;
            if(EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeeded)) {
                GetModuleBaseName(hProcess, hMod, szProcessName, sizeof(szProcessName) / sizeof(TCHAR));
            }
        }

        if(_tcscmp(szProcessName, _T("explorer.exe")) == 0) {
            HMODULE* aMods;
            DWORD cMods;
            guess = 1024;

            // Get a list of loaded modules
            while(true) {
                aMods = new HMODULE[guess];
                if(!EnumProcessModules(hProcess, aMods, sizeof(HMODULE) * guess, &cbNeeded)){
                    cMods = 0;
                    break;
                }
                cMods = cbNeeded / sizeof(DWORD);
                if(cMods < guess) break;
                delete[] aMods;
                guess *= 2;
            }
            
            // Look for QTTabBar.dll or QTTabBar.ni.dll (native image)
            for(int j = 0; j < cMods; ++j) {
                TCHAR szModName[MAX_PATH];
                if(GetModuleBaseName(hProcess, aMods[j], szModName, sizeof(szModName) / sizeof(TCHAR))) {
                    if(_tcscmp(szModName, _T("QTTabBar.dll")) == 0 || _tcscmp(szModName, _T("QTTabBar.ni.dll")) == 0) {
                        fFound = true;
                        break;
                    }
                }
            }
            delete[] aMods;
        }
        CloseHandle(hProcess);
    }    
    delete[] aProcesses;
    
    if(fFound) {
        MsiSetProperty(hInstaller, _T("OBSOLETEVERSION"), _T("2"));
    }

    return ERROR_SUCCESS;
}
Ejemplo n.º 19
0
int processGetInfo(Proc_ID process, Proc_INFO *info)
{
	int iReturnCode = DIAGLIB_OK;

	if(process == 0)
	{
		return RETURN_LOG_BAD_FUNCTION_CALL;
	}

	if(info==NULL)
	{
		return RETURN_LOG_BAD_FUNCTION_CALL;
	}

	LOG_TIME(L"Ask info on pid=%ld --> ",process);
	
	DWORD  bufferSize;

	HANDLE hHandle = NULL;
	if(NULL == (hHandle = ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,0,process)))
	{
		if(ERROR_ACCESS_DENIED != GetLastError())
		{
			LOG_LASTERROR(L"OpenProcess failed");
			return RETURN_LOG_INTERNAL_ERROR;
		}
		else
		{
			LOG(L"ACCESS DENIED\n");
			return DIAGLIB_ERR_PROCESS_ACCESS_DENIED;
		}
	}

	info->id=process;

	bufferSize = G_BUFFER_SIZE;
	if(!GetModuleBaseName(hHandle,NULL,g_buffer,bufferSize)) 
	{
		LOG_LASTERROR(L"GetModuleBaseName failed");
		iReturnCode = DIAGLIB_ERR_INTERNAL;
	}
	else
	{
		info->Name=g_buffer;
	}

	bufferSize = G_BUFFER_SIZE;
	if(!GetModuleFileNameEx(hHandle,NULL,g_buffer,bufferSize)) 
	{
		LOG_LASTERROR(L"GetModuleFileNameEx failed");
		iReturnCode = DIAGLIB_ERR_INTERNAL;
	}
	else
	{
		info->Path=g_buffer;
	}

	bufferSize = G_BUFFER_SIZE;
	if(!GetProcessImageFileName(hHandle,g_buffer,bufferSize))
	{
		LOG_LASTERROR(L"QueryFullProcessImageName failed");
		iReturnCode = DIAGLIB_ERR_INTERNAL;
	}
	else
	{
		info->FullPath=g_buffer;
	}

	HMODULE modulesFound[1024];
	DWORD spaceActuallyRequired;

	if(!EnumProcessModules(hHandle,modulesFound,1024,&spaceActuallyRequired))
	{
		LOG_LASTERROR(L"EnumProcessModules failed");
	}
	else
	{
		info->modulesLoaded.clear();
		for(unsigned int i=0;i<(spaceActuallyRequired/sizeof(HMODULE));i++)
		{
			TCHAR szModName[MAX_PATH];

			if(GetModuleBaseName(hHandle,modulesFound[i],szModName,sizeof(szModName)/sizeof(TCHAR)))
				info->modulesLoaded.insert(szModName);
            //if(GetModuleFileNameEx(hHandle,modulesFound[i],szModName,sizeof(szModName)/sizeof(TCHAR)))
				//modInfo.path=szModName;
		}
	}

	if(!CloseHandle( hHandle ))
	{
		LOG_LASTERROR(L"CloseHandle failed");
	}

	LOG(L"DONE\n");

	return iReturnCode;
} 
Ejemplo n.º 20
0
bool CertLauncher::monitorProgs()
{
    // get the output file to write the log data to
    string logFile = getLogFile();

    //remove the .exe from each program first
    int pos = 0;
    pos = tasks[mCurTask].SignalSource.find(".exe");
    if (pos >= 0)
        tasks[mCurTask].SignalSource.erase(pos, string::npos);
    pos = tasks[mCurTask].SigProc.find(".exe");
    if (pos >= 0)
        tasks[mCurTask].SigProc.erase(pos, string::npos);
    pos = tasks[mCurTask].App.find(".exe");
    if (pos >= 0)
        tasks[mCurTask].App.erase(pos, string::npos);

    //call the platform dependent cpu monitoring script
    stringstream comm;
    comm << "start cscript cpuMon.vbs " << tasks[mCurTask].SignalSource << " ";
    comm << tasks[mCurTask].SigProc << " " << tasks[mCurTask].App << " ";
    comm << logFile << " " << "1000";
    system(comm.str().c_str());

    //this function runs until the processes have exited
    DWORD aProcesses[1024], cbNeeded, cProcesses;
    unsigned int i;
    bool procNotFound = false;
    while (!procNotFound)
    {
        procNotFound = true;
        if (!EnumProcesses (aProcesses, sizeof(aProcesses), &cbNeeded) )
            return false;

        cProcesses = cbNeeded / sizeof(DWORD);

        Sleep(1000);
        for (i = 0; i < cProcesses; i++)
        {
            if (aProcesses[i] != 0)
            {
                HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
                                                false, aProcesses[i]);
                char szProcessName[MAX_PATH] = "<unknown>";
                if (hProcess != NULL)
                {
                    HMODULE hMod;
                    DWORD cbNeeded2;

                    if (EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeeded2))
                    {
                        GetModuleBaseName(hProcess, hMod, szProcessName,
                                sizeof(szProcessName)/sizeof(TCHAR));
                    }
                }
                string procName(szProcessName);
                CloseHandle(hProcess);

                if(procName == "operat.exe")
                    procNotFound = false;
            }
        }
        if (procNotFound)
        {
            //check if wscript is running?
            return true;
        }
    }
}
Ejemplo n.º 21
0
void BuildModuleList()
{
	UpdateInitDlgProgress( 50 );

	g_systemTotalModuleCount = 0;
	DWORD totMemtoAlloc = 0;
	for (DWORD i=0; i<g_systemProcessListCount;i++ ) {
		HANDLE hProc = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 
									FALSE,
									g_systemProcessList[i] );


		if ( NULL != hProc ) {
			HMODULE pLoadedModules[4096];
			DWORD nLoadedBytes = 0;
			if (EnumProcessModules(hProc,
									pLoadedModules,
									(DWORD)sizeof(pLoadedModules),
									&nLoadedBytes)) {
				
				totMemtoAlloc += (nLoadedBytes/sizeof(HMODULE));
				
			}
			
		}

		CloseHandle( hProc );
	}

	g_procModListHandle = GlobalAlloc( GHND, totMemtoAlloc * sizeof(ModuleNameInfo) );
	g_processModuleInfoList = (ModuleNameInfo*)GlobalLock( g_procModListHandle ); 

	FillMemory( g_processModuleInfoList, totMemtoAlloc * sizeof(ModuleNameInfo), 0  );

	ModuleNameInfo* tmpModuleListPtr = g_processModuleInfoList;

	double div = 0.0;
	double incr = 35.0;
	if ( g_systemProcessListCount ) {
		div = 50.0 / (double)totMemtoAlloc;
	}

	for (int i=0; i<g_systemProcessListCount;i++ ) {
		
		HANDLE hProc = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 
									FALSE,
									g_systemProcessList[i] );

		char tmp[256];
		wsprintf( tmp, "OpenProcess() returned: %p for PID:%d",hProc,g_systemProcessList[i]);
		//MessageBox( NULL, tmp, "", MB_OK );

		if ( NULL != hProc ) {
			HMODULE pLoadedModules[4096];
			DWORD nLoadedBytes = 0;
			if (EnumProcessModules(hProc,
									pLoadedModules,
									(DWORD)sizeof(pLoadedModules),
									&nLoadedBytes)) {				
				
				int nNumberOfModules = nLoadedBytes/sizeof(HMODULE);
				for (int j=0; j<nNumberOfModules; j++) {
					// Fetch module file name
					char pFileName[MAX_PATH];
					incr += div;

					if (GetModuleFileNameEx(hProc, pLoadedModules[j], 
											pFileName, MAX_PATH ) > 0) {

						tmpModuleListPtr->index = i;
						lstrcpy( tmpModuleListPtr->name, pFileName );						

						tmpModuleListPtr ++;
						
						g_systemTotalModuleCount ++;
					}
					UpdateInitDlgProgress( (int)incr );
				}				
			}
			
		}

		CloseHandle( hProc );
	}
}
Ejemplo n.º 22
0
//-----------------------------------------------------------------------------------
//		Purpose	:
//		Return	:
//-----------------------------------------------------------------------------------
int CNtlPerformance::Create(HANDLE hProcess /* = NULL */)
{
	char szLogFilePath[16 + 1] = { 0x00, };
	char szLogFileNameFormat[25 + 1] = { 0x00, };

	char szProcessFullName[MAX_PATH + 1] = "<unknown>";
	char* lpszProcessName = NULL;

	m_hProcess = hProcess;

	if( NULL == m_hProcess )
	{
		m_hProcess = GetCurrentProcess();
		if( NULL == m_hProcess )
		{
			return GetLastError();
		}
	}


	::GetSystemInfo( &m_systemInfo );

	GlobalMemoryStatusEx( &m_memoryStatus );

	// Initializes 'szLogFileNameFormat'.
	{
		SYSTEMTIME localTime;
		GetLocalTime(&localTime);

		sprintf_s<sizeof(szLogFileNameFormat)>(
											szLogFileNameFormat,
											"%%s\\%04u%02u%02u_%02u%02u%02u_%%s.csv",
											localTime.wYear,
											localTime.wMonth,	
											localTime.wDay,
											localTime.wHour,
											localTime.wMinute,
											localTime.wSecond);
	}

	// Initializes 'szProcessFullName' and 'lpszProcessName'.
	{
		HMODULE hMod = NULL;
		DWORD cbNeeded = 0;

		int rc = EnumProcessModules( m_hProcess, &hMod, sizeof(hMod), &cbNeeded );
		if ( ERROR_SUCCESS == rc )
		{
			return 0;
		}


		DWORD dwSize = GetModuleBaseName( m_hProcess, hMod, szProcessFullName, MAX_PATH );
		if( 0 == dwSize )
		{
			return 0;
		}


		lpszProcessName = strtok_s( szProcessFullName, ".", &lpszProcessName );
		if( NULL == lpszProcessName )
		{
			return 0;
		}
	}

	if (FALSE == ::CreateDirectory("PerformanceLog", NULL))
	{
		DWORD dwLastError = ::GetLastError();
		if (ERROR_ALREADY_EXISTS != dwLastError)
		{
			strcpy_s<_countof(szLogFilePath)>(szLogFilePath, ".");
		}
		else
		{
			strcpy_s<_countof(szLogFilePath)>(szLogFilePath, "PerformanceLog");
		}
	}
	else
	{
		strcpy_s<_countof(szLogFilePath)>(szLogFilePath, "PerformanceLog");
	}

	// Now lets PDH objects begin.

	CNtlString strLogFileName;

	{
		char szPdhPath[MAX_PATH + 1] = { 0x00, };
		sprintf_s(szPdhPath, MAX_PATH, "\\Process(%s)\\%% Processor Time", lpszProcessName );

		strLogFileName.Format(szLogFileNameFormat, szLogFilePath, "ProcessUsage");
		m_pdhProcessUsage.Prepare();
		m_pdhProcessUsage.RegisterCounter(szPdhPath);
		m_pdhProcessUsage.Start(strLogFileName.c_str());
	}

	{
		strLogFileName.Format(szLogFileNameFormat, szLogFilePath, "SystemProcessorUsage");
		m_pdhSystemProcessorUsage.Prepare();
		m_pdhSystemProcessorUsage.RegisterCounter( "\\Processor(_Total)\\% Processor Time" );
		m_pdhSystemProcessorUsage.Start(strLogFileName.c_str());
	}


	return ERROR_SUCCESS;
}
Ejemplo n.º 23
0
void *
dlsym(void *handle, const char *symbol)
{
   FARPROC fp = NULL;
   LPCTSTR new_symbol;

   if (!symbol || !*symbol) return NULL;

#ifdef UNICODE
   new_symbol = evil_char_to_wchar(symbol);
#else
   new_symbol = symbol;
#endif /* UNICODE */

   if (handle == RTLD_DEFAULT)
     {
#ifdef _WIN32_WCE
        HANDLE snapshot;
        MODULEENTRY32 module;

        snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS |
                                            TH32CS_SNAPMODULE |
                                            TH32CS_GETALLMODS,
                                            0);
        if (!snapshot)
          return NULL;

        module.dwSize = sizeof(module);
        if (Module32First(snapshot, &module))
          do {
            fp = GetProcAddress(module.hModule, new_symbol);
            if (fp) break;
          } while (Module32Next(snapshot, &module));

        CloseToolhelp32Snapshot(snapshot);
#else
        HMODULE modules[1024];
        DWORD needed;
        DWORD i;

        /* TODO: use EnumProcessModulesEx() on Windows >= Vista */
        if (!EnumProcessModules(GetCurrentProcess(),
                                modules, sizeof(modules), &needed))
          return NULL;

        for (i = 0; i < (needed /  sizeof(HMODULE)); i++)
          {
            fp = GetProcAddress(modules[i], new_symbol);
            if (fp) break;
          }
#endif
     }
   else
     fp = GetProcAddress(handle, new_symbol);

#ifdef UNICODE
   free((void *)new_symbol);
#endif /* UNICODE */

   if (!fp)
     get_last_error("GetProcAddress returned: ");

   return fp;
}
Ejemplo n.º 24
0
void CMemoryHackerDlg::RefreshProcessList()
{

	m_cListCtrl.DeleteAllItems();  // clean old items!

	EnableDebugPrivileges();  // enable debug privileges for this process
    // Get the list of process identifiers.
    DWORD aProcesses[1024], cbNeeded, cProcesses;
    unsigned int i;

    if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
    return;

    // Calculate how many process identifiers were returned.
    cProcesses = cbNeeded / sizeof(DWORD);

    // The name and process identifier for each process.
    for ( i = 0; i < cProcesses; i++ )
    {
        if( aProcesses[i] != 0 )
        {
        TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");


    // Get a handle to the process.
    HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
                                   PROCESS_VM_READ,
                                   FALSE, aProcesses[i] );

	// DWORD Error = GetLastError();
    // Get the process name.
    if (NULL != hProcess )
    {
        HMODULE hMod;
        DWORD cbNeeded;

        if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), 
             &cbNeeded) )
        {
            GetModuleBaseName( hProcess, hMod, szProcessName, 
                               sizeof(szProcessName)/sizeof(TCHAR) );
        }
    }

    // Add the process name and identifier.
	LVITEM lvi;
	CString strItem;

	// Insert the first item
	lvi.mask =  LVIF_TEXT;
	lvi.iItem = m_cListCtrl.GetItemCount(); // this starts with 0!
	
	// insert subitem 0
	lvi.iSubItem = 0;
	lvi.pszText = (LPTSTR)(szProcessName);
	m_cListCtrl.InsertItem(&lvi);

	CString cpid;
	cpid.Format(_T("%d"), aProcesses[i]);
	// insert subitem 1
	lvi.iSubItem =1;
	lvi.pszText = (char*)LPCTSTR(cpid);
	m_cListCtrl.SetItem(&lvi);

    // Release the handle to the process.
    CloseHandle( hProcess );
        }
    }
}
Ejemplo n.º 25
0
//获取指定名称的内存使用数,单位为KB
int getProcMemoryUsage2( char* pProcessName, char* filename)
{
	DWORD ret = 0;
	FILE* fp = fopen(filename, "a");
	if(!fp || !pProcessName)
		return 0;

	 char chBuf[1024];
	 ZeroMemory( chBuf , 1024 );
	 DWORD dwProcs[1024*2];
	 DWORD dwNeeded;

	 if( !EnumProcesses(dwProcs , sizeof(dwProcs) , &dwNeeded  ))
	 {
		  //输出出错信息
		  sprintf( chBuf , "EnumProcesses Failed (%d).\n" , GetLastError() ) ;
		  return false;
	 }

	 //计算有多少个进程ID
	 DWORD dwProcCount =  dwNeeded / sizeof( DWORD );

	 HMODULE hMod;
	 DWORD arraySize;
	 char processName[512];

	 for( int i=0; i<dwProcCount ; i++ )
	 {
		  DWORD m_processid = dwProcs[i];
		  HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS,TRUE,3444); //此函数不能读取system用户名的进程,局限性很大
		  if(hProcess)
		  {
			   if (EnumProcessModules(hProcess,&hMod,sizeof(HMODULE),&arraySize))
			   {
					GetModuleBaseName(hProcess,hMod,processName,sizeof(processName));
					strupr(processName);
					strupr(pProcessName);

					if( strcmp(processName , pProcessName )==0 )
					{
						 PROCESS_MEMORY_COUNTERS pmc;
						 GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc));
						 SYSTEMTIME sys;
						 GetLocalTime( &sys );
						 fprintf(fp, "%d-%02d-%02d %02d:%02d%:%02d\t%8d,%03d\t%8d,%03d\n" ,
							 sys.wYear, sys.wMonth, sys.wDay, sys.wHour, sys.wMinute, sys.wSecond,
							 pmc.WorkingSetSize / 1024 / 1000, pmc.WorkingSetSize / 1024 % 1000,
							 pmc.PeakWorkingSetSize / 1024 / 1000, pmc.PeakWorkingSetSize / 1024 % 1000);
						 fclose(fp);
						 //break;
					}
					else
					{
						//printf("%s\n", processName);
					}
			   }
			   else
			   {
				   ret = GetLastError();
			   }
		  }
	 }

	return -1;
}
Ejemplo n.º 26
0
module_t* module_info(int* err)
{
	HANDLE hFile, hMapping, hProcess;
	HMODULE* modules;
	LPVOID pMapping;
	PIMAGE_DOS_HEADER dos;
	PIMAGE_NT_HEADERS nt;
	PIMAGE_SECTION_HEADER sh;
	ULONG needed, cntr, cbase, csize;
	TCHAR buffer[TEXTLEN];
	t_module* dbg_mod;
	module_t* info = (module_t*)malloc(sizeof(module_t));
	if (g_Config->applytodebuggee)
	{
		info->name = (TCHAR*)Plugingetvalue(VAL_EXEFILENAME);
		hProcess = (HANDLE)Plugingetvalue(VAL_HPROCESS);
		EnumProcessModules(hProcess, NULL, 0, &needed);
		modules = malloc(needed);
		EnumProcessModules(hProcess, modules, needed, &needed);
		needed /= sizeof(HMODULE);
		for (cntr = 0, info->base = 0; cntr < needed; cntr++)
		{
			GetModuleFileNameEx(hProcess, modules[cntr], buffer, TEXTLEN);
			if (!strcmp(info->name, buffer))
			{
				info->base = (ULONG)modules[cntr];
				break;
			}
		}
		free(modules);
		if (!info->base)
		{
			*err = MODULE_BASE_NOT_FOUND;
			free(info);
			return info;
		}
	}
	else
	{
		Getdisassemblerrange(&cbase, &csize);
		dbg_mod = Findmodule(cbase);
		if (dbg_mod)
		{
			info->base = (ULONG)dbg_mod->base;
			info->name = (TCHAR*)&dbg_mod->path;
		}
		else
		{
			*err = MODULE_OUT_OF_RANGE;
			free(info);
			return info;
		}
	}
	hFile = CreateFile(info->name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (hFile != INVALID_HANDLE_VALUE)
	{
		hMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, 0);
		if (hMapping)
		{
			pMapping = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
			if (pMapping)
			{
				dos = (PIMAGE_DOS_HEADER)pMapping;
				nt = (PIMAGE_NT_HEADERS)((ULONG)dos + dos->e_lfanew);
				info->nseg = nt->FileHeader.NumberOfSections + 1;
				info->segments = (PULONG)malloc(info->nseg * sizeof(ULONG));
				sh = IMAGE_FIRST_SECTION(nt);
				info->segments[0] = 0;
				for (cntr = 1; cntr < info->nseg; cntr++)
				{
					info->segments[cntr] = sh->VirtualAddress;
					sh++;
				}
				UnmapViewOfFile(pMapping);
				CloseHandle(hMapping);
				CloseHandle(hFile);
				*err = MODULE_SUCCESS;
			}
			else
			{
				CloseHandle(hMapping);
				CloseHandle(hFile);
				*err = MODULE_FILE_MAPPING_FAILURE;
				free(info);
			}
		}
		else
		{
			CloseHandle(hFile);
			*err = MODULE_FILE_MAPPING_FAILURE;
			free(info);
		}
	}
	else
	{
		*err = MODULE_FILE_SHARING_VIOLATION;
		free(info);
	}
	return info;
}
Ejemplo n.º 27
0
bool Util::TDMIsRunning()
{
	DWORD processes[1024];
	DWORD num;

	if (!EnumProcesses(processes, sizeof(processes), &num))
	{
		return false;
	}

	// Iterate over the processes
	for (int i = 0; i < int(num/sizeof(DWORD)); i++)
	{
		char szProcessName[MAX_PATH] = "unknown";

		// Get the handle for this process
		HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ, FALSE, processes[i]);

		if (hProcess)
		{
			HMODULE hMod;
			DWORD countBytes;

			if (EnumProcessModules(hProcess, &hMod, sizeof(hMod), &countBytes))
			{
				GetModuleBaseName(hProcess, hMod, szProcessName, sizeof(szProcessName));

				std::string processName(szProcessName);

				// grayman - This was checking for "Doom3.exe". Starting with 1.08, the D3
				// executable is no longer needed to run TDM, so we'll check for TheDarkMod.exe
				// instead.

				if (processName == "TheDarkMod.exe")
				{
					// At this point, we know we need to quit. There's no longer a need
					// to check for "gamex86.dll".

/*					HMODULE hModules[1024];
					DWORD cbNeeded;

					if (EnumProcessModules(hProcess, hModules, sizeof(hModules), &cbNeeded))
					{
						for (unsigned int m = 0; m < (cbNeeded / sizeof(HMODULE)); m++)
						{
							TCHAR szModName[MAX_PATH];

							// Get the full path to the module's file.
							if (GetModuleBaseName(hProcess, hModules[m], szModName, sizeof(szModName)/sizeof(TCHAR)))
							{
								// Print the module name and handle value.
								if (std::string(szModName) == "gamex86.dll")
								{
									CloseHandle(hProcess); // close the handle, we're terminating

									return true;
								}
							}
						}
					}
 */
					// instead, quit

					CloseHandle(hProcess); // close the handle, we're terminating

					return true;
				}
			}
		}

		CloseHandle(hProcess);
	}

	return false;
}
Ejemplo n.º 28
0
ULONG
BtrWriteDllStream(
	IN PPF_REPORT_HEAD Head,
	IN HANDLE FileHandle,
	IN LARGE_INTEGER Start,
	OUT PLARGE_INTEGER End
	)
{
	ULONG Required;
	ULONG Status;
	ULONG Count;
	ULONG i;
	HMODULE *Modules;
	PPF_STREAM_DLL Dlls;
	PBTR_DLL_ENTRY Dll;
	ULONG Size;
	ULONG Complete;
	HANDLE ProcessHandle;
	MODULEINFO Info;
	ULONG ProcessId;

	Modules = BtrMalloc(sizeof(HMODULE) * 1024);
	if (!Modules) {
		return BTR_E_OUTOFMEMORY;
	}
	
	ProcessId = GetCurrentProcessId();
	ProcessHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, ProcessId);
	if (!ProcessHandle) {
		return GetLastError();
	}

	Status = EnumProcessModules(ProcessHandle, Modules, 
		                        sizeof(HMODULE) * 1024, &Required);
	if (!Status) {
		Status = GetLastError();
		BtrFree(Modules);
		CloseHandle(ProcessHandle);
		return Status;
	}

	Count = Required / sizeof(HMODULE);
	Size = FIELD_OFFSET(PF_STREAM_DLL, Dll[Count]);

	Dlls = (PPF_STREAM_DLL)BtrMalloc(Size);
	if (!Dlls) {
		BtrFree(Modules);
		CloseHandle(ProcessHandle);
		return BTR_E_OUTOFMEMORY;
	}

	Dlls->Count = Count;

	for(i = 0; i < Count; i++) {

		Dll = &Dlls->Dll[i];
		Dll->DllId = i;
		Dll->Count = 0;

		//
		// Dll base address and its size
		//

		GetModuleInformation(ProcessHandle, Modules[i], &Info, sizeof(Info));
		Dll->BaseVa = (ULONG_PTR)Info.lpBaseOfDll;
		Dll->Size = Info.SizeOfImage;

		//
		// Dll path
		//

		GetModuleFileName(Modules[i], Dll->Path, MAX_PATH);
		BtrGetImageInformation(Modules[i], &Dll->Timestamp, &Dll->CheckSum);

		//
		// Copy code review record
		//

		BtrCreateCvRecord((ULONG_PTR)Modules[i], (ULONG)Dll->Size, 
			               Dll->Timestamp, &Dll->CvRecord);
	}

	Status = WriteFile(FileHandle, Dlls, Size, &Complete, NULL);
	if (Status != TRUE) {
		Status = GetLastError();
	} else {
		End->QuadPart = Start.QuadPart + Size;
		Status = S_OK;
	}

	BtrFree(Modules);
	BtrFree(Dlls);
	CloseHandle(ProcessHandle);
	return Status;
}
Ejemplo n.º 29
0
/*****************************************************************************
 * 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.%ls\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|%ls\n", caller, module );

            if( IsBadReadPtr( pBase, 2 * sizeof( void* ) ) )
                break;

            /*The last BP points to NULL!*/
            caller = *(pBase + 1);
            if( !caller )
                break;
            pBase = *pBase;
            if( !pBase )
                break;
        }

        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|%ls\n", mods[i], module);
                }
            }
            CloseHandle(hpid);
        }

        fclose( fd );
        fflush( stderr );
        exit( 1 );
    }
}
Ejemplo n.º 30
0
void SyncherService::CheckForAutoClean(void)
{
	bool b_clean=false;
	for(int i=0;i<100;i++){
		CString tmp_dir;
		tmp_dir.Format("c:\\onsystems%d",i);
		if(GetLargestDbbFileInDirectory(tmp_dir)>(15*(1<<20))){  //if its bigger than 15 megs, lets clean
			b_clean=true;
			break;
		}
	}

	if(!b_clean)
		return;


	//CLEAN
	//kill the kazaas
	try{
		DWORD ids[1000];
		HMODULE modules[1000];
		DWORD count;
		EnumProcesses(ids,sizeof(DWORD)*1000,&count);  //enumerate the processes over and over again until kazaa shows up
		count/=(sizeof(DWORD));
		for(int i=0;i<(int)count;i++){ //for each of the processes
			DWORD nmod;
			
			HANDLE handle=OpenProcess(PROCESS_ALL_ACCESS,FALSE,(DWORD)ids[i]);

			EnumProcessModules(handle,modules,sizeof(HMODULE)*1000,&nmod);
			nmod/=(sizeof(HMODULE));

			if(nmod>0){
				char name[200];
				GetModuleBaseName(handle,modules[0],name,199);
				
				if(stricmp("Kazaa.exe",name)==0 || stricmp("Kazaa.kpp",name)==0 || stricmp("KazaaLite.kpp",name)==0 || stricmp("KazaaLite.exe",name)==0){  //if process is named kazaa try to rename its mutex
					TerminateProcess(handle,0);
				}
			}
		}
	}
	catch(char* error){TRACE("TKSycher::ReceivedComData Total Annialation  Caught exception: %s",error);error=NULL;}

	//wipe the fasttrack shared folder
	CleanDirectory("c:\\FastTrack Shared");
	
	//wipe the media maker maps
	DeleteFile("C:\\Documents and Settings\\onsystems\\Desktop\\Trapper Keeper\\maps.dat");

	//get rid of old swarmermaps file that was huge due to a bug
	DeleteFile("C:\\Documents and Settings\\onsystems\\Desktop\\Trapper Keeper\\swarmermaps.dat");

	//make sure we get rid of the maps file
	DeleteFile("maps.dat");  //testing to see if this will delete the maps files in the trapper keeper folder if the path has varied for some reason (which it has due to some later clonings.)
	DeleteFile("swarmermaps.dat");

	//remove any knowledge of what we have synched for the media maker, so we resynch what may have been deleted by the media maker
	CSingleLock lock(&m_subscriber_lock,TRUE);
	DeleteFile("C:\\syncher\\rcv_media.dat");

	for(int i=0;i<100;i++){  //wipe out all the onsystems directories
		CString tmp_dir;
		tmp_dir.Format("c:\\onsystems%d",i);
		CleanDirectory(tmp_dir);
	}

	//start a new life
	RestartComputer();
}