void CPutFile::CheckFile(wstring name, wstring path, bool replace)
{		
	HMODULE hKernel32 = ::LoadLibrary(_T("Kernel32.dll"));
	PVOID OldValue;
	BOOL bRet = FALSE;
	if(CGetOSInfo::getInstance()->isX64())
	{
		Wow64DisableWow64FsRedirectionFun pWow64DisableWow64FsRedirection = NULL;
		if (hKernel32)
		{
			pWow64DisableWow64FsRedirection = (Wow64DisableWow64FsRedirectionFun)::GetProcAddress(hKernel32, "Wow64DisableWow64FsRedirection");
		}
		if(pWow64DisableWow64FsRedirection != NULL)
			bRet = pWow64DisableWow64FsRedirection(&OldValue);
	}

	wstring fullPath;
	fullPath = path + L"\\" + name;

	WCHAR expName[MAX_PATH] ={0};
	ExpandEnvironmentStringsW(fullPath.c_str(), expName, MAX_PATH);

	if(::PathFileExistsW(expName) == FALSE)// 判断文件是否存在
	{
		CRecordProgram::GetInstance ()->RecordCommonInfo(L"PutFile", 1001, CRecordProgram::GetInstance ()->GetRecordInfo(L"%s文件不存在", expName));
		wstring file = CResourceManager::_()->GetFilePath(m_pWebsiteData->GetWebsiteType(), m_pWebsiteData->GetID(), name.c_str());

		::CopyFileW(file.c_str(), expName , TRUE);
		
		DWORD re = ::GetLastError();
		CRecordProgram::GetInstance ()->RecordCommonInfo(L"PutFile", 1001, CRecordProgram::GetInstance ()->GetRecordInfo(L"替换%s文件结果:%d", file.c_str(),re));
		if(re == ERROR_ACCESS_DENIED)
		{
			CRecordProgram::GetInstance ()->RecordCommonInfo(L"PutFile", 1001, CRecordProgram::GetInstance ()->GetRecordInfo(L"%s文件放入失败", file.c_str()));
			USES_CONVERSION;
			string appid;
			if(m_pWebsiteData)
			{
				USES_CONVERSION;
				appid = CFavBankOperator::GetBankIDOrBankName(W2A(m_pWebsiteData->GetID()),false);
				CWebsiteData::StartUAC(A2W(appid.c_str()));
			}
		}
	}
	else
	{
		if(replace == true)//强制替换
		{
			DWORD oLength = 0, nLength = 0;
			HANDLE hFile = CreateFileW(expName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
			if(hFile != INVALID_HANDLE_VALUE)
			{
				oLength = GetFileSize(hFile, NULL);
				CloseHandle(hFile);
			}		
			
			CRecordProgram::GetInstance ()->RecordCommonInfo(L"PutFile", 1001, CRecordProgram::GetInstance ()->GetRecordInfo(L"%s文件已经存在", expName));
			wstring file = CResourceManager::_()->GetFilePath(m_pWebsiteData->GetWebsiteType(), m_pWebsiteData->GetID(), name.c_str());

			hFile = CreateFileW(file.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
			if(hFile != INVALID_HANDLE_VALUE)
			{
				nLength = GetFileSize(hFile, NULL);
				CloseHandle(hFile);
			}
			
			if((oLength != 0) && (oLength != nLength))
			{
				::CopyFileW(file.c_str(), expName , FALSE);//

				DWORD re = ::GetLastError();
				CRecordProgram::GetInstance ()->RecordCommonInfo(L"PutFile", 1001, CRecordProgram::GetInstance ()->GetRecordInfo(L"替换%s文件结果:%d", file.c_str(),re));
				if(re == ERROR_ACCESS_DENIED)
				{
					USES_CONVERSION;
					string appid;
					if(m_pWebsiteData)
					{
						appid = CFavBankOperator::GetBankIDOrBankName(W2A(m_pWebsiteData->GetID()),false);
						CWebsiteData::StartUAC(A2W(appid.c_str()));
					}
				}
			}
		}
	}
	if(CGetOSInfo::getInstance()->isX64())
		if(bRet == TRUE)
		{
			Wow64RevertWow64FsRedirectionFun pWow64RevertWow64FsRedirection = NULL;
			if (hKernel32)
			{
				pWow64RevertWow64FsRedirection = (Wow64RevertWow64FsRedirectionFun)::GetProcAddress(hKernel32, "Wow64RevertWow64FsRedirection");
			}
			if(pWow64RevertWow64FsRedirection != NULL)
				pWow64RevertWow64FsRedirection(OldValue);
		}
	return;
}
Beispiel #2
0
BOOL Osmo4::InitInstance()
{
	CCommandLineInfo cmdInfo;

	m_logs = NULL;

	m_term = NULL;

	memset(&m_user, 0, sizeof(GF_User));

	/*get Osmo4.exe path*/
	strcpy((char *) szApplicationPath, AfxGetApp()->m_pszHelpFilePath);
	while (szApplicationPath[strlen((char *) szApplicationPath)-1] != '\\') szApplicationPath[strlen((char *) szApplicationPath)-1] = 0;
	if (szApplicationPath[strlen((char *) szApplicationPath)-1] != '\\') strcat(szApplicationPath, "\\");

	gf_sys_init(0);

	/*setup user*/
	memset(&m_user, 0, sizeof(GF_User));

	Bool first_launch = 0;
	/*init config and modules*/
	m_user.config = gf_cfg_init(NULL, &first_launch);
	if (!m_user.config) {
		MessageBox(NULL, "GPAC Configuration file not found", "Fatal Error", MB_OK);
		m_pMainWnd->PostMessage(WM_CLOSE);
	}

	char *name = gf_cfg_get_filename(m_user.config);
	char *sep = strrchr(name, '\\');
	if (sep) sep[0] = 0;
	strcpy(szUserPath, name);
	if (sep) sep[0] = '\\';
	gf_free(name);

	const char *opt = gf_cfg_get_key(m_user.config, "General", "SingleInstance");
	m_SingleInstance = (opt && !stricmp(opt, "yes")) ? 1 : 0;

	m_hMutex = NULL;
	if (m_SingleInstance) {
		m_hMutex = CreateMutex(NULL, FALSE, "Osmo4_GPAC_INSTANCE");
		if ( GetLastError() == ERROR_ALREADY_EXISTS ) {
			char szDIR[1024];
			if (m_hMutex) CloseHandle(m_hMutex);
			m_hMutex = NULL;

			if (!static_gpac_hwnd || !IsWindow(static_gpac_hwnd) ) {
				::MessageBox(NULL, "Osmo4 ghost process detected", "Error at last shutdown" , MB_OK);
			} else {
				::SetForegroundWindow(static_gpac_hwnd);

				if (m_lpCmdLine && strlen(m_lpCmdLine)) {
					DWORD res;
					u32 len;
					char *the_url, *cmd;
					GetCurrentDirectory(1024, szDIR);
					if (szDIR[strlen(szDIR)-1] != '\\') strcat(szDIR, "\\");
					cmd = (char *)(const char *) m_lpCmdLine;
					strcpy(static_szCmdLine, "");
					if (cmd[0]=='"') cmd+=1;

					if (!strnicmp(cmd, "-queue ", 7)) {
						strcat(static_szCmdLine, "-queue ");
						cmd += 7;
					}
					the_url = gf_url_concatenate(szDIR, cmd);
					if (!the_url) {
						strcat(static_szCmdLine, cmd);
					} else {
						strcat(static_szCmdLine, the_url);
						gf_free(the_url);
					}
					while ( (len = strlen(static_szCmdLine)) ) {
						char s = static_szCmdLine[len-1];
						if ((s==' ') || (s=='"')) static_szCmdLine[len-1]=0;
						else break;
					}
					::SendMessageTimeout(static_gpac_hwnd, WM_NEWINSTANCE, 0, 0, 0, 1000, &res);
				}
			}
			
			return FALSE;
		}
	}

#if 0
	// Standard initialization
#ifdef _AFXDLL
	Enable3dControls();			// Call this when using MFC in a shared DLL
#else
	Enable3dControlsStatic();	// Call this when linking to MFC statically
#endif

#endif

	SetRegistryKey(_T("GPAC"));
	CMainFrame* pFrame = new CMainFrame;
	m_pMainWnd = pFrame;
	pFrame->LoadFrame(IDR_MAINFRAME, WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, NULL, NULL);
	m_pMainWnd->DragAcceptFiles();

	if (m_SingleInstance) static_gpac_hwnd = m_pMainWnd->m_hWnd;

	const char *str = gf_cfg_get_key(m_user.config, "General", "ModulesDirectory");
	m_user.modules = gf_modules_new(str, m_user.config);
	if (!m_user.modules || ! gf_modules_get_count(m_user.modules) ) {
		MessageBox(NULL, "No modules available - system cannot work", "Fatal Error", MB_OK);
		m_pMainWnd->PostMessage(WM_CLOSE);
	}
	else if (first_launch) {
		/*first launch, register all files ext*/
		u32 i;
		for (i=0; i<gf_modules_get_count(m_user.modules); i++) {
			GF_InputService *ifce = (GF_InputService *) gf_modules_load_interface(m_user.modules, i, GF_NET_CLIENT_INTERFACE);
			if (!ifce) continue;
			if (ifce) {
				ifce->CanHandleURL(ifce, "test.test");
				gf_modules_close_interface((GF_BaseInterface *)ifce);
			}
		}
		/*set some shortcuts*/
		gf_cfg_set_key(m_user.config, "Shortcuts", "VolumeUp", "ctrl+Up");
		gf_cfg_set_key(m_user.config, "Shortcuts", "VolumeDown", "ctrl+Down");
		gf_cfg_set_key(m_user.config, "Shortcuts", "FastRewind", "ctrl+Left");
		gf_cfg_set_key(m_user.config, "Shortcuts", "FastForward", "ctrl+Right");
		gf_cfg_set_key(m_user.config, "Shortcuts", "Play", "ctrl+ ");
	}

	/*check log file*/
	str = gf_cfg_get_key(m_user.config, "General", "LogFile");
	if (str) {
		m_logs = gf_f64_open(str, "wt");
		gf_log_set_callback(m_logs, osmo4_do_log);
	}
	else m_logs = NULL;

	/*set log level*/
	m_log_level = gf_log_parse_level(gf_cfg_get_key(m_user.config, "General", "LogLevel") );
	gf_log_set_level(m_log_level);

	/*set log tools*/
	m_log_tools = gf_log_parse_tools(gf_cfg_get_key(m_user.config, "General", "LogTools") );
	gf_log_set_tools(m_log_tools); 
	
	m_user.opaque = this;
	m_user.os_window_handler = pFrame->m_pWndView->m_hWnd;
	m_user.EventProc = Osmo4_EventProc;

	m_reset = 0;
	orig_width = 320;
	orig_height = 240;

	gf_set_progress_callback(this, Osmo4_progress_cbk);

	m_term = gf_term_new(&m_user);
	if (! m_term) {
		MessageBox(NULL, "Cannot load GPAC Terminal", "Fatal Error", MB_OK);
		m_pMainWnd->PostMessage(WM_CLOSE);
		return TRUE;
	}
	SetOptions();
	UpdateRenderSwitch();

	pFrame->SendMessage(WM_SETSIZE, orig_width, orig_height);
	pFrame->m_Address.ReloadURLs();

	pFrame->m_Sliders.SetVolume();

	m_reconnect_time = 0;


	ParseCommandLine(cmdInfo);

	start_mode = 0;

	if (! cmdInfo.m_strFileName.IsEmpty()) {
		pFrame->m_pPlayList->QueueURL(cmdInfo.m_strFileName);
		pFrame->m_pPlayList->RefreshList();
		pFrame->m_pPlayList->PlayNext();
	} else {
		char sPL[MAX_PATH];
		strcpy((char *) sPL, szUserPath);
		strcat(sPL, "gpac_pl.m3u");
		pFrame->m_pPlayList->OpenPlayList(sPL);
		const char *sOpt = gf_cfg_get_key(GetApp()->m_user.config, "General", "PLEntry");
		if (sOpt) {
			s32 count = (s32)gf_list_count(pFrame->m_pPlayList->m_entries);
			pFrame->m_pPlayList->m_cur_entry = atoi(sOpt);
			if (pFrame->m_pPlayList->m_cur_entry>=count)
				pFrame->m_pPlayList->m_cur_entry = count-1;
		} else {
			pFrame->m_pPlayList->m_cur_entry = -1;
		}
#if 0
		if (pFrame->m_pPlayList->m_cur_entry>=0) {
			start_mode = 1;
			pFrame->m_pPlayList->Play();
		}
#endif

		sOpt = gf_cfg_get_key(GetApp()->m_user.config, "General", "StartupFile");
		if (sOpt) gf_term_connect(m_term, sOpt);
	}
	pFrame->SetFocus();
	pFrame->SetForegroundWindow();
	return TRUE;
}
    void Run()
	{
		break_ = false;

		// prepare the window events which we use to wake up on incoming data
		// we use this instead of select() primarily to support the AsyncBreak()
		// mechanism.

		std::vector<HANDLE> events( socketListeners_.size() + 1, 0 );
		int j=0;
		for( std::vector< std::pair< PacketListener*, UdpSocket* > >::iterator i = socketListeners_.begin();
				i != socketListeners_.end(); ++i, ++j ){

			HANDLE event = CreateEvent( NULL, FALSE, FALSE, NULL );
			WSAEventSelect( i->second->impl_->Socket(), event, FD_READ ); // note that this makes the socket non-blocking which is why we can safely call RecieveFrom() on all sockets below
			events[j] = event;
		}


		events[ socketListeners_.size() ] = breakEvent_; // last event in the collection is the break event


		// configure the timer queue
		double currentTimeMs = GetCurrentTimeMs();

		// expiry time ms, listener
		std::vector< std::pair< double, AttachedTimerListener > > timerQueue_;
		for( std::vector< AttachedTimerListener >::iterator i = timerListeners_.begin();
				i != timerListeners_.end(); ++i )
			timerQueue_.push_back( std::make_pair( currentTimeMs + i->initialDelayMs, *i ) );
		std::sort( timerQueue_.begin(), timerQueue_.end(), CompareScheduledTimerCalls );

		const int MAX_BUFFER_SIZE = 4098;
		char *data = new char[ MAX_BUFFER_SIZE ];
		IpEndpointName remoteEndpoint;

		while( !break_ ){

			currentTimeMs = GetCurrentTimeMs();

            DWORD waitTime = INFINITE;
            if( !timerQueue_.empty() ){

                waitTime = (DWORD)( timerQueue_.front().first >= currentTimeMs
                            ? timerQueue_.front().first - currentTimeMs
                            : 0 );
            }

			DWORD waitResult = WaitForMultipleObjects( (DWORD)socketListeners_.size() + 1, &events[0], FALSE, waitTime );
			if( break_ )
				break;

			if( waitResult != WAIT_TIMEOUT ){
				for( int i = waitResult - WAIT_OBJECT_0; i < (int)socketListeners_.size(); ++i ){
					int size = socketListeners_[i].second->ReceiveFrom( remoteEndpoint, data, MAX_BUFFER_SIZE );
					if( size > 0 ){
						socketListeners_[i].first->ProcessPacket( data, size, remoteEndpoint );
						if( break_ )
							break;
					}
				}
			}

			// execute any expired timers
			currentTimeMs = GetCurrentTimeMs();
			bool resort = false;
			for( std::vector< std::pair< double, AttachedTimerListener > >::iterator i = timerQueue_.begin();
					i != timerQueue_.end() && i->first <= currentTimeMs; ++i ){

				i->second.listener->TimerExpired();
				if( break_ )
					break;

				i->first += i->second.periodMs;
				resort = true;
			}
			if( resort )
				std::sort( timerQueue_.begin(), timerQueue_.end(), CompareScheduledTimerCalls );
		}

		delete [] data;

		// free events
		j = 0;
		for( std::vector< std::pair< PacketListener*, UdpSocket* > >::iterator i = socketListeners_.begin();
				i != socketListeners_.end(); ++i, ++j ){

			WSAEventSelect( i->second->impl_->Socket(), events[j], 0 ); // remove association between socket and event
			CloseHandle( events[j] );
			unsigned long enableNonblocking = 0;
			ioctlsocket( i->second->impl_->Socket(), FIONBIO, &enableNonblocking );  // make the socket blocking again
		}
	}
void CPutFile::CheckExe(wstring installname, wstring name, int type)
{
	if(type == 2)//file
	{
		WCHAR path[MAX_PATH] = {0};
		ExpandEnvironmentStringsW(installname.c_str(), path, MAX_PATH);

		if(::PathFileExistsW(path) == TRUE)
			return;
	}
	else if(type == 1)//reg
	{
		HKEY rootkey;
		size_t nEndKeyName = installname.find_first_of(']', 1);
		std::wstring strKeyName = installname.substr(1, nEndKeyName - 1);

		size_t nEnd = strKeyName.find_first_of('\\');
		std::wstring strRootKey = strKeyName.substr(0, nEnd);

		if(strRootKey == L"HKEY_CURRENT_USER")
			rootkey = HKEY_CURRENT_USER;
		else if (strRootKey == _T("HKEY_LOCAL_MACHINE"))
			rootkey = HKEY_LOCAL_MACHINE;
		else if(strRootKey == _T("HKEY_CLASSES_ROOT"))
			rootkey = HKEY_CLASSES_ROOT;

		std::wstring strKey = strKeyName.substr(nEnd + 1, wstring::npos);

		HKEY hKey = NULL;                               // 操作键句柄

		if (ERROR_SUCCESS == ::RegOpenKeyExW(rootkey, strKey.c_str(), 0, KEY_READ, &hKey))   
		{   
			::RegCloseKey(hKey);
			return;
		} 
	}
	else
		return;

	wstring file = CResourceManager::_()->GetFilePath(m_pWebsiteData->GetWebsiteType(), m_pWebsiteData->GetID(), name.c_str());

	OSVERSIONINFO os = { sizeof(OSVERSIONINFO) };
	::GetVersionEx(&os);
	if(os.dwMajorVersion >= 6)
	{
		SHELLEXECUTEINFOW shExecInfo;
		shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
		shExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;//SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI; 
		shExecInfo.hwnd = NULL;
		shExecInfo.lpVerb = L"runas";
		shExecInfo.lpFile = LPWSTR(file.c_str());
		shExecInfo.lpParameters = NULL;
		shExecInfo.lpDirectory = NULL;
		shExecInfo.nShow = SW_SHOWNORMAL;
		shExecInfo.hInstApp = NULL;

		if (!ShellExecuteExW(&shExecInfo))
		{			
			int err = GetLastError();
			CRecordProgram::GetInstance()->FeedbackError(L"PutFile", err,
				CRecordProgram::GetInstance()->GetRecordInfo(L"CPutFile创建安装进程%s失败!", file.c_str()));
		}
		else
			WaitForSingleObject (shExecInfo.hProcess, INFINITE); 
	}
	else
	{
		STARTUPINFOW si;
		memset (&si, 0, sizeof (STARTUPINFOW));
		si.wShowWindow = SW_HIDE;
		si.cb = sizeof (STARTUPINFOW);
		PROCESS_INFORMATION pi;
		memset (&pi, 0, sizeof (PROCESS_INFORMATION));	

		if (!CreateProcess(NULL, LPWSTR(file.c_str()), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
		{
			CRecordProgram::GetInstance()->FeedbackError(L"PutFile", 1200,
				CRecordProgram::GetInstance()->GetRecordInfo(L"CPutFile创建安装进程%s失败!", file.c_str()));
			return;
		}
		else
			WaitForSingleObject (pi.hProcess, INFINITE); 
		CloseHandle (pi.hThread);
		CloseHandle (pi.hProcess);
	}
	return;
}
BOOL EncryptionThreadPoolStart ()
{
	size_t cpuCount, i;

	if (ThreadPoolRunning)
		return TRUE;

#ifdef DEVICE_DRIVER
	cpuCount = GetCpuCount();
#else
	{
		SYSTEM_INFO sysInfo;
		GetSystemInfo (&sysInfo);
		cpuCount = sysInfo.dwNumberOfProcessors;
	}
#endif

	if (cpuCount < 2)
		return TRUE;

	if (cpuCount > TC_ENC_THREAD_POOL_MAX_THREAD_COUNT)
		cpuCount = TC_ENC_THREAD_POOL_MAX_THREAD_COUNT;

	StopPending = FALSE;
	DequeuePosition = 0;
	EnqueuePosition = 0;

#ifdef DEVICE_DRIVER
	KeInitializeEvent (&WorkItemReadyEvent, SynchronizationEvent, FALSE);
	KeInitializeEvent (&WorkItemCompletedEvent, SynchronizationEvent, FALSE);
#else
	WorkItemReadyEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
	if (!WorkItemReadyEvent)
		return FALSE;
	
	WorkItemCompletedEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
	if (!WorkItemCompletedEvent)
	{
		CloseHandle (WorkItemReadyEvent);
		return FALSE;
	}
#endif
	
	TC_INIT_MUTEX (&DequeueMutex);
	TC_INIT_MUTEX (&EnqueueMutex);

	memset (WorkItemQueue, 0, sizeof (WorkItemQueue));

	for (i = 0; i < sizeof (WorkItemQueue) / sizeof (WorkItemQueue[0]); ++i)
	{
		WorkItemQueue[i].State = WorkItemFree;

#ifdef DEVICE_DRIVER
		KeInitializeEvent (&WorkItemQueue[i].ItemCompletedEvent, SynchronizationEvent, FALSE);
#else
		WorkItemQueue[i].ItemCompletedEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
		if (!WorkItemQueue[i].ItemCompletedEvent)
		{
			EncryptionThreadPoolStop();
			return FALSE;
		}
#endif
	}

	for (ThreadCount = 0; ThreadCount < cpuCount; ++ThreadCount)
	{
#ifdef DEVICE_DRIVER
		if (!NT_SUCCESS (TCStartThread (EncryptionThreadProc, NULL, &ThreadHandles[ThreadCount])))
#else
		if (!(ThreadHandles[ThreadCount] = (HANDLE) _beginthreadex (NULL, 0, EncryptionThreadProc, NULL, 0, NULL)))
#endif
		{
			EncryptionThreadPoolStop();
			return FALSE;
		}
	}

	ThreadPoolRunning = TRUE;
	return TRUE;
}
Beispiel #6
0
void
proc_title_set(const char *format, ...)
{
#ifndef PS_USE_NONE
	va_list ap;
	int buflen;

#ifdef PS_USE_CLOBBER_ARGV
	/* If ps_buffer is a pointer, it might still be null */
	if (!ps_buffer)
		return;
#endif

	/* Update ps_buffer to contain both fixed part and activity */
	va_start(ap, format);
	buflen = vsnprintf(ps_buffer,
		  ps_buffer_size - ps_sentinel_size, format, ap);
	va_end(ap);

	if (buflen < 0)
		return;

	/* Transmit new setting to kernel, if necessary */
#ifdef PS_USE_SETPROCTITLE
	setproctitle("-%s", ps_buffer);
#endif

#ifdef PS_USE_PSTAT
	{
		union pstun pst;

		pst.pst_command = ps_buffer;
		pstat(PSTAT_SETCMD, pst, strlen(ps_buffer), 0, 0);
	}
#endif /* PS_USE_PSTAT */

#ifdef PS_USE_PS_STRINGS
    static char *argvstr[2];
    argvstr[0] = ps_buffer;
	PS_STRINGS->ps_nargvstr = 1;
	PS_STRINGS->ps_argvstr = argvstr;
#endif /* PS_USE_PS_STRINGS */

#ifdef PS_USE_CLOBBER_ARGV
	{
		/* clobber remainder of old status string */
		if (ps_last_status_len > (size_t)buflen)
			memset(ps_buffer + buflen, PS_PADDING, ps_last_status_len - buflen);
		ps_last_status_len = buflen;
	}
#endif /* PS_USE_CLOBBER_ARGV */

#ifdef PS_USE_WIN32
	{
		/*
		 * Win32 does not support showing any changed arguments. To make it at
		 * all possible to track which backend is doing what, we create a
		 * named object that can be viewed with for example Process Explorer.
		 */
		static HANDLE ident_handle = INVALID_HANDLE_VALUE;
		char name[PS_BUFFER_SIZE + 32];

		if (ident_handle != INVALID_HANDLE_VALUE)
			CloseHandle(ident_handle);

		sprintf(name, "pgident(%d): %s", MyProcPid, ps_buffer);

		ident_handle = CreateEvent(NULL, TRUE, FALSE, name);
	}
#endif /* PS_USE_WIN32 */
#endif /* not PS_USE_NONE */
}
Beispiel #7
0
static int
_tiffCloseProc(thandle_t fd)
{
	return (CloseHandle(fd) ? 0 : -1);
}
Beispiel #8
0
int main(int argc, char *argv[]) {
	FILE *fp_infile = NULL, *fp_outfile = NULL, *fp_xmloutfile = NULL, *devnull;
#ifdef __MINGW32__
	HANDLE fh_infile = NULL;
#endif
	int c, lastsecond = 0, lastkeyframe = 0, unlink_infile = 0;
	char *flv, *infile, *outfile, *xmloutfile, *tempfile, *creator;
	unsigned int i;
	size_t filesize = 0, streampos, metadatasize;
	struct stat sb;
	FLVFileHeader_t *flvfileheader;

	opterr = 0;

	infile = NULL;
	outfile = NULL;
	xmloutfile = NULL;
	tempfile = NULL;
	creator = NULL;

	while((c = getopt(argc, argv, "i:o:x:t:c:lkh")) != -1) {
		switch(c) {
			case 'i':
				infile = optarg;
				break;
			case 'o':
				outfile = optarg;
				break;
			case 'x':
				xmloutfile = optarg;
				break;
			case 't':
				tempfile = optarg;
				break;
			case 'c':
				creator = optarg;
				break;
			case 'l':
				lastsecond = 1;
				break;
			case 'k':
				lastkeyframe = 1;
				break;
			case 'h':
				print_usage();
				exit(1);
				break;
			case ':':
				fprintf(stderr, "The option -%c expects a parameter. -h for help.\n", optopt);
				exit(1);
				break;
			case '?':
				fprintf(stderr, "Unknown option: -%c. -h for help.\n", optopt);
				exit(1);
				break;
			default:
				print_usage();
				exit(1);
				break;
		}
	}

	if(infile == NULL) {
		fprintf(stderr, "Please provide an input file. -h for help.\n");
		exit(1);
	}

	if(outfile == NULL && xmloutfile == NULL) {
		fprintf(stderr, "Please provide at least one output file. -h for help.\n");
		exit(1);
	}

	if(tempfile == NULL && !strcmp(infile, "-")) {
		fprintf(stderr, "Please specify a temporary file. -h for help.\n");
		exit(1);
	}

	// Check input file
	if(!strcmp(infile, "-")) {		// Read from stdin
		// Check the temporary file
		if(outfile != NULL) {
			if(!strcmp(tempfile, outfile)) {
				fprintf(stderr, "The temporary file and the output file must not be the same.\n");
				exit(1);
			}
		}

		if(xmloutfile != NULL) {
			if(!strcmp(tempfile, xmloutfile)) {
				fprintf(stderr, "The temporary file and the XML output file must not be the same.\n");
				exit(1);
			}
		}

		// Open the temporary file
		fp_infile = fopen(tempfile, "wb");
		if(fp_infile == NULL) {
			fprintf(stderr, "Couldn't open the tempfile %s.\n", tempfile);
			exit(1);
		}

		// Store stdin to temporary file
		storeFLVFromStdin(fp_infile);

		// Close temporary file
		fclose(fp_infile);

		// Mimic normal input file, but don't forget to remove the temporary file
		infile = tempfile;
		unlink_infile = 1;
	}
	else {
		if(outfile != NULL) {
			if(!strcmp(infile, outfile)) {
				fprintf(stderr, "The input file and the output file must not be the same.\n");
				exit(1);
			}
		}

		if(xmloutfile != NULL) {
			if(!strcmp(infile, xmloutfile)) {
				fprintf(stderr, "The input file and the XML output file must not be the same.\n");
				exit(1);
			}
		}
	}

	// Get size of input file
	if(stat(infile, &sb) == -1) {
		fprintf(stderr, "Couldn't stat on %s.\n", infile);
		exit(1);
	}

	filesize = sb.st_size;

	// Open input file
#ifndef __MINGW32__
	fp_infile = fopen(infile, "rb");
#else
	// Open infile with CreateFile() API
	fh_infile = CreateFile(infile, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	// Meaningless type casting here. It is just used to pass the error checking codes.
	fp_infile = (FILE *)fh_infile;
#endif
	if(fp_infile == NULL) {
		fprintf(stderr, "Couldn't open %s.\n", infile);
		exit(1);
	}

	// Check output file
	if(outfile != NULL) {
		if(!strcmp(infile, outfile)) {
			fprintf(stderr, "The input file and the output file must not be the same.\n");
			exit(1);
		}

		if(strcmp(outfile, "-")) {
			fp_outfile = fopen(outfile, "wb");
			if(fp_outfile == NULL) {
				fprintf(stderr, "Couldn't open %s.\n", outfile);
				exit(1);
			}
		}
		else
			fp_outfile = stdout;
	}

	// Check XML output file
	if(xmloutfile != NULL) {
		if(!strcmp(infile, xmloutfile)) {
			fprintf(stderr, "The input file and the XML output file must not be the same.\n");
			exit(1);
		}

		if(!strcmp(outfile, xmloutfile)) {
			fprintf(stderr, "The output file and the XML output file must not be the same.\n");
			exit(1);
		}

		if(strcmp(xmloutfile, "-")) {
			fp_xmloutfile = fopen(xmloutfile, "wb");
			if(fp_xmloutfile == NULL) {
				fprintf(stderr, "Couldn't open %s.\n", xmloutfile);
				exit(1);
			}
		}
		else
			fp_xmloutfile = stdout;
	}

	// create mmap of input file
#ifndef __MINGW32__
	flv = mmap(NULL, filesize, PROT_READ, MAP_NOCORE | MAP_PRIVATE, fileno(fp_infile), 0);
	if(flv == MAP_FAILED) {
		fprintf(stderr, "Couldn't load %s (%s).\n", infile, strerror(errno));
		exit(1);
	}

#else
	HANDLE h = NULL;
	h = CreateFileMapping(fh_infile, NULL, PAGE_READONLY | SEC_COMMIT, 0, filesize,  NULL);
	if(h == NULL) {
		fprintf(stderr, "Couldn't create file mapping object %s. Error code: %d\n", infile, (int)GetLastError());
		exit(1);
	}
	flv = MapViewOfFile(h, FILE_MAP_READ, 0, 0, filesize);
	if(flv == NULL) {
		fprintf(stderr, "Couldn't load %s.\n", infile);
		exit(1);
	}
#endif

	// Simple check if the filee is a flv file
	if(strncmp(flv, "FLV", 3)) {
		fprintf(stderr, "The input file is not a FLV.\n");
		exit(1);
	}

	// Metadata initialisieren
	initFLVMetaData(creator, lastsecond, lastkeyframe);

	flvfileheader = (FLVFileHeader_t *)flv;

	// Die Position des 1. Tags im FLV bestimmen (Header + PrevTagSize0)
	streampos = FLV_UI32(flvfileheader->headersize) + 4;

	// Das FLV einlesen und Informationen fuer die Metatags extrahieren
	readFLVFirstPass(flv, streampos, filesize);

#ifndef __MINGW32__
	devnull = fopen("/dev/null", "wb");
#else
	devnull = fopen("nul", "wb");
#endif

	if(devnull == NULL) {
		fprintf(stderr, "Couldn't open NULL device.\n");
		exit(1);
	}

	// Die Groessen berechnen
	metadatasize = writeFLVMetaData(devnull);
	flvmetadata.lastsecondsize = writeFLVLastSecond(devnull, 0.0);
	flvmetadata.lastkeyframesize = writeFLVLastKeyframe(devnull);	// Not fully implemented, i.e. has no effect

	fclose(devnull);

	// Falls es Keyframes hat, muss ein 2. Durchgang fuer den Keyframeindex gemacht werden
	if(flvmetadata.hasKeyframes == 1) {
		readFLVSecondPass(flv, streampos, filesize);

		// Die Filepositions korrigieren
		for(i = 0; i < flvmetadata.keyframes; i++)
			flvmetadata.filepositions[i] += (double)(sizeof(FLVFileHeader_t) + 4 + metadatasize);

		flvmetadata.lastkeyframelocation = flvmetadata.filepositions[flvmetadata.keyframes - 1];
	}

	// filesize = FLVFileHeader + PreviousTagSize0 + MetadataSize + DataSize
	flvmetadata.filesize = (double)(sizeof(FLVFileHeader_t) + 4 + metadatasize + flvmetadata.datasize);
	if(flvmetadata.hasLastSecond == 1)
		flvmetadata.filesize += (double)flvmetadata.lastsecondsize;

	if(outfile != NULL)
		writeFLV(fp_outfile, flv, streampos, filesize);

	if(xmloutfile != NULL)
		writeXMLMetadata(fp_xmloutfile, infile, outfile);

	// Some cleanup
#ifndef __MINGW32__
	munmap(flv, filesize);
	fclose(fp_infile);
#else
	UnmapViewOfFile(flv);
	CloseHandle(h);
	CloseHandle(fh_infile);
#endif

	// Remove the input file if it is the temporary file
	if(unlink_infile == 1)
		unlink(infile);

	if(fp_outfile != NULL && fp_outfile != stdout)
		fclose(fp_outfile);

	if(fp_xmloutfile != NULL && fp_xmloutfile != stdout)
		fclose(fp_xmloutfile);

	return 0;
}
Beispiel #9
0
/*
 * The runtime library's popen() on win32 does not work when being
 * called from a service when running on windows <= 2000, because
 * there is no stdin/stdout/stderr.
 *
 * Executing a command in a pipe and reading the first line from it
 * is all we need.
 */
static char *
pipe_read_line(char *cmd, char *line, int maxsize)
{
#ifndef WIN32
	FILE	   *pgver;

	/* flush output buffers in case popen does not... */
	fflush(stdout);
	fflush(stderr);

	errno = 0;
	if ((pgver = popen(cmd, "r")) == NULL)
	{
		perror("popen failure");
		return NULL;
	}

	errno = 0;
	if (fgets(line, maxsize, pgver) == NULL)
	{
		if (feof(pgver))
			fprintf(stderr, "no data was returned by command \"%s\"\n", cmd);
		else
			perror("fgets failure");
		pclose(pgver);			/* no error checking */
		return NULL;
	}

	if (pclose_check(pgver))
		return NULL;

	return line;
#else							/* WIN32 */

	SECURITY_ATTRIBUTES sattr;
	HANDLE		childstdoutrd,
				childstdoutwr,
				childstdoutrddup;
	PROCESS_INFORMATION pi;
	STARTUPINFO si;
	char	   *retval = NULL;

	sattr.nLength = sizeof(SECURITY_ATTRIBUTES);
	sattr.bInheritHandle = TRUE;
	sattr.lpSecurityDescriptor = NULL;

	if (!CreatePipe(&childstdoutrd, &childstdoutwr, &sattr, 0))
		return NULL;

	if (!DuplicateHandle(GetCurrentProcess(),
						 childstdoutrd,
						 GetCurrentProcess(),
						 &childstdoutrddup,
						 0,
						 FALSE,
						 DUPLICATE_SAME_ACCESS))
	{
		CloseHandle(childstdoutrd);
		CloseHandle(childstdoutwr);
		return NULL;
	}

	CloseHandle(childstdoutrd);

	ZeroMemory(&pi, sizeof(pi));
	ZeroMemory(&si, sizeof(si));
	si.cb = sizeof(si);
	si.dwFlags = STARTF_USESTDHANDLES;
	si.hStdError = childstdoutwr;
	si.hStdOutput = childstdoutwr;
	si.hStdInput = INVALID_HANDLE_VALUE;

	if (CreateProcess(NULL,
					  cmd,
					  NULL,
					  NULL,
					  TRUE,
					  0,
					  NULL,
					  NULL,
					  &si,
					  &pi))
	{
		/* Successfully started the process */
		char	   *lineptr;

		ZeroMemory(line, maxsize);

		/* Try to read at least one line from the pipe */
		/* This may require more than one wait/read attempt */
		for (lineptr = line; lineptr < line + maxsize - 1;)
		{
			DWORD		bytesread = 0;

			/* Let's see if we can read */
			if (WaitForSingleObject(childstdoutrddup, 10000) != WAIT_OBJECT_0)
				break;			/* Timeout, but perhaps we got a line already */

			if (!ReadFile(childstdoutrddup, lineptr, maxsize - (lineptr - line),
						  &bytesread, NULL))
				break;			/* Error, but perhaps we got a line already */

			lineptr += strlen(lineptr);

			if (!bytesread)
				break;			/* EOF */

			if (strchr(line, '\n'))
				break;			/* One or more lines read */
		}

		if (lineptr != line)
		{
			/* OK, we read some data */
			int			len;

			/* If we got more than one line, cut off after the first \n */
			lineptr = strchr(line, '\n');
			if (lineptr)
				*(lineptr + 1) = '\0';

			len = strlen(line);

			/*
			 * If EOL is \r\n, convert to just \n. Because stdout is a
			 * text-mode stream, the \n output by the child process is
			 * received as \r\n, so we convert it to \n.  The server main.c
			 * sets setvbuf(stdout, NULL, _IONBF, 0) which has the effect of
			 * disabling \n to \r\n expansion for stdout.
			 */
			if (len >= 2 && line[len - 2] == '\r' && line[len - 1] == '\n')
			{
				line[len - 2] = '\n';
				line[len - 1] = '\0';
				len--;
			}

			/*
			 * We emulate fgets() behaviour. So if there is no newline at the
			 * end, we add one...
			 */
			if (len == 0 || line[len - 1] != '\n')
				strcat(line, "\n");

			retval = line;
		}

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

	CloseHandle(childstdoutwr);
	CloseHandle(childstdoutrddup);

	return retval;
#endif   /* WIN32 */
}
/* goodB2G uses the BadSource with the GoodSink */
void goodB2GSink(vector<wchar_t *> dataVector)
{
    wchar_t * data = dataVector[2];
    {
        HANDLE pHandle;
        wchar_t * username = L"User";
        wchar_t * domain = L"Domain";
        char hashData[100] = HASH_INPUT;
        HCRYPTPROV hCryptProv = 0;
        HCRYPTHASH hHash = 0;
        HCRYPTKEY hKey = 0;
        do
        {
            BYTE payload[(100 - 1) * sizeof(wchar_t)]; /* same size as data except for NUL terminator */
            DWORD payloadBytes;
            /* Hex-decode the input string into raw bytes */
            payloadBytes = decodeHexWChars(payload, sizeof(payload), data);
            /* Wipe the hex string, to prevent it from being given to LogonUserW if
             * any of the crypto calls fail. */
            SecureZeroMemory(data, 100 * sizeof(wchar_t));
            /* Aquire a Context */
            if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0))
            {
                break;
            }
            /* Create hash handle */
            if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash))
            {
                break;
            }
            /* Hash the input string */
            if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0))
            {
                break;
            }
            /* Derive an AES key from the hash */
            if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey))
            {
                break;
            }
            if(!CryptDecrypt(hKey, 0, 1, 0, payload, &payloadBytes))
            {
                break;
            }
            /* Copy back into data and NUL-terminate */
            memcpy(data, payload, payloadBytes);
            data[payloadBytes / sizeof(wchar_t)] = L'\0';
        }
        while (0);
        if (hKey)
        {
            CryptDestroyKey(hKey);
        }
        if (hHash)
        {
            CryptDestroyHash(hHash);
        }
        if (hCryptProv)
        {
            CryptReleaseContext(hCryptProv, 0);
        }
        /* FIX: Decrypt the password before using it for authentication  */
        if (LogonUserW(
                    username,
                    domain,
                    data,
                    LOGON32_LOGON_NETWORK,
                    LOGON32_PROVIDER_DEFAULT,
                    &pHandle) != 0)
        {
            printLine("User logged in successfully.");
            CloseHandle(pHandle);
        }
        else
        {
            printLine("Unable to login.");
        }
    }
}
Beispiel #11
0
LONG CALLBACK OBSExceptionHandler (PEXCEPTION_POINTERS exceptionInfo)
{
    HANDLE  hProcess;

    HMODULE hDbgHelp;

    MINIDUMP_EXCEPTION_INFORMATION miniInfo;

    STACKFRAME64        frame = {0};
    CONTEXT             context = *exceptionInfo->ContextRecord;
    SYMBOL_INFO         *symInfo;
    DWORD64             fnOffset;
    TCHAR               logPath[MAX_PATH];
    TCHAR               dumpPath[MAX_PATH];
    OSVERSIONINFOEX     osInfo;
    SYSTEMTIME          timeInfo;

    ENUMERATELOADEDMODULES64    fnEnumerateLoadedModules64;
    SYMSETOPTIONS               fnSymSetOptions;
    SYMINITIALIZE               fnSymInitialize;
    STACKWALK64                 fnStackWalk64;
    SYMFUNCTIONTABLEACCESS64    fnSymFunctionTableAccess64;
    SYMGETMODULEBASE64          fnSymGetModuleBase64;
    SYMFROMADDR                 fnSymFromAddr;
    SYMCLEANUP                  fnSymCleanup;
    MINIDUMPWRITEDUMP           fnMiniDumpWriteDump;
    SYMGETMODULEINFO64          fnSymGetModuleInfo64;

    DWORD                       i;
    DWORD64                     InstructionPtr;
    DWORD                       imageType;

    BOOL                        wantUpload = TRUE;

    TCHAR                       searchPath[MAX_PATH], *p;

    static BOOL                 inExceptionHandler = FALSE;

    moduleinfo_t                moduleInfo;

    //always break into a debugger if one is present
    if (IsDebuggerPresent ())
        return EXCEPTION_CONTINUE_SEARCH;

    //exception codes < 0x80000000 are typically informative only and not crash worthy
    //0xe06d7363 indicates a c++ exception was thrown, let's just hope it was caught.
    if (exceptionInfo->ExceptionRecord->ExceptionCode < 0x80000000 || exceptionInfo->ExceptionRecord->ExceptionCode == 0xe06d7363 ||
        exceptionInfo->ExceptionRecord->ExceptionCode == 0x800706b5)
        return EXCEPTION_CONTINUE_SEARCH;

    //uh oh, we're crashing inside ourselves... this is really bad!
    if (inExceptionHandler)
        return EXCEPTION_CONTINUE_SEARCH;

    inExceptionHandler = TRUE;

    //load dbghelp dynamically
    hDbgHelp = LoadLibrary (TEXT("DBGHELP"));

    if (!hDbgHelp)
        return EXCEPTION_CONTINUE_SEARCH;

    fnEnumerateLoadedModules64 = (ENUMERATELOADEDMODULES64)GetProcAddress (hDbgHelp, "EnumerateLoadedModulesW64");
    fnSymSetOptions = (SYMSETOPTIONS)GetProcAddress (hDbgHelp, "SymSetOptions");
    fnSymInitialize = (SYMINITIALIZE)GetProcAddress (hDbgHelp, "SymInitialize");
    fnSymFunctionTableAccess64 = (SYMFUNCTIONTABLEACCESS64)GetProcAddress (hDbgHelp, "SymFunctionTableAccess64");
    fnSymGetModuleBase64 = (SYMGETMODULEBASE64)GetProcAddress (hDbgHelp, "SymGetModuleBase64");
    fnStackWalk64 = (STACKWALK64)GetProcAddress (hDbgHelp, "StackWalk64");
    fnSymFromAddr = (SYMFROMADDR)GetProcAddress (hDbgHelp, "SymFromAddrW");
    fnSymCleanup = (SYMCLEANUP)GetProcAddress (hDbgHelp, "SymCleanup");
    fnSymGetModuleInfo64 = (SYMGETMODULEINFO64)GetProcAddress (hDbgHelp, "SymGetModuleInfo64");
    fnMiniDumpWriteDump = (MINIDUMPWRITEDUMP)GetProcAddress (hDbgHelp, "MiniDumpWriteDump");

    if (!fnEnumerateLoadedModules64 || !fnSymSetOptions || !fnSymInitialize || !fnSymFunctionTableAccess64 ||
        !fnSymGetModuleBase64 || !fnStackWalk64 || !fnSymFromAddr || !fnSymCleanup || !fnSymGetModuleInfo64)
    {
        FreeLibrary (hDbgHelp);
        return EXCEPTION_CONTINUE_SEARCH;
    }

    hProcess = GetCurrentProcess();

    fnSymSetOptions (SYMOPT_UNDNAME | SYMOPT_FAIL_CRITICAL_ERRORS | SYMOPT_LOAD_ANYTHING);

    GetModuleFileName (NULL, searchPath, _countof(searchPath)-1);
    p = srchr (searchPath, '\\');
    if (p)
        *p = 0;

    //create a log file
    GetSystemTime (&timeInfo);
    for (i = 1;;)
    {
        tsprintf_s (logPath, _countof(logPath)-1, TEXT("%s\\crashDumps\\OBSCrashLog%.4d-%.2d-%.2d_%d.txt"), lpAppDataPath, timeInfo.wYear, timeInfo.wMonth, timeInfo.wDay, i);
        if (GetFileAttributes(logPath) == INVALID_FILE_ATTRIBUTES)
            break;
        i++;
    }

    XFile   crashDumpLog;

    if (!crashDumpLog.Open(logPath, XFILE_WRITE, XFILE_CREATENEW))
    {
        FreeLibrary (hDbgHelp);
        return EXCEPTION_CONTINUE_SEARCH;
    }

    //initialize debug symbols
    fnSymInitialize (hProcess, NULL, TRUE);

#ifdef _WIN64
    InstructionPtr = context.Rip;
    frame.AddrPC.Offset = InstructionPtr;
    frame.AddrFrame.Offset = context.Rbp;
    frame.AddrStack.Offset = context.Rsp;
    imageType = IMAGE_FILE_MACHINE_AMD64;
#else
    InstructionPtr = context.Eip;
    frame.AddrPC.Offset = InstructionPtr;
    frame.AddrFrame.Offset = context.Ebp;
    frame.AddrStack.Offset = context.Esp;
    imageType = IMAGE_FILE_MACHINE_I386;
#endif

    frame.AddrFrame.Mode = AddrModeFlat;
    frame.AddrPC.Mode = AddrModeFlat;
    frame.AddrStack.Mode = AddrModeFlat;

    symInfo = (SYMBOL_INFO *)LocalAlloc (LPTR, sizeof(*symInfo) + 256);
    symInfo->SizeOfStruct = sizeof(SYMBOL_INFO);
    symInfo->MaxNameLen = 256;
    fnOffset = 0;

    //get os info
    memset (&osInfo, 0, sizeof(osInfo));
    osInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);

    if (!GetVersionEx ((OSVERSIONINFO *)&osInfo))
    {
        osInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
        GetVersionEx ((OSVERSIONINFO *)&osInfo);
    }

    //determine which module the crash occured in
    scpy (moduleInfo.moduleName, TEXT("<unknown>"));
    moduleInfo.faultAddress = InstructionPtr;
    fnEnumerateLoadedModules64 (hProcess, (PENUMLOADED_MODULES_CALLBACK64)EnumerateLoadedModulesProcInfo, (VOID *)&moduleInfo);
    slwr (moduleInfo.moduleName);

    String strModuleInfo;
    String crashMessage;

    fnEnumerateLoadedModules64(hProcess, (PENUMLOADED_MODULES_CALLBACK64)RecordAllLoadedModules, (VOID *)&strModuleInfo);

    crashMessage << 
        TEXT("OBS has encountered an unhandled exception and has terminated. If you are able to\r\n")
        TEXT("reproduce this crash, please submit this crash report on the forums at\r\n")
        TEXT("http://www.obsproject.com/ - include the contents of this crash log and the\r\n")
        TEXT("minidump .dmp file (if available) as well as your regular OBS log files and\r\n")
        TEXT("a description of what you were doing at the time of the crash.\r\n")
        TEXT("\r\n")
        TEXT("This crash appears to have occured in the '") << moduleInfo.moduleName << TEXT("' module.\r\n\r\n");

    crashDumpLog.WriteStr(crashMessage.Array());

    crashDumpLog.WriteStr(FormattedString(TEXT("**** UNHANDLED EXCEPTION: %x\r\nFault address: %I64p (%s)\r\n"), exceptionInfo->ExceptionRecord->ExceptionCode, InstructionPtr, moduleInfo.moduleName));

    crashDumpLog.WriteStr(TEXT("OBS version: ") OBS_VERSION_STRING TEXT("\r\n"));
    crashDumpLog.WriteStr(FormattedString(TEXT("Windows version: %d.%d (Build %d) %s\r\n\r\n"), osInfo.dwMajorVersion, osInfo.dwMinorVersion, osInfo.dwBuildNumber, osInfo.szCSDVersion));

    crashDumpLog.WriteStr(TEXT("Crashing thread stack trace:\r\n"));
