Example #1
0
/// <summary>
/// Unlink memory VAD node
/// </summary>
/// <param name="imageMem">Image to purge</param>
/// <returns>bool on success</returns>
bool MMap::UnlinkVad( const MemBlock& imageMem )
{
    HANDLE hFile = CreateFile( _T( "\\\\.\\VadPurge" ), GENERIC_ALL, 0, NULL, OPEN_EXISTING, 0, NULL );

    // Load missing driver
    if (hFile == INVALID_HANDLE_VALUE)
    {
        std::wstring drvPath = Utils::GetExeDirectory() + L"\\";

        if (IsWindows8Point1OrGreater())
            drvPath += L"VadPurge81.sys";
        else if(IsWindows8OrGreater())
            drvPath += L"VadPurge8.sys";
        else if(IsWindows7OrGreater())
            drvPath += L"VadPurge7.sys";

        NTSTATUS status = Utils::LoadDriver( L"VadPurge", drvPath );

        if (status != ERROR_SUCCESS && status != STATUS_IMAGE_ALREADY_LOADED)
            return false;

        hFile = CreateFile( _T( "\\\\.\\VadPurge" ), GENERIC_ALL, 0, NULL, OPEN_EXISTING, 0, NULL );
    }

    //
    // Lock pages in working set before unlinking
    // UserMode page faults can't be resolved without VAD record
    //
    if (hFile != INVALID_HANDLE_VALUE)
    {
        //
        // Adjust working set and lock pages
        //
        SIZE_T sizeMin = 0, sizeMax = 0;
        BOOL ret = FALSE;

        GetProcessWorkingSetSize( _process.core().handle(), &sizeMin, &sizeMax );
        SetProcessWorkingSetSize( _process.core().handle(), sizeMin + imageMem.size(), sizeMax + imageMem.size() );

        PVOID pBase = imageMem.ptr<PVOID>();
        ULONG size = static_cast<ULONG>(imageMem.size());
        NTSTATUS status = GET_IMPORT( NtLockVirtualMemory )(_process.core().handle(), &pBase, &size, 1);

        // Continue only if pages are locked
        if (status == STATUS_SUCCESS)
        {
            PURGE_DATA data = { _process.core().pid(), 1, { imageMem.ptr<ULONGLONG>(), imageMem.size() } };
            DWORD junk = 0;

            ret = DeviceIoControl( hFile, static_cast<DWORD>(IOCTL_VADPURGE_PURGE), &data, sizeof(data), NULL, 0, &junk, NULL );
        }

        CloseHandle( hFile );

        return (status == STATUS_SUCCESS && ret == TRUE) ? true : false;
    }

    return false;
}
Example #2
0
// ----------------------------------------------------------------------------------------
void FreeMemory(void *lParam)
{
    while (1)
    {
        Sleep(20000);
        SetProcessWorkingSetSize(GetCurrentProcess(), -1, -1);
    }
}
Example #3
0
int fnShowHide(WPARAM, LPARAM)
{
	BOOL bShow = FALSE;

	int iVisibleState = cli.pfnGetWindowVisibleState(cli.hwndContactList, 0, 0);

	//bShow is FALSE when we enter the switch.
	switch (iVisibleState) {
	case GWVS_PARTIALLY_COVERED:
		//If we don't want to bring it to top, we can use a simple break. This goes against readability ;-) but the comment explains it.
		if (!db_get_b(NULL, "CList", "BringToFront", SETTING_BRINGTOFRONT_DEFAULT))
			break;
	case GWVS_COVERED:     //Fall through (and we're already falling)
	case GWVS_HIDDEN:
		bShow = TRUE;
		break;
	case GWVS_VISIBLE:     //This is not needed, but goes for readability.
		bShow = FALSE;
		break;
	case -1:               //We can't get here, both cli.hwndContactList and iStepX and iStepY are right.
		return 0;
	}

	if (bShow == TRUE) {
		RECT rcWindow;

		ShowWindow(cli.hwndContactList, SW_RESTORE);
		if (!db_get_b(NULL, "CList", "OnTop", SETTING_ONTOP_DEFAULT))
			SetWindowPos(cli.hwndContactList, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
		else
			SetWindowPos(cli.hwndContactList, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);

		SetForegroundWindow(cli.hwndContactList);
		db_set_b(NULL, "CList", "State", SETTING_STATE_NORMAL);

		//this forces the window onto the visible screen
		GetWindowRect(cli.hwndContactList, &rcWindow);
		if (Utils_AssertInsideScreen(&rcWindow) == 1) {
			MoveWindow(cli.hwndContactList, rcWindow.left, rcWindow.top,
				rcWindow.right - rcWindow.left, rcWindow.bottom - rcWindow.top, TRUE);
		}
	}
	else {                      //It needs to be hidden
		if (db_get_b(NULL, "CList", "ToolWindow", SETTING_TOOLWINDOW_DEFAULT) ||
			db_get_b(NULL, "CList", "Min2Tray", SETTING_MIN2TRAY_DEFAULT)) {
			ShowWindow(cli.hwndContactList, SW_HIDE);
			db_set_b(NULL, "CList", "State", SETTING_STATE_HIDDEN);
		}
		else {
			ShowWindow(cli.hwndContactList, SW_MINIMIZE);
			db_set_b(NULL, "CList", "State", SETTING_STATE_MINIMIZED);
		}

		if (db_get_b(NULL, "CList", "DisableWorkingSet", 1))
			SetProcessWorkingSetSize(GetCurrentProcess(), -1, -1);
	}
	return 0;
}
BOOL My_SetProcessWorkingSetSize()
{
	HANDLE hProcess=NULL;
	SIZE_T dwMinimumWorkingSetSize=NULL;
	SIZE_T dwMaximumWorkingSetSize=NULL;
	BOOL returnVal_Real = NULL;
	BOOL returnVal_Intercepted = NULL;

	DWORD error_Real = 0;
	DWORD error_Intercepted = 0;
	disableInterception();
	returnVal_Real = SetProcessWorkingSetSize (hProcess,dwMinimumWorkingSetSize,dwMaximumWorkingSetSize);
	error_Real = GetLastError();
	enableInterception();
	returnVal_Intercepted = SetProcessWorkingSetSize (hProcess,dwMinimumWorkingSetSize,dwMaximumWorkingSetSize);
	error_Intercepted = GetLastError();
	return ((returnVal_Real == returnVal_Intercepted) && (error_Real == error_Intercepted));
}
Example #5
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	SetProcessWorkingSetSize(GetCurrentProcess(), -1, -1);
	HWND hwnd;
	MSG messages;

	WNDCLASSEX win_main;

	SetProcessWorkingSetSize(GetCurrentProcess(), -1, -1);

	HICON hICON = NULL;
	win_main.hInstance = hInstance;
	win_main.style = CS_HREDRAW | CS_VREDRAW;
	win_main.cbSize = sizeof(WNDCLASSEX);
	win_main.cbClsExtra = 0;
	win_main.cbWndExtra = 0;
	win_main.lpszClassName = "LifeGame";
	win_main.lpszMenuName = NULL;
	win_main.lpfnWndProc = Procedure;
	win_main.hIcon = hICON;
	win_main.hIconSm = hICON;
	win_main.hCursor = LoadCursor(NULL, IDC_ARROW);
	win_main.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);

	if (!RegisterClassEx(&win_main))
		return 0;

	hwnd = CreateWindowEx(0, "LifeGame", "LifeGame", WS_SYSMENU | WS_MINIMIZEBOX, CW_USEDEFAULT,
		CW_USEDEFAULT, win_width+16, win_height+39, HWND_DESKTOP, NULL, hInstance, NULL);

	ShowWindow(hwnd, nCmdShow);

	ZeroMemory(&messages, sizeof(messages));
	while (messages.message != WM_QUIT)
	{
		if (PeekMessage(&messages, NULL, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&messages);
			DispatchMessage(&messages);
		}
	}
	return messages.wParam;
}
Example #6
0
LRESULT CALLBACK PluginProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    if (message == BB_BROADCAST)
    {
        if (!_stricmp("@ShrinkMemory", (char*)(lParam)))
            SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
        return 0;
    }
    return DefWindowProc(hwnd, message, wParam, lParam);
}
Example #7
0
static VOID CALLBACK TrayIconAutoHideTimer(HWND hwnd, UINT, UINT_PTR idEvent, DWORD)
{
	KillTimer(hwnd, idEvent);
	HWND hwndClui = pcli->hwndContactList;
	HWND ActiveWindow = GetActiveWindow();
	if (ActiveWindow == hwndClui) return;
	if (CLUI_CheckOwnedByClui(ActiveWindow)) return;

	CListMod_HideWindow();
	SetProcessWorkingSetSize(GetCurrentProcess(), -1, -1);
}
Example #8
0
void CLuzj_ZTEDlg::OnTrayShow()
{   
	if (IsWindowVisible())
	{
		ShowWindow(SW_HIDE);
		SetProcessWorkingSetSize(GetCurrentProcess(),-1,-1);
	} 
	else
	{
		ShowWindow(SW_SHOW);
	}
}
Example #9
0
void	xrMemory::mem_compact	()
{
	RegFlushKey						( HKEY_CLASSES_ROOT );
	RegFlushKey						( HKEY_CURRENT_USER );
	if (g_allow_heap_min)
		_heapmin					( );
	HeapCompact					(GetProcessHeap(),0);
	if (g_pStringContainer)			g_pStringContainer->clean		();
	if (g_pSharedMemoryContainer)	g_pSharedMemoryContainer->clean	();
	if (strstr(Core.Params,"-swap_on_compact"))
		SetProcessWorkingSetSize	(GetCurrentProcess(),size_t(-1),size_t(-1));
}
Example #10
0
int ShowHide(WPARAM, LPARAM)
{
	BOOL bShow = FALSE;

	int iVisibleState = pcli->pfnGetWindowVisibleState(pcli->hwndContactList, 0, 0);

	if (IsIconic(pcli->hwndContactList)) {
		SendMessage(pcli->hwndContactList, WM_SYSCOMMAND, SC_RESTORE, 0);
		bShow = TRUE;
	}
	else {
		switch (iVisibleState) {
		case GWVS_PARTIALLY_COVERED:
			//If we don't want to bring it to top, we can use a simple break. This goes against readability ;-) but the comment explains it.
			if (!db_get_b(NULL, "CList", "BringToFront", SETTING_BRINGTOFRONT_DEFAULT))
				break;
		case GWVS_COVERED:     //Fall through (and we're already falling)
		case GWVS_HIDDEN:
			bShow = TRUE;
			break;
		case GWVS_VISIBLE:     //This is not needed, but goes for readability.
			bShow = FALSE;
			break;
		case -1:               //We can't get here, both cli.hwndContactList and iStepX and iStepY are right.
			return 0;
		}
	}

	if (bShow == TRUE) {
		RECT rcWindow;

		SetWindowPos(pcli->hwndContactList, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOREDRAW | SWP_NOSENDCHANGING | SWP_NOCOPYBITS);
		if (!db_get_b(NULL, "CList", "OnTop", SETTING_ONTOP_DEFAULT))
			SetWindowPos(pcli->hwndContactList, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW | SWP_NOSENDCHANGING | SWP_NOCOPYBITS);
		SetForegroundWindow(pcli->hwndContactList);
		//SetActiveWindow(pcli->hwndContactList);
		ShowWindow(pcli->hwndContactList, SW_SHOW);
		db_set_b(NULL, "CList", "State", SETTING_STATE_NORMAL);

		GetWindowRect(pcli->hwndContactList, &rcWindow);
		if (Utils_AssertInsideScreen(&rcWindow) == 1) {
			MoveWindow(pcli->hwndContactList, rcWindow.left, rcWindow.top,
				rcWindow.right - rcWindow.left, rcWindow.bottom - rcWindow.top, TRUE);
		}
	}
	else {                      //It needs to be hidden
		ShowWindow(pcli->hwndContactList, SW_HIDE);
		db_set_b(NULL, "CList", "State", SETTING_STATE_HIDDEN);
		if (db_get_b(NULL, "CList", "DisableWorkingSet", 1))
			SetProcessWorkingSetSize(GetCurrentProcess(), -1, -1);
	}
	return 0;
}
Example #11
0
static VOID CALLBACK TrayIconAutoHideTimer(HWND hwnd, UINT, UINT_PTR idEvent, DWORD)
{
	initcheck;
	mir_cslock lck(trayLockCS);

	KillTimer(hwnd, idEvent);
	HWND hwndClui = cli.hwndContactList;
	if (GetActiveWindow() != hwndClui) {
		ShowWindow(hwndClui, SW_HIDE);
		SetProcessWorkingSetSize(GetCurrentProcess(), -1, -1);
	}
}
Example #12
0
void CLuzj_ZTEDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == SC_MINIMIZE || (nID & 0xFFF0) == SC_CLOSE)
	{
		ShowWindow(SW_HIDE);
		SetProcessWorkingSetSize(GetCurrentProcess(),-1,-1);
		SetBubble("提示",STR_AppName" 正在后台运行着……",1);
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}
Example #13
0
int uSetCurProcessWorkingSetSize(usize_t MinWorkingSetSize, usize_t MaxWorkingSetSize, sys_call_error_fun fun)
{
#ifdef _WIN32
    BOOL res = SetProcessWorkingSetSize(
                  GetCurrentProcess(), // handle to the process
                  MinWorkingSetSize,   // minimum working set size
                  MaxWorkingSetSize    // maximum working set size
               );
    if (res == 0)
    {
        sys_call_error("SetProcessWorkingSetSize");
        return 1;
    }
    return 0;
#else
    return 0;
#endif
}
Example #14
0
static int extend_memory(size_t size)
{
        // page commit
        SIZE_T minimum=0,maximum=0;
        if(GetProcessWorkingSetSize(GetCurrentProcess(),&minimum,&maximum))
        {
         debug("btw, min=%d max=%d\n",minimum/1024,maximum/1024);

         minimum+=size;
         if(maximum<minimum+size) maximum=minimum+size;
         debug("kxasio: extending working space by %d bytes [min=%d max=%d]...\n",size,minimum,maximum);
         if(SetProcessWorkingSetSize(GetCurrentProcess(),minimum,maximum)==0)
         {
           char tmp_str[128];
           sprintf(tmp_str,"Error increasing current process's virtual memory amount. You should have Administrator privileges. Error code: %x\n",GetLastError());
           MessageBox(NULL,tmp_str,"kX ASIO",MB_OK|MB_ICONSTOP);
           return ASE_NoMemory;
         } 
        } else debug("!! kxasio: GetProcessWorkingSetSize error\n",GetLastError());
        return 0;
}
Example #15
0
LONG CLuzj_ZTEDlg::OnTrayNotification(WPARAM wparam, LPARAM lparam)
{   
	CMenu	m_menu;
	CPoint	m_point;
	switch (lparam)
	{
	case WM_RBUTTONDOWN:
		m_menu.CreatePopupMenu();
		if (IsWindowVisible())
		{
			m_menu.AppendMenu(MF_ENABLED, MENU_SHOW,_T("隐藏窗口"));
		} 
		else
		{
			m_menu.AppendMenu(MF_ENABLED, MENU_SHOW,_T("显示窗口"));
		}
		m_menu.AppendMenu(MF_ENABLED, MF_SEPARATOR);
		m_menu.AppendMenu(MF_ENABLED, MENU_EXIT,_T("退 出"));
		GetCursorPos(&m_point);
		m_menu.TrackPopupMenu(TPM_LEFTALIGN,m_point.x,m_point.y,this);
		break;
	case WM_LBUTTONDOWN:
		if (IsWindowVisible())
		{
			ShowWindow(SW_HIDE);
			SetProcessWorkingSetSize(GetCurrentProcess(),-1,-1);
		}
		else
		{
			ShowWindow(SW_SHOW);
			BringWindowToTop();
		}	
		break;
	}
	return 0;
}
Example #16
0
int execute(char *exname, char *inname, char *outname, double t, int max_mem)
{
  STARTUPINFO si;
  PROCESS_INFORMATION pi;
  int ifsuccess = EXE_RESULT_OK;
  
  ZeroMemory(&si, sizeof(si));
  si.cb = sizeof(si);
  ZeroMemory(&pi, sizeof(pi));
  
  setstartupinfo(&si, inname, outname);
  
  if(!CreateProcess( NULL,  // No module name (use command line). 
		     TEXT(exname), // Command line. 
		     NULL,  // Process handle not inheritable. 
		     NULL,  // Thread handle not inheritable. 
		     TRUE,  // Set handle inheritance to FALSE. 
		     0,     // No creation flags. 
		     NULL,  // Use parent's environment block. 
		     NULL,  // Use parent's starting directory. 
		     &si,   // Pointer to STARTUPINFO structure.
		     &pi))  // Pointer to PROCESS_INFORMATION structure. 
    {
      //printf( "CreateProcess failed (%d).\n", GetLastError() );
    }
  //fprintf(stderr,"Process ID: %ld\n",pi.dwProcessId);
  //fprintf(stderr,"time limit = %d\n",t);

  SetProcessWorkingSetSize(pi.hProcess,
			   1,
			   max_mem);
  
  // checking memory usage
  // wait 0.1 sec before checking mem usage
  Sleep(INITIAL_WAIT_FOR_MEM_CHECK);
  if(!check_memory_usage(pi.dwProcessId,max_mem)) {
    // using too much memory
    printf("memory exceeded (beginning)\n");
    PrintMemoryInfo(pi.dwProcessId);
    ifsuccess = EXE_RESULT_MEMORY;
  }

  if((ifsuccess == EXE_RESULT_MEMORY) ||
     (WaitForSingleObject(pi.hProcess, 
			  (int)(t*1000) + 1 
			  - INITIAL_WAIT_FOR_MEM_CHECK)==WAIT_TIMEOUT)) {
    // need to kill...
    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pi.dwProcessId);
    
    if(hProcess != NULL) {
      fprintf(stderr,"killing pid: %ld\n",pi.dwProcessId);
      TerminateProcess(hProcess, 0);
      wait_dialog();
    } else {
      DWORD dwNtvdmId = get_ntvdm_pid();
      fprintf(stderr,"killing (ntvdm) pid: %ld\n",dwNtvdmId);
      if(dwNtvdmId!=0) {
	hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwNtvdmId);
	TerminateProcess(hProcess, 0);
      } else {
        fprintf(stderr,"killing process error\n");
      }
      
      if(get_ntvdm_pid()!=0) {
	fprintf(stderr,"killing error, ntvdm.exe still remains;");
	fprintf(stderr,"please MANUALLY kill it.");
	fflush(stderr);
	do {
	  Sleep(1000);
	} while(get_ntvdm_pid()!=0);
	fprintf(stderr,"... done\n");
	wait_dialog();
      }
    }
    if(ifsuccess != EXE_RESULT_MEMORY)
      ifsuccess = EXE_RESULT_TIMEOUT;
  }
  if((ifsuccess==EXE_RESULT_OK) && 
     (!check_memory_usage(pi.dwProcessId,max_mem))) {
    // using too much memory
    ifsuccess = EXE_RESULT_MEMORY;
  }
  wait_dialog();
  if(si.hStdInput!=NULL)
    CloseHandle(si.hStdInput);
  if(si.hStdOutput!=NULL)
    CloseHandle(si.hStdOutput);
  
  return ifsuccess;
}
Example #17
0
BOOL CLuzj_ZTEDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	//读取配置到文件配置对象中去
	Config.LoadConfig();

	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	SetWindowText(STR_AppName);
	status = INIT;
	m_bAuth = FALSE;
	m_DHCPThread = NULL;
	m_WebAuthThread = NULL;
	m_AuthThread = NULL;
	m_HttpHeartThread = NULL;

	editLog = (CEdit*)GetDlgItem(IDC_EDIT_LOG);

	//创建托盘图标
	m_tray.Create(this, WM_USER_TRAY_NOTIFICATION,STR_AppName, m_hIcon, 0);

	//修改列表控件
	GetWindowRect(&m_rc);
	m_rc.top=m_rc.bottom-5;    //设置状态栏的矩形区域
	m_StatusBar.Create(WS_CHILD |WS_VISIBLE|CBRS_BOTTOM,m_rc,this,20000);  
	int nParts[3]= {100,250,-1};      //分割尺寸
	m_StatusBar.SetParts(3, nParts);
	m_StatusBar.SetText("",0,0);
	m_StatusBar.SetText("",1,0);
	m_StatusBar.SetText("",2,0);
	
	//控制状态栏的显示
	SetTimer(1,1000,NULL);
	//开始的时候先将日志框隐藏
	OnLogshow();

	Log(I_MSG, "APP version:%s", STR_Version);
	Log(I_INFO, "Winpcap version:%s", pcap_lib_version());
	Log(I_INFO, "OS version:%s", GetOSVersion());

	//////////////////////////////////////////////////////////////////////////	
	int i=0,k=0;
	CString str;
	
	//if(Config.m_bAutoUpdate) CheckUpdate();

	CheckDlgButton(IDC_REMEMBER,Config.m_bRememberPWD?BST_CHECKED:BST_UNCHECKED);
	//////////////////////////////////////////////////////////////////////////
	//加载账号信息
	CString user,pass;	
	POSITION p = Config.m_UserInfo.GetStartPosition();	
	while(p != NULL) {
		Config.m_UserInfo.GetNextAssoc(p, user, pass);		
		m_ccb_username.AddString(user);		
	}
	k = m_ccb_username.FindStringExact(-1, Config.m_csLastUser);
	if(k < 0) k = 0;
	if(!Config.m_UserInfo.IsEmpty()) {
		m_ccb_username.SetCurSel(k);
		m_ccb_username.GetWindowText(user);
		GetDlgItem(IDC_PWD)->SetWindowText(Config.m_UserInfo[user]);		
	}
	
	//////////////////////////////////////////////////////////////////////////

	//////////////////////////////////////////////////////////////////////////
	//加载网卡信息	
	char errorBuffer[ PCAP_ERRBUF_SIZE ];		//错误信息缓冲区
	pcap_if_t		* allAdapters;				//适配器列表
	if(pcap_findalldevs(&allAdapters, errorBuffer) == -1 || allAdapters == NULL)
	{
		MessageBox("读取网卡信息失败,请确保你安装了WinPcap!","错误",MB_ICONERROR|MB_OK);
		pcap_freealldevs(allAdapters);
		CDialog::OnCancel();
	}

	k = 0; m_csAdapters.RemoveAll();
	pcap_if_t* adapter;//临时存放适配器
	char *szGuid = NULL;	
	Log(I_INFO, "LastNetcard:%s", Config.m_csNetCard);
    for(k = 0, adapter = allAdapters; adapter != NULL; adapter = adapter->next) {
		if(adapter->flags & PCAP_IF_LOOPBACK) continue;	

		szGuid = GetGUID(adapter->name);
		if(Config.m_bAutoFilter && TestAdapter(szGuid) != 0) continue;

		Log(I_INFO, "load netcard:(%d)%s(%s)", k, szGuid, adapter->description);
		m_csAdapters.Add(szGuid); m_ccbNetCard.AddString(adapter->description); 
		
		k++;
    }
	pcap_freealldevs(allAdapters);

	for(k = m_ccbNetCard.GetCount() - 1; k >= 0; k--) {
		if(stricmp(m_csAdapters[k], Config.m_csNetCard) == 0) break;		
	}
	
	if(k >= 0 && m_ccbNetCard.GetCount() > k) {		
		m_ccbNetCard.SetCurSel(k);
		Log(I_INFO, "select netcard:(%d)%s", k, m_csAdapters[k]);
	}
	
	this->Log(I_INFO, "加载网卡完成");
	//////////////////////////////////////////////////////////////////////////

	//使得开始按钮有效,而断开按钮无效
	UpdateStatus(FALSE);
	
	if (k >= 0 && Config.m_bAutologon == TRUE) OnStart();
	SetProcessWorkingSetSize(GetCurrentProcess(),-1,-1);
	return TRUE;  // return TRUE  unless you set the focus to a control
}
Example #18
0
int __cdecl main(int argc, char *argv[]) {
#define N_FRAME 100
#define N_PATCH 600000//(1<<LFSR_SIZE)
  const char* readfn = "\\\\.\\xillybus_rd"
	  , * writefn = "\\\\.\\xillybus_wr";
  HANDLE tid[2];
  struct xillyfifo fifo;
  unsigned int fifo_size = 4096*16;
  int write_fd, bTalk2FPGA = (int)(argc < 2);
  unsigned int n_frame = 0;
  unsigned int msg, n_msg;
  int rd;
  FILE* pixel_coeff_f = fopen("reducer_coeff_0.bin", "rb")
    , *ds_coeff_f = fopen("ds_0.bin", "rb");
  if(!pixel_coeff_f) {
    perror("Failed to open reducer_coeff");
    exit(errno);
  }
  if(!ds_coeff_f) {
    perror("Failed to open ds_coeff");
    exit(errno);
  }

  if(bTalk2FPGA) {
    //printf("Press any key to connect to FPGA\n"); getchar();
    write_fd = _open(writefn, O_WRONLY | _O_BINARY);
    if (write_fd < 0) {
      if (errno == ENODEV)
        fprintf(stderr, "(Maybe %s a write-only file?)\n", writefn);

      fprintf(stderr, "Failed to open %s", writefn);
      exit(1);
    }

    // If more than one FIFO is created, use the total memory needed instead
    // of fifo_size with SetProcessWorkingSetSize()
    if(fifo_size > 20000
      && !SetProcessWorkingSetSize(GetCurrentProcess()
            , 1024*1024 + fifo_size, 2048*1024 + fifo_size))
      errorprint("Failed to enlarge unswappable RAM limit", GetLastError());

    if (fifo_init(&fifo, fifo_size)) {
      perror("Failed to init");
      exit(1);
    }

    read_fd = _open(readfn, O_RDONLY | _O_BINARY);
    if (read_fd < 0) {
      perror("Failed to open read file");
      exit(1);
    }

    if (_setmode(1, _O_BINARY) < 0)
      fprintf(stderr, "Failed to set binary mode for standard output\n");

    // default security, default stack size, default startup flags
    tid[0] = CreateThread(NULL, 0, read_thread, &fifo, 0, NULL);
    if (tid[0] == NULL) {
      errorprint("Failed to create read thread", GetLastError());
      exit(1);
    }
    tid[1] = CreateThread(NULL, 0, report_thread, &fifo, 0, NULL);
    if (tid[1] == NULL) {
      errorprint("Failed to create report thread", GetLastError());
      exit(1);
    }
  }//end if(bTalk2FPGA)

  for(n_msg = 0; !feof(pixel_coeff_f); ) {
    rd = fread(&msg, sizeof(msg), 1, pixel_coeff_f);
    if(bTalk2FPGA) allwrite(write_fd, (unsigned char*)&msg, sizeof(msg));
    printf("weights 0x%08X\n", msg);
  } //end for

  for(; !feof(ds_coeff_f); ) {
    rd = fread(&msg, sizeof(msg), 1, ds_coeff_f);
    printf("DS 0x%08X\n", msg);
    if(bTalk2FPGA) allwrite(write_fd, (unsigned char*)&msg, sizeof(msg));
  } //end for

cleanup:
  if(bTalk2FPGA) {
    unsigned int msg = ~0;//Make the FPGA close the rd file
    allwrite(write_fd, (unsigned char*)&msg, sizeof(msg));
    _close(write_fd);
    _close(read_fd);

    // Wait for threads to exit
    if (WaitForSingleObject(tid[0], INFINITE) != WAIT_OBJECT_0) 
      errorprint("Failed waiting for read_thread to terminate"
        , GetLastError());
    fifo_destroy(&fifo);
  }
  fclose(ds_coeff_f);
  fclose(pixel_coeff_f);
  printf("Press any key to exit\n"); getchar();
  return 0;
}
Example #19
0
void CLuzj_ZTEDlg::get_packet(u_char *args, const struct pcap_pkthdr *pcaket_header, const u_char *packet)
{
	int retcode;
	static int good = 0;
	CLuzj_ZTEDlg *Dlg = (CLuzj_ZTEDlg*)args;
	/* declare pointers to packet headers */
	CPacket P;
	if(packet[15] == 0x00) { //eap_packet
		if(packet[18] == 0x01) {//request
			if(packet[22] == 0x01) { //identity
				Dlg->Log(I_INFO, "Server:Request Identity...");
				if(!(retcode=P.send_packet_response_Identity(Dlg->m_adapterHandle,
					packet,Dlg->m_MacAdd,Dlg->m_username,Dlg->m_usernameLen)))	{
					Dlg->Log(I_INFO, "send_packet_response_Identity:(%d)%s", retcode, pcap_geterr(Dlg->m_adapterHandle));					
					Dlg->UpdateStatus(FALSE); return;					
				}
				Dlg->Log(I_INFO, "Client:Response Identity:%s", Dlg->m_username);
			} else if(packet[22] == 0x04) {//md5 challenge
				Dlg->Log(I_INFO, "Server:Request MD5 Chanllenge...");
				if(!(retcode=P.send_packet_response_MD5(Dlg->m_adapterHandle,packet,Dlg->m_MacAdd,
					Dlg->m_username,Dlg->m_usernameLen,Dlg->m_password,Dlg->m_passwordLen))) {
					Dlg->Log(I_INFO, "send_packet_response_MD5:(%d)%s", retcode, pcap_geterr(Dlg->m_adapterHandle));
					Dlg->UpdateStatus(FALSE); return;
				}
				Dlg->Log(I_INFO, "Client:Response MD5 Chanllenge");				
			} else if(packet[22] == 0x02) {//notification
				Dlg->Log(I_INFO, "Server Notification:%s", (char*)packet+23);
			} else {//unknown
				Dlg->Log(I_INFO, "Unknown EAPOL Type:0x%02X", packet[22]);
			}
		} else if(packet[18] == 0x03) {//successful
			Dlg->status = AUTHED;
			SetProcessWorkingSetSize(GetCurrentProcess(),-1,-1);
			Dlg->UpdateStatus(TRUE);
			Dlg->ShowWindow(SW_HIDE);
			Dlg->Log(I_MSG, "认证成功.");

			if(Dlg->m_DHCPThread == NULL) 
				Dlg->m_DHCPThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)dhcp_thread, Dlg, 0, 0);
			
		} else if(packet[18] == 0x04) {//fail
			Dlg->UpdateStatus(FALSE);				
			Dlg->Log(I_ERR, "服务器认证失败,请查看日志信息!");
			Dlg->Log(I_INFO, (char*)packet+24);
			ExitThread(0);
			return;
		} else {//unknown
			Dlg->Log(I_INFO, "Unknown EAP Type:0x%02X", packet[18]);
		}
	} else if(packet[15] == 0x03) {//key		
		if(!(retcode=P.send_packet_key2(Dlg->m_adapterHandle,packet,Dlg->m_MacAdd))) {
			Dlg->Log(I_INFO, "send_packet_key2:(%d)%s", retcode, pcap_geterr(Dlg->m_adapterHandle));
			Dlg->UpdateStatus(FALSE);  return;
		}	
		if(good <= 3) Dlg->Log(I_INFO, good++ == 3 ? "正常在线." : "send_packet_key2...");	
		if(good >= 3) Dlg->status = ONLINE;

		//Dlg->HttpAuth();
	} else {//unknown
		Dlg->Log(I_INFO, "Unknown Type:0x%02X", packet[15]);
	}
   
    return;
}
Example #20
0
void FlushMemory()
{
	SetProcessWorkingSetSize(GetCurrentProcess(), 102400, 614400);
}
Example #21
0
ULONG 
FANCONTROL::DlgProc(HWND hwnd, ULONG msg, WPARAM mp1, LPARAM mp2)
{
	ULONG rc= 0;
		switch (msg) 
			{
			case WM_INITDIALOG:
				break;
			case WM_TIMER:
				switch (mp1)
				{
				case 1:	
					::PostMessage(this->hwndDialog, WM__GETDATA, 0, 0);
					if (tried2connect)
					{
						if (this->ShowTempIcon==1) 
						{
							this->ProcessTextIcons();  //icon Einstieg
						}
						else 
						{
							this->RemoveTextIcons();
						}

						if (this->pTaskbarIcon)
						{
							this->pTaskbarIcon->SetIcon(this->iFarbeIconB);

							if (_isConnected == FALSE)this->pTaskbarIcon->SetTooltip("not connected to tpfc service");
							else this->pTaskbarIcon->SetTooltip(Title2);

							if (_isConnected == TRUE && _hasShownConnected == FALSE){
									this->pTaskbarIcon->SetBalloon(NIIF_INFO, "TPFanControl Icon",
									"connected to TPFanControl service",11);
									_hasShownConnected = TRUE;}
							if (_isConnected == FALSE && _hasShownDisconnected == FALSE){
									this->pTaskbarIcon->SetBalloon(NIIF_ERROR, "TPFanControl Icon",
									"NOT connected to TPFanControl service",11);
									_hasShownDisconnected = TRUE;}
						}
					}
					break;
				default:
					break;

				}	//switch(mp1)



			//say windows not to hold much more memspace
            SetProcessWorkingSetSize(GetCurrentProcess(),65536,WANTED_MEM_SIZE);
			break;

		case WM_COMMAND:
				if (HIWORD(mp1)==BN_CLICKED || HIWORD(mp1)==EN_CHANGE) 
				{
					int cmd= LOWORD(mp1);

					switch (cmd) {
						case 5001: // bios
						case 5002: // smart
								   break;

						case 5010: // show window
								   ::ShowWindow(this->hwndDialog, TRUE);
								   ::SetForegroundWindow(this->hwndDialog);
								   break;

						case 5050: // donate
								   ::ShellExecute(NULL, "open", Title4, //"http://www.staff.uni-marburg.de/~schmitzr/donate.html", 
									   NULL, NULL, SW_SHOW);
								   break;

						case 5070: // show old temp icon
								   this->ShowTempIcon = NULL;
								   this->pTaskbarIcon= new	TASKBARICON(this->hwndDialog, 11, Title2);
								   //this->pTaskbarIcon->SetIcon(this->iFarbeIconB);
								   break;

						case 5080: // show temp icon
									delete this->pTaskbarIcon;
									this->pTaskbarIcon= NULL;
									this->ShowTempIcon = 1;
									break;

						case 5030: // hide window
								::CloseWindow(this->hwndDialog);
								break;

						case 5020: // end program
							::KillTimer(this->hwndDialog, m_titleTimer);
							::PostMessage(hwnd, WM__DISMISSDLG, IDCANCEL, 0); // exit from ProcessDialog() 
							break;
					}
				}
				break;

		case WM_CLOSE:
			::CloseWindow(this->hwndDialog);
				break;
		case WM_MOVE:
				break;
		case WM_SIZE:
				if (mp1==SIZE_MINIMIZED) {
				    ::ShowWindow(this->hwndDialog, FALSE);
				}
				rc= TRUE;
				break;
		case WM_DESTROY:
				break;

		//
		// USER messages
		//

		case WM__GETDATA:
			if (!this->hThread)
			{
				this->hThread= this->CreateThread(FANCONTROL_Thread, (ULONG)this);
			}
			break;


		case WM__NEWDATA:
	/*			if (this->hThread) {
					::WaitForSingleObject(this->hThread, INFINITE);
					::CloseHandle(this->hThread);
					this->hThread= 0;
				}
	*/
			break;

		case WM__TASKBAR:

				switch (mp2) 
				{
				    case WM_LBUTTONDOWN:
						if (!IsWindowVisible(this->hwndDialog))
						{
								::ShowWindow(this->hwndDialog, TRUE);
								::SetForegroundWindow(this->hwndDialog);
						}
						else	::CloseWindow(this->hwndDialog);
				        break;
				    case WM_LBUTTONUP:
						{
						BOOL 
						isshift= ::GetAsyncKeyState(VK_SHIFT) & 0x8000,
						isctrl= ::GetAsyncKeyState(VK_CONTROL) & 0x8000;
									int action= -1;
								// some fancy key dependent stuff could be done here
						}
						break;
				    case WM_LBUTTONDBLCLK:
						if (!IsWindowVisible(this->hwndDialog)){
								::ShowWindow(this->hwndDialog, TRUE);
								::SetForegroundWindow(this->hwndDialog);
						}
						else	::CloseWindow(this->hwndDialog);
				        break;
				    case WM_RBUTTONDOWN:
								{
								MENU m(5000);
									if (!IsWindowVisible(this->hwndDialog))
										m.DeleteMenuItem(5030);
									if (IsWindowVisible(this->hwndDialog))
										m.DeleteMenuItem(5010);
									if (this->ShowTempIcon == 0)
										m.DeleteMenuItem(5070);
									if (this->ShowTempIcon == 1)
										m.DeleteMenuItem(5080);
								m.Popup(this->hwndDialog);  
						}
						break;
				}
				rc= TRUE;
				break;
		default:
		break;
	}
	return rc;
}
Example #22
0
// ---------------------------------------------------------------------------
void TfrmMain::LiberarMemoria() {
	if (Win32Platform == VER_PLATFORM_WIN32_NT)
		SetProcessWorkingSetSize(GetCurrentProcess(), 0xFFFFFFFF, 0xFFFFFFFF);
}
Example #23
0
int
main()
{
    int round;
    int b, t;
    int res;

    INIT();

#ifdef USE_DYNAMO
    dynamorio_app_init();
    dynamorio_app_start();
#endif


    /* this doesn't do much in fact */
    res = SetProcessWorkingSetSize(GetCurrentProcess(),
                                   MINSIZE_KB*1024,
                                   MAXSIZE_KB*1024);
    // on Win2003 there is a SetProcessWorkingSetSizeEx that sets QUOTA_LIMITS_HARDWS_ENABLE


    if (res == 0)
        print("SetProcessWorkingSetSize failed GLE: %d\n", GetLastError());

    for (round = 0; round < ROUNDS; round++) {
#ifdef VERBOSE
        print("round %d\n", round);
#endif
        global_started = 0;
        global_finished = 0;

        /* do in a batch */
        for (b = 0; b < TOTAL_THREADS / BATCH_SIZE; b++) {
            for (t = 0; t < BATCH_SIZE; t++) {
                thread[t] = create_thread(executor);
                if (thread[t] == NULL)
                    print("GLE: %d\n", GetLastError());
                assert(thread[t] != NULL);
            }
            /* now synchronize with all of them - or maybe some? */

#ifdef VERBOSE
            print("started %d threads\n", TOTAL_THREADS);
#else
#ifndef SILENT
            print("started some threads\n");
#endif
#endif
            for (t = 0; t < BATCH_SIZE; t++) {
                assert(thread[t] != NULL);
                join_thread(thread[t]);
                CloseHandle((HANDLE)thread[t]);
                thread[t] = NULL; /* in case want to synch with some in a batch, but with all at the end */

                if (SWAP_OUT_AFTER_THREAD) {
                    res = SetProcessWorkingSetSize(GetCurrentProcess(),
                                                   -1, -1);
                }
            }
#ifdef VERBOSE
            print("some %d work, done %d\n", global_started, global_finished);
#endif
            if (SWAP_OUT_AFTER_BATCH) {
                res = SetProcessWorkingSetSize(GetCurrentProcess(),
                                               -1, -1);
            }
        }
    }

#ifdef USE_DYNAMO
    dynamorio_app_stop();
    dynamorio_app_exit();
#endif

    print("done\n");
    return 0;
}
Example #24
0
int _tmain(int argc, _TCHAR* argv[])
{
	// コンソール出力か?
	bool useConsole = _isatty(_fileno(stdout)) != 0;

	// メモリ状況の取得
	MEMORYSTATUSEX meminfo = {0};
	meminfo.dwLength = sizeof(MEMORYSTATUSEX);

	if (!GlobalMemoryStatusEx(&meminfo)) {
		_ftprintf(
			stderr,
			_T("GlobalMemoryStatusEx: errorcode: %ld\n"),
			GetLastError()
			);
		exit(1);
	}

	// 物理メモリ使用状況の表示
	size_t unit = 1024 * 1024; // 1 MegaBytes

	_ftprintf(
		stdout,
		_T("Phys: %I64d/%I64d MBytes\n"),
		meminfo.ullAvailPhys / unit,
		meminfo.ullTotalPhys / unit
		);

	// 最大ループ回数 = 空き物理メモリ(MB単位)
	size_t maxLoopCount = static_cast<size_t>(meminfo.ullAvailPhys / unit);
	if (argc > 1) {
		maxLoopCount = _ttoi(argv[1]);
	}

	// 現在のワーキングセットの取得
	HANDLE hProcess = GetCurrentProcess();
	SIZE_T curMinSize = 0;
	SIZE_T curMaxSize = 0;
	GetProcessWorkingSetSize(hProcess, &curMinSize, &curMaxSize);

	// ワーキングセットの設定
	SIZE_T maxMem = (maxLoopCount + 1) * unit + curMaxSize;
	if (!SetProcessWorkingSetSize(
		hProcess, maxMem, maxMem)) {
		_ftprintf(
			stderr,
			_T("SetProcessWorkingSetSizeEx: errorcode: %ld\n"),
			GetLastError()
			);
		// とりあえず継続してみる
	}

	// メモリを最大まで確保する.
	if (maxLoopCount > 0) {
		std::vector<void *> buf(maxLoopCount);
		for (size_t loopCount = 0; loopCount < maxLoopCount; loopCount++) {

			// コンソール出力であればプログレス表示
			if (useConsole) {
				_ftprintf(stderr, _T("allocating... %ld/%ld MBytes \r"), loopCount + 1, maxLoopCount);
			}

			// メモリの確保
			void *p = VirtualAlloc(NULL, unit, MEM_COMMIT, PAGE_READWRITE);
			if (p == NULL) {
				DWORD errcode = GetLastError();
				if (useConsole) {
					_ftprintf(stderr, _T("\n"));
				}
				_ftprintf(stderr, _T("VirtualAlloc: errorcode: %ld\n"), errcode);
				break;
			}
			
			// 確保済みメモリとして記憶する.
			buf[loopCount] = p;

			// 物理メモリをロックする
			if (!VirtualLock(p, unit)) {
				DWORD errcode = GetLastError();
				if (useConsole) {
					_ftprintf(stderr, _T("\n"));
				}
				_ftprintf(stderr, _T("VirtualLock: errorcode: %ld\n"), errcode);
				break;
			}
		}
		if (useConsole) {
			_ftprintf(stderr, _T("\n"));
		}

		// メモリを解放する
		for (size_t loopCount = 0; loopCount < maxLoopCount; loopCount++) {
			void *p = buf[loopCount];
			if (p) {
				VirtualUnlock(p, unit);
				VirtualFree(p, unit, MEM_DECOMMIT);
			}
		}
	}

	return 0;
}
Example #25
0
void JudgingThread::runProgram()
{
    result = CorrectAnswer;
    int extraTime = qCeil(qMax(2000, timeLimit * 2) * extraTimeRatio);
    
#ifdef Q_OS_WIN32
    SetErrorMode(SEM_NOGPFAULTERRORBOX);
    
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    SECURITY_ATTRIBUTES sa;
    
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    si.dwFlags = STARTF_USESTDHANDLES;
    ZeroMemory(&pi, sizeof(pi));
    ZeroMemory(&sa, sizeof(sa));
    sa.bInheritHandle = TRUE;
    
    if (task->getStandardInputCheck())
        si.hStdInput = CreateFile((const WCHAR*)(inputFile.utf16()), GENERIC_READ,
                                  FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa,
                                  OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    
    if (task->getStandardOutputCheck())
        si.hStdOutput = CreateFile((const WCHAR*)((workingDirectory + "_tmpout").utf16()), GENERIC_WRITE,
                                   FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa,
                                   CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    
    si.hStdError = CreateFile((const WCHAR*)((workingDirectory + "_tmperr").utf16()), GENERIC_WRITE,
                              FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa,
                              CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    
    QString values = environment.toStringList().join('\0') + '\0';
    if (! CreateProcess(NULL, (WCHAR*)(QString("\"%1\" %2").arg(executableFile, arguments).utf16()), NULL, &sa,
                        TRUE, HIGH_PRIORITY_CLASS | CREATE_NO_WINDOW, (LPVOID)(values.toLocal8Bit().data()),
                        (const WCHAR*)(workingDirectory.utf16()), &si, &pi)) {
        if (task->getStandardInputCheck()) CloseHandle(si.hStdInput);
        if (task->getStandardOutputCheck()) CloseHandle(si.hStdOutput);
        CloseHandle(si.hStdError);
        score = 0;
        result = CannotStartProgram;
        return;
    }
    
    PROCESS_MEMORY_COUNTERS_EX info;
    ZeroMemory(&info, sizeof(info));
    info.cb = sizeof(info);
    if (memoryLimit != -1) {
        GetProcessMemoryInfo(pi.hProcess, (PROCESS_MEMORY_COUNTERS*)&info, sizeof(info));
        if (qMax(info.PrivateUsage, info.PeakWorkingSetSize) > memoryLimit * 1024 * 1024) {
            TerminateProcess(pi.hProcess, 0);
            if (task->getStandardInputCheck()) CloseHandle(si.hStdInput);
            if (task->getStandardOutputCheck()) CloseHandle(si.hStdOutput);
            CloseHandle(si.hStdError);
            CloseHandle(pi.hProcess);
            CloseHandle(pi.hThread);
            score = 0;
            result = MemoryLimitExceeded;
            memoryUsed = timeUsed = -1;
            return;
        }
    }
    
	if (memoryLimit != -1)
        SetProcessWorkingSetSize(pi.hProcess, memoryLimit * 1024 * 1024 / 4, memoryLimit * 1024 * 1024);
    
    bool flag = false;
    QElapsedTimer timer;
    timer.start();
    
    while (timer.elapsed() <= timeLimit + extraTime) {
        if (WaitForSingleObject(pi.hProcess, 0) == WAIT_OBJECT_0) {
            flag = true;
            break;
        }
        if (memoryLimit != -1) {
            GetProcessMemoryInfo(pi.hProcess, (PROCESS_MEMORY_COUNTERS*)&info, sizeof(info));
            if (qMax(info.PrivateUsage, info.PeakWorkingSetSize) > memoryLimit * 1024 * 1024) {
                TerminateProcess(pi.hProcess, 0);
                if (task->getStandardInputCheck()) CloseHandle(si.hStdInput);
                if (task->getStandardOutputCheck()) CloseHandle(si.hStdOutput);
                CloseHandle(si.hStdError);
                CloseHandle(pi.hProcess);
                CloseHandle(pi.hThread);
                score = 0;
                result = MemoryLimitExceeded;
                memoryUsed = timeUsed = -1;
                return;
            }
        }
        QCoreApplication::processEvents();
        if (stopJudging) {
            TerminateProcess(pi.hProcess, 0);
            if (task->getStandardInputCheck()) CloseHandle(si.hStdInput);
            if (task->getStandardOutputCheck()) CloseHandle(si.hStdOutput);
            CloseHandle(si.hStdError);
            CloseHandle(pi.hProcess);
            CloseHandle(pi.hThread);
            return;
        }
        Sleep(10);
    }
    
    if (! flag) {
        TerminateProcess(pi.hProcess, 0);
        if (task->getStandardInputCheck()) CloseHandle(si.hStdInput);
        if (task->getStandardOutputCheck()) CloseHandle(si.hStdOutput);
        CloseHandle(si.hStdError);
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
        score = 0;
        result = TimeLimitExceeded;
        timeUsed = -1;
        return;
    }
    
    unsigned long exitCode;
    GetExitCodeProcess(pi.hProcess, &exitCode);
    if (exitCode != 0) {
        if (task->getStandardInputCheck()) CloseHandle(si.hStdInput);
        if (task->getStandardOutputCheck()) CloseHandle(si.hStdOutput);
        CloseHandle(si.hStdError);
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
        score = 0;
        result = RunTimeError;
        QFile file(workingDirectory + "_tmperr");
        if (file.open(QFile::ReadOnly)) {
            QTextStream stream(&file);
            message = stream.readAll();
            file.close();
        }
        memoryUsed = timeUsed = -1;
        return;
    }
    
    FILETIME creationTime, exitTime, kernelTime, userTime;
    GetProcessTimes(pi.hProcess, &creationTime, &exitTime, &kernelTime, &userTime);
    
    SYSTEMTIME realTime;
    FileTimeToSystemTime(&userTime, &realTime);
    
    timeUsed = realTime.wMilliseconds
               + realTime.wSecond * 1000
               + realTime.wMinute * 60 * 1000
               + realTime.wHour * 60 * 60 * 1000;
    
    GetProcessMemoryInfo(pi.hProcess, (PROCESS_MEMORY_COUNTERS*)&info, sizeof(info));
    memoryUsed = info.PeakWorkingSetSize;
    
    if (task->getStandardInputCheck()) CloseHandle(si.hStdInput);
    if (task->getStandardOutputCheck()) CloseHandle(si.hStdOutput);
    CloseHandle(si.hStdError);
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
#endif
    
#ifdef Q_OS_LINUX
    QFile::copy(":/watcher/watcher_unix", workingDirectory + "watcher");
    QProcess::execute(QString("chmod +wx \"") + workingDirectory + "watcher" + "\"");
    
    QProcess *runner = new QProcess(this);
    QStringList argumentsList;
    argumentsList << QString("\"%1\" %2").arg(executableFile, arguments);
    if (task->getStandardInputCheck())
        argumentsList << QFileInfo(inputFile).absoluteFilePath();
    else
        argumentsList << "";
    if (task->getStandardOutputCheck())
        argumentsList << "_tmpout";
    else
        argumentsList << "";
    argumentsList << "_tmperr";
    argumentsList << QString("%1").arg(timeLimit + extraTime);
    argumentsList << QString("%1").arg(memoryLimit);
    runner->setProcessEnvironment(environment);
    runner->setWorkingDirectory(workingDirectory);
    runner->start(workingDirectory + "watcher", argumentsList);
    if (! runner->waitForStarted(-1)) {
        delete runner;
        score = 0;
        result = CannotStartProgram;
        return;
    }
    
    bool flag = false;
    QElapsedTimer timer;
    timer.start();
    
    while (timer.elapsed() <= timeLimit + extraTime) {
        if (runner->state() != QProcess::Running) {
            flag = true;
            break;
        }
        QCoreApplication::processEvents();
        if (stopJudging) {
            runner->terminate();
            runner->waitForFinished(-1);
            delete runner;
            return;
        }
        msleep(10);
    }
    
    if (! flag) {
        runner->terminate();
        runner->waitForFinished(-1);
        delete runner;
        score = 0;
        result = TimeLimitExceeded;
        timeUsed = memoryUsed = -1;
        return;
    }
    
    int code = runner->exitCode();
    
    if (code == 1) {
        delete runner;
        score = 0;
        result = CannotStartProgram;
        timeUsed = memoryUsed = -1;
        return;
    }
    
    if (code == 2) {
        delete runner;
        score = 0;
        result = RunTimeError;
        QFile file(workingDirectory + "_tmperr");
        if (file.open(QFile::ReadOnly)) {
            QTextStream stream(&file);
            message = stream.readAll();
            file.close();
        }
        timeUsed = memoryUsed = -1;
        return;
    }
    
    QString out = QString::fromLocal8Bit(runner->readAllStandardOutput().data());
    QTextStream stream(&out, QIODevice::ReadOnly);
    stream >> timeUsed >> memoryUsed;
    
    if (memoryUsed <= 0) memoryLimit = -1;
    
    if (code == 3) {
        delete runner;
        score = 0;
        result = TimeLimitExceeded;
        timeUsed = -1;
        return;
    }
    
    if (code == 4) {
        delete runner;
        score = 0;
        result = MemoryLimitExceeded;
        memoryUsed = -1;
        return;
    }
    
    delete runner;
#endif
}
Example #26
0
//
//  函数: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  目的: 处理主窗口的消息。
//
//  WM_COMMAND	- 处理应用程序菜单
//  WM_PAINT	- 绘制主窗口
//  WM_DESTROY	- 发送退出消息并返回
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;

	switch (message)
	{
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);

        // 选择音频渲染器
        if (wmId >= AUDIOMENUIDBASE && wmId < AUDIOMENUIDBASE + outputCount)
        {
            HMENU m = GetSubMenu(menu, 0);
            HMENU outMenu = GetSubMenu(m, 3);
            playerConfig->SetOutputDevice(wmId - AUDIOMENUIDBASE, 0);
            ::CheckMenuItem(outMenu, audioRender, MF_UNCHECKED);
            ::CheckMenuItem(outMenu, wmId, MF_CHECKED);
            audioRender = wmId;
            return 0;
        }
        
        // 选择视频渲染器
        if (wmId == ID_OLDRENDER || wmId == ID_VMR7WINDOWNED || 
            wmId == ID_VMR7WINDOWNLESS || wmId == ID_VMR7RENDERLESS || 
            wmId == ID_VMR9WINDOWNED || wmId == ID_VMR9WINDOWNLESS ||
            wmId == ID_VMR9RENDERLESS)
        {
            HMENU m = GetSubMenu(menu, 0);
            HMENU outMenu = GetSubMenu(m, 4);
            ::CheckMenuItem(outMenu, videoRender, MF_UNCHECKED);
            ::CheckMenuItem(outMenu, wmId, MF_CHECKED);   
            videoRender = wmId;
		    switch (wmId)
            {
            case ID_OLDRENDER:
                playerConfig->SetDefaultVedioRenderer((GUID)CLSID_VideoRendererDefault,
                    RENDER_MODE_WINDOWED);
                break;
            case ID_VMR7WINDOWNED:
                playerConfig->SetDefaultVedioRenderer((GUID)CLSID_VideoMixingRenderer,
                    RENDER_MODE_WINDOWED);
                break;
            case ID_VMR7WINDOWNLESS:
                playerConfig->SetDefaultVedioRenderer((GUID)CLSID_VideoMixingRenderer,
                    RENDER_MODE_WINDOWLESS);
                break;
            case ID_VMR7RENDERLESS:
                playerConfig->SetDefaultVedioRenderer((GUID)CLSID_VideoMixingRenderer,
                    RENDER_MODE_RENDERLESS);
                break;
            case ID_VMR9WINDOWNED:
                playerConfig->SetDefaultVedioRenderer((GUID)CLSID_VideoMixingRenderer9,
                    RENDER_MODE_WINDOWED);
                break;
            case ID_VMR9WINDOWNLESS:
                playerConfig->SetDefaultVedioRenderer((GUID)CLSID_VideoMixingRenderer9,
                    RENDER_MODE_WINDOWLESS);
                break;
            case ID_VMR9RENDERLESS:
                playerConfig->SetDefaultVedioRenderer((GUID)CLSID_VideoMixingRenderer9,
                    RENDER_MODE_RENDERLESS);
                break;
            }
            return 0;
        }

		// 分析菜单选择:
		switch (wmId)
		{
		case IDM_CONTROL:
			ShowWindow(control, SW_SHOWNORMAL);
			break;
		case IDM_PLAY:
			player->Play();
			break;
		case IDM_STOP:
			player->Stop();
			SetWindowText(hWnd, _T(""));
			break;
		case IDM_PAUSE:
			player->Pause();
			break;			
		case IDM_EXIT:
			DestroyWindow(hWnd);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	case WM_PAINT:
		hdc = BeginPaint(hWnd, &ps);
		// TODO: 在此添加任意绘图代码...
		EndPaint(hWnd, &ps);
		break;
    case WM_LBUTTONDOWN:
    case WM_RBUTTONDOWN:
        ::PostMessage(hWnd, WM_NCLBUTTONDOWN, HTCAPTION, 0);
        return 0;
    case WM_DROPFILES:
		{
			int count = DragQueryFile((HDROP)wParam, -1, NULL, 0);//取得被拖动文件的数目
			if (count > 0)
			{
				TCHAR name[MAX_PATH] = {0};
				DragQueryFile((HDROP)wParam, 0, name, MAX_PATH);//把文件名拷贝到缓冲区
				player->OpenFile(name, NULL);
				SetWindowText(hWnd, name);
				SetForegroundWindow(hWnd);
				player->Play();
				break;
			}
			break;
		}
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	case WM_KGPLAYER_GET_MV_WINDOW:
		*((HWND*)wParam) = hWnd;
		break;
	case WM_KEYDOWN:
		if (wParam == 32)// 空格
		{
			if (state == psPlaying)
			{
				player->Pause();
			}
			else
			{
				player->Play();
			}
		}
		else if (wParam == 27) //esc
		{
			player->Stop();
			SetWindowText(hWnd, _T(""));
		}

		break;
	case WM_RBUTTONUP:
		if (menu)
		{
			HMENU m = GetSubMenu(menu, 0);
			POINT point;
			GetCursorPos(&point); 
			TrackPopupMenu(m, TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y,
						   0, hWnd, NULL);
		}
		break;
	case WM_KGPLAYER_PLAYER_STATE:
		state = (TPlayerState)wParam;
        SetProcessWorkingSetSize( GetCurrentProcess(), 0xFFFFFFFF, 0xFFFFFFFF );
        if (psOpen == state)
            player->GetAudioInfo(&info);
        break;
#if 1
	case WM_KGPLAYER_PLAYING_PROGRESS:
        if (!slidKeyDown)
        {
            __int64 time = 0;
            int* p = (int*)&time;
            *p = wParam;
            p++;
            *p = lParam;

            int pos = (int)((double)time / info.Duration * 1000.0);
            SendMessage(GetDlgItem(control, IDC_SLIDER1), TBM_SETPOS, TRUE, pos);
            if (itl)
                itl->SetProgressValue(hWnd, pos, 1000);  
        }
        break;
#endif

    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}
Example #27
0
int WINAPI _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);

 	// TODO: 在此放置代码。
	MSG msg;
	HACCEL hAccelTable;

	// 初始化全局字符串
	LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
	LoadString(hInstance, IDC_PLAYER, szWindowClass, MAX_LOADSTRING);

	MyRegisterClass(hInstance);
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); // 由于播放器程用到COM,所以这里一定要初始化
	// 执行应用程序初始化:
    HWND hWnd = InitInstance (hInstance, nCmdShow);
	if (!hWnd)
		return FALSE;

	hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_PLAYER));

    control = CreateDialogParam(hInstance, MAKEINTRESOURCE(IDD_CONTROL), hWnd, Control, 0);
    SendMessage(GetDlgItem(control, IDC_SLIDER1), TBM_SETRANGE, TRUE,
                MAKELPARAM(0, 1000));  
    RECT workArea; 
    SystemParametersInfo(SPI_GETWORKAREA, 0, &workArea, 0); 
    RECT rect;
    GetWindowRect(control, &rect);
    SetWindowPos(control, NULL, (workArea.right - workArea.left - (rect.right - rect.left)) / 2,
                 workArea.bottom - workArea.top - (rect.bottom - rect.top), 0, 0, 
                 SWP_NOSIZE | SWP_SHOWWINDOW);
    if (__argc > 1)
    {
        player->OpenFile(__wargv[1],NULL);
        player->Play();
        SetWindowText(hWnd, __wargv[1]);
    }

    HRESULT hr = CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&itl));  
    if (SUCCEEDED(hr))
    {  
        hr = itl->HrInit();  
        if (FAILED(hr))
        {  
            itl->Release();  
            itl = NULL;  
        }  
    }

    SetProcessWorkingSetSize( GetCurrentProcess(), 0xFFFFFFFF, 0xFFFFFFFF );
	// 主消息循环:
	while (GetMessage(&msg, NULL, 0, 0))
	{
		if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

	if (player)
	{
 		player->Stop();
		player->Release();
		player = NULL;
	}
    DestroyWindow(control);
	if (playerConfig)
	{
		playerConfig->Release();
		player = NULL;
	}
    if (itl)
    {  
        itl->Release();  
        itl = NULL;  
    }  
    if (dll)
	{
		FreeLibrary(dll);
	}
 	CoUninitialize();
	return (int) msg.wParam;
}
Example #28
0
//main function
int WINAPI WinMain (HINSTANCE hThisInstance,
                    HINSTANCE hPrevInstance,
                    LPSTR lpszArgument,
                    int nFunsterStil)

