예제 #1
0
int _tmain(int argc, _TCHAR *argv[])
{
    int i;

    for (i = 0; i < 10; ++i)
    {
        if (!QueueUserWorkItem(ThreadProc, (LPVOID)i, WT_EXECUTEDEFAULT))
            _ftprintf(stderr, _T("Failed to queue user worker item %d.\n"), i);
    }

    _putts(_T("Done!"));

    Sleep(1000);

    _putts(_T("-------------------------------------------------------------------------------"));

    for (i = 10; i < 20; ++i)
    {
        if (!QueueUserWorkItem(ThreadProc, (LPVOID)i, WT_EXECUTEDEFAULT))
            _ftprintf(stderr, _T("Failed to queue user worker item %d.\n"), i);
    }
    
    _tsystem(_T("pause"));

    return 0;
}
예제 #2
0
파일: logoff.c 프로젝트: RareHare/reactos
//----------------------------------------------------------------------
//
//Sets flags based on commandline arguments
//
//----------------------------------------------------------------------
BOOL ParseCommandLine(int argc, TCHAR *argv[])
{
	int i;
	LPTSTR lpIllegalMsg;

	//FIXME: Add handling of commandline arguments to select the session number and name, and also name of remote machine
	//Example: logoff.exe 4 /SERVER:Master should logoff session number 4 on remote machine called Master.

	for (i = 1; i < argc; i++) {
		switch(argv[i][0]){
		case '-':
		case '/':
			// -v (verbose)
			if (argv[i][1] == 'v') {
				bVerbose = TRUE;
				break; //continue parsing the arguments
			}
			// -? (usage)
			else if(argv[i][1] == '?') {
				return FALSE; //display the Usage
			}
		default:
			//Invalid parameter detected
			if (AllocAndLoadString(&lpIllegalMsg, GetModuleHandle(NULL), IDS_ILLEGAL_PARAM))
			_putts(lpIllegalMsg);
			return FALSE;
		}
	}

	return TRUE;
}
예제 #3
0
파일: ansicon.c 프로젝트: voxik/ansicon
void help( void )
{
  _putts( TEXT(
"ANSICON by Jason Hood <*****@*****.**>.\n"
"Version " PVERS " (" PDATE ").  Freeware.\n"
"http://ansicon.adoxa.cjb.net/\n"
"\n"
#ifdef _WIN64
"Process ANSI escape sequences in Windows console programs.\n"
#else
"Process ANSI escape sequences in Win32 console programs.\n"
#endif
"\n"
"ansicon -i|I | -u|U\n"
"ansicon [-m[<attr>]] [-p | -e|E string | -t|T [file(s)] | program [args]]\n"
"\n"
"  -i\t\tinstall - add ANSICON to the AutoRun entry\n"
"  -u\t\tuninstall - remove ANSICON from the AutoRun entry\n"
"  -I -U\t\tuse local machine instead of current user\n"
"  -m\t\tuse grey on black (\"monochrome\") or <attr> as default color\n"
"  -p\t\thook into the parent process\n"
"  -e\t\techo string\n"
"  -E\t\techo string, don't append newline\n"
"  -t\t\tdisplay files (\"-\" for stdin), combined as a single stream\n"
"  -T\t\tdisplay files, name first, blank line before and after\n"
"  program\trun the specified program\n"
"  nothing\trun a new command processor, or display stdin if redirected\n"
"\n"
"<attr> is one or two hexadecimal digits; please use \"COLOR /?\" for details."
	      ) );
}
예제 #4
0
//-----------------------------------------------------------------------------
// プログラム スタート
//-----------------------------------------------------------------------------
int _tmain(int argc, TCHAR** argv) {
	_tsetlocale(LC_ALL, _T("japanese"));

	if (argc == 2) {
		cDrv = argv[1][0];
	}

	TCHAR stressPath[MAX_PATH];
	_stprintf(stressPath, _T("%c:\\__hddstress__"), cDrv);

	TCHAR readPath[MAX_PATH];
	_stprintf(readPath, _T("%c:\\"), cDrv);

	// Ctrl+C でしか止まりません。
	for (;;) {
		// ストレステスト用ファイルを作成するフォルダを準備
		_tmkdir(stressPath);

		// ストレステスト用のファイルを作成
		MakeAll(stressPath);

		// 全ファイルを読み込むテスト
		ReadAll(readPath);
		_putts(_T(""));
	}

	return 0;
}
예제 #5
0
int main(int argc, char **argv) {
  if (argc != 2) {
    fprintf(stderr, "Usage: %s NAME\n", argv[0]);
    return 1;
  }

#ifdef _UNICODE
  TCHAR name[1024];
  int length = ::MultiByteToWideChar(CP_ACP, 0, argv[1], -1, name, 1024);
  if (length == 0)
    return 2;
#else
  const char *name = argv[1];
#endif

  InitialiseDataPath();
  Profile::SetFiles(_T(""));
  Profile::Load();
  DeinitialiseDataPath();

  const TCHAR *value = Profile::Get(name);
  if (value != NULL) {
    _putts(value);
    return 0;
  } else {
    fputs("No such value\n", stderr);
    return 2;
  }
}
예제 #6
0
///////////////////////////////////////////////////////////////////////////////////////
// Logging functions
void CServiceModule::LogEvent(LPCTSTR pFormat, ...)
{
    TCHAR    chMsg[256];
    HANDLE  hEventSource;
    LPTSTR  lpszStrings[1];
    va_list pArg;

    va_start(pArg, pFormat);
    _vstprintf(chMsg, pFormat, pArg);
    va_end(pArg);

    lpszStrings[0] = chMsg;

    if (m_bService)
    {
        /* Get a handle to use with ReportEvent(). */
        hEventSource = RegisterEventSource(NULL, m_szServiceName);
        if (hEventSource != NULL)
        {
            /* Write to event log. */
            ReportEvent(hEventSource, EVENTLOG_INFORMATION_TYPE, 0, 0, NULL, 1, 0, (LPCTSTR*) &lpszStrings[0], NULL);
            DeregisterEventSource(hEventSource);
        }
    }
    else
    {
        // As we are not running as a service, just write the error to the console.
        _putts(chMsg);
    }
}
예제 #7
0
파일: logoff.c 프로젝트: RareHare/reactos
//----------------------------------------------------------------------
//
//Retrieve resource string and output the Usage to the console
//
//----------------------------------------------------------------------
static void PrintUsage() {
	LPTSTR lpUsage = NULL;

	if (AllocAndLoadString(&lpUsage, GetModuleHandle(NULL), IDS_USAGE)) {
		_putts(lpUsage);
	}

}
예제 #8
0
파일: logoff.c 프로젝트: RareHare/reactos
//----------------------------------------------------------------------
//
//Main entry for program
//
//----------------------------------------------------------------------
int _tmain(int argc, TCHAR *argv[])
{
	LPTSTR lpLogoffRemote, lpLogoffLocal;

	//
	// Parse command line
	//
	if (!ParseCommandLine(argc, argv)) {
		PrintUsage();
		return 1;
	}

	//
	//Should we log off session on remote server?
	//
	if (szRemoteServerName) {
		if (bVerbose) {
			if (AllocAndLoadString(&lpLogoffRemote, GetModuleHandle(NULL), IDS_LOGOFF_REMOTE))
			_putts(lpLogoffRemote);
		}

		//FIXME: Add Remote Procedure Call to logoff user on a remote machine
		_ftprintf(stderr, "Remote Procedure Call in logoff.exe has not been implemented");
	}
	//
	//Perform logoff of current session on local machine instead
	//
	else {
		if (bVerbose) {
			//Get resource string, and print it.
			if (AllocAndLoadString(&lpLogoffLocal, GetModuleHandle(NULL), IDS_LOGOFF_LOCAL))
			_putts(lpLogoffLocal);
		}

		//Actual logoff
		if (!ExitWindows(NULL, NULL)) {
			DisplayLastError();
			return 1;
		}
	}

	return 0;
}
예제 #9
0
파일: sample.c 프로젝트: k-takata/bregonig
int _tmain(int argc,TCHAR *argv[])
{
	TCHAR fname[512],line[4096],*p1;
	TCHAR msg[BREGEXP_MAX_ERROR_MESSAGE_LEN];
	FILE *fp;
	int len,ctr;
	BREGEXP *rxp = 0;
	TCHAR dmy[] = _T(" ");
	setlocale(LC_ALL, "");
	if (argc < 2) {
		_putts (_T("usage /regstr/ [file]\n  if omitted assume /usr/dict/words"));
		return 0;
	}
	_tcscpy(fname,_T("/usr/dict/words"));
	if (argc > 2)
		_tcscpy(fname,argv[2]);
	p1 = argv[1];
	fp = _tfopen(fname,_T("r"));
	if (!fp) {
		_tprintf (_T("file cant open  %s\n"),fname);
		return 0;
	}
	BMatch(p1,dmy,dmy+1,&rxp,msg);	// compile using dummy 
	if (msg[0]) {
		_tprintf (_T("parse error  %s\n"),msg);
		return 0;
	}
	ctr = 0;
	while(_fgetts(line,sizeof(line),fp)) {
		len = _tcslen(line);
		if (len && (BMatch(p1,line,line+len,&rxp,msg) > 0)) {
			ctr++;
			line[len-1] = 0;
			_putts(line);
		}
	}
	fclose(fp);

	_tprintf(_T("%ld lines(s) greped\n"),ctr);
	return 0;
}
예제 #10
0
int _tmain( int argc, TCHAR* argv[]) {

 _tsetlocale( LC_ALL, _T(""));

 if ( argc != 3 ) {
  _putts(
   _T("mirrorup, version 1.5 2008-01-17--2008-02-26 (c) Denis Ryzhkov\n")
   _T("http://denis.ryzhkov.org/?soft/mirrorup\n")
   _T("\n")
   _T("usage: mirrorup C:\\proj U:\\proj\n")
   _T("\n")
   _T("means: make a mirror backup of C:\\proj to U:\\proj\n")
   _T("i.e. copy or delete only files and folders\n")
   _T("that were changed after previous backup.\n")
   _T("file size and modification time are only compared.\n")
   _T("\n")
   _T("source code and batch script provided."));
  return 0;
 }

 TCHAR* fromPath = unslash( argv[1]);
 TCHAR* toPath = unslash( argv[2]);
 TCHAR dateTimeStr[ BUF_LEN ];
 _tprintf( _T("\n%s make a mirror backup of %s to %s\n\n"),
  timestamp( dateTimeStr ), fromPath, toPath );

 #define attrErr 0xFFFFFFFF
 if ( GetFileAttributes( toPath ) == attrErr )
  CreateDirectoryEx( fromPath, toPath, 0 );
 if ( GetFileAttributes( toPath ) == attrErr ) {
  _putts( _T("bad path"));
  return 1;
 }

 mirrorup( fromPath, toPath );

 _tprintf( _T("\n%s done ok: %d, errors: %d\n"),
  timestamp( dateTimeStr ), okCount, errCount );
 return 0;
}
예제 #11
0
파일: printf.cpp 프로젝트: xyn9/libstd
int __cdecl _tprintf(LPCTSTR _format, ...){
  //
  TCHAR buff[1024];
  va_list argptr;
  DWORD writed_size = 0;
  //
  va_start(argptr, _format);
  writed_size = wvsprintf(buff, _format, argptr);
  va_end(argptr);
  writed_size = writed_size ? _putts(buff) : 0;
  //
  return writed_size;
}
/**
 * @brief 主函数
 * @return 成功返回EXIT_SUCCESS,失败返回EXIT_FAILURE
 */