#ifdef _WIN64
    crashDumpLog.WriteStr(TEXT("Stack            EIP              Arg0             Arg1             Arg2             Arg3             Address\r\n"));
#else
    crashDumpLog.WriteStr(TEXT("Stack    EIP      Arg0     Arg1     Arg2     Arg3     Address\r\n"));
#endif
    crashDumpLog.FlushFileBuffers();

    while (fnStackWalk64 (imageType, hProcess, GetCurrentThread(), &frame, &context, NULL, (PFUNCTION_TABLE_ACCESS_ROUTINE64)fnSymFunctionTableAccess64, (PGET_MODULE_BASE_ROUTINE64)fnSymGetModuleBase64, NULL))
    {
        scpy (moduleInfo.moduleName, TEXT("<unknown>"));
        moduleInfo.faultAddress = frame.AddrPC.Offset;
        fnEnumerateLoadedModules64 (hProcess, (PENUMLOADED_MODULES_CALLBACK64)EnumerateLoadedModulesProcInfo, (VOID *)&moduleInfo);
        slwr (moduleInfo.moduleName);

        p = srchr (moduleInfo.moduleName, '\\');
        if (p)
            p++;
        else
            p = moduleInfo.moduleName;

#ifdef _WIN64
        if (fnSymFromAddr (hProcess, frame.AddrPC.Offset, &fnOffset, symInfo) && !(symInfo->Flags & SYMFLAG_EXPORT))
        {
            crashDumpLog.WriteStr(FormattedString(TEXT("%016I64X %016I64X %016I64X %016I64X %016I64X %016I64X %s!%s+0x%I64x\r\n"),
                frame.AddrStack.Offset,
                frame.AddrPC.Offset,
                frame.Params[0],
                frame.Params[1],
                frame.Params[2],
                frame.Params[3],
                p,
                symInfo->Name,
                fnOffset));
        }
        else
        {
            crashDumpLog.WriteStr(FormattedString(TEXT("%016I64X %016I64X %016I64X %016I64X %016I64X %016I64X %s!0x%I64x\r\n"),
                frame.AddrStack.Offset,
                frame.AddrPC.Offset,
                frame.Params[0],
                frame.Params[1],
                frame.Params[2],
                frame.Params[3],
                p,
                frame.AddrPC.Offset));
        }
#else
        if (fnSymFromAddr (hProcess, frame.AddrPC.Offset, &fnOffset, symInfo) && !(symInfo->Flags & SYMFLAG_EXPORT))
        {
            crashDumpLog.WriteStr(FormattedString(TEXT("%08.8I64X %08.8I64X %08.8X %08.8X %08.8X %08.8X %s!%s+0x%I64x\r\n"),
                frame.AddrStack.Offset,
                frame.AddrPC.Offset,
                (DWORD)frame.Params[0],
                (DWORD)frame.Params[1],
                (DWORD)frame.Params[2],
                (DWORD)frame.Params[3],
                p,
                symInfo->Name,
                fnOffset));
        }
        else
        {
            crashDumpLog.WriteStr(FormattedString(TEXT("%08.8I64X %08.8I64X %08.8X %08.8X %08.8X %08.8X %s!0x%I64x\r\n"),
                frame.AddrStack.Offset,
                frame.AddrPC.Offset,
                (DWORD)frame.Params[0],
                (DWORD)frame.Params[1],
                (DWORD)frame.Params[2],
                (DWORD)frame.Params[3],
                p,
                frame.AddrPC.Offset
                ));
        }
#endif

        crashDumpLog.FlushFileBuffers();
    }

    //generate a minidump if possible
    if (fnMiniDumpWriteDump)
    {
        HANDLE    hFile;

        tsprintf_s (dumpPath, _countof(dumpPath)-1, TEXT("%s\\crashDumps\\OBSCrashDump%.4d-%.2d-%.2d_%d.dmp"), lpAppDataPath, timeInfo.wYear, timeInfo.wMonth, timeInfo.wDay, i);

        hFile = CreateFile (dumpPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
        if (hFile != INVALID_HANDLE_VALUE)
        {
            miniInfo.ClientPointers = TRUE;
            miniInfo.ExceptionPointers = exceptionInfo;
            miniInfo.ThreadId = GetCurrentThreadId ();

            if (fnMiniDumpWriteDump (hProcess, GetCurrentProcessId(), hFile, MiniDumpWithIndirectlyReferencedMemory, &miniInfo, NULL, NULL))
            {
                crashDumpLog.WriteStr(FormattedString(TEXT("\r\nA minidump was saved to %s.\r\nPlease include this file when posting a crash report.\r\n"), dumpPath));
            }
            else
            {
                CloseHandle (hFile);
                DeleteFile (dumpPath);
            }
        }
    }
    else
    {
        crashDumpLog.WriteStr(TEXT("\r\nA minidump could not be created. Please check dbghelp.dll is present.\r\n"));
    }

    crashDumpLog.WriteStr("\r\nList of loaded modules:\r\n");
#ifdef _WIN64
    crashDumpLog.WriteStr("Base Address                      Module\r\n");
#else
    crashDumpLog.WriteStr("Base Address      Module\r\n");
#endif
    crashDumpLog.WriteStr(strModuleInfo);

    crashDumpLog.Close();

    LocalFree (symInfo);

    fnSymCleanup (hProcess);

    if (MessageBox(hwndMain, TEXT("Woops! OBS has crashed. Would you like to view a crash report?"), NULL, MB_ICONERROR | MB_YESNO) == IDYES)
        ShellExecute(NULL, NULL, logPath, NULL, searchPath, SW_SHOWDEFAULT);

    FreeLibrary (hDbgHelp);

    //we really shouldn't be returning here, if we're at the bottom of the VEH chain this is a pretty legitimate crash
    //and if we return we could end up invoking a second crash handler or other weird / annoying things
    //ExitProcess(exceptionInfo->ExceptionRecord->ExceptionCode);
    return EXCEPTION_CONTINUE_SEARCH;
}
Beispiel #12
0
gcore::Semaphore::~Semaphore() {
  CloseHandle((HANDLE)mData);
}
Beispiel #13
0
gcore::Mutex::~Mutex() {
  CloseHandle(MUTEX);
}
Beispiel #14
0
gcore::Condition::~Condition() {
  details::COND_WIN32 *cond = (details::COND_WIN32*)(&mData[0]);
  CloseHandle(cond->notifyOne);
  CloseHandle(cond->notifyAll);
  DeleteCriticalSection(&(cond->blockedLock));
}
Beispiel #15
0
// TODO: Test for archives > 4GB
BOOL WINAPI SFileCreateArchiveEx(const char * szMpqName, DWORD dwCreationDisposition, DWORD dwHashTableSize, HANDLE * phMPQ)
{
    LARGE_INTEGER MpqPos = {0};             // Position of MPQ header in the file
    TMPQArchive * ha = NULL;                // MPQ archive handle
    HANDLE hFile = INVALID_HANDLE_VALUE;    // File handle
    DWORD dwTransferred = 0;                // Number of bytes written into the archive
    USHORT wFormatVersion;
    BOOL bFileExists = FALSE;
    int nIndex = 0;
    int nError = ERROR_SUCCESS;

    // Pre-initialize the result value
    if(phMPQ != NULL)
        *phMPQ = NULL;

    // Check the parameters, if they are valid
    if(szMpqName == NULL || *szMpqName == 0 || phMPQ == NULL)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    // Check the value of dwCreationDisposition against file existence
    bFileExists = (GetFileAttributes(szMpqName) != 0xFFFFFFFF);

    // Extract format version from the "dwCreationDisposition"
    wFormatVersion = (USHORT)(dwCreationDisposition >> 0x10);
    dwCreationDisposition &= 0x0000FFFF;

    // If the file exists and open required, do it.
    if(bFileExists && (dwCreationDisposition == OPEN_EXISTING || dwCreationDisposition == OPEN_ALWAYS))
    {
        // Try to open the archive normal way. If it fails, it means that
        // the file exist, but it is not a MPQ archive.
        if(SFileOpenArchiveEx(szMpqName, 0, 0, phMPQ, GENERIC_READ | GENERIC_WRITE))
            return TRUE;
    }

    // Two error cases
    if(dwCreationDisposition == CREATE_NEW && bFileExists)
    {
        SetLastError(ERROR_ALREADY_EXISTS);
        return FALSE;
    }
    if(dwCreationDisposition == OPEN_EXISTING && bFileExists == FALSE)
    {
        SetLastError(ERROR_FILE_NOT_FOUND);
        return FALSE;
    }

    // At this point, we have to create the archive. If the file exists,
    // we will convert it to MPQ archive.
    // Check the value of hash table size. It has to be a power of two
    // and must be between HASH_TABLE_SIZE_MIN and HASH_TABLE_SIZE_MAX
    if(dwHashTableSize < HASH_TABLE_SIZE_MIN)
        dwHashTableSize = HASH_TABLE_SIZE_MIN;
    if(dwHashTableSize > HASH_TABLE_SIZE_MAX)
        dwHashTableSize = HASH_TABLE_SIZE_MAX;
    
    // Round the hash table size up to the nearest power of two
    for(nIndex = 0; PowersOfTwo[nIndex] != 0; nIndex++)
    {
        if(dwHashTableSize <= PowersOfTwo[nIndex])
        {
            dwHashTableSize = PowersOfTwo[nIndex];
            break;
        }
    }

    // Prepare the buffer for decryption engine
    if(nError == ERROR_SUCCESS)
        nError = PrepareStormBuffer();

    // Get the position where the MPQ header will begin.
    if(nError == ERROR_SUCCESS)
    {
        hFile = CreateFile(szMpqName,
                           GENERIC_READ | GENERIC_WRITE,
                           FILE_SHARE_READ,
                           NULL,
                           dwCreationDisposition,
                           0,
                           NULL);
        if(hFile == INVALID_HANDLE_VALUE)
            nError = GetLastError();
    }

    // Retrieve the file size and round it up to 0x200 bytes
    if(nError == ERROR_SUCCESS)
    {
        MpqPos.LowPart  = GetFileSize(hFile, (LPDWORD)&MpqPos.HighPart);
        MpqPos.QuadPart += 0x1FF;
        MpqPos.LowPart &= 0xFFFFFE00;

        if(wFormatVersion == MPQ_FORMAT_VERSION_1 && MpqPos.HighPart != 0)
            nError = ERROR_DISK_FULL;
        if(wFormatVersion == MPQ_FORMAT_VERSION_2 && MpqPos.HighPart > 0x0000FFFF)
            nError = ERROR_DISK_FULL;
    }

    // Move to the end of the file (i.e. begin of the MPQ)
    if(nError == ERROR_SUCCESS)
    {
        if(SetFilePointer(hFile, MpqPos.LowPart, &MpqPos.HighPart, FILE_BEGIN) == 0xFFFFFFFF)
            nError = GetLastError();
    }

    // Set the new end of the file to the MPQ header position
    if(nError == ERROR_SUCCESS)
    {
        if(!SetEndOfFile(hFile))
            nError = GetLastError();
    }

    // Create the archive handle
    if(nError == ERROR_SUCCESS)
    {
        if((ha = ALLOCMEM(TMPQArchive, 1)) == NULL)
            nError = ERROR_NOT_ENOUGH_MEMORY;
    }

    // Fill the MPQ archive handle structure and create the header,
    // block buffer, hash table and block table
    if(nError == ERROR_SUCCESS)
    {
        memset(ha, 0, sizeof(TMPQArchive));
        strcpy(ha->szFileName, szMpqName);
        ha->hFile          = hFile;
        ha->dwBlockSize    = 0x200 << DEFAULT_BLOCK_SIZE;
        ha->MpqPos         = MpqPos;
        ha->FilePointer    = MpqPos;
        ha->pHeader        = &ha->Header;
        ha->pHashTable     = ALLOCMEM(TMPQHash, dwHashTableSize);
        ha->pBlockTable    = ALLOCMEM(TMPQBlock, dwHashTableSize);
        ha->pExtBlockTable = ALLOCMEM(TMPQBlockEx, dwHashTableSize);
        ha->pbBlockBuffer  = ALLOCMEM(BYTE, ha->dwBlockSize);
        ha->pListFile      = NULL;
        ha->dwFlags       |= MPQ_FLAG_CHANGED;

        if(!ha->pHashTable || !ha->pBlockTable || !ha->pExtBlockTable || !ha->pbBlockBuffer)
            nError = GetLastError();
        hFile = INVALID_HANDLE_VALUE;
    }

    // Fill the MPQ header and all buffers
    if(nError == ERROR_SUCCESS)
    {
        LARGE_INTEGER TempPos;
        TMPQHeader2 * pHeader = ha->pHeader;
        DWORD dwHeaderSize = (wFormatVersion == MPQ_FORMAT_VERSION_2) ? sizeof(TMPQHeader2) : sizeof(TMPQHeader);

        memset(pHeader, 0, sizeof(TMPQHeader2));
        pHeader->dwID            = ID_MPQ;
        pHeader->dwHeaderSize    = dwHeaderSize;
        pHeader->dwArchiveSize   = pHeader->dwHeaderSize + dwHashTableSize * sizeof(TMPQHash);
        pHeader->wFormatVersion  = wFormatVersion;
        pHeader->wBlockSize      = 3;               // 0x1000 bytes per block
        pHeader->dwHashTableSize = dwHashTableSize;

        // Set proper hash table positions
        ha->HashTablePos.QuadPart = ha->MpqPos.QuadPart + pHeader->dwHeaderSize;
        ha->pHeader->dwHashTablePos = pHeader->dwHeaderSize;
        ha->pHeader->wHashTablePosHigh = 0;

        // Set proper block table positions
        ha->BlockTablePos.QuadPart = ha->HashTablePos.QuadPart +
                                     (ha->pHeader->dwHashTableSize * sizeof(TMPQHash));
        TempPos.QuadPart = ha->BlockTablePos.QuadPart - ha->MpqPos.QuadPart;
        ha->pHeader->dwBlockTablePos = TempPos.LowPart;
        ha->pHeader->wBlockTablePosHigh = (USHORT)TempPos.HighPart;

        // For now, we set extended block table positioon top zero unless we add enough
        // files to cause the archive size exceed 4 GB
        ha->ExtBlockTablePos.QuadPart = 0;

        // Clear all tables
        memset(ha->pBlockTable, 0, sizeof(TMPQBlock) * dwHashTableSize);
        memset(ha->pExtBlockTable, 0, sizeof(TMPQBlockEx) * dwHashTableSize);
        memset(ha->pHashTable, 0xFF, sizeof(TMPQHash) * dwHashTableSize);
    }

    // Write the MPQ header to the file
    if(nError == ERROR_SUCCESS)
    {
        DWORD dwHeaderSize = ha->pHeader->dwHeaderSize;

        BSWAP_TMPQHEADER(ha->pHeader);
        WriteFile(ha->hFile, ha->pHeader, dwHeaderSize, &dwTransferred, NULL);
        BSWAP_TMPQHEADER(ha->pHeader);
        
        if(dwTransferred != ha->pHeader->dwHeaderSize)
            nError = ERROR_DISK_FULL;

        ha->FilePointer.QuadPart = ha->MpqPos.QuadPart + dwTransferred;
        ha->MpqSize.QuadPart += dwTransferred;
    }

    // Create the internal listfile
    if(nError == ERROR_SUCCESS)
        nError = SListFileCreateListFile(ha);

    // Try to add the internal listfile
    if(nError == ERROR_SUCCESS)
        SFileAddListFile((HANDLE)ha, NULL);

    // Cleanup : If an error, delete all buffers and return
    if(nError != ERROR_SUCCESS)
    {
        FreeMPQArchive(ha);
        if(hFile != INVALID_HANDLE_VALUE)
            CloseHandle(hFile);
        SetLastError(nError);
    }
    
    // Return the values
    *phMPQ = (HANDLE)ha;
    return (nError == ERROR_SUCCESS);
}
Beispiel #16
0
int ReadFromExeFile(BYTE *filename) 
{
/* Reads data attached to the exe file and calls
   ProcessData(pointertodata, datasize).
   Return values:
	  * ERR_READFAILED - read from exe file had failed;
	  * ERR_BADFORMAT  - invalid format of the exe file;
	  * ERR_NOINFO     - no info was attached.
   If the data were read OK, it returns the return value of ProcessData.
*/
	printf("file= %s\n", filename);
#define ErrIf(a) if(a) goto HANDLE_BADFORMAT;
	BYTE buff[4096]; 
	DWORD read; BYTE* data;

	// Open exe file
	//GetModuleFileNameA(NULL, (CHAR*)buff, sizeof(buff));
	HANDLE hFile = CreateFileA((CHAR*)filename, GENERIC_READ, FILE_SHARE_READ,
		NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if(INVALID_HANDLE_VALUE == hFile) return ERR_READFAILED;
	if(!ReadFile(hFile, buff, sizeof(buff), &read, NULL)) goto HANDLE_READFAILED;
	IMAGE_DOS_HEADER* dosheader = (IMAGE_DOS_HEADER*)buff;
	ErrIf(dosheader->e_magic != IMAGE_DOS_SIGNATURE);
	ErrIf(ULONG(dosheader->e_lfanew) >= ULONG(sizeof(buff) - sizeof(IMAGE_NT_HEADERS32)));

	// Locate PE header
	IMAGE_NT_HEADERS32* header = (IMAGE_NT_HEADERS32*)(buff + dosheader->e_lfanew);
	ErrIf(header->Signature != IMAGE_NT_SIGNATURE);
	IMAGE_SECTION_HEADER* sectiontable =
		(IMAGE_SECTION_HEADER*)((BYTE*)header + sizeof(IMAGE_NT_HEADERS32));
	ErrIf((BYTE*)sectiontable >= buff + sizeof(buff));
	DWORD maxpointer = 0, exesize = 0;

	// For each section
	for(int i = 0; i < header->FileHeader.NumberOfSections; ++i) {
		if(sectiontable->PointerToRawData > maxpointer) {
			maxpointer = sectiontable->PointerToRawData;
			exesize = sectiontable->PointerToRawData + sectiontable->SizeOfRawData;
		}
		sectiontable++;
	}

	// Seek to the overlay
	DWORD filesize = GetFileSize(hFile, NULL);
	if(exesize == filesize) goto HANDLE_NOINFO;
	ErrIf(filesize == INVALID_FILE_SIZE || exesize > filesize);
	if(SetFilePointer(hFile, exesize, NULL, FILE_BEGIN) ==
		INVALID_SET_FILE_POINTER) goto HANDLE_READFAILED;
	data = (BYTE*)malloc(filesize - exesize + 8);
	if(!ReadFile(hFile, data, filesize - exesize, &read, NULL)) goto HANDLE_WITHFREE;
	CloseHandle(hFile);

	// Process the data
	int result = ProcessData(data, filesize - exesize);
	free(data);
	return result;
HANDLE_WITHFREE:
	free(data);
HANDLE_READFAILED:
	CloseHandle(hFile);
	return ERR_READFAILED;
HANDLE_BADFORMAT:
	CloseHandle(hFile);
	return ERR_BADFORMAT;
HANDLE_NOINFO:
	CloseHandle(hFile);
	return ERR_NOINFO;
#undef ErrIf
}
Beispiel #17
0
void starnt::dictionary::load(const std::wstring file)
{	
	if( !dict.empty())
		if(file == dict_file)
			return;
		else
			dict.clear();
	
	char* word;
	[&file, &word]()->void
	{	
		#if defined _WIN32
			HANDLE FileIn;
			FileIn = CreateFileW( file.c_str(),GENERIC_READ ,0,NULL,OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,NULL);
			if (FileIn == INVALID_HANDLE_VALUE) 
				return;
			LARGE_INTEGER len;
			GetFileSizeEx(FileIn, &len);
			word = new char[len.LowPart + 1];
			DWORD count;
			ReadFile(FileIn, word, len.LowPart, &count, NULL);
			if(count != len.LowPart)
				return;

			word[len.LowPart] = '\0';
			CloseHandle(FileIn);
		#else
			// nix version
		#endif
	}();

	//load individual words into strings
	std::pair<std::string, std::string> dict_entry;	
	char* wordtok;
	wordtok = strtok(word, "\n");
	for(int j = 0 ; wordtok != NULL ; j++ , wordtok = strtok(NULL, "\n"))
	{
		if(type == 1)
		{	// encode
			dict_entry.first = wordtok;		// the word
			transform(j, dict_entry.second);	// code
		}
		else
		{	//decode	
			transform(j, dict_entry.first);	// code
			dict_entry.second = wordtok;		// the word
		}
		dict.insert( dict_entry );	
	}



	// replace LF with \0
/*	for(size_t i=0; i < len ; i++)
	{
		while( (word[i] != '\n') && i < len)
			i++;
		word[i] = '\0';
	}

	// then load individual words into strings
	std::pair<std::string, std::string> dict_entry;

	dict_entry.first= &word[0];
	dict_entry.second = "a";
	dict.insert( dict_entry );
	
	for(int i = 2, j = 1 ; i < len ; i++,j++)
	{
		while(word[i] != '\0')
			i++;
		i++;
		if( i <len)
		{	
			dict_entry.first = &word[i];		// the word
			dict_entry.second = transform(j);	// code

			dict.insert( dict_entry );	
		}
		else
			break;
	}
*/

	delete [] word;

}
Beispiel #18
0
int WINAPI
WinMain (
         _In_ HINSTANCE hInstance,
         _In_opt_ HINSTANCE hPrevInstance,
         _In_ PSTR szCmdLine,
         _In_ int iCmdShow)
/*++

Routine Description:

    Entry point for app. Registers class, creates window.

--*/
{
    CHAR        szAppClassName[] = "w1394_AppClass";
    CHAR        szTitleBar[] = "WDF 1394 Hybrid Test Application";
    MSG         Msg;
    WNDCLASSEX  WndClassEx;
    HWND        hWnd;

    UNREFERENCED_PARAMETER (hPrevInstance);
    UNREFERENCED_PARAMETER (szCmdLine);


    g_hInstance = hInstance;

    // main window app...
    WndClassEx.cbSize = sizeof(WNDCLASSEX);
    WndClassEx.style = CS_DBLCLKS | CS_BYTEALIGNWINDOW | CS_GLOBALCLASS;
    WndClassEx.lpfnWndProc = w1394_AppWndProc;
    WndClassEx.cbClsExtra = 0;
    WndClassEx.cbWndExtra = 0;
    WndClassEx.hInstance = g_hInstance;
    WndClassEx.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APP_ICON));
    WndClassEx.hIconSm = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APP_ICON));
    WndClassEx.hCursor = NULL;
    WndClassEx.hbrBackground = (HBRUSH)COLOR_BACKGROUND;
    WndClassEx.lpszMenuName = "AppMenu";
    WndClassEx.lpszClassName = szAppClassName;

    RegisterClassEx( &WndClassEx );

    hWnd = CreateWindowEx ( 
        WS_EX_WINDOWEDGE | WS_EX_ACCEPTFILES,
        szAppClassName,
        szTitleBar,
        WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
        CW_USEDEFAULT,
        CW_USEDEFAULT,
        CW_USEDEFAULT,
        CW_USEDEFAULT,
        NULL,
        NULL,
        g_hInstance,
        NULL);

    ShowWindow(hWnd, iCmdShow);

    while (GetMessage(&Msg, NULL, 0, 0)) 
    {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }

    if (g_hTestDevice)
    {
        CloseHandle (g_hTestDevice);
    }

    return (int)(Msg.wParam);
} // WinMain
Beispiel #19
0
    ~Implementation()
	{
		CloseHandle( breakEvent_ );
	}