{

    HWND hwnd,hCheckWnd;        /* This is the handle for our window */
    MSG messages;        /* Here messages to the application are saved */
    WNDCLASSEX wincl;        /* Data structure for the windowclass */

    hCheckWnd = GetRunningWindow();

    if (hCheckWnd)   // hCheckWnd != NULL -> Previous instance exists
    {
        MessageBox(hCheckWnd, "The program is already running", "Info", MB_OK);
        return FALSE;       // Exit program
    }
    /* The Window structure */
    wincl.hInstance = hThisInstance;
    wincl.lpszClassName = szClassName;
    wincl.lpfnWndProc = WindowProcedure;      /* This function is called by windows */
    wincl.style = CS_DBLCLKS;       /* Catch double-clicks */
    wincl.cbSize = sizeof (WNDCLASSEX);

    /* Use default icon and mouse-pointer */
    wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
    wincl.lpszMenuName = NULL;        /* No menu */
    wincl.cbClsExtra = 0;        /* No extra bytes after the window class */
    wincl.cbWndExtra = 0;        /* structure or the window instance */
    /* Use Windows's default color as the background of the window */
    //wincl.hbrBackground = (HBRUSH) COLOR_BACKGROUND;
    wincl.hbrBackground = GetSysColorBrush(COLOR_3DFACE);

    /* Register the window class, and if it fails quit the program */
    if (!RegisterClassEx (&wincl))
        return 0;

   // int desktopwidth=GetSystemMetrics(SM_CXSCREEN);
    //int desktopheight=GetSystemMetrics(SM_CYSCREEN);


    /* The class is registered, let's create the program*/
    hwnd = CreateWindow (
               szClassName,        /* Classname */
               szTitleText,        /* Title Text */
               WS_DISABLED  , /* default window */
               CW_USEDEFAULT,       /* Windows decides the position */
               CW_USEDEFAULT,       /* where the window ends up on the screen */
               MAX_X,        /* The programs width */
               MAX_Y,        /* and height in pixels */
               HWND_DESKTOP,        /* The window is a child-window to desktop */
               NULL,         /* No menu */
               hThisInstance,       /* Program Instance handler */
               NULL         /* No Window Creation data */
           );

    RegisterSession(hwnd);

    RegisterHotKey(NULL,1,MOD_CONTROL,0x71);

    SetProcessWorkingSetSize(GetCurrentProcess(), (SIZE_T) -1, (SIZE_T) -1);

    bool gRet;

    /* Run the message loop. It will run until GetMessage() returns 0 */
    while ((gRet = GetMessage (&messages, NULL, 0, 0)) != 0 )
    {
        if (gRet == -1)
        {
            UnregisterSession(hwnd);
            OnDestroyTray();
            PostQuitMessage (0);
        }
        else
        {
            /* Translate virtual-key messages into character messages */
            TranslateMessage(&messages);
            /* Send message to WindowProcedure */
            DispatchMessage(&messages);
            if (messages.message == WM_HOTKEY)
            {
                SaveEnergyShort();
            }
        }
    }
    /* The program return-value is 0 - The value that PostQuitMessage() gave */
    return messages.wParam;
}