int _tmain()
{
	setlocale(LC_ALL, "");

	// 显示虚拟内存的基本信息
	ShowVirtualMemory();

	_putts(TEXT(""));

	// 遍历当前进程的虚拟内存
	WalkVM(GetCurrentProcess());

	return EXIT_SUCCESS;
}
예제 #13
0
int main() {
    if (setlocale(LC_ALL, "") == NULL) {
        return 1;
    }

    std::vector<TCHAR> locale_dir(3000);
    DWORD result = GetModuleFileName(GetModuleHandle(NULL), 
                                     &locale_dir[0], locale_dir.size());

    if (result == 0 || result == locale_dir.size()) {
        return 1;
    }

    if (PathRemoveFileSpec(&locale_dir[0]) == FALSE) {
        return 1;
    }

    const TCHAR dir[] = _T("locale");
    locale_dir.resize(locale_dir.size() + (sizeof(dir) / sizeof(*dir)));
    if (PathAppend(&locale_dir[0], dir) == FALSE) {
        return 1;
    }

#if defined(UNICODE) || defined(_UNICODE)
    _putws(L"UNICODE");
    if (bindtextdomain(PACKAGE_NAME, &locale_dir[0]) == NULL) {
        return 1;
    }
    if (bind_textdomain_codeset(PACKAGE_NAME, "UTF-16LE") == NULL) {
        return 1;
    }
#else
    puts("MBCS");
    if (bindtextdomain(PACKAGE_NAME, &locale_dir[0]) == NULL) {
        return 1;
    }
#endif

    if (textdomain(PACKAGE_NAME) == NULL) {
        return 1;
    }

    _putts(_("Hello, world!"));
    MessageBox(NULL, _("Hello, world!"), &locale_dir[0], MB_OK);

    void use_symbol(); use_symbol();
    return 0;
}
예제 #14
0
int main(int argc, char **argv)
{
  if (argc != 2) {
    fprintf(stderr, "Usage: %s FILE\n", argv[0]);
    return 1;
  }

  const char *path = argv[1];
  FileLineReader reader(path);
  if (reader.error()) {
    fprintf(stderr, "Failed to open %s\n", path);
    return 1;
  }

  TCHAR *line;
  while ((line = reader.read()) != NULL)
    _putts(line);
}
예제 #15
0
int main(int argc, char **argv)
{
  Args args(argc, argv, "FILE");
  const char *path = args.ExpectNext();
  args.ExpectEnd();

  ZipLineReader reader(path);
  if (reader.error()) {
    fprintf(stderr, "Failed to open %s\n", path);
    return 1;
  }

  TCHAR *line;
  while ((line = reader.ReadLine()) != NULL)
    _putts(line);

  return EXIT_SUCCESS;
}
예제 #16
0
int APIENTRY _tWinMain(
					HINSTANCE	hInstance,
					HINSTANCE	/*hPrevInstance*/,
					LPTSTR		/*lpCmdLine*/,
					int			/*nCmdShow*/)
