/* main - open file system, list inode info */ int main(int argc, char **argv1) { TSK_IMG_TYPE_ENUM imgtype = TSK_IMG_TYPE_DETECT; TSK_IMG_INFO *img; TSK_OFF_T imgaddr = 0; TSK_FS_TYPE_ENUM fstype = TSK_FS_TYPE_DETECT; TSK_FS_INFO *fs; TSK_TCHAR *cp, *dash; TSK_INUM_T istart = 0, ilast = 0; int ch; int flags = TSK_FS_META_FLAG_UNALLOC | TSK_FS_META_FLAG_USED; int ils_flags = 0; int set_range = 1; TSK_TCHAR *image = NULL; int32_t sec_skew = 0; TSK_TCHAR **argv; unsigned int ssize = 0; #ifdef TSK_WIN32 // On Windows, get the wide arguments (mingw doesn't support wmain) argv = CommandLineToArgvW(GetCommandLineW(), &argc); if (argv == NULL) { fprintf(stderr, "Error getting wide arguments\n"); exit(1); } #else argv = (TSK_TCHAR **) argv1; #endif progname = argv[0]; setlocale(LC_ALL, ""); /* * Provide convenience options for the most commonly selected feature * combinations. */ while ((ch = GETOPT(argc, argv, _TSK_T("aAb:ef:i:lLmo:Oprs:vVzZ"))) > 0) { switch (ch) { case _TSK_T('?'): default: TFPRINTF(stderr, _TSK_T("Invalid argument: %s\n"), argv[OPTIND]); usage(); case _TSK_T('b'): ssize = (unsigned int) TSTRTOUL(OPTARG, &cp, 0); if (*cp || *cp == *OPTARG || ssize < 1) { TFPRINTF(stderr, _TSK_T ("invalid argument: sector size must be positive: %s\n"), OPTARG); usage(); } break; case _TSK_T('f'): if (TSTRCMP(OPTARG, _TSK_T("list")) == 0) { tsk_fs_type_print(stderr); exit(1); } fstype = tsk_fs_type_toid(OPTARG); if (fstype == TSK_FS_TYPE_UNSUPP) { TFPRINTF(stderr, _TSK_T("Unsupported file system type: %s\n"), OPTARG); usage(); } break; case _TSK_T('i'): if (TSTRCMP(OPTARG, _TSK_T("list")) == 0) { tsk_img_type_print(stderr); exit(1); } imgtype = tsk_img_type_toid(OPTARG); if (imgtype == TSK_IMG_TYPE_UNSUPP) { TFPRINTF(stderr, _TSK_T("Unsupported image type: %s\n"), OPTARG); usage(); } break; case _TSK_T('e'): flags |= (TSK_FS_META_FLAG_ALLOC | TSK_FS_META_FLAG_UNALLOC); flags &= ~TSK_FS_META_FLAG_USED; break; case _TSK_T('m'): ils_flags |= TSK_FS_ILS_MAC; break; case _TSK_T('o'): if ((imgaddr = tsk_parse_offset(OPTARG)) == -1) { tsk_error_print(stderr); exit(1); } break; case _TSK_T('O'): flags |= TSK_FS_META_FLAG_UNALLOC; flags &= ~TSK_FS_META_FLAG_ALLOC; ils_flags |= TSK_FS_ILS_OPEN; break; case _TSK_T('p'): flags |= (TSK_FS_META_FLAG_ORPHAN | TSK_FS_META_FLAG_UNALLOC); flags &= ~TSK_FS_META_FLAG_ALLOC; break; case _TSK_T('r'): flags |= (TSK_FS_META_FLAG_UNALLOC | TSK_FS_META_FLAG_USED); flags &= ~TSK_FS_META_FLAG_ALLOC; break; case _TSK_T('s'): sec_skew = TATOI(OPTARG); break; case _TSK_T('v'): tsk_verbose++; break; case _TSK_T('V'): tsk_version_print(stdout); exit(0); /* * Provide fine controls to tweak one feature at a time. */ case _TSK_T('a'): flags |= TSK_FS_META_FLAG_ALLOC; flags &= ~TSK_FS_META_FLAG_UNALLOC; break; case _TSK_T('A'): flags |= TSK_FS_META_FLAG_UNALLOC; break; case _TSK_T('l'): ils_flags |= TSK_FS_ILS_LINK; break; case _TSK_T('L'): ils_flags |= TSK_FS_ILS_UNLINK; break; case _TSK_T('z'): flags |= TSK_FS_META_FLAG_UNUSED; break; case _TSK_T('Z'): flags |= TSK_FS_META_FLAG_USED; break; } } if (OPTIND >= argc) { tsk_fprintf(stderr, "Missing image name\n"); usage(); } if ((ils_flags & TSK_FS_ILS_LINK) && (ils_flags & TSK_FS_ILS_UNLINK)) { tsk_fprintf(stderr, "ERROR: Only linked or unlinked should be used\n"); usage(); } /* We need to determine if an inode or inode range was given */ if ((dash = TSTRCHR(argv[argc - 1], _TSK_T('-'))) == NULL) { /* Check if is a single number */ istart = TSTRTOULL(argv[argc - 1], &cp, 0); if (*cp || *cp == *argv[argc - 1]) { /* Not a number - consider it a file name */ image = argv[OPTIND]; if ((img = tsk_img_open(argc - OPTIND, &argv[OPTIND], imgtype, ssize)) == NULL) { tsk_error_print(stderr); exit(1); } if ((imgaddr * img->sector_size) >= img->size) { tsk_fprintf(stderr, "Sector offset supplied is larger than disk image (maximum: %" PRIu64 ")\n", img->size / img->sector_size); exit(1); } } else { /* Single address set end addr to start */ ilast = istart; set_range = 0; image = argv[OPTIND]; if ((img = tsk_img_open(argc - OPTIND - 1, &argv[OPTIND], imgtype, ssize)) == NULL) { tsk_error_print(stderr); exit(1); } if ((imgaddr * img->sector_size) >= img->size) { tsk_fprintf(stderr, "Sector offset supplied is larger than disk image (maximum: %" PRIu64 ")\n", img->size / img->sector_size); exit(1); } } } else { /* We have a dash, but it could be part of the file name */ *dash = '\0'; istart = TSTRTOULL(argv[argc - 1], &cp, 0); if (*cp || *cp == *argv[argc - 1]) { /* Not a number - consider it a file name */ *dash = _TSK_T('-'); image = argv[OPTIND]; if ((img = tsk_img_open(argc - OPTIND, &argv[OPTIND], imgtype, ssize)) == NULL) { tsk_error_print(stderr); exit(1); } if ((imgaddr * img->sector_size) >= img->size) { tsk_fprintf(stderr, "Sector offset supplied is larger than disk image (maximum: %" PRIu64 ")\n", img->size / img->sector_size); exit(1); } } else { dash++; ilast = TSTRTOULL(dash, &cp, 0); if (*cp || *cp == *dash) { /* Not a number - consider it a file name */ dash--; *dash = '-'; image = argv[OPTIND]; if ((img = tsk_img_open(argc - OPTIND, &argv[OPTIND], imgtype, ssize)) == NULL) { tsk_error_print(stderr); exit(1); } if ((imgaddr * img->sector_size) >= img->size) { tsk_fprintf(stderr, "Sector offset supplied is larger than disk image (maximum: %" PRIu64 ")\n", img->size / img->sector_size); exit(1); } } else { set_range = 0; /* It was a block range, so do not include it in the open */ image = argv[OPTIND]; if ((img = tsk_img_open(argc - OPTIND - 1, &argv[OPTIND], imgtype, ssize)) == NULL) { tsk_error_print(stderr); exit(1); } if ((imgaddr * img->sector_size) >= img->size) { tsk_fprintf(stderr, "Sector offset supplied is larger than disk image (maximum: %" PRIu64 ")\n", img->size / img->sector_size); exit(1); } } } } if ((fs = tsk_fs_open_img(img, imgaddr * img->sector_size, fstype)) == NULL) { tsk_error_print(stderr); if (tsk_error_get_errno() == TSK_ERR_FS_UNSUPTYPE) tsk_fs_type_print(stderr); img->close(img); exit(1); } /* do we need to set the range or just check them? */ if (set_range) { istart = fs->first_inum; ilast = fs->last_inum; } else { if (istart < fs->first_inum) { istart = fs->first_inum; } if (ilast > fs->last_inum) { ilast = fs->last_inum; } } /* NTFS uses alloc and link different than UNIX so change * the default behavior * * The link value can be > 0 on deleted files (even when closed) */ /* NTFS and FAT have no notion of deleted but still open */ if ((ils_flags & TSK_FS_ILS_OPEN) && (TSK_FS_TYPE_ISNTFS(fs->ftype) || TSK_FS_TYPE_ISFAT(fs->ftype))) { fprintf(stderr, "Error: '-O' argument does not work with NTFS and FAT images\n"); exit(1); } if (tsk_fs_ils(fs, (TSK_FS_ILS_FLAG_ENUM) ils_flags, istart, ilast, (TSK_FS_META_FLAG_ENUM) flags, sec_skew, image)) { tsk_error_print(stderr); fs->close(fs); img->close(img); exit(1); } fs->close(fs); img->close(img); exit(0); }
//----------------------------------------------------------------------------- // Name: WinMain() // Desc: The application's entry point //----------------------------------------------------------------------------- INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR commandLine, INT ) { //this can't be set from CAdvancedSettings::Initialize() because it will overwrite //the loglevel set with the --debug flag #ifdef _DEBUG g_advancedSettings.m_logLevel = LOG_LEVEL_DEBUG; g_advancedSettings.m_logLevelHint = LOG_LEVEL_DEBUG; #else g_advancedSettings.m_logLevel = LOG_LEVEL_NORMAL; g_advancedSettings.m_logLevelHint = LOG_LEVEL_NORMAL; #endif // Initializes CreateMiniDump to handle exceptions. SetUnhandledExceptionFilter( CreateMiniDump ); // check if XBMC is already running CreateMutex(NULL, FALSE, "XBMC Media Center"); if(GetLastError() == ERROR_ALREADY_EXISTS) { HWND m_hwnd = FindWindow("XBMC","XBMC"); if(m_hwnd != NULL) { // switch to the running instance ShowWindow(m_hwnd,SW_RESTORE); SetForegroundWindow(m_hwnd); } return 0; } #ifndef HAS_DX if(CWIN32Util::GetDesktopColorDepth() < 32) { //FIXME: replace it by a SDL window for all ports MessageBox(NULL, "Desktop Color Depth isn't 32Bit", "XBMC: Fatal Error", MB_OK|MB_ICONERROR); return 0; } #endif //Initialize COM CoInitializeEx(NULL, COINIT_MULTITHREADED); // parse the command line CStdStringW strcl(commandLine); LPWSTR *szArglist; int nArgs; setlocale(LC_NUMERIC, "C"); g_advancedSettings.Initialize(); szArglist = CommandLineToArgvW(strcl.c_str(), &nArgs); if(szArglist != NULL) { for(int i=0;i<nArgs;i++) { CStdStringW strArgW(szArglist[i]); if(strArgW.Equals(L"-fs")) g_advancedSettings.m_startFullScreen = true; else if(strArgW.Equals(L"-p") || strArgW.Equals(L"--portable")) g_application.EnablePlatformDirectories(false); else if(strArgW.Equals(L"-d")) { if(++i < nArgs) { int iSleep = _wtoi(szArglist[i]); if(iSleep > 0 && iSleep < 360) Sleep(iSleep*1000); else --i; } } else if(strArgW.Equals(L"--debug")) { g_advancedSettings.m_logLevel = LOG_LEVEL_DEBUG; g_advancedSettings.m_logLevelHint = LOG_LEVEL_DEBUG; } } LocalFree(szArglist); } WSADATA wd; WSAStartup(MAKEWORD(2,2), &wd); // Create and run the app if(!g_application.Create()) { CStdString errorMsg; errorMsg.Format("CApplication::Create() failed - check log file and that it is writable"); MessageBox(NULL, errorMsg.c_str(), "XBMC: Error", MB_OK|MB_ICONERROR); return 0; } #ifndef _DEBUG // we don't want to see the "no disc in drive" windows message box SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOOPENFILEERRORBOX); #endif g_application.Run(); // put everything in CApplication::Cleanup() since this point is never reached return 0; }
#ifndef WITH_PYTHON_MODULE bArgs *ba; #endif #ifdef WIN32 /* FMA3 support in the 2013 CRT is broken on Vista and Windows 7 RTM (fixed in SP1). Just disable it. */ # if defined(_MSC_VER) && _MSC_VER >= 1800 && defined(_M_X64) _set_FMA3_enable(0); # endif /* Win32 Unicode Args */ /* NOTE: cannot use guardedalloc malloc here, as it's not yet initialized * (it depends on the args passed in, which is what we're getting here!) */ wchar_t **argv_16 = CommandLineToArgvW(GetCommandLineW(), &argc); char **argv = malloc(argc * sizeof(char *)); int argci = 0; for (argci = 0; argci < argc; argci++) { argv[argci] = alloc_utf_8_from_16(argv_16[argci], 0); } LocalFree(argv_16); #endif /* NOTE: Special exception for guarded allocator type switch: * we need to perform switch from lock-free to fully * guarded allocator before any allocation happened. */ {
int WINAPI WinMain (HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int argc; WCHAR** argv; DWORD dwSize; HWND hMainWnd; MSG msg; WNDCLASSEXW wincl; HINSTANCE hDLL; PGFRI GetFontResourceInfoW; LPCWSTR fileName; switch (GetUserDefaultUILanguage()) { case MAKELANGID(LANG_HEBREW, SUBLANG_DEFAULT): SetProcessDefaultLayout(LAYOUT_RTL); break; default: break; } g_hInstance = hThisInstance; /* Get unicode command line */ argv = CommandLineToArgvW(GetCommandLineW(), &argc); if (argc < 2) { OPENFILENAMEW fontOpen; WCHAR szFileName[MAX_PATH] = L""; HLOCAL dialogTitle = NULL; /* Gets the title for the dialog box ready */ FormatString(FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, IDS_OPEN, 0, (LPWSTR)&dialogTitle, 0, NULL); /* Clears out any values of fontOpen before we use it */ ZeroMemory(&fontOpen, sizeof(fontOpen)); /* Sets up the open dialog box */ fontOpen.lStructSize = sizeof(fontOpen); fontOpen.hwndOwner = NULL; fontOpen.lpstrFilter = L"TrueType Font (*.ttf)\0*.ttf\0" L"All Files (*.*)\0*.*\0"; fontOpen.lpstrFile = szFileName; fontOpen.lpstrTitle = dialogTitle; fontOpen.nMaxFile = MAX_PATH; fontOpen.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; fontOpen.lpstrDefExt = L"ttf"; /* Opens up the Open File dialog box in order to chose a font file. */ if(GetOpenFileNameW(&fontOpen)) { fileName = fontOpen.lpstrFile; g_fileName = fileName; } else { /* If the user decides to close out of the open dialog effectively exiting the program altogether */ return 0; } LocalFree(dialogTitle); } else { /* Try to add the font resource from command line */ fileName = argv[1]; g_fileName = fileName; } if (!AddFontResourceW(fileName)) { ErrorMsgBox(0, IDS_ERROR, IDS_ERROR_NOFONT, fileName); return -1; } /* Load the GetFontResourceInfo function from gdi32.dll */ hDLL = LoadLibraryW(L"GDI32.DLL"); GetFontResourceInfoW = (PGFRI)GetProcAddress(hDLL, "GetFontResourceInfoW"); /* Get the font name */ dwSize = sizeof(g_ExtLogFontW.elfFullName); if (!GetFontResourceInfoW(fileName, &dwSize, g_ExtLogFontW.elfFullName, 1)) { ErrorMsgBox(0, IDS_ERROR, IDS_ERROR_NOFONT, fileName); return -1; } dwSize = sizeof(LOGFONTW); if (!GetFontResourceInfoW(fileName, &dwSize, &g_ExtLogFontW.elfLogFont, 2)) { ErrorMsgBox(0, IDS_ERROR, IDS_ERROR_NOFONT, fileName); return -1; } if (!Display_InitClass(hThisInstance)) { ErrorMsgBox(0, IDS_ERROR, IDS_ERROR_NOCLASS); return -1; } /* The main window class */ wincl.cbSize = sizeof (WNDCLASSEXW); wincl.style = CS_DBLCLKS; wincl.lpfnWndProc = MainWndProc; wincl.cbClsExtra = 0; wincl.cbWndExtra = 0; wincl.hInstance = hThisInstance; wincl.hIcon = LoadIcon (GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_TT)); wincl.hCursor = LoadCursor (NULL, IDC_ARROW); wincl.hbrBackground = (HBRUSH)COLOR_BACKGROUND; wincl.lpszMenuName = NULL; wincl.lpszClassName = g_szFontViewClassName; wincl.hIconSm = LoadIcon (GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_TT)); /* Register the window class, and if it fails quit the program */ if (!RegisterClassExW (&wincl)) { ErrorMsgBox(0, IDS_ERROR, IDS_ERROR_NOCLASS); return 0; } /* The class is registered, let's create the main window */ hMainWnd = CreateWindowExW( 0, /* Extended possibilites for variation */ g_szFontViewClassName, /* Classname */ g_ExtLogFontW.elfFullName,/* Title Text */ WS_OVERLAPPEDWINDOW, /* default window */ CW_USEDEFAULT, /* Windows decides the position */ CW_USEDEFAULT, /* where the window ends up on the screen */ 544, /* The programs width */ 375, /* and height in pixels */ HWND_DESKTOP, /* The window is a child-window to desktop */ NULL, /* No menu */ hThisInstance, /* Program Instance handler */ NULL /* No Window Creation data */ ); ShowWindow(hMainWnd, nCmdShow); /* Main message loop */ while (GetMessage (&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } RemoveFontResourceW(argv[1]); return (int)msg.wParam; }
/** * Parse command line arguments. * * @param cmd_line structure to store parsed options data */ static void parse_cmdline_options(struct parsed_cmd_line_t* cmd_line) { int argc; int n_files = 0, b_opt_end = 0; rsh_tchar** files; rsh_tchar **parg, **end_arg; parsed_option_t *next_opt; #ifdef _WIN32 parg = cmd_line->warg = CommandLineToArgvW(GetCommandLineW(), &argc); if( NULL == parg || argc < 1) { die(_("CommandLineToArgvW failed\n")); } #else argc = cmd_line->argc; parg = cmd_line->argv; #endif /* allocate array for files */ files = (rsh_tchar**)rsh_malloc(argc * sizeof(rsh_tchar*)); end_arg = parg + argc; /* loop by program arguments */ for(parg++; parg < end_arg; parg++) { /* if argument is not an option */ if((*parg)[0] != RSH_T('-') || (*parg)[1] == 0 || b_opt_end) { /* it's a file, note that '-' is interpreted as stdin */ files[n_files++] = *parg; continue; } assert((*parg)[0] == RSH_T('-') && (*parg)[1] != 0); if((*parg)[1] == L'-' && (*parg)[2] == 0) { b_opt_end = 1; /* string "--" means end of options */ continue; } /* check for "--" */ if((*parg)[1] == RSH_T('-')) { cmdline_opt_t *t; /* allocate parsed_option */ rsh_blocks_vector_add_empty(&cmd_line->options, 16, sizeof(parsed_option_t)); next_opt = rsh_blocks_vector_get_item(&cmd_line->options, cmd_line->options.size - 1, 16, parsed_option_t); /* find the long option */ parse_long_option(next_opt, &parg); t = next_opt->o; /* process encoding and -o/-l options early */ if(is_output_modifier(t->type)) { apply_option(&opt, next_opt); } } else if((*parg)[1] != 0) { /* found '-'<some string> */ rsh_tchar* ptr; /* parse short options. A string of several characters is interpreted * as separate short options */ for(ptr = *parg + 1; *ptr; ptr++) { cmdline_opt_t *t; char ch = (char)*ptr; #ifdef _WIN32 if(((unsigned)*ptr) >= 128) { ptr[1] = 0; fail_on_unknow_option(w2c(ptr)); } #endif /* allocate parsed_option */ rsh_blocks_vector_add_empty(&cmd_line->options, 16, sizeof(parsed_option_t)); next_opt = rsh_blocks_vector_get_item(&cmd_line->options, cmd_line->options.size - 1, 16, parsed_option_t); next_opt->buf[0] = '-', next_opt->buf[1] = ch, next_opt->buf[2] = '\0'; next_opt->name = next_opt->buf; next_opt->parameter = NULL; /* search for the short option */ for(t = cmdline_opt; t->type && ch != t->short1 && ch != t->short2; t++); if(!t->type) fail_on_unknow_option(next_opt->buf); next_opt->o = t; if(is_param_required(t->type)) { next_opt->parameter = (ptr[1] ? ptr + 1 : *(++parg)); if(!next_opt->parameter) { /* note: need to check for parameter here, for early -o/-l options processing */ log_error(_("argument is required for option %s\n"), next_opt->name); rsh_exit(2); } } /* process encoding and -o/-l options early */ if(is_output_modifier(t->type)) { apply_option(&opt, next_opt); } if(next_opt->parameter) break; /* a parameter ends the short options string */ } } } /* for */ cmd_line->n_files = n_files; cmd_line->files = files; }
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nShowCmd) { LPWSTR pCommandLineW = GetCommandLineW(); int retVal = 0; DWORD id = 0; int numArgs = 0; bool safe = false; #ifdef _WIN64 const wchar_t pDLLName[] = L"GraphicsCaptureHook64.dll"; #else const wchar_t pDLLName[] = L"GraphicsCaptureHook.dll"; #endif /* -------------------------- */ LPWSTR *pCommandLineArgs = CommandLineToArgvW(pCommandLineW, &numArgs); LoadSeDebugPrivilege(); if (numArgs > 2) { safe = *pCommandLineArgs[2] == '1'; id = wcstoul(pCommandLineArgs[1], NULL, 10); if (id != 0) { if (!safe) { OPPROC pOpenProcess; HANDLE hProcess; char pOPStr[12]; int i; memcpy(pOPStr, "NpflUvhel{x", 12); //OpenProcess obfuscated for (i = 0; i<11; i++) pOPStr[i] ^= i ^ 1; pOpenProcess = (OPPROC)GetProcAddress(GetModuleHandle(TEXT("KERNEL32")), pOPStr); hProcess = (*pOpenProcess)(PROCESS_ALL_ACCESS, FALSE, id); if (hProcess) { UINT dirLen = GetCurrentDirectory(0, 0); /* includes null terminator */ const UINT fileNameLen = (sizeof(pDLLName) / sizeof(wchar_t)) - 1; UINT len = dirLen + fileNameLen + 1; /* 1 for '/' */ wchar_t *pPath; /* -------------------------- */ if (dirLen) { pPath = (wchar_t*)malloc(len * sizeof(wchar_t)); memset(pPath, 0, len * sizeof(wchar_t)); GetCurrentDirectoryW(dirLen, pPath); pPath[dirLen - 1] = '\\'; wcsncpy_s(pPath + dirLen, len - dirLen, pDLLName, fileNameLen); if (!InjectLibrary(hProcess, pPath, len - 1)) { retVal = GetLastError(); if (!retVal) retVal = -5; } free(pPath); } else retVal = -4; CloseHandle(hProcess); } else retVal = -3; } else { UINT dirLen = GetCurrentDirectory(0, 0); /* includes null terminator */ const UINT fileNameLen = (sizeof(pDLLName) / sizeof(wchar_t)) - 1; UINT len = dirLen + fileNameLen + 1; /* 1 for '/' */ wchar_t *pPath; /* -------------------------- */ if (dirLen) { pPath = (wchar_t*)malloc(len * sizeof(wchar_t)); memset(pPath, 0, len * sizeof(wchar_t)); GetCurrentDirectoryW(dirLen, pPath); pPath[dirLen - 1] = '\\'; wcsncpy_s(pPath + dirLen, len - dirLen, pDLLName, fileNameLen); if (!InjectLibrarySafe(id, pPath, len - 1)) { retVal = GetLastError(); if (!retVal) retVal = -7; } free(pPath); } else retVal = -6; } } else retVal = -2; } else retVal = -1; LocalFree(pCommandLineArgs); return retVal; }
int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE prevInstance, LPWSTR cmdParamarg, int cmdShow) { openLog(); _oldWndExceptionFilter = SetUnhandledExceptionFilter(_exceptionFilter); // CAPIHook apiHook("kernel32.dll", "SetUnhandledExceptionFilter", (PROC)RedirectedSetUnhandledExceptionFilter); writeLog(L"Updaters started.."); LPWSTR *args; int argsCount; bool needupdate = false, autostart = false, debug = false, writeprotected = false, startintray = false, testmode = false, externalupdater = false; args = CommandLineToArgvW(GetCommandLine(), &argsCount); if (args) { for (int i = 1; i < argsCount; ++i) { writeLog(std::wstring(L"Argument: ") + args[i]); if (equal(args[i], L"-update")) { needupdate = true; } else if (equal(args[i], L"-autostart")) { autostart = true; } else if (equal(args[i], L"-debug")) { debug = _debug = true; openLog(); } else if (equal(args[i], L"-startintray")) { startintray = true; } else if (equal(args[i], L"-testmode")) { testmode = true; } else if (equal(args[i], L"-externalupdater")) { externalupdater = true; } else if (equal(args[i], L"-writeprotected") && ++i < argsCount) { writeLog(std::wstring(L"Argument: ") + args[i]); writeprotected = true; updateTo = args[i]; for (int j = 0, l = updateTo.size(); j < l; ++j) { if (updateTo[j] == L'/') { updateTo[j] = L'\\'; } } } else if (equal(args[i], L"-workdir") && ++i < argsCount) { writeLog(std::wstring(L"Argument: ") + args[i]); customWorkingDir = args[i]; } else if (equal(args[i], L"-key") && ++i < argsCount) { writeLog(std::wstring(L"Argument: ") + args[i]); customKeyFile = args[i]; } else if (equal(args[i], L"-exename") && ++i < argsCount) { writeLog(std::wstring(L"Argument: ") + args[i]); exeName = args[i]; for (int j = 0, l = exeName.size(); j < l; ++j) { if (exeName[j] == L'/' || exeName[j] == L'\\') { exeName = L"Telegram.exe"; break; } } } } if (exeName.empty()) { exeName = L"Telegram.exe"; } if (needupdate) writeLog(L"Need to update!"); if (autostart) writeLog(L"From autostart!"); if (writeprotected) writeLog(L"Write Protected folder!"); if (!customWorkingDir.empty()) writeLog(L"Will pass custom working dir: " + customWorkingDir); updaterName = args[0]; writeLog(L"Updater name is: " + updaterName); if (updaterName.size() > 11) { if (equal(updaterName.substr(updaterName.size() - 11), L"Updater.exe")) { updaterDir = updaterName.substr(0, updaterName.size() - 11); writeLog(L"Updater dir is: " + updaterDir); if (!writeprotected) { updateTo = updaterDir; } writeLog(L"Update to: " + updateTo); if (needupdate && update()) { updateRegistry(); } if (writeprotected) { // if we can't clear all tupdates\ready (Updater.exe is there) - clear only version if (DeleteFile(L"tupdates\\temp\\tdata\\version") || DeleteFile(L"tupdates\\ready\\tdata\\version")) { writeLog(L"Version file deleted!"); } else { writeLog(L"Error: could not delete version file"); } } } else { writeLog(L"Error: bad exe name!"); } } else { writeLog(L"Error: short exe name!"); } LocalFree(args); } else { writeLog(L"Error: No command line arguments!"); } wstring targs; if (autostart) targs += L" -autostart"; if (debug) targs += L" -debug"; if (startintray) targs += L" -startintray"; if (testmode) targs += L" -testmode"; if (externalupdater) targs += L" -externalupdater"; if (!customWorkingDir.empty()) { targs += L" -workdir \"" + customWorkingDir + L"\""; } if (!customKeyFile.empty()) { targs += L" -key \"" + customKeyFile + L"\""; } writeLog(L"Result arguments: " + targs); bool executed = false; if (writeprotected) { // run un-elevated writeLog(L"Trying to run un-elevated by temp.lnk"); HRESULT hres = CoInitialize(0); if (SUCCEEDED(hres)) { IShellLink* psl; HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl); if (SUCCEEDED(hres)) { IPersistFile* ppf; wstring exe = updateTo + exeName, dir = updateTo; psl->SetArguments((targs.size() ? targs.substr(1) : targs).c_str()); psl->SetPath(exe.c_str()); psl->SetWorkingDirectory(dir.c_str()); psl->SetDescription(L""); hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf); if (SUCCEEDED(hres)) { wstring lnk = L"tupdates\\temp\\temp.lnk"; hres = ppf->Save(lnk.c_str(), TRUE); if (!SUCCEEDED(hres)) { lnk = L"tupdates\\ready\\temp.lnk"; // old hres = ppf->Save(lnk.c_str(), TRUE); } ppf->Release(); if (SUCCEEDED(hres)) { writeLog(L"Executing un-elevated through link.."); ShellExecute(0, 0, L"explorer.exe", lnk.c_str(), 0, SW_SHOWNORMAL); executed = true; } else { writeLog(L"Error: ppf->Save failed"); } } else { writeLog(L"Error: Could not create interface IID_IPersistFile"); } psl->Release(); } else { writeLog(L"Error: could not create instance of IID_IShellLink"); } CoUninitialize(); } else { writeLog(L"Error: Could not initialize COM"); } } if (!executed) { ShellExecute(0, 0, (updateTo + exeName).c_str(), (L"-noupdate" + targs).c_str(), 0, SW_SHOWNORMAL); } writeLog(L"Executed '" + exeName + L"', closing log and quitting.."); closeLog(); return 0; }
//-------------------------------------------------------------------------------------- // Parses the command line for parameters. See DXUTInit() for list //-------------------------------------------------------------------------------------- bool ParseCommandLine( SETTINGS* pSettings ) { bool bDisplayError = false; bool bDisplayHelp = false; WCHAR* strCmdLine; WCHAR* strArg; int nNumArgs; WCHAR** pstrArgList = CommandLineToArgvW( GetCommandLine(), &nNumArgs ); for( int iArg=1; iArg<nNumArgs; iArg++ ) { strCmdLine = pstrArgList[iArg]; // Handle flag args if( *strCmdLine == L'/' || *strCmdLine == L'-' ) { strCmdLine++; if( IsNextArg( strCmdLine, L"y" ) ) { pSettings->bOverwrite = true; continue; } if( IsNextArg( strCmdLine, L"t" ) ) { pSettings->bGenTangents = true; continue; } if( IsNextArg( strCmdLine, L"tb" ) ) { pSettings->bGenTangents = true; pSettings->bGenBinormals = true; continue; } if( IsNextArg( strCmdLine, L"a" ) ) { pSettings->bRetainAnimation = true; continue; } if( IsNextArg( strCmdLine, L"v" ) ) { pSettings->bVerbose = true; continue; } if( IsNextArg( strCmdLine, L"xt" ) ) { pSettings->outputType = MESH_TYPE_X_TEXT; continue; } if( IsNextArg( strCmdLine, L"x" ) ) { pSettings->outputType = MESH_TYPE_X_BINARY; continue; } if( IsNextArg( strCmdLine, L"sdkmesh" ) ) { pSettings->outputType = MESH_TYPE_SDKMESH; continue; } if( IsNextArg( strCmdLine, L"o" ) ) { if( iArg+1 < nNumArgs ) { strArg = pstrArgList[++iArg]; pSettings->bOutputFileProvided = true; StringCchCopy( pSettings->strOutputFile, 256, strArg ); continue; } wprintf( L"Incorrect flag usage: /o\n" ); bDisplayError = true; continue; } if( IsNextArg( strCmdLine, L"?" ) ) { DisplayUsage(); return false; } // Unrecognized flag wprintf( L"Unrecognized or incorrect flag usage: %s\n", strCmdLine ); bDisplayError = true; } else { // Handle non-flag args as seperate input file if( pSettings->bInputFileProvided ) { wprintf( L"Too many input files provided: %s\n", strCmdLine ); bDisplayError = true; } else { pSettings->bInputFileProvided = true; StringCchCopy( pSettings->strInputFile, 256, strCmdLine ); continue; } } } if( !pSettings->bInputFileProvided ) bDisplayHelp = true; if( pSettings->bInputFileProvided && !pSettings->bOutputFileProvided ) { StringCchCopy( pSettings->strOutputFile, MAX_PATH, pSettings->strInputFile ); } if( bDisplayHelp ) { DisplayUsage(); return false; } if( bDisplayError ) { wprintf( L"Type \"MeshConvert.exe /?\" for a complete list of options\n" ); return false; } return true; }
int main(void) { int argc; TCHAR** argv = CommandLineToArgvW(GetCommandLineW(), &argc); return _tmain(argc, argv); }
bool os_initialize( application_t* app ) { // // We only need to set the resource path on Windows. There are no // system events to install handlers for, etc. We say that the // resource path is the folder with the executable inside. // LPWSTR *szArglist; int nArgs; szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs); if( NULL == szArglist ) throw std::runtime_error("CommandLineToArgvW failed"); std::string directory_string; if (!hackery::LPCWSTR_to_string(szArglist[0], directory_string)) throw std::runtime_error("Path character conversion failed."); std::string file1; if (nArgs >= 2 && !hackery::LPCWSTR_to_string(szArglist[1], file1)) throw std::runtime_error("Path character conversion failed."); std::string file2; if (nArgs >= 3 && !hackery::LPCWSTR_to_string(szArglist[2], file2)) throw std::runtime_error("Path character conversion failed."); clip_quotes(directory_string); // // Now we need to get a directory from the command line name. // boost::filesystem::path directory( directory_string, boost::filesystem::native ); // // Tell the application... // app->set_resource_directory( directory.branch_path() ); setup_main_window( app ); if (!file1.empty()) { clip_quotes(file1); open_document(app, file1); } if (!file2.empty()) { clip_quotes(file2); open_document(app, file2); } LocalFree(szArglist); return true; }
/* * returns a Python list representing the arguments for the process * with given pid or NULL on error. */ PyObject* psutil_get_arg_list(long pid) { int nArgs, i; LPWSTR *szArglist = NULL; HANDLE hProcess = NULL; PVOID pebAddress; PVOID rtlUserProcParamsAddress; UNICODE_STRING commandLine; WCHAR *commandLineContents = NULL; PyObject *arg = NULL; PyObject *arg_from_wchar = NULL; PyObject *argList = NULL; hProcess = psutil_handle_from_pid(pid); if(hProcess == NULL) { return NULL; } pebAddress = psutil_get_peb_address(hProcess); /* get the address of ProcessParameters */ #ifdef _WIN64 if (!ReadProcessMemory(hProcess, (PCHAR)pebAddress + 32, &rtlUserProcParamsAddress, sizeof(PVOID), NULL)) #else if (!ReadProcessMemory(hProcess, (PCHAR)pebAddress + 0x10, &rtlUserProcParamsAddress, sizeof(PVOID), NULL)) #endif { ////printf("Could not read the address of ProcessParameters!\n"); PyErr_SetFromWindowsErr(0); goto error; } /* read the CommandLine UNICODE_STRING structure */ #ifdef _WIN64 if (!ReadProcessMemory(hProcess, (PCHAR)rtlUserProcParamsAddress + 112, &commandLine, sizeof(commandLine), NULL)) #else if (!ReadProcessMemory(hProcess, (PCHAR)rtlUserProcParamsAddress + 0x40, &commandLine, sizeof(commandLine), NULL)) #endif { ////printf("Could not read CommandLine!\n"); PyErr_SetFromWindowsErr(0); goto error; } /* allocate memory to hold the command line */ commandLineContents = (WCHAR *)malloc(commandLine.Length+1); if (commandLineContents == NULL) { PyErr_NoMemory(); goto error; } /* read the command line */ if (!ReadProcessMemory(hProcess, commandLine.Buffer, commandLineContents, commandLine.Length, NULL)) { ////printf("Could not read the command line string!\n"); PyErr_SetFromWindowsErr(0); goto error; } /* print the commandline */ ////printf("%.*S\n", commandLine.Length / 2, commandLineContents); // null-terminate the string to prevent wcslen from returning incorrect length // the length specifier is in characters, but commandLine.Length is in bytes commandLineContents[(commandLine.Length/sizeof(WCHAR))] = '\0'; // attemempt tp parse the command line using Win32 API, fall back on string // cmdline version otherwise szArglist = CommandLineToArgvW(commandLineContents, &nArgs); if (NULL == szArglist) { // failed to parse arglist // encode as a UTF8 Python string object from WCHAR string arg_from_wchar = PyUnicode_FromWideChar(commandLineContents, commandLine.Length / 2); if (arg_from_wchar == NULL) goto error; #if PY_MAJOR_VERSION >= 3 argList = Py_BuildValue("N", PyUnicode_AsUTF8String(arg_from_wchar)); #else argList = Py_BuildValue("N", PyUnicode_FromObject(arg_from_wchar)); #endif if (!argList) goto error; } else { // arglist parsed as array of UNICODE_STRING, so convert each to Python // string object and add to arg list argList = Py_BuildValue("[]"); if (argList == NULL) goto error; for(i=0; i<nArgs; i++) { arg_from_wchar = NULL; arg = NULL; ////printf("%d: %.*S (%d characters)\n", i, wcslen(szArglist[i]), // szArglist[i], wcslen(szArglist[i])); arg_from_wchar = PyUnicode_FromWideChar(szArglist[i], wcslen(szArglist[i]) ); if (arg_from_wchar == NULL) goto error; #if PY_MAJOR_VERSION >= 3 arg = PyUnicode_FromObject(arg_from_wchar); #else arg = PyUnicode_AsUTF8String(arg_from_wchar); #endif if (arg == NULL) goto error; Py_XDECREF(arg_from_wchar); if (PyList_Append(argList, arg)) goto error; Py_XDECREF(arg); } } if (szArglist != NULL) LocalFree(szArglist); free(commandLineContents); CloseHandle(hProcess); return argList; error: Py_XDECREF(arg); Py_XDECREF(arg_from_wchar); Py_XDECREF(argList); if (hProcess != NULL) CloseHandle(hProcess); if (commandLineContents != NULL) free(commandLineContents); if (szArglist != NULL) LocalFree(szArglist); return NULL; }
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int iCmdShow) { STARTUPINFO si; PROCESS_INFORMATION pi; WCHAR combinedOptions[2048]; HWND hWnd; HDC hDC; HGLRC hRC; MSG msg; BOOL quit = FALSE; LPWSTR *szArgList; int argCount; LPWSTR pathToEmulator = NULL; LPWSTR pathToRom = NULL; LPWSTR cmdLineOptions = NULL; bool splitScreen = false; GLuint texID; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); szArgList = CommandLineToArgvW(GetCommandLine(), &argCount); for(int i = 0; i < argCount; i++) { LPWSTR s = szArgList[i]; if(wcsstr( s, TEXT("--emupath=")) > 0) { pathToEmulator = wcsstr( s, TEXT("="))+1; continue; } if(wcsstr( s, TEXT("--rompath=")) > 0) { pathToRom = wcsstr( s, TEXT("="))+1; continue; } if(wcsstr( s, TEXT("--options=")) > 0) { cmdLineOptions = wcsstr( s, TEXT("="))+1; continue; } } if(pathToEmulator == NULL) { exit(1); } wsprintf(combinedOptions, TEXT("\"%s\" \"%s\" %s"), pathToEmulator, pathToRom, cmdLineOptions); RegisterWindowClass(hInstance); hWnd = CreateWindowEx( WS_EX_TOPMOST|WS_EX_TOOLWINDOW , TEXT("GLSample"), TEXT("OpenGL Sample"), WS_POPUP|WS_VISIBLE|WS_SYSMENU, 0, 0, 512, 512, NULL, NULL, hInstance, NULL ); SetWindowLong(hWnd, GWL_EXSTYLE, GetWindowLong(hWnd, GWL_EXSTYLE) | WS_EX_LAYERED | WS_EX_TRANSPARENT); // enable OpenGL for the window EnableOpenGL( hWnd, &hDC, &hRC ); SetLayeredWindowAttributes(hWnd, 0,255, LWA_ALPHA); // init openGL glEnable(GL_TEXTURE_2D); glDisable(GL_DEPTH_TEST| GL_LIGHTING | GL_CULL_FACE); glGenTextures(1, &texID); if(!CreateProcess(NULL, combinedOptions, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) { DWORD error = GetLastError(); exit(error); } while(EnumWindows(EnumWindowsProc, pi.dwThreadId)) Sleep(100); // program main loop while ( !quit ) { if(GetAsyncKeyState( VK_ESCAPE) < 0) { SendMessage(clientHwnd, WM_CLOSE, 0,0); break; } // check the child process DWORD exCode; if(!GetExitCodeProcess(pi.hProcess, &exCode) || exCode != STILL_ACTIVE) { break; } // check for messages if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) { // handle or dispatch messages if ( msg.message == WM_QUIT ) { quit = TRUE; } else { TranslateMessage( &msg ); DispatchMessage( &msg ); } } else { Draw(clientHwnd, texID); SwapBuffers( hDC ); UpdateGLWindow(hWnd); } } // shutdown OpenGL DisableOpenGL( hWnd, hDC, hRC ); // destroy the window explicitly DestroyWindow( hWnd ); return msg.wParam; }
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpCmdLine, int /*nCmdShow*/) { SetDllDirectory(L""); SetTaskIDPerUUID(); CRegStdDWORD loc = CRegStdDWORD(_T("Software\\TortoiseGit\\LanguageID"), 1033); long langId = loc; CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); CLangDll langDLL; hResource = langDLL.Init(_T("TortoiseIDiff"), langId); if (hResource == NULL) hResource = hInstance; git_libgit2_init(); CCmdLineParser parser(lpCmdLine); if (parser.HasKey(_T("?")) || parser.HasKey(_T("help"))) { TCHAR buf[1024] = { 0 }; LoadString(hResource, IDS_COMMANDLINEHELP, buf, _countof(buf)); MessageBox(NULL, buf, _T("TortoiseIDiff"), MB_ICONINFORMATION); langDLL.Close(); return 0; } MSG msg; hInst = hInstance; INITCOMMONCONTROLSEX used = { sizeof(INITCOMMONCONTROLSEX), ICC_STANDARD_CLASSES | ICC_BAR_CLASSES | ICC_WIN95_CLASSES }; InitCommonControlsEx(&used); // load the cursors we need curHand = (HCURSOR)LoadImage(hInst, MAKEINTRESOURCE(IDC_PANCUR), IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE); curHandDown = (HCURSOR)LoadImage(hInst, MAKEINTRESOURCE(IDC_PANDOWNCUR), IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE); std::unique_ptr<CMainWindow> mainWindow(new CMainWindow(hResource)); mainWindow->SetRegistryPath(_T("Software\\TortoiseGit\\TortoiseIDiffWindowPos")); std::wstring leftfile = parser.HasVal(_T("left")) ? parser.GetVal(_T("left")) : _T(""); std::wstring rightfile = parser.HasVal(_T("right")) ? parser.GetVal(_T("right")) : _T(""); if ((leftfile.empty()) && (lpCmdLine[0] != 0)) { int nArgs; LPWSTR * szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs); if (szArglist) { if (nArgs == 3) { // Four parameters: // [0]: Program name // [1]: left file // [2]: right file if (PathFileExists(szArglist[1]) && PathFileExists(szArglist[2])) { leftfile = szArglist[1]; rightfile = szArglist[2]; } } } // Free memory allocated for CommandLineToArgvW arguments. LocalFree(szArglist); } mainWindow->SetLeft(leftfile.c_str(), parser.HasVal(_T("lefttitle")) ? parser.GetVal(_T("lefttitle")) : _T("")); mainWindow->SetRight(rightfile.c_str(), parser.HasVal(_T("righttitle")) ? parser.GetVal(_T("righttitle")) : _T("")); if (parser.HasVal(L"base")) mainWindow->SetSelectionImage(FileTypeBase, parser.GetVal(L"base"), parser.HasVal(L"basetitle") ? parser.GetVal(L"basetitle") : L""); if (parser.HasVal(L"mine")) mainWindow->SetSelectionImage(FileTypeMine, parser.GetVal(L"mine"), parser.HasVal(L"minetitle") ? parser.GetVal(L"minetitle") : L""); if (parser.HasVal(L"theirs")) mainWindow->SetSelectionImage(FileTypeTheirs, parser.GetVal(L"theirs"), parser.HasVal(L"theirstitle") ? parser.GetVal(L"theirstitle") : L""); if (parser.HasVal(L"result")) mainWindow->SetSelectionResult(parser.GetVal(L"result")); mainWindow->resolveMsgWnd = parser.HasVal(L"resolvemsghwnd") ? (HWND)parser.GetLongLongVal(L"resolvemsghwnd") : 0; mainWindow->resolveMsgWParam = parser.HasVal(L"resolvemsgwparam") ? (WPARAM)parser.GetLongLongVal(L"resolvemsgwparam") : 0; mainWindow->resolveMsgLParam = parser.HasVal(L"resolvemsglparam") ? (LPARAM)parser.GetLongLongVal(L"resolvemsglparam") : 0; if (mainWindow->RegisterAndCreateWindow()) { HACCEL hAccelTable = LoadAccelerators(hResource, MAKEINTRESOURCE(IDR_TORTOISEIDIFF)); if (!parser.HasVal(L"left") && parser.HasVal(L"base") && !parser.HasVal(L"mine") && !parser.HasVal(L"theirs")) { PostMessage(*mainWindow, WM_COMMAND, ID_FILE_OPEN, 0); } if (parser.HasKey(_T("overlay"))) { PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_OVERLAPIMAGES, 0); } if (parser.HasKey(_T("fit"))) { PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_FITIMAGEHEIGHTS, 0); PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_FITIMAGEWIDTHS, 0); } if (parser.HasKey(_T("fitwidth"))) { PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_FITIMAGEWIDTHS, 0); } if (parser.HasKey(_T("fitheight"))) { PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_FITIMAGEHEIGHTS, 0); } if (parser.HasKey(_T("showinfo"))) { PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_IMAGEINFO, 0); } // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(*mainWindow, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; } langDLL.Close(); DestroyCursor(curHand); DestroyCursor(curHandDown); CoUninitialize(); git_libgit2_shutdown(); return 1; }
/* * returns a Python list representing the arguments for the process * with given pid or NULL on error. */ PyObject * psutil_get_cmdline(long pid) { int nArgs, i; LPWSTR *szArglist = NULL; HANDLE hProcess = NULL; PVOID pebAddress; PVOID rtlUserProcParamsAddress; UNICODE_STRING commandLine; WCHAR *commandLineContents = NULL; PyObject *py_unicode = NULL; PyObject *py_retlist = NULL; hProcess = psutil_handle_from_pid(pid); if (hProcess == NULL) return NULL; pebAddress = psutil_get_peb_address(hProcess); // get the address of ProcessParameters #ifdef _WIN64 if (!ReadProcessMemory(hProcess, (PCHAR)pebAddress + 32, &rtlUserProcParamsAddress, sizeof(PVOID), NULL)) #else if (!ReadProcessMemory(hProcess, (PCHAR)pebAddress + 0x10, &rtlUserProcParamsAddress, sizeof(PVOID), NULL)) #endif { ////printf("Could not read the address of ProcessParameters!\n"); PyErr_SetFromWindowsErr(0); goto error; } // read the CommandLine UNICODE_STRING structure #ifdef _WIN64 if (!ReadProcessMemory(hProcess, (PCHAR)rtlUserProcParamsAddress + 112, &commandLine, sizeof(commandLine), NULL)) #else if (!ReadProcessMemory(hProcess, (PCHAR)rtlUserProcParamsAddress + 0x40, &commandLine, sizeof(commandLine), NULL)) #endif { PyErr_SetFromWindowsErr(0); goto error; } // allocate memory to hold the command line commandLineContents = (WCHAR *)malloc(commandLine.Length + 1); if (commandLineContents == NULL) { PyErr_NoMemory(); goto error; } // read the command line if (!ReadProcessMemory(hProcess, commandLine.Buffer, commandLineContents, commandLine.Length, NULL)) { PyErr_SetFromWindowsErr(0); goto error; } // Null-terminate the string to prevent wcslen from returning // incorrect length the length specifier is in characters, but // commandLine.Length is in bytes. commandLineContents[(commandLine.Length / sizeof(WCHAR))] = '\0'; // attempt to parse the command line using Win32 API, fall back // on string cmdline version otherwise szArglist = CommandLineToArgvW(commandLineContents, &nArgs); if (szArglist == NULL) { PyErr_SetFromWindowsErr(0); goto error; } else { // arglist parsed as array of UNICODE_STRING, so convert each to // Python string object and add to arg list py_retlist = Py_BuildValue("[]"); if (py_retlist == NULL) goto error; for (i = 0; i < nArgs; i++) { py_unicode = PyUnicode_FromWideChar( szArglist[i], wcslen(szArglist[i])); if (py_unicode == NULL) goto error; if (PyList_Append(py_retlist, py_unicode)) goto error; Py_XDECREF(py_unicode); } } if (szArglist != NULL) LocalFree(szArglist); free(commandLineContents); CloseHandle(hProcess); return py_retlist; error: Py_XDECREF(py_unicode); Py_XDECREF(py_retlist); if (hProcess != NULL) CloseHandle(hProcess); if (commandLineContents != NULL) free(commandLineContents); if (szArglist != NULL) LocalFree(szArglist); return NULL; }
// xxx.exe -enc dst.path src.path xxxxx 1 rc4 0 HRESULT CZConvertCmd::TransferCmdLine() { LPWSTR *szArglist; int nArgs; szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs); if (nArgs == 3&& NULL != szArglist) { if (0==_tcscmp(szArglist[1],CONVERT_CMD_OPTION_ENCRPT_BYMEM)) { LPTSTR memName = szArglist[2]; ZDbgPrint(DBG_INFO,_T("ZDATABACK memName = %s"),memName); return TransferByMem(memName); } else { return ERROR_INVALID_PARAMETER; } } else if( szArglist == NULL || nArgs < 5) { return ERROR_INVALID_PARAMETER; } TCHAR dstPath[MAX_PATH] = {NULL}; TCHAR srcPath[MAX_PATH] = {NULL}; ULONG optionType = 0; ULONG encyptType = ENCRYPT_RC4; BOOL showProcDialog = FALSE; UCHAR passWord[MAX_PATH]; ULONG passWorfLen = 0; if (0==_tcscmp(szArglist[1],CONVERT_CMD_OPTION_ENCRPT_TOFILE)) { optionType = CONVERT_OPTIONCODE_ENCRPT_TOFILE; } else if (0==_tcscmp(szArglist[1],CONVERT_CMD_OPTION_DECRPT_FROMFILE)) { optionType = CONVERT_OPTIONCODE_DECRPT_FROMFILE; } else if (0==_tcscmp(szArglist[1],CONVERT_CMD_OPTION_ENCRPT_TOZIP)) { optionType = CONVERT_OPTIONCODE_ENCRPT_TOZIP; } else if (0==_tcscmp(szArglist[1],CONVERT_CMD_OPTION_DECRPT_FROMZIP)) { optionType = CONVERT_OPTIONCODE_DECRPT_FROMZIP; } _tcscpy_s(dstPath,_countof(dstPath),szArglist[2]); _tcscpy_s(srcPath,_countof(srcPath),szArglist[3]); memcpy(passWord,szArglist[4],_tcslen(szArglist[4]) * sizeof(TCHAR)); passWorfLen = _tcslen(szArglist[4]) * sizeof(TCHAR); if (nArgs > 5) { if (0==_tcscmp(szArglist[5],CONVERT_CMD_SHOWPROCDIALOG)) { showProcDialog = TRUE; } else if (0==_tcscmp(szArglist[5],CONVERT_CMD_NOTSHOWPROCDIALOG)) { showProcDialog = FALSE; } } if (nArgs > 6) { if (0==_tcscmp(szArglist[6],CONVERT_CMD_ENCRPTTYPE_RC4)) { encyptType = ENCRYPT_RC4; } } ZDbgPrint(DBG_INFO,_T("ZDATABACK srcpath = %s"),srcPath); return ConvertFileBase(dstPath,srcPath,optionType,encyptType,showProcDialog,passWord,passWorfLen,NULL,0,NULL); }
int main(int argc, char *argv[]) #endif { #if defined(PHP_WIN32) # ifdef PHP_CLI_WIN32_NO_CONSOLE int argc = __argc; char **argv = __argv; # else int num_args; wchar_t **argv_wide; char **argv_save = argv; BOOL using_wide_argv = 0; # endif #endif int c; int exit_status = SUCCESS; int module_started = 0, sapi_started = 0; char *php_optarg = NULL; int php_optind = 1, use_extended_info = 0; char *ini_path_override = NULL; char *ini_entries = NULL; int ini_entries_len = 0; int ini_ignore = 0; sapi_module_struct *sapi_module = &cli_sapi_module; /* * Do not move this initialization. It needs to happen before argv is used * in any way. */ argv = save_ps_args(argc, argv); cli_sapi_module.additional_functions = additional_functions; #if defined(PHP_WIN32) && defined(_DEBUG) && defined(PHP_WIN32_DEBUG_HEAP) { int tmp_flag; _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); tmp_flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); tmp_flag |= _CRTDBG_DELAY_FREE_MEM_DF; tmp_flag |= _CRTDBG_LEAK_CHECK_DF; _CrtSetDbgFlag(tmp_flag); } #endif #ifdef HAVE_SIGNAL_H #if defined(SIGPIPE) && defined(SIG_IGN) signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so that sockets created via fsockopen() don't kill PHP if the remote site closes it. in apache|apxs mode apache does that for us! [email protected] 20000419 */ #endif #endif #ifdef ZTS tsrm_startup(1, 1, 0, NULL); (void)ts_resource(0); ZEND_TSRMLS_CACHE_UPDATE(); #endif zend_signal_startup(); #ifdef PHP_WIN32 _fmode = _O_BINARY; /*sets default for file streams to binary */ setmode(_fileno(stdin), O_BINARY); /* make the stdio mode be binary */ setmode(_fileno(stdout), O_BINARY); /* make the stdio mode be binary */ setmode(_fileno(stderr), O_BINARY); /* make the stdio mode be binary */ #endif while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2))!=-1) { switch (c) { case 'c': if (ini_path_override) { free(ini_path_override); } ini_path_override = strdup(php_optarg); break; case 'n': ini_ignore = 1; break; case 'd': { /* define ini entries on command line */ int len = (int)strlen(php_optarg); char *val; if ((val = strchr(php_optarg, '='))) { val++; if (!isalnum(*val) && *val != '"' && *val != '\'' && *val != '\0') { ini_entries = realloc(ini_entries, ini_entries_len + len + sizeof("\"\"\n\0")); memcpy(ini_entries + ini_entries_len, php_optarg, (val - php_optarg)); ini_entries_len += (int)(val - php_optarg); memcpy(ini_entries + ini_entries_len, "\"", 1); ini_entries_len++; memcpy(ini_entries + ini_entries_len, val, len - (val - php_optarg)); ini_entries_len += len - (int)(val - php_optarg); memcpy(ini_entries + ini_entries_len, "\"\n\0", sizeof("\"\n\0")); ini_entries_len += sizeof("\n\0\"") - 2; } else { ini_entries = realloc(ini_entries, ini_entries_len + len + sizeof("\n\0")); memcpy(ini_entries + ini_entries_len, php_optarg, len); memcpy(ini_entries + ini_entries_len + len, "\n\0", sizeof("\n\0")); ini_entries_len += len + sizeof("\n\0") - 2; } } else { ini_entries = realloc(ini_entries, ini_entries_len + len + sizeof("=1\n\0")); memcpy(ini_entries + ini_entries_len, php_optarg, len); memcpy(ini_entries + ini_entries_len + len, "=1\n\0", sizeof("=1\n\0")); ini_entries_len += len + sizeof("=1\n\0") - 2; } break; } #ifndef PHP_CLI_WIN32_NO_CONSOLE case 'S': sapi_module = &cli_server_sapi_module; cli_server_sapi_module.additional_functions = server_additional_functions; break; #endif case 'h': /* help & quit */ case '?': php_cli_usage(argv[0]); goto out; case 'i': case 'v': case 'm': sapi_module = &cli_sapi_module; goto exit_loop; case 'e': /* enable extended info output */ use_extended_info = 1; break; } } exit_loop: sapi_module->ini_defaults = sapi_cli_ini_defaults; sapi_module->php_ini_path_override = ini_path_override; sapi_module->phpinfo_as_text = 1; sapi_module->php_ini_ignore_cwd = 1; sapi_startup(sapi_module); sapi_started = 1; sapi_module->php_ini_ignore = ini_ignore; sapi_module->executable_location = argv[0]; if (sapi_module == &cli_sapi_module) { if (ini_entries) { ini_entries = realloc(ini_entries, ini_entries_len + sizeof(HARDCODED_INI)); memmove(ini_entries + sizeof(HARDCODED_INI) - 2, ini_entries, ini_entries_len + 1); memcpy(ini_entries, HARDCODED_INI, sizeof(HARDCODED_INI) - 2); } else { ini_entries = malloc(sizeof(HARDCODED_INI)); memcpy(ini_entries, HARDCODED_INI, sizeof(HARDCODED_INI)); } ini_entries_len += sizeof(HARDCODED_INI) - 2; } sapi_module->ini_entries = ini_entries; /* startup after we get the above ini override se we get things right */ if (sapi_module->startup(sapi_module) == FAILURE) { /* there is no way to see if we must call zend_ini_deactivate() * since we cannot check if EG(ini_directives) has been initialised * because the executor's constructor does not set initialize it. * Apart from that there seems no need for zend_ini_deactivate() yet. * So we goto out_err.*/ exit_status = 1; goto out; } module_started = 1; #if defined(PHP_WIN32) && !defined(PHP_CLI_WIN32_NO_CONSOLE) php_win32_cp_cli_setup(); orig_cp = (php_win32_cp_get_orig())->id; /* Ignore the delivered argv and argc, read from W API. This place might be too late though, but this is the earliest place ATW we can access the internal charset information from PHP. */ argv_wide = CommandLineToArgvW(GetCommandLineW(), &num_args); PHP_WIN32_CP_W_TO_A_ARRAY(argv_wide, num_args, argv, argc) using_wide_argv = 1; SetConsoleCtrlHandler(php_cli_win32_ctrl_handler, TRUE); #endif /* -e option */ if (use_extended_info) { CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO; } zend_first_try { #ifndef PHP_CLI_WIN32_NO_CONSOLE if (sapi_module == &cli_sapi_module) { #endif exit_status = do_cli(argc, argv); #ifndef PHP_CLI_WIN32_NO_CONSOLE } else { exit_status = do_cli_server(argc, argv); } #endif } zend_end_try(); out: if (ini_path_override) { free(ini_path_override); } if (ini_entries) { free(ini_entries); } if (module_started) { php_module_shutdown(); } if (sapi_started) { sapi_shutdown(); } #ifdef ZTS tsrm_shutdown(); #endif #if defined(PHP_WIN32) && !defined(PHP_CLI_WIN32_NO_CONSOLE) (void)php_win32_cp_cli_restore(); if (using_wide_argv) { PHP_WIN32_FREE_ARRAY(argv, argc); LocalFree(argv_wide); } argv = argv_save; #endif /* * Do not move this de-initialization. It needs to happen right before * exiting. */ cleanup_ps_args(argv); exit(exit_status); }
int main() { int argc; LPWSTR *argv = CommandLineToArgvW(GetCommandLineW(), &argc); if (argc < 3) die(printf("[!] Need a file name to analyze and a filename for the memory dump\n")); strOutFileName = argv[2]; #ifndef _DEBUG printf("[!] PRIMA di eseguire questo, guarda il certificato e verifica che la firma sia valida senno' esegui questo programma solo su una VM disposable!!!\n"); printf("[!] Premi 'k' e invio per andare avanti\n"); if (getchar() != 'k') exit(printf("[*] Exiting..\n")); #endif STARTUPINFO pStartupInfo; PROCESS_INFORMATION pProcessInfo; SecureZeroMemory(&pStartupInfo, sizeof(STARTUPINFO)); SecureZeroMemory(&pProcessInfo, sizeof(PROCESS_INFORMATION)); pStartupInfo.cb = sizeof(STARTUPINFO); if (!CreateProcess(argv[1], NULL, NULL, NULL, FALSE, DEBUG_PROCESS, NULL, NULL, &pStartupInfo, &pProcessInfo)) exit(printf("[!] Cannot start %S, got => %08x\n", argv[1], GetLastError())); printf("[*] Process %d started\n", GetProcessId(hProcess)); hProcess = pProcessInfo.hProcess; while (1) { DEBUG_EVENT pEvent; if (!WaitForDebugEvent(&pEvent, INFINITE)) break; DWORD dwStatus = DBG_CONTINUE; switch (pEvent.dwDebugEventCode) { case EXCEPTION_DEBUG_EVENT: dwStatus = HandleException(&pEvent); break; case LOAD_DLL_DEBUG_EVENT: HandleDll(&pEvent); break; case EXIT_PROCESS_DEBUG_EVENT: break; // FIXME case CREATE_PROCESS_DEBUG_EVENT: case CREATE_THREAD_DEBUG_EVENT: case EXIT_THREAD_DEBUG_EVENT: case UNLOAD_DLL_DEBUG_EVENT: case OUTPUT_DEBUG_STRING_EVENT: case RIP_EVENT: break; default: printf("[!] Got unknown debug event => %d\n", pEvent.dwDebugEventCode); TerminateProcess(pProcessInfo.hProcess, 0); ExitProcess(0); } ContinueDebugEvent(pEvent.dwProcessId, pEvent.dwThreadId, dwStatus); } TerminateProcess(pProcessInfo.hProcess, 0); }
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { LPWIN32_FIND_DATAW ffd; LARGE_INTEGER filesize; WCHAR szDir[MAX_PATH]; size_t length_of_arg; HANDLE hFind = INVALID_HANDLE_VALUE; DWORD dwError=0; LPWSTR *szArgList; int argCount; std::ofstream logFile; logFile.open ("FileListing.log"); // If the directory is not specified as a command-line argument, // print usage. szArgList = CommandLineToArgvW((LPCWSTR)GetCommandLine(), &argCount); if(argCount !=2) logFile << "\nUsage: %s <directory name>\n" << szArgList[0]; /*if(argc != 2) { _tprintf(TEXT("\nUsage: %s <directory name>\n"), argv[0]); return (-1); }*/ // Check that the input path plus 3 is not longer than MAX_PATH. // Three characters are for the "\*" plus NULL appended below. StringCchLengthW(szArgList[1], MAX_PATH, (size_t *)&argCount); if ( argCount > (MAX_PATH - 3)) { logFile << "\nDirectory path is too long.\n"; return (-1); } logFile <<"\nTarget directory is "<<szArgList[1] <<":\n\n"; // Prepare string for use with FindFile functions. First, copy the // string to a buffer, then append '\*' to the directory name. StringCchCopyW(szDir, MAX_PATH, szArgList[1]); StringCchCatW(szDir, MAX_PATH, L"\\*"); // Find the first file in the directory. hFind = FindFirstFileW(szDir, &ffd); if (INVALID_HANDLE_VALUE == hFind) { DisplayErrorBox(TEXT("FindFirstFile")); return dwError; } // List all the files in the directory with some info about them. do { if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { _tprintf(TEXT(" %s <DIR>\n"), ffd.cFileName); } else { filesize.LowPart = ffd.nFileSizeLow; filesize.HighPart = ffd.nFileSizeHigh; _tprintf(TEXT(" %s %ld bytes\n"), ffd.cFileName, filesize.QuadPart); } } while (FindNextFile(hFind, &ffd) != 0); dwError = GetLastError(); if (dwError != ERROR_NO_MORE_FILES) { DisplayErrorBox(TEXT("FindFirstFile")); } FindClose(hFind); return dwError; return 0; }
// CTortoiseMergeApp initialization BOOL CTortoiseMergeApp::InitInstance() { SetDllDirectory(L""); SetTaskIDPerUUID(); CCrashReport::Instance().AddUserInfoToReport(L"CommandLine", GetCommandLine()); { DWORD len = GetCurrentDirectory(0, NULL); if (len) { std::unique_ptr<TCHAR[]> originalCurrentDirectory(new TCHAR[len]); if (GetCurrentDirectory(len, originalCurrentDirectory.get())) { sOrigCWD = originalCurrentDirectory.get(); sOrigCWD = CPathUtils::GetLongPathname(sOrigCWD); } } } //set the resource dll for the required language CRegDWORD loc = CRegDWORD(_T("Software\\TortoiseGit\\LanguageID"), 1033); long langId = loc; CString langDll; HINSTANCE hInst = NULL; do { langDll.Format(_T("%sLanguages\\TortoiseMerge%ld.dll"), (LPCTSTR)CPathUtils::GetAppParentDirectory(), langId); hInst = LoadLibrary(langDll); CString sVer = _T(STRPRODUCTVER); CString sFileVer = CPathUtils::GetVersionFromFile(langDll); if (sFileVer.Compare(sVer)!=0) { FreeLibrary(hInst); hInst = NULL; } if (hInst != NULL) AfxSetResourceHandle(hInst); else { DWORD lid = SUBLANGID(langId); lid--; if (lid > 0) { langId = MAKELANGID(PRIMARYLANGID(langId), lid); } else langId = 0; } } while ((hInst == NULL) && (langId != 0)); TCHAR buf[6] = { 0 }; _tcscpy_s(buf, _T("en")); langId = loc; CString sHelppath = CPathUtils::GetAppDirectory() + _T("TortoiseMerge_en.chm"); free((void*)m_pszHelpFilePath); m_pszHelpFilePath=_tcsdup(sHelppath); sHelppath = CPathUtils::GetAppParentDirectory() + _T("Languages\\TortoiseMerge_en.chm"); do { GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO639LANGNAME, buf, _countof(buf)); CString sLang = _T("_"); sLang += buf; sHelppath.Replace(_T("_en"), sLang); if (PathFileExists(sHelppath)) { free((void*)m_pszHelpFilePath); m_pszHelpFilePath=_tcsdup(sHelppath); break; } sHelppath.Replace(sLang, _T("_en")); GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO3166CTRYNAME, buf, _countof(buf)); sLang += _T("_"); sLang += buf; sHelppath.Replace(_T("_en"), sLang); if (PathFileExists(sHelppath)) { free((void*)m_pszHelpFilePath); m_pszHelpFilePath=_tcsdup(sHelppath); break; } sHelppath.Replace(sLang, _T("_en")); DWORD lid = SUBLANGID(langId); lid--; if (lid > 0) { langId = MAKELANGID(PRIMARYLANGID(langId), lid); } else langId = 0; } while (langId); setlocale(LC_ALL, ""); // We need to explicitly set the thread locale to the system default one to avoid possible problems with saving files in its original codepage // The problems occures when the language of OS differs from the regional settings // See the details here: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=100887 SetThreadLocale(LOCALE_SYSTEM_DEFAULT); // InitCommonControls() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. InitCommonControls(); CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows)); CMFCButton::EnableWindowsTheming(); EnableTaskbarInteraction(FALSE); // Initialize all Managers for usage. They are automatically constructed // if not yet present InitContextMenuManager(); InitKeyboardManager(); InitTooltipManager (); CMFCToolTipInfo params; params.m_bVislManagerTheme = TRUE; GetTooltipManager ()->SetTooltipParams ( AFX_TOOLTIP_TYPE_ALL, RUNTIME_CLASS (CMFCToolTipCtrl), ¶ms); CCmdLineParser parser = CCmdLineParser(this->m_lpCmdLine); g_sGroupingUUID = parser.GetVal(L"groupuuid"); if (parser.HasKey(_T("?")) || parser.HasKey(_T("help"))) { CString sHelpText; sHelpText.LoadString(IDS_COMMANDLINEHELP); MessageBox(NULL, sHelpText, _T("TortoiseGitMerge"), MB_ICONINFORMATION); return FALSE; } // Initialize OLE libraries if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored SetRegistryKey(_T("TortoiseGitMerge")); if (CRegDWORD(_T("Software\\TortoiseGitMerge\\Debug"), FALSE)==TRUE) AfxMessageBox(AfxGetApp()->m_lpCmdLine, MB_OK | MB_ICONINFORMATION); // To create the main window, this code creates a new frame window // object and then sets it as the application's main window object CMainFrame* pFrame = new CMainFrame; if (pFrame == NULL) return FALSE; m_pMainWnd = pFrame; // create and load the frame with its resources if (!pFrame->LoadFrame(IDR_MAINFRAME, WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, NULL, NULL)) return FALSE; // Fill in the command line options pFrame->m_Data.m_baseFile.SetFileName(parser.GetVal(_T("base"))); pFrame->m_Data.m_baseFile.SetDescriptiveName(parser.GetVal(_T("basename"))); pFrame->m_Data.m_baseFile.SetReflectedName(parser.GetVal(_T("basereflectedname"))); pFrame->m_Data.m_theirFile.SetFileName(parser.GetVal(_T("theirs"))); pFrame->m_Data.m_theirFile.SetDescriptiveName(parser.GetVal(_T("theirsname"))); pFrame->m_Data.m_theirFile.SetReflectedName(parser.GetVal(_T("theirsreflectedname"))); pFrame->m_Data.m_yourFile.SetFileName(parser.GetVal(_T("mine"))); pFrame->m_Data.m_yourFile.SetDescriptiveName(parser.GetVal(_T("minename"))); pFrame->m_Data.m_yourFile.SetReflectedName(parser.GetVal(_T("minereflectedname"))); pFrame->m_Data.m_mergedFile.SetFileName(parser.GetVal(_T("merged"))); pFrame->m_Data.m_mergedFile.SetDescriptiveName(parser.GetVal(_T("mergedname"))); pFrame->m_Data.m_mergedFile.SetReflectedName(parser.GetVal(_T("mergedreflectedname"))); pFrame->m_Data.m_sPatchPath = parser.HasVal(_T("patchpath")) ? parser.GetVal(_T("patchpath")) : _T(""); pFrame->m_Data.m_sPatchPath.Replace('/', '\\'); if (parser.HasKey(_T("patchoriginal"))) pFrame->m_Data.m_sPatchOriginal = parser.GetVal(_T("patchoriginal")); if (parser.HasKey(_T("patchpatched"))) pFrame->m_Data.m_sPatchPatched = parser.GetVal(_T("patchpatched")); pFrame->m_Data.m_sDiffFile = parser.GetVal(_T("diff")); pFrame->m_Data.m_sDiffFile.Replace('/', '\\'); if (parser.HasKey(_T("oneway"))) pFrame->m_bOneWay = TRUE; if (parser.HasKey(_T("diff"))) pFrame->m_bOneWay = FALSE; if (parser.HasKey(_T("reversedpatch"))) pFrame->m_bReversedPatch = TRUE; if (parser.HasKey(_T("saverequired"))) pFrame->m_bSaveRequired = true; if (parser.HasKey(_T("saverequiredonconflicts"))) pFrame->m_bSaveRequiredOnConflicts = true; if (parser.HasKey(_T("deletebasetheirsmineonclose"))) pFrame->m_bDeleteBaseTheirsMineOnClose = true; if (pFrame->m_Data.IsBaseFileInUse() && !pFrame->m_Data.IsYourFileInUse() && pFrame->m_Data.IsTheirFileInUse()) { pFrame->m_Data.m_yourFile.TransferDetailsFrom(pFrame->m_Data.m_theirFile); } if ((!parser.HasKey(_T("patchpath")))&&(parser.HasVal(_T("diff")))) { // a patchfile was given, but not folder path to apply the patch to // If the patchfile is located inside a working copy, then use the parent directory // of the patchfile as the target directory, otherwise ask the user for a path. if (parser.HasKey(_T("wc"))) pFrame->m_Data.m_sPatchPath = pFrame->m_Data.m_sDiffFile.Left(pFrame->m_Data.m_sDiffFile.ReverseFind('\\')); else { CBrowseFolder fbrowser; fbrowser.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS; if (fbrowser.Show(NULL, pFrame->m_Data.m_sPatchPath)==CBrowseFolder::CANCEL) return FALSE; } } if ((parser.HasKey(_T("patchpath")))&&(!parser.HasVal(_T("diff")))) { // A path was given for applying a patchfile, but // the patchfile itself was not. // So ask the user for that patchfile HRESULT hr; // Create a new common save file dialog CComPtr<IFileOpenDialog> pfd = NULL; hr = pfd.CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER); if (SUCCEEDED(hr)) { // Set the dialog options DWORD dwOptions; if (SUCCEEDED(hr = pfd->GetOptions(&dwOptions))) { hr = pfd->SetOptions(dwOptions | FOS_FILEMUSTEXIST | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST); } // Set a title if (SUCCEEDED(hr)) { CString temp; temp.LoadString(IDS_OPENDIFFFILETITLE); pfd->SetTitle(temp); } CSelectFileFilter fileFilter(IDS_PATCHFILEFILTER); hr = pfd->SetFileTypes(fileFilter.GetCount(), fileFilter); bool bAdvised = false; DWORD dwCookie = 0; CComObjectStackEx<PatchOpenDlgEventHandler> cbk; CComQIPtr<IFileDialogEvents> pEvents = cbk.GetUnknown(); { CComPtr<IFileDialogCustomize> pfdCustomize; hr = pfd->QueryInterface(IID_PPV_ARGS(&pfdCustomize)); if (SUCCEEDED(hr)) { // check if there's a unified diff on the clipboard and // add a button to the fileopen dialog if there is. UINT cFormat = RegisterClipboardFormat(_T("TSVN_UNIFIEDDIFF")); if ((cFormat)&&(OpenClipboard(NULL))) { HGLOBAL hglb = GetClipboardData(cFormat); if (hglb) { pfdCustomize->AddPushButton(101, CString(MAKEINTRESOURCE(IDS_PATCH_COPYFROMCLIPBOARD))); hr = pfd->Advise(pEvents, &dwCookie); bAdvised = SUCCEEDED(hr); } CloseClipboard(); } } } // Show the save file dialog if (SUCCEEDED(hr) && SUCCEEDED(hr = pfd->Show(pFrame->m_hWnd))) { // Get the selection from the user CComPtr<IShellItem> psiResult = NULL; hr = pfd->GetResult(&psiResult); if (bAdvised) pfd->Unadvise(dwCookie); if (SUCCEEDED(hr)) { PWSTR pszPath = NULL; hr = psiResult->GetDisplayName(SIGDN_FILESYSPATH, &pszPath); if (SUCCEEDED(hr)) { pFrame->m_Data.m_sDiffFile = pszPath; CoTaskMemFree(pszPath); } } else { // no result, which means we closed the dialog in our button handler std::wstring sTempFile; if (TrySavePatchFromClipboard(sTempFile)) pFrame->m_Data.m_sDiffFile = sTempFile.c_str(); } } else { if (bAdvised) pfd->Unadvise(dwCookie); return FALSE; } } else { OPENFILENAME ofn = {0}; // common dialog box structure TCHAR szFile[MAX_PATH] = {0}; // buffer for file name // Initialize OPENFILENAME ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = pFrame->m_hWnd; ofn.lpstrFile = szFile; ofn.nMaxFile = _countof(szFile); CString temp; temp.LoadString(IDS_OPENDIFFFILETITLE); if (temp.IsEmpty()) ofn.lpstrTitle = NULL; else ofn.lpstrTitle = temp; ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_EXPLORER; if( HasClipboardPatch() ) { ofn.Flags |= ( OFN_ENABLETEMPLATE | OFN_ENABLEHOOK ); ofn.hInstance = AfxGetResourceHandle(); ofn.lpTemplateName = MAKEINTRESOURCE(IDD_PATCH_FILE_OPEN_CUSTOM); ofn.lpfnHook = CreatePatchFileOpenHook; } CSelectFileFilter fileFilter(IDS_PATCHFILEFILTER); ofn.lpstrFilter = fileFilter; ofn.nFilterIndex = 1; // Display the Open dialog box. if (GetOpenFileName(&ofn)==FALSE) { return FALSE; } pFrame->m_Data.m_sDiffFile = ofn.lpstrFile; } } if ( pFrame->m_Data.m_baseFile.GetFilename().IsEmpty() && pFrame->m_Data.m_yourFile.GetFilename().IsEmpty() ) { int nArgs; LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs); if( NULL == szArglist ) { TRACE("CommandLineToArgvW failed\n"); } else { if ( nArgs==3 || nArgs==4 ) { // Four parameters: // [0]: Program name // [1]: BASE file // [2]: my file // [3]: THEIR file (optional) // This is the same format CAppUtils::StartExtDiff // uses if %base and %mine are not set and most // other diff tools use it too. if ( PathFileExists(szArglist[1]) && PathFileExists(szArglist[2]) ) { pFrame->m_Data.m_baseFile.SetFileName(szArglist[1]); pFrame->m_Data.m_yourFile.SetFileName(szArglist[2]); if ( nArgs == 4 && PathFileExists(szArglist[3]) ) { pFrame->m_Data.m_theirFile.SetFileName(szArglist[3]); } } } else if (nArgs == 2) { // only one path specified: use it to fill the "open" dialog if (PathFileExists(szArglist[1])) { pFrame->m_Data.m_yourFile.SetFileName(szArglist[1]); pFrame->m_Data.m_yourFile.StoreFileAttributes(); } } } // Free memory allocated for CommandLineToArgvW arguments. LocalFree(szArglist); } pFrame->m_bReadOnly = !!parser.HasKey(_T("readonly")); if (GetFileAttributes(pFrame->m_Data.m_yourFile.GetFilename()) & FILE_ATTRIBUTE_READONLY) pFrame->m_bReadOnly = true; pFrame->m_bBlame = !!parser.HasKey(_T("blame")); // diffing a blame means no editing! if (pFrame->m_bBlame) pFrame->m_bReadOnly = true; pFrame->SetWindowTitle(); if (parser.HasKey(_T("createunifieddiff"))) { // user requested to create a unified diff file CString origFile = parser.GetVal(_T("origfile")); CString modifiedFile = parser.GetVal(_T("modifiedfile")); if (!origFile.IsEmpty() && !modifiedFile.IsEmpty()) { CString outfile = parser.GetVal(_T("outfile")); if (outfile.IsEmpty()) { CCommonAppUtils::FileOpenSave(outfile, NULL, IDS_SAVEASTITLE, IDS_COMMONFILEFILTER, false, NULL); } if (!outfile.IsEmpty()) { CRegStdDWORD regContextLines(L"Software\\TortoiseGitMerge\\ContextLines", (DWORD)-1); CAppUtils::CreateUnifiedDiff(origFile, modifiedFile, outfile, regContextLines, false); return FALSE; } } } pFrame->resolveMsgWnd = parser.HasVal(L"resolvemsghwnd") ? (HWND)parser.GetLongLongVal(L"resolvemsghwnd") : 0; pFrame->resolveMsgWParam = parser.HasVal(L"resolvemsgwparam") ? (WPARAM)parser.GetLongLongVal(L"resolvemsgwparam") : 0; pFrame->resolveMsgLParam = parser.HasVal(L"resolvemsglparam") ? (LPARAM)parser.GetLongLongVal(L"resolvemsglparam") : 0; // The one and only window has been initialized, so show and update it pFrame->ActivateFrame(); pFrame->ShowWindow(SW_SHOW); pFrame->UpdateWindow(); pFrame->ShowDiffBar(!pFrame->m_bOneWay); if (!pFrame->m_Data.IsBaseFileInUse() && pFrame->m_Data.m_sPatchPath.IsEmpty() && pFrame->m_Data.m_sDiffFile.IsEmpty()) { pFrame->OnFileOpen(pFrame->m_Data.m_yourFile.InUse()); return TRUE; } int line = -2; if (parser.HasVal(_T("line"))) { line = parser.GetLongVal(_T("line")); line--; // we need the index } return pFrame->LoadViews(line); }
//----------------------------------------------------------------------------- // Name: WinMain() // Desc: The application's entry point //----------------------------------------------------------------------------- INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR commandLine, INT ) { #ifdef WIN32_MEMORY_LEAK_DETECT // Turn on the heap checking _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_DELAY_FREE_MEM_DF | _CRTDBG_LEAK_CHECK_DF ) ; // Not adding the _CRTDBG_CHECK_ALWAYS_DF flag either - since it makes Boxee run VERY slow. #endif #ifdef USE_MINI_DUMPS g_MiniDumps.Install(); #endif CStdStringW strcl(commandLine); if (strcl.Find(L"-usf") >= 0) { CUpdateSourceFile UpdateSourceFile; bool success = UpdateSourceFile.UpdateProfilesSourceFile(); if(success) { printf("main - Successfully updated the profiles source files\n"); } else { printf("main - Failed to update profiles source files\n"); } success = UpdateSourceFile.UpgradeSettings(); if(success) { printf("main - Successfully updated GUI Settings\n"); } else { printf("main - Failed to update GUI Settings\n"); } exit(0); } // Initializes CreateMiniDump to handle exceptions. SetUnhandledExceptionFilter( CreateMiniDump ); // check if Boxee is already running bool AlreadyRunning; HANDLE hMutexOneInstance = ::CreateMutex( NULL, FALSE, _T("BOXEE-4B71588F-DDBB-40da-AD86-3187B70AA5A3")); AlreadyRunning = ( ::GetLastError() == ERROR_ALREADY_EXISTS || ::GetLastError() == ERROR_ACCESS_DENIED); // The call fails with ERROR_ACCESS_DENIED if the Mutex was // created in a different users session because of passing // NULL for the SECURITY_ATTRIBUTES on Mutex creation); #ifndef _DEBUG if ( AlreadyRunning ) { HWND m_hwnd = FindWindow("Boxee","Boxee"); if(m_hwnd != NULL) { // switch to the running instance ShowWindow(m_hwnd,SW_RESTORE); SetForegroundWindow(m_hwnd); } return 0; } #endif if(CWIN32Util::GetDesktopColorDepth() < 32) { //FIXME: replace it by a SDL window for all ports MessageBox(NULL, "Desktop Color Depth isn't 32Bit", "BOXEE: Fatal Error", MB_OK|MB_ICONERROR); return 0; } // parse the command line LPWSTR *szArglist; int nArgs; g_advancedSettings.m_startFullScreen = false; szArglist = CommandLineToArgvW(strcl.c_str(), &nArgs); if(szArglist != NULL) { for(int i=0;i<nArgs;i++) { CStdStringW strArgW(szArglist[i]); if(strArgW.Equals(L"-fs")) g_advancedSettings.m_startFullScreen = true; else if(strArgW.Equals(L"-p") || strArgW.Equals(L"--portable")) g_application.EnablePlatformDirectories(false); else if(strArgW.Equals(L"-d")) { if(++i < nArgs) { int iSleep = _wtoi(szArglist[i]); if(iSleep > 0 && iSleep < 360) Sleep(iSleep*1000); else --i; } } // this flag indicate boxee was started from the registry on user login // We create a delay to make sure initialization succeed. else if (strArgW.Equals(L"-startup")) { Sleep(5000); } } LocalFree(szArglist); } // we don't want to see the "no disc in drive" windows message box SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOOPENFILEERRORBOX); // Create and run the app if (!SUCCEEDED(g_application.Create(NULL))) { return 1; } g_application.Run(); char *a = new char[50]; return 0; }
/// Application entry point int main(int argc, char** argv) { Config config; int option_index = 0; bool use_gdbstub = Settings::values.use_gdbstub; u32 gdb_port = static_cast<u32>(Settings::values.gdbstub_port); char* endarg; #ifdef _WIN32 int argc_w; auto argv_w = CommandLineToArgvW(GetCommandLineW(), &argc_w); if (argv_w == nullptr) { LOG_CRITICAL(Frontend, "Failed to get command line arguments"); return -1; } #endif std::string boot_filename; static struct option long_options[] = { {"gdbport", required_argument, 0, 'g'}, {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'}, {0, 0, 0, 0}, }; while (optind < argc) { char arg = getopt_long(argc, argv, "g:hv", long_options, &option_index); if (arg != -1) { switch (arg) { case 'g': errno = 0; gdb_port = strtoul(optarg, &endarg, 0); use_gdbstub = true; if (endarg == optarg) errno = EINVAL; if (errno != 0) { perror("--gdbport"); exit(1); } break; case 'h': PrintHelp(argv[0]); return 0; case 'v': PrintVersion(); return 0; } } else { #ifdef _WIN32 boot_filename = Common::UTF16ToUTF8(argv_w[optind]); #else boot_filename = argv[optind]; #endif optind++; } } #ifdef _WIN32 LocalFree(argv_w); #endif Log::Filter log_filter(Log::Level::Debug); Log::SetFilter(&log_filter); MicroProfileOnThreadCreate("EmuThread"); SCOPE_EXIT({ MicroProfileShutdown(); });
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int argc, i; UInt16 **argvUnicode; UInt8 **argvUTF8; int result; HANDLE startupCheck; UInt16 *moduleFileName, *mutexName; DWORD lastError; const UInt16 *kMutexBaseName = L"Fsk-startup-check-"; #if USE_TIMEBOMB if (!CheckDate()) return -1; #endif FskMainSetHInstance(hInstance); argvUnicode = CommandLineToArgvW(GetCommandLineW(), &argc); argvUTF8 = (UInt8 **)calloc(sizeof(UInt16 *), argc); for (i= 0; i< argc; i++) { int charCount = wcslen(argvUnicode[i]); argvUTF8[i] = malloc((charCount + 1) * 3); WideCharToMultiByte(CP_UTF8, 0, argvUnicode[i], charCount + 1, argvUTF8[i], (charCount + 1) * 3, NULL, NULL); } GlobalFree(argvUnicode); moduleFileName = (UInt16 *)malloc(sizeof(UInt16) * 520); GetModuleFileNameW(0, moduleFileName, 512); mutexName = malloc((1 + wcslen(moduleFileName) + wcslen(kMutexBaseName)) * 2); wcscpy(mutexName, kMutexBaseName); wcscat(mutexName, wcsrchr(moduleFileName, '\\') + 1); free(moduleFileName); startupCheck = CreateMutexW(0, true, mutexName); lastError = GetLastError(); free(mutexName); for (i = 0; i < argc; i++){ if(strcmp(argvUTF8[i],"-new-instance")==0) { lastError=0; break; } } switch (lastError) { case 0: result = doMain(kFskMainNetwork | kFskMainServer, argc, argvUTF8); break; case ERROR_ALREADY_EXISTS: { char *fileList; UInt32 fileListSize; result = 0; FskUtilsSetArgs(argc, argvUTF8); fileList = FskUtilsGetFileArgs(&fileListSize); if (NULL != fileList) { char *fileName; HANDLE hMapFile; char number[64]; SInt32 val; val = FskRandom() ^ GetTickCount(); FskStrNumToStr(val, number, sizeof(number)); fileName = FskStrDoCat("FskFileOpen-", number); hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, fileListSize, fileName); if ((NULL != hMapFile) && (INVALID_HANDLE_VALUE != hMapFile)) { unsigned char *pBuf = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, fileListSize); if (NULL != pBuf) { memmove(pBuf, fileList, fileListSize); UnmapViewOfFile(pBuf); PostMessage(FindWindow("projectf-utils", NULL), RegisterWindowMessage("FskOpenFiles"), 0, val); } CloseHandle(hMapFile); } FskMemPtrDispose(fileName); } } break; default: result = -1; break; } CloseHandle(startupCheck); for (i = 0; i < argc; i++) free(argvUTF8[i]); free(argvUTF8); return result; }
int main(int argc, char* argv[]) { jq_state *jq = NULL; int ret = 0; int compiled = 0; int parser_flags = 0; int nfiles = 0; int badwrite; jv program_arguments = jv_array(); #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); fflush(stdout); fflush(stderr); _setmode(fileno(stdout), _O_TEXT | _O_U8TEXT); _setmode(fileno(stderr), _O_TEXT | _O_U8TEXT); int wargc; wchar_t **wargv = CommandLineToArgvW(GetCommandLineW(), &wargc); assert(wargc == argc); size_t arg_sz; for (int i = 0; i < argc; i++) { argv[i] = alloca((arg_sz = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, 0, 0, 0, 0))); WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, argv[i], arg_sz, 0, 0); } #endif if (argc) progname = argv[0]; jq = jq_init(); if (jq == NULL) { perror("malloc"); ret = 2; goto out; } int dumpopts = JV_PRINT_INDENT_FLAGS(2); const char* program = 0; jv_extra_opt extra_opt; extra_opt.array_fold=0; extra_opt.array_fold_indent=1; jq_util_input_state *input_state = jq_util_input_init(NULL, NULL); // XXX add err_cb int further_args_are_files = 0; int jq_flags = 0; size_t short_opts = 0; jv lib_search_paths = jv_null(); for (int i=1; i<argc; i++, short_opts = 0) { if (further_args_are_files) { jq_util_input_add_input(input_state, argv[i]); nfiles++; } else if (!strcmp(argv[i], "--")) { if (!program) usage(2); further_args_are_files = 1; } else if (!isoptish(argv[i])) { if (program) { jq_util_input_add_input(input_state, argv[i]); nfiles++; } else { program = argv[i]; } } else { if (argv[i][1] == 'L') { if (jv_get_kind(lib_search_paths) == JV_KIND_NULL) lib_search_paths = jv_array(); if (argv[i][2] != 0) { // -Lname (faster check than strlen) lib_search_paths = jv_array_append(lib_search_paths, jq_realpath(jv_string(argv[i]+2))); } else if (i >= argc - 1) { fprintf(stderr, "-L takes a parameter: (e.g. -L /search/path or -L/search/path)\n"); die(); } else { lib_search_paths = jv_array_append(lib_search_paths, jq_realpath(jv_string(argv[i+1]))); i++; } continue; } if (isoption(argv[i], 0, "fold", &short_opts)) { if (i >= argc - 1) { fprintf(stderr, "%s: --fold takes one parameter\n", progname); die(); } extra_opt.array_fold = atoi(argv[i+1]); if (extra_opt.array_fold < 1 || extra_opt.array_fold > 255) { fprintf(stderr, "%s: --fold takes a number between 1 and 255\n", progname); die(); } i++; if (!short_opts) continue; } if (isoption(argv[i], 's', "slurp", &short_opts)) { options |= SLURP; if (!short_opts) continue; } if (isoption(argv[i], 'r', "raw-output", &short_opts)) { options |= RAW_OUTPUT; if (!short_opts) continue; } if (isoption(argv[i], 'c', "compact-output", &short_opts)) { dumpopts &= ~(JV_PRINT_TAB | JV_PRINT_INDENT_FLAGS(7)); if (!short_opts) continue; } if (isoption(argv[i], 'C', "color-output", &short_opts)) { options |= COLOR_OUTPUT; if (!short_opts) continue; } if (isoption(argv[i], 'M', "monochrome-output", &short_opts)) { options |= NO_COLOR_OUTPUT; if (!short_opts) continue; } if (isoption(argv[i], 'a', "ascii-output", &short_opts)) { options |= ASCII_OUTPUT; if (!short_opts) continue; } if (isoption(argv[i], 0, "unbuffered", &short_opts)) { options |= UNBUFFERED_OUTPUT; if (!short_opts) continue; } if (isoption(argv[i], 'S', "sort-keys", &short_opts)) { options |= SORTED_OUTPUT; if (!short_opts) continue; } if (isoption(argv[i], 'R', "raw-input", &short_opts)) { options |= RAW_INPUT; if (!short_opts) continue; } if (isoption(argv[i], 'n', "null-input", &short_opts)) { options |= PROVIDE_NULL; if (!short_opts) continue; } if (isoption(argv[i], 'f', "from-file", &short_opts)) { options |= FROM_FILE; if (!short_opts) continue; } if (isoption(argv[i], 'j', "join-output", &short_opts)) { options |= RAW_OUTPUT | RAW_NO_LF; if (!short_opts) continue; } if (isoption(argv[i], 0, "tab", &short_opts)) { dumpopts &= ~JV_PRINT_INDENT_FLAGS(7); dumpopts |= JV_PRINT_TAB | JV_PRINT_PRETTY; if (!short_opts) continue; } if (isoption(argv[i], 0, "indent", &short_opts)) { if (i >= argc - 1) { fprintf(stderr, "%s: --indent takes one parameter\n", progname); die(); } dumpopts &= ~(JV_PRINT_TAB | JV_PRINT_INDENT_FLAGS(7)); int indent = atoi(argv[i+1]); if (indent < -1 || indent > 7) { fprintf(stderr, "%s: --indent takes a number between -1 and 7\n", progname); die(); } dumpopts |= JV_PRINT_INDENT_FLAGS(indent); i++; if (!short_opts) continue; } if (isoption(argv[i], 0, "seq", &short_opts)) { options |= SEQ; if (!short_opts) continue; } if (isoption(argv[i], 0, "stream", &short_opts)) { parser_flags |= JV_PARSE_STREAMING; if (!short_opts) continue; } if (isoption(argv[i], 0, "stream-errors", &short_opts)) { parser_flags |= JV_PARSE_STREAM_ERRORS; if (!short_opts) continue; } if (isoption(argv[i], 'e', "exit-status", &short_opts)) { options |= EXIT_STATUS; if (!short_opts) continue; } // FIXME: For --arg* we should check that the varname is acceptable if (isoption(argv[i], 0, "arg", &short_opts)) { if (i >= argc - 2) { fprintf(stderr, "%s: --arg takes two parameters (e.g. --arg varname value)\n", progname); die(); } jv arg = jv_object(); arg = jv_object_set(arg, jv_string("name"), jv_string(argv[i+1])); arg = jv_object_set(arg, jv_string("value"), jv_string(argv[i+2])); program_arguments = jv_array_append(program_arguments, arg); i += 2; // skip the next two arguments if (!short_opts) continue; } if (isoption(argv[i], 0, "argjson", &short_opts)) { if (i >= argc - 2) { fprintf(stderr, "%s: --argjson takes two parameters (e.g. --argjson varname text)\n", progname); die(); } jv v = jv_parse(argv[i+2]); if (!jv_is_valid(v)) { fprintf(stderr, "%s: invalid JSON text passed to --argjson\n", progname); die(); } jv arg = jv_object(); arg = jv_object_set(arg, jv_string("name"), jv_string(argv[i+1])); arg = jv_object_set(arg, jv_string("value"), v); program_arguments = jv_array_append(program_arguments, arg); i += 2; // skip the next two arguments if (!short_opts) continue; } if (isoption(argv[i], 0, "argfile", &short_opts) || isoption(argv[i], 0, "slurpfile", &short_opts)) { const char *which; if (isoption(argv[i], 0, "argfile", &short_opts)) which = "argfile"; else which = "slurpfile"; if (i >= argc - 2) { fprintf(stderr, "%s: --%s takes two parameters (e.g. --%s varname filename)\n", progname, which, which); die(); } jv arg = jv_object(); arg = jv_object_set(arg, jv_string("name"), jv_string(argv[i+1])); jv data = jv_load_file(argv[i+2], 0); if (!jv_is_valid(data)) { data = jv_invalid_get_msg(data); fprintf(stderr, "%s: Bad JSON in --%s %s %s: %s\n", progname, which, argv[i+1], argv[i+2], jv_string_value(data)); jv_free(data); jv_free(arg); ret = 2; goto out; } if (isoption(argv[i], 0, "argfile", &short_opts) && jv_get_kind(data) == JV_KIND_ARRAY && jv_array_length(jv_copy(data)) == 1) data = jv_array_get(data, 0); arg = jv_object_set(arg, jv_string("value"), data); program_arguments = jv_array_append(program_arguments, arg); i += 2; // skip the next two arguments if (!short_opts) continue; } if (isoption(argv[i], 0, "debug-dump-disasm", &short_opts)) { options |= DUMP_DISASM; if (!short_opts) continue; } if (isoption(argv[i], 0, "debug-trace", &short_opts)) { jq_flags |= JQ_DEBUG_TRACE; if (!short_opts) continue; } if (isoption(argv[i], 'h', "help", &short_opts)) { usage(0); if (!short_opts) continue; } if (isoption(argv[i], 'V', "version", &short_opts)) { printf("jq-%s\n", JQ_VERSION); ret = 0; goto out; } if (isoption(argv[i], 0, "run-tests", &short_opts)) { i++; // XXX Pass program_arguments, even a whole jq_state *, through; // could be useful for testing ret = jq_testsuite(lib_search_paths, (options & DUMP_DISASM) || (jq_flags & JQ_DEBUG_TRACE), argc - i, argv + i); goto out; } // check for unknown options... if this argument was a short option if (strlen(argv[i]) != short_opts + 1) { fprintf(stderr, "%s: Unknown option %s\n", progname, argv[i]); die(); } } } if (isatty(fileno(stdout))) { dumpopts |= JV_PRINT_ISATTY; #ifndef WIN32 /* Disable color by default on Windows builds as Windows terminals tend not to display it correctly */ dumpopts |= JV_PRINT_COLOR; #endif } if (options & SORTED_OUTPUT) dumpopts |= JV_PRINT_SORTED; if (options & ASCII_OUTPUT) dumpopts |= JV_PRINT_ASCII; if (options & COLOR_OUTPUT) dumpopts |= JV_PRINT_COLOR; if (options & NO_COLOR_OUTPUT) dumpopts &= ~JV_PRINT_COLOR; if (jv_get_kind(lib_search_paths) == JV_KIND_NULL) { // Default search path list lib_search_paths = JV_ARRAY(jv_string("~/.jq"), jv_string("$ORIGIN/../lib/jq"), jv_string("$ORIGIN/lib")); } jq_set_attr(jq, jv_string("JQ_LIBRARY_PATH"), lib_search_paths); char *origin = strdup(argv[0]); if (origin == NULL) { fprintf(stderr, "Error: out of memory\n"); exit(1); } jq_set_attr(jq, jv_string("JQ_ORIGIN"), jv_string(dirname(origin))); free(origin); if (strchr(JQ_VERSION, '-') == NULL) jq_set_attr(jq, jv_string("VERSION_DIR"), jv_string(JQ_VERSION)); else jq_set_attr(jq, jv_string("VERSION_DIR"), jv_string_fmt("%.*s-master", (int)(strchr(JQ_VERSION, '-') - JQ_VERSION), JQ_VERSION)); #if (!defined(WIN32) && defined(HAVE_ISATTY)) || defined(HAVE__ISATTY) #if defined(HAVE__ISATTY) && defined(isatty) #undef isatty #define isatty _isatty #endif if (!program && isatty(STDOUT_FILENO) && !isatty(STDIN_FILENO)) program = "."; #endif if (!program) usage(2); if (options & FROM_FILE) { char *program_origin = strdup(program); if (program_origin == NULL) { perror("malloc"); exit(2); } jv data = jv_load_file(program, 1); if (!jv_is_valid(data)) { data = jv_invalid_get_msg(data); fprintf(stderr, "%s: %s\n", progname, jv_string_value(data)); jv_free(data); ret = 2; goto out; } jq_set_attr(jq, jv_string("PROGRAM_ORIGIN"), jq_realpath(jv_string(dirname(program_origin)))); compiled = jq_compile_args(jq, jv_string_value(data), jv_copy(program_arguments)); free(program_origin); jv_free(data); } else { jq_set_attr(jq, jv_string("PROGRAM_ORIGIN"), jq_realpath(jv_string("."))); // XXX is this good? compiled = jq_compile_args(jq, program, jv_copy(program_arguments)); } if (!compiled){ ret = 3; goto out; } if (options & DUMP_DISASM) { jq_dump_disassembly(jq, 0); printf("\n"); } if ((options & SEQ)) parser_flags |= JV_PARSE_SEQ; if ((options & RAW_INPUT)) jq_util_input_set_parser(input_state, NULL, (options & SLURP) ? 1 : 0); else jq_util_input_set_parser(input_state, jv_parser_new(parser_flags), (options & SLURP) ? 1 : 0); // Let jq program read from inputs jq_set_input_cb(jq, jq_util_input_next_input_cb, input_state); // Let jq program call `debug` builtin and have that go somewhere jq_set_debug_cb(jq, debug_cb, &dumpopts); if (nfiles == 0) jq_util_input_add_input(input_state, "-"); if (options & PROVIDE_NULL) { if (extra_opt.array_fold==0) { ret = process(jq, jv_null(), jq_flags, dumpopts); } else { ret = process_extra_opt(jq, jv_null(), jq_flags, dumpopts, &extra_opt); } } else { jv value; while (jq_util_input_errors(input_state) == 0 && (jv_is_valid((value = jq_util_input_next_input(input_state))) || jv_invalid_has_msg(jv_copy(value)))) { if (jv_is_valid(value)) { if (extra_opt.array_fold==0) { ret = process(jq, value, jq_flags, dumpopts); } else { ret = process_extra_opt(jq, value, jq_flags, dumpopts, &extra_opt); } continue; } // Parse error jv msg = jv_invalid_get_msg(value); if (!(options & SEQ)) { // --seq -> errors are not fatal ret = 4; fprintf(stderr, "parse error: %s\n", jv_string_value(msg)); jv_free(msg); break; } fprintf(stderr, "ignoring parse error: %s\n", jv_string_value(msg)); jv_free(msg); } } if (jq_util_input_errors(input_state) != 0) ret = 2; out: badwrite = ferror(stdout); if (fclose(stdout)!=0 || badwrite) { fprintf(stderr,"Error: writing output failed: %s\n", strerror(errno)); ret = 2; } jv_free(program_arguments); jq_util_input_free(&input_state); jq_teardown(&jq); if (ret >= 10 && (options & EXIT_STATUS)) return ret - 10; if (ret >= 10) return 0; return ret; }
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { static HWND hList; static HFONT hFont; static DWORD dwSplitLine; switch (msg) { case WM_CREATE: InitCommonControls(); hFont = CreateFont(26, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, TEXT("MS ゴシック")); hList = CreateWindowEx(0, TEXT("LISTBOX"), 0, WS_VISIBLE | WS_CHILD | WS_VSCROLL | LBS_NOINTEGRALHEIGHT | LBS_OWNERDRAWFIXED | LBS_EXTENDEDSEL | LBS_MULTIPLESEL, 0, 0, 0, 0, hWnd, (HMENU)IDC_LIST, ((LPCREATESTRUCT)lParam)->hInstance, 0); SendMessage(hList, WM_SETFONT, (WPARAM)hFont, 0); EditDefProc = (WNDPROC)SetWindowLong(hList, GWL_WNDPROC, (LONG)ListProc); { int n; LPTSTR* argv = CommandLineToArgvW(GetCommandLine(), &n); for (int i = 1; i<n; i++) { CalcSha1(hList, argv[i]); const DWORD dwTempWidth = GetStringWidth(hList, PathFindFileName(argv[i])); if (dwTempWidth>dwSplitLine)dwSplitLine = dwTempWidth; } if (argv) GlobalFree(argv); const DWORD dwLastItem = SendMessage(hList, LB_GETCOUNT, 0, 0); SendMessage(hList, LB_SELITEMRANGE, TRUE, MAKELPARAM(0, dwLastItem - 1)); } DragAcceptFiles(hWnd, TRUE); break; case WM_ERASEBKGND: return 1; case WM_COMMAND: switch (LOWORD(wParam)) { case ID_COPYTOCLIPBOARD: { const int nSelItems = SendMessage(hList, LB_GETSELCOUNT, 0, 0); if (nSelItems > 0) { int* pBuffer = (int*)GlobalAlloc(0, sizeof(int) * nSelItems); SendMessage(hList, LB_GETSELITEMS, nSelItems, (LPARAM)pBuffer); INT nLen = 0; for (int i = 0; i < nSelItems; i++) { DATA* pData = (DATA*)SendMessage(hList, LB_GETITEMDATA, pBuffer[i], 0); nLen += lstrlen(pData->szFilePath); nLen += lstrlen(pData->szHashValue); nLen += 3; } HGLOBAL hMem = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, sizeof(TCHAR)*(nLen + 1)); LPTSTR lpszBuflpszBuf = (LPTSTR)GlobalLock(hMem); lpszBuflpszBuf[0] = 0; for (int i = 0; i < nSelItems; i++) { DATA* pData = (DATA*)SendMessage(hList, LB_GETITEMDATA, pBuffer[i], 0); lstrcat(lpszBuflpszBuf, pData->szFilePath); lstrcat(lpszBuflpszBuf, TEXT("\t")); lstrcat(lpszBuflpszBuf, pData->szHashValue); lstrcat(lpszBuflpszBuf, TEXT("\r\n")); } lpszBuflpszBuf[nLen] = 0; GlobalFree(pBuffer); GlobalUnlock(hMem); OpenClipboard(NULL); EmptyClipboard(); SetClipboardData(CF_UNICODETEXT, hMem); CloseClipboard(); } } break; case ID_SELECTALL: SendMessage(hList, LB_SETSEL, 1, -1); break; case ID_DELETE: { const int nSelItems = SendMessage(hList, LB_GETSELCOUNT, 0, 0); if (nSelItems > 0) { int* pBuffer = (int*)GlobalAlloc(0, sizeof(int) * nSelItems); SendMessage(hList, LB_GETSELITEMS, nSelItems, (LPARAM)pBuffer); for (int i = nSelItems - 1; i >= 0; i--) { DeleteItem(hList, pBuffer[i]); } GlobalFree(pBuffer); dwSplitLine = 0; const int nCount = SendMessage(hList, LB_GETCOUNT, 0, 0); for (int i = 0; i < nCount; i++) { const DATA* pData = (const DATA*)SendMessage(hList, LB_GETITEMDATA, i, 0); const DWORD dwTemp = GetStringWidth(hList, PathFindFileName(pData->szFilePath)); if (dwTemp>dwSplitLine)dwSplitLine = dwTemp; } } } break; } break; case WM_MEASUREITEM: ((LPMEASUREITEMSTRUCT)lParam)->itemHeight = 32; return 0; case WM_SIZE: MoveWindow(hList, 0, 0, LOWORD(lParam), HIWORD(lParam), 0); break; case WM_EXITTHREAD: { DATA* pData = (DATA*)lParam; WaitForSingleObject(pData->hThread, INFINITE); CloseHandle(pData->hThread); pData->hThread = 0; InvalidateRect(hList, 0, 0); } break; case WM_DRAWITEM: if ((UINT)wParam == IDC_LIST) { LPDRAWITEMSTRUCT lpdis = (LPDRAWITEMSTRUCT)lParam; if (lpdis->itemID == -1) { if (!SendMessage(hList, LB_GETCOUNT, 0, 0)) { RECT rect; GetClientRect(hList, &rect); HBRUSH hBrush = CreateSolidBrush(GetSysColor(COLOR_WINDOW)); FillRect(lpdis->hDC, &rect, hBrush); DeleteObject(hBrush); SetTextColor(lpdis->hDC, GetSysColor(COLOR_GRAYTEXT)); DrawText(lpdis->hDC, TEXT("ここにファイルをドラッグ"), -1, &rect, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_CENTER); } break; } DATA* pData = (DATA*)SendMessage(hList, LB_GETITEMDATA, lpdis->itemID, 0); if ((lpdis->itemState)&(ODS_SELECTED)) { SetBkColor(lpdis->hDC, GetSysColor(COLOR_HIGHLIGHT)); SetTextColor(lpdis->hDC, GetSysColor(COLOR_HIGHLIGHTTEXT)); } else { SetBkColor(lpdis->hDC, GetSysColor(COLOR_WINDOW)); SetTextColor(lpdis->hDC, GetSysColor(COLOR_WINDOWTEXT)); } RECT rect1 = lpdis->rcItem; rect1.right = dwSplitLine + 16; const LPCTSTR lpszFileName = PathFindFileName(pData->szFilePath); SetTextAlign(lpdis->hDC, TA_RIGHT); ExtTextOut(lpdis->hDC, rect1.right, rect1.top + 4, ETO_OPAQUE, &rect1, lpszFileName, lstrlen(lpszFileName), 0); RECT rect2 = lpdis->rcItem; rect2.left = dwSplitLine + 16; SetTextAlign(lpdis->hDC, TA_LEFT); ExtTextOut(lpdis->hDC, rect2.left + 32, rect2.top + 4, ETO_OPAQUE, &rect2, pData->szHashValue, lstrlen(pData->szHashValue), 0); } break; case WM_DROPFILES: { HDROP hDrop = (HDROP)wParam; TCHAR szFileName[MAX_PATH]; UINT i; const DWORD dwFastItem = SendMessage(hList, LB_GETCOUNT, 0, 0); SendMessage(hList, LB_SETSEL, 0, -1); const UINT nFiles = DragQueryFile((HDROP)hDrop, 0xFFFFFFFF, NULL, 0); for (i = 0; i<nFiles; i++) { DragQueryFile(hDrop, i, szFileName, sizeof(szFileName)); CalcSha1(hList, szFileName); const DWORD dwTempWidth = GetStringWidth(hList, PathFindFileName(szFileName)); if (dwTempWidth>dwSplitLine)dwSplitLine = dwTempWidth; } DragFinish(hDrop); const DWORD dwLastItem = SendMessage(hList, LB_GETCOUNT, 0, 0); SendMessage(hList, LB_SELITEMRANGE, TRUE, MAKELPARAM(dwFastItem, dwLastItem - 1)); SetForegroundWindow(hWnd); } break; case WM_CLOSE: DestroyWindow(hWnd); break; case WM_DESTROY: { const int nCount = SendMessage(hList, LB_GETCOUNT, 0, 0); for (int i = nCount - 1; i >= 0; i--) { DeleteItem(hList, i); } } DeleteObject(hFont); PostQuitMessage(0); break; default: return DefDlgProc(hWnd, msg, wParam, lParam); } return 0; }
BOOL CTortoiseProcApp::InitInstance() { CheckUpgrade(); CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows)); CMFCButton::EnableWindowsTheming(); Gdiplus::GdiplusStartupInput gdiplusStartupInput; Gdiplus::GdiplusStartup(&m_gdiplusToken,&gdiplusStartupInput,NULL); //set the resource dll for the required language CRegDWORD loc = CRegDWORD(_T("Software\\TortoiseGit\\LanguageID"), 1033); long langId = loc; CString langDll; CStringA langpath = CStringA(CPathUtils::GetAppParentDirectory()); langpath += "Languages"; HINSTANCE hInst = NULL; do { langDll.Format(_T("%sLanguages\\TortoiseProc%d.dll"), (LPCTSTR)CPathUtils::GetAppParentDirectory(), langId); hInst = LoadLibrary(langDll); CString sVer = _T(STRPRODUCTVER); CString sFileVer = CPathUtils::GetVersionFromFile(langDll); if (sFileVer.Compare(sVer)!=0) { FreeLibrary(hInst); hInst = NULL; } if (hInst != NULL) { AfxSetResourceHandle(hInst); } else { DWORD lid = SUBLANGID(langId); lid--; if (lid > 0) { langId = MAKELANGID(PRIMARYLANGID(langId), lid); } else langId = 0; } } while ((hInst == NULL) && (langId != 0)); TCHAR buf[6]; _tcscpy_s(buf, _T("en")); langId = loc; // MFC uses a help file with the same name as the application by default, // which means we have to change that default to our language specific help files CString sHelppath = CPathUtils::GetAppDirectory() + _T("TortoiseGit_en.chm"); free((void*)m_pszHelpFilePath); m_pszHelpFilePath=_tcsdup(sHelppath); sHelppath = CPathUtils::GetAppParentDirectory() + _T("Languages\\TortoiseGit_en.chm"); do { CString sLang = _T("_"); if (GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO639LANGNAME, buf, _countof(buf))) { sLang += buf; sHelppath.Replace(_T("_en"), sLang); if (PathFileExists(sHelppath)) { free((void*)m_pszHelpFilePath); m_pszHelpFilePath=_tcsdup(sHelppath); break; } } sHelppath.Replace(sLang, _T("_en")); if (GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO3166CTRYNAME, buf, _countof(buf))) { sLang += _T("_"); sLang += buf; sHelppath.Replace(_T("_en"), sLang); if (PathFileExists(sHelppath)) { free((void*)m_pszHelpFilePath); m_pszHelpFilePath=_tcsdup(sHelppath); break; } } sHelppath.Replace(sLang, _T("_en")); DWORD lid = SUBLANGID(langId); lid--; if (lid > 0) { langId = MAKELANGID(PRIMARYLANGID(langId), lid); } else langId = 0; } while (langId); setlocale(LC_ALL, ""); if(!CheckMsysGitDir()) { UINT ret = CMessageBox::Show(NULL, IDS_PROC_NOMSYSGIT, IDS_APPNAME, 3, IDI_HAND, IDS_PROC_SETMSYSGITPATH, IDS_PROC_GOTOMSYSGITWEBSITE, IDS_ABORTBUTTON); if(ret == 2) { ShellExecute(NULL, NULL, _T("http://code.google.com/p/msysgit/"), NULL, NULL, SW_SHOW); } else if(ret == 1) { // open settings dialog CSinglePropSheetDlg(CString(MAKEINTRESOURCE(IDS_PROC_SETTINGS_TITLE)), new CSetMainPage(), this->GetMainWnd()).DoModal(); } return FALSE; } if (CAppUtils::GetMsysgitVersion() < 0x01070a00) { int ret = CMessageBox::ShowCheck(NULL, IDS_PROC_OLDMSYSGIT, IDS_APPNAME, 1, IDI_EXCLAMATION, IDS_PROC_GOTOMSYSGITWEBSITE, IDS_ABORTBUTTON, IDS_IGNOREBUTTON, _T("OldMsysgitVersionWarning"), IDS_PROC_NOTSHOWAGAINIGNORE); if (ret == 1) { CMessageBox::RemoveRegistryKey(_T("OldMsysgitVersionWarning")); // only store answer if it is "Ignore" ShellExecute(NULL, NULL, _T("http://code.google.com/p/msysgit/"), NULL, NULL, SW_SHOW); return FALSE; } else if (ret == 2) { CMessageBox::RemoveRegistryKey(_T("OldMsysgitVersionWarning")); // only store answer if it is "Ignore" return FALSE; } } // InitCommonControls() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX used = { sizeof(INITCOMMONCONTROLSEX), ICC_ANIMATE_CLASS | ICC_BAR_CLASSES | ICC_COOL_CLASSES | ICC_DATE_CLASSES | ICC_HOTKEY_CLASS | ICC_INTERNET_CLASSES | ICC_LISTVIEW_CLASSES | ICC_NATIVEFNTCTL_CLASS | ICC_PAGESCROLLER_CLASS | ICC_PROGRESS_CLASS | ICC_TAB_CLASSES | ICC_TREEVIEW_CLASSES | ICC_UPDOWN_CLASS | ICC_USEREX_CLASSES | ICC_WIN95_CLASSES }; InitCommonControlsEx(&used); AfxOleInit(); AfxEnableControlContainer(); AfxInitRichEdit2(); CWinAppEx::InitInstance(); SetRegistryKey(_T("TortoiseGit")); AfxGetApp()->m_pszProfileName = _tcsdup(_T("TortoiseProc")); // w/o this ResizableLib will store data under TortoiseGitProc which is not compatible with older versions CCmdLineParser parser(AfxGetApp()->m_lpCmdLine); hWndExplorer = NULL; CString sVal = parser.GetVal(_T("hwnd")); if (!sVal.IsEmpty()) hWndExplorer = (HWND)_ttoi64(sVal); while (GetParent(hWndExplorer)!=NULL) hWndExplorer = GetParent(hWndExplorer); if (!IsWindow(hWndExplorer)) { hWndExplorer = NULL; } // if HKCU\Software\TortoiseGit\Debug is not 0, show our command line // in a message box if (CRegDWORD(_T("Software\\TortoiseGit\\Debug"), FALSE)==TRUE) AfxMessageBox(AfxGetApp()->m_lpCmdLine, MB_OK | MB_ICONINFORMATION); if ( parser.HasKey(_T("path")) && parser.HasKey(_T("pathfile"))) { CMessageBox::Show(NULL, IDS_ERR_INVALIDPATH, IDS_APPNAME, MB_ICONERROR); return FALSE; } CTGitPath cmdLinePath; CTGitPathList pathList; if (g_sGroupingUUID.IsEmpty()) g_sGroupingUUID = parser.GetVal(L"groupuuid"); if ( parser.HasKey(_T("pathfile")) ) { CString sPathfileArgument = CPathUtils::GetLongPathname(parser.GetVal(_T("pathfile"))); cmdLinePath.SetFromUnknown(sPathfileArgument); if (pathList.LoadFromFile(cmdLinePath)==false) return FALSE; // no path specified! if ( parser.HasKey(_T("deletepathfile")) ) { // We can delete the temporary path file, now that we've loaded it ::DeleteFile(cmdLinePath.GetWinPath()); } // This was a path to a temporary file - it's got no meaning now, and // anybody who uses it again is in for a problem... cmdLinePath.Reset(); } else { CString sPathArgument = CPathUtils::GetLongPathname(parser.GetVal(_T("path"))); if (parser.HasKey(_T("expaths"))) { // an /expaths param means we're started via the buttons in our Win7 library // and that means the value of /expaths is the current directory, and // the selected paths are then added as additional parameters but without a key, only a value // because of the "strange treatment of quotation marks and backslashes by CommandLineToArgvW" // we have to escape the backslashes first. Since we're only dealing with paths here, that's // a save bet. // Without this, a command line like: // /command:commit /expaths:"D:\" "D:\Utils" // would fail because the "D:\" is treated as the backslash being the escape char for the quotation // mark and we'd end up with: // argv[1] = /command:commit // argv[2] = /expaths:D:" D:\Utils // See here for more details: http://blogs.msdn.com/b/oldnewthing/archive/2010/09/17/10063629.aspx CString cmdLine = GetCommandLineW(); cmdLine.Replace(L"\\", L"\\\\"); int nArgs = 0; LPWSTR *szArglist = CommandLineToArgvW(cmdLine, &nArgs); if (szArglist) { // argument 0 is the process path, so start with 1 for (int i = 1; i < nArgs; ++i) { if (szArglist[i][0] != '/') { if (!sPathArgument.IsEmpty()) sPathArgument += '*'; sPathArgument += szArglist[i]; } } sPathArgument.Replace(L"\\\\", L"\\"); } LocalFree(szArglist); } if (sPathArgument.IsEmpty() && parser.HasKey(L"path")) { CMessageBox::Show(hWndExplorer, IDS_ERR_INVALIDPATH, IDS_APPNAME, MB_ICONERROR); return FALSE; } int asterisk = sPathArgument.Find('*'); cmdLinePath.SetFromUnknown(asterisk >= 0 ? sPathArgument.Left(asterisk) : sPathArgument); pathList.LoadFromAsteriskSeparatedString(sPathArgument); } if (pathList.GetCount() == 0) { pathList.AddPath(CTGitPath::CTGitPath(g_Git.m_CurrentDir)); } // Subversion sometimes writes temp files to the current directory! // Since TSVN doesn't need a specific CWD anyway, we just set it // to the users temp folder: that way, Subversion is guaranteed to // have write access to the CWD { DWORD len = GetCurrentDirectory(0, NULL); if (len) { std::unique_ptr<TCHAR[]> originalCurrentDirectory(new TCHAR[len]); if (GetCurrentDirectory(len, originalCurrentDirectory.get())) { sOrigCWD = originalCurrentDirectory.get(); sOrigCWD = CPathUtils::GetLongPathname(sOrigCWD); } } TCHAR pathbuf[MAX_PATH]; GetTortoiseGitTempPath(MAX_PATH, pathbuf); SetCurrentDirectory(pathbuf); } CheckForNewerVersion(); if (parser.HasVal(_T("configdir"))) { // the user can override the location of the Subversion config directory here CString sConfigDir = parser.GetVal(_T("configdir")); // g_GitGlobal.SetConfigDir(sConfigDir); } CAutoGeneralHandle TGitMutex = ::CreateMutex(NULL, FALSE, _T("TortoiseGitProc.exe")); if (!g_Git.SetCurrentDir(cmdLinePath.GetWinPathString(), parser.HasKey(_T("submodule")) == TRUE)) { for (int i = 0; i < pathList.GetCount(); ++i) if(g_Git.SetCurrentDir(pathList[i].GetWinPath())) break; } if(!g_Git.m_CurrentDir.IsEmpty()) { sOrigCWD = g_Git.m_CurrentDir; SetCurrentDirectory(g_Git.m_CurrentDir); } if (g_sGroupingUUID.IsEmpty()) { CRegStdDWORD groupSetting = CRegStdDWORD(_T("Software\\TortoiseGit\\GroupTaskbarIconsPerRepo"), 3); switch (DWORD(groupSetting)) { case 1: case 2: // implemented differently to TortoiseSVN atm break; case 3: case 4: { CString wcroot; if (g_GitAdminDir.HasAdminDir(g_Git.m_CurrentDir, true, &wcroot)) { git_oid oid; CStringA wcRootA(wcroot); if (!git_odb_hash(&oid, wcRootA.GetBuffer(), wcRootA.GetLength(), GIT_OBJ_BLOB)) { CStringA hash; git_oid_tostr(hash.GetBufferSetLength(GIT_OID_HEXSZ + 1), GIT_OID_HEXSZ + 1, &oid); hash.ReleaseBuffer(); g_sGroupingUUID = hash; } } } } } CString sAppID = GetTaskIDPerUUID(g_sGroupingUUID).c_str(); InitializeJumpList(sAppID); EnsureGitLibrary(false); { CString err; try { // requires CWD to be set CGit::m_LogEncode = CAppUtils::GetLogOutputEncode(); // make sure all config files are read in order to check that none contains an error g_Git.GetConfigValue(_T("doesnot.exist")); } catch (char* msg) { err = CString(msg); } if (!err.IsEmpty()) { UINT choice = CMessageBox::Show(hWndExplorer, err, _T("TortoiseGit"), 1, IDI_ERROR, CString(MAKEINTRESOURCE(IDS_PROC_EDITLOCALGITCONFIG)), CString(MAKEINTRESOURCE(IDS_PROC_EDITGLOBALGITCONFIG)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON))); if (choice == 1) { // open the config file with alternative editor CAppUtils::LaunchAlternativeEditor(g_Git.GetGitLocalConfig()); } else if (choice == 2) { // open the global config file with alternative editor CAppUtils::LaunchAlternativeEditor(g_Git.GetGitGlobalConfig()); } return FALSE; } } // execute the requested command CommandServer server; Command * cmd = server.GetCommand(parser.GetVal(_T("command"))); if (cmd) { cmd->SetExplorerHwnd(hWndExplorer); cmd->SetParser(parser); cmd->SetPaths(pathList, cmdLinePath); retSuccess = cmd->Execute(); delete cmd; } // Look for temporary files left around by TortoiseSVN and // remove them. But only delete 'old' files because some // apps might still be needing the recent ones. { DWORD len = GetTortoiseGitTempPath(0, NULL); std::unique_ptr<TCHAR[]> path(new TCHAR[len + 100]); len = GetTortoiseGitTempPath (len + 100, path.get()); if (len != 0) { CDirFileEnum finder(path.get()); FILETIME systime_; ::GetSystemTimeAsFileTime(&systime_); __int64 systime = (((_int64)systime_.dwHighDateTime)<<32) | ((__int64)systime_.dwLowDateTime); bool isDir; CString filepath; while (finder.NextFile(filepath, &isDir)) { HANDLE hFile = ::CreateFile(filepath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, isDir ? FILE_FLAG_BACKUP_SEMANTICS : NULL, NULL); if (hFile != INVALID_HANDLE_VALUE) { FILETIME createtime_; if (::GetFileTime(hFile, &createtime_, NULL, NULL)) { ::CloseHandle(hFile); __int64 createtime = (((_int64)createtime_.dwHighDateTime)<<32) | ((__int64)createtime_.dwLowDateTime); if ((createtime + 864000000000) < systime) //only delete files older than a day { ::SetFileAttributes(filepath, FILE_ATTRIBUTE_NORMAL); if (isDir) ::RemoveDirectory(filepath); else ::DeleteFile(filepath); } } else ::CloseHandle(hFile); } } } } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; }
INT_PTR CALLBACK MainDlgProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam) { int lbItem=0; HWND hwndList=0; DWORD pid=0xFFFFFFFF; HDC dc = 0; PAINTSTRUCT ps; gHWND = hwndDlg; char szpid[1024] = {0}; switch (message) { case WM_INITDIALOG: // reset progress bar SetProgressBar(0); gProcList = new ProcessList(hwndDlg, hInst); gProcList->FillList(); szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs); if(nArgs > 1) { wsprintf(szpid, "%S", szArglist[1]); gProcList->SetSelectionFromPid(atoi(szpid)); if(nArgs >2 ) { MemorySnapshot *gMemSnap = new MemorySnapshot; char filename[MAX_PATH]; wsprintf(filename, "%S", szArglist[2]); bool res = gMemSnap->Dump(atoi(szpid), filename); SendMessage(hwndDlg, WM_CLOSE, IDC_DUMP, (LPARAM)res); } else { DumpProcess(atoi(szpid)); } } return TRUE; case WM_PAINT: { BeginPaint(gHWND, &ps); RECT rc; GetClientRect(gHWND, &rc); EndPaint(gHWND, &ps); } break; case WM_CLOSE: delete gProcList; gProcList = 0; EndDialog(gHWND, 0); ExitProcess((UINT)lParam); break; case WM_COMMAND: switch(LOWORD(wParam)) { case IDC_DUMP: pid = gProcList->GetSelectedPid(); gProcList->EnableDisable(FALSE); DumpProcess(pid); gProcList->EnableDisable(TRUE); break; case IDC_REFRESH: gProcList->FillList(); break; case IDC_EXIT: SendMessage(gHWND, WM_CLOSE, 0, 0); break; case IDC_PROCLIST: if(pid == 0xFFFFFFFF) { if(gProcList) { pid = gProcList->GetSelectedPid(); } if(pid == 0xFFFFFFFF) EnableWindow(GetDlgItem(gHWND, IDC_DUMP), TRUE); } switch (HIWORD(wParam)) { case LBN_DBLCLK: SendMessage(gHWND, WM_COMMAND, IDC_DUMP, 0); break; default: break; } default: break; } default: break; } // UpdateWindow(gHWND); return (INT_PTR)FALSE; }
int SDL_MAIN_FUNC(int argc, char *argv[]) { CLogger logger; // single instance of logger // Workaround for character encoding in argv on Windows #if PLATFORM_WINDOWS int wargc = 0; wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &wargc); if (wargv == nullptr) { logger.Error("CommandLineToArgvW failed\n"); return 1; } std::vector<std::vector<char>> windowsArgs; for (int i = 0; i < wargc; i++) { std::wstring warg = wargv[i]; std::string arg = CSystemUtilsWindows::UTF8_Encode(warg); std::vector<char> argVec(arg.begin(), arg.end()); argVec.push_back('\0'); windowsArgs.push_back(std::move(argVec)); } auto windowsArgvPtrs = MakeUniqueArray<char*>(wargc); for (int i = 0; i < wargc; i++) windowsArgvPtrs[i] = windowsArgs[i].data(); argv = windowsArgvPtrs.get(); LocalFree(wargv); #endif logger.Info("%s starting\n", COLOBOT_FULLNAME); auto systemUtils = CSystemUtils::Create(); // platform-specific utils systemUtils->Init(); CSignalHandlers::Init(systemUtils.get()); CResourceManager manager(argv[0]); // Initialize static string arrays InitializeRestext(); InitializeEventTypeTexts(); int code = 0; CApplication app(systemUtils.get()); // single instance of the application ParseArgsStatus status = app.ParseArguments(argc, argv); if (status == PARSE_ARGS_FAIL) { systemUtils->SystemDialog(SDT_ERROR, "COLOBOT - Fatal Error", "Invalid commandline arguments!\n"); return app.GetExitCode(); } else if (status == PARSE_ARGS_HELP) { return app.GetExitCode(); } if (! app.Create()) { code = app.GetExitCode(); if (code != 0 && !app.GetErrorMessage().empty()) { systemUtils->SystemDialog(SDT_ERROR, "COLOBOT - Fatal Error", app.GetErrorMessage()); } logger.Info("Didn't run main loop. Exiting with code %d\n", code); return code; } code = app.Run(); logger.Info("Exiting with code %d\n", code); return code; }
//----------------------------------------------------------------------------- // Name: WinMain() // Desc: The application's entry point //----------------------------------------------------------------------------- INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR commandLine, INT ) { // set up some xbmc specific relationships XBMC::Context context; //this can't be set from CAdvancedSettings::Initialize() because it will overwrite //the loglevel set with the --debug flag #ifdef _DEBUG g_advancedSettings.m_logLevel = LOG_LEVEL_DEBUG; g_advancedSettings.m_logLevelHint = LOG_LEVEL_DEBUG; #else g_advancedSettings.m_logLevel = LOG_LEVEL_NORMAL; g_advancedSettings.m_logLevelHint = LOG_LEVEL_NORMAL; #endif CLog::SetLogLevel(g_advancedSettings.m_logLevel); // Initializes CreateMiniDump to handle exceptions. win32_exception::set_version(g_infoManager.GetVersion()); SetUnhandledExceptionFilter( CreateMiniDump ); // check if XBMC is already running CreateMutex(NULL, FALSE, "XBMC Media Center"); if(GetLastError() == ERROR_ALREADY_EXISTS) { HWND m_hwnd = FindWindow("XBMC","XBMC"); if(m_hwnd != NULL) { // switch to the running instance ShowWindow(m_hwnd,SW_RESTORE); SetForegroundWindow(m_hwnd); } return 0; } #ifndef HAS_DX if(CWIN32Util::GetDesktopColorDepth() < 32) { //FIXME: replace it by a SDL window for all ports MessageBox(NULL, "Desktop Color Depth isn't 32Bit", "XBMC: Fatal Error", MB_OK|MB_ICONERROR); return 0; } #endif //Initialize COM CoInitializeEx(NULL, COINIT_MULTITHREADED); // Handle numeric values using the default/POSIX standard setlocale(LC_NUMERIC, "C"); // If the command line passed to WinMain, commandLine, is not "" we need // to process the command line arguments. // Note that commandLine does not include the program name and can be // equal to "" if no arguments were supplied. By contrast GetCommandLineW() // does include the program name and is never equal to "". g_advancedSettings.Initialize(); if (strlen(commandLine) != 0) { int argc; LPWSTR* argvW = CommandLineToArgvW(GetCommandLineW(), &argc); CStdString* strargvA = new CStdString[argc]; const char** argv = (const char**) LocalAlloc(LMEM_FIXED, argc*sizeof(char*)); for (int i = 0; i < argc; i++) { g_charsetConverter.wToUTF8(argvW[i], strargvA[i]); argv[i] = strargvA[i].c_str(); } // Parse the arguments CAppParamParser appParamParser; appParamParser.Parse(argv, argc); // Clean up the storage we've used LocalFree(argvW); LocalFree(argv); delete [] strargvA; } // Initialise Winsock WSADATA wd; WSAStartup(MAKEWORD(2,2), &wd); // use 1 ms timer precision - like SDL initialization used to do timeBeginPeriod(1); // Create and run the app if(!g_application.Create()) { CStdString errorMsg; errorMsg.Format("CApplication::Create() failed - check log file and that it is writable"); MessageBox(NULL, errorMsg.c_str(), "XBMC: Error", MB_OK|MB_ICONERROR); return 0; } #ifndef _DEBUG // we don't want to see the "no disc in drive" windows message box SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOOPENFILEERRORBOX); #endif if (!g_application.CreateGUI()) { CStdString errorMsg; errorMsg.Format("CApplication::CreateGUI() failed - Check log file for display errors"); MessageBox(NULL, errorMsg.c_str(), "XBMC: Error", MB_OK|MB_ICONERROR); return 0; } if (!g_application.Initialize()) { CStdString errorMsg; errorMsg.Format("CApplication::Initialize() failed - Check log file and that it is writable"); MessageBox(NULL, errorMsg.c_str(), "XBMC: Error", MB_OK|MB_ICONERROR); return 0; } g_application.Run(true); // clear previously set timer resolution timeEndPeriod(1); // the end WSACleanup(); CoUninitialize(); return 0; }
int main(int argc, char **argv1) { TSK_VS_INFO *vs; TSK_IMG_TYPE_ENUM imgtype = TSK_IMG_TYPE_DETECT; TSK_VS_TYPE_ENUM vstype = TSK_VS_TYPE_DETECT; int ch; TSK_OFF_T imgaddr = 0; TSK_IMG_INFO *img; TSK_TCHAR **argv; unsigned int ssize = 0; TSK_TCHAR *cp; #ifdef TSK_WIN32 // On Windows, get the wide arguments (mingw doesn't support wmain) argv = CommandLineToArgvW(GetCommandLineW(), &argc); if (argv == NULL) { fprintf(stderr, "Error getting wide arguments\n"); exit(1); } #else argv = (TSK_TCHAR **) argv1; #endif progname = argv[0]; while ((ch = GETOPT(argc, argv, _TSK_T("b:i:o:t:vV"))) > 0) { switch (ch) { case _TSK_T('b'): ssize = (unsigned int) TSTRTOUL(OPTARG, &cp, 0); if (*cp || *cp == *OPTARG || ssize < 1) { TFPRINTF(stderr, _TSK_T ("invalid argument: sector size must be positive: %s\n"), OPTARG); usage(); } break; case _TSK_T('i'): if (TSTRCMP(OPTARG, _TSK_T("list")) == 0) { tsk_img_type_print(stderr); exit(1); } imgtype = tsk_img_type_toid(OPTARG); if (imgtype == TSK_IMG_TYPE_UNSUPP) { TFPRINTF(stderr, _TSK_T("Unsupported image type: %s\n"), OPTARG); usage(); } break; case _TSK_T('o'): if ((imgaddr = tsk_parse_offset(OPTARG)) == -1) { tsk_error_print(stderr); exit(1); } break; case _TSK_T('t'): if (TSTRCMP(OPTARG, _TSK_T("list")) == 0) { tsk_vs_type_print(stderr); exit(1); } vstype = tsk_vs_type_toid(OPTARG); if (vstype == TSK_VS_TYPE_UNSUPP) { TFPRINTF(stderr, _TSK_T("Unsupported volume system type: %s\n"), OPTARG); usage(); } break; case 'v': tsk_verbose++; break; case 'V': tsk_version_print(stdout); exit(0); case '?': default: tsk_fprintf(stderr, "Unknown argument\n"); usage(); } } /* We need at least one more argument */ if (OPTIND >= argc) { tsk_fprintf(stderr, "Missing image name\n"); usage(); } /* open the image */ if ((img = tsk_img_open(argc - OPTIND, &argv[OPTIND], imgtype, ssize)) == NULL) { tsk_error_print(stderr); exit(1); } if ((imgaddr * img->sector_size) >= img->size) { tsk_fprintf(stderr, "Sector offset supplied is larger than disk image (maximum: %" PRIu64 ")\n", img->size / img->sector_size); exit(1); } /* process the partition tables */ if ((vs = tsk_vs_open(img, imgaddr * img->sector_size, vstype)) == NULL) { tsk_error_print(stderr); if (tsk_error_get_errno() == TSK_ERR_VS_UNSUPTYPE) tsk_vs_type_print(stderr); exit(1); } print_stats(vs); tsk_vs_close(vs); tsk_img_close(img); exit(0); }
NTSTATUS mimikatz_doLocal(wchar_t * input) { NTSTATUS status = STATUS_SUCCESS; int argc; wchar_t ** argv = CommandLineToArgvW(input, &argc), *module = NULL, *command = NULL, *match; unsigned short indexModule, indexCommand; BOOL moduleFound = FALSE, commandFound = FALSE; if(argv && (argc > 0)) { if(match = wcsstr(argv[0], L"::")) { if(module = (wchar_t *) LocalAlloc(LPTR, (match - argv[0] + 1) * sizeof(wchar_t))) { if((unsigned int) (match + 2 - argv[0]) < wcslen(argv[0])) command = match + 2; RtlCopyMemory(module, argv[0], (match - argv[0]) * sizeof(wchar_t)); } } else command = argv[0]; for(indexModule = 0; !moduleFound && (indexModule < sizeof(mimikatz_modules) / sizeof(KUHL_M *)); indexModule++) if(moduleFound = (!module || (_wcsicmp(module, mimikatz_modules[indexModule]->shortName) == 0))) if(command) for(indexCommand = 0; !commandFound && (indexCommand < mimikatz_modules[indexModule]->nbCommands); indexCommand++) if(commandFound = _wcsicmp(command, mimikatz_modules[indexModule]->commands[indexCommand].command) == 0) status = mimikatz_modules[indexModule]->commands[indexCommand].pCommand(argc - 1, argv + 1); if(!moduleFound) { PRINT_ERROR(L"\"%s\" module not found !\n", module); for(indexModule = 0; indexModule < sizeof(mimikatz_modules) / sizeof(KUHL_M *); indexModule++) { kprintf(L"\n%16s", mimikatz_modules[indexModule]->shortName); if(mimikatz_modules[indexModule]->fullName) kprintf(L" - %s", mimikatz_modules[indexModule]->fullName); if(mimikatz_modules[indexModule]->description) kprintf(L" [%s]", mimikatz_modules[indexModule]->description); } kprintf(L"\n"); } else if(!commandFound) { indexModule -= 1; PRINT_ERROR(L"\"%s\" command of \"%s\" module not found !\n", command, mimikatz_modules[indexModule]->shortName); kprintf(L"\nModule :\t%s", mimikatz_modules[indexModule]->shortName); if(mimikatz_modules[indexModule]->fullName) kprintf(L"\nFull name :\t%s", mimikatz_modules[indexModule]->fullName); if(mimikatz_modules[indexModule]->description) kprintf(L"\nDescription :\t%s", mimikatz_modules[indexModule]->description); kprintf(L"\n"); for(indexCommand = 0; indexCommand < mimikatz_modules[indexModule]->nbCommands; indexCommand++) { kprintf(L"\n%16s", mimikatz_modules[indexModule]->commands[indexCommand].command); if(mimikatz_modules[indexModule]->commands[indexCommand].description) kprintf(L" - %s", mimikatz_modules[indexModule]->commands[indexCommand].description); } kprintf(L"\n"); } LocalFree(module); LocalFree(argv); } return status; }