Beispiel #20
0
static DWORD shgfi_get_exe_type(LPCWSTR szFullPath)
{
    BOOL status = FALSE;
    HANDLE hfile;
    DWORD BinaryType;
    IMAGE_DOS_HEADER mz_header;
    IMAGE_NT_HEADERS nt;
    DWORD len;
    char magic[4];

    status = GetBinaryTypeW (szFullPath, &BinaryType);
    if (!status)
        return 0;
    if (BinaryType == SCS_DOS_BINARY || BinaryType == SCS_PIF_BINARY)
        return 0x4d5a;

    hfile = CreateFileW( szFullPath, GENERIC_READ, FILE_SHARE_READ,
                         NULL, OPEN_EXISTING, 0, 0 );
    if ( hfile == INVALID_HANDLE_VALUE )
        return 0;

    /*
     * The next section is adapted from MODULE_GetBinaryType, as we need
     * to examine the image header to get OS and version information. We
     * know from calling GetBinaryTypeA that the image is valid and either
     * an NE or PE, so much error handling can be omitted.
     * Seek to the start of the file and read the header information.
     */

    SetFilePointer( hfile, 0, NULL, SEEK_SET );
    ReadFile( hfile, &mz_header, sizeof(mz_header), &len, NULL );

    SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET );
    ReadFile( hfile, magic, sizeof(magic), &len, NULL );
    if ( *(DWORD*)magic == IMAGE_NT_SIGNATURE )
    {
        SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET );
        ReadFile( hfile, &nt, sizeof(nt), &len, NULL );
        CloseHandle( hfile );
        /* DLL files are not executable and should return 0 */
        if (nt.FileHeader.Characteristics & IMAGE_FILE_DLL)
            return 0;
        if (nt.OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
        {
             return IMAGE_NT_SIGNATURE | 
                   (nt.OptionalHeader.MajorSubsystemVersion << 24) |
                   (nt.OptionalHeader.MinorSubsystemVersion << 16);
        }
        return IMAGE_NT_SIGNATURE;
    }
    else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
    {
        IMAGE_OS2_HEADER ne;
        SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET );
        ReadFile( hfile, &ne, sizeof(ne), &len, NULL );
        CloseHandle( hfile );
        if (ne.ne_exetyp == 2)
            return IMAGE_OS2_SIGNATURE | (ne.ne_expver << 16);
        return 0;
    }
    CloseHandle( hfile );
    return 0;
}
LONG ProcessException(struct _EXCEPTION_POINTERS *ExceptionInfo)
{
	char appDescriptor[_MAX_PATH];
	if ((CrashReporter::controls.actionToTake & AOC_SILENT_MODE) == 0)
	{
		sprintf(appDescriptor, "%s has crashed.\nGenerate a report?",  CrashReporter::controls.appName);
		if (::MessageBox( NULL, appDescriptor, "Crash Reporter", MB_YESNO )==IDNO)
		{
			return EXCEPTION_CONTINUE_SEARCH;
		}
	}

	char dumpFilepath[_MAX_PATH];
	char dumpFilename[_MAX_PATH];
	sprintf(appDescriptor, "%s %s - %s %s", CrashReporter::controls.appName, CrashReporter::controls.appVersion, __DATE__, __TIME__);

	if ((CrashReporter::controls.actionToTake & AOC_EMAIL_WITH_ATTACHMENT) ||
		(CrashReporter::controls.actionToTake & AOC_WRITE_TO_DISK)
		)
	{
		if (CrashReporter::controls.actionToTake & AOC_WRITE_TO_DISK)
		{
			strcpy(dumpFilepath, CrashReporter::controls.pathToMinidump);
			WriteFileWithDirectories(dumpFilepath,0,0);
			AddSlash(dumpFilepath);
		}
		else
		{
			// Write to a temporary directory if the user doesn't want the dump on the harddrive.
			if (!GetTempPath( _MAX_PATH, dumpFilepath ))
				dumpFilepath[0]=0;
		}
		unsigned i, dumpFilenameLen;
		strcpy(dumpFilename, appDescriptor);
		dumpFilenameLen=(unsigned) strlen(appDescriptor);
		for (i=0; i < dumpFilenameLen; i++)
			if (dumpFilename[i]==':' || dumpFilename[i]=='/' || dumpFilename[i]=='\\')
				dumpFilename[i]='.'; // Remove illegal characters from filename
		strcat(dumpFilepath, dumpFilename);
		strcat(dumpFilepath, ".dmp");

		HANDLE hFile = CreateFile(dumpFilepath,GENERIC_WRITE, FILE_SHARE_READ,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
		if (hFile==INVALID_HANDLE_VALUE)
			return EXCEPTION_CONTINUE_SEARCH;

		MINIDUMP_EXCEPTION_INFORMATION eInfo;
		eInfo.ThreadId = GetCurrentThreadId();
		eInfo.ExceptionPointers = ExceptionInfo;
		eInfo.ClientPointers = FALSE;

		if (MiniDumpWriteDump(
			GetCurrentProcess(),
			GetCurrentProcessId(),
			hFile,
			(MINIDUMP_TYPE)CrashReporter::controls.minidumpType,
			ExceptionInfo ? &eInfo : NULL,
			NULL,
			NULL)==false)
			return EXCEPTION_CONTINUE_SEARCH;

		CloseHandle(hFile);
	}

	char silentModeEmailBody[1024];
	char subject[1204];
	if (CrashReporter::controls.actionToTake & AOC_EMAIL_NO_ATTACHMENT)
	{
		strcpy(subject, CrashReporter::controls.emailSubjectPrefix);
		strcat(subject, appDescriptor);

		if (CrashReporter::controls.actionToTake & AOC_SILENT_MODE)
		{
			sprintf(silentModeEmailBody, "%s version %s has crashed.\r\nIt was compiled on %s %s.\r\n", CrashReporter::controls.appName,CrashReporter::controls.appVersion, __DATE__, __TIME__);

			if (CrashReporter::controls.actionToTake & AOC_WRITE_TO_DISK)
				sprintf(silentModeEmailBody+strlen(silentModeEmailBody), "Minidump written to %s \r\n", dumpFilepath);

			// Silently send email with attachment
			EmailSender emailSender;
			emailSender.Send(CrashReporter::controls.SMTPServer,
				25,
				CrashReporter::controls.SMTPAccountName,
				CrashReporter::controls.emailRecipient,
				CrashReporter::controls.emailSender,
				CrashReporter::controls.emailRecipient,
				subject,
				silentModeEmailBody,
				0,
				false,
				CrashReporter::controls.emailPassword);
		}
		else
		{
			CSendFileTo sendFile;
			sendFile.SendMail(0, 0, 0, subject, CrashReporter::controls.emailBody, CrashReporter::controls.emailRecipient);
		}
	}
	else if (CrashReporter::controls.actionToTake & AOC_EMAIL_WITH_ATTACHMENT)
	{
		strcpy(subject, CrashReporter::controls.emailSubjectPrefix);
		strcat(subject, dumpFilename);
		strcat(dumpFilename, ".dmp");

		if (CrashReporter::controls.actionToTake & AOC_SILENT_MODE)
		{
			sprintf(silentModeEmailBody, "%s version %s has crashed.\r\nIt was compiled on %s %s.\r\n", CrashReporter::controls.appName,CrashReporter::controls.appVersion, __DATE__, __TIME__);

			if (CrashReporter::controls.actionToTake & AOC_WRITE_TO_DISK)
				sprintf(silentModeEmailBody+strlen(silentModeEmailBody), "Minidump written to %s \r\n", dumpFilepath);

			// Silently send email with attachment
			EmailSender emailSender;
			FileList files;
			files.AddFile(dumpFilepath,dumpFilename,0);
			emailSender.Send(CrashReporter::controls.SMTPServer,
				25,
				CrashReporter::controls.SMTPAccountName,
				CrashReporter::controls.emailRecipient,
				CrashReporter::controls.emailSender,
				CrashReporter::controls.emailRecipient,
				subject,
				silentModeEmailBody,
				&files,
				false,
				CrashReporter::controls.emailPassword);
		}
		else
		{
			CSendFileTo sendFile;
			sendFile.SendMail(0, dumpFilepath, dumpFilename, subject, CrashReporter::controls.emailBody, CrashReporter::controls.emailRecipient);
		}
	}

	return EXCEPTION_EXECUTE_HANDLER;
}
Beispiel #22
0
int nt_execve(const char *prog, const char *const *args, const char *const *envir)
{
	STARTUPINFO si;
	PROCESS_INFORMATION pi;
	enum {none, directex, shellex} execmode;
	DWORD exitcode;
	DWORD dwCreationflags;
	int priority;
	char *argv0;
	char *cmdstr, *cmdend;
	unsigned int cmdsize;
	size_t prognamelen, cmdlen;
	int hasext;
	char extension[_MAX_FNAME];
	const char *begin, *end, *extptr;
	static char exts[MAX_PATH];

	UNREFERENCED_PARAMETER(envir);

	/* get default PATHEXT or use empty exts */
	if (!*exts) {
		DWORD rc;
		/* not initialized */
		rc = GetEnvironmentVariable("PATHEXT", exts, sizeof(exts));
		if ((rc == 0) || (rc >= sizeof(exts)))
			/* if error or PATHEXT too big will retry at the next call */
			*exts = 0;
	}

	/* if prog has an extension initialize begin end to skip PATHEXT search */
	prognamelen = strlen(prog);
	extptr = prog + prognamelen - 1;
	hasext = 0;
	while (extptr > prog && !ISPATHSEP(*extptr)) {
		if (*extptr == '.' && *(extptr - 1) != ':' && !ISPATHSEP(*(extptr - 1))) {
			hasext++;
			break;
		}
		extptr--;
	}
	if (hasext) {
		begin = ".";
		end = "";
		strcpy(extension, extptr);
	} else {
		begin = exts;
		end = exts;
		*extension = '\0';
	}

	argv0 = (char *)heap_alloc(MAX_PATH);
	/* (prognamelen + 1) does not really matter, argv0 is '\0' filled */
	memcpy(argv0, prog, prognamelen + 1);

	errno = 0;
	execmode = none;
	/* NOTE: loops over PATHEXT if no extension found */
	while (*begin) {
		size_t extlen;
		if (GetBinaryType(argv0, &exitcode)) {
			/* exists and is executable
			   NOTE: an "xxx.exe" without a correct PE header (i.e. a text file)
			   has type "DOS binary", but execution will generate a WOW error */
			execmode = directex;
			break;
		}
		if (GetLastError() == ERROR_BAD_EXE_FORMAT) {
			/* exists but is not "executable" */
			execmode = shellex;
			break;
		}
		if (hasext)
			break;
		/* get next PATHEXT extension */
		while (*begin && (*begin != '.'))
			begin++;
		while (*end && (*end != ';'))
			end++;
		if (!*begin)
			break;
		extlen = end - begin;
		if (extlen < sizeof(extension)) {
			memcpy(extension, begin, extlen);
			extension[extlen] = '\0';
			/* prognamelen ignores the last '\r' if present */
			memcpy(argv0, prog, prognamelen);
			/* update argv0 adding the extension to prog */
			memcpy(argv0 + prognamelen, extension, extlen + 1);
		}
		begin = end;
		/* skip sequences of ';' */
		while (*end && *end == ';')
			end++;
	};

	cmdstr = (char *)heap_alloc(MAX_PATH << 2);
	cmdsize = MAX_PATH << 2;
	cmdlen = 0;
	cmdend = cmdstr;

	dbgprintf(PR_VERBOSE, "%s(): execute [%s] extension=[%s] mode=%d hasext=%d\n", __FUNCTION__, argv0, extension, execmode, hasext);
	/* skip over program name */
	args++;

	/* the file (after PATHEXT search) exists, but it's not "executable" */
	if (execmode == shellex) {
		/* if prog had no extension or has the extension associated to shell scripts */
		if ((hasext == 0 && *extension == '\0') || is_shell_script(extension)) {
			int res = process_shebang(argv0, (const char *const *)&cmdstr, &cmdlen, &cmdend, &cmdsize);
			if (res < 0) {
				execmode = none;
			} else if (res == 0) {
				char *newargv[2];
				cmdlen = copy_quote_and_fix_slashes(gModuleName, cmdstr);
				cmdend = cmdstr + cmdlen;
				newargv[0] = path_to_slash(argv0);
				newargv[1] = NULL;
				concat_args_and_quote((const char *const *)newargv, &cmdstr, &cmdlen, &cmdend, &cmdsize);
				*cmdend = 0;
				argv0 = gModuleName;
				execmode = directex;
			} else {
				cmdend = cmdstr + cmdlen;
				execmode = directex;
			}
		} else {
			unsigned long shflags = 0L;
			/* if the file extension is in pathext, use the same console
			   and wait for child. StrStrI() is from shlwapi */
			if (StrStrI(exts, extension))
				shflags = SEE_MASK_NO_CONSOLE | SEE_MASK_NOCLOSEPROCESS;
			if (try_shell_ex(argv0, args, shflags, &cmdstr, &cmdsize))
				return (0);
			/* ShellExecute failed, the file has an unknown extension, but it
			    may be a shell script with a shebang */
			if (process_shebang(argv0, (const char *const *)&cmdstr, &cmdlen, &cmdend, &cmdsize) > 0) {
				cmdend = cmdstr + cmdlen;
				execmode = directex;
			} else {
				/* the file extension is NOT known and the file has NO shebang:
				   returns EPERM, see NOTES */
				errno = EPERM;
				return (-1);
			}
		}
	} else if (execmode == directex) {
		cmdlen = copy_quote_and_fix_slashes(prog, cmdstr);
		cmdend = cmdstr + cmdlen;
	}
	if (execmode == none) {
		/* error: prog not found even after trying PATHEXT extensions */
		errno = ENOENT;
		return (-1);
	}

	concat_args_and_quote(args, &cmdstr, &cmdlen, &cmdend, &cmdsize);
	if (*cmdstr == ' ') {
		/* if we left a ' ' for the quote and there is no quote */
		cmdstr++;
		cmdlen--;
	}
	*cmdend = 0;

	init_startupinfo(&si);
	dwCreationflags = GetPriorityClass(GetCurrentProcess());
	priority = GetThreadPriority(GetCurrentThread());

#if defined(W32DEBUG)
	/* DebugView output is very difficult to read with overlong lines */
	if (cmdlen < 128)
		dbgprintf(PR_EXEC, "%s(): CreateProcess(%s, ..) cmdstr=[%s]\n", __FUNCTION__, argv0, cmdstr);
	else {
		char shortbuf[128+4];
		memcpy(shortbuf, cmdstr, 128);
		memcpy(shortbuf + 128, "...", 4);
		dbgprintf(PR_EXEC, "nt_execve(): CreateProcess(%s, ..) cmdstr=[%s]\n", argv0, shortbuf);
	}
#endif
	if (!CreateProcess(argv0, cmdstr, NULL, NULL,
			   TRUE, // need this for redirecting std handles
			   dwCreationflags | CREATE_SUSPENDED,
			   NULL, NULL, &si, &pi)) {
                exitcode = GetLastError();
		if (exitcode == ERROR_BAD_EXE_FORMAT) {
			dbgprintf(PR_ERROR, "!!! CreateProcess(%s, ..) error BAD_EXE_FORMAT in %s\n", argv0, __FUNCTION__);
			errno  = ENOEXEC;
		} else if (exitcode == ERROR_INVALID_PARAMETER) {
			dbgprintf(PR_ERROR, "!!! CreateProcess(%s, ..) error INVALID_PARAMETER in %s, cmdstr len=%u\n", argv0, __FUNCTION__, strlen(cmdstr));
			/* exceeded command line */
			/* return NOT found, ENAMETOOLONG is correct but not understood by
			   the shell that will retry with another path ... */
			errno = ENOENT;
		} else {
			dbgprintf(PR_ERROR, "!!! CreateProcess(%s, ..) error %ld in %s\n", argv0, exitcode, __FUNCTION__);
			errno = ENOENT;
		}
		goto fail_return;
	} else {
		exitcode = 0;
		if (!SetThreadPriority(pi.hThread, priority))
			dbgprintf(PR_ERROR, "!!! SetThreadPriority(0x%p) failed, error %ld\n", pi.hThread, GetLastError());
		ResumeThread(pi.hThread);
		if (!is_gui(argv0)) {
			if (WaitForSingleObject(pi.hProcess, INFINITE) != WAIT_OBJECT_0)
				dbgprintf(PR_ERROR, "!!! error %ld waiting for process %ld\n", GetLastError(), pi.dwProcessId);
			if (!GetExitCodeProcess(pi.hProcess, &exitcode))
				dbgprintf(PR_ERROR, "!!! GetExitCodeProcess(0x%p, ..) error %ld in %s\n", pi.hProcess, GetLastError(), __FUNCTION__);
		}
		CloseHandle(pi.hProcess);
		CloseHandle(pi.hThread);
		close_si_handles();
		/* @@@@ should wait for the clipboard ?
		if (is_dev_clipboard_active) {
			CloseHandle((HANDLE)_get_osfhandle(0));
			CloseHandle((HANDLE)_get_osfhandle(1));
			CloseHandle((HANDLE)_get_osfhandle(2));
			...
			WaitForSingleObject(ghdevclipthread,60*1000);
			}
		*/
		dbgprintf(PR_ALL, "--- %s(): Exec'd process %ld terminated with exitcode %ld\n", __FUNCTION__, pi.dwProcessId, exitcode);
		exec_exit((int)exitcode);
	}

fail_return:
        heap_free(cmdstr);
	close_si_handles();
	exec_exit(-1);
	return (-1);
}
Beispiel #23
0
BOOL WINAPI AddToEFSFile(
	IN EFSHANDLEFORWRITE hEFSFile,
	IN LPCSTR lpszFileName,
	IN DWORD dwComponentID,
	IN DWORD dwFileID,
	IN DWORD dwData,
	IN DWORD dwFlags
)
{
	assert(hEFSFile);
	assert(lpszFileName);

	// Check for unsupported flags. Right now all flags are unsupported.
	if (dwFlags)
		return FALSE;

	// Extract the EFS archive structure
	EFSFILEHANDLEFORWRITE *pEFSFile = (EFSFILEHANDLEFORWRITE *)hEFSFile;

	assert(pEFSFile->hFile != INVALID_HANDLE_VALUE);
	assert(pEFSFile->pDirectory);

	// If we've exceeded the number of entries in the directory table, we need to allocate a bigger one
	if (pEFSFile->nNumDirectoryEntries >= pEFSFile->nMaxDirectoryEntries)
	{
		DWORD nNumDirEntriesToAlloc = pEFSFile->nMaxDirectoryEntries * 2,
			nNumBytesToAlloc = nNumDirEntriesToAlloc * sizeof(EFSDIRECTORYENTRY);
		EFSDIRECTORYENTRY *pNewDirectory = (EFSDIRECTORYENTRY *)malloc(nNumBytesToAlloc);

		if (!pNewDirectory)
			return FALSE;

		// Copy the entrees over
		DWORD nNumBytesToCopy = pEFSFile->nMaxDirectoryEntries * sizeof(EFSDIRECTORYENTRY);
		memcpy(pNewDirectory, pEFSFile->pDirectory, nNumBytesToCopy);
		ZeroMemory((LPBYTE)pNewDirectory + nNumBytesToCopy, nNumBytesToAlloc - nNumBytesToCopy);

		// Replace the old directory entirely
		free(pEFSFile->pDirectory);

		pEFSFile->pDirectory = pNewDirectory;
		pEFSFile->nMaxDirectoryEntries = nNumDirEntriesToAlloc;
	}

	// Open the file to add to the EFS archive
	HANDLE hFile = CreateFile(lpszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
	if (hFile == INVALID_HANDLE_VALUE)
		return FALSE;

	// Add the file using AddUncompressedToEFSFile
	BOOL bRetVal = FALSE;
	// AddUncompressedToEFSFile may trash the directory even if the addition fails, so we need to make sure we always write it again (mark the archive as modified)
	pEFSFile->bModified = TRUE;

	EFSDIRECTORYENTRY *pDirEntry = &pEFSFile->pDirectory[pEFSFile->nNumDirectoryEntries];
	if (AddUncompressedToEFSFile(pEFSFile, hFile, pDirEntry))
	{
		// Success. Fill in the file data not filled in by AddUncompressedToEFSFile.
		pDirEntry->dwComponentID = dwComponentID;
		pDirEntry->dwFileID = dwFileID;
		pDirEntry->dwData = dwData;
		pDirEntry->dwFlags = 0;

		// Update the archive state
		pEFSFile->dwInsertPoint += pDirEntry->dwSize;
		pEFSFile->nNumDirectoryEntries++;

		bRetVal = TRUE;
	}

	CloseHandle(hFile);

	return bRetVal;
}
Beispiel #24
0
static int try_shell_ex(char *argv0, const char *const *argv, unsigned long shellexflags, char **cmdstr, unsigned int *cmdsize)
{
	char *cmdend;
	size_t cmdlen;
	SHELLEXECUTEINFO shinfo;
	BOOL nocmd = 0;

	path_to_backslash(argv0);

	/* @@@@ is this code really needed ? when ? */
	if ((!*argv) && (argv0[0] == '\\') && (argv0[1] == '\\')) {
		shellexflags |= SEE_MASK_CONNECTNETDRV;
		nocmd = 1;
		goto noargs;
	}

	cmdend = *cmdstr;
	cmdlen = 0;
	concat_args_and_quote(argv, cmdstr, &cmdlen, &cmdend, cmdsize);
	*cmdend = '\0';

noargs:
	dbgprintf(PR_EXEC, "ShellExecute(%s, ..) with cmdstr [%s]\n", argv0, *cmdstr);
	memset(&shinfo, 0, sizeof(shinfo));
	shinfo.cbSize = sizeof(shinfo);
	shinfo.fMask = SEE_MASK_FLAG_NO_UI | SEE_MASK_FLAG_DDEWAIT | shellexflags;
	shinfo.hwnd = NULL;
	shinfo.lpVerb = NULL;
	shinfo.lpFile = argv0;
	shinfo.lpParameters = nocmd ? NULL : *cmdstr;
	shinfo.lpDirectory = 0;
	shinfo.nShow = SW_SHOWDEFAULT;

	if (ShellExecuteEx(&shinfo)) {
		DWORD retval = 255;
		dbgprintf(PR_EXEC, "ShellExecute() created process handle 0x%p\n", shinfo.hProcess);
		/* may happen if "executing" a file associated to a running program, i.e.
		   "execute" a .html file with an already opened browser window */
		if (shinfo.hProcess != (HANDLE)0) {
			if (shellexflags & SEE_MASK_NOCLOSEPROCESS) {
				if ((intptr_t)(shinfo.hInstApp) > 32) {
					if (WaitForSingleObject(shinfo.hProcess, INFINITE) == WAIT_OBJECT_0) {
						/* try to get the return value */
						GetExitCodeProcess(shinfo.hProcess, &retval);
					} else {
						dbgprintf(PR_ERROR, "!!! ShellExecute() [%s] WaitForSingleObject() error %ld\n", argv0, GetLastError());
					}
				} else {
					dbgprintf(PR_ERROR, "!!! ShellExecute() [%s] error %p\n", argv0, shinfo.hInstApp);
				}
			}
			/* try to close, it may fail but .. what else could we do */
			CloseHandle(shinfo.hProcess);
		}
		dbgprintf(PR_ALL, "--- %s(): ShellExecute() OK, exiting with code %ld\n", __FUNCTION__, retval);
		exec_exit((int)retval);
	} else {
		dbgprintf(PR_EXEC, "ShellExecute() failed\n");
	}
       	return (0);
}
Beispiel #25
0
static int process_shebang(char *argv0, const char *const *cmdstr, size_t *cmdlen, char **cmdend, unsigned int *cmdsize)
{
	HANDLE hfile;
	char buf[512];
	unsigned int nn, t0;
	char *ptr, *ptr2;
	char *newargv[4];
	char pbuffer[MAX_PATH];
	char *filepart;
	static const char *shellnames[] = {"/bin/sh", "/bin/zsh", "/bin/ksh"};
	static const char usrbinenv[] = "/usr/bin/env";
	static const char usrbinpython[] = "/usr/bin/python";
	static const char usrbinperl[] = "/usr/bin/perl";
	static const char usrbintcl[] = "/usr/bin/tcl";

	hfile = CreateFile(argv0, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
			   NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (hfile == INVALID_HANDLE_VALUE)
		return (-1);
	if (!ReadFile(hfile, buf, (DWORD)sizeof(buf), (DWORD *)&nn, NULL)) {
		CloseHandle(hfile);
		return (-1);
	}
	CloseHandle(hfile);
	if (!((nn >= 3) && (buf[0] == '#') && (buf[1] == '!')))
		return (0);

	/* this code is more or less what zexecve() does */
	for (t0 = 0; t0 != nn; t0++)
		if ((buf[t0] == '\n') || (buf[t0] == '\r'))
			break;
	while (isspace(buf[t0]))
		buf[t0--] = '\0';
	buf[sizeof(buf)-1] = '\0';
	/* @@@@ fails for "/b/s p/pgm" !!! */
	for (ptr = buf + 2; *ptr && *ptr == ' '; ptr++)
		;
	for (ptr2 = ptr; *ptr && *ptr != ' '; ptr++)
		;
	/* ptr2 is the program name, ptr points to the args */
	dbgprintf(PR_VERBOSE, "%s(): found \"!#\" program=[%s] arg ptr=[%s]\n", __FUNCTION__, ptr2, *ptr ? ptr + 1 : "NULL");
	/* append to the cmdstr
	   should have argv0 ('/' or '\' format ?) */
	if (*ptr) {
		*ptr = '\0';
		newargv[0] = ptr2;
		newargv[1] = ptr + 1;
		newargv[2] = argv0;
	} else {
		newargv[0] = ptr2;
		newargv[1] = argv0;
		newargv[2] = NULL;
	}
	newargv[3] = NULL;
	concat_args_and_quote((const char *const *)newargv, (char **)cmdstr, cmdlen, cmdend, cmdsize);
	*cmdend = '\0';
	/* if ptr2 is a "well known" shell name set argv0 to our module name */
	for (nn = 0; nn < LENGTH_OF(shellnames); nn++) {
		if (strcmp(ptr2, shellnames[nn]) == 0) {
			strcpy(argv0, gModuleName);
			return (1);
		}
	}
	if (strcmp(ptr2, usrbinenv) == 0) {
		SearchPath(NULL, "env.exe", NULL, sizeof(pbuffer), pbuffer, &filepart);
		strcpy(argv0, pbuffer);
	} else if (strcmp(ptr2, usrbinpython) == 0) {
		SearchPath(NULL, "python.exe", NULL, sizeof(pbuffer), pbuffer, &filepart);
		strcpy(argv0, pbuffer);
	} else if (strcmp(ptr2, usrbinperl) == 0) {
		SearchPath(NULL, "perl.exe", NULL, sizeof(pbuffer), pbuffer, &filepart);
		strcpy(argv0, pbuffer);
	} else if (strcmp(ptr2, usrbintcl) == 0) {
		SearchPath(NULL, "tcl.exe", NULL, sizeof(pbuffer), pbuffer, &filepart);
		strcpy(argv0, pbuffer);
	} else {
		char *exeptr;
		path_to_backslash(ptr2);
		strcpy(argv0, ptr2);
		/* if argv0 does not end with ".exe" add ".exe" */
		exeptr = StrStrI(argv0, ".exe");
		if ((exeptr == NULL) || (exeptr != strrchr(argv0, '.'))) {
			strcat(argv0, ".exe");
			dbgprintf(PR_VERBOSE, "%s(): argv0 modified to [%s]\n", __FUNCTION__, argv0);
		}
	}
	return (1);
}
Beispiel #26
0
static int is_gui(const char *exename)
{
	HANDLE hImage;

	DWORD  bytes;
	DWORD  SectionOffset;
	DWORD  CoffHeaderOffset;
	DWORD  MoreDosHeader[16];
	ULONG  ntSignature;
	IMAGE_DOS_HEADER      image_dos_header;
	IMAGE_FILE_HEADER     image_file_header;
	IMAGE_OPTIONAL_HEADER image_optional_header;

	hImage = CreateFile(exename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (INVALID_HANDLE_VALUE == hImage) {
		return 0;
	}

	/*
	 *  Read the MS-DOS image header.
	 */
	if (!ReadFile(hImage, &image_dos_header, sizeof(IMAGE_DOS_HEADER), &bytes, NULL)) {
		CloseHandle(hImage);
		return 0;
	}

	if (IMAGE_DOS_SIGNATURE != image_dos_header.e_magic) {
		CloseHandle(hImage);
		return 0;
	}

	/* Read more MS-DOS header */
	if (!ReadFile(hImage, MoreDosHeader, sizeof(MoreDosHeader), &bytes, NULL)) {
		CloseHandle(hImage);
		return 0;
	}

	/* Get actual COFF header. */
	CoffHeaderOffset = SetFilePointer(hImage, image_dos_header.e_lfanew, NULL, FILE_BEGIN);

	if (CoffHeaderOffset == (DWORD)(-1)) {
		CloseHandle(hImage);
		return 0;
	}

	CoffHeaderOffset += sizeof(ULONG);

	if (!ReadFile (hImage, &ntSignature, sizeof(ULONG), &bytes, NULL)) {
		CloseHandle(hImage);
		return 0;
	}

	if (IMAGE_NT_SIGNATURE != ntSignature) {
		CloseHandle(hImage);
		return 0;
	}

	SectionOffset = CoffHeaderOffset + IMAGE_SIZEOF_FILE_HEADER + IMAGE_SIZEOF_NT_OPTIONAL_HEADER;

	if (!ReadFile(hImage, &image_file_header, IMAGE_SIZEOF_FILE_HEADER, &bytes, NULL)) {
		CloseHandle(hImage);
		return 0;
	}

	/* Read optional header. */
	if (!ReadFile(hImage, &image_optional_header, IMAGE_SIZEOF_NT_OPTIONAL_HEADER, &bytes, NULL)) {
		CloseHandle(hImage);
		return 0;
	}

	CloseHandle(hImage);

	if (image_optional_header.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
		return 1;
	return 0;
}
int WINAPI WinMain(HINSTANCE hInstance,      // handle to current instance
                   HINSTANCE hPrevInstance,  // handle to previous instance
                   LPWSTR lpCmdLine,          // pointer to command line
                   int nCmdShow)             // show state of window
{

    HANDLE tRx, tTx;
    BOOL dma_enable = FALSE;

    NKDbgPrintfW(L"******************************************\n\r");
    NKDbgPrintfW(L"*********    Program Start  **************\n\r");
    NKDbgPrintfW(L"******************************************\n\r");

    dma_enable = FALSE;

    bufferTx = sbufferTx;
    bufferRx = sbufferRx;

    if ((bufferRx == NULL) || (bufferTx == NULL))
    {
        printf("Could not alloc buffers");
        return FALSE;
    }

    //Initialize SSP1 (Master)
    //-----------------------------
    if (!SPIInit(txSSPport, DATABITS, SPI_CLOCK_812_KHZ, SPI_MASTER, SPI_MODE_3, NULL))
    {
        printf("Error in InitSPI");
        return FALSE;
    }

    //Initialize SSP2 (Slave)
    //-----------------------------
    if (!SPIInit(rxSSPport, DATABITS, SPI_CLOCK_812_KHZ, SPI_SLAVE, SPI_MODE_3, NULL))
    {
        printf("Error in InitSPI");
        return FALSE;
    }

    //Create and start transmit/receive threads
    //-----------------------------
    tRx = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) RXThread, 0, 0, NULL);
    CeSetThreadPriority(tRx,10);  //Set receive thread to a high priority to avoid buffer overflows

    //Sleep(100);
    tTx = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) TXThread, 0, 0, NULL);

    printf("\r\nPress ENTER to leave the application.\r\n");
    getchar();

    TerminateThread(tRx, 0);
    TerminateThread(tTx, 0);
    Sleep(20);

    CloseHandle(tRx);
    CloseHandle(tTx);

    //Deinit
    //Very Important
    //if you forget to Deinit a SPI and Init the SPI new the spi interrupts will not work.
    //In this case you have to reset the System
    DeinitSPI(txSSPport);
    DeinitSPI(rxSSPport);

    return TRUE;

}
Beispiel #28
0
/* makes the replace */
INT replace(TCHAR source[MAX_PATH], TCHAR dest[MAX_PATH], DWORD dwFlags, BOOL *doMore)
{
    TCHAR d[MAX_PATH];
    TCHAR s[MAX_PATH];
    HANDLE hFileSrc, hFileDest;
    DWORD  dwAttrib, dwRead, dwWritten;
    LPBYTE buffer;
    BOOL   bEof = FALSE;
    FILETIME srcCreationTime, destCreationTime, srcLastAccessTime, destLastAccessTime;
    FILETIME srcLastWriteTime, destLastWriteTime;
    GetPathCase(source, s);
    GetPathCase(dest, d);
    s[0] = _totupper(s[0]);
    d[0] = _totupper(d[0]);
    // ConOutPrintf(_T("old-src:  %s\n"), s);
    // ConOutPrintf(_T("old-dest: %s\n"), d);
    // ConOutPrintf(_T("src:  %s\n"), source);
    // ConOutPrintf(_T("dest: %s\n"), dest);

    /* Open up the sourcefile */
    hFileSrc = CreateFile (source, GENERIC_READ, FILE_SHARE_READ,NULL, OPEN_EXISTING, 0, NULL);
    if (hFileSrc == INVALID_HANDLE_VALUE)
    {
        ConOutResPrintf(STRING_COPY_ERROR1, source);
        return 0;
    }

    /*
     * Get the time from source file to be used in the comparison
     * with dest time if update switch is set.
     */
    GetFileTime (hFileSrc, &srcCreationTime, &srcLastAccessTime, &srcLastWriteTime);

    /*
     * Retrieve the source attributes so that they later on
     * can be inserted in to the destination.
     */
    dwAttrib = GetFileAttributes (source);

    if (IsExistingFile (dest))
    {
        /*
         * Resets the attributes to avoid probles with read only files,
         * checks for read only has been made earlier.
         */
        SetFileAttributes(dest,FILE_ATTRIBUTE_NORMAL);
        /*
         * Is the update flas set? The time has to be controled so that
         * only older files are replaced.
         */
        if (dwFlags & REPLACE_UPDATE)
        {
            /* Read destination time */
            hFileDest = CreateFile(dest, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
                0, NULL);

            if (hFileSrc == INVALID_HANDLE_VALUE)
            {
                ConOutResPrintf(STRING_COPY_ERROR1, dest);
                return 0;
            }

            /* Compare time */
            GetFileTime (hFileDest, &destCreationTime, &destLastAccessTime, &destLastWriteTime);
            if (!((srcLastWriteTime.dwHighDateTime > destLastWriteTime.dwHighDateTime) ||
                    (srcLastWriteTime.dwHighDateTime == destLastWriteTime.dwHighDateTime &&
                     srcLastWriteTime.dwLowDateTime > destLastWriteTime.dwLowDateTime)))
            {
                CloseHandle (hFileSrc);
                CloseHandle (hFileDest);
                return 0;
            }
            CloseHandle (hFileDest);
        }
        /* Delete the old file */
        DeleteFile (dest);
    }

    /* Check confirm flag, and take appropriate action */
    if (dwFlags & REPLACE_CONFIRM)
    {
        /* Output depending on add flag */
        if (dwFlags & REPLACE_ADD)
            ConOutResPrintf(STRING_REPLACE_HELP9, dest);
        else
            ConOutResPrintf(STRING_REPLACE_HELP10, dest);
        if ( !FilePromptYNA (0))
        {
            CloseHandle (hFileSrc);
            return 0;
        }
    }

    /* Output depending on add flag */
    if (dwFlags & REPLACE_ADD)
        ConOutResPrintf(STRING_REPLACE_HELP11, dest);
    else
        ConOutResPrintf(STRING_REPLACE_HELP5, dest);

    /* Make sure source and destination is not the same */
    if (!_tcscmp(s, d))
    {
        ConOutResPaging(TRUE, STRING_REPLACE_ERROR7);
        CloseHandle (hFileSrc);
        *doMore = FALSE;
        return 0;
    }

    /* Open destination file to write to */
    hFileDest = CreateFile (dest, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
    if (hFileDest == INVALID_HANDLE_VALUE)
    {
        CloseHandle (hFileSrc);
        ConOutResPaging(TRUE, STRING_REPLACE_ERROR7);
        *doMore = FALSE;
        return 0;
    }

    /* Get buffer for the copy process */
    buffer = VirtualAlloc(NULL, BUFF_SIZE, MEM_COMMIT, PAGE_READWRITE);
    if (buffer == NULL)
    {
        CloseHandle (hFileDest);
        CloseHandle (hFileSrc);
        ConOutResPaging(TRUE, STRING_ERROR_OUT_OF_MEMORY);
        return 0;
    }

    /* Put attribute and time to the new destination file */
    SetFileAttributes (dest, dwAttrib);
    SetFileTime (hFileDest, &srcCreationTime, &srcLastAccessTime, &srcLastWriteTime);
    do
    {
        /* Read data from source */
        ReadFile (hFileSrc, buffer, BUFF_SIZE, &dwRead, NULL);

        /* Done? */
        if (dwRead == 0)
            break;

        /* Write to destination file */
        WriteFile (hFileDest, buffer, dwRead, &dwWritten, NULL);

        /* Done! or ctrl break! */
        if (dwWritten != dwRead || CheckCtrlBreak(BREAK_INPUT))
        {
            ConOutResPuts(STRING_COPY_ERROR3);
            VirtualFree (buffer, 0, MEM_RELEASE);
            CloseHandle (hFileDest);
            CloseHandle (hFileSrc);
            nErrorLevel = 1;
            return 0;
        }
    }
    while (!bEof);

    /* Return memory and close files */
    VirtualFree (buffer, 0, MEM_RELEASE);
    CloseHandle (hFileDest);
    CloseHandle (hFileSrc);

    /* Return one file replaced */
    return 1;
}
Beispiel #29
0
int
rpl_stat (char const *name, struct stat *buf)
{
#ifdef WINDOWS_NATIVE
  /* Fill the fields ourselves, because the original stat function returns
     values for st_atime, st_mtime, st_ctime that depend on the current time
     zone.  See
     <https://lists.gnu.org/archive/html/bug-gnulib/2017-04/msg00134.html>  */
  /* XXX Should we convert to wchar_t* and prepend '\\?\', in order to work
     around length limitations
     <https://msdn.microsoft.com/en-us/library/aa365247.aspx> ?  */

  /* POSIX <http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13>
     specifies: "More than two leading <slash> characters shall be treated as
     a single <slash> character."  */
  if (ISSLASH (name[0]) && ISSLASH (name[1]) && ISSLASH (name[2]))
    {
      name += 2;
      while (ISSLASH (name[1]))
        name++;
    }

  size_t len = strlen (name);
  size_t drive_prefix_len = (HAS_DEVICE (name) ? 2 : 0);

  /* Remove trailing slashes (except the very first one, at position
     drive_prefix_len), but remember their presence.  */
  size_t rlen;
  bool check_dir = false;

  rlen = len;
  while (rlen > drive_prefix_len && ISSLASH (name[rlen-1]))
    {
      check_dir = true;
      if (rlen == drive_prefix_len + 1)
        break;
      rlen--;
    }

  /* Handle '' and 'C:'.  */
  if (!check_dir && rlen == drive_prefix_len)
    {
      errno = ENOENT;
      return -1;
    }

  /* Handle '\\'.  */
  if (rlen == 1 && ISSLASH (name[0]) && len >= 2)
    {
      errno = ENOENT;
      return -1;
    }

  const char *rname;
  char *malloca_rname;
  if (rlen == len)
    {
      rname = name;
      malloca_rname = NULL;
    }
  else
    {
      malloca_rname = malloca (rlen + 1);
      if (malloca_rname == NULL)
        {
          errno = ENOMEM;
          return -1;
        }
      memcpy (malloca_rname, name, rlen);
      malloca_rname[rlen] = '\0';
      rname = malloca_rname;
    }

  /* There are two ways to get at the requested information:
       - by scanning the parent directory and examining the relevant
         directory entry,
       - by opening the file directly.
     The first approach fails for root directories (e.g. 'C:\') and
     UNC root directories (e.g. '\\server\share').
     The second approach fails for some system files (e.g. 'C:\pagefile.sys'
     and 'C:\hiberfil.sys'): ERROR_SHARING_VIOLATION.
     The second approach gives more information (in particular, correct
     st_dev, st_ino, st_nlink fields).
     So we use the second approach and, as a fallback except for root and
     UNC root directories, also the first approach.  */
  {
    int ret;

    {
      /* Approach based on the file.  */

      /* Open a handle to the file.
         CreateFile
         <https://msdn.microsoft.com/en-us/library/aa363858.aspx>
         <https://msdn.microsoft.com/en-us/library/aa363874.aspx>  */
      HANDLE h =
        CreateFile (rname,
                    FILE_READ_ATTRIBUTES,
                    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                    NULL,
                    OPEN_EXISTING,
                    /* FILE_FLAG_POSIX_SEMANTICS (treat file names that differ only
                       in case as different) makes sense only when applied to *all*
                       filesystem operations.  */
                    FILE_FLAG_BACKUP_SEMANTICS /* | FILE_FLAG_POSIX_SEMANTICS */,
                    NULL);
      if (h != INVALID_HANDLE_VALUE)
        {
          ret = _gl_fstat_by_handle (h, rname, buf);
          CloseHandle (h);
          goto done;
        }
    }

    /* Test for root and UNC root directories.  */
    if ((rlen == drive_prefix_len + 1 && ISSLASH (rname[drive_prefix_len]))
        || is_unc_root (rname))
      goto failed;

    /* Fallback.  */
    {
      /* Approach based on the directory entry.  */

      if (strchr (rname, '?') != NULL || strchr (rname, '*') != NULL)
        {
          /* Other Windows API functions would fail with error
             ERROR_INVALID_NAME.  */
          if (malloca_rname != NULL)
            freea (malloca_rname);
          errno = ENOENT;
          return -1;
        }

      /* Get the details about the directory entry.  This can be done through
         FindFirstFile
         <https://msdn.microsoft.com/en-us/library/aa364418.aspx>
         <https://msdn.microsoft.com/en-us/library/aa365740.aspx>
         or through
         FindFirstFileEx with argument FindExInfoBasic
         <https://msdn.microsoft.com/en-us/library/aa364419.aspx>
         <https://msdn.microsoft.com/en-us/library/aa364415.aspx>
         <https://msdn.microsoft.com/en-us/library/aa365740.aspx>  */
      WIN32_FIND_DATA info;
      HANDLE h = FindFirstFile (rname, &info);
      if (h == INVALID_HANDLE_VALUE)
        goto failed;

      /* Test for error conditions before starting to fill *buf.  */
      if (sizeof (buf->st_size) <= 4 && info.nFileSizeHigh > 0)
        {
          FindClose (h);
          if (malloca_rname != NULL)
            freea (malloca_rname);
          errno = EOVERFLOW;
          return -1;
        }

# if _GL_WINDOWS_STAT_INODES
      buf->st_dev = 0;
#  if _GL_WINDOWS_STAT_INODES == 2
      buf->st_ino._gl_ino[0] = buf->st_ino._gl_ino[1] = 0;
#  else /* _GL_WINDOWS_STAT_INODES == 1 */
      buf->st_ino = 0;
#  endif
# else
      /* st_ino is not wide enough for identifying a file on a device.
         Without st_ino, st_dev is pointless.  */
      buf->st_dev = 0;
      buf->st_ino = 0;
# endif

      /* st_mode.  */
      unsigned int mode =
        /* XXX How to handle FILE_ATTRIBUTE_REPARSE_POINT ?  */
        ((info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? _S_IFDIR | S_IEXEC_UGO : _S_IFREG)
        | S_IREAD_UGO
        | ((info.dwFileAttributes & FILE_ATTRIBUTE_READONLY) ? 0 : S_IWRITE_UGO);
      if (!(info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
        {
          /* Determine whether the file is executable by looking at the file
             name suffix.  */
          if (info.nFileSizeHigh > 0 || info.nFileSizeLow > 0)
            {
              const char *last_dot = NULL;
              const char *p;
              for (p = info.cFileName; *p != '\0'; p++)
                if (*p == '.')
                  last_dot = p;
              if (last_dot != NULL)
                {
                  const char *suffix = last_dot + 1;
                  if (_stricmp (suffix, "exe") == 0
                      || _stricmp (suffix, "bat") == 0
                      || _stricmp (suffix, "cmd") == 0
                      || _stricmp (suffix, "com") == 0)
                    mode |= S_IEXEC_UGO;
                }
            }
        }
      buf->st_mode = mode;

      /* st_nlink.  Ignore hard links here.  */
      buf->st_nlink = 1;

      /* There's no easy way to map the Windows SID concept to an integer.  */
      buf->st_uid = 0;
      buf->st_gid = 0;

      /* st_rdev is irrelevant for normal files and directories.  */
      buf->st_rdev = 0;

      /* st_size.  */
      if (sizeof (buf->st_size) <= 4)
        /* Range check already done above.  */
        buf->st_size = info.nFileSizeLow;
      else
        buf->st_size = ((long long) info.nFileSizeHigh << 32) | (long long) info.nFileSizeLow;

      /* st_atime, st_mtime, st_ctime.  */
# if _GL_WINDOWS_STAT_TIMESPEC
      buf->st_atim = _gl_convert_FILETIME_to_timespec (&info.ftLastAccessTime);
      buf->st_mtim = _gl_convert_FILETIME_to_timespec (&info.ftLastWriteTime);
      buf->st_ctim = _gl_convert_FILETIME_to_timespec (&info.ftCreationTime);
# else
      buf->st_atime = _gl_convert_FILETIME_to_POSIX (&info.ftLastAccessTime);
      buf->st_mtime = _gl_convert_FILETIME_to_POSIX (&info.ftLastWriteTime);
      buf->st_ctime = _gl_convert_FILETIME_to_POSIX (&info.ftCreationTime);
# endif

      FindClose (h);

      ret = 0;
    }

   done:
    if (ret >= 0 && check_dir && !S_ISDIR (buf->st_mode))
      {
        errno = ENOTDIR;
        ret = -1;
      }
    if (malloca_rname != NULL)
      {
        int saved_errno = errno;
        freea (malloca_rname);
        errno = saved_errno;
      }
    return ret;
  }

 failed:
  {
    DWORD error = GetLastError ();
    #if 0
    fprintf (stderr, "rpl_stat error 0x%x\n", (unsigned int) error);
    #endif

    if (malloca_rname != NULL)
      freea (malloca_rname);

    switch (error)
      {
      /* Some of these errors probably cannot happen with the specific flags
         that we pass to CreateFile.  But who knows...  */
      case ERROR_FILE_NOT_FOUND: /* The last component of rname does not exist.  */
      case ERROR_PATH_NOT_FOUND: /* Some directory component in rname does not exist.  */
      case ERROR_BAD_PATHNAME:   /* rname is such as '\\server'.  */
      case ERROR_BAD_NET_NAME:   /* rname is such as '\\server\nonexistentshare'.  */
      case ERROR_INVALID_NAME:   /* rname contains wildcards, misplaced colon, etc.  */
      case ERROR_DIRECTORY:
        errno = ENOENT;
        break;

      case ERROR_ACCESS_DENIED:  /* rname is such as 'C:\System Volume Information\foo'.  */
      case ERROR_SHARING_VIOLATION: /* rname is such as 'C:\pagefile.sys' (second approach only).  */
                                    /* XXX map to EACCESS or EPERM? */
        errno = EACCES;
        break;

      case ERROR_OUTOFMEMORY:
        errno = ENOMEM;
        break;

      case ERROR_WRITE_PROTECT:
        errno = EROFS;
        break;

      case ERROR_WRITE_FAULT:
      case ERROR_READ_FAULT:
      case ERROR_GEN_FAILURE:
        errno = EIO;
        break;

      case ERROR_BUFFER_OVERFLOW:
      case ERROR_FILENAME_EXCED_RANGE:
        errno = ENAMETOOLONG;
        break;

      case ERROR_DELETE_PENDING: /* XXX map to EACCESS or EPERM? */
        errno = EPERM;
        break;

      default:
        errno = EINVAL;
        break;
      }

    return -1;
  }
#else
  int result = orig_stat (name, buf);
# if REPLACE_FUNC_STAT_FILE
  /* Solaris 9 mistakenly succeeds when given a non-directory with a
     trailing slash.  */
  if (result == 0 && !S_ISDIR (buf->st_mode))
    {
      size_t len = strlen (name);
      if (ISSLASH (name[len - 1]))
        {
          errno = ENOTDIR;
          return -1;
        }
    }
# endif /* REPLACE_FUNC_STAT_FILE */
  return result;
#endif
}
Beispiel #30
-31
bool execute(const char* command, std::string currentDir, DWORD& retCode, std::string& output) {
	HANDLE outWR;

	SECURITY_ATTRIBUTES sa;
	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
	sa.lpSecurityDescriptor = NULL;
	sa.bInheritHandle = TRUE;

	TCHAR lpTempPathBuffer[BUFSIZE];
	TCHAR szTempFileName[MAX_PATH];
	DWORD ret = GetTempPath(BUFSIZE, lpTempPathBuffer);
	if (ret > BUFSIZE || ret == 0) {
		MessageBox(	NULL, "Error GetTempPath", "Error", MB_OK );
		return false;
	}

	ret = GetTempFileName(lpTempPathBuffer, "svn", 0, szTempFileName);
	if (ret == 0) {
		MessageBox(	NULL, "Error GetTempFileName", "Error", MB_OK );
		return false;
	}

	outWR = CreateFile(szTempFileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if (outWR == INVALID_HANDLE_VALUE) {
		MessageBox(	NULL, "Error create file", "Error", MB_OK );
		return false;
	}

	PROCESS_INFORMATION processInfomation;
	STARTUPINFO startupInfo;
	memset(&processInfomation, 0, sizeof(processInfomation));
	memset(&startupInfo, 0, sizeof(startupInfo));
	startupInfo.cb = sizeof(startupInfo);
	startupInfo.hStdError = outWR;
	startupInfo.hStdOutput = outWR;
	startupInfo.dwFlags |= STARTF_USESTDHANDLES;
	startupInfo.wShowWindow = SW_HIDE;

	BOOL result = CreateProcess(
		NULL,
		(char*) command,
		NULL,
		NULL,
		TRUE,
		0,
		NULL,
		currentDir.c_str(),
		&startupInfo,
		&processInfomation);

	if (!result) {
		MessageBox(	NULL, "Can't CreateProcess", "Error", MB_OK );
		CloseHandle(outWR);
		return false;
	} else {
		WaitForSingleObject(processInfomation.hProcess, INFINITE);
		GetExitCodeProcess(processInfomation.hProcess, &retCode);
		CloseHandle(processInfomation.hProcess);
		CloseHandle(processInfomation.hThread);

		// read from stdout
		if (!CloseHandle(outWR)) {
			MessageBox(	NULL, "Can't CloseHandle", "Error", MB_OK );
			return false;
		}

		outWR = CreateFile(szTempFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
		if (outWR == INVALID_HANDLE_VALUE) {
			MessageBox(	NULL, "Error open file", "Error", MB_OK );
			return false;
		}

		CHAR buf[BUFSIZE];
		DWORD dwRead;
		DWORD totalSize = 0;
		std::vector<char*> allBufs;
		std::vector<DWORD> lens;
		while (true) {
			result = ReadFile(outWR, buf, BUFSIZE, &dwRead, NULL);
			if (!result || dwRead == 0) break;
			totalSize += dwRead;
			char* content = new char[dwRead];
			memcpy(content, buf, dwRead);
			allBufs.push_back(content);
			lens.push_back(dwRead);
		}
		char* content = new char[totalSize + 1];
		char* currentPtr = content;
		for (std::size_t i = 0; i < allBufs.size(); i++) {
			memcpy(currentPtr, allBufs[i], lens[i]);
			currentPtr += lens[i];
		}
		content[totalSize] = 0;
		for (std::size_t i = 0; i < allBufs.size(); i++) {
			delete[] allBufs[i];
		}
		output.swap(std::string(content));
		delete[] content;

		CloseHandle(outWR);
		return true;
	}
}