#endif
{
#ifndef EMPTY
	TCHAR szPath[MAX_PATH * 3];

	*szPath = 0;

	GetCurrentDirectory(sizeof(szPath)/sizeof(szPath[0]), szPath);

#ifndef _CONSOLE
	CString strCaption(MAKEINTRESOURCE(IDS_CAPTION));
#endif

	CString strText;
	strText.Format(IDS_TEXT, szPath, GetCommandLine());

#ifdef _CONSOLE
	strText.AnsiToOem();
	_putts(strText);
#else // _WINDOWS

	// We have to create window in order to show message box.
	// Otherwise it won't be shown on XP SP2 + latest updates.

	INITCOMMONCONTROLSEX initCtrls = { sizeof(INITCOMMONCONTROLSEX), 0 };
	ATLVERIFY(InitCommonControlsEx(&initCtrls));

	HWND hwnd = CreateWindow(_T("button"), _T(""), WS_OVERLAPPED | BS_PUSHBUTTON, 0, 0, 0, 0, NULL, NULL, hInstance, NULL);
	ATLASSERT(hwnd != NULL);

	ATLVERIFY(MessageBox(hwnd, strText, strCaption, MB_OK | MB_ICONINFORMATION | MB_TOPMOST | MB_SETFOREGROUND));

	ATLVERIFY(DestroyWindow(hwnd));
#endif // _WINDOWS
#else // EMPTY
	hInstance;
#endif // EMPTY
	return 0;
}
예제 #17
0
int main(int argc, char **argv) {
  Args args(argc, argv, "NAME");
  tstring name = args.ExpectNextT();
  args.ExpectEnd();

  InitialiseDataPath();
  Profile::SetFiles(_T(""));
  Profile::Load();
  DeinitialiseDataPath();

  const TCHAR *value = Profile::Get(name.c_str());
  if (value != NULL) {
    _putts(value);
    return 0;
  } else {
    fputs("No such value\n", stderr);
    return 2;
  }
}
예제 #18
0
파일: dwnl.c 프로젝트: AmineKhaldi/reactos
static void
write_status(LPCTSTR lpFmt, ...)
{
    va_list args;
    TCHAR szTxt[128];
    CONSOLE_SCREEN_BUFFER_INFO csbi;

    va_start(args, lpFmt);
    StringCbVPrintf(szTxt, sizeof(szTxt), lpFmt, args);
    va_end(args);

    if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
    {
        _tprintf(_T("\r%*.*s"), -(csbi.dwSize.X - 1), csbi.dwSize.X - 1, szTxt);
    }
    else
    {
        _putts(szTxt);
    }
}
예제 #19
0
//-----------------------------------------------------------------------------
// ストレスファイルの作成
//-----------------------------------------------------------------------------
int MakeAll(LPCTSTR path) {
	_tprintf(_T("ストレスファイルを '%s' に作成。\n"), path);

	__int64 freeBytes;
	GetDiskFreeSpaceEx(path, (PULARGE_INTEGER)&freeBytes, NULL, NULL);
	_tprintf(_T("空き容量:%13I64u\n"), freeBytes);

	// 空き容量が 1GB を切ったら中身を可能なかぎり削除して次の処理を行う。
	if (freeBytes < 1000000000) {
		RemoveAll(path);
	}

	freeBytes /= 2;
	_tprintf(_T("空き÷2:%13I64u\n"), freeBytes);

	TCHAR fname[MAX_PATH];
	TCHAR fspec[MAX_PATH];
	_stprintf(fspec, _T("%04X-%08X.bin"), GetCurrentProcessId(), GetTickCount());

	PathAppend(lstrcpy(fname, path), fspec);
	FILE* fp = _tfopen(fname, _T("wb"));
	if (fp) {
		__int64 wsize = 0;
		DWORD t1 = GetTickCount();
		for (__int64 i = 0; i < (freeBytes / sizeof(g_buf)); i++) {
			_tprintf(_T("作成中 :%13I64u\r"), i * sizeof(g_buf));
			int ret = fwrite(g_buf, sizeof(char), _countof(g_buf), fp);
			wsize += ret;
			if (ret != _countof(g_buf)) {
				_tprintf(_T("\n書込み中断\n"));
				break;
			}
		}
		DWORD t2 = GetTickCount();
		_tprintf(_T("\n書込み性能:%d Kbps\n"), (wsize / ((t2 - t1) / 1000)) / 1024);
		fclose(fp);
	}
	_putts(_T(""));

	return 0;
}
예제 #20
0
// For not implemented procedures in the library
static void Null_Procedure()
{
#if defined (_WIN32) || defined (_WIN64)
	_putts(_T("Calling a not implemented procedure.\n")
		_T("Check the call stack for more information.\n")
		_T("Terminating..."));
	MessageBox(NULL, _T("Calling a not implemented procedure.\n")
		_T("Check the call stack for more information.\n")
		_T("Terminating..."),
		_T("adl_wrapper error"), MB_OK);
#elif defined (__linux__)
	puts("Calling a not implemented procedure.\n"
		"Use a debugger to check the call stack for more information.\n"
		"Terminating...");
#else
#error unknown os platform
#endif

	assert(0);
	exit(EXIT_FAILURE);
}
예제 #21
0
BOOL UMailSlot::read(LPTSTR sMessage)
{
    if (m_hObj == INVALID_HANDLE_VALUE)
        return FALSE;

    DWORD cbMessageBytes = 0;        // Size of the message in bytes
    DWORD cbBytesRead = 0;            // Number of bytes read from the slot
    DWORD cMessages = 0;            // Number of messages in the mailslot
    DWORD nMessageId = 0;            // Message ID

    BOOL bResult;

    LPTSTR lpszBuffer;                // A buffer used to store one message


    /////////////////////////////////////////////////////////////////////////
    // Check for the number of messages in the mailslot.
    //

    bResult = GetMailslotInfo(
        m_hObj,                    // Handle of the mailslot
        NULL,                        // No maximum message size
        &cbMessageBytes,            // Size of next message
        &cMessages,                    // Number of messages
        NULL);                        // No read time-out

    if (!bResult)
    {
        _tprintf(_T("GetMailslotInfo failed w/err 0x%08lx\n"), GetLastError());
        return FALSE;
    }

    if (cbMessageBytes == MAILSLOT_NO_MESSAGE)
    {
        // There are no new messages in the mailslot at present
        _putts(_T("No new messages."));
        return TRUE;
    }


    /////////////////////////////////////////////////////////////////////////
    // Retrieve the messages one by one from the mailslot.
    //

    while (cMessages != 0) // If there are still un-read messages in the slot
    {
        nMessageId++;

        // Allocate the memory for the message based on its size info,
        // cbMessageBytes, which was retrieved from GetMailslotInfo.

        lpszBuffer = (LPTSTR) GlobalAlloc(GPTR, cbMessageBytes);
        if (NULL == lpszBuffer)
            return FALSE;

        bResult = ReadFile(            // Read from the mailslot.
            m_hObj,                // Handle of the slot
            lpszBuffer,                // Buffer to receive data
            cbMessageBytes,            // Size of buffer in bytes
            &cbBytesRead,            // Number of bytes read
            NULL);                    // Not overlapped I/O

        if (!bResult)
        {
            _tprintf(_T("ReadFile failed w/err 0x%08lx\n"), GetLastError());
            GlobalFree((HGLOBAL)lpszBuffer);
            return FALSE;
        }

        // Display the message.
        _tprintf(_T("Message #%ld: %s\n"), nMessageId, lpszBuffer);

        GlobalFree((HGLOBAL) lpszBuffer); // Free the buffer

        // Get the current number of un-read messages in the slot. The number
        // may not equal the initial message number because new messages may
        // arrive while we are reading the items in the slot.

        bResult = GetMailslotInfo(
            m_hObj,                // Handle of the mailslot
            NULL,                    // No maximum message size
            &cbMessageBytes,        // Size of next message
            &cMessages,                // Number of messages
            NULL);                    // No read time-out

        if (!bResult)
        {
            _tprintf(_T("GetMailslotInfo failed w/err 0x%08lx\n"), GetLastError());
            return FALSE;
        }
    }
    return TRUE;
}
예제 #22
0
파일: var.c 프로젝트: drewpiroli/gwabbitemu
int FindRomVersion(int calc, char *string, unsigned char *rom, int size) {
	int i,b;
	if (calc == -1) {
		if (size == (128 * 1024)) calc = TI_82;
		else if (size == (256 * 1024)) calc = TI_83;
		else if ((size >= (510 * 1024)) && (size <= (590 * 1024))) calc = TI_83P;
		else if ((size >= (1016 * 1024)) && (size<= (1030 * 1024))) calc = TI_84P;
		else if ((size >= (2044 * 1024)) && (size<= (2260 * 1024))) calc = TI_83PSE;
		else {
			_putts(_T("not a known rom"));
			return -1;
		}
	}
	switch (calc) {
		case TI_82:
			for(i = 0; i < (size - strlen(catalog) - 10); i++) {
				if (!CmpStringCase(catalog, rom + i)) {
					calc = TI_85;
						for(i = 0; i < (size - strlen(self_test) - 10); i++) {
							if (CmpStringCase(self_test, rom + i) == 0) break;
						}
						for(; i < (size - 40); i++) {
							if (isdigit(rom[i])) break;
						}
						if (i < (size - 40)) {
							for(b = 0; (b + i) < (size - 4) && b < 32; b++) {
								if (rom[b + i] != ' ') string[b] = rom[b + i];
								else string[b] = 0;
							}
							string[31] = 0;
						} else {
							string[0] = '?';
							string[1] = '?';
							string[2] = '?';
							string[3] = 0;
						}
					break;
				}
			}
			if (calc != TI_82) break;

		case TI_83:
			if (calc == TI_83) {
				for(i = 0; i < (size - strlen(txt86) - 10); i++) {
					if (!CmpStringCase(txt86, rom + i)) {
						calc = TI_86;
							for(i = 0; i < size - strlen(self_test) - 10; i++) {
								if (CmpStringCase(self_test, rom + i) == 0) break;
							}
							for(; i < size - 40; i++) {
								if (isdigit(rom[i])) break;
							}
							if (i < size - 40) {
								for(b = 0; (b + i) < (size - 4) && b < 32; b++) {
									if (rom[b + i] != ' ')
										string[b] = rom[b + i];
									else string[b] = 0;
								}
								string[31] = 0;
							} else {
								string[0] = '?';
								string[1] = '?';
								string[2] = '?';
								string[3] = 0;
							}
						break;
					}
				}
			}
			if (calc == TI_86) break;

			for(i = 0; i < (size - strlen(self_test) - 10); i++) {
				if (CmpStringCase(self_test, rom + i)==0) break;
			}
			if ((i + 64) < size) {
				i += 10;
				for(b = 0; b < 32; b++) {
					string[b] = rom[i++];
				}
				string[31] = 0;
			} else {
				string[0] = '?';
				string[1] = '?';
				string[2] = '?';
				string[3] = 0;
			}
			break;
		case TI_83P:
			for(i = 0; i < (size - strlen(txt73) - 10); i++) {
				if (CmpStringCase(txt73, rom + i) == 0) {
					calc = TI_73;
					break;
				}
			}
		case TI_84P:
		case TI_83PSE:
		case TI_84PSE:
			i = 0x0064;
			for(b = 0; b < 32; b++) {
				string[b] = rom[i++];
			}
			string[31] = 0;
			if (calc == TI_83PSE) {
				if (string[0] > '1') {
					calc = TI_84PSE;
				}
			}
			break;
	}
	return calc;
}
예제 #23
0
void WriteSave(const TCHAR *fn, SAVESTATE_t* save, int compress) {
	int i;
	FILE* ofile;
	FILE* cfile;
	TCHAR tmpfn[L_tmpnam];
	TCHAR temp_save[MAX_PATH];
	
	if (!save) {
		_putts(_T("Save was null for write"));
		return;
	}
	if (compress == 0) {
#ifdef WINVER
		_tfopen_s(&ofile, fn, _T("wb"));
#else
		ofile = fopen(fn,"wb");
#endif
	} else {
#ifdef WINVER
		_ttmpnam_s(tmpfn, sizeof(tmpfn));
		GetAppDataString(temp_save, sizeof(temp_save));
		StringCbCat(temp_save, sizeof(temp_save), tmpfn);
		_tfopen_s(&ofile, temp_save, _T("wb"));
#else
		tmpnam(tmpfn);
		strcpy(temp_save, getenv("appdata"));
		strcat(temp_save, tmpfn);
		ofile = fopen(temp_save,"wb");
#endif
	}
		
	if (!ofile) {
		_putts(_T("Could not open save file for write"));
		return;
	}

	fputs(DETECT_STR, ofile);

	fputi(SAVE_HEADERSIZE, ofile);	
	
	fputi(save->version_major, ofile);
	fputi(save->version_minor, ofile);
	fputi(save->version_build, ofile);
	fputi(save->model, ofile);
	fputi(save->chunk_count, ofile);
	fwrite(save->author, 1,32, ofile);
	fwrite(save->comment, 1, 64, ofile);
	
	for(i = 0; i < save->chunk_count; i++) {
		fputc(save->chunks[i]->tag[0], ofile);
		fputc(save->chunks[i]->tag[1], ofile);
		fputc(save->chunks[i]->tag[2], ofile);
		fputc(save->chunks[i]->tag[3], ofile);
		fputi(save->chunks[i]->size,ofile);
		fwrite(save->chunks[i]->data, 1, save->chunks[i]->size, ofile);
	}
	fclose(ofile);
	
	if (compress) {
#ifdef WINVER
		_tfopen_s(&cfile, fn, _T("wb"));
#else
		cfile = fopen(fn,"wb");
#endif
		if (!cfile) {
			return;
		}
#ifdef WINVER
		_tfopen_s(&ofile, temp_save, _T("rb"));
#else
		ofile = fopen(temp_save,"rb");
#endif
		if (!ofile) {
			return;
		}
		//int error;
		fputs(DETECT_CMP_STR, cfile);
		switch(compress) {
#ifdef ZLIB_WINAPI
			case ZLIB_CMP:
				{
					fputc(ZLIB_CMP, cfile);
				
					int error = def(ofile, cfile, 9);
					break;
				}
#endif
			default:
				break;
		}
		fclose(ofile);
		fclose(cfile);
#ifdef _WINDOWS
		_tremove(temp_save);
#else
		remove(temp_save);
#endif
	}
}
int WiimoteNamedPipeServer::StartPipeServer()
{
	/////////////////////////////////////////////////////////////////////////
	// Create a named pipe.
	// 

	// Prepare the pipe name
	CString strPipeName;
	strPipeName.Format(_T("\\\\%s\\pipe\\%s"), 
		_T("."),			// Server name
		unformattedPipeName	// Pipe name
		);


	// Prepare the security attributes

	// If lpSecurityAttributes of CreateNamedPipe is NULL, the named pipe 
	// gets a default security descriptor and the handle cannot be inherited. 
	// The ACLs in the default security descriptor for a named pipe grant 
	// full control to the LocalSystem account, administrators, and the 
	// creator owner. They also grant read access to members of the Everyone 
	// group and the anonymous account. In other words, with NULL as the 
	// security attributes, the named pipe cannot be connected with the 
	// WRITE permission across the network, or from a local client running 
	// as a lower integiry level. Here, we fill the security attributes to 
	// grant EVERYONE all access (not just the connect access) to the server 
	// This solves the cross-network and cross-IL issues, but it creates 
	// a security hole right there: the clients have WRITE_OWNER access and 
	// then the server just lose the control of the pipe object.
	SECURITY_ATTRIBUTES sa;
	sa.lpSecurityDescriptor = (PSECURITY_DESCRIPTOR)malloc(
		SECURITY_DESCRIPTOR_MIN_LENGTH);
	InitializeSecurityDescriptor(sa.lpSecurityDescriptor, 
		SECURITY_DESCRIPTOR_REVISION);
	// ACL is set as NULL in order to allow all access to the object.
	SetSecurityDescriptorDacl(sa.lpSecurityDescriptor, TRUE, NULL, FALSE);
	sa.nLength = sizeof(sa);
	sa.bInheritHandle = TRUE;

	// Create the named pipe.
	hPipe = CreateNamedPipe(
		strPipeName,				// The unique pipe name. This string must 
									// have the form of \\.\pipe\pipename
		PIPE_ACCESS_DUPLEX,			// The pipe is bi-directional; both  
									// server and client processes can read 
									// from and write to the pipe
		PIPE_TYPE_MESSAGE |			// Message type pipe 
		PIPE_READMODE_MESSAGE |		// Message-read mode 
		PIPE_WAIT,					// Blocking mode is enabled
		PIPE_UNLIMITED_INSTANCES,	// Max. instances

		// These two buffer sizes have nothing to do with the buffers that 
		// are used to read from or write to the messages. The input and 
		// output buffer sizes are advisory. The actual buffer size reserved 
		// for each end of the named pipe is either the system default, the 
		// system minimum or maximum, or the specified size rounded up to the 
		// next allocation boundary. The buffer size specified should be 
		// small enough that your process will not run out of nonpaged pool, 
		// but large enough to accommodate typical requests.
		BUFFER_SIZE,				// Output buffer size in bytes
		BUFFER_SIZE,				// Input buffer size in bytes

		NMPWAIT_USE_DEFAULT_WAIT,	// Time-out interval
		&sa							// Security attributes
		);

	if (hPipe == INVALID_HANDLE_VALUE)
	{
		_tprintf(_T("Unable to create wiimote Command pipe %s w/err 0x%08lx\n"), 
			strPipeName, GetLastError());
		return 1;
	}
	_tprintf(_T("The named pipe, %s, is created.\n"), strPipeName);
	FileLogger::getFileLogger()->logEntry("Wiimote pipe is created");


	Sleep(5000);
	/////////////////////////////////////////////////////////////////////////
	// Wait for the client to connect.
	// 
	
	_putts(_T("Waiting for the client's connection..."));
	FileLogger::getFileLogger()->logEntry("Waiting for the client's connection...");

	BOOL bPipeConnected = ConnectNamedPipe(hPipe, NULL) ? 
		TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);

	if (!bPipeConnected)
	{
		_tprintf(_T(
			"Error occurred while connecting to the client: 0x%08lx\n"
			), GetLastError()); 
		CloseHandle(hPipe);
		return 1;
	}
	FileLogger::getFileLogger()->logEntry("Wiimote Pipe Connected");

	run();
}
예제 #25
0
int _tmain(int argc, _TCHAR* argv[])
{
    HRESULT hr;

    // Initializes the COM library on the current thread and identifies the
    // concurrency model as single-thread apartment (STA).
    ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);


    /////////////////////////////////////////////////////////////////////////
    // Create the ATLDllCOMServer.SimpleObject COM object using the
    // #import directive and smart pointers.
    //

    CComQIPtr<ISimpleObject> spSimpleObj;
    hr = spSimpleObj.CoCreateInstance(OLESTR(
                                          "ATLDllCOMServer.SimpleObject"));
    if (FAILED(hr))
    {
        _tprintf(_T(
                     "ISimpleObjectPtr.CoCreateInstance failed w/err 0x%08lx\n"
                 ), hr);
        return hr;
    }


    /////////////////////////////////////////////////////////////////////////
    // Use sink object 1 (CATLSimpleSinkObject1) to set up the sink for the
    // events of the source COM object.
    //

    _putts(_T("Create sink object 1"));

    // Construct the sink object CATLSimpleSinkObject1 defined in
    // ATLSimpleSinkObject.h
    CATLSimpleSinkObject1* pSinkObj1 = new CATLSimpleSinkObject1();

    // Make sure the COM object corresponding to pUnk implements
    // IProvideClassInfo2 or IPersist*. Call this method to extract info
    // about source type library if you specified only 2 parameters to
    // IDispEventImpl.
    hr = AtlGetObjectSourceInterface(spSimpleObj, &pSinkObj1->m_libid,
                                     &pSinkObj1->m_iid, &pSinkObj1->m_wMajorVerNum,
                                     &pSinkObj1->m_wMinorVerNum);
    _ASSERTE(SUCCEEDED(hr));

    // Connect the sink and source, spSimpleObj is the source COM object
    hr = pSinkObj1->DispEventAdvise(spSimpleObj, &pSinkObj1->m_iid);
    _ASSERTE(SUCCEEDED(hr));


    // Invoke the source COM object
    {
        // Set FloatProperty which fires the event FloatPropertyChanging
        _tprintf(_T("Set FloatProperty = %.2f\n"), 1.1f);
        spSimpleObj->PutFloatProperty(1.1f);

        float fProp = spSimpleObj->GetFloatProperty();
        _tprintf(_T("Get FloatProperty = %.2f\n"), fProp);
    }


    // Disconnect from the source COM object if connected
    if (pSinkObj1->m_dwEventCookie != 0xFEFEFEFE)
        pSinkObj1->DispEventUnadvise(spSimpleObj, &pSinkObj1->m_iid);

    // Destroy the sink object
    delete pSinkObj1;


    /////////////////////////////////////////////////////////////////////////
    // Use sink object 2 (CATLSimpleSinkObject2) to set up the sink for the
    // events of the source COM object.
    //

    _putts(_T("Create sink object 2"));

    // Construct the sink object CATLSimpleSinkObject2 defined in
    // ATLSimpleSinkObject.h
    CATLSimpleSinkObject2* pSinkObj2 = new CATLSimpleSinkObject2();

    // Connect the sink and source, m_spSrcObj is the source COM object
    hr = pSinkObj2->DispEventAdvise(spSimpleObj);
    _ASSERTE(SUCCEEDED(hr));


    // Invoke the source COM object
    {
        // Set FloatProperty which fires the event FloatPropertyChanging
        _tprintf(_T("Set FloatProperty = %.2f\n"), 1.2f);
        spSimpleObj->PutFloatProperty(1.2f);

        float fProp = spSimpleObj->GetFloatProperty();
        _tprintf(_T("Get FloatProperty = %.2f\n"), fProp);
    }


    // Disconnect from source if connected
    if (pSinkObj2->m_dwEventCookie != 0xFEFEFEFE)
        pSinkObj2->DispEventUnadvise(spSimpleObj);

    // Destroy the sink object
    delete pSinkObj2;


    /////////////////////////////////////////////////////////////////////////
    // Use sink object 3 (CATLSimpleSinkObject3) to set up the sink for the
    // events of the source COM object.
    //

    _putts(_T("Create sink object 3"));

    // Construct the sink object CATLSimpleSinkObject3 defined in
    // ATLSimpleSinkObject.h
    CATLSimpleSinkObject3* pSinkObj3 = new CATLSimpleSinkObject3();

    // Connect the sink and source, m_spSrcObj is the source COM object
    hr = pSinkObj3->DispEventAdvise(spSimpleObj);
    _ASSERTE(SUCCEEDED(hr));


    // Invoke the source COM object
    {
        // Set FloatProperty which fires the event FloatPropertyChanging
        _tprintf(_T("Set FloatProperty = %.2f\n"), 1.3f);
        spSimpleObj->PutFloatProperty(1.3f);

        float fProp = spSimpleObj->GetFloatProperty();
        _tprintf(_T("Get FloatProperty = %.2f\n"), fProp);
    }


    // Disconnect from source if connected
    if (pSinkObj3->m_dwEventCookie != 0xFEFEFEFE)
        pSinkObj3->DispEventUnadvise(spSimpleObj);

    // Destroy the sink object
    delete pSinkObj3;


    /////////////////////////////////////////////////////////////////////////
    // Release the COM object.
    //

    // Make sure that the source COM object is release before CoUninitialize
    spSimpleObj.Release();

    // Uninitialize COM for this thread
    ::CoUninitialize();

    return 0;
}
예제 #26
0
파일: dbgprint.c 프로젝트: GYGit/reactos
int _tmain(int argc, TCHAR ** argv)
{
    TCHAR * buf;
    int bufsize;
    int i;
    int offset;

    bufsize = 0;
    for(i = 1; i < argc; i++)
    {
        bufsize += _tcslen(argv[i]) + 1;
    }

    if (!bufsize)
    {
        return -1;
    }

    if (_tcsstr(argv[1], "--winetest") && (argc == 3))
    {
        char   psBuffer[128];
        char   psBuffer2[128];
        char   *nlptr2;
        char   cmd[255];
        char   test[300];
        FILE   *pPipe;
        FILE   *pPipe2;

        /* get available tests */
        strcpy(cmd, argv[2]);
        strcat(cmd, " --list");        
        pPipe = _tpopen(cmd, "r");
        if (pPipe != NULL)
        {
            while(fgets(psBuffer, 128, pPipe))
            {
                if (psBuffer[0] == ' ')
                {
                    strcpy(cmd, argv[2]);
                    strcat(cmd, " ");
                    strcat(cmd, psBuffer+4);
                    /* run the current test */
                    strcpy(test, "\n\nRunning ");
                    strcat(test, cmd);
                    OutputDebugStringA(test);
                    pPipe2 = _popen(cmd, "r");
                    if (pPipe2 != NULL)
                    {
                        while(fgets(psBuffer2, 128, pPipe2))
                        {
                            nlptr2 = strchr(psBuffer2, '\n');
                            if (nlptr2)
                                *nlptr2 = '\0';
                            puts(psBuffer2);
                            OutputDebugStringA(psBuffer2);
                        }
                        _pclose(pPipe2);
                    }
                }
            }
            _pclose(pPipe);
        }
    }
    else if (_tcsstr(argv[1], "--process") && (argc == 3))
    {
        char   psBuffer[128];
        FILE   *pPipe;

        pPipe = _tpopen(argv[2], "r");
        if (pPipe != NULL)
        {
            while(fgets(psBuffer, 128, pPipe))
            {
                puts(psBuffer);
                OutputDebugStringA(psBuffer);
            }
            _pclose(pPipe);
        }
    }
    else
    {
        buf = HeapAlloc(GetProcessHeap(), 0, (bufsize+1) * sizeof(TCHAR));
        if (!buf)
        {
            return -1;
        }

        offset = 0;
        for(i = 1; i < argc; i++)
        {
            int length = _tcslen(argv[i]);
            _tcsncpy(&buf[offset], argv[i], length);
            offset += length;
            if (i + 1 < argc)
            {
                buf[offset] = _T(' ');
            }
            else
            {
                buf[offset] = _T('\n');
                buf[offset+1] = _T('\0');
            }
            offset++;
        }
        _putts(buf);
        OutputDebugString(buf);
        HeapFree(GetProcessHeap(), 0, buf);
    }
    return 0;
}
예제 #27
0
int _tmain(int argc, _TCHAR* argv[])
{
	_tsetlocale(LC_ALL, _T("")); // fixes VS11DP quirk

	// open csv file

	RCSVFileRO file;

	if (argc == 2)
	{
		if (!file.Open(CorrectPath(argv[1])))
			{_putts(_T("Unable to open file: ") + CorrectPath(argv[1])); PAUSERETURN(-1);}
	}
	else if (argc == 1)
	{
		if (!file.Open(CorrectPath(_T("strings.csv"))))
			{_putts(_T("Please supply the name of CSV-file.")); PAUSERETURN(-2);}
	}
	else
		{_putts(_T("Invalid argument count.")); PAUSERETURN(-3);}

	if (file.GetLineCount() == 0)
		{_putts(_T("Empty file.")); PAUSERETURN(1);}

	if (file.GetLineCount() < 2)
		{_putts(_T("File must contain at least two lines.")); PAUSERETURN(-4);}

	if (file.GetFieldCount() < 2)
		{_putts(_T("File must contain at least two columns.")); PAUSERETURN(-5);}

	// generate header file contents

	RString str;
	str += _T("// strings.h : Defines the strings to be used throughout the application.\r\n");
	str += _T("//\r\n");
	str += _T("\r\n");

	int n = 1000;
	
	int i, j;
	for (i = 1; i < file.GetLineCount(); i++)
		if (_tcscmp(file.GetField(i, 0), _T("")) != 0)
			str += RString(_T("#define ")) + file.GetField(i, 0) + _T(" ") + NumberToString(n++) + _T("\r\n");

	str += _T("\r\n");
	str += _T("inline void LoadStrings()\r\n");
	str += _T("{\r\n");
	str += _T("\tINT_PTR nLanguage;\r\n");

	for (i = 1; i < file.GetFieldCount(); i++)
	{
		str += _T("\r\n");
		str += (RString)_T("\tnLanguage = GetLangMgr()->GetLanguage(_T(\"") + file.GetField(0, i) + _T("\"));\r\n");
		str += (RString)_T("\tif (nLanguage == -1)\r\n");
		str += (RString)_T("\t\tnLanguage = GetLangMgr()->AddLanguage(_T(\"") + file.GetField(0, i) + _T("\"), _T(\"") + file.GetField(1, i)
				+ _T("\"), _T(\"\"));\r\n\r\n");

		for (j = 1; j < file.GetLineCount(); j++)
		{
			if (_tcscmp(file.GetField(j, 0), _T("")) == 0)
				continue; // skip empty ids

			str += (RString)_T("\tGetLangMgr()->SetString(nLanguage, ") + NumberToString(j-1) + _T(", _T(\"") +
					file.GetField(j, i) + _T("\"), false);\r\n");
		}
	}

	str += _T("}\r\n");

	// write to file

	RString strFilePath = CorrectPath(argc == 2 ? argv[1] : _T("strings.csv"));
	strFilePath = strFilePath.Left(strFilePath.ReverseFind(_T('\\'))+1) + _T("strings.h");

	RArray<BYTE> data = StringToData(str, CHARSET_ANSI);
	if (!DataToFile(data, strFilePath))
		{_tprintf(_T("Failed to open %s for writing.\n"), (LPCTSTR)strFilePath); PAUSERETURN(-6);}

	_tprintf(_T("Created %s succesfully.\n"), (LPCTSTR)strFilePath);

	PAUSERETURN(0);
}
예제 #28
0
파일: WlanHelper.cpp 프로젝트: nmap/npcap
int MainInteractive()
{
	HANDLE hClient = NULL;
	WLAN_INTERFACE_INFO sInfo[64];
	RPC_TSTR strGuid = NULL;

	TCHAR szBuffer[256];
	DWORD dwRead;
	if (OpenHandleAndCheckVersion(&hClient) != ERROR_SUCCESS)
	{
		_tsystem(_T("PAUSE"));
		return -1;
	}

	UINT nCount = EnumInterface(hClient, sInfo);
	for (UINT i = 0; i < nCount; ++i)
	{
		if (UuidToString(&sInfo[i].InterfaceGuid, &strGuid) == RPC_S_OK)
		{
			ULONG ulOperationMode = -1;
			PULONG pOperationMode;
			DWORD dwResult = GetInterface(wlan_intf_opcode_current_operation_mode, (PVOID*)&pOperationMode, &sInfo[i].InterfaceGuid);
			if (dwResult != ERROR_SUCCESS)
			{
				_tprintf(_T("GetInterface error, error code = %d\n"), dwResult);
				_tsystem(_T("PAUSE"));
			}
			else
			{
				ulOperationMode = *pOperationMode;
				WlanFreeMemory(pOperationMode);
			}

			_tprintf(_T("%d. %s\n\tName: %s\n\tDescription: %s\n\tState: %s\n\tOperation Mode: %s\n"),
				i,
				strGuid,
				getAdapterNameFromGuid((TCHAR*) strGuid).c_str(),
				sInfo[i].strInterfaceDescription,
				GetInterfaceStateString(sInfo[i].isState),
				GetInterfaceOperationModeString(ulOperationMode));

			RpcStringFree(&strGuid);
		}
	}

	UINT nChoice = 0;
	GUID ChoiceGUID;
	LPGUID pChoiceGUID = NULL;
	_tprintf(_T("Enter the choice (0, 1,..) of the wireless card you want to operate on:\n"));

	if (ReadConsole(GetStdHandle(STD_INPUT_HANDLE), szBuffer, _countof(szBuffer), &dwRead, NULL) == FALSE)
	{
		_putts(_T("Error input."));
		_tsystem(_T("PAUSE"));
		return -1;
	}
	szBuffer[dwRead] = 0;

	// TCHAR *aaa = _T("42dfd47a-2764-43ac-b58e-3df569c447da");
	// dwRead = sizeof(aaa);

	TCHAR buf[256];
	_stprintf_s(buf, 256, _T("{%s}"), szBuffer);

	if (dwRead > 32)
	{
		if (myGUIDFromString(buf, &ChoiceGUID) != TRUE)
		{
			_tprintf(_T("UuidFromString error, error code = %d\n"), -1);
			_tsystem(_T("PAUSE"));
		}
		else
		{
			pChoiceGUID = &ChoiceGUID;
		}
	}
	else
	{
		nChoice = _ttoi(szBuffer);

		if (nChoice > nCount)
		{
			_putts(_T("No such index."));
			_tsystem(_T("PAUSE"));
			return -1;
		}

		pChoiceGUID = &sInfo[nChoice].InterfaceGuid;
	}

	UINT nSTate = 0;
	ULONG ulOperationMode = -1;
	_tprintf(_T("Enter the operation mode (0, 1 or 2) you want to switch to for the chosen wireless card:\n"));
	_tprintf(_T("0: Extensible Station (ExtSTA)\n1: Network Monitor (NetMon)\n2: Extensible Access Point (ExtAP)\n"));

	if (ReadConsole(GetStdHandle(STD_INPUT_HANDLE), szBuffer, _countof(szBuffer), &dwRead, NULL) == FALSE)
	{
		_putts(_T("Error input."));
		_tsystem(_T("PAUSE"));
		return -1;
	}
	szBuffer[dwRead] = 0;
	nSTate = _ttoi(szBuffer);

	if (nSTate != 0 && nSTate != 1 && nSTate != 2)
	{
		_putts(_T("Only 0, 1 and 2 are valid inputs."));
		_tsystem(_T("PAUSE"));
		return -1;
	}
	if (nSTate == 0)
	{
		ulOperationMode = DOT11_OPERATION_MODE_EXTENSIBLE_STATION;
	}
	else if (nSTate == 1)
	{
		ulOperationMode = DOT11_OPERATION_MODE_NETWORK_MONITOR;
	}
	else // nSTate == 2
	{
		ulOperationMode = DOT11_OPERATION_MODE_EXTENSIBLE_AP;
	}

	DWORD dwResult = SetInterface(wlan_intf_opcode_current_operation_mode, (PVOID*)&ulOperationMode, pChoiceGUID);
	if (dwResult != ERROR_SUCCESS)
	{
		_tprintf(_T("SetInterface error, error code = %d\n"), dwResult);
		_tsystem(_T("PAUSE"));
	}
	else
	{
		_tprintf(_T("SetInterface success!\n"));
	}

	return 0;
}
예제 #29
0
파일: ansicon.c 프로젝트: voxik/ansicon
//int _tmain( int argc, TCHAR* argv[] )
int main( void )
{
  STARTUPINFO si;
  PROCESS_INFORMATION pi;
  TCHAR*  cmd;
  BOOL	  option;
  BOOL	  opt_m;
  BOOL	  installed;
  HMODULE ansi;
  int	  rc = 0;

  int argc;
  LPWSTR* argv = CommandLineToArgvW( GetCommandLineW(), &argc );

  if (argc > 1)
  {
    if (lstrcmp( argv[1], TEXT("--help") ) == 0 ||
	(argv[1][0] == '-' && (argv[1][1] == '?' || argv[1][1] == 'h')) ||
	(argv[1][0] == '/' && argv[1][1] == '?'))
    {
      help();
      return rc;
    }
    if (lstrcmp( argv[1], TEXT("--version") ) == 0)
    {
      _putts( TEXT("ANSICON (" BITS "-bit) version " PVERS " (" PDATE ").") );
      return rc;
    }
  }

  option = (argc > 1 && argv[1][0] == '-');
  if (option && (_totlower( argv[1][1] ) == 'i' ||
		 _totlower( argv[1][1] ) == 'u'))
  {
    process_autorun( argv[1][1] );
    return rc;
  }

  get_original_attr();

  opt_m = FALSE;
  if (option && argv[1][1] == 'm')
  {
    WORD attr = 7;
    if (_istxdigit( argv[1][2] ))
    {
      attr = _istdigit( argv[1][2] ) ? argv[1][2] - '0'
				     : (argv[1][2] | 0x20) - 'a' + 10;
      if (_istxdigit( argv[1][3]))
      {
	attr <<= 4;
	attr |= _istdigit( argv[1][3] ) ? argv[1][3] - '0'
					: (argv[1][3] | 0x20) - 'a' + 10;
      }
    }
    SetConsoleTextAttribute( hConOut, attr );

    opt_m = TRUE;
    ++argv;
    --argc;
    option = (argc > 1 && argv[1][0] == '-');
  }

  installed = (GetEnvironmentVariable( TEXT("ANSICON"), NULL, 0 ) != 0);

  if (option && argv[1][1] == 'p')
  {
    // If it's already installed, there's no need to do anything.
    if (installed)
      ;
    else if (GetParentProcessInfo( &pi ))
    {
      pi.hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, pi.dwProcessId );
      pi.hThread  = OpenThread(  THREAD_ALL_ACCESS,  FALSE, pi.dwThreadId  );
      SuspendThread( pi.hThread );
      Inject( &pi );
      ResumeThread( pi.hThread );
      CloseHandle( pi.hThread );
      CloseHandle( pi.hProcess );
    }
    else
    {
      _putts( TEXT("ANSICON: could not obtain the parent process.") );
      rc = 1;
    }
  }
  else
  {
    ansi = 0;
    if (!installed)
      ansi = LoadLibrary( TEXT("ANSI" BITS ".dll") );

    if (option && (argv[1][1] == 't' || argv[1][1] == 'T'))
    {
      BOOL title = (argv[1][1] == 'T');
      if (argc == 2)
      {
	argv[2] = L"-";
	++argc;
      }
      for (; argc > 2; ++argv, --argc)
      {
	if (title)
	  _tprintf( TEXT("==> %s <==\n"), argv[2] );
	display( argv[2], title );
	if (title)
	  _puttchar( '\n' );
      }
    }
    else
    {
      // Retrieve the original command line, skipping our name and the option.
      cmd = skip_spaces( skip_arg( skip_spaces( GetCommandLine() ) ) );
      if (opt_m)
	cmd = skip_spaces( skip_arg( cmd ) );

      if (cmd[0] == '-' && (cmd[1] == 'e' || cmd[1] == 'E'))
      {
	_fputts( cmd + 3, stdout );
	if (cmd[1] == 'e')
	  _puttchar( '\n' );
      }
      else if (!isatty( 0 ) && *cmd == '\0')
      {
	display( TEXT("-"), FALSE );
      }
      else
      {
	if (*cmd == '\0')
	{
	  cmd = _tgetenv( TEXT("ComSpec") );
	  if (cmd == NULL)
	    cmd = TEXT("cmd");
	}

	ZeroMemory( &si, sizeof(si) );
	si.cb = sizeof(si);
	if (CreateProcess( NULL, cmd, NULL,NULL, TRUE, 0, NULL,NULL, &si, &pi ))
	{
	  SetConsoleCtrlHandler( (PHANDLER_ROUTINE)CtrlHandler, TRUE );
	  WaitForSingleObject( pi.hProcess, INFINITE );
	}
	else
	{
	  *skip_arg( cmd ) = '\0';
	  _tprintf( TEXT("ANSICON: '%s' could not be executed.\n"), cmd );
	  rc = 1;
	}
      }
    }

    if (ansi)
      FreeLibrary( ansi );
  }

  set_original_attr();
  return rc;
}
예제 #30
0
int _tmain(int argc, _TCHAR* argv[])
{
	// we have three parameters
	const TCHAR* src = nullptr;
	const TCHAR* dst = nullptr;
	const TCHAR* wc = nullptr;
	BOOL bErrResursively = FALSE;
	BOOL bErrOnMods = FALSE;
	BOOL bErrOnUnversioned = FALSE;
	BOOL bQuiet = FALSE;
	GitWCRev_t GitStat;

	SetDllDirectory(L"");
	CCrashReportTGit crasher(L"GitWCRev " _T(APP_X64_STRING), TGIT_VERMAJOR, TGIT_VERMINOR, TGIT_VERMICRO, TGIT_VERBUILD, TGIT_VERDATE);

	if (argc >= 2 && argc <= 5)
	{
		// WC path is always first argument.
		wc = argv[1];
	}
	if (argc == 4 || argc == 5)
	{
		// GitWCRev Path Tmpl.in Tmpl.out [-params]
		src = argv[2];
		dst = argv[3];
		if (!PathFileExists(src))
		{
			_tprintf(L"File '%s' does not exist\n", src);
			return ERR_FNF; // file does not exist
		}
	}
	if (argc == 3 || argc == 5)
	{
		// GitWCRev Path -params
		// GitWCRev Path Tmpl.in Tmpl.out -params
		const TCHAR* Params = argv[argc - 1];
		if (Params[0] == L'-')
		{
			if (wcschr(Params, L'e') != 0)
				_setmode(_fileno(stdout), _O_U16TEXT);
			if (wcschr(Params, L'q') != 0)
				bQuiet = TRUE;
			if (wcschr(Params, L'm') != 0)
				bErrOnMods = TRUE;
			if (wcschr(Params, L'u') != 0)
				bErrOnUnversioned = TRUE;
			if (wcschr(Params, L'M') != 0)
			{
				bErrOnMods = TRUE;
				bErrResursively = TRUE;
			}
			if (wcschr(Params, L'U') != 0)
			{
				bErrOnUnversioned = TRUE;
				bErrResursively = TRUE;
			}
			if (wcschr(Params, L'd') != 0)
			{
				if (dst && PathFileExists(dst))
				{
					_tprintf(L"File '%s' already exists\n", dst);
					return ERR_OUT_EXISTS;
				}
			}
			if (wcschr(Params, L's') != 0)
				GitStat.bNoSubmodules = TRUE;
		}
		else
		{
			// Bad params - abort and display help.
			wc = nullptr;
		}
	}

	if (!wc)
	{
		_tprintf(L"GitWCRev %d.%d.%d, Build %d - %s\n\n", TGIT_VERMAJOR, TGIT_VERMINOR, TGIT_VERMICRO, TGIT_VERBUILD, _T(TGIT_PLATFORM));
		_putts(_T(HelpText1));
		_putts(_T(HelpText2));
		_putts(_T(HelpText3));
		_putts(_T(HelpText4));
		_putts(_T(HelpText5));
		return ERR_SYNTAX;
	}

	DWORD reqLen = GetFullPathName(wc, 0, nullptr, nullptr);
	auto wcfullPath = std::make_unique<TCHAR[]>(reqLen + 1);
	GetFullPathName(wc, reqLen, wcfullPath.get(), nullptr);
	// GetFullPathName() sometimes returns the full path with the wrong
	// case. This is not a problem on Windows since its filesystem is
	// case-insensitive. But for Git that's a problem if the wrong case
	// is inside a working copy: the git index is case sensitive.
	// To fix the casing of the path, we use a trick:
	// convert the path to its short form, then back to its long form.
	// That will fix the wrong casing of the path.
	int shortlen = GetShortPathName(wcfullPath.get(), nullptr, 0);
	if (shortlen)
	{
		auto shortPath = std::make_unique<TCHAR[]>(shortlen + 1);
		if (GetShortPathName(wcfullPath.get(), shortPath.get(), shortlen + 1))
		{
			reqLen = GetLongPathName(shortPath.get(), nullptr, 0);
			wcfullPath = std::make_unique<TCHAR[]>(reqLen + 1);
			GetLongPathName(shortPath.get(), wcfullPath.get(), reqLen);
		}
	}
	wc = wcfullPath.get();
	std::unique_ptr<TCHAR[]> dstfullPath;
	if (dst)
	{
		reqLen = GetFullPathName(dst, 0, nullptr, nullptr);
		dstfullPath = std::make_unique<TCHAR[]>(reqLen + 1);
		GetFullPathName(dst, reqLen, dstfullPath.get(), nullptr);
		shortlen = GetShortPathName(dstfullPath.get(), nullptr, 0);
		if (shortlen)
		{
			auto shortPath = std::make_unique<TCHAR[]>(shortlen + 1);
			if (GetShortPathName(dstfullPath.get(), shortPath.get(), shortlen+1))
			{
				reqLen = GetLongPathName(shortPath.get(), nullptr, 0);
				dstfullPath = std::make_unique<TCHAR[]>(reqLen + 1);
				GetLongPathName(shortPath.get(), dstfullPath.get(), reqLen);
			}
		}
		dst = dstfullPath.get();
	}
	std::unique_ptr<TCHAR[]> srcfullPath;
	if (src)
	{
		reqLen = GetFullPathName(src, 0, nullptr, nullptr);
		srcfullPath = std::make_unique<TCHAR[]>(reqLen + 1);
		GetFullPathName(src, reqLen, srcfullPath.get(), nullptr);
		shortlen = GetShortPathName(srcfullPath.get(), nullptr, 0);
		if (shortlen)
		{
			auto shortPath = std::make_unique<TCHAR[]>(shortlen + 1);
			if (GetShortPathName(srcfullPath.get(), shortPath.get(), shortlen+1))
			{
				reqLen = GetLongPathName(shortPath.get(), nullptr, 0);
				srcfullPath = std::make_unique<TCHAR[]>(reqLen + 1);
				GetLongPathName(shortPath.get(), srcfullPath.get(), reqLen);
			}
		}
		src = srcfullPath.get();
	}

	if (!PathFileExists(wc))
	{
		_tprintf(L"Directory or file '%s' does not exist\n", wc);
		if (wcschr(wc, '\"')) // dir contains a quotation mark
		{
			_tprintf(L"The WorkingCopyPath contains a quotation mark.\n");
			_tprintf(L"this indicates a problem when calling GitWCRev from an interpreter which treats\n");
			_tprintf(L"a backslash char specially.\n");
			_tprintf(L"Try using double backslashes or insert a dot after the last backslash when\n");
			_tprintf(L"calling GitWCRev\n");
			_tprintf(L"Examples:\n");
			_tprintf(L"GitWCRev \"path to wc\\\\\"\n");
			_tprintf(L"GitWCRev \"path to wc\\.\"\n");
		}
		return ERR_FNF; // dir does not exist
	}
	std::unique_ptr<char[]> pBuf;
	DWORD readlength = 0;
	size_t filelength = 0;
	size_t maxlength  = 0;
	if (dst)
	{
		// open the file and read the contents
		CAutoFile hFile = CreateFile(src, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, 0);
		if (!hFile)
		{
			_tprintf(L"Unable to open input file '%s'\n", src);
			return ERR_OPEN; // error opening file
		}
		filelength = GetFileSize(hFile, nullptr);
		if (filelength == INVALID_FILE_SIZE)
		{
			_tprintf(L"Could not determine file size of '%s'\n", src);
			return ERR_READ;
		}
		maxlength = filelength + 8192; // We might be increasing file size.
		pBuf = std::make_unique<char[]>(maxlength);
		if (!pBuf)
		{
			_tprintf(L"Could not allocate enough memory!\n");
			return ERR_ALLOC;
		}
		if (!ReadFile(hFile, pBuf.get(), (DWORD)filelength, &readlength, nullptr))
		{
			_tprintf(L"Could not read the file '%s'\n", src);
			return ERR_READ;
		}
		if (readlength != filelength)
		{
			_tprintf(L"Could not read the file '%s' to the end!\n", src);
			return ERR_READ;
		}
	}

	git_libgit2_init();

	// Now check the status of every file in the working copy
	// and gather revision status information in GitStat.
	int err = GetStatus(wc, GitStat);

	git_libgit2_shutdown();
	if (err)
		return err;

	if (!bQuiet)
	{
		char wcfull_oem[MAX_PATH] = { 0 };
		CharToOem(wc, wcfull_oem);
		_tprintf(L"GitWCRev: '%hs'\n", wcfull_oem);
	}

	if (bErrOnMods && (GitStat.HasMods || GitStat.bHasSubmoduleNewCommits || (bErrResursively && GitStat.bHasSubmoduleMods)))
	{
		if (!bQuiet)
			_tprintf(L"Working tree has uncomitted modifications!\n");
		return ERR_GIT_MODS;
	}
	if (bErrOnUnversioned && (GitStat.HasUnversioned || (bErrResursively && GitStat.bHasSubmoduleUnversioned)))
	{
		if (!bQuiet)
			_tprintf(L"Working tree has unversioned items!\n");
		return ERR_GIT_UNVER;
	}

	if (!bQuiet)
	{
		_tprintf(L"HEAD is %s\n", CUnicodeUtils::StdGetUnicode(GitStat.HeadHashReadable).c_str());

		if (GitStat.HasMods)
			_tprintf(L"Uncommitted modifications found\n");

		if (GitStat.HasUnversioned)
			_tprintf(L"Unversioned items found\n");
	}

	if (!dst)
		return 0;

	// now parse the file contents for version defines.
	size_t index = 0;
	while (InsertRevision(VERDEF, pBuf.get(), index, filelength, maxlength, &GitStat));
	index = 0;
	while (InsertRevisionW(TEXT(VERDEF), (wchar_t*)pBuf.get(), index, filelength, maxlength, &GitStat));

	index = 0;
	while (InsertRevision(VERDEFSHORT, pBuf.get(), index, filelength, maxlength, &GitStat));
	index = 0;
	while (InsertRevisionW(TEXT(VERDEFSHORT), (wchar_t*)pBuf.get(), index, filelength, maxlength, &GitStat));

	index = 0;
	while (InsertDate(DATEDEF, pBuf.get(), index, filelength, maxlength, GitStat.HeadTime));
	index = 0;
	while (InsertDateW(TEXT(DATEDEF), (wchar_t*)pBuf.get(), index, filelength, maxlength, GitStat.HeadTime));

	index = 0;
	while (InsertDate(DATEDEFUTC, pBuf.get(), index, filelength, maxlength, GitStat.HeadTime));
	index = 0;
	while (InsertDateW(TEXT(DATEDEFUTC), (wchar_t*)pBuf.get(), index, filelength, maxlength, GitStat.HeadTime));

	index = 0;
	while (InsertDate(DATEWFMTDEF, pBuf.get(), index, filelength, maxlength, GitStat.HeadTime));
	index = 0;
	while (InsertDateW(TEXT(DATEWFMTDEF), (wchar_t*)pBuf.get(), index, filelength, maxlength, GitStat.HeadTime));
	index = 0;
	while (InsertDate(DATEWFMTDEFUTC, pBuf.get(), index, filelength, maxlength, GitStat.HeadTime));
	index = 0;
	while (InsertDateW(TEXT(DATEWFMTDEFUTC), (wchar_t*)pBuf.get(), index, filelength, maxlength, GitStat.HeadTime));

	index = 0;
	while (InsertDate(NOWDEF, pBuf.get(), index, filelength, maxlength, USE_TIME_NOW));
	index = 0;
	while (InsertDateW(TEXT(NOWDEF), (wchar_t*)pBuf.get(), index, filelength, maxlength, USE_TIME_NOW));

	index = 0;
	while (InsertDate(NOWDEFUTC, pBuf.get(), index, filelength, maxlength, USE_TIME_NOW));
	index = 0;
	while (InsertDateW(TEXT(NOWDEFUTC), (wchar_t*)pBuf.get(), index, filelength, maxlength, USE_TIME_NOW));

	index = 0;
	while (InsertDate(NOWWFMTDEF, pBuf.get(), index, filelength, maxlength, USE_TIME_NOW));
	index = 0;
	while (InsertDateW(TEXT(NOWWFMTDEF), (wchar_t*)pBuf.get(), index, filelength, maxlength, USE_TIME_NOW));

	index = 0;
	while (InsertDate(NOWWFMTDEFUTC, pBuf.get(), index, filelength, maxlength, USE_TIME_NOW));
	index = 0;
	while (InsertDateW(TEXT(NOWWFMTDEFUTC), (wchar_t*)pBuf.get(), index, filelength, maxlength, USE_TIME_NOW));

	index = 0;
	while (InsertBoolean(MODDEF, pBuf.get(), index, filelength, GitStat.HasMods || GitStat.bHasSubmoduleNewCommits));
	index = 0;
	while (InsertBooleanW(TEXT(MODDEF), (wchar_t*)pBuf.get(), index, filelength, GitStat.HasMods || GitStat.bHasSubmoduleNewCommits));

	index = 0;
	while (InsertBoolean(UNVERDEF, pBuf.get(), index, filelength, GitStat.HasUnversioned));
	index = 0;
	while (InsertBooleanW(TEXT(UNVERDEF), (wchar_t*)pBuf.get(), index, filelength, GitStat.HasUnversioned));

	index = 0;
	while (InsertBoolean(ISTAGGED, pBuf.get(), index, filelength, GitStat.bIsTagged));
	index = 0;
	while (InsertBooleanW(TEXT(ISTAGGED), (wchar_t*)pBuf.get(), index, filelength, GitStat.bIsTagged));

	index = 0;
	while (InsertBoolean(ISINGIT, pBuf.get(), index, filelength, GitStat.bIsGitItem));
	index = 0;
	while (InsertBooleanW(TEXT(ISINGIT), (wchar_t*)pBuf.get(), index, filelength, GitStat.bIsGitItem));

	index = 0;
	while (InsertBoolean(SUBDEF, pBuf.get(), index, filelength, GitStat.bHasSubmodule));
	index = 0;
	while (InsertBooleanW(TEXT(SUBDEF), (wchar_t*)pBuf.get(), index, filelength, GitStat.bHasSubmodule));

	index = 0;
	while (InsertBoolean(SUBUP2DATEDEF, pBuf.get(), index, filelength, !GitStat.bHasSubmoduleNewCommits));
	index = 0;
	while (InsertBooleanW(TEXT(SUBUP2DATEDEF), (wchar_t*)pBuf.get(), index, filelength, !GitStat.bHasSubmoduleNewCommits));

	index = 0;
	while (InsertBoolean(MODINSUBDEF, pBuf.get(), index, filelength, GitStat.bHasSubmoduleMods));
	index = 0;
	while (InsertBooleanW(TEXT(MODINSUBDEF), (wchar_t*)pBuf.get(), index, filelength, GitStat.bHasSubmoduleMods));

	index = 0;
	while (InsertBoolean(UNVERINSUBDEF, pBuf.get(), index, filelength, GitStat.bHasSubmoduleUnversioned));
	index = 0;
	while (InsertBooleanW(TEXT(UNVERINSUBDEF), (wchar_t*)pBuf.get(), index, filelength, GitStat.bHasSubmoduleUnversioned));

	index = 0;
	while (InsertBoolean(UNVERFULLDEF, pBuf.get(), index, filelength, GitStat.HasUnversioned || GitStat.bHasSubmoduleUnversioned));
	index = 0;
	while (InsertBooleanW(TEXT(UNVERFULLDEF), (wchar_t*)pBuf.get(), index, filelength, GitStat.HasUnversioned || GitStat.bHasSubmoduleUnversioned));

	index = 0;
	while (InsertBoolean(MODFULLDEF, pBuf.get(), index, filelength, GitStat.HasMods || GitStat.bHasSubmoduleMods || GitStat.bHasSubmoduleUnversioned));
	index = 0;
	while (InsertBooleanW(TEXT(MODFULLDEF), (wchar_t*)pBuf.get(), index, filelength, GitStat.HasMods || GitStat.bHasSubmoduleMods || GitStat.bHasSubmoduleUnversioned));

	index = 0;
	while (InsertBoolean(MODSFILEDEF, pBuf.get(), index, filelength, GitStat.HasMods));
	index = 0;
	while (InsertBooleanW(TEXT(MODSFILEDEF), (wchar_t*)pBuf.get(), index, filelength, GitStat.HasMods));

	index = 0;
	while (InsertNumber(VALDEF, pBuf.get(), index, filelength, maxlength, GitStat.NumCommits));
	index = 0;
	while (InsertNumberW(TEXT(VALDEF), (wchar_t*)pBuf.get(), index, filelength, maxlength, GitStat.NumCommits));

	index = 0;
	while (InsertNumber(VALDEFAND, pBuf.get(), index, filelength, maxlength, GitStat.NumCommits));
	index = 0;
	while (InsertNumberW(TEXT(VALDEFAND), (wchar_t*)pBuf.get(), index, filelength, maxlength, GitStat.NumCommits));

	index = 0;
	while (InsertNumber(VALDEFOFFSET1, pBuf.get(), index, filelength, maxlength, GitStat.NumCommits));
	index = 0;
	while (InsertNumberW(TEXT(VALDEFOFFSET1), (wchar_t*)pBuf.get(), index, filelength, maxlength, GitStat.NumCommits));

	index = 0;
	while (InsertNumber(VALDEFOFFSET2, pBuf.get(), index, filelength, maxlength, GitStat.NumCommits));
	index = 0;
	while (InsertNumberW(TEXT(VALDEFOFFSET2), (wchar_t*)pBuf.get(), index, filelength, maxlength, GitStat.NumCommits));

	index = 0;
	while (InsertText(BRANCHDEF, pBuf.get(), index, filelength, maxlength, GitStat.CurrentBranch));
	index = 0;
	while (InsertTextW(TEXT(BRANCHDEF), (wchar_t*)pBuf.get(), index, filelength, maxlength, GitStat.CurrentBranch));

	CAutoFile hFile = CreateFile(dst, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_ALWAYS, 0, 0);
	if (!hFile)
	{
		_tprintf(L"Unable to open output file '%s' for writing\n", dst);
		return ERR_OPEN;
	}

	size_t filelengthExisting = GetFileSize(hFile, nullptr);
	BOOL sameFileContent = FALSE;
	if (filelength == filelengthExisting)
	{
		DWORD readlengthExisting = 0;
		auto pBufExisting = std::make_unique<char[]>(filelength);
		if (!ReadFile(hFile, pBufExisting.get(), (DWORD)filelengthExisting, &readlengthExisting, nullptr))
		{
			_tprintf(L"Could not read the file '%s'\n", dst);
			return ERR_READ;
		}
		if (readlengthExisting != filelengthExisting)
		{
			_tprintf(L"Could not read the file '%s' to the end!\n", dst);
			return ERR_READ;
		}
		sameFileContent = (memcmp(pBuf.get(), pBufExisting.get(), filelength) == 0);
	}

	// The file is only written if its contents would change.
	// this object prevents the timestamp from changing.
	if (!sameFileContent)
	{
		SetFilePointer(hFile, 0, nullptr, FILE_BEGIN);

		WriteFile(hFile, pBuf.get(), (DWORD)filelength, &readlength, nullptr);
		if (readlength != filelength)
		{
			_tprintf(L"Could not write the file '%s' to the end!\n", dst);
			return ERR_READ;
		}

		if (!SetEndOfFile(hFile))
		{
			_tprintf(L"Could not truncate the file '%s' to the end!\n", dst);
			return ERR_READ;
		}
	}

	return 0;
}