int DoInjectHooks(LPWSTR asCmdArg) { gbInShutdown = TRUE; // чтобы не возникло вопросов при выходе gnRunMode = RM_SETHOOK64; LPWSTR pszNext = asCmdArg; LPWSTR pszEnd = NULL; BOOL lbForceGui = FALSE; PROCESS_INFORMATION pi = {NULL}; pi.hProcess = (HANDLE)wcstoul(pszNext, &pszEnd, 16); if (pi.hProcess && pszEnd && *pszEnd) { pszNext = pszEnd+1; pi.dwProcessId = wcstoul(pszNext, &pszEnd, 10); } if (pi.dwProcessId && pszEnd && *pszEnd) { pszNext = pszEnd+1; pi.hThread = (HANDLE)wcstoul(pszNext, &pszEnd, 16); } if (pi.hThread && pszEnd && *pszEnd) { pszNext = pszEnd+1; pi.dwThreadId = wcstoul(pszNext, &pszEnd, 10); } if (pi.dwThreadId && pszEnd && *pszEnd) { pszNext = pszEnd+1; lbForceGui = wcstoul(pszNext, &pszEnd, 10); } #ifdef SHOW_INJECT_MSGBOX wchar_t szDbgMsg[512], szTitle[128]; PROCESSENTRY32 pinf; GetProcessInfo(pi.dwProcessId, &pinf); _wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"ConEmuCD PID=%u", GetCurrentProcessId()); _wsprintf(szDbgMsg, SKIPLEN(countof(szDbgMsg)) L"InjectsTo PID=%s {%s}\nConEmuCD PID=%u", asCmdArg ? asCmdArg : L"", pinf.szExeFile, GetCurrentProcessId()); MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL); #endif if (pi.hProcess && pi.hThread && pi.dwProcessId && pi.dwThreadId) { // Аргумент abForceGui не использовался CINJECTHK_EXIT_CODES iHookRc = InjectHooks(pi, /*lbForceGui,*/ gbLogProcess); if (iHookRc == CIH_OK/*0*/) { return CERR_HOOKS_WAS_SET; } // Ошибку (пока во всяком случае) лучше показать, для отлова возможных проблем DWORD nErrCode = GetLastError(); //_ASSERTE(iHookRc == 0); -- ассерт не нужен, есть MsgBox wchar_t szDbgMsg[255], szTitle[128]; _wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"ConEmuC[%u], PID=%u", WIN3264TEST(32,64), GetCurrentProcessId()); _wsprintf(szDbgMsg, SKIPLEN(countof(szDbgMsg)) L"ConEmuC.X, PID=%u\nInjecting hooks into PID=%u\nFAILED, code=%i:0x%08X", GetCurrentProcessId(), pi.dwProcessId, iHookRc, nErrCode); MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL); } else { //_ASSERTE(pi.hProcess && pi.hThread && pi.dwProcessId && pi.dwThreadId); wchar_t szDbgMsg[512], szTitle[128]; _wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"ConEmuC, PID=%u", GetCurrentProcessId()); _wsprintf(szDbgMsg, SKIPLEN(countof(szDbgMsg)) L"ConEmuC.X, PID=%u\nCmdLine parsing FAILED (%u,%u,%u,%u,%u)!\n%s", GetCurrentProcessId(), LODWORD(pi.hProcess), LODWORD(pi.hThread), pi.dwProcessId, pi.dwThreadId, lbForceGui, //-V205 asCmdArg); MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL); } return CERR_HOOKS_FAILED; }
static BOOL ParseCmdLine(int argc, PWSTR argv[]) { int i; if (argc < 2) { ConResPrintf(StdOut, IDS_USAGE); return FALSE; } for (i = 1; i < argc; i++) { if (argv[i][0] == L'-' || argv[i][0] == L'/') { switch (argv[i][1]) { case L't': PingForever = TRUE; break; case L'a': ResolveAddress = TRUE; break; case L'n': { if (i + 1 < argc) { PingForever = FALSE; PingCount = wcstoul(argv[++i], NULL, 0); if (PingCount == 0) { ConResPrintf(StdErr, IDS_BAD_VALUE, argv[i - 1], 1, UINT_MAX); return FALSE; } } else { ConResPrintf(StdErr, IDS_MISSING_VALUE, argv[i]); return FALSE; } break; } case L'l': { if (i + 1 < argc) { RequestSize = wcstoul(argv[++i], NULL, 0); if (RequestSize > MAX_SEND_SIZE) { ConResPrintf(StdErr, IDS_BAD_VALUE, argv[i - 1], 0, MAX_SEND_SIZE); return FALSE; } } else { ConResPrintf(StdErr, IDS_MISSING_VALUE, argv[i]); return FALSE; } break; } case L'f': { if (Family == AF_INET6) { ConResPrintf(StdErr, IDS_WRONG_FAMILY, argv[i], L"IPv4"); return FALSE; } Family = AF_INET; IpOptions.Flags |= IP_FLAG_DF; break; } case L'i': { if (i + 1 < argc) { ULONG Ttl = wcstoul(argv[++i], NULL, 0); if ((Ttl == 0) || (Ttl > UCHAR_MAX)) { ConResPrintf(StdErr, IDS_BAD_VALUE, argv[i - 1], 1, UCHAR_MAX); return FALSE; } IpOptions.Ttl = (UCHAR)Ttl; } else { ConResPrintf(StdErr, IDS_MISSING_VALUE, argv[i]); return FALSE; } break; } case L'v': { if (Family == AF_INET6) { ConResPrintf(StdErr, IDS_WRONG_FAMILY, argv[i], L"IPv4"); return FALSE; } Family = AF_INET; if (i + 1 < argc) { /* This option has been deprecated. Don't do anything. */ i++; } else { ConResPrintf(StdErr, IDS_MISSING_VALUE, argv[i]); return FALSE; } break; } case L'w': { if (i + 1 < argc) { Timeout = wcstoul(argv[++i], NULL, 0); if (Timeout < DEFAULT_TIMEOUT) Timeout = DEFAULT_TIMEOUT; } else { ConResPrintf(StdErr, IDS_MISSING_VALUE, argv[i]); return FALSE; } break; } case L'R': { if (Family == AF_INET) { ConResPrintf(StdErr, IDS_WRONG_FAMILY, argv[i], L"IPv6"); return FALSE; } Family = AF_INET6; /* This option has been deprecated. Don't do anything. */ break; } case L'4': { if (Family == AF_INET6) { ConResPrintf(StdErr, IDS_WRONG_FAMILY, argv[i], L"IPv4"); return FALSE; } Family = AF_INET; break; } case L'6': { if (Family == AF_INET) { ConResPrintf(StdErr, IDS_WRONG_FAMILY, argv[i], L"IPv6"); return FALSE; } Family = AF_INET6; break; } case L'?': ConResPrintf(StdOut, IDS_USAGE); return FALSE; default: ConResPrintf(StdErr, IDS_BAD_OPTION, argv[i]); ConResPrintf(StdErr, IDS_USAGE); return FALSE; } } else { if (TargetName != NULL) { ConResPrintf(StdErr, IDS_BAD_PARAMETER, argv[i]); return FALSE; } TargetName = argv[i]; } } if (TargetName == NULL) { ConResPrintf(StdErr, IDS_MISSING_ADDRESS); return FALSE; } return TRUE; }
double wcstod (const wchar_t * str, wchar_t ** end) { double val; double mantissa; unsigned long divisor; unsigned long power; int sign; int sign_power; wchar_t *pend; wchar_t ch; // skip blank for (; iswblank (*str); str ++) { } for (ch = *str; (ch == '-') || (ch == '+'); str ++) { } // the sign sign = 0; if ('-' == ch) { sign = 1; str ++; } // skip leading zero for (; '0' == (*str); str ++) { } val = 0.0; mantissa = 0.0; divisor = 0; power = 0.0; // integer part for (ch = *str; ('0' <= ch) && (ch <= '9'); str ++) { ch -= '0'; val *= 10; val += ch; } // floating point & mantissa if ('.' == *str) { str ++; for (ch = *str; ('0' <= ch) && (ch <= '9'); str ++) { ch -= '0'; mantissa *= 10.0; mantissa += ch; divisor ++; } } for (; divisor > 0; divisor --) { mantissa /= 10.0; } val += mantissa; sign_power = 0; if (('e' == *str) || ('E' == *str)) { str ++; if ('-' == ch) { sign_power = 1; str ++; } pend = NULL; power = wcstoul (str, &pend, 10); if (NULL != pend) { str = pend; } } if (power > 0) { if (sign_power) { for (; power > 0; power --) { val /= 10.0; } } else { for (; power > 0; power --) { val *= 10.0; } } } if (sign) { val = - val; } if (end) { *end = (wchar_t *)str; } return val; }
static DWORD WINAPI StdErrReaderThread(LPVOID lpParameter) { CDownloader* pObj = ((PipeThreadParm*)lpParameter)->pObj; char Line[4096+1]; // When output is redirected, RAW ASCII is used const DWORD dwToRead = countof(Line)-1; DWORD dwRead, nValue, nErrCode; BOOL bSuccess; CEStr szLine; const wchar_t *ptr; const wchar_t sProgressMark[] = L" " CEDLOG_MARK_PROGR; const wchar_t sInformationMark[] = L" " CEDLOG_MARK_INFO; const wchar_t sErrorMark[] = L" " CEDLOG_MARK_ERROR; LineBuffer buffer = {}; bool bExit = false; while (!bExit) { bSuccess = ReadFile(pObj->mh_PipeErrRead, Line, dwToRead, &dwRead, NULL); if (!bSuccess || dwRead == 0) { nErrCode = GetLastError(); break; } _ASSERTE(dwRead < countof(Line)); Line[dwRead] = 0; // Ensure it is ASCIIZ // Append to the line-buffer buffer.AddBlock(Line, dwRead); // Parse read line while (buffer.GetLine(szLine)) { bool bProgress = false; if ((ptr = wcsstr(szLine, sProgressMark)) != NULL) { bProgress = true; if (pObj->mfn_Callback[dc_ProgressCallback]) { // 09:01:20.811{1234} Progr: Bytes downloaded 1656 wchar_t* ptrEnd = NULL; LPCWSTR pszFrom = wcspbrk(ptr+wcslen(sProgressMark), L"0123456789"); nValue = pszFrom ? wcstoul(pszFrom, &ptrEnd, 10) : 0; if (nValue) { CEDownloadInfo progrInfo = { sizeof(progrInfo), pObj->m_CallbackLParam[dc_ProgressCallback] }; progrInfo.argCount = 1; progrInfo.Args[0].argType = at_Uint; progrInfo.Args[0].uintArg = nValue; pObj->mfn_Callback[dc_ProgressCallback](&progrInfo); } } } // For logging purposes if (!bProgress && ((ptr = wcsstr(szLine, sErrorMark)) != NULL)) { if (pObj->mfn_Callback[dc_ErrCallback]) { CEDownloadInfo Error = { sizeof(Error), pObj->m_CallbackLParam[dc_ErrCallback], szLine.ms_Val }; pObj->mfn_Callback[dc_ErrCallback](&Error); } } else //if (bProgress || ((ptr = wcsstr(szLine, sInformationMark)) != NULL)) { if (pObj->mfn_Callback[dc_LogCallback]) { CEDownloadInfo Info = { sizeof(Info), pObj->m_CallbackLParam[dc_LogCallback], szLine.ms_Val }; pObj->mfn_Callback[dc_LogCallback](&Info); } // Exit? ptr = wcsstr(szLine, sInformationMark); if (ptr) { ptr += wcslen(sInformationMark); if (wcsncmp(ptr, L"Exit", 4) == 0) { bExit = true; break; } } } } } return 0; };
DWORD HTTPGetFile(String url, char * outHtml, unsigned &bufeLen, CTSTR extraHeaders, int *responseCode) { if (NULL == outHtml || 0 == bufeLen) { return 1; } unsigned nMaxBufLen = bufeLen; bufeLen = 0; HINTERNET hSession = NULL; HINTERNET hConnect = NULL; HINTERNET hRequest = NULL; URL_COMPONENTS urlComponents; BOOL secure = FALSE; DWORD ret = 1; String hostName, path; const TCHAR *acceptTypes[] = { TEXT("*/*"), NULL }; hostName.SetLength(256); path.SetLength(1024); zero(&urlComponents, sizeof(urlComponents)); urlComponents.dwStructSize = sizeof(urlComponents); urlComponents.lpszHostName = hostName; urlComponents.dwHostNameLength = hostName.Length(); urlComponents.lpszUrlPath = path; urlComponents.dwUrlPathLength = path.Length(); WinHttpCrackUrl(url, 0, 0, &urlComponents); if (urlComponents.nPort == 443) secure = TRUE; hSession = WinHttpOpen(TEXT("ButelLive agent"), WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (!hSession) goto failure; DWORD dwTimeOut = 5000; // ms DWORD dwSize = sizeof(DWORD); WinHttpSetOption(hSession, WINHTTP_OPTION_CONNECT_TIMEOUT, &dwTimeOut, dwSize); WinHttpSetOption(hSession, WINHTTP_OPTION_SEND_TIMEOUT, &dwTimeOut, dwSize); WinHttpSetOption(hSession, WINHTTP_OPTION_RECEIVE_TIMEOUT, &dwTimeOut, dwSize); hConnect = WinHttpConnect(hSession, hostName, urlComponents.nPort, 0); if (!hConnect) goto failure; hRequest = WinHttpOpenRequest(hConnect, TEXT("Get"), path, NULL, WINHTTP_NO_REFERER, acceptTypes, secure ? WINHTTP_FLAG_SECURE | WINHTTP_FLAG_REFRESH : WINHTTP_FLAG_REFRESH); if (!hRequest) goto failure; BOOL bResults = WinHttpSendRequest( hRequest, extraHeaders, extraHeaders ? -1 : 0, NULL, 0, 0, NULL ); // End the request. if (bResults) bResults = WinHttpReceiveResponse(hRequest, NULL); else goto failure; TCHAR statusCode[8]; DWORD statusCodeLen; statusCodeLen = sizeof(statusCode); if (!WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_STATUS_CODE, WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &statusCodeLen, WINHTTP_NO_HEADER_INDEX)) { //ERROR_WINHTTP_HEADER_NOT_FOUND int error = GetLastError(); goto failure; } *responseCode = wcstoul(statusCode, NULL, 10); if (bResults && *responseCode == 200) { BYTE buffer[16384]; DWORD dwSize, dwOutSize; do { // Check for available data. dwSize = 0; if (!WinHttpQueryDataAvailable(hRequest, &dwSize)) goto failure; if (!WinHttpReadData(hRequest, (LPVOID)buffer, dwSize, &dwOutSize)) { goto failure; } else { if (!dwOutSize) break; if (bufeLen + dwOutSize > nMaxBufLen) { goto failure; } //strHtml.AppendString((CTSTR)buffer, dwOutSize); memcpy(outHtml + bufeLen, buffer, dwOutSize); bufeLen += dwOutSize; outHtml[bufeLen] = '\0'; } } while (dwSize > 0); } ret = 0; failure: if (0 != ret) { DWORD dwError = GetLastError(); if (dwError != 0) { ret = dwError; } } if (hSession) WinHttpCloseHandle(hSession); if (hConnect) WinHttpCloseHandle(hConnect); if (hRequest) WinHttpCloseHandle(hRequest); return ret; }
void CPLUGIN::exec_before(const CSAORIInput& in,CSAORIOutput& out) { //----------変数群初期化---------- script.erase(); script_option.erase(); event.erase(); event_option.erase(); target.erase(); marker.erase(); security_level.erase(); language.erase(); map_strpair::const_iterator itr = in.opts.find(L"Language"); if ( itr != in.opts.end() ) { language = itr->second; } sender.erase(); itr = in.opts.find(L"Sender"); if ( itr != in.opts.end() ) { sender = itr->second; } //----------ゴーストリスト更新---------- if ( in.args.size() >= 5 ) { if ( wcsicmp(in.id.c_str(),L"OnGhostBoot") == 0 || wcsicmp(in.id.c_str(),L"OnGhostInfoUpdate") == 0 ) { string_t path = in.args[4]; ghost_map_type::iterator itr = ghost_map.find(path); SAORI_FUNC::CCriticalSectionLock lock(sstp_thread_lock); CGhostInfo *pGI; if ( itr != ghost_map.end() ) { pGI = &(itr->second); } else { pGI = &(ghost_map[path]); } pGI->hwnd = reinterpret_cast<void*>(wcstoul(in.args[0].c_str(),NULL,10)); pGI->name = in.args[1]; pGI->shell_name = in.args[2]; pGI->id = in.args[3]; pGI->path = path; if ( in.args.size() >= 6 ) { pGI->shell_path = in.args[5]; } else { pGI->shell_path.erase(); } } else if ( wcsicmp(in.id.c_str(),L"OnGhostExit") == 0 ) { string_t path = in.args[4]; SAORI_FUNC::CCriticalSectionLock lock(sstp_thread_lock); ghost_map_type::iterator itr = ghost_map.find(path); if ( itr != ghost_map.end() ) { ghost_map.erase(itr); } } } }
// Returns ">0" - when changes was made // 0 - no changes // -1 - error // bForceCurConsole==true, если разбор параметров идет // при запуске Tasks из GUI int RConStartArgs::ProcessNewConArg(bool bForceCurConsole /*= false*/) { NewConsole = crb_Undefined; if (!pszSpecialCmd || !*pszSpecialCmd) { _ASSERTE(pszSpecialCmd && *pszSpecialCmd); return -1; } int nChanges = 0; // 140219 - Остановить обработку, если встретим любой из: ConEmu[.exe], ConEmu64[.exe], ConEmuC[.exe], ConEmuC64[.exe] LPCWSTR pszStopAt = NULL; { LPCWSTR pszTemp = pszSpecialCmd; LPCWSTR pszSave = pszSpecialCmd; LPCWSTR pszName; CmdArg szExe; LPCWSTR pszWords[] = {L"ConEmu", L"ConEmu.exe", L"ConEmu64", L"ConEmu64.exe", L"ConEmuC", L"ConEmuC.exe", L"ConEmuC64", L"ConEmuC64.exe", L"ConEmuPortable.exe", L"ConEmuPortable", NULL}; while (!pszStopAt && (0 == NextArg(&pszTemp, szExe))) { pszName = PointToName(szExe); for (size_t i = 0; pszWords[i]; i++) { if (lstrcmpi(pszName, pszWords[i]) == 0) { pszStopAt = pszSave; break; } } pszSave = pszTemp; } } #if 0 // 140219 - Остановить обработку, если встретим любой из: ConEmu[.exe], ConEmu64[.exe], ConEmuC[.exe], ConEmuC64[.exe] if (!hShlwapi) { hShlwapi = LoadLibrary(L"Shlwapi.dll"); WcsStrI = hShlwapi ? (StrStrI_t)GetProcAddress(hShlwapi, "StrStrIW") : NULL; } #endif // 111211 - здесь может быть передан "-new_console:..." LPCWSTR pszNewCon = L"-new_console"; // 120108 - или "-cur_console:..." для уточнения параметров запуска команд (из фара например) LPCWSTR pszCurCon = L"-cur_console"; int nNewConLen = lstrlen(pszNewCon); _ASSERTE(lstrlen(pszCurCon)==nNewConLen); wchar_t* pszFrom = pszSpecialCmd; bool bStop = false; while (!bStop) { wchar_t* pszSwitch = wcschr(pszFrom, L'-'); if (!pszSwitch) break; // Pre-validation if (((pszSwitch[1] != L'n') && (pszSwitch[1] != L'c')) // -new_... or -cur_... || (((pszSwitch != /* > */ pszFrom) // If it is started from pszFrom - no need to check previous symbols && (*(pszSwitch-1) != L'"') || (((pszSwitch-2) >= pszFrom) && (*(pszSwitch-2) == L'\\'))) // Found: \"-new... && (*(pszSwitch-1) != L' '))) // Prev symbol was space { // НЕ наш аргумент pszSwitch = wcschr(pszSwitch+1, L' '); if (!pszSwitch) break; pszFrom = pszSwitch; continue; } wchar_t* pszFindNew = NULL; wchar_t* pszFind = NULL; wchar_t szTest[12]; lstrcpyn(szTest, pszSwitch+1, countof(szTest)); if (lstrcmp(szTest, L"new_console") == 0) pszFindNew = pszFind = pszSwitch; else if (lstrcmp(szTest, L"cur_console") == 0) pszFind = pszSwitch; else { // НЕ наш аргумент pszSwitch = wcschr(pszSwitch+1, L' '); if (!pszSwitch) break; pszFrom = pszSwitch; continue; } if (!pszFind) break; if (pszStopAt && (pszFind >= pszStopAt)) break; // Проверка валидности _ASSERTE(pszFind >= pszSpecialCmd); if ((pszFind[nNewConLen] != L' ') && (pszFind[nNewConLen] != L':') && (pszFind[nNewConLen] != L'"') && (pszFind[nNewConLen] != 0)) { // НЕ наш аргумент pszFrom = pszFind+nNewConLen; } else { if (pszFindNew) NewConsole = crb_On; // -- не будем пока, мешает. например, при запуске задач //// По умолчанию, принудительно включить "Press Enter or Esc to close console" //if (!bForceCurConsole) // eConfirmation = eConfAlways; bool lbQuot = (*(pszFind-1) == L'"'); bool lbWasQuot = lbQuot; const wchar_t* pszEnd = pszFind+nNewConLen; //wchar_t szNewConArg[MAX_PATH+1]; if (lbQuot) pszFind--; if (*pszEnd == L'"') { pszEnd++; } else if (*pszEnd != L':') { // Конец _ASSERTE(*pszEnd == L' ' || *pszEnd == 0); } else { if (*pszEnd == L':') { pszEnd++; } else { _ASSERTE(*pszEnd == L':'); } // Найти конец аргумента const wchar_t* pszArgEnd = pszEnd; bool lbLocalQuot = false; while (*pszArgEnd) { switch (*pszArgEnd) { case L'^': pszArgEnd++; // Skip control char, goto escaped char break; case L'"': if (*(pszArgEnd+1) == L'"') { pszArgEnd += 2; // Skip qoubled qouble quote continue; } if (!lbQuot) { if (!lbLocalQuot && (*(pszArgEnd-1) == L':')) { lbLocalQuot = true; pszArgEnd++; continue; } if (lbLocalQuot) { if (*(pszArgEnd+1) != L':') goto EndFound; lbLocalQuot = false; pszArgEnd += 2; continue; } } goto EndFound; case L' ': if (!lbQuot && !lbLocalQuot) goto EndFound; break; case 0: goto EndFound; } pszArgEnd++; } EndFound: // Обработка доп.параметров -new_console:xxx bool lbReady = false; while (!lbReady && *pszEnd) { _ASSERTE(pszEnd <= pszArgEnd); wchar_t cOpt = *(pszEnd++); switch (cOpt) { //case L'-': // bStop = true; // следующие "-new_console" - не трогать! // break; case L'"': // Assert was happened, for example, with: "/C \"ConEmu:run:Far.exe -new_console:\"" _ASSERTE((pszEnd > pszArgEnd) && "Wrong quotation usage in -new_console?"); lbReady = true; break; case L' ': case 0: lbReady = true; break; case L':': // Just skip ':'. Delimiter between switches: -new_console:c:b:a // Revert stored value to lbQuot. We need to "cut" last double quote in the first two cases // cmd -cur_console:d:"C:\users":t:"My title" "-cur_console:C:C:\cmd.ico" -cur_console:P:"<PowerShell>":a /k ver lbWasQuot = lbQuot; break; case L'b': // b - background, не активировать таб BackgroundTab = crb_On; ForegroungTab = crb_Off; break; case L'f': // f - foreground, активировать таб (аналог ">" в Tasks) ForegroungTab = crb_On; BackgroundTab = crb_Off; break; case L'z': // z - don't use "Default terminal" feature NoDefaultTerm = crb_On; break; case L'a': // a - RunAs shell verb (as admin on Vista+, login/password in WinXP-) RunAsAdministrator = crb_On; break; case L'r': // r - run as restricted user RunAsRestricted = crb_On; break; case L'o': // o - disable "Long output" for next command (Far Manager) LongOutputDisable = crb_On; break; case L'w': // e - enable "Overwrite" mode in console prompt OverwriteMode = crb_On; break; case L'p': if (isDigit(*pszEnd)) { switch (*(pszEnd++)) { case L'0': nPTY = 0; // don't change break; case L'1': nPTY = 1; // enable PTY mode break; case L'2': nPTY = 2; // disable PTY mode (switch to plain $CONIN, $CONOUT, $CONERR) break; default: nPTY = 1; } } else { nPTY = 1; // enable PTY mode } break; case L'i': // i - don't inject ConEmuHk into the starting application InjectsDisable = crb_On; break; case L'N': // N - Force new ConEmu window with Default terminal ForceNewWindow = crb_On; break; case 'R': // R - Force CheckHookServer (GitShowBranch.cmd, actually used with -cur_console) ForceHooksServer = crb_On; break; case L'h': // "h0" - отключить буфер, "h9999" - включить буфер в 9999 строк { BufHeight = crb_On; if (isDigit(*pszEnd)) { wchar_t* pszDigits = NULL; nBufHeight = wcstoul(pszEnd, &pszDigits, 10); if (pszDigits) pszEnd = pszDigits; } else { nBufHeight = 0; } } // L'h': break; case L'n': // n - отключить "Press Enter or Esc to close console" eConfirmation = eConfNever; break; case L'c': // c - принудительно включить "Press Enter or Esc to close console" eConfirmation = eConfAlways; break; case L'x': // x - Force using dosbox for .bat files ForceDosBox = crb_On; break; case L'I': // I - tell GuiMacro to execute new command inheriting active process state. This is only usage ATM. ForceInherit = crb_On; break; // "Long" code blocks below: 'd', 'u', 's' and so on (in future) case L's': // s[<SplitTab>T][<Percents>](H|V) // Пример: "s3T30H" - разбить 3-ий таб. будет создан новый Pane справа, шириной 30% от 3-го таба. { UINT nTab = 0 /*active*/, nValue = /*пополам*/DefaultSplitValue/10; bool bDisableSplit = false; while (*pszEnd) { if (isDigit(*pszEnd)) { wchar_t* pszDigits = NULL; UINT n = wcstoul(pszEnd, &pszDigits, 10); if (!pszDigits) break; pszEnd = pszDigits; if (*pszDigits == L'T') { nTab = n; } else if ((*pszDigits == L'H') || (*pszDigits == L'V')) { nValue = n; eSplit = (*pszDigits == L'H') ? eSplitHorz : eSplitVert; } else { break; } pszEnd++; } else if (*pszEnd == L'T') { nTab = 0; pszEnd++; } else if ((*pszEnd == L'H') || (*pszEnd == L'V')) { nValue = DefaultSplitValue/10; eSplit = (*pszEnd == L'H') ? eSplitHorz : eSplitVert; pszEnd++; } else if (*pszEnd == L'N') { bDisableSplit = true; pszEnd++; break; } else { break; } } if (bDisableSplit) { eSplit = eSplitNone; nSplitValue = DefaultSplitValue; nSplitPane = 0; } else { if (!eSplit) eSplit = eSplitHorz; // Для удобства, пользователь задает размер НОВОЙ части nSplitValue = 1000-max(1,min(nValue*10,999)); // проценты _ASSERTE(nSplitValue>=1 && nSplitValue<1000); nSplitPane = nTab; } } // L's' break; // Following options (except of single 'u') must be placed on the end of "-new_console:..." // If one needs more that one option - use several "-new_console:..." switches case L'd': // d:<StartupDir>. MUST be last option case L't': // t:<TabName>. MUST be last option case L'u': // u - ConEmu choose user dialog (may be specified in the middle, if it is without ':' - user or pwd) // u:<user> - ConEmu choose user dialog with prefilled user field. MUST be last option // u:<user>:<pwd> - specify user/pwd in args. MUST be last option case L'C': // C:<IconFile>. MUST be last option case L'P': // P:<Palette>. MUST be last option case L'W': // W:<Wallpaper>. MUST be last option { if (cOpt == L'u') { // Show choose user dialog (may be specified in the middle, if it is without ':' - user or pwd) SafeFree(pszUserName); SafeFree(pszDomain); if (szUserPassword[0]) SecureZeroMemory(szUserPassword, sizeof(szUserPassword)); } if (*pszEnd == L':') { pszEnd++; } else { if (cOpt == L'u') { ForceUserDialog = crb_On; break; } } const wchar_t* pszTab = pszEnd; // we need to find end of argument pszEnd = pszArgEnd; // temp buffer wchar_t* lpszTemp = NULL; wchar_t** pptr = NULL; switch (cOpt) { case L'd': pptr = &pszStartupDir; break; case L't': pptr = &pszRenameTab; break; case L'u': pptr = &lpszTemp; break; case L'C': pptr = &pszIconFile; break; case L'P': pptr = &pszPalette; break; case L'W': pptr = &pszWallpaper; break; } if (pszEnd > pszTab) { size_t cchLen = pszEnd - pszTab; SafeFree(*pptr); *pptr = (wchar_t*)malloc((cchLen+1)*sizeof(**pptr)); if (*pptr) { // We need to process escape sequences ("^>" -> ">", "^&" -> "&", etc.) //wmemmove(*pptr, pszTab, cchLen); wchar_t* pD = *pptr; const wchar_t* pS = pszTab; if (lbQuot) { lbLocalQuot = false; } else if (*pS == L'"' && *(pS+1) != L'"') { // Remember, that last processed switch was local-quoted lbWasQuot = true; // This item is local quoted. Example: -new_console:t:"My title" lbLocalQuot = true; pS++; } // There is enough room allocated while (pS < pszEnd) { if ((*pS == L'^') && ((pS + 1) < pszEnd)) { pS++; // Skip control char, goto escaped char } else if (*pS == L'"') { if (((pS + 1) < pszEnd) && (*(pS+1) == L'"')) { pS++; // Skip qoubled qouble quote } else if (lbLocalQuot) { pszEnd = (pS+1); _ASSERTE(*pszEnd==L':' || *pszEnd==L' ' || *pszEnd==0); break; // End of local quoted argument: -new_console:d:"C:\User\super user":t:"My title" } } *(pD++) = *(pS++); } // Terminate with '\0' _ASSERTE(pD <= ((*pptr)+cchLen)); *pD = 0; // Issue 1711: Supposing there can't be ending quotes INT_PTR iLen = (pD - *pptr); while (((iLen--) > 0) && (*(--pD) == L'"')) *pD = 0; } // Additional processing switch (cOpt) { case L'd': // Например, "%USERPROFILE%" // TODO("А надо ли разворачивать их тут? Наверное при запуске под другим юзером некорректно? Хотя... все равно до переменных не доберемся"); if (wcschr(pszStartupDir, L'%')) { wchar_t* pszExpand = NULL; if (((pszExpand = ExpandEnvStr(pszStartupDir)) != NULL)) { SafeFree(pszStartupDir); pszStartupDir = pszExpand; } } break; case L'u': if (lpszTemp) { // Split in form: // [Domain\]UserName[:Password] wchar_t* pszPwd = wcschr(lpszTemp, L':'); if (pszPwd) { // Password was specified, dialog prompt is not required ForceUserDialog = crb_Off; *pszPwd = 0; int nPwdLen = lstrlen(pszPwd+1); lstrcpyn(szUserPassword, pszPwd+1, countof(szUserPassword)); if (nPwdLen > 0) SecureZeroMemory(pszPwd+1, nPwdLen); UseEmptyPassword = (nPwdLen == 0) ? crb_On : crb_Off; } else { // Password was NOT specified, dialog prompt IS required ForceUserDialog = crb_On; UseEmptyPassword = crb_Off; } wchar_t* pszSlash = wcschr(lpszTemp, L'\\'); if (pszSlash) { *pszSlash = 0; pszDomain = lstrdup(lpszTemp); pszUserName = lstrdup(pszSlash+1); } else { pszUserName = lstrdup(lpszTemp); } } break; } } SafeFree(lpszTemp); } // L't': break; } } } if (pszEnd > pszFind) { // pszEnd должен указывать на конец -new_console[:...] / -cur_console[:...] // и включать обрамляющую кавычку, если он окавычен if (lbWasQuot) { if (*pszEnd == L'"' && *(pszEnd-1) != L'"') pszEnd++; } else { while (*(pszEnd-1) == L'"') pszEnd--; } // Откусить лишние пробелы, которые стоят ПЕРЕД -new_console[:...] / -cur_console[:...] while (((pszFind - 1) >= pszSpecialCmd) && (*(pszFind-1) == L' ') && (((pszFind - 1) == pszSpecialCmd) || (*(pszFind-2) == L' ') || (/**pszEnd == L'"' ||*/ *pszEnd == 0 || *pszEnd == L' '))) { pszFind--; } // Откусить лишние пробелы ПОСЛЕ -new_console[:...] / -cur_console[:...] если он стоит в НАЧАЛЕ строки! if (pszFind == pszSpecialCmd) { while (*pszEnd == L' ') pszEnd++; } // Здесь нужно подвинуть pszStopAt if (pszStopAt) pszStopAt -= (pszEnd - pszFind); // Удалить из строки запуска обработанный ключ wmemmove(pszFind, pszEnd, (lstrlen(pszEnd)+1)); nChanges++; } else { _ASSERTE(pszEnd > pszFind); *pszFind = 0; nChanges++; } } // if ((((pszFind == pszFrom) ... } // while (!bStop) return nChanges; } // int RConStartArgs::ProcessNewConArg(bool bForceCurConsole /*= false*/)
ulong StringParser::WStringTo(const WStringRef& inString, int base /*= 10*/) { return (ulong)wcstoul(inString.c_str(), nullptr, base); }
int test_wcstol(void) { int i; long l; unsigned long ul; long long ll; unsigned long long ull; char *msg=""; int err=0; wchar_t *s, *c; TEST(l, wcstol(L"2147483647", 0, 0), 2147483647L, "max 32bit signed %ld != %ld"); TEST(ul, wcstoul(L"4294967295", 0, 0), 4294967295UL, "max 32bit unsigned %lu != %lu"); if (sizeof(long) == 4) { errno = 0; TEST(l, wcstol(s=L"2147483648", &c, 0), 2147483647L, "uncaught overflow %ld != %ld"); TEST2(i, c-s, 10, "wrong final position %d != %d"); TEST2(i, errno, ERANGE, "missing errno %d != %d"); errno = 0; TEST(l, wcstol(s=L"-2147483649", &c, 0), -2147483647L-1, "uncaught overflow %ld != %ld"); TEST2(i, c-s, 11, "wrong final position %d != %d"); TEST2(i, errno, ERANGE, "missing errno %d != %d"); errno = 0; TEST(ul, wcstoul(s=L"4294967296", &c, 0), 4294967295UL, "uncaught overflow %lu != %lu"); TEST2(i, c-s, 10, "wrong final position %d != %d"); TEST2(i, errno, ERANGE, "missing errno %d != %d"); errno = 0; TEST(ul, wcstoul(s=L"-1", &c, 0), -1UL, "rejected negative %lu != %lu"); TEST2(i, c-s, 2, "wrong final position %d != %d"); TEST2(i, errno, 0, "spurious errno %d != %d"); errno = 0; TEST(ul, wcstoul(s=L"-2", &c, 0), -2UL, "rejected negative %lu != %lu"); TEST2(i, c-s, 2, "wrong final position %d != %d"); TEST2(i, errno, 0, "spurious errno %d != %d"); errno = 0; TEST(ul, wcstoul(s=L"-2147483648", &c, 0), -2147483648UL, "rejected negative %lu != %lu"); TEST2(i, c-s, 11, "wrong final position %d != %d"); TEST2(i, errno, 0, "spurious errno %d != %d"); errno = 0; TEST(ul, wcstoul(s=L"-2147483649", &c, 0), -2147483649UL, "rejected negative %lu != %lu"); TEST2(i, c-s, 11, "wrong final position %d != %d"); TEST2(i, errno, 0, "spurious errno %d != %d"); } else { TEST(i, 0, 1, "64bit tests not implemented"); } TEST(l, wcstol(L"z", 0, 36), 35, "%ld != %ld"); TEST(l, wcstol(L"00010010001101000101011001111000", 0, 2), 0x12345678, "%ld != %ld"); TEST(l, wcstol(s=L"0xz", &c, 16), 0, "%ld != %ld"); TEST2(i, c-s, 1, "wrong final position %ld != %ld"); TEST(l, wcstol(s=L"0x1234", &c, 16), 0x1234, "%ld != %ld"); TEST2(i, c-s, 6, "wrong final position %ld != %ld"); errno = 0; c = NULL; TEST(l, wcstol(s=L"123", &c, 37), 0, "%ld != %ld"); TEST2(i, c-s, 0, "wrong final position %d != %d"); TEST2(i, errno, EINVAL, "%d != %d"); return err; }
void Definition::GetAsNumber(Number<T>& n, StringMapW<T>* n2n) { CStringW str = m_value; str.Replace(L" ", L""); n.value = 0; n.unit = m_unit; n.sign = 0; if(n2n) { if(m_status == node) throw Exception(_T("expected value type")); if(StringMapW<T>::CPair* p = n2n->Lookup(str)) { n.value = p->m_value; return; } } if(m_status != number) throw Exception(_T("expected number")); n.sign = str.Find('+') == 0 ? 1 : str.Find('-') == 0 ? -1 : 0; str.TrimLeft(L"+-"); if(str.Find(L"0x") == 0) { if(n.sign) throw Exception(_T("hex values must be unsigned")); n.value = (T)wcstoul(str.Mid(2), NULL, 16); } else { CStringW num_string = m_value + m_unit; if(m_num_string != num_string) { Split sa(':', str); Split sa2('.', sa ? sa[sa-1] : L""); if(sa == 0 || sa2 == 0 || sa2 > 2) throw Exception(_T("invalid number")); float f = 0; for(size_t i = 0; i < sa; i++) {f *= 60; f += wcstoul(sa[i], NULL, 10);} if(sa2 > 1) f += (float)wcstoul(sa2[1], NULL, 10) / pow((float)10, sa2[1].GetLength()); if(n.unit == L"ms") {f /= 1000; n.unit = L"s";} else if(n.unit == L"m") {f *= 60; n.unit = L"s";} else if(n.unit == L"h") {f *= 3600; n.unit = L"s";} m_num.value = f; m_num.unit = n.unit; m_num_string = num_string; n.value = (T)f; } else { n.value = (T)m_num.value; n.unit = m_num.unit; } if(n.sign) n.value *= n.sign; } }
INT wmain(INT argc, WCHAR *argv[]) { #ifdef STANDALONE if (argc < 2) { wprintf(L"\nReactOS Virtual DOS Machine\n\n" L"Usage: NTVDM <executable> [<parameters>]\n"); return 0; } #else INT i; WCHAR *endptr; /* Parse the command line arguments */ for (i = 1; i < argc; i++) { if (wcsncmp(argv[i], L"-i", 2) == 0) { /* This is the session ID */ SessionId = wcstoul(argv[i] + 2, &endptr, 10); /* The VDM hasn't been started from a console, so quit when the task is done */ AcceptCommands = FALSE; } } #endif NtVdmArgc = argc; NtVdmArgv = argv; DPRINT1("\n\n\nNTVDM - Starting...\n\n\n"); /* Create the task event */ VdmTaskEvent = CreateEvent(NULL, TRUE, FALSE, NULL); ASSERT(VdmTaskEvent != NULL); /* Initialize the console */ if (!ConsoleInit()) { wprintf(L"FATAL: A problem occurred when trying to initialize the console\n"); goto Cleanup; } /* Initialize the emulator */ if (!EmulatorInitialize(ConsoleInput, ConsoleOutput)) { wprintf(L"FATAL: Failed to initialize the emulator\n"); goto Cleanup; } /* Initialize the system BIOS */ if (!BiosInitialize(NULL)) { wprintf(L"FATAL: Failed to initialize the VDM BIOS.\n"); goto Cleanup; } /* Let's go! Start simulation */ CpuSimulate(); Cleanup: BiosCleanup(); EmulatorCleanup(); ConsoleCleanup(); #ifndef STANDALONE ExitVDM(FALSE, 0); #endif /* Quit the VDM */ DPRINT1("\n\n\nNTVDM - Exiting...\n\n\n"); return 0; }
int main() { // mbstate_t comes from the underlying C library; it is defined (in C99) as: // a complete object type other than an array type that can hold the conversion // state information necessary to convert between sequences of multibyte // characters and wide characters #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wmissing-braces" #endif mbstate_t mb = {0}; #if defined(__clang__) #pragma clang diagnostic pop #endif size_t s = 0; tm *tm = 0; wint_t w = 0; ::FILE* fp = 0; #ifdef __APPLE__ __darwin_va_list va; #else __builtin_va_list va; #endif char* ns = 0; wchar_t* ws = 0; static_assert((std::is_same<decltype(fwprintf(fp, L"")), int>::value), ""); static_assert((std::is_same<decltype(fwscanf(fp, L"")), int>::value), ""); static_assert((std::is_same<decltype(swprintf(ws, s, L"")), int>::value), ""); static_assert((std::is_same<decltype(swscanf(L"", L"")), int>::value), ""); static_assert((std::is_same<decltype(vfwprintf(fp, L"", va)), int>::value), ""); static_assert((std::is_same<decltype(vfwscanf(fp, L"", va)), int>::value), ""); static_assert((std::is_same<decltype(vswprintf(ws, s, L"", va)), int>::value), ""); static_assert((std::is_same<decltype(vswscanf(L"", L"", va)), int>::value), ""); static_assert((std::is_same<decltype(fgetwc(fp)), wint_t>::value), ""); static_assert((std::is_same<decltype(fgetws(ws, 0, fp)), wchar_t*>::value), ""); static_assert((std::is_same<decltype(fputwc(L' ', fp)), wint_t>::value), ""); static_assert((std::is_same<decltype(fputws(L"", fp)), int>::value), ""); static_assert((std::is_same<decltype(fwide(fp, 0)), int>::value), ""); static_assert((std::is_same<decltype(getwc(fp)), wint_t>::value), ""); static_assert((std::is_same<decltype(putwc(L' ', fp)), wint_t>::value), ""); static_assert((std::is_same<decltype(ungetwc(L' ', fp)), wint_t>::value), ""); static_assert((std::is_same<decltype(wcstod(L"", (wchar_t**)0)), double>::value), ""); static_assert((std::is_same<decltype(wcstof(L"", (wchar_t**)0)), float>::value), ""); static_assert((std::is_same<decltype(wcstold(L"", (wchar_t**)0)), long double>::value), ""); static_assert((std::is_same<decltype(wcstol(L"", (wchar_t**)0, 0)), long>::value), ""); static_assert((std::is_same<decltype(wcstoll(L"", (wchar_t**)0, 0)), long long>::value), ""); static_assert((std::is_same<decltype(wcstoul(L"", (wchar_t**)0, 0)), unsigned long>::value), ""); static_assert((std::is_same<decltype(wcstoull(L"", (wchar_t**)0, 0)), unsigned long long>::value), ""); static_assert((std::is_same<decltype(wcscpy(ws, L"")), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcsncpy(ws, L"", s)), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcscat(ws, L"")), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcsncat(ws, L"", s)), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcscmp(L"", L"")), int>::value), ""); static_assert((std::is_same<decltype(wcscoll(L"", L"")), int>::value), ""); static_assert((std::is_same<decltype(wcsncmp(L"", L"", s)), int>::value), ""); static_assert((std::is_same<decltype(wcsxfrm(ws, L"", s)), size_t>::value), ""); static_assert((std::is_same<decltype(wcschr((wchar_t*)0, L' ')), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcscspn(L"", L"")), size_t>::value), ""); static_assert((std::is_same<decltype(wcslen(L"")), size_t>::value), ""); static_assert((std::is_same<decltype(wcspbrk((wchar_t*)0, L"")), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcsrchr((wchar_t*)0, L' ')), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcsspn(L"", L"")), size_t>::value), ""); static_assert((std::is_same<decltype(wcsstr((wchar_t*)0, L"")), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcstok(ws, L"", (wchar_t**)0)), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wmemchr((wchar_t*)0, L' ', s)), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wmemcmp(L"", L"", s)), int>::value), ""); static_assert((std::is_same<decltype(wmemcpy(ws, L"", s)), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wmemmove(ws, L"", s)), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wmemset(ws, L' ', s)), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcsftime(ws, s, L"", tm)), size_t>::value), ""); static_assert((std::is_same<decltype(btowc(0)), wint_t>::value), ""); static_assert((std::is_same<decltype(wctob(w)), int>::value), ""); static_assert((std::is_same<decltype(mbsinit(&mb)), int>::value), ""); static_assert((std::is_same<decltype(mbrlen("", s, &mb)), size_t>::value), ""); static_assert((std::is_same<decltype(mbrtowc(ws, "", s, &mb)), size_t>::value), ""); static_assert((std::is_same<decltype(wcrtomb(ns, L' ', &mb)), size_t>::value), ""); static_assert((std::is_same<decltype(mbsrtowcs(ws, (const char**)0, s, &mb)), size_t>::value), ""); static_assert((std::is_same<decltype(wcsrtombs(ns, (const wchar_t**)0, s, &mb)), size_t>::value), ""); // These tests fail on systems whose C library doesn't provide a correct overload // set for wcschr, wcspbrk, wcsrchr, wcsstr, and wmemchr, unless the compiler is // a suitably recent version of Clang. #if !defined(__APPLE__) || defined(_LIBCPP_PREFERRED_OVERLOAD) static_assert((std::is_same<decltype(wcschr((const wchar_t*)0, L' ')), const wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcspbrk((const wchar_t*)0, L"")), const wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcsrchr((const wchar_t*)0, L' ')), const wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcsstr((const wchar_t*)0, L"")), const wchar_t*>::value), ""); static_assert((std::is_same<decltype(wmemchr((const wchar_t*)0, L' ', s)), const wchar_t*>::value), ""); #endif #ifndef _LIBCPP_HAS_NO_STDIN static_assert((std::is_same<decltype(getwchar()), wint_t>::value), ""); static_assert((std::is_same<decltype(vwscanf(L"", va)), int>::value), ""); static_assert((std::is_same<decltype(wscanf(L"")), int>::value), ""); #endif #ifndef _LIBCPP_HAS_NO_STDOUT static_assert((std::is_same<decltype(putwchar(L' ')), wint_t>::value), ""); static_assert((std::is_same<decltype(vwprintf(L"", va)), int>::value), ""); static_assert((std::is_same<decltype(wprintf(L"")), int>::value), ""); #endif }
bool SettingsXML::Load(const wchar_t *regName, LPBYTE value, DWORD nSize) { bool lbRc = false; HRESULT hr = S_OK; IXMLDOMNode* pChild = NULL; IXMLDOMNamedNodeMap* pAttrs = NULL; IXMLDOMAttribute *pIXMLDOMAttribute = NULL; IXMLDOMNode *pNode = NULL; BSTR bsType = NULL; BSTR bsData = NULL; if (!value || !nSize) return false; if (mp_Key) pChild = FindItem(mp_Key, L"value", regName, false); if (!pChild) return false; hr = pChild->get_attributes(&pAttrs); if (SUCCEEDED(hr) && pAttrs) { bsType = GetAttr(pChild, pAttrs, L"type"); } if (SUCCEEDED(hr) && bsType) { bsData = GetAttr(pChild, pAttrs, L"data"); } if (SUCCEEDED(hr) && bsData) { if (!lstrcmpi(bsType, L"string")) { #ifdef _DEBUG DWORD nLen = _tcslen(bsData) + 1; #endif DWORD nMaxLen = nSize / 2; lstrcpyn((wchar_t*)value, bsData, nMaxLen); lbRc = true; } else if (!lstrcmpi(bsType, L"ulong")) { wchar_t* pszEnd = NULL; DWORD lVal = wcstoul(bsData, &pszEnd, 10); if (nSize > 4) nSize = 4; if (pszEnd && pszEnd != bsData) { memmove(value, &lVal, nSize); lbRc = true; } } else if (!lstrcmpi(bsType, L"long")) { wchar_t* pszEnd = NULL; int lVal = wcstol(bsData, &pszEnd, 10); if (nSize > 4) nSize = 4; if (pszEnd && pszEnd != bsData) { memmove(value, &lVal, nSize); lbRc = true; } } else if (!lstrcmpi(bsType, L"dword")) { wchar_t* pszEnd = NULL; DWORD lVal = wcstoul(bsData, &pszEnd, 16); if (nSize > 4) nSize = 4; if (pszEnd && pszEnd != bsData) { memmove(value, &lVal, nSize); lbRc = true; } } else if (!lstrcmpi(bsType, L"hex")) { wchar_t* pszCur = bsData; wchar_t* pszEnd = NULL; LPBYTE pCur = value; wchar_t cHex; DWORD lVal = 0; lbRc = true; while (*pszCur && nSize) { lVal = 0; cHex = *(pszCur++); if (cHex >= L'0' && cHex <= L'9') { lVal = cHex - L'0'; } else if (cHex >= L'a' && cHex <= L'f') { lVal = cHex - L'a' + 10; } else if (cHex >= L'A' && cHex <= L'F') { lVal = cHex - L'A' + 10; } else { lbRc = false; break; } cHex = *(pszCur++); if (cHex && cHex != L',') { lVal = lVal << 4; if (cHex >= L'0' && cHex <= L'9') { lVal |= cHex - L'0'; } else if (cHex >= L'a' && cHex <= L'f') { lVal |= cHex - L'a' + 10; } else if (cHex >= L'A' && cHex <= L'F') { lVal |= cHex - L'A' + 10; } else { lbRc = false; break; } cHex = *(pszCur++); } *pCur = (BYTE)lVal; pCur++; nSize--; if (cHex != L',') { break; } } while(nSize--) // очистить хвост *(pCur++) = 0; } } // Остальные типы (строки) - не интересуют if (bsType) { ::SysFreeString(bsType); bsType = NULL; } if (bsData) { ::SysFreeString(bsData); bsData = NULL; } if (pChild) { pChild->Release(); pChild = NULL; } if (pAttrs) { pAttrs->Release(); pAttrs = NULL; } return lbRc; }
int _tmain(int nArgs, TCHAR *argv[]) { RETVAL rv; HANDLE hRemoteProc = NULL; HANDLE hRemoteProcToken = NULL; bool bSignalThisProcessGroup = false; if (nArgs != 2 || ((argv[1][0] == '/' || argv[1][0] == '-') && (argv[1][1] == 'H' || argv[1][1] == 'h'|| argv[1][1] == '?') )) { PrintHelp(); exit(1); } // check for the special parameter TCHAR *szPid = argv[1]; bSignalThisProcessGroup = ('-' == szPid[0]); TCHAR *szEnd; DWORD dwPid = wcstoul(szPid, &szEnd, 0); if (bSignalThisProcessGroup == false && (szPid == szEnd || dwPid == 0)) { _tprintf(__T("\"%ls\" is not a valid PID.\n"), szPid); rv = ERROR_INVALID_PARAMETER; goto error; } //_tprintf(__T("Determining address of kernel32!CtrlRoutine...\n"); rv = GetCtrlRoutineAddress(); if (rv != EXIT_OK) { _HandleError(rv, __T("GetCtrlRoutineAddress")); } //_tprintf(__T("Address is 0x%08X.\n", g_dwCtrlRoutineAddr); // open the process if (argv[1][0] == '-') { _tprintf(__T("Sending signal to self...\n")); hRemoteProc = GetCurrentProcess(); } else { _tprintf(__T("Sending signal to process %d...\n"), dwPid); rv = AdvancedOpenProcess(dwPid, &hRemoteProc); if (rv != EXIT_OK) { _HandleError1(rv, __T("AdvancedOpenProcess"), argv[1]); } } rv = StartRemoteThread(hRemoteProc, g_dwCtrlRoutineAddr); if (rv != EXIT_OK) { _HandleError(rv, __T("StartRemoteThread")); } //done: rv = EXIT_OK; error: if (hRemoteProc != NULL && hRemoteProc != GetCurrentProcess()) { if (!CloseHandle(hRemoteProc)) { RETVAL rv2 = GetLastError(); _TeardownIfError(rv, rv2, __T("CloseHandle")); } } if (rv != EXIT_OK) { _tprintf(__T("0x%08X == "), rv); PrintError(rv); } return rv; }
int DoInjectRemote(LPWSTR asCmdArg, bool abDefTermOnly) { gbInShutdown = TRUE; // чтобы не возникло вопросов при выходе gnRunMode = RM_SETHOOK64; LPWSTR pszNext = asCmdArg; LPWSTR pszEnd = NULL; DWORD nRemotePID = wcstoul(pszNext, &pszEnd, 10); wchar_t szStr[16]; wchar_t szTitle[128]; wchar_t szInfo[120]; wchar_t szParentPID[32]; #ifdef _DEBUG extern int ShowInjectRemoteMsg(int nRemotePID, LPCWSTR asCmdArg); if (ShowInjectRemoteMsg(nRemotePID, asCmdArg) != IDOK) { return CERR_HOOKS_FAILED; } #endif if (nRemotePID) { #if defined(SHOW_ATTACH_MSGBOX) if (!IsDebuggerPresent()) { wchar_t szTitle[100]; _wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"%s PID=%u /INJECT", gsModuleName, gnSelfPID); const wchar_t* pszCmdLine = GetCommandLineW(); MessageBox(NULL,pszCmdLine,szTitle,MB_SYSTEMMODAL); } #endif CEStr lsName, lsPath; { CProcessData processes; processes.GetProcessName(nRemotePID, lsName.GetBuffer(MAX_PATH), MAX_PATH, lsPath.GetBuffer(MAX_PATH*2), MAX_PATH*2, NULL); CEStr lsLog(L"Remote: PID=", _ultow(nRemotePID, szStr, 10), L" Name=`", lsName, L"` Path=`", lsPath, L"`"); LogString(lsLog); } // Go to hook // InjectRemote waits for thread termination DWORD nErrCode = 0; CINFILTRATE_EXIT_CODES iHookRc = InjectRemote(nRemotePID, abDefTermOnly, &nErrCode); _wsprintf(szInfo, SKIPCOUNT(szInfo) L"InjectRemote result: %i (%s)", iHookRc, (iHookRc == CIR_OK) ? L"CIR_OK" : (iHookRc == CIR_AlreadyInjected) ? L"CIR_AlreadyInjected" : L"?"); LogString(szInfo); if (iHookRc == CIR_OK/*0*/ || iHookRc == CIR_AlreadyInjected/*1*/) { return iHookRc ? CERR_HOOKS_WAS_ALREADY_SET : CERR_HOOKS_WAS_SET; } else if ((iHookRc == CIR_ProcessWasTerminated) || (iHookRc == CIR_OpenProcess)) { // Don't show error message to user. These codes are logged to file only. return CERR_HOOKS_FAILED; } DWORD nSelfPID = GetCurrentProcessId(); PROCESSENTRY32 self = {sizeof(self)}, parent = {sizeof(parent)}; // Not optimal, needs refactoring if (GetProcessInfo(nSelfPID, &self)) GetProcessInfo(self.th32ParentProcessID, &parent); // Ошибку (пока во всяком случае) лучше показать, для отлова возможных проблем //_ASSERTE(iHookRc == 0); -- ассерт не нужен, есть MsgBox _wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"%s %s, PID=%u", gsModuleName, gsVersion, nSelfPID); _wsprintf(szInfo, SKIPCOUNT(szInfo) L"Injecting remote FAILED, code=%i:0x%08X\n" L"%s %s, PID=%u\n" L"RemotePID=%u ", iHookRc, nErrCode, gsModuleName, gsVersion, nSelfPID, nRemotePID); _wsprintf(szParentPID, SKIPCOUNT(szParentPID) L"\n" L"ParentPID=%u ", self.th32ParentProcessID); CEStr lsError(lstrmerge( szInfo, lsPath.IsEmpty() ? lsName.IsEmpty() ? L"<Unknown>" : lsName.ms_Val : lsPath.ms_Val, szParentPID, parent.szExeFile)); LogString(lsError); MessageBoxW(NULL, lsError, szTitle, MB_SYSTEMMODAL); } else { //_ASSERTE(pi.hProcess && pi.hThread && pi.dwProcessId && pi.dwThreadId); wchar_t szDbgMsg[512], szTitle[128]; _wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"ConEmuC, PID=%u", GetCurrentProcessId()); _wsprintf(szDbgMsg, SKIPLEN(countof(szDbgMsg)) L"ConEmuC.X, PID=%u\nCmdLine parsing FAILED (%u)!\n%s", GetCurrentProcessId(), nRemotePID, asCmdArg); LogString(szDbgMsg); MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL); } return CERR_HOOKS_FAILED; }
int _tmain(int argc, _TCHAR* argv[]) { //---------------- hLog = fopen("log.txt", "w"); LPCTSTR path = L".\\options.ini"; TCHAR stecilPicturePathResult[4096]; TCHAR maskedPicturePathResult[4096]; TCHAR serverPortResult[255]; TCHAR serverIPResult[255]; TCHAR listenUDPPortResult[255]; TCHAR listenUDPIPResult[255]; TCHAR colorResult[255]; TCHAR shiftXResult[255]; TCHAR shiftYResult[255]; TCHAR isEyeWindowShowResult[255]; TCHAR isEyePositionWindowShowResult[255]; TCHAR isCalibrateResult[255]; char buffer[4096]; GetPrivateProfileString(_T("Base"), _T("stecilPicturePath"), _T(""), stecilPicturePathResult, sizeof(buffer), path); GetPrivateProfileString(_T("Base"), _T("maskedPicturePath"), _T(""), maskedPicturePathResult, sizeof(buffer), path); GetPrivateProfileString(_T("Base"), _T("serverPort"), _T(""), serverPortResult, 255, path); GetPrivateProfileString(_T("Base"), _T("serverIP"), _T(""), serverIPResult, 255, path); GetPrivateProfileString(_T("Base"), _T("listenUDPPort"), _T(""), listenUDPPortResult, 255, path); GetPrivateProfileString(_T("Base"), _T("listenUDPIP"), _T(""), listenUDPIPResult, 255, path); GetPrivateProfileString(_T("Base"), _T("color"), _T(""), colorResult, 255, path); GetPrivateProfileString(_T("Base"), _T("shiftX"), _T(""), shiftXResult, 255, path); GetPrivateProfileString(_T("Base"), _T("shiftY"), _T(""), shiftYResult, 255, path); GetPrivateProfileString(_T("Base"), _T("isEyeWindowShow"), _T(""), isEyeWindowShowResult, 255, path); GetPrivateProfileString(_T("Base"), _T("isEyePositionWindowShow"), _T(""), isEyePositionWindowShowResult, 255, path); GetPrivateProfileString(_T("Base"), _T("isCalibrate"), _T(""), isCalibrateResult, 255, path); int shiftXint = _ttoi(shiftXResult); int shiftYint = _ttoi(shiftYResult); int serverPortint = _ttoi(serverPortResult); int listenUDPPortint = _ttoi(listenUDPPortResult); desiredColor = wcstoul(colorResult, NULL, 0x10); char serverIPChar[255]; wcstombs(serverIPChar, serverIPResult, wcslen(serverIPResult) + 1); char listenUDPIPChar[255]; wcstombs(listenUDPIPChar, listenUDPIPResult, wcslen(listenUDPIPResult) + 1); bool isEyeWindowShowBool = false; bool isEyePositionWindowShow = false; bool isCalibrate = false; if(_tcscmp(isEyeWindowShowResult, L"true") == 0){ isEyeWindowShowBool = true; } if(_tcscmp(isEyePositionWindowShowResult, L"true") == 0){ isEyePositionWindowShow = true; } if(_tcscmp(isCalibrateResult, L"true") == 0){ isCalibrate = true; } //getchar(); //return 0; // screenMasker.exe 757575 checker4px.pgm stencil.pgm 23 45 Y" // parse arguments //E:\OrlovPA\screenMasker\screenmasker\screenMasker_bin\screenMasker_bin\screenMasker.exe 757575 bg.pgm stencil.pgm 0 //LPWSTR *argc; //LPWSTR bgPath; //wchar_t newBgPath[] = L"E:\\OrlovPA\\screenMasker\\screenmasker\\screenMasker_bin\\screenMasker_bin\\bg.pgm"; //wchar_t newBgPath[] = maskedPicturePathResult; //LPWSTR stencilPath; //wchar_t newStencilPath[] = L"E:\\OrlovPA\\screenMasker\\screenmasker\\screenMasker_bin\\screenMasker_bin\\stencil.pgm"; //int localstencilX, localstencilY, localCoursor; //wchar_t myColor = '757575'; //const wchar_t * myColorAdress = &myColor; //desiredColor = wcstoul(L"1a3399", NULL, 0x10); //desiredColor = 757575; isCoursor = 1; // read background and stencil to buffers UINT8 *bytes; int width; int height; //bytes = readPGM(bgPath, &width, &height); bytes = readPGM(maskedPicturePathResult, &width, &height); //bytes = readPGM(newBgPath, &width, &height); if(bytes == NULL) { return 1; } bgBmpBytes = bytes; bgBmpWidth = width; bgBmpHeight = height; //bytes = readPGM(newStencilPath, &width, &height); bytes = readPGM(stecilPicturePathResult, &width, &height); if(bytes == NULL){ return 1; } stencilBmpBytes = bytes; stencilBmpWidth = width; stencilBmpHeight = height; //---------------- POINT pt = {}; HMONITOR hMon; MONITORINFO monitorInfo = {}; GetCursorPos(&pt); hMon = MonitorFromPoint(pt, MONITOR_DEFAULTTOPRIMARY); monitorInfo.cbSize = sizeof(MONITORINFO); GetMonitorInfo(hMon, &monitorInfo); mX = monitorInfo.rcMonitor.left; mY = monitorInfo.rcMonitor.top; mW = monitorInfo.rcMonitor.right - monitorInfo.rcMonitor.left; mH = monitorInfo.rcMonitor.bottom - monitorInfo.rcMonitor.top; WNDCLASSEX wc; MSG msg; // Init wc wc.cbSize = sizeof( WNDCLASSEX ); wc.style = 0; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = GetModuleHandle(0); wc.hIcon = NULL; wc.hCursor = LoadCursor( NULL, IDC_ARROW ); wc.hbrBackground = NULL; wc.hIconSm = NULL; wc.lpszClassName = toString("animation_class"); wc.lpszMenuName = NULL; // Register wc if ( !RegisterClassEx(&wc) ) { MessageBox( NULL, toString("Failed to register window class."), toString("Error"), MB_OK ); return 0; } // Make window hwnd = CreateWindowEx( //WS_EX_APPWINDOW, WS_EX_LAYERED | WS_EX_TOPMOST | WS_EX_TRANSPARENT, toString("animation_class"), toString("Animation"), WS_POPUP | WS_SYSMENU, mX, mY, mW, mH, NULL, NULL, GetModuleHandle(0), NULL ); assert(hwnd); /* RECT rcClient, rcWindow; POINT ptDiff; // Get window and client sizes GetClientRect( hwnd, &rcClient ); GetWindowRect( hwnd, &rcWindow ); // Find offset between window size and client size ptDiff.x = (rcWindow.right - rcWindow.left) - rcClient.right; ptDiff.y = (rcWindow.bottom - rcWindow.top) - rcClient.bottom; // Resize client MoveWindow( hwnd, rcWindow.left, rcWindow.top, width + ptDiff.x, height + ptDiff.y, false); //UpdateLayeredWindow(hwnd, NULL, &ptDst, &siz, hdcOutBmp, &ptZero, 0, &blendFunc, ULW_ALPHA); //SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 0x0, LWA_COLORKEY); */ ShowWindow( hwnd, SW_SHOWDEFAULT ); UpdateWindow( hwnd ); initGpuResources( bgBmpBytes, stencilBmpBytes, bgBmpWidth, bgBmpHeight, stencilBmpHeight, stencilBmpWidth, mW, mH ); //**************************** AccuracyStruct accuracyData; SystemInfoStruct systemInfoData; CalibrationStruct calibrationData; int ret_calibrate = 0, ret_validate = 0, ret_connect = 0; char c = ' '; char repeat = ' '; std::cout << "Output from iViewXAPI Demo"<< std::endl; // define logger iV_SetLogger(1, "ScreenMasker.txt"); std::cout << "ScreenMasker on iViewX API" << std::endl; // connect to iViewX ret_connect = iV_Connect(serverIPChar, serverPortint, listenUDPIPChar, listenUDPPortint); switch(ret_connect) { case RET_SUCCESS: std::cout << "Connection was established successfully" << std::endl; // read out meta data from iViewX std::cout << "GetSystemInfo: " << iV_GetSystemInfo(&systemInfoData) << std::endl; std::cout << "SystemInfo ETSystem: " << systemInfoData.iV_ETDevice << std::endl; std::cout << "SystemInfo iV_Version: " << systemInfoData.iV_MajorVersion << "." << systemInfoData.iV_MinorVersion << "." << systemInfoData.iV_Buildnumber << std::endl; std::cout << "SystemInfo API_Version: " << systemInfoData.API_MajorVersion << "." << systemInfoData.API_MinorVersion << "." << systemInfoData.API_Buildnumber << std::endl; std::cout << "SystemInfo samplerate: " << systemInfoData.samplerate << std::endl; break; case ERR_COULD_NOT_CONNECT: std::cout << "Connection could not be established" << std::endl; break; case ERR_WRONG_PARAMETER: std::cout << "Wrong Parameter used" << std::endl; break; default: std::cout << "Any other error appeared" << std::endl; return 0; } if(ret_connect == RET_SUCCESS) { calibrationData.method = 5; calibrationData.speed = 0; calibrationData.displayDevice = 0; calibrationData.targetShape = 20; calibrationData.foregroundBrightness = 250; calibrationData.backgroundBrightness = 100; calibrationData.autoAccept = 1; calibrationData.targetSize = 10; calibrationData.visualization = 1; strcpy(calibrationData.targetFilename, ""); iV_SetupCalibration(&calibrationData); // start calibration //std::cout << "Do you want to calibrate? (y)es | (n)o" << std::endl; //c = getchar(); if(isCalibrate){ ret_calibrate = iV_Calibrate(); switch(ret_calibrate){ case RET_SUCCESS: std::cout << "Calibration done successfully" << std::endl; // start validation ret_validate = iV_Validate(); break; case ERR_NOT_CONNECTED: std::cout << "iViewX is not reachable" << std::endl; break; case ERR_WRONG_PARAMETER: std::cout << "Wrong Parameter used" << std::endl; break; case ERR_WRONG_DEVICE: std::cout << "Not possible to calibrate connected Eye Tracking System" << std::endl; break; default: std::cout << "An unknown error appeared" << std::endl; break; } } // show accuracy only if validation was successful if(ret_validate == RET_SUCCESS){ std::cout << "iV_GetAccuracy: " << iV_GetAccuracy(&accuracyData, 0) << std::endl; std::cout << "AccuracyData DevX: " << accuracyData.deviationLX << " DevY: " << accuracyData.deviationLY << std::endl; //getchar(); } if(isEyeWindowShowBool){ iV_ShowEyeImageMonitor(); } if(isEyePositionWindowShow){ iV_ShowTrackingMonitor(); iV_ShowSceneVideoMonitor(); } // start data output via callback function // define a callback function for receiving samples iV_SetSampleCallback(SampleCallbackFunction); iV_SetTrackingMonitorCallback(TrackingMonitorCallbackFunction); while ( GetMessage(&msg, 0, 0, NULL) > 0 ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } /* getchar(); iV_SetSampleCallback(NULL); iV_SetTrackingMonitorCallback(NULL); std::cout << "iV_Disconnect: " << iV_Disconnect() << std::endl; getchar(); */ } freeGpuResources(); fclose(hLog); return 0; }
int DriveMng::SetDriveID(const WCHAR *_root) { if (!_root || !_root[0]) return -1; WCHAR root[MAX_PATH]; int idx = -1; ::CharUpperW(wcscpy(root, _root)); if (root[1] == ':') { idx = DrvLetterToIndex(root[0]); if (idx < 0 || idx >= MAX_LOCAL_DRIVES) return -1; } else { // ネットワークドライブの場合、\\server\volume\ もしくは \\server\ (設定に依存) // を大文字にした文字列のハッシュ値を識別値(drvId[].data)とする ModifyNetRoot(root); uint64 hash_id = MakeHash64(root, (int)wcslen(root)); if ((idx = shareInfo->RegisterNetDrive(hash_id)) < 0) return -1; if (drvID[idx].len) return idx; // already registerd RegisterDriveID(idx, &hash_id, sizeof(hash_id)); return idx; } if (drvID[idx].len) return idx; // already registerd if (::GetDriveTypeW(root) == DRIVE_REMOTE) { BYTE buf[2048]; DWORD size = sizeof(buf); REMOTE_NAME_INFOW *pni = (REMOTE_NAME_INFOW *)buf; if (::WNetGetUniversalNameW(root, REMOTE_NAME_INFO_LEVEL, pni, &size) != NO_ERROR) { //Debug("WNetGetUniversalNameW err=%d\n", GetLastError()); return -1; } wcscpy(root, pni->lpUniversalName); ::CharUpperW(root); ModifyNetRoot(root); uint64 hash_id = MakeHash64(root, (int)wcslen(root)); RegisterDriveID(idx, &hash_id, sizeof(hash_id)); int net_idx = shareInfo->RegisterNetDrive(hash_id); if (net_idx >= 0) RegisterDriveID(net_idx, &hash_id, sizeof(hash_id)); return idx; } WCHAR vol_name[MAX_PATH]; if (::GetVolumeNameForVolumeMountPointW(root, vol_name, MAX_PATH)) { vol_name[wcslen(vol_name) -1] = 0; HANDLE hFile = ::CreateFileW(vol_name, FILE_READ_ATTRIBUTES, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0); if (hFile != INVALID_HANDLE_VALUE) { VOLUME_DISK_EXTENTS vde = {}; DWORD size; DWORD val = 0; if (::DeviceIoControl(hFile, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, 0, 0, &vde, sizeof(vde), &size, 0) || GetLastError() == ERROR_MORE_DATA) { if (vde.NumberOfDiskExtents >= 1) { // SetDriveMapが ID: 1~Nを利用するため、オフセット0x1000を加算 val = vde.Extents[0].DiskNumber | 0x1000; //Debug("disk id = %d\n", vde.Extents[0].DiskNumber); } } ::CloseHandle(hFile); if (val) { RegisterDriveID(idx, &val, sizeof(val)); return idx; } } } TRegistry reg(HKEY_LOCAL_MACHINE); if (reg.OpenKey(MOUNTED_DEVICES)) { char reg_path[MAX_PATH * 2]; BYTE buf[1024]; int size = sizeof(buf); WCHAR *wbuf = (WCHAR *)buf, *wp; DWORD val = 0; ::sprintf(reg_path, FMT_DOSDEVICES, root[0]); if (reg.GetByte(reg_path, buf, &size)) { if (wcsncmp(wbuf, L"\\??\\", 4) == 0 && (wp = wcschr(wbuf, '#')) && (wp = wcschr(wp+1, '#')) && (wp = wcschr(wp, '&'))) { val = wcstoul(wp+1, 0, 16); } else if (wcsncmp(wbuf, L"_??_", 4) == 0 && (wp = wcschr(wbuf, '{'))) { val = wcstoul(wp+1, 0, 16); } else if (wcsncmp(wbuf, L"DMIO:ID:", 8) == 0) { val = *(DWORD *)(wbuf + 8); } else { val = *(DWORD *)buf; } if (val <= 30) val |= 0x88000000; RegisterDriveID(idx, &val, sizeof(val)); return idx; } } RegisterDriveID(idx, "", 1); return idx; }
_MY_C_HEAD_ #include "LZMA/7zVersion.h" #include "LZMA/Alloc.h" #include "LZMA/Lzma86.h" _MY_C_TAIL_ void __cdecl main2(int argc, wchar_t **argv) { if (argc < 3) { printf("Too few parameters\n"); return; } Byte *outBuffer, FileType, bLZMA; SizeT inSize, outSize, outMaxSize; WCHAR szFileName[MAX_PATH]; WCHAR *szFileType[] = { L"UCA", L"UCI", L"AAC", L"M4A", L"Unknown" }; PBYTE pbFile; DWORD dwFileNumber, dwErrorCount, dwMaxNumber, dwFileSize, dwRead; DWORD dwBufferSize, dwMaxFileNumber, dwMethod[] = {'ACU', 'ICU', 'CAA', 'A4M', 'KNU'}; HANDLE hFind, hHeap, hFile, hDestFile; WIN32_FIND_DATAW wfd; TSpiArchiveInfo *pSpiArcInfo; LARGE_INTEGER liFrequency, liStart, liStop; setlocale(LC_CTYPE, ""); hDestFile = CreateFileW(argv[2], GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hDestFile == INVALID_HANDLE_VALUE) { wprintf(L"Can't create %s\n", argv[2]); return; } swprintf(szFileName, L"%s\\*.*", argv[1]); hFind = FindFirstFileW(szFileName, &wfd); if (hFind == INVALID_HANDLE_VALUE) { wprintf(L"Can't find %s\n", szFileName); return; } outMaxSize = 0; dwBufferSize = 0; dwErrorCount = 0; dwFileNumber = 0; dwMaxNumber = 1000; hHeap = GetProcessHeap(); pbFile = (PBYTE)HeapAlloc(hHeap, 0, 0); outBuffer = (Byte *)HeapAlloc(hHeap, 0, 0); pSpiArcInfo = (TSpiArchiveInfo *)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, dwMaxNumber * sizeof(*pSpiArcInfo)); WriteFile(hDestFile, pSpiArcInfo, 0x10, &dwRead, NULL); bLZMA = argc >= 4 ? (Byte)wcstoul(argv[3], NULL, 10) : 1; dwMaxFileNumber = argc == 5 ? wcstoul(argv[4], NULL, 10) : -1; QueryPerformanceFrequency(&liFrequency); QueryPerformanceCounter(&liStart); do { if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue; swprintf(szFileName, L"%s\\%s", argv[1], wfd.cFileName); hFile = CreateFileW(szFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { wprintf(L"Open %s failed.\n", szFileName); ++dwErrorCount; continue; } if (dwFileNumber >= dwMaxNumber) { dwMaxNumber = dwMaxNumber + (dwMaxNumber >> 1); pSpiArcInfo = (TSpiArchiveInfo *)HeapReAlloc(hHeap, HEAP_ZERO_MEMORY, pSpiArcInfo, dwMaxNumber * sizeof(*pSpiArcInfo)); } dwFileSize = GetFileSize(hFile, NULL); if (dwFileSize > dwBufferSize) { dwBufferSize = dwFileSize; pbFile = (PBYTE)HeapReAlloc(hHeap, 0, pbFile, dwBufferSize); } ReadFile(hFile, pbFile, dwFileSize, &dwRead, NULL); CloseHandle(hFile); FileType = CheckFileType(pbFile); wprintf(L"Packing %s ... %s ", szFileName, szFileType[FileType]); pSpiArcInfo[dwFileNumber].position = SetFilePointer(hDestFile, 0, 0, FILE_CURRENT); if (dwFileSize > 300 && bLZMA && FileType != UCI && FileType != M4A && FileType != AAC) { outSize = dwFileSize / 20 * 21 + (1 << 16) + 4; if (outSize > outMaxSize) { outMaxSize = outSize; outBuffer = (Byte *)HeapReAlloc(hHeap, 0, outBuffer, outSize); } Lzma86_Encode(outBuffer, &outSize, (Byte *)pbFile, dwFileSize, 9, 1 << 27, 0); pSpiArcInfo[dwFileNumber].compsize = outSize; WriteFile(hDestFile, outBuffer, outSize, &dwRead, NULL); wprintf(L"@ compressed ... "); } else { if (FileType != UCI && FileType != UCA) { WriteFile(hDestFile, &dwFileSize, 4, &dwRead, NULL); } WriteFile(hDestFile, pbFile, dwFileSize, &dwRead, NULL); pSpiArcInfo[dwFileNumber].compsize = dwFileSize; } if (FileType != UNKNOWN) { *(LPDWORD)&pSpiArcInfo[dwFileNumber].method = dwMethod[FileType]; } int w, h, b; CHAR *p; HSTREAM hStream; static BOOL bBassInit = FALSE; WideCharToMultiByte(936, 0, wfd.cFileName, -1, pSpiArcInfo[dwFileNumber].filename, sizeof(pSpiArcInfo[dwFileNumber].filename), NULL, NULL); if (FileType == UNKNOWN) { CHAR *pExt = PathFindExtensionA(pSpiArcInfo[dwFileNumber].filename); if (pExt++) { lstrcpynA((LPSTR)pSpiArcInfo[dwFileNumber].method, pExt, sizeof(pSpiArcInfo->method)); } else { *(LPDWORD)&pSpiArcInfo[dwFileNumber].method = 'KNU'; } } p = PathFindExtensionA(pSpiArcInfo[dwFileNumber].filename); switch (FileType) { case UCA: UCADecode(pbFile, dwFileSize, NULL,(int *)&pSpiArcInfo[dwFileNumber].filesize); if (p) { lstrcpyA(p + 1, "wav"); } printf("OK!"); break; case UCI: UCIDecode(pbFile, dwFileSize, NULL, NULL, &w, &h, &b); pSpiArcInfo[dwFileNumber].filesize = (w * b / 8 + (b == 0x18 ? (w & 3) : 0)) * h + sizeof(TBitMapHeader); if (p) { lstrcpyA(p + 1, "bmp"); } printf("OK!"); break; case AAC: case M4A: if (bBassInit == FALSE) { bBassInit = TRUE; if (BASS_Init(0, 44100, 0, NULL, NULL) == FALSE) { ++dwErrorCount; printf("failed!"); break; } } hStream = FileType == AAC ? BASS_AAC_StreamCreateFile(TRUE, pbFile, 0, dwFileSize, BASS_STREAM_DECODE) : BASS_MP4_StreamCreateFile(TRUE, pbFile, 0, dwFileSize, BASS_STREAM_DECODE); if (hStream) { pSpiArcInfo[dwFileNumber].filesize = (DWORD)BASS_ChannelGetLength(hStream, BASS_POS_BYTE) + + sizeof(TWaveHeader); BASS_StreamFree(hStream); if (p) { lstrcpyA(p + 1, "wav"); } printf("OK!"); } else { ++dwErrorCount; printf("failed!"); } break; default: pSpiArcInfo[dwFileNumber].filesize = dwFileSize; printf("OK!"); } wprintf(L"\n"); ++dwFileNumber; } while (dwFileNumber < dwMaxFileNumber && FindNextFileW(hFind, &wfd));
dword StringBase::strdword( const wchar * p, int nBase /*= 10*/ ) { return wcstoul( p, NULL, nBase ); }
// // Based on the input switches, pick the specified device to use. // bool PickDevice(IMMDevice **DeviceToUse, bool *IsDefaultDevice, ERole *DefaultDeviceRole) { HRESULT hr; bool retValue = true; IMMDeviceEnumerator *deviceEnumerator = NULL; IMMDeviceCollection *deviceCollection = NULL; *IsDefaultDevice = false; // Assume we're not using the default device. hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&deviceEnumerator)); if (FAILED(hr)) { printf("Unable to instantiate device enumerator: %x\n", hr); retValue = false; goto Exit; } IMMDevice *device = NULL; // // First off, if none of the console switches was specified, use the console device. // if (!UseConsoleDevice && !UseCommunicationsDevice && !UseMultimediaDevice && OutputEndpoint == NULL) { // // The user didn't specify an output device, prompt the user for a device and use that. // hr = deviceEnumerator->EnumAudioEndpoints(eCapture, DEVICE_STATE_ACTIVE, &deviceCollection); if (FAILED(hr)) { printf("Unable to retrieve device collection: %x\n", hr); retValue = false; goto Exit; } printf("Select an output device:\n"); printf(" 0: Default Console Device\n"); printf(" 1: Default Communications Device\n"); printf(" 2: Default Multimedia Device\n"); UINT deviceCount; hr = deviceCollection->GetCount(&deviceCount); if (FAILED(hr)) { printf("Unable to get device collection length: %x\n", hr); retValue = false; goto Exit; } for (UINT i = 0 ; i < deviceCount ; i += 1) { LPWSTR deviceName; deviceName = GetDeviceName(deviceCollection, i); if (deviceName == NULL) { retValue = false; goto Exit; } printf(" %d: %S\n", i + 3, deviceName); free(deviceName); } wchar_t choice[10]; _getws_s(choice); // Note: Using the safe CRT version of _getws. long deviceIndex; wchar_t *endPointer; deviceIndex = wcstoul(choice, &endPointer, 0); if (deviceIndex == 0 && endPointer == choice) { printf("unrecognized device index: %S\n", choice); retValue = false; goto Exit; } switch (deviceIndex) { case 0: UseConsoleDevice = 1; break; case 1: UseCommunicationsDevice = 1; break; case 2: UseMultimediaDevice = 1; break; default: hr = deviceCollection->Item(deviceIndex - 3, &device); if (FAILED(hr)) { printf("Unable to retrieve device %d: %x\n", deviceIndex - 3, hr); retValue = false; goto Exit; } break; } } else if (OutputEndpoint != NULL) { hr = deviceEnumerator->GetDevice(OutputEndpoint, &device); if (FAILED(hr)) { printf("Unable to get endpoint for endpoint %S: %x\n", OutputEndpoint, hr); retValue = false; goto Exit; } } if (device == NULL) { ERole deviceRole = eConsole; // Assume we're using the console role. if (UseConsoleDevice) { deviceRole = eConsole; } else if (UseCommunicationsDevice) { deviceRole = eCommunications; } else if (UseMultimediaDevice) { deviceRole = eMultimedia; } hr = deviceEnumerator->GetDefaultAudioEndpoint(eCapture, deviceRole, &device); if (FAILED(hr)) { printf("Unable to get default device for role %d: %x\n", deviceRole, hr); retValue = false; goto Exit; } *IsDefaultDevice = true; *DefaultDeviceRole = deviceRole; } *DeviceToUse = device; retValue = true; Exit: SafeRelease(&deviceCollection); SafeRelease(&deviceEnumerator); return retValue; }
// Returns ">0" - when changes was made // 0 - no changes // -1 - error // bForceCurConsole==true, если разбор параметров идет // при запуске Tasks из GUI int RConStartArgs::ProcessNewConArg(bool bForceCurConsole /*= false*/) { bNewConsole = FALSE; if (!pszSpecialCmd || !*pszSpecialCmd) { _ASSERTE(pszSpecialCmd && *pszSpecialCmd); return -1; } int nChanges = 0; // 120115 - Если первый аргумент - "ConEmu.exe" или "ConEmu64.exe" - не обрабатывать "-cur_console" и "-new_console" { LPCWSTR pszTemp = pszSpecialCmd; wchar_t szExe[MAX_PATH+1]; if (0 == NextArg(&pszTemp, szExe)) { pszTemp = PointToName(szExe); if (lstrcmpi(pszTemp, L"ConEmu.exe") == 0 || lstrcmpi(pszTemp, L"ConEmu") == 0 || lstrcmpi(pszTemp, L"ConEmu64.exe") == 0 || lstrcmpi(pszTemp, L"ConEmu64") == 0) { return 0; } } } // 111211 - здесь может быть передан "-new_console:..." LPCWSTR pszNewCon = L"-new_console"; // 120108 - или "-cur_console:..." для уточнения параметров запуска команд (из фара например) LPCWSTR pszCurCon = L"-cur_console"; int nNewConLen = lstrlen(pszNewCon); _ASSERTE(lstrlen(pszCurCon)==nNewConLen); bool bStop = false; while (!bStop) { wchar_t* pszFindNew = wcsstr(pszSpecialCmd, pszNewCon); wchar_t* pszFind = pszFindNew ? pszFindNew : wcsstr(pszSpecialCmd, pszCurCon); if (pszFindNew) bNewConsole = TRUE; else if (!pszFind) break; // Проверка валидности _ASSERTE(pszFind >= pszSpecialCmd); if (((pszFind == pszSpecialCmd) || (*(pszFind-1) == L'"') || (*(pszFind-1) == L' ')) // начало аргумента && (pszFind[nNewConLen] == L' ' || pszFind[nNewConLen] == L':' || pszFind[nNewConLen] == L'"' || pszFind[nNewConLen] == 0)) { // -- не будем пока, мешает. например, при запуске задач //// По умолчанию, принудительно включить "Press Enter or Esc to close console" //if (!bForceCurConsole) // eConfirmation = eConfAlways; bool lbQuot = (*(pszFind-1) == L'"'); const wchar_t* pszEnd = pszFind+nNewConLen; //wchar_t szNewConArg[MAX_PATH+1]; if (lbQuot) pszFind--; if (*pszEnd == L'"') { pszEnd++; } else if (*pszEnd != L':') { // Конец _ASSERTE(*pszEnd == L' ' || *pszEnd == 0); } else { if (*pszEnd == L':') { pszEnd++; } else { _ASSERTE(*pszEnd == L':'); } // Обработка доп.параметров -new_console:xxx bool lbReady = false; while (!lbReady && *pszEnd) { wchar_t cOpt = *(pszEnd++); switch (cOpt) { //case L'-': // bStop = true; // следующие "-new_console" - не трогать! // break; case L'"': case L' ': case 0: lbReady = true; break; case L'b': // b - background, не активировать таб bBackgroundTab = TRUE; bForegroungTab = FALSE; break; case L'f': // f - foreground, активировать таб (аналог ">" в Tasks) bForegroungTab = TRUE; bBackgroundTab = FALSE; break; case L'z': // z - don't use "Default terminal" feature bNoDefaultTerm = TRUE; break; case L'a': // a - RunAs shell verb (as admin on Vista+, login/password in WinXP-) bRunAsAdministrator = TRUE; break; case L'r': // r - run as restricted user bRunAsRestricted = TRUE; break; case L'o': // o - disable "Long output" for next command (Far Manager) bLongOutputDisable = TRUE; break; case L'w': // e - enable "Overwrite" mode in console prompt bOverwriteMode = TRUE; break; case L'p': if (isDigit(*pszEnd)) { switch (*(pszEnd++)) { case L'0': nPTY = 0; // don't change break; case L'1': nPTY = 1; // enable PTY mode break; case L'2': nPTY = 2; // disable PTY mode (switch to plain $CONIN, $CONOUT, $CONERR) break; default: nPTY = 1; } } else { nPTY = 1; // enable PTY mode } break; case L'i': // i - don't inject ConEmuHk into the starting application bInjectsDisable = TRUE; break; case L'h': // "h0" - отключить буфер, "h9999" - включить буфер в 9999 строк { bBufHeight = TRUE; if (isDigit(*pszEnd)) { wchar_t* pszDigits = NULL; nBufHeight = wcstoul(pszEnd, &pszDigits, 10); if (pszDigits) pszEnd = pszDigits; } else { nBufHeight = 0; } } // L'h': break; case L'n': // n - отключить "Press Enter or Esc to close console" eConfirmation = eConfNever; break; case L'c': // c - принудительно включить "Press Enter or Esc to close console" eConfirmation = eConfAlways; break; case L'x': // x - Force using dosbox for .bat files bForceDosBox = TRUE; break; case L'I': // I - tell GuiMacro to execute new command inheriting active process state. This is only usage ATM. bForceInherit = TRUE; break; // "Long" code blocks below: 'd', 'u', 's' and so on (in future) case L'd': // d:<StartupDir>. MUST be last options { if (*pszEnd == L':') pszEnd++; const wchar_t* pszDir = pszEnd; while ((*pszEnd) && (lbQuot || *pszEnd != L' ') && (*pszEnd != L'"')) pszEnd++; if (pszEnd > pszDir) { size_t cchLen = pszEnd - pszDir; SafeFree(pszStartupDir); pszStartupDir = (wchar_t*)malloc((cchLen+1)*sizeof(*pszStartupDir)); if (pszStartupDir) { wmemmove(pszStartupDir, pszDir, cchLen); pszStartupDir[cchLen] = 0; // Например, "%USERPROFILE%" if (wcschr(pszStartupDir, L'%')) { wchar_t* pszExpand = NULL; if (((pszExpand = ExpandEnvStr(pszStartupDir)) != NULL)) { SafeFree(pszStartupDir); pszStartupDir = pszExpand; } } } } } // L'd': break; case L't': // t:<TabName>. MUST be last options case L'C': // C:<IconFile>. MUST be last options case L'P': // P:<Palette>. MUST be last options case L'W': // W:<Wallpaper>. MUST be last options { if (*pszEnd == L':') pszEnd++; const wchar_t* pszTab = pszEnd; while ((*pszEnd) && (lbQuot || *pszEnd != L' ') && (*pszEnd != L'"')) pszEnd++; if (pszEnd > pszTab) { wchar_t** pptr = NULL; switch (cOpt) { case L't': pptr = &pszRenameTab; break; case L'C': pptr = &pszIconFile; break; case L'P': pptr = &pszPalette; break; case L'W': pptr = &pszWallpaper; break; } size_t cchLen = pszEnd - pszTab; SafeFree(*pptr); *pptr = (wchar_t*)malloc((cchLen+1)*sizeof(**pptr)); if (*pptr) { // We need to process escape sequences ("^>" -> ">", "^&" -> "&", etc.) //wmemmove(*pptr, pszTab, cchLen); wchar_t* pD = *pptr; const wchar_t* pS = pszTab; // There is enough room allocated while (pS < pszEnd) { if ((*pS == L'^') && ((pS + 1) < pszEnd)) pS++; // Skip control char, goto escaped char else if ((*pS == L'"') && ((pS + 1) < pszEnd) && (*(pS+1) == L'"')) pS++; // Skip qoubled qouble quote *(pD++) = *(pS++); } // Terminate with '\0' _ASSERTE(pD <= ((*pptr)+cchLen)); *pD = 0; } } } // L't': break; case L's': // s[<SplitTab>T][<Percents>](H|V) // Пример: "s3T30H" - разбить 3-ий таб. будет создан новый Pane справа, шириной 30% от 3-го таба. { UINT nTab = 0 /*active*/, nValue = /*пополам*/DefaultSplitValue/10; bool bDisableSplit = false; while (*pszEnd) { if (isDigit(*pszEnd)) { wchar_t* pszDigits = NULL; UINT n = wcstoul(pszEnd, &pszDigits, 10); if (!pszDigits) break; pszEnd = pszDigits; if (*pszDigits == L'T') { nTab = n; } else if ((*pszDigits == L'H') || (*pszDigits == L'V')) { nValue = n; eSplit = (*pszDigits == L'H') ? eSplitHorz : eSplitVert; } else { break; } pszEnd++; } else if (*pszEnd == L'T') { nTab = 0; pszEnd++; } else if ((*pszEnd == L'H') || (*pszEnd == L'V')) { nValue = DefaultSplitValue/10; eSplit = (*pszEnd == L'H') ? eSplitHorz : eSplitVert; pszEnd++; } else if (*pszEnd == L'N') { bDisableSplit = true; pszEnd++; break; } else { break; } } if (bDisableSplit) { eSplit = eSplitNone; nSplitValue = DefaultSplitValue; nSplitPane = 0; } else { if (!eSplit) eSplit = eSplitHorz; // Для удобства, пользователь задает размер НОВОЙ части nSplitValue = 1000-max(1,min(nValue*10,999)); // проценты _ASSERTE(nSplitValue>=1 && nSplitValue<1000); nSplitPane = nTab; } } // L's' break; case L'u': { // u - ConEmu choose user dialog // u:<user>:<pwd> - specify user/pwd in args. MUST be last option lbReady = true; // последняя опция SafeFree(pszUserName); SafeFree(pszDomain); if (szUserPassword[0]) SecureZeroMemory(szUserPassword, sizeof(szUserPassword)); if (*pszEnd == L':') { pszEnd++; wchar_t szUser[MAX_PATH], *p = szUser, *p2 = szUser+countof(szUser)-1; while (*pszEnd && (p < p2)) { if ((*pszEnd == 0) || (*pszEnd == L':') || (*pszEnd == L'"')) { break; } //else if (*pszEnd == L'"' && *(pszEnd+1) == L'"') //{ // *(p++) = L'"'; pszEnd += 2; //} else if (*pszEnd == L'^') { pszEnd++; *(p++) = *(pszEnd++); } else { *(p++) = *(pszEnd++); } } *p = 0; wchar_t* pszSlash = wcschr(szUser, L'\\'); if (pszSlash) { *pszSlash = 0; pszDomain = lstrdup(szUser); pszUserName = lstrdup(pszSlash+1); } else { pszUserName = lstrdup(szUser); } if (*pszEnd == L':') { pszEnd++; //lstrcpyn(szUserPassword, pszPwd, countof(szUserPassword)); p = szUserPassword; p2 = szUserPassword+countof(szUserPassword)-1; while (*pszEnd && (p < p2)) { if ((*pszEnd == 0) || (*pszEnd == L':') || (*pszEnd == L'"')) { break; } else if (*pszEnd == L'^') { pszEnd++; *(p++) = *(pszEnd++); } else { *(p++) = *(pszEnd++); } } *p = 0; } } else { bForceUserDialog = TRUE; } } // L'u' break; } } } if (pszEnd > pszFind) { // pszEnd должен указывать на конец -new_console[:...] / -cur_console[:...] // и включать обрамляющую кавычку, если он окавычен if (lbQuot) { if (*pszEnd == L'"' && *(pszEnd-1) != L'"') pszEnd++; } else { while (*(pszEnd-1) == L'"') pszEnd--; } // Откусить лишние пробелы, которые стоят ПЕРЕД -new_console[:...] / -cur_console[:...] while (((pszFind - 1) > pszSpecialCmd) && (*(pszFind-1) == L' ') && ((*(pszFind-2) == L' ') || (/**pszEnd == L'"' ||*/ *pszEnd == 0 || *pszEnd == L' '))) { pszFind--; } wmemmove(pszFind, pszEnd, (lstrlen(pszEnd)+1)); nChanges++; } else { _ASSERTE(pszEnd > pszFind); *pszFind = 0; nChanges++; } } } return nChanges; }
int CALLBACK _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { int argc = 0; LPWSTR * argv = CommandLineToArgvW( GetCommandLineW(), &argc ); if ( argv == NULL || argc != 3 ) return 1; wchar_t * end_char = 0; unsigned in_sum = wcstoul( argv[ 2 ], &end_char, 16 ); if ( end_char == argv[ 2 ] || *end_char ) return 2; unsigned test_sum = 0; end_char = argv[ 1 ]; while ( *end_char ) { test_sum += (TCHAR)( *end_char++ * 820109 ); } #ifdef NDEBUG if ( test_sum != in_sum ) return 3; #endif unsigned code = 0; HMODULE hDll = NULL; main_func pMain = NULL; AEffect * pEffect[3] = {0, 0, 0}; audioMasterData effectData[3] = { { 0 }, { 1 }, { 2 } }; std::vector<uint8_t> blState; uint32_t max_num_outputs = 2; uint32_t sample_rate = 44100; std::vector<uint8_t> chunk; std::vector<float> sample_buffer; null_file = CreateFile( _T("NUL"), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL ); pipe_in = GetStdHandle( STD_INPUT_HANDLE ); pipe_out = GetStdHandle( STD_OUTPUT_HANDLE ); SetStdHandle( STD_INPUT_HANDLE, null_file ); SetStdHandle( STD_OUTPUT_HANDLE, null_file ); { INITCOMMONCONTROLSEX icc; icc.dwSize = sizeof(icc); icc.dwICC = ICC_WIN95_CLASSES | ICC_COOL_CLASSES | ICC_STANDARD_CLASSES; if ( !InitCommonControlsEx( &icc ) ) return 4; } if ( FAILED( CoInitialize( NULL ) ) ) return 5; #ifndef _DEBUG SetUnhandledExceptionFilter( myExceptFilterProc ); #endif size_t dll_name_len = wcslen( argv[ 1 ] ); dll_dir = ( char * ) malloc( dll_name_len + 1 ); wcstombs( dll_dir, argv[ 1 ], dll_name_len ); dll_dir[ dll_name_len ] = '\0'; char * slash = strrchr( dll_dir, '\\' ); *slash = '\0'; hDll = LoadLibraryW( argv[ 1 ] ); if ( !hDll ) { code = 6; goto exit; } pMain = (main_func) GetProcAddress( hDll, "main" ); if ( !pMain ) { code = 7; goto exit; } #if 0 MessageBox( GetDesktopWindow(), argv[ 1 ], _T("HUUUURRRRRR"), 0 ); #endif pEffect[ 0 ] = pMain( &audioMaster ); if ( !pEffect[ 0 ] || pEffect[ 0 ]->magic != kEffectMagic ) { code = 8; goto exit; } pEffect[ 0 ]->user = &effectData[ 0 ]; pEffect[ 0 ]->dispatcher( pEffect[ 0 ], effOpen, 0, 0, 0, 0 ); if ( pEffect[ 0 ]->dispatcher( pEffect[ 0 ], effGetPlugCategory, 0, 0, 0, 0 ) != kPlugCategSynth || pEffect[ 0 ]->dispatcher( pEffect[ 0 ], effCanDo, 0, 0, "sendVstMidiEvent", 0 ) == 0 ) { code = 9; goto exit; } max_num_outputs = min( pEffect[ 0 ]->numOutputs, 2 ); { char name_string[256] = { 0 }; char vendor_string[256] = { 0 }; char product_string[256] = { 0 }; uint32_t name_string_length; uint32_t vendor_string_length; uint32_t product_string_length; uint32_t vendor_version; uint32_t unique_id; pEffect[ 0 ]->dispatcher( pEffect[ 0 ], effGetEffectName, 0, 0, &name_string, 0 ); pEffect[ 0 ]->dispatcher( pEffect[ 0 ], effGetVendorString, 0, 0, &vendor_string, 0 ); pEffect[ 0 ]->dispatcher( pEffect[ 0 ], effGetProductString, 0, 0, &product_string, 0 ); name_string_length = strlen( name_string ); vendor_string_length = strlen( vendor_string ); product_string_length = strlen( product_string ); vendor_version = pEffect[ 0 ]->dispatcher( pEffect[ 0 ], effGetVendorVersion, 0, 0, 0, 0 ); unique_id = pEffect[ 0 ]->uniqueID; put_code( 0 ); put_code( name_string_length ); put_code( vendor_string_length ); put_code( product_string_length ); put_code( vendor_version ); put_code( unique_id ); put_code( max_num_outputs ); if ( name_string_length ) put_bytes( name_string, name_string_length ); if ( vendor_string_length ) put_bytes( vendor_string, vendor_string_length ); if ( product_string_length ) put_bytes( product_string, product_string_length ); } float ** float_list_in; float ** float_list_out; float * float_null; float * float_out; for (;;) { uint32_t command = get_code(); if ( !command ) break; switch ( command ) { case 1: // Get Chunk getChunk( pEffect[ 0 ], chunk ); put_code( 0 ); put_code( chunk.size() ); put_bytes( chunk.data(), chunk.size() ); break; case 2: // Set Chunk { uint32_t size = get_code(); chunk.resize( size ); if ( size ) get_bytes( chunk.data(), size ); setChunk( pEffect[ 0 ], chunk ); setChunk( pEffect[ 1 ], chunk ); setChunk( pEffect[ 2 ], chunk ); put_code( 0 ); } break; case 3: // Has Editor { uint32_t has_editor = ( pEffect[ 0 ]->flags & effFlagsHasEditor ) ? 1 : 0; put_code( 0 ); put_code( has_editor ); } break; case 4: // Display Editor Modal { if ( pEffect[ 0 ]->flags & effFlagsHasEditor ) { MyDLGTEMPLATE t; t.style = WS_POPUPWINDOW | WS_DLGFRAME | DS_MODALFRAME | DS_CENTER; DialogBoxIndirectParam ( 0, &t, GetDesktopWindow(), (DLGPROC)EditorProc, (LPARAM)( pEffect[ 0 ] ) ); getChunk( pEffect[ 0 ], chunk ); setChunk( pEffect[ 1 ], chunk ); setChunk( pEffect[ 2 ], chunk ); } put_code( 0 ); } break; case 5: // Set Sample Rate { uint32_t size = get_code(); if ( size != sizeof(sample_rate) ) { code = 10; goto exit; } sample_rate = get_code(); put_code( 0 ); } break; case 6: // Reset { if ( pEffect[ 2 ] ) { if ( blState.size() ) pEffect[ 2 ]->dispatcher( pEffect[ 2 ], effStopProcess, 0, 0, 0, 0 ); pEffect[ 2 ]->dispatcher( pEffect[ 2 ], effClose, 0, 0, 0, 0 ); pEffect[ 2 ] = NULL; } if ( pEffect[ 1 ] ) { if ( blState.size() ) pEffect[ 1 ]->dispatcher( pEffect[ 1 ], effStopProcess, 0, 0, 0, 0 ); pEffect[ 1 ]->dispatcher( pEffect[ 1 ], effClose, 0, 0, 0, 0 ); pEffect[ 1 ] = NULL; } if ( blState.size() ) pEffect[ 0 ]->dispatcher( pEffect[ 0 ], effStopProcess, 0, 0, 0, 0 ); pEffect[ 0 ]->dispatcher( pEffect[ 0 ], effClose, 0, 0, 0, 0 ); blState.resize( 0 ); freeChain(); pEffect[ 0 ] = pMain( &audioMaster ); if ( !pEffect[ 0 ] ) { code = 8; goto exit; } pEffect[ 0 ]->user = &effectData[ 0 ]; pEffect[ 0 ]->dispatcher( pEffect[ 0 ], effOpen, 0, 0, 0, 0 ); setChunk( pEffect[ 0 ], chunk ); put_code( 0 ); } break; case 7: // Send MIDI Event { myVstEvent * ev = ( myVstEvent * ) calloc( sizeof( myVstEvent ), 1 ); if ( evTail ) evTail->next = ev; evTail = ev; if ( !evChain ) evChain = ev; uint32_t b = get_code(); ev->port = (b & 0x7F000000) >> 24; if (ev->port > 2) ev->port = 2; ev->ev.midiEvent.type = kVstMidiType; ev->ev.midiEvent.byteSize = sizeof(ev->ev.midiEvent); memcpy(&ev->ev.midiEvent.midiData, &b, 3); put_code( 0 ); } break; case 8: // Send System Exclusive Event { myVstEvent * ev = ( myVstEvent * ) calloc( sizeof( myVstEvent ), 1 ); if ( evTail ) evTail->next = ev; evTail = ev; if ( !evChain ) evChain = ev; uint32_t size = get_code(); uint32_t port = size >> 24; size &= 0xFFFFFF; ev->port = port; if (ev->port > 2) ev->port = 2; ev->ev.sysexEvent.type = kVstSysExType; ev->ev.sysexEvent.byteSize = sizeof(ev->ev.sysexEvent); ev->ev.sysexEvent.dumpBytes = size; ev->ev.sysexEvent.sysexDump = (char*) malloc( size ); get_bytes( ev->ev.sysexEvent.sysexDump, size ); put_code( 0 ); } break; case 9: // Render Samples { if ( !pEffect[ 1 ] ) { pEffect[ 1 ] = pMain( &audioMaster ); if ( !pEffect[ 1 ] ) { code = 11; goto exit; } pEffect[ 1 ]->user = &effectData[ 1 ]; pEffect[ 1 ]->dispatcher( pEffect[ 1 ], effOpen, 0, 0, 0, 0 ); setChunk( pEffect[ 1 ], chunk ); } if ( !pEffect[ 2 ] ) { pEffect[ 2 ] = pMain( &audioMaster ); if ( !pEffect[ 2 ] ) { code = 11; goto exit; } pEffect[ 2 ]->user = &effectData[ 2 ]; pEffect[ 2 ]->dispatcher( pEffect[ 2 ], effOpen, 0, 0, 0, 0 ); setChunk( pEffect[ 2 ], chunk ); } if ( !blState.size() ) { pEffect[ 0 ]->dispatcher( pEffect[ 0 ], effSetSampleRate, 0, 0, 0, float(sample_rate) ); pEffect[ 0 ]->dispatcher( pEffect[ 0 ], effSetBlockSize, 0, BUFFER_SIZE, 0, 0 ); pEffect[ 0 ]->dispatcher( pEffect[ 0 ], effMainsChanged, 0, 1, 0, 0 ); pEffect[ 0 ]->dispatcher( pEffect[ 0 ], effStartProcess, 0, 0, 0, 0 ); pEffect[ 1 ]->dispatcher( pEffect[ 1 ], effSetSampleRate, 0, 0, 0, float(sample_rate) ); pEffect[ 1 ]->dispatcher( pEffect[ 1 ], effSetBlockSize, 0, BUFFER_SIZE, 0, 0 ); pEffect[ 1 ]->dispatcher( pEffect[ 1 ], effMainsChanged, 0, 1, 0, 0 ); pEffect[ 1 ]->dispatcher( pEffect[ 1 ], effStartProcess, 0, 0, 0, 0 ); pEffect[ 2 ]->dispatcher( pEffect[ 2 ], effSetSampleRate, 0, 0, 0, float(sample_rate) ); pEffect[ 2 ]->dispatcher( pEffect[ 2 ], effSetBlockSize, 0, BUFFER_SIZE, 0, 0 ); pEffect[ 2 ]->dispatcher( pEffect[ 2 ], effMainsChanged, 0, 1, 0, 0 ); pEffect[ 2 ]->dispatcher( pEffect[ 2 ], effStartProcess, 0, 0, 0, 0 ); size_t buffer_size = sizeof(float*) * ( pEffect[ 0 ]->numInputs + pEffect[ 0 ]->numOutputs * 3 ); // float lists buffer_size += sizeof(float) * BUFFER_SIZE; // null input buffer_size += sizeof(float) * BUFFER_SIZE * pEffect[ 0 ]->numOutputs * 3; // outputs blState.resize( buffer_size ); float_list_in = (float**) blState.data(); float_list_out = float_list_in + pEffect[ 0 ]->numInputs; float_null = (float*) ( float_list_out + pEffect[ 0 ]->numOutputs * 3 ); float_out = float_null + BUFFER_SIZE; for ( unsigned i = 0; i < pEffect[ 0 ]->numInputs; ++i ) float_list_in [ i ] = float_null; for ( unsigned i = 0; i < pEffect[ 0 ]->numOutputs * 3; ++i ) float_list_out[ i ] = float_out + BUFFER_SIZE * i; memset( float_null, 0, sizeof(float) * BUFFER_SIZE ); sample_buffer.resize( BUFFER_SIZE * max_num_outputs ); } if ( need_idle ) { pEffect[ 0 ]->dispatcher( pEffect[ 0 ], DECLARE_VST_DEPRECATED (effIdle), 0, 0, 0, 0 ); pEffect[ 1 ]->dispatcher( pEffect[ 1 ], DECLARE_VST_DEPRECATED (effIdle), 0, 0, 0, 0 ); pEffect[ 2 ]->dispatcher( pEffect[ 2 ], DECLARE_VST_DEPRECATED (effIdle), 0, 0, 0, 0 ); if ( !idle_started ) { unsigned idle_run = BUFFER_SIZE * 128; while ( idle_run ) { unsigned count_to_do = min( idle_run, BUFFER_SIZE ); unsigned num_outputs = pEffect[ 0 ]->numOutputs; pEffect[ 0 ]->processReplacing( pEffect[ 0 ], float_list_in, float_list_out, count_to_do ); pEffect[ 1 ]->processReplacing( pEffect[ 1 ], float_list_in, float_list_out + num_outputs, count_to_do ); pEffect[ 2 ]->processReplacing( pEffect[ 2 ], float_list_in, float_list_out + num_outputs * 2, count_to_do ); pEffect[ 0 ]->dispatcher( pEffect[ 0 ], DECLARE_VST_DEPRECATED (effIdle), 0, 0, 0, 0 ); pEffect[ 1 ]->dispatcher( pEffect[ 1 ], DECLARE_VST_DEPRECATED (effIdle), 0, 0, 0, 0 ); pEffect[ 2 ]->dispatcher( pEffect[ 2 ], DECLARE_VST_DEPRECATED (effIdle), 0, 0, 0, 0 ); idle_run -= count_to_do; } } } VstEvents * events[ 3 ] = {0}; if ( evChain ) { unsigned event_count[ 3 ] = {0}; myVstEvent * ev = evChain; while ( ev ) { event_count[ ev->port ]++; ev = ev->next; } if ( event_count[ 0 ] ) { events[ 0 ] = ( VstEvents * ) malloc( sizeof(long) + sizeof(long) + sizeof(VstEvent*) * event_count[ 0 ] ); events[ 0 ]->numEvents = event_count[ 0 ]; events[ 0 ]->reserved = 0; ev = evChain; for ( unsigned i = 0; ev; ) { if ( !ev->port ) events[ 0 ]->events[ i++ ] = (VstEvent*) &ev->ev; ev = ev->next; } pEffect[ 0 ]->dispatcher( pEffect[ 0 ], effProcessEvents, 0, 0, events[ 0 ], 0 ); } if ( event_count[ 1 ] ) { events[ 1 ] = ( VstEvents * ) malloc( sizeof(long) + sizeof(long) + sizeof(VstEvent*) * event_count[ 1 ] ); events[ 1 ]->numEvents = event_count[ 1 ]; events[ 1 ]->reserved = 0; ev = evChain; for ( unsigned i = 0; ev; ) { if ( ev->port == 1 ) events[ 1 ]->events[ i++ ] = (VstEvent*) &ev->ev; ev = ev->next; } pEffect[ 1 ]->dispatcher( pEffect[ 1 ], effProcessEvents, 0, 0, events[ 1 ], 0 ); } if ( event_count[ 2 ] ) { events[ 2 ] = ( VstEvents * ) malloc( sizeof(long) + sizeof(long) + sizeof(VstEvent*) * event_count[ 2 ] ); events[ 2 ]->numEvents = event_count[ 2 ]; events[ 2 ]->reserved = 0; ev = evChain; for ( unsigned i = 0; ev; ) { if ( ev->port == 2 ) events[ 2 ]->events[ i++ ] = (VstEvent*) &ev->ev; ev = ev->next; } pEffect[ 2 ]->dispatcher( pEffect[ 2 ], effProcessEvents, 0, 0, events[ 2 ], 0 ); } } if ( need_idle ) { pEffect[ 0 ]->dispatcher( pEffect[ 0 ], DECLARE_VST_DEPRECATED (effIdle), 0, 0, 0, 0 ); pEffect[ 1 ]->dispatcher( pEffect[ 1 ], DECLARE_VST_DEPRECATED (effIdle), 0, 0, 0, 0 ); pEffect[ 2 ]->dispatcher( pEffect[ 2 ], DECLARE_VST_DEPRECATED (effIdle), 0, 0, 0, 0 ); if ( !idle_started ) { if ( events[ 0 ] ) pEffect[ 0 ]->dispatcher( pEffect[ 0 ], effProcessEvents, 0, 0, events[ 0 ], 0 ); if ( events[ 1 ] ) pEffect[ 1 ]->dispatcher( pEffect[ 1 ], effProcessEvents, 0, 0, events[ 1 ], 0 ); if ( events[ 2 ] ) pEffect[ 2 ]->dispatcher( pEffect[ 2 ], effProcessEvents, 0, 0, events[ 2 ], 0 ); idle_started = true; } } uint32_t count = get_code(); put_code( 0 ); while( count ) { unsigned count_to_do = min( count, BUFFER_SIZE ); unsigned num_outputs = pEffect[ 0 ]->numOutputs; pEffect[ 0 ]->processReplacing( pEffect[ 0 ], float_list_in, float_list_out, count_to_do ); pEffect[ 1 ]->processReplacing( pEffect[ 1 ], float_list_in, float_list_out + num_outputs, count_to_do ); pEffect[ 2 ]->processReplacing( pEffect[ 2 ], float_list_in, float_list_out + num_outputs * 2, count_to_do ); float * out = sample_buffer.data(); if ( max_num_outputs == 2 ) { for ( unsigned i = 0; i < count_to_do; ++i ) { float sample = ( float_out[ i ] + float_out[ i + BUFFER_SIZE * num_outputs ] + float_out[ i + BUFFER_SIZE * num_outputs * 2 ] ); out[ 0 ] = sample; sample = ( float_out[ i + BUFFER_SIZE ] + float_out[ i + BUFFER_SIZE + BUFFER_SIZE * num_outputs ] + float_out[ i + BUFFER_SIZE + BUFFER_SIZE * num_outputs * 2 ] ); out[ 1 ] = sample; out += 2; } } else { for ( unsigned i = 0; i < count_to_do; ++i ) { float sample = ( float_out[ i ] + float_out[ i + BUFFER_SIZE * num_outputs ] + float_out[ i + BUFFER_SIZE * num_outputs * 2 ] ); out[ 0 ] = sample; out++; } } put_bytes( sample_buffer.data(), sizeof(float) * count_to_do * max_num_outputs ); count -= count_to_do; } if ( events[ 0 ] ) free( events[ 0 ] ); if ( events[ 1 ] ) free( events[ 1 ] ); if ( events[ 2 ] ) free( events[ 2 ] ); freeChain(); } break; default: code = 12; goto exit; break; } } exit: if ( pEffect[ 2 ] ) { if ( blState.size() ) pEffect[ 2 ]->dispatcher( pEffect[ 2 ], effStopProcess, 0, 0, 0, 0 ); pEffect[ 2 ]->dispatcher( pEffect[ 2 ], effClose, 0, 0, 0, 0 ); } if ( pEffect[ 1 ] ) { if ( blState.size() ) pEffect[ 1 ]->dispatcher( pEffect[ 1 ], effStopProcess, 0, 0, 0, 0 ); pEffect[ 1 ]->dispatcher( pEffect[ 1 ], effClose, 0, 0, 0, 0 ); } if ( pEffect[ 0 ] ) { if ( blState.size() ) pEffect[ 0 ]->dispatcher( pEffect[ 0 ], effStopProcess, 0, 0, 0, 0 ); pEffect[ 0 ]->dispatcher( pEffect[ 0 ], effClose, 0, 0, 0, 0 ); } freeChain(); if ( hDll ) FreeLibrary( hDll ); CoUninitialize(); if ( argv ) LocalFree( argv ); put_code( code ); if ( null_file ) { CloseHandle( null_file ); SetStdHandle( STD_INPUT_HANDLE, pipe_in ); SetStdHandle( STD_OUTPUT_HANDLE, pipe_out ); } return code; }
BOOL HTTPGetFile (CTSTR url, CTSTR outputPath, CTSTR extraHeaders, int *responseCode) { HINTERNET hSession = NULL; HINTERNET hConnect = NULL; HINTERNET hRequest = NULL; URL_COMPONENTS urlComponents; BOOL secure = FALSE; BOOL ret = FALSE; String hostName, path; const TCHAR *acceptTypes[] = { TEXT("*/*"), NULL }; hostName.SetLength(256); path.SetLength(1024); zero(&urlComponents, sizeof(urlComponents)); urlComponents.dwStructSize = sizeof(urlComponents); urlComponents.lpszHostName = hostName; urlComponents.dwHostNameLength = hostName.Length(); urlComponents.lpszUrlPath = path; urlComponents.dwUrlPathLength = path.Length(); WinHttpCrackUrl(url, 0, 0, &urlComponents); if (urlComponents.nPort == 443) secure = TRUE; hSession = WinHttpOpen(L"User Agent", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (!hSession) goto failure; hConnect = WinHttpConnect(hSession, hostName, secure ? INTERNET_DEFAULT_HTTPS_PORT : urlComponents.nPort, 0); if (!hConnect) goto failure; hRequest = WinHttpOpenRequest(hConnect, TEXT("GET"), path, NULL, WINHTTP_NO_REFERER, acceptTypes, secure ? WINHTTP_FLAG_SECURE|WINHTTP_FLAG_REFRESH : WINHTTP_FLAG_REFRESH); if (!hRequest) goto failure; BOOL bResults = WinHttpSendRequest(hRequest, extraHeaders, extraHeaders ? -1 : 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); // End the request. if (bResults) bResults = WinHttpReceiveResponse(hRequest, NULL); else goto failure; TCHAR statusCode[8]; DWORD statusCodeLen; statusCodeLen = sizeof(statusCode); if (!WinHttpQueryHeaders (hRequest, WINHTTP_QUERY_STATUS_CODE, WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &statusCodeLen, WINHTTP_NO_HEADER_INDEX)) goto failure; *responseCode = wcstoul(statusCode, NULL, 10); if (bResults && *responseCode == 200) { BYTE buffer[16384]; DWORD dwSize, dwOutSize; XFile updateFile; if (!updateFile.Open(outputPath, XFILE_WRITE, CREATE_ALWAYS)) goto failure; do { // Check for available data. dwSize = 0; if (!WinHttpQueryDataAvailable(hRequest, &dwSize)) goto failure; if (!WinHttpReadData(hRequest, (LPVOID)buffer, dwSize, &dwOutSize)) { goto failure; } else { if (!dwOutSize) break; if (!updateFile.Write(buffer, dwOutSize)) goto failure; } } while (dwSize > 0); updateFile.Close(); } ret = TRUE; failure: if (hSession) WinHttpCloseHandle(hSession); if (hConnect) WinHttpCloseHandle(hConnect); if (hRequest) WinHttpCloseHandle(hRequest); return ret; }
TEST(wchar, wcstoull) { ASSERT_EQ(123ULL, wcstoul(L"123", NULL, 0)); }
unsigned long strto<unsigned long>(const wchar_t *str, wchar_t **str_end, int base) { return wcstoul(str, str_end, base); }
int scilab_sscanf(wchar_t* _wcsFormat, wchar_t* _wcsData, int _iIterrator, int _iNiter, std::vector<types::InternalType*> *_pITOut) { int i = 0; int j = 0; int nbrOfDigit = 0; int dims = 2; int dimsArray[2] = {_iNiter, 1}; BOOL bStar = FALSE; BOOL bUnsigned = FALSE; BOOL bIgnoredChars = TRUE; int base = 0; wchar_t wcsLLH = L' '; wchar_t* wcsData = NULL; int sizeOfData = (int)wcslen(_wcsData); int iCountDataRead = 0; wcsData = (wchar_t*)MALLOC((sizeOfData + 1) * sizeof(wchar_t)); memcpy(wcsData, _wcsData, sizeOfData * sizeof(wchar_t)); wcsData[sizeOfData] = '\0'; while (i < (int)wcslen(_wcsFormat)) { while (bIgnoredChars && i < (int)wcslen(_wcsFormat)) // %da%s => 'a' is an ignored char. { if (wcsData != NULL && wcsData[0] != L'\0' && _wcsFormat[i] == wcsData[0]) { if (_wcsFormat[i] != L' ') { i++; wcsData++; } else { while (wcsData[0] == L' ') { wcsData++; } while (_wcsFormat[i] == L' ') { i++; } } } else if ((wcsData == NULL || wcsData[0] == L'\0') && i < (int)wcslen(_wcsFormat) && iCountDataRead == 0 && _pITOut->size() == 0) { iCountDataRead = -1; } else { if (_wcsFormat[i] == L' ') { do { i++; } while (i < (int)wcslen(_wcsFormat) && _wcsFormat[i] == L' '); } if (_wcsFormat[i] != L'%') { wcsData = NULL; while (i < (int)wcslen(_wcsFormat) && _wcsFormat[i] != L'%') { i++; } } break; } } if (i == (int)wcslen(_wcsFormat)) { break; } if (iswdigit(_wcsFormat[i])) { nbrOfDigit = wcstol(&_wcsFormat[i], NULL, 10); while (iswdigit(_wcsFormat[i])) { i++; } } else switch (_wcsFormat[i]) { case L' ' : case L'\n': case L'\t': i++; break; case L'%' : i++; bIgnoredChars = FALSE; break; case L'*' : bStar = TRUE; i++; break; case L'h' : case L'l' : case L'L' : wcsLLH = _wcsFormat[i]; i++; break; case L'c' : { if (wcsData != NULL && wcsData[0] != L'\0') // If the end of data has not been reached we can get datas. { wchar_t wcSingleData[2]; wcSingleData[0] = wcsData[0]; wcSingleData[1] = 0; if (!bStar) // If this format is not ignored put the datas found. { if (_iIterrator == 0) // Create and initialize the container only the first time. { types::String* pS = new types::String(dims, dimsArray); for (int k = 0 ; k < pS->getSize(); k++) { pS->set(k, L""); } _pITOut->push_back(pS); } (*_pITOut)[j]->getAs<types::String>()->set(_iIterrator, wcSingleData); iCountDataRead++; } wcsData++; } else { if (_iIterrator == 0 && !bStar && _iNiter == 1) { _pITOut->push_back(types::Double::Empty()); } else { FREE(wcsData); return -10; } } if (!bStar) { j++; } i++; bIgnoredChars = TRUE; bStar = FALSE; } break; case L's' : { if (wcsData != NULL && wcsData[0] != L'\0') { wchar_t* wcsSingleData = NULL; wchar_t* wcsRes = NULL; wchar_t seps[] = L" \t\n"; int sizeOfCurrentData = (int)wcslen(wcsData); wchar_t* wcsTemp = (wchar_t*)MALLOC((sizeOfCurrentData + 1) * sizeof(wchar_t)); memcpy(wcsTemp, wcsData, sizeOfCurrentData * sizeof(wchar_t)); wcsTemp[sizeOfCurrentData] = L'\0'; wcsRes = os_wcstok(wcsTemp, seps, &wcsTemp); // the seps[] found is replaced by the '\0' char. if (wcsTemp == NULL || wcsTemp[0] == L'\0') { wcsData = NULL; } else { wcsData += (wcslen(wcsData) - wcslen(wcsTemp) - 1); // set the pointer on the seps[] and not on the next char. } if (nbrOfDigit) // Get only the numbers of digit indicated in the format. (ex: %2d) { wcsSingleData = (wchar_t*)MALLOC(sizeof(wchar_t) * (nbrOfDigit + 1)); memcpy(wcsSingleData, wcsRes, sizeof(wchar_t) * nbrOfDigit); wcsSingleData[nbrOfDigit] = L'\0'; nbrOfDigit = 0; } else // Get all data find. { wcsSingleData = wcsRes; } if (!bStar) { if (_iIterrator == 0) { types::String* pS = new types::String(dims, dimsArray); for (int k = 0 ; k < pS->getSize(); k++) { pS->set(k, L""); } _pITOut->push_back(pS); } (*_pITOut)[j]->getAs<types::String>()->set(_iIterrator, wcsSingleData); iCountDataRead++; } if (nbrOfDigit) { FREE(wcsSingleData); } } else { if (_iIterrator == 0 && !bStar && _iNiter == 1) { _pITOut->push_back(types::Double::Empty()); } else { FREE(wcsData); return -10; } } if (!bStar) { j++; } i++; bIgnoredChars = TRUE; bStar = FALSE; } break; case L'[' : { if (wcsData != NULL && wcsData[0] != L'\0') { wchar_t* wcsInside = NULL; wchar_t* wcsCpyFormat = NULL; unsigned int iPos = 0; wchar_t* wcsSingleData = NULL; wchar_t* wcsRes = NULL; wchar_t* wscToFind = NULL; BOOL bInv = FALSE; i++; wcsCpyFormat = (wchar_t*)MALLOC((wcslen(_wcsFormat) - i + 1) * sizeof(wchar_t)); memcpy(wcsCpyFormat, &_wcsFormat[i], (wcslen(_wcsFormat) - i) * sizeof(wchar_t)); wcsCpyFormat[wcslen(_wcsFormat) - i] = L'\0'; wcsInside = os_wcstok(wcsCpyFormat, L"]", &wcsCpyFormat); i += (int)wcslen(wcsInside) + 1; // +1 => ] wscToFind = findChars(wcsInside, &bInv); if (wscToFind == NULL) { // MALLOC error FREE(wcsData); return -10; } if (bInv) { iPos = (int)wcscspn(wcsData, wscToFind); } else { iPos = (int)wcsspn(wcsData, wscToFind); } if (iPos == 0) { // The string begins with a character which is not in wscToFind if (_iIterrator == 0 && !bStar && _iNiter == 1) { _pITOut->push_back(types::Double::Empty()); } else { FREE(wcsData); return -10; } } else { wcsRes = (wchar_t*)MALLOC((iPos + 1) * sizeof(wchar_t)); memcpy(wcsRes, wcsData, iPos * sizeof(wchar_t)); wcsRes[iPos] = '\0'; FREE(wcsInside); if (nbrOfDigit) { wcsSingleData = (wchar_t*)MALLOC(sizeof(wchar_t) * (nbrOfDigit + 1)); memcpy(wcsSingleData, wcsRes, sizeof(wchar_t) * nbrOfDigit); wcsSingleData[nbrOfDigit] = L'\0'; wcsData += nbrOfDigit; } else { wcsSingleData = wcsRes; wcsData += iPos; } } if (!bStar) { if (_iIterrator == 0) { types::String* pS = new types::String(dims, dimsArray); for (int k = 0 ; k < pS->getSize(); k++) { pS->set(k, L""); } _pITOut->push_back(pS); } if (wcsSingleData != NULL) { (*_pITOut)[j]->getAs<types::String>()->set(_iIterrator, wcsSingleData); iCountDataRead++; } } if (nbrOfDigit) { FREE(wcsSingleData); } } else { if (_iIterrator == 0 && !bStar && _iNiter == 1) { _pITOut->push_back(types::Double::Empty()); } else { FREE(wcsData); return -10; } } if (!bStar) { j++; } bIgnoredChars = TRUE; nbrOfDigit = 0; bStar = FALSE; } break; case L'x' : case L'X' : base += 6; // 6 + 2 + 8 = 16 // Compute the base of data to get. case L'u' : if (base == 0) { bUnsigned = TRUE; // unsigned int } case L'i' : case L'd' : base += 2; // 2 + 8 = 10 case L'o' : base += 8; // 8 = 8 :D { if (wcsData != NULL && wcsData[0] != L'\0') { long int iSingleData = 0; while (wcsData[0] == L' ') { wcsData++; } if (nbrOfDigit) { wchar_t* number = NULL; if (wcslen(wcsData) < nbrOfDigit) { nbrOfDigit = (int)wcslen(wcsData); } number = (wchar_t*)MALLOC((nbrOfDigit + 1) * sizeof(wchar_t)); memcpy(number, wcsData, nbrOfDigit * sizeof(wchar_t)); number[nbrOfDigit] = L'\0'; iSingleData = wcstoul(number, &number, base); if ((iSingleData == 0) && (number[0] == wcsData[0])) { if (_iIterrator == 0 && !bStar && _iNiter == 1) { wcsData = NULL; _pITOut->push_back(types::Double::Empty()); bStar = TRUE; } else { FREE(wcsData); return -10; } } if (number == NULL) { wcsData += nbrOfDigit; } else { wcsData += (nbrOfDigit - wcslen(number)); } nbrOfDigit = 0; } else { wchar_t temp = wcsData[0]; iSingleData = wcstoul(wcsData, &wcsData, base); if ((iSingleData == 0) && (temp == wcsData[0])) { if (_iIterrator == 0 && !bStar && _iNiter == 1) { wcsData = NULL; _pITOut->push_back(types::Double::Empty()); bStar = TRUE; } else { FREE(wcsData); return -10; } } } if (!bStar) { if (_iIterrator == 0) { switch (wcsLLH) { case L'h' : { if (bUnsigned) { types::UInt16* pUInt16 = new types::UInt16(dims, dimsArray); for (int k = 0; k < pUInt16->getSize(); k++) { pUInt16->set(k, 0); } _pITOut->push_back(pUInt16); } else { types::Int16* pInt16 = new types::Int16(dims, dimsArray); for (int k = 0; k < pInt16->getSize(); k++) { pInt16->set(k, 0); } _pITOut->push_back(pInt16); } } break; case L'l' : case L'L' : { if (bUnsigned) { types::UInt64* pUInt64 = new types::UInt64(dims, dimsArray); for (int k = 0; k < pUInt64->getSize(); k++) { pUInt64->set(k, 0); } _pITOut->push_back(pUInt64); } else { types::Int64* pInt64 = new types::Int64(dims, dimsArray); for (int k = 0; k < pInt64->getSize(); k++) { pInt64->set(k, 0); } _pITOut->push_back(pInt64); } } break; default : { if (bUnsigned) { types::UInt32* pUInt32 = new types::UInt32(dims, dimsArray); for (int k = 0; k < pUInt32->getSize(); k++) { pUInt32->set(k, 0); } _pITOut->push_back(pUInt32); } else { types::Int32* pInt32 = new types::Int32(dims, dimsArray); for (int k = 0; k < pInt32->getSize(); k++) { pInt32->set(k, 0); } _pITOut->push_back(pInt32); } } } } switch (wcsLLH) { case L'h' : if (bUnsigned) { (*_pITOut)[j]->getAs<types::UInt16>()->set(_iIterrator, static_cast<unsigned short int>(iSingleData)); iCountDataRead++; } else { (*_pITOut)[j]->getAs<types::Int16>()->set(_iIterrator, static_cast<short int>(iSingleData)); iCountDataRead++; } break; case L'l' : case L'L' : if (bUnsigned) { (*_pITOut)[j]->getAs<types::UInt64>()->set(_iIterrator, iSingleData); iCountDataRead++; } else { (*_pITOut)[j]->getAs<types::Int64>()->set(_iIterrator, static_cast<long int>(iSingleData)); iCountDataRead++; } break; default : if (bUnsigned) { (*_pITOut)[j]->getAs<types::UInt32>()->set(_iIterrator, static_cast<unsigned int>(iSingleData)); iCountDataRead++; } else { (*_pITOut)[j]->getAs<types::Int32>()->set(_iIterrator, static_cast<int>(iSingleData)); iCountDataRead++; } } } } else { if (_iIterrator == 0 && !bStar && _iNiter == 1) { _pITOut->push_back(types::Double::Empty()); } else { FREE(wcsData); return -10; } } if (!bStar) { j++; } wcsLLH = L' '; bIgnoredChars = TRUE; bUnsigned = FALSE; bStar = FALSE; base = 0; i++; } break; case L'e' : case L'E' : case L'g' : case L'G' : case L'f' : { if (wcsData != NULL && wcsData[0] != L'\0') { double dSingleData = 0; BOOL bSigne = FALSE; while (wcsData[0] == L' ') { wcsData++; } if (nbrOfDigit) { int iSizeRead = 0; wchar_t* number = NULL; wchar_t* next = NULL; if (wcslen(wcsData) < nbrOfDigit) { nbrOfDigit = (int)wcslen(wcsData); } number = (wchar_t*)MALLOC((nbrOfDigit + 1) * sizeof(wchar_t)); memcpy(number, wcsData, nbrOfDigit * sizeof(wchar_t)); number[nbrOfDigit] = L'\0'; dSingleData = wcstod(number, &next); if (next) { iSizeRead = nbrOfDigit - (int)wcslen(next); } else { iSizeRead = nbrOfDigit; } if ((dSingleData == 0) && (number[0] == next[0])) { if (_iIterrator == 0 && !bStar && _iNiter == 1) { wcsData = NULL; _pITOut->push_back(types::Double::Empty()); bStar = TRUE; } else { FREE(wcsData); return -10; } } wcsData += iSizeRead; FREE(number); nbrOfDigit = 0; } else { int iLenData = (int)wcslen(wcsData); dSingleData = wcstod(wcsData, &wcsData); if ((dSingleData == 0) && (iLenData == wcslen(wcsData))) { if (_iIterrator == 0 && !bStar && _iNiter == 1) { wcsData = NULL; _pITOut->push_back(types::Double::Empty()); bStar = TRUE; } else { FREE(wcsData); return -10; } } } if (!bStar) { if (_iIterrator == 0) { types::Double* pD = new types::Double(dims, dimsArray); for (int k = 0 ; k < pD->getSize(); k++) { pD->set(k, 0); } _pITOut->push_back(pD); } (*_pITOut)[j]->getAs<types::Double>()->set(_iIterrator, dSingleData); iCountDataRead++; } } else { if (_iIterrator == 0 && !bStar && _iNiter == 1) { _pITOut->push_back(types::Double::Empty()); } else { FREE(wcsData); return -10; } } if (!bStar) { j++; } i++; bIgnoredChars = TRUE; bStar = FALSE; } break; case L'n' : { double dSingleData = -1; if (_iIterrator == 0 && !bStar) { types::Double* pD = new types::Double(dims, dimsArray); for (int k = 0 ; k < pD->getSize(); k++) { pD->set(k, 0); } _pITOut->push_back(pD); } if (wcsData == NULL || wcsData[0] == L'\0') { dSingleData = (double)sizeOfData; } else { dSingleData = (double)sizeOfData - (double)wcslen(wcsData); } if (!bStar) { (*_pITOut)[j]->getAs<types::Double>()->set(_iIterrator, dSingleData); j++; } i++; bIgnoredChars = TRUE; bStar = FALSE; } break; default : printf("format read : %c\n", _wcsFormat[i]); FREE(wcsData); return -10; } } FREE(wcsData); return iCountDataRead; }
void ProcessDebugEvent() { static wchar_t wszDbgText[1024]; static char szDbgText[1024]; BOOL lbNonContinuable = FALSE; DEBUG_EVENT evt = {0}; BOOL lbEvent = WaitForDebugEvent(&evt,10); #ifdef _DEBUG DWORD dwErr = GetLastError(); #endif static bool bFirstExitThreadEvent = false; // Чтобы вывести на экран подсказку по возможностям "дебаггера" //HMODULE hCOMDLG32 = NULL; //typedef BOOL (WINAPI* GetSaveFileName_t)(LPOPENFILENAMEW lpofn); //GetSaveFileName_t _GetSaveFileName = NULL; DWORD dwContinueStatus = DBG_EXCEPTION_NOT_HANDLED; if (lbEvent) { lbNonContinuable = FALSE; switch (evt.dwDebugEventCode) { case CREATE_PROCESS_DEBUG_EVENT: case CREATE_THREAD_DEBUG_EVENT: case EXIT_PROCESS_DEBUG_EVENT: case EXIT_THREAD_DEBUG_EVENT: case RIP_EVENT: { LPCSTR pszName = "Unknown"; switch (evt.dwDebugEventCode) { case CREATE_PROCESS_DEBUG_EVENT: pszName = "CREATE_PROCESS_DEBUG_EVENT"; break; case CREATE_THREAD_DEBUG_EVENT: pszName = "CREATE_THREAD_DEBUG_EVENT"; break; case EXIT_PROCESS_DEBUG_EVENT: pszName = "EXIT_PROCESS_DEBUG_EVENT"; break; case EXIT_THREAD_DEBUG_EVENT: pszName = "EXIT_THREAD_DEBUG_EVENT"; break; case RIP_EVENT: pszName = "RIP_EVENT"; break; } _wsprintfA(szDbgText, SKIPLEN(countof(szDbgText)) "{%i.%i} %s\n", evt.dwProcessId,evt.dwThreadId, pszName); _printf(szDbgText); if (!bFirstExitThreadEvent && evt.dwDebugEventCode == EXIT_THREAD_DEBUG_EVENT) { bFirstExitThreadEvent = true; if (gpSrv->DbgInfo.nDebugDumpProcess == 0) { _printf("ConEmuC: Press Ctrl+Break to create minidump of debugging process\n"); } else { // Сразу сделать дамп и выйти HandlerRoutine(CTRL_BREAK_EVENT); } } if (evt.dwDebugEventCode == CREATE_PROCESS_DEBUG_EVENT) { gpSrv->DbgInfo.nProcessCount++; _ASSERTE(gpSrv->DbgInfo.pDebugTreeProcesses!=NULL); CEDebugProcessInfo pi = {evt.dwProcessId}; gpSrv->DbgInfo.pDebugTreeProcesses->Set(evt.dwProcessId, pi); UpdateDebuggerTitle(); } else if (evt.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT) { CEDebugProcessInfo pi = {}; if (gpSrv->DbgInfo.pDebugTreeProcesses && gpSrv->DbgInfo.pDebugTreeProcesses->Get(evt.dwProcessId, &pi, true) && pi.hProcess) { CloseHandle(pi.hProcess); } if (gpSrv->DbgInfo.nProcessCount > 0) gpSrv->DbgInfo.nProcessCount--; UpdateDebuggerTitle(); } break; } case LOAD_DLL_DEBUG_EVENT: case UNLOAD_DLL_DEBUG_EVENT: { LPCSTR pszName = "Unknown"; char szBase[32] = {}; char szFile[MAX_PATH+128] = {}; struct MY_FILE_NAME_INFO { DWORD FileNameLength; WCHAR FileName[1]; }; typedef BOOL (WINAPI* GetFileInformationByHandleEx_t)(HANDLE hFile, int FileInformationClass, LPVOID lpFileInformation, DWORD dwBufferSize); static GetFileInformationByHandleEx_t _GetFileInformationByHandleEx = NULL; switch (evt.dwDebugEventCode) { case LOAD_DLL_DEBUG_EVENT: //6 Reports a load-dynamic-link-library (DLL) debugging event. The value of u.LoadDll specifies a LOAD_DLL_DEBUG_INFO structure. pszName = "LOAD_DLL_DEBUG_EVENT"; if (evt.u.LoadDll.hFile) { if (gnOsVer >= 0x0600) { if (!_GetFileInformationByHandleEx) _GetFileInformationByHandleEx = (GetFileInformationByHandleEx_t)GetProcAddress(GetModuleHandle(L"kernel32.dll"), "GetFileInformationByHandleEx"); if (_GetFileInformationByHandleEx) { DWORD nSize = sizeof(MY_FILE_NAME_INFO)+MAX_PATH*sizeof(wchar_t); MY_FILE_NAME_INFO* pfi = (MY_FILE_NAME_INFO*)calloc(nSize+2,1); if (pfi) { pfi->FileNameLength = MAX_PATH; if (_GetFileInformationByHandleEx(evt.u.LoadDll.hFile, 2/*FileNameInfo*/, pfi, nSize) && pfi->FileName[0]) { wchar_t szFullPath[MAX_PATH+1] = {}, *pszFile; DWORD n = GetFullPathName(pfi->FileName, countof(szFullPath), szFullPath, &pszFile); if (!n || (n >= countof(szFullPath))) { lstrcpyn(szFullPath, pfi->FileName, countof(szFullPath)); pszFile = (wchar_t*)PointToName(pfi->FileName); } else if (!pszFile) { pszFile = (wchar_t*)PointToName(szFullPath); } lstrcpyA(szFile, ", "); WideCharToMultiByte(CP_OEMCP, 0, pszFile, -1, szFile+lstrlenA(szFile), 80, 0,0); lstrcatA(szFile, "\n\t"); WideCharToMultiByte(CP_OEMCP, 0, szFullPath, -1, szFile+lstrlenA(szFile), MAX_PATH, 0,0); } free(pfi); } } } CloseHandle(evt.u.LoadDll.hFile); } _wsprintfA(szBase, SKIPLEN(countof(szBase)) " at " WIN3264TEST("0x%08X","0x%08X%08X"), WIN3264WSPRINT((DWORD_PTR)evt.u.LoadDll.lpBaseOfDll)); break; case UNLOAD_DLL_DEBUG_EVENT: //7 Reports an unload-DLL debugging event. The value of u.UnloadDll specifies an UNLOAD_DLL_DEBUG_INFO structure. pszName = "UNLOAD_DLL_DEBUG_EVENT"; _wsprintfA(szBase, SKIPLEN(countof(szBase)) " at " WIN3264TEST("0x%08X","0x%08X%08X"), WIN3264WSPRINT((DWORD_PTR)evt.u.UnloadDll.lpBaseOfDll)); break; } _wsprintfA(szDbgText, SKIPLEN(countof(szDbgText)) "{%i.%i} %s%s%s\n", evt.dwProcessId,evt.dwThreadId, pszName, szBase, szFile); _printf(szDbgText); break; } case EXCEPTION_DEBUG_EVENT: //1 Reports an exception debugging event. The value of u.Exception specifies an EXCEPTION_DEBUG_INFO structure. { lbNonContinuable = (evt.u.Exception.ExceptionRecord.ExceptionFlags&EXCEPTION_NONCONTINUABLE)==EXCEPTION_NONCONTINUABLE; //static bool bAttachEventRecieved = false; //if (!bAttachEventRecieved) //{ // bAttachEventRecieved = true; // StringCchPrintfA(szDbgText, countof(szDbgText),"{%i.%i} Debugger attached successfully. (0x%08X address 0x%08X flags 0x%08X%s)\n", // evt.dwProcessId,evt.dwThreadId, // evt.u.Exception.ExceptionRecord.ExceptionCode, // evt.u.Exception.ExceptionRecord.ExceptionAddress, // evt.u.Exception.ExceptionRecord.ExceptionFlags, // (evt.u.Exception.ExceptionRecord.ExceptionFlags&EXCEPTION_NONCONTINUABLE) ? "(EXCEPTION_NONCONTINUABLE)" : ""); //} //else switch (evt.u.Exception.ExceptionRecord.ExceptionCode) { case EXCEPTION_ACCESS_VIOLATION: // The thread tried to read from or write to a virtual address for which it does not have the appropriate access. { if (evt.u.Exception.ExceptionRecord.NumberParameters>=2) { _wsprintfA(szDbgText, SKIPLEN(countof(szDbgText)) "{%i.%i} EXCEPTION_ACCESS_VIOLATION at " WIN3264TEST("0x%08X","0x%08X%08X") " flags 0x%08X%s %s of " WIN3264TEST("0x%08X","0x%08X%08X") " FC=%u\n", evt.dwProcessId,evt.dwThreadId, WIN3264WSPRINT((DWORD_PTR)evt.u.Exception.ExceptionRecord.ExceptionAddress), evt.u.Exception.ExceptionRecord.ExceptionFlags, ((evt.u.Exception.ExceptionRecord.ExceptionFlags&EXCEPTION_NONCONTINUABLE) ? "(EXCEPTION_NONCONTINUABLE)" : ""), ((evt.u.Exception.ExceptionRecord.ExceptionInformation[0]==0) ? "Read" : (evt.u.Exception.ExceptionRecord.ExceptionInformation[0]==1) ? "Write" : (evt.u.Exception.ExceptionRecord.ExceptionInformation[0]==8) ? "DEP" : "???"), WIN3264WSPRINT(evt.u.Exception.ExceptionRecord.ExceptionInformation[1]), evt.u.Exception.dwFirstChance ); } else { _wsprintfA(szDbgText, SKIPLEN(countof(szDbgText)) "{%i.%i} EXCEPTION_ACCESS_VIOLATION at " WIN3264TEST("0x%08X","0x%08X%08X") " flags 0x%08X%s FC=%u\n", evt.dwProcessId,evt.dwThreadId, WIN3264WSPRINT((DWORD_PTR)evt.u.Exception.ExceptionRecord.ExceptionAddress), evt.u.Exception.ExceptionRecord.ExceptionFlags, (evt.u.Exception.ExceptionRecord.ExceptionFlags&EXCEPTION_NONCONTINUABLE) ? "(EXCEPTION_NONCONTINUABLE)" : "", evt.u.Exception.dwFirstChance); } _printf(szDbgText); } break; default: { char szName[32]; LPCSTR pszName; pszName = szName; #define EXCASE(s) case s: pszName = #s; break switch(evt.u.Exception.ExceptionRecord.ExceptionCode) { EXCASE(EXCEPTION_ARRAY_BOUNDS_EXCEEDED); // The thread tried to access an array element that is out of bounds and the underlying hardware supports bounds checking. EXCASE(EXCEPTION_BREAKPOINT); // A breakpoint was encountered. EXCASE(EXCEPTION_DATATYPE_MISALIGNMENT); // The thread tried to read or write data that is misaligned on hardware that does not provide alignment. For example, 16-bit values must be aligned on 2-byte boundaries; 32-bit values on 4-byte boundaries, and so on. EXCASE(EXCEPTION_FLT_DENORMAL_OPERAND); // One of the operands in a floating-point operation is denormal. A denormal value is one that is too small to represent as a standard floating-point value. EXCASE(EXCEPTION_FLT_DIVIDE_BY_ZERO); // The thread tried to divide a floating-point value by a floating-point divisor of zero. EXCASE(EXCEPTION_FLT_INEXACT_RESULT); // The result of a floating-point operation cannot be represented exactly as a decimal fraction. EXCASE(EXCEPTION_FLT_INVALID_OPERATION); // This exception represents any floating-point exception not included in this list. EXCASE(EXCEPTION_FLT_OVERFLOW); // The exponent of a floating-point operation is greater than the magnitude allowed by the corresponding type. EXCASE(EXCEPTION_FLT_STACK_CHECK); // The stack overflowed or underflowed as the result of a floating-point operation. EXCASE(EXCEPTION_FLT_UNDERFLOW); // The exponent of a floating-point operation is less than the magnitude allowed by the corresponding type. EXCASE(EXCEPTION_ILLEGAL_INSTRUCTION); // The thread tried to execute an invalid instruction. EXCASE(EXCEPTION_IN_PAGE_ERROR); // The thread tried to access a page that was not present, and the system was unable to load the page. For example, this exception might occur if a network connection is lost while running a program over the network. EXCASE(EXCEPTION_INT_DIVIDE_BY_ZERO); // The thread tried to divide an integer value by an integer divisor of zero. EXCASE(EXCEPTION_INT_OVERFLOW); // The result of an integer operation caused a carry out of the most significant bit of the result. EXCASE(EXCEPTION_INVALID_DISPOSITION); // An exception handler returned an invalid disposition to the exception dispatcher. Programmers using a high-level language such as C should never encounter this exception. EXCASE(EXCEPTION_NONCONTINUABLE_EXCEPTION); // The thread tried to continue execution after a noncontinuable exception occurred. EXCASE(EXCEPTION_PRIV_INSTRUCTION); // The thread tried to execute an instruction whose operation is not allowed in the current machine mode. EXCASE(EXCEPTION_SINGLE_STEP); // A trace trap or other single-instruction mechanism signaled that one instruction has been executed. EXCASE(EXCEPTION_STACK_OVERFLOW); // The thread used up its stack. default: _wsprintfA(szName, SKIPLEN(countof(szName)) "Exception 0x%08X", evt.u.Exception.ExceptionRecord.ExceptionCode); } _wsprintfA(szDbgText, SKIPLEN(countof(szDbgText)) "{%i.%i} %s at " WIN3264TEST("0x%08X","0x%08X%08X") " flags 0x%08X%s FC=%u\n", evt.dwProcessId,evt.dwThreadId, pszName, WIN3264WSPRINT((DWORD_PTR)evt.u.Exception.ExceptionRecord.ExceptionAddress), evt.u.Exception.ExceptionRecord.ExceptionFlags, (evt.u.Exception.ExceptionRecord.ExceptionFlags&EXCEPTION_NONCONTINUABLE) ? "(EXCEPTION_NONCONTINUABLE)" : "", evt.u.Exception.dwFirstChance); _printf(szDbgText); } } BOOL bDumpOnBreakPoint = gpSrv->DbgInfo.bDebuggerRequestDump; if (gpSrv->DbgInfo.bDebugProcessTree && (!lbNonContinuable && (evt.u.Exception.ExceptionRecord.ExceptionCode==EXCEPTION_BREAKPOINT))) { // Когда отладчик цепляется к процессу в первый раз - возникает EXCEPTION_BREAKPOINT CEDebugProcessInfo pi = {}; if (gpSrv->DbgInfo.pDebugTreeProcesses && gpSrv->DbgInfo.pDebugTreeProcesses->Get(evt.dwProcessId, &pi)) { if (!pi.bWasBreak) { pi.bWasBreak = TRUE; gpSrv->DbgInfo.pDebugTreeProcesses->Set(evt.dwProcessId, pi); } else { bDumpOnBreakPoint = TRUE; } } } if (gpSrv->DbgInfo.bDebuggerRequestDump || (!lbNonContinuable && !gpSrv->DbgInfo.bDebugProcessTree && (evt.u.Exception.ExceptionRecord.ExceptionCode != EXCEPTION_BREAKPOINT)) || (gpSrv->DbgInfo.bDebugProcessTree && ((evt.u.Exception.ExceptionRecord.ExceptionCode>=0xC0000000) || (bDumpOnBreakPoint && (evt.u.Exception.ExceptionRecord.ExceptionCode==EXCEPTION_BREAKPOINT)))) ) { BOOL bGenerateTreeBreak = gpSrv->DbgInfo.bDebugProcessTree && (gpSrv->DbgInfo.bDebuggerRequestDump || lbNonContinuable); if (gpSrv->DbgInfo.bDebugProcessTree && !bGenerateTreeBreak && (evt.u.Exception.ExceptionRecord.ExceptionCode==EXCEPTION_BREAKPOINT)) { if (gpSrv->DbgInfo.nWaitTreeBreaks == 0) { bGenerateTreeBreak = TRUE; gpSrv->DbgInfo.nWaitTreeBreaks++; } } gpSrv->DbgInfo.bDebuggerRequestDump = FALSE; // один раз char szConfirm[2048]; if (evt.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT) { if (gpSrv->DbgInfo.nDebugDumpProcess) szConfirm[0] = 0; else lstrcpynA(szConfirm, szDbgText, countof(szConfirm)); } else { _wsprintfA(szConfirm, SKIPLEN(countof(szConfirm)) "%s exception (FC=%u)\n", lbNonContinuable ? "Non continuable" : "Continuable", evt.u.Exception.dwFirstChance); StringCchCatA(szConfirm, countof(szConfirm), szDbgText); } StringCchCatA(szConfirm, countof(szConfirm), "\nCreate minidump (<No> - fulldump)?"); //GenerateTreeDebugBreak WriteMiniDump(evt.dwProcessId, evt.dwThreadId, &evt.u.Exception.ExceptionRecord, szConfirm, bGenerateTreeBreak); if (gpSrv->DbgInfo.bDebugProcessTree && (evt.u.Exception.ExceptionRecord.ExceptionCode==EXCEPTION_BREAKPOINT)) { if (gpSrv->DbgInfo.nWaitTreeBreaks > 0) gpSrv->DbgInfo.nWaitTreeBreaks--; } } if (!lbNonContinuable /*|| (evt.u.Exception.ExceptionRecord.ExceptionCode==EXCEPTION_BREAKPOINT)*/) { dwContinueStatus = DBG_CONTINUE; } } break; case OUTPUT_DEBUG_STRING_EVENT: //8 Reports an output-debugging-string debugging event. The value of u.DebugString specifies an OUTPUT_DEBUG_STRING_INFO structure. { wszDbgText[0] = 0; if (evt.u.DebugString.nDebugStringLength >= 1024) evt.u.DebugString.nDebugStringLength = 1023; DWORD_PTR nRead = 0; HANDLE hProcess = GetProcessHandleForDebug(evt.dwProcessId); if (evt.u.DebugString.fUnicode) { if (!ReadProcessMemory(hProcess, evt.u.DebugString.lpDebugStringData, wszDbgText, 2*evt.u.DebugString.nDebugStringLength, &nRead)) { wcscpy_c(wszDbgText, L"???"); } else { wszDbgText[min(1023,nRead+1)] = 0; } static int nPrefixLen = lstrlen(CONEMU_CONHOST_CREATED_MSG); if (memcmp(wszDbgText, CONEMU_CONHOST_CREATED_MSG, nPrefixLen*sizeof(wszDbgText[0])) == 0) { LPWSTR pszEnd = NULL; DWORD nConHostPID = wcstoul(wszDbgText+nPrefixLen, &pszEnd, 10); if (nConHostPID && !gpSrv->DbgInfo.pDebugTreeProcesses->Get(nConHostPID, NULL)) { AttachConHost(nConHostPID); } } } else { if (!ReadProcessMemory(hProcess, evt.u.DebugString.lpDebugStringData, szDbgText, evt.u.DebugString.nDebugStringLength, &nRead)) { wcscpy_c(wszDbgText, L"???"); } else { szDbgText[min(1023,nRead+1)] = 0; // CP_ACP differs from CP_OEMCP, thats why we need some overhead... MultiByteToWideChar(CP_ACP, 0, szDbgText, -1, wszDbgText, 1024); } } WideCharToMultiByte(CP_OEMCP, 0, wszDbgText, -1, szDbgText, 1024, 0, 0); #ifdef CRTPRINTF { _printf("{PID=%i.TID=%i} ", evt.dwProcessId,evt.dwThreadId, wszDbgText); } #else { _printf("{PID=%i.TID=%i} %s", evt.dwProcessId,evt.dwThreadId, szDbgText); int nLen = lstrlenA(szDbgText); if (nLen > 0 && szDbgText[nLen-1] != '\n') _printf("\n"); } #endif dwContinueStatus = DBG_CONTINUE; } break; } // Продолжить отлаживаемый процесс ContinueDebugEvent(evt.dwProcessId, evt.dwThreadId, dwContinueStatus); } //if (hCOMDLG32) // FreeLibrary(hCOMDLG32); }
/***************************************************************************** wmain *****************************************************************************/ DWORD __cdecl wmain( int argc, LPWSTR argv[] ) { HRESULT hr = S_OK; int i = 0; BOOL fPeerTrust = FALSE; DWORD dwChainFlags = CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT; LPCWSTR wsCertFile = NULL; LPCWSTR wsStoreFile = NULL; PCCERT_CONTEXT pCert = NULL; HCERTSTORE hStore = NULL; HCERTCHAINENGINE hChainEngine = NULL; PCCERT_CHAIN_CONTEXT pChainContext = NULL; CERT_ENHKEY_USAGE EnhkeyUsage = {0}; CERT_USAGE_MATCH CertUsage = {0}; CERT_CHAIN_PARA ChainPara = {0}; CERT_CHAIN_POLICY_PARA ChainPolicy = {0}; CERT_CHAIN_POLICY_STATUS PolicyStatus = {0}; CERT_CHAIN_ENGINE_CONFIG EngineConfig = {0}; //--------------------------------------------------------- // Initialize data structures for chain building. EnhkeyUsage.cUsageIdentifier = 0; EnhkeyUsage.rgpszUsageIdentifier=NULL; CertUsage.dwType = USAGE_MATCH_TYPE_AND; CertUsage.Usage = EnhkeyUsage; ChainPara.cbSize = sizeof(ChainPara); ChainPara.RequestedUsage=CertUsage; ChainPolicy.cbSize = sizeof(ChainPolicy); PolicyStatus.cbSize = sizeof(PolicyStatus); EngineConfig.cbSize = sizeof(EngineConfig); EngineConfig.dwUrlRetrievalTimeout = 0; // // options // for( i=1; i<argc; i++ ) { if ( lstrcmpW (argv[i], L"/?") == 0 || lstrcmpW (argv[i], L"-?") == 0 ) { Usage(argv[0]); goto CleanUp; } if( *argv[i] != L'-' ) break; if ( lstrcmpW (argv[i], L"-fc") == 0 ) { if( i+1 >= argc ) { goto InvalidCommandLine; } dwChainFlags = (DWORD)wcstoul( argv[++i], NULL, 0 ); } else if ( lstrcmpW (argv[i], L"-fe") == 0 ) { if( i+1 >= argc ) { goto InvalidCommandLine; } EngineConfig.dwFlags = (DWORD)wcstoul( argv[++i], NULL, 0 ); } else if ( lstrcmpW (argv[i], L"-p") == 0 ) { fPeerTrust = TRUE; } else { goto InvalidCommandLine; } } if( i >= argc ) { goto InvalidCommandLine; } wsStoreFile = argv[i++]; if( i < argc ) { wsCertFile = argv[i]; } hStore = CertOpenStore( CERT_STORE_PROV_FILENAME_W, X509_ASN_ENCODING, NULL, CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG, wsStoreFile ); if( NULL == hStore ) { hr = HRESULT_FROM_WIN32( GetLastError() ); goto CleanUp; } if( NULL != wsCertFile && 0 != *wsCertFile ) { if( !CryptQueryObject( CERT_QUERY_OBJECT_FILE, wsCertFile, CERT_QUERY_CONTENT_FLAG_CERT | CERT_QUERY_CONTENT_SERIALIZED_CERT , CERT_QUERY_FORMAT_FLAG_ALL, 0, // dwFlags, 0, // pdwMsgAndCertEncodingType, 0, // pdwContentType, 0, // pdwFormatType, 0, // phCertStore, 0, // phMsg, (const void**)&pCert )) { hr = HRESULT_FROM_WIN32( GetLastError() ); goto CleanUp; } } else { pCert = CertFindCertificateInStore( hStore, X509_ASN_ENCODING, 0, CERT_FIND_ANY, NULL, NULL ); if( NULL == pCert ) { hr = CRYPT_E_NOT_FOUND; goto CleanUp; } } if( fPeerTrust ) { EngineConfig.hExclusiveTrustedPeople = hStore; // Exclusive peer trust dwChainFlags |= CERT_CHAIN_ENABLE_PEER_TRUST; } else { EngineConfig.hExclusiveRoot = hStore; // Exclusive root } //--------------------------------------------------------- // Create chain engine. if( !CertCreateCertificateChainEngine( &EngineConfig, &hChainEngine )) { hr = HRESULT_FROM_WIN32( GetLastError() ); goto CleanUp; } //------------------------------------------------------------------- // Build a chain using CertGetCertificateChain if( !CertGetCertificateChain( hChainEngine, pCert, // pointer to the end certificate NULL, // use the default time NULL, // search no additional stores &ChainPara, // use AND logic and enhanced key usage // as indicated in the ChainPara // data structure dwChainFlags, NULL, // currently reserved &pChainContext )) // return a pointer to the chain created { hr = HRESULT_FROM_WIN32( GetLastError() ); goto CleanUp; } //--------------------------------------------------------------- // Verify that the chain complies with policy if( !CertVerifyCertificateChainPolicy( CERT_CHAIN_POLICY_BASE, // use the base policy pChainContext, // pointer to the chain &ChainPolicy, &PolicyStatus )) // return a pointer to the policy status { hr = HRESULT_FROM_WIN32( GetLastError() ); goto CleanUp; } if( PolicyStatus.dwError != S_OK ) { hr = PolicyStatus.dwError; // Instruction: If the PolicyStatus.dwError is CRYPT_E_NO_REVOCATION_CHECK or CRYPT_E_REVOCATION_OFFLINE, it indicates errors in obtaining // revocation information. These can be ignored since the retrieval of revocation information depends on network availability goto CleanUp; } wprintf( L"CertVerifyCertificateChainPolicy succeeded.\n" ); hr = S_OK; // // END // goto CleanUp; // // Invalid Command Line // InvalidCommandLine: if( i < argc ) { wprintf( L"Invalid command line '%s'\n", argv[i] ); } else Usage(argv[0]); hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); CleanUp: if( FAILED(hr) ) { ReportError( NULL, hr ); } if( NULL != pChainContext ) { CertFreeCertificateChain( pChainContext ); } if( NULL != hChainEngine ) { CertFreeCertificateChainEngine( hChainEngine ); } if( NULL != pCert ) { CertFreeCertificateContext( pCert ); } if( NULL != hStore ) { CertCloseStore( hStore, 0 ); } return (DWORD)hr; } // end main