static void DbgPrint(LPCWSTR format, ...) { if (g_DebugMode) { const WCHAR *outputString; WCHAR *buffer = NULL; size_t length; va_list argp; va_start(argp, format); length = _vscwprintf(format, argp) + 1; buffer = _malloca(length * sizeof(WCHAR)); if (buffer) { vswprintf_s(buffer, length, format, argp); outputString = buffer; } else { outputString = format; } if (g_UseStdErr) fputws(outputString, stderr); else OutputDebugStringW(outputString); if (buffer) _freea(buffer); va_end(argp); } }
void _DBGPRINT( LPCWSTR kwszFunction, INT iLineNumber, LPCWSTR kwszDebugFormatString, ... ) { INT cbFormatString = 0; va_list args; PWCHAR wszDebugString = NULL; size_t st_Offset = 0; va_start( args, kwszDebugFormatString ); cbFormatString = _scwprintf( L"[%s:%d] ", kwszFunction, iLineNumber ) * sizeof( WCHAR ); cbFormatString += _vscwprintf( kwszDebugFormatString, args ) * sizeof( WCHAR ) + 2; /* Depending on the size of the format string, allocate space on the stack or the heap. */ wszDebugString = (PWCHAR)_malloca( cbFormatString ); /* Populate the buffer with the contents of the format string. */ StringCbPrintfW( wszDebugString, cbFormatString, L"[%s:%d] ", kwszFunction, iLineNumber ); StringCbLengthW( wszDebugString, cbFormatString, &st_Offset ); StringCbVPrintfW( &wszDebugString[st_Offset / sizeof(WCHAR)], cbFormatString - st_Offset, kwszDebugFormatString, args ); OutputDebugStringW( wszDebugString ); _freea( wszDebugString ); va_end( args ); }
VOID Console::FormatV( LPCWSTR wstrFormat, va_list pArgList ) { // Count the required length of the string DWORD dwStrLen = _vscwprintf( wstrFormat, pArgList ) + 1; // +1 = null terminator WCHAR* strMessage = ( WCHAR* )_malloca( dwStrLen * sizeof( WCHAR ) ); vswprintf_s( strMessage, dwStrLen, wstrFormat, pArgList ); // Output the string to the console for( DWORD i = 0; i < wcslen( strMessage ); i++ ) { Add( strMessage[i] ); } // Output the string to the debug channel, if requested if( m_bOutputToDebugChannel ) { OutputDebugStringW( strMessage ); } // Render the new output Render(); _freea( strMessage ); }
void FixedSizeAllocator::FreePage(void *page) { switch (m_arena) { case MEMORY_ARENA_STACK: _freea(page); break; case MEMORY_ARENA_HEAP: free(page); break; } }
BOOL ConvertMultiByteToUnicode(UINT CodePage) { // Get required buffer size int cbMultiByte = WideCharToMultiByte(CP_ACP, 0, lpSource, -1, NULL, 0, NULL, NULL); LPSTR lpTemp = (LPSTR)_malloca(cbMultiByte); WideCharToMultiByte(CP_ACP, 0, lpSource, -1, lpTemp, cbMultiByte, NULL, NULL); // Convert the CodePage encoded str to unicode int cchWideChar = MultiByteToWideChar(CodePage, 0, lpTemp, -1, NULL, 0); int cbUnicode = cchWideChar * sizeof(WCHAR); LPWSTR lpTarget = (LPWSTR)_malloca(cbUnicode); MultiByteToWideChar(CodePage, 0, lpTemp, -1, lpTarget, cchWideChar); BOOL fRenamed = MoveFile(lpSource, lpTarget) != 0; _freea(lpTemp); _freea(lpTarget); return fRenamed; }
BOOL ConvertTextFileToUnicode(UINT CodePage) { int const cbMax = 1024 * 1024; // Unable to process files larger than 1MB HANDLE hFile = CreateFile(lpSource, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL); if (hFile == INVALID_HANDLE_VALUE) return FALSE; LPSTR lpSourceText = (LPSTR)_malloca(cbMax); DWORD NumberOfBytesRead; ReadFile(hFile, lpSourceText, cbMax, &NumberOfBytesRead, NULL); CloseHandle(hFile); // Convert the CodePage encoded text to unicode int cchWideChar = MultiByteToWideChar(CodePage, 0, lpSourceText, NumberOfBytesRead, NULL, 0); int cbUnicode = cchWideChar * sizeof(WCHAR); LPWSTR lpTarget = (LPWSTR)_malloca(cbUnicode); int nWideCharsWritten = MultiByteToWideChar(CodePage, 0, lpSourceText, NumberOfBytesRead, lpTarget, cchWideChar); _freea(lpSourceText); // Backup the source file TCHAR szDefaultExt[5] = TEXT(".bak"); //int nLength = _tcslen(lpSource) + _tcslen(szDefaultExt); //LPTSTR lpBakFileName = (LPTSTR)malloc(nLength * sizeof(TCHAR)); //*lpBakFileName = NULL; TCHAR lpBakFileName[MAX_PATH] = TEXT(""); _tcscat_s(lpBakFileName, MAX_PATH, lpSource); _tcscat_s(lpBakFileName, MAX_PATH, szDefaultExt); if (MoveFile(lpSource, lpBakFileName) == 0) return FALSE; // Write the unicode text HANDLE hNewFile = CreateFile(lpSource, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hNewFile == INVALID_HANDLE_VALUE) return FALSE; DWORD NumberOfBytesWritten; // Write the unicode signature const WORD bom = 0xfeff; WriteFile(hFile, &bom, sizeof(bom), &NumberOfBytesWritten, NULL); WriteFile(hNewFile, lpTarget, nWideCharsWritten * sizeof(WCHAR), &NumberOfBytesWritten, NULL); // Treat lpTarget as ansi type to get the length in byte _freea(lpTarget); CloseHandle(hNewFile); return TRUE; }
HANDLE MemoryCallEntryPoint(HMEMORYMODULE mod, LPTSTR cmdLine) { PMEMORYMODULE module = (PMEMORYMODULE)mod; if (module == NULL || module->isDLL || module->exeEntry == NULL || !module->isRelocated) { return 0; } LPTSTR acmd = GetCommandLine(); LPTSTR bkpcmd = (LPTSTR)_malloca((_tcslen(acmd) + 1) * sizeof(TCHAR)); _tcscpy(bkpcmd, acmd); _tcscpy(acmd, cmdLine); HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *)) module->exeEntry, NULL, 0, 0); WaitForSingleObject(hThread, 100); _tcscpy(acmd, bkpcmd); _freea(bkpcmd); return hThread; }
std::wstring KRtoWide(const char* pKrStr, int len) { // Trim Right while (len > 0) { int ch = pKrStr[len - 1]; if (ch == ' ' || ch == 0) --len; else break; } int nReq = MultiByteToWideChar(CP_949, 0, pKrStr, len, NULL, 0); int cbAlloc = ++nReq * sizeof(WCHAR); WCHAR* pBuff = (WCHAR*)_malloca(cbAlloc); int wlen = MultiByteToWideChar(CP_949, 0, pKrStr, len, pBuff, nReq); ASSERT(wlen >= 0); std::wstring ret(pBuff, &pBuff[wlen]); _freea(pBuff); return ret; }
//-------------------------------------------------------------------------------------- // Name: FormatV() // Desc: Output a va_list using a format string //-------------------------------------------------------------------------------------- VOID Console::FormatV( _In_z_ _Printf_format_string_ LPCSTR strFormat, va_list pArgList ) { // Count the required length of the string DWORD dwStrLen = _vscprintf( strFormat, pArgList ) + 1; // +1 = null terminator CHAR* strMessage = ( CHAR* )_malloca( dwStrLen ); vsprintf_s( strMessage, dwStrLen, strFormat, pArgList ); // Output the string to the console for( DWORD i = 0; i < strlen( strMessage ); i++ ) { Add( strMessage[i] ); } // Output the string to the debug channel, if requested if( m_bOutputToDebugChannel ) { OutputDebugStringA( strMessage ); } // Render the new output Render(); _freea( strMessage ); }
int __cdecl _kbhit_nolock ( void ) { DWORD NumPending; DWORD NumPeeked; int ret = FALSE; PINPUT_RECORD pIRBuf=NULL; /* * if a character has been pushed back, return TRUE */ if ( chbuf != -1 ) return TRUE; /* * _coninpfh, the handle to the console input, is created the first * time that either _getch() or _cgets() or _kbhit() is called. */ if ( _coninpfh == -2 ) __initconin(); /* * Peek all pending console events */ if ( (_coninpfh == -1) || !GetNumberOfConsoleInputEvents((HANDLE)_coninpfh, &NumPending) || (NumPending == 0)) { return FALSE; } pIRBuf=(PINPUT_RECORD)_calloca(NumPending, sizeof(INPUT_RECORD)); if ( pIRBuf == NULL ) { return FALSE; } if ( PeekConsoleInput( (HANDLE)_coninpfh, pIRBuf, NumPending, &NumPeeked ) && (NumPeeked != 0L) && (NumPeeked <= NumPending) ) { /* * Scan all of the peeked events to determine if any is a key event * which should be recognized. */ PINPUT_RECORD pIR; for ( pIR = pIRBuf ; NumPeeked > 0 ; NumPeeked--, pIR++ ) { if ( (pIR->EventType == KEY_EVENT) && (pIR->Event.KeyEvent.bKeyDown) && ( pIR->Event.KeyEvent.uChar.AsciiChar || _getextendedkeycode( &(pIR->Event.KeyEvent) ) ) ) { /* * Key event corresponding to an ASCII character or an * extended code. In either case, success! */ ret = TRUE; } } } _freea( pIRBuf ); return ret; }
static int __cdecl __crtLCMapStringW_stat( _locale_t plocinfo, LCID Locale, DWORD dwMapFlags, LPCWSTR lpSrcStr, int cchSrc, LPWSTR lpDestStr, int cchDest, int code_page ) { static int f_use = 0; /* * Look for unstubbed 'preferred' flavor. Otherwise use available flavor. * Must actually call the function to ensure it's not a stub. */ if (0 == f_use) { if (0 != LCMapStringW(0, LCMAP_LOWERCASE, L"\0", 1, NULL, 0)) { f_use = USE_W; } else if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED) { f_use = USE_A; } } /* * LCMapString will map past NULL. Must find NULL if in string * before cchSrc wide characters. */ if (cchSrc > 0) { cchSrc = wcsncnt(lpSrcStr, cchSrc); } /* Use "W" version */ if (USE_W == f_use) { return LCMapStringW(Locale, dwMapFlags, lpSrcStr, cchSrc, lpDestStr, cchDest); } /* Use "A" version */ if (USE_A == f_use || f_use == 0) { int retval = 0; int inbuff_size; int outbuff_size; unsigned char* inbuffer = NULL; unsigned char* outbuffer = NULL; int AnsiCP = 0; /* * Convert string and return the requested information. Note that * we are converting to a multibyte string so there is not a * one-to-one correspondence between number of wide chars in the * input string and the number of *bytes* in the buffer. However, * there had *better be* a one-to-one correspondence between the * number of wide characters and the number of multibyte characters * (enforced by WC_SEPCHARS) in the buffer or the resulting mapped * string will be worthless to the user. * */ /* * Use __lc_codepage for conversion if code_page not specified */ if (0 == Locale) { Locale = plocinfo->locinfo->lc_handle[LC_CTYPE]; } if (0 == code_page) { code_page = plocinfo->locinfo->lc_codepage; } /* * Always use Ansi codepage with Ansi WinAPI because they use * Ansi codepage */ if (code_page != (AnsiCP = __ansicp(Locale))) { if (AnsiCP != -1) { code_page = AnsiCP; } } /* find out how big a buffer we need (includes NULL if any) */ if (0 == (inbuff_size = WideCharToMultiByte(code_page, 0, lpSrcStr, cchSrc, NULL, 0, NULL, NULL))) { return 0; } /* allocate enough space for chars */ inbuffer = (unsigned char*)_calloca(inbuff_size, sizeof(char)); if (inbuffer == NULL) { return 0; } /* do the conversion */ if (0 == WideCharToMultiByte(code_page, 0, lpSrcStr, cchSrc, (char*)inbuffer, inbuff_size, NULL, NULL)) { goto error_cleanup; } /* get size required for string mapping */ if (0 == (outbuff_size = LCMapStringA(Locale, dwMapFlags, (const char*)inbuffer, inbuff_size, NULL, 0))) { goto error_cleanup; } /* allocate enough space for chars and NULL */ outbuffer = (unsigned char*)_calloca(outbuff_size, sizeof(char)); if (outbuffer == NULL) { goto error_cleanup; } /* do string mapping */ if (0 == LCMapStringA(Locale, dwMapFlags, (const char*)inbuffer, inbuff_size, (char*)outbuffer, outbuff_size)) { goto error_cleanup; } if (dwMapFlags & LCMAP_SORTKEY) { /* outbuff_size > cchDest is allowed */ retval = outbuff_size; if (0 != cchDest) /* SORTKEY returns BYTES, just copy */ _ERRCHECK(strncpy_s((char*)lpDestStr, cchDest, (char*)outbuffer, cchDest <= outbuff_size ? cchDest - 1 : outbuff_size)); } else { if (0 == cchDest) { /* get size required */ if (0 == (retval = MultiByteToWideChar(code_page, MB_PRECOMPOSED, (const char*)outbuffer, outbuff_size, NULL, 0))) { goto error_cleanup; } } else { /* convert mapping */ if (0 == (retval = MultiByteToWideChar(code_page, MB_PRECOMPOSED, (const char*)outbuffer, outbuff_size, lpDestStr, cchDest))) { goto error_cleanup; } } } error_cleanup: if (outbuffer != NULL) { _freea(outbuffer); } _freea(inbuffer); return retval; } else { /* f_use is neither USE_A nor USE_W */ return 0; } }
static int __cdecl __crtGetLocaleInfoW_stat( _locale_t plocinfo, LCID Locale, LCTYPE LCType, LPWSTR lpLCData, int cchData, int code_page ) { static int f_use = 0; /* * Look for unstubbed 'preferred' flavor. Otherwise use available flavor. * Must actually call the function to ensure it's not a stub. */ if (0 == f_use) { if (0 != GetLocaleInfoW(0, LOCALE_ILANGUAGE, NULL, 0)) { f_use = USE_W; } else if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED) { f_use = USE_A; } } /* Use "W" version */ if (USE_W == f_use) { return GetLocaleInfoW(Locale, LCType, lpLCData, cchData); } /* Use "A" version */ if (USE_A == f_use || f_use == 0) { int retval = 0; int buff_size; unsigned char* buffer; /* * Use __lc_codepage for conversion if code_page not specified */ if (0 == code_page) { code_page = plocinfo->locinfo->lc_codepage; } /* find out how big buffer needs to be */ if (0 == (buff_size = GetLocaleInfoA(Locale, LCType, NULL, 0))) { return 0; } /* allocate buffer */ buffer = (unsigned char*)_calloca(buff_size, sizeof(char)); if (buffer == NULL) { return 0; } /* get the info in ANSI format */ if (0 == GetLocaleInfoA(Locale, LCType, (char*)buffer, buff_size)) { goto error_cleanup; } if (0 == cchData) { /* find out how much space needed */ retval = MultiByteToWideChar(code_page, MB_PRECOMPOSED, (const char*)buffer, -1, NULL, 0); } else { /* convert into user buffer */ retval = MultiByteToWideChar(code_page, MB_PRECOMPOSED, (const char*)buffer, -1, lpLCData, cchData); } error_cleanup: _freea(buffer); return retval; } else { /* f_use is neither USE_A nor USE_W */ return 0; } }
static errno_t __cdecl _wcslwr_s_l_stat ( wchar_t * wsrc, size_t sizeInWords, _locale_t plocinfo ) { wchar_t *p; /* traverses string for C locale conversion */ wchar_t *wdst; /* wide version of string in alternate case */ int dstsize; /* size in wide chars of wdst string buffer (include null) */ errno_t e = 0; size_t stringlen; /* validation section */ _VALIDATE_RETURN_ERRCODE(wsrc != NULL, EINVAL); stringlen = wcsnlen(wsrc, sizeInWords); if (stringlen >= sizeInWords) { _RESET_STRING(wsrc, sizeInWords); _RETURN_DEST_NOT_NULL_TERMINATED(wsrc, sizeInWords); } _FILL_STRING(wsrc, sizeInWords, stringlen + 1); if ( plocinfo->locinfo->locale_name[LC_CTYPE] == NULL) { for ( p = wsrc ; *p ; p++ ) { if ( (*p >= (wchar_t)L'A') && (*p <= (wchar_t)L'Z') ) { *p -= L'A' - L'a'; } } return 0; } /* C locale */ /* Inquire size of wdst string */ if ( (dstsize = __crtLCMapStringW( plocinfo->locinfo->locale_name[LC_CTYPE], LCMAP_LOWERCASE, wsrc, -1, NULL, 0 )) == 0 ) { errno = EILSEQ; return errno; } if (sizeInWords < (size_t)dstsize) { _RESET_STRING(wsrc, sizeInWords); _RETURN_BUFFER_TOO_SMALL(wsrc, sizeInWords); } /* Allocate space for wdst */ wdst = (wchar_t *)_calloca(dstsize, sizeof(wchar_t)); if (wdst == NULL) { errno = ENOMEM; return errno; } /* Map wrc string to wide-character wdst string in alternate case */ if (__crtLCMapStringW( plocinfo->locinfo->locale_name[LC_CTYPE], LCMAP_LOWERCASE, wsrc, -1, wdst, dstsize ) != 0) { /* Copy wdst string to user string */ e = wcscpy_s(wsrc, sizeInWords, wdst); } else { e = errno = EILSEQ; } _freea(wdst); return e; }
DWORD WINAPI ep_DriverService(void *arg) { const CONFIG_DATA *cd = GetConfigData(); SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST); // Build the threadpool POOL_DATA pd; ZeroMemory(&pd, sizeof(POOL_DATA)); pd.hSharedDriverHandle = g_hDriver; const DWORD dwNumChannels = NUM_EVENTTYPES-1; // -1 to ignore EVENT_NONE THREADPOOL *tp = ThreadPoolAlloc(cd->dThreadPoolSize, dwNumChannels, PfWorkerInit, PfWorkerWork, PfWorkerDestroy, &pd, sizeof(WORKER_DATA), THREAD_PRIORITY_NORMAL); if (!tp) Die("Unable to allocate threadpool"); // Create the read file event for use with overlapped I/O HANDLE hReadFileEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (hReadFileEvent == NULL) Die("Unable to create read file event"); // Allocate memory for the buffer to be read from the kernel PROCFILTER_REQUEST *req = (PROCFILTER_REQUEST*)_malloca(PROCFILTER_REQUEST_SIZE); while (true) { if (WaitForSingleObject(g_hStopTheadEvent, 0) == WAIT_OBJECT_0) break; // Read request from driver using synch/asynch calls according to https://support.microsoft.com/en-us/kb/156932 DWORD dwBytesRead = 0; OVERLAPPED overlapped; ZeroMemory(&overlapped, sizeof(OVERLAPPED)); ResetEvent(hReadFileEvent); overlapped.hEvent = hReadFileEvent; BOOL rc = ReadFile(g_hDriver, req, PROCFILTER_REQUEST_SIZE, &dwBytesRead, &overlapped); DWORD dwErrorCode = GetLastError(); if (rc) { // Successfully completed a synchronous read, do nothing } else if (dwErrorCode == ERROR_IO_PENDING) { // Successfully completed an asynchronous read, so wait for it DWORD dwNumberOfBytesTransferred = 0; if (!GetOverlappedResult(g_hDriver, &overlapped, &dwNumberOfBytesTransferred, TRUE)) { dwErrorCode = GetLastError(); if (dwErrorCode == ERROR_OPERATION_ABORTED || dwErrorCode == ERROR_INVALID_HANDLE) break; // Cancel the pending IO to ensure the IO operation does not complete after this function ends // and the result is stored to an invalid location CancelIo(g_hDriver); Die("GetOverlappedResult() failure in reader: %d", dwErrorCode); } dwErrorCode = GetLastError(); dwBytesRead = dwNumberOfBytesTransferred; } else if (dwErrorCode == ERROR_OPERATION_ABORTED || dwErrorCode == ERROR_INVALID_HANDLE) { break; } else { Die("Unable to read data from driver: %d / %ls", dwErrorCode, ErrorText(dwErrorCode)); } LogDebugFmt("Read event from driver: PID:%u Event:%u", req->dwProcessId, req->dwEventType); ULONG64 ulStartPerformanceCount = GetPerformanceCount(); // Validate the size of data read if (dwBytesRead < sizeof(PROCFILTER_REQUEST) || dwBytesRead > PROCFILTER_REQUEST_SIZE) { Die("Read invalid size from driver device: %u < %u || %u > %u ReadFile:%hs ErrorCode:%d", dwBytesRead, sizeof(PROCFILTER_REQUEST), dwBytesRead, PROCFILTER_REQUEST_SIZE, rc ? "TRUE" : "FALSE", dwErrorCode); } if (dwBytesRead != req->dwRequestSize) { Die("Read partial packet from driver device: Read:%u PacketSize:%u", dwBytesRead, req->dwRequestSize); } // Post a copy of the retrieved data to a worker thread LogDebug("Posting work task to worker"); // Allocate memory for the task data, the structure of which includes only the header portion of the procfilter request, // so allocate only the exact size needed WORKER_TASK_DATA *wtd = (WORKER_TASK_DATA*)malloc(sizeof(WORKER_TASK_DATA) + (dwBytesRead - sizeof(PROCFILTER_REQUEST))); if (!wtd) Die("Memory allocation failure for ProcFilter request"); memcpy(&wtd->peProcFilterRequest, req, dwBytesRead); wtd->ulStartPerformanceCount = ulStartPerformanceCount; LogDebugFmt("Posting to threadpool: PID:%u Event:%u", req->dwProcessId, req->dwEventType); if (ThreadPoolPost(tp, req->dwEventType, false, g_hStopTheadEvent, wtd)) { LogDebug("Posted work task to worker"); } else { LogDebugFmt("Failed to post task to worker"); free(wtd); } } _freea(req); ThreadPoolFree(tp); CloseHandle(hReadFileEvent); // Driver closing is done here since this thread could terminate due to an error situation // and if closing were done elsewhere (such as service exit) the driver device would be kept open, consequently // blocking process creation events until service shutdown CloseHandle(g_hDriver); g_hDriver = INVALID_HANDLE_VALUE; return 0; }
static int glob_add(char *path, int *argc, char ***argv) { char *tail = strchr(path, '*'), *tailqmark; char *dup1, *dup2, *dir, *base, *taildirsep, *tailwldsep; struct dirent *de; int baselen, taillen, dirlen, mergedir = 0, outlen = 0; int qmarklen = 0; DIR *d; if(strlen(path) > 4 && !memcmp(path, "\\\\?\\", 4)) tailqmark = strchr(&path[4], '?'); else tailqmark = strchr(path, '?'); if(tailqmark && (!tail || tailqmark < tail)) tail = tailqmark; if(!tail) { *argv = realloc(*argv, sizeof(**argv) * (*argc + 1)); (*argv)[*argc] = path; (*argc)++; return strlen(path); } if(tail!=path && tail[-1] == '\\') { tail[-1] = '\0'; mergedir = 1; } while(*tail) { if(*tail == '?') { if(tail == tailqmark || qmarklen) qmarklen++; *tail = 0; } else if(*tail == '*') { *tail = '\0'; qmarklen = 0; } else break; tail++; } taillen = strlen(tail); taildirsep = strchr(tail, '\\'); if(taildirsep && taildirsep - tail == taillen - 1) { *taildirsep = '\0'; taildirsep = NULL; taillen--; } if(!taildirsep) taildirsep = tail + taillen; tailwldsep = strchr(tail, '*'); tailqmark = strchr(tail, '?'); if(tailqmark && (!tailwldsep || tailqmark < tailwldsep)) tailwldsep = tailqmark; if(!tailwldsep) tailwldsep = tail + taillen; baselen = strlen(path) + 1; dup1 = (char *)_alloca(baselen * 2); memcpy(dup1, path, baselen); dup2 = dup1 + baselen; memcpy(dup2, path, baselen); if(!mergedir) { dir = dirname(dup1); base = basename(dup2); } else { dir = dup1; base = dup2; *dup2 = '\0'; } dirlen = strlen(dir); baselen = strlen(base); d = opendir(dir); while(d && (de = readdir(d))) { int namelen = strlen(de->d_name); char *newpath; if(!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) continue; if(namelen < baselen) continue; if(strncasecmp(base, de->d_name, baselen)) continue; if(de->d_type == DT_DIR && taildirsep < tailwldsep) { int d_taillen = taildirsep - tail; if(namelen < baselen + d_taillen) continue; if(strncasecmp(tail, &de->d_name[namelen - d_taillen], d_taillen)) continue; newpath = malloc(dirlen + namelen + taillen - d_taillen + 3); sprintf(newpath, "%s\\%s\\%s", dir, de->d_name, &tail[d_taillen+1]); outlen += glob_add(newpath, argc, argv); } else { int d_taillen = tailwldsep - tail; char *start; if(namelen < baselen + d_taillen) continue; if(qmarklen && baselen + qmarklen + d_taillen != namelen) continue; if(d_taillen == taillen) { start = &de->d_name[namelen - d_taillen]; namelen = d_taillen; } else { start = &de->d_name[baselen]; namelen -= baselen; } for(; namelen >= d_taillen; start++, namelen--) { if(strncasecmp(start, tail, d_taillen)) continue; newpath = malloc(dirlen + (start - de->d_name) + taillen + 2); sprintf(newpath, "%s\\", dir); memcpy(&newpath[dirlen + 1], de->d_name, start - de->d_name); strcpy(&newpath[dirlen + 1 + start - de->d_name], tail); outlen += glob_add(newpath, argc, argv); } } } if(d) closedir(d); _freea(dup1); free(path); return outlen; }
static int menubar_set_menu(menubar_t* mb, HMENU menu, BOOL is_refresh) { BYTE* buffer = NULL; TBBUTTON* buttons; TCHAR* labels; int i, n; MENUBAR_TRACE("menubar_set_menu(%p, %p)", mb, menu); if(menu == mb->menu && !is_refresh) return 0; /* If dropped down, cancel it */ if(mb->pressed_item >= 0) { menubar_ht_disable(mb); MENUBAR_SENDMSG(mb->win, WM_CANCELMODE, 0, 0); } /* Uninstall the old menu */ if(mb->menu != NULL) { n = MENUBAR_SENDMSG(mb->win, TB_BUTTONCOUNT, 0, 0); for(i = 0; i < n; i++) MENUBAR_SENDMSG(mb->win, TB_DELETEBUTTON, 0, 0); mb->menu = NULL; } /* Install the new menu */ n = (menu != NULL ? GetMenuItemCount(menu) : 0); if(MC_ERR(n < 0)) { MC_TRACE("menubar_set_menu: GetMenuItemCount() failed."); return -1; } if(n == 0) { mb->menu = menu; return 0; } buffer = (BYTE*) _malloca(n * sizeof(TBBUTTON) + n * sizeof(TCHAR) * MENUBAR_ITEM_LABEL_MAXSIZE); if(MC_ERR(buffer == NULL)) { MC_TRACE("menubar_set_menu: _malloca() failed."); mc_send_notify(mb->notify_win, mb->win, NM_OUTOFMEMORY); return -1; } buttons = (TBBUTTON*) buffer; labels = (TCHAR*) (buffer + n * sizeof(TBBUTTON)); memset(buttons, 0, n * sizeof(TBBUTTON)); for(i = 0; i < n; i++) { UINT state; state = GetMenuState(menu, i, MF_BYPOSITION); buttons[i].iBitmap = I_IMAGENONE; buttons[i].fsState = 0; if(!(state & (MF_DISABLED | MF_GRAYED))) buttons[i].fsState |= TBSTATE_ENABLED; if((state & (MF_MENUBREAK | MF_MENUBARBREAK)) && i > 0) buttons[i-1].fsState |= TBSTATE_WRAP; if(state & MF_POPUP) { TCHAR* label = labels + i * MENUBAR_ITEM_LABEL_MAXSIZE; GetMenuString(menu, i, label, MENUBAR_ITEM_LABEL_MAXSIZE, MF_BYPOSITION); buttons[i].fsStyle = BTNS_AUTOSIZE | BTNS_DROPDOWN | BTNS_SHOWTEXT; buttons[i].dwData = i; buttons[i].iString = (INT_PTR) label; buttons[i].idCommand = i; } else { buttons[i].dwData = 0xffff; buttons[i].idCommand = 0xffff; if(state & MF_SEPARATOR) { buttons[i].fsStyle = BTNS_SEP; buttons[i].iBitmap = MENUBAR_SEPARATOR_WIDTH; } } } MENUBAR_SENDMSG(mb->win, TB_ADDBUTTONS, n, buttons); mb->menu = menu; _freea(buffer); return 0; }
static int __cdecl __crtLCMapStringA_stat( _locale_t plocinfo, LPCWSTR LocaleName, DWORD dwMapFlags, LPCSTR lpSrcStr, int cchSrc, LPSTR lpDestStr, int cchDest, int code_page, BOOL bError ) { /* * LCMapString will map past NULL. Must find NULL if in string * before cchSrc characters. */ if (cchSrc > 0) { int cchSrcCnt = strncnt(lpSrcStr, cchSrc); /* * Include NULL in cchSrc if lpSrcStr terminated within cchSrc bytes. */ if (cchSrcCnt < cchSrc) { cchSrc = cchSrcCnt + 1; } else { cchSrc = cchSrcCnt; } } int retval = 0; int inbuff_size; int outbuff_size; wchar_t *inwbuffer = NULL; wchar_t *outwbuffer = NULL; /* * Convert string and return the requested information. Note that * we are converting to a wide string so there is not a * one-to-one correspondence between number of wide chars in the * input string and the number of *bytes* in the buffer. However, * there had *better be* a one-to-one correspondence between the * number of wide characters and the number of multibyte characters * or the resulting mapped string will be worthless to the user. */ /* * Use __lc_codepage for conversion if code_page not specified */ if (0 == code_page) code_page = plocinfo->locinfo->lc_codepage; /* find out how big a buffer we need (includes NULL if any) */ if ( 0 == (inbuff_size = MultiByteToWideChar( code_page, bError ? MB_PRECOMPOSED | MB_ERR_INVALID_CHARS : MB_PRECOMPOSED, lpSrcStr, cchSrc, NULL, 0 )) ) return 0; /* allocate enough space for wide chars */ inwbuffer = (wchar_t *)_calloca( inbuff_size, sizeof(wchar_t) ); if ( inwbuffer == NULL ) { return 0; } /* do the conversion */ if ( 0 == MultiByteToWideChar( code_page, MB_PRECOMPOSED, lpSrcStr, cchSrc, inwbuffer, inbuff_size) ) goto error_cleanup; /* get size required for string mapping */ if ( 0 == (retval = __crtLCMapStringEx( LocaleName, dwMapFlags, inwbuffer, inbuff_size, NULL, 0)) ) goto error_cleanup; if (dwMapFlags & LCMAP_SORTKEY) { /* retval is size in BYTES */ if (0 != cchDest) { if (retval > cchDest) goto error_cleanup; /* do string mapping */ if ( 0 == __crtLCMapStringEx( LocaleName, dwMapFlags, inwbuffer, inbuff_size, (LPWSTR)lpDestStr, cchDest) ) goto error_cleanup; } } else { /* retval is size in wide chars */ outbuff_size = retval; /* allocate enough space for wide chars (includes NULL if any) */ outwbuffer = (wchar_t *)_calloca( outbuff_size, sizeof(wchar_t) ); if ( outwbuffer == NULL ) { goto error_cleanup; } /* do string mapping */ if ( 0 == __crtLCMapStringEx( LocaleName, dwMapFlags, inwbuffer, inbuff_size, outwbuffer, outbuff_size) ) goto error_cleanup; if (0 == cchDest) { /* get size required */ if ( 0 == (retval = WideCharToMultiByte( code_page, 0, outwbuffer, outbuff_size, NULL, 0, NULL, NULL )) ) goto error_cleanup; } else { /* convert mapping */ if ( 0 == (retval = WideCharToMultiByte( code_page, 0, outwbuffer, outbuff_size, lpDestStr, cchDest, NULL, NULL )) ) goto error_cleanup; } } error_cleanup: if ( outwbuffer != NULL ) _freea(outwbuffer); _freea(inwbuffer); return retval; }
HRESULT VisualizeFaceModel(IFTImage* pColorImg, IFTModel* pModel, FT_CAMERA_CONFIG const* pCameraConfig, FLOAT const* pSUCoef, FLOAT zoomFactor, POINT viewOffset, IFTResult* pAAMRlt, UINT32 color) { if (!pColorImg || !pModel || !pCameraConfig || !pSUCoef || !pAAMRlt) { return E_POINTER; } HRESULT hr = S_OK; UINT vertexCount = pModel->GetVertexCount(); FT_VECTOR2D* pPts2D = reinterpret_cast<FT_VECTOR2D*>(_malloca(sizeof(FT_VECTOR2D) * vertexCount)); if (pPts2D) { FLOAT *pAUs; UINT auCount; hr = pAAMRlt->GetAUCoefficients(&pAUs, &auCount); if (SUCCEEDED(hr)) { FLOAT scale, rotationXYZ[3], translationXYZ[3]; hr = pAAMRlt->Get3DPose(&scale, rotationXYZ, translationXYZ); if (SUCCEEDED(hr)) { hr = pModel->GetProjectedShape(pCameraConfig, zoomFactor, viewOffset, pSUCoef, pModel->GetSUCount(), pAUs, auCount, scale, rotationXYZ, translationXYZ, pPts2D, vertexCount); if (SUCCEEDED(hr)) { POINT* p3DMdl = reinterpret_cast<POINT*>(_malloca(sizeof(POINT) * vertexCount)); if (p3DMdl) { for (UINT i = 0; i < vertexCount; ++i) { p3DMdl[i].x = LONG(pPts2D[i].x + 0.5f); p3DMdl[i].y = LONG(pPts2D[i].y + 0.5f); } FT_TRIANGLE* pTriangles; UINT triangleCount; hr = pModel->GetTriangles(&pTriangles, &triangleCount); if (SUCCEEDED(hr)) { struct EdgeHashTable { UINT32* pEdges; UINT edgesAlloc; void Insert(int a, int b) { UINT32 v = (min(a, b) << 16) | max(a, b); UINT32 index = (v + (v << 8)) * 49157, i; for (i = 0; i < edgesAlloc - 1 && pEdges[(index + i) & (edgesAlloc - 1)] && v != pEdges[(index + i) & (edgesAlloc - 1)]; ++i) { } pEdges[(index + i) & (edgesAlloc - 1)] = v; } } eht; eht.edgesAlloc = 1 << UINT(log(2.f * (1 + vertexCount + triangleCount)) / log(2.f)); eht.pEdges = reinterpret_cast<UINT32*>(_malloca(sizeof(UINT32) * eht.edgesAlloc)); if (eht.pEdges) { ZeroMemory(eht.pEdges, sizeof(UINT32) * eht.edgesAlloc); for (UINT i = 0; i < triangleCount; ++i) { eht.Insert(pTriangles[i].i, pTriangles[i].j); eht.Insert(pTriangles[i].j, pTriangles[i].k); eht.Insert(pTriangles[i].k, pTriangles[i].i); } for (UINT i = 0; i < eht.edgesAlloc; ++i) { if(eht.pEdges[i] != 0) { pColorImg->DrawLine(p3DMdl[eht.pEdges[i] >> 16], p3DMdl[eht.pEdges[i] & 0xFFFF], color, 1); } } _freea(eht.pEdges); } // Render the face rect in magenta RECT rectFace; hr = pAAMRlt->GetFaceRect(&rectFace); if (SUCCEEDED(hr)) { POINT leftTop = {rectFace.left, rectFace.top}; POINT rightTop = {rectFace.right - 1, rectFace.top}; POINT leftBottom = {rectFace.left, rectFace.bottom - 1}; POINT rightBottom = {rectFace.right - 1, rectFace.bottom - 1}; UINT32 nColor = 0xff00ff; SUCCEEDED(hr = pColorImg->DrawLine(leftTop, rightTop, nColor, 1)) && SUCCEEDED(hr = pColorImg->DrawLine(rightTop, rightBottom, nColor, 1)) && SUCCEEDED(hr = pColorImg->DrawLine(rightBottom, leftBottom, nColor, 1)) && SUCCEEDED(hr = pColorImg->DrawLine(leftBottom, leftTop, nColor, 1)); } } _freea(p3DMdl); } else { hr = E_OUTOFMEMORY; } } }
// // Perform the scanning as specified in the various input parameters // void Scan(DWORD dwEventType, int dScanContext, PROCFILTER_EVENT *e, YARASCAN_CONTEXT *ctx, HANDLE hDriver, HANDLE hWriteCompletionEvent, DWORD dwProcessId, DWORD dwParentProcessId, WCHAR *lpszFileName, void *lpImageBase, void *lpvScanDataArray) { if (!lpszFileName) return; LONG64 llStart = GetPerformanceCount(); CONFIG_DATA *cd = GetConfigData(); bool bScanFile = false; bool bScanMemory = false; bool bBlock = false; bool bLog = false; bool bQuarantine = false; // Pull the scan parameters out of config if (dScanContext == PROCFILTER_SCAN_CONTEXT_PROCESS_CREATE) { bScanFile = cd->bScanFileOnProcessCreate; bScanMemory = cd->bScanMemoryOnProcessCreate; } else if (dScanContext == PROCFILTER_SCAN_CONTEXT_PROCESS_TERMINATE) { bScanFile = cd->bScanFileOnProcessTerminate; bScanMemory = cd->bScanMemoryOnProcessTerminate; } else if (dScanContext == PROCFILTER_SCAN_CONTEXT_PERIODIC_SCAN) { bScanFile = cd->bScanFileOnPeriodic; bScanMemory = cd->bScanMemoryOnPeriodic; } else if (dScanContext == PROCFILTER_SCAN_CONTEXT_IMAGE_LOAD) { bScanFile = cd->bScanFileOnImageLoad; bScanMemory = cd->bScanMemoryOnImageLoad; } else { Die("Invalid context passed to Scan(): %d", dScanContext); } // Initialize the API event with the passed-in parameters ApiEventReinit(e, PROCFILTER_EVENT_YARA_SCAN_INIT); e->dwProcessId = dwProcessId; e->dwParentProcessId = dwParentProcessId; e->lpszFileName = lpszFileName; e->dScanContext = dScanContext; e->bScanFile = bScanFile; e->bScanMemory = bScanMemory; e->lpvScanData = lpvScanDataArray; // Export the event to the API and handle the result flags DWORD dwPluginResultFlags = ApiEventExport(e); if (dwPluginResultFlags & PROCFILTER_RESULT_BLOCK_PROCESS) bBlock = true; if (dwPluginResultFlags & PROCFILTER_RESULT_DONT_SCAN_MEMORY) bScanMemory = false; if (dwPluginResultFlags & PROCFILTER_RESULT_FORCE_SCAN_MEMORY) bScanMemory = true; if (dwPluginResultFlags & PROCFILTER_RESULT_DONT_SCAN_FILE) bScanFile = false; if (dwPluginResultFlags & PROCFILTER_RESULT_FORCE_SCAN_FILE) bScanFile = true; if (dwPluginResultFlags & PROCFILTER_RESULT_QUARANTINE) bQuarantine = true; // Scan the file if requested SCAN_RESULT srFileResult; ZeroMemory(&srFileResult, sizeof(SCAN_RESULT)); if (bScanFile) { CALLBACK_USER_DATA cud = { e, dwProcessId, lpszFileName, lpvScanDataArray, dScanContext, PROCFILTER_MATCH_FILE }; YarascanScanFile(ctx, lpszFileName, cd->dwScanFileSizeLimit, OnMatchCallback, OnMetaCallback, &cud, &srFileResult); if (srFileResult.bScanSuccessful) { bBlock |= srFileResult.bBlock; bLog |= srFileResult.bLog; bQuarantine |= srFileResult.bQuarantine; } else { EventWriteSCAN_FILE_FAILED(dwProcessId, lpszFileName, srFileResult.szError); } } // Scan the memory if requested SCAN_RESULT srMemoryResult; ZeroMemory(&srMemoryResult, sizeof(SCAN_RESULT)); if (bScanMemory) { CALLBACK_USER_DATA cud = { e, dwProcessId, lpszFileName, lpvScanDataArray, dScanContext, PROCFILTER_MATCH_MEMORY }; YarascanScanMemory(ctx, dwProcessId, OnMatchCallback, OnMetaCallback, &cud, &srMemoryResult); if (srMemoryResult.bScanSuccessful) { bBlock |= srMemoryResult.bBlock; bLog |= srMemoryResult.bLog; bQuarantine |= srMemoryResult.bQuarantine; } else { EventWriteSCAN_PROCESS_FAILED(dwProcessId, lpszFileName, srMemoryResult.szError); } } // Export the scan results to plugins ApiEventReinit(e, PROCFILTER_EVENT_YARA_SCAN_COMPLETE); e->dwProcessId = dwProcessId; e->dwParentProcessId = dwParentProcessId; e->lpszFileName = lpszFileName; e->dScanContext = dScanContext; e->srFileResult = bScanFile ? &srFileResult : NULL; e->srMemoryResult = bScanMemory ? &srMemoryResult : NULL; e->bBlockProcess = bBlock; e->lpvScanData = lpvScanDataArray; dwPluginResultFlags = ApiEventExport(e); if (dwPluginResultFlags & PROCFILTER_RESULT_BLOCK_PROCESS) bBlock = true; if (dwPluginResultFlags & PROCFILTER_RESULT_QUARANTINE) bQuarantine = true; WCHAR *szFileQuarantineRuleNames = bScanFile && srFileResult.bScanSuccessful ? srFileResult.szQuarantineRuleNames : NULL; WCHAR *szMemoryQuarantineRuleNames = bScanMemory && srMemoryResult.bScanSuccessful ? srMemoryResult.szQuarantineRuleNames : NULL; // Quarantine here if (bQuarantine) { char hexdigest[SHA1_HEXDIGEST_LENGTH+1] = { '\0' }; if (QuarantineFile(lpszFileName, cd->szQuarantineDirectory, cd->dwQuarantineFileSizeLimit, szFileQuarantineRuleNames, szMemoryQuarantineRuleNames, hexdigest)) { EventWriteFILE_QUARANTINED(dwProcessId, lpszFileName, hexdigest, (bScanFile && srFileResult.bScanSuccessful) ? srFileResult.szQuarantineRuleNames : NULL, (bScanMemory && srMemoryResult.bScanSuccessful) ? srMemoryResult.szQuarantineRuleNames : NULL); } } // Write the result back to the kernel driver, which releases the process bool bProcessBlocked = false; if (dScanContext == PROCFILTER_SCAN_CONTEXT_PROCESS_CREATE || dScanContext == PROCFILTER_SCAN_CONTEXT_PROCESS_TERMINATE) { PROCFILTER_RESPONSE response; ZeroMemory(&response, sizeof(PROCFILTER_RESPONSE)); response.dwEventType = dwEventType; response.dwProcessId = dwProcessId; // Block the process according to configuration if (dScanContext == PROCFILTER_SCAN_CONTEXT_PROCESS_CREATE) { if (cd->bDenyProcessCreationOnFailedScan) { if (bScanFile && !srFileResult.bScanSuccessful) bBlock = true; if (bScanMemory && !srMemoryResult.bScanSuccessful) bBlock = true; } if (bBlock) { response.bBlock = true; } } if (DriverSendResponse(hDriver, hWriteCompletionEvent, &response)) { if (dScanContext == PROCFILTER_SCAN_CONTEXT_PROCESS_CREATE) bProcessBlocked = true; } } else if (dScanContext == PROCFILTER_SCAN_CONTEXT_IMAGE_LOAD) { PROCFILTER_RESPONSE response; ZeroMemory(&response, sizeof(PROCFILTER_RESPONSE)); response.dwEventType = dwEventType; response.dwProcessId = dwProcessId; response.lpImageBase = lpImageBase; DriverSendResponse(hDriver, hWriteCompletionEvent, &response); } // Log to event log based on what was sent to the kernel (excluding the quarantining) WCHAR *szFileLogRuleNames = bScanFile && srFileResult.bScanSuccessful ? srFileResult.szLogRuleNames : NULL; WCHAR *szFileBlockRuleNames = bScanFile && srFileResult.bScanSuccessful ? srFileResult.szBlockRuleNames : NULL; WCHAR *szFileMatchRuleNames = bScanFile && srFileResult.bScanSuccessful ? srFileResult.szMatchedRuleNames : NULL; WCHAR *szMemoryLogRuleNames = bScanMemory && srMemoryResult.bScanSuccessful ? srMemoryResult.szLogRuleNames : NULL; WCHAR *szMemoryBlockRuleNames = bScanMemory && srMemoryResult.bScanSuccessful ? srMemoryResult.szBlockRuleNames : NULL; WCHAR *szMemoryMatchRuleNames = bScanMemory && srMemoryResult.bScanSuccessful ? srMemoryResult.szMatchedRuleNames : NULL; // Log the actions taken according to which events happened if (dScanContext == PROCFILTER_SCAN_CONTEXT_PROCESS_CREATE) { if (bLog) EventWriteEXECUTION_LOGGED(dwProcessId, lpszFileName, szFileLogRuleNames, szMemoryLogRuleNames); if (bBlock) EventWriteEXECUTION_BLOCKED(dwProcessId, lpszFileName, szFileBlockRuleNames, szMemoryBlockRuleNames); } else if (dScanContext == PROCFILTER_SCAN_CONTEXT_PROCESS_TERMINATE) { if (bLog) EventWriteEXITING_PROCESS_SCAN_MATCHED_LOGGED_RULE(dwProcessId, lpszFileName, szFileLogRuleNames, szMemoryLogRuleNames); if (bBlock) EventWriteEXITING_PROCESS_SCAN_MATCHED_BLOCKED_RULE(dwProcessId, lpszFileName, szFileBlockRuleNames, szMemoryBlockRuleNames); } else if (dScanContext == PROCFILTER_SCAN_CONTEXT_PERIODIC_SCAN) { if (bLog) EventWriteRUNNING_PROCESS_MATCHED_LOGGED_RULE(dwProcessId, lpszFileName, szFileLogRuleNames, szMemoryLogRuleNames); if (bBlock) { EventWriteRUNNING_PROCESS_MATCHED_BLOCKED_RULE(dwProcessId, lpszFileName, szFileBlockRuleNames, szMemoryBlockRuleNames); if (TerminateProcessByPid(dwProcessId, true, lpszFileName, szFileBlockRuleNames, szMemoryBlockRuleNames)) { bProcessBlocked = true; } } } else if (dScanContext == PROCFILTER_SCAN_CONTEXT_IMAGE_LOAD) { if (bLog || bBlock) { WCHAR *lpszImageLoaderProcessName = NULL; DWORD dwImageLoaderProcessNameSize = sizeof(WCHAR) * (MAX_PATH+1); HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, dwProcessId); if (hProcess) { lpszImageLoaderProcessName = (WCHAR*)_malloca(dwImageLoaderProcessNameSize); if (!QueryFullProcessImageNameW(hProcess, PROCESS_NAME_NATIVE, lpszImageLoaderProcessName, &dwImageLoaderProcessNameSize)) { _freea(lpszImageLoaderProcessName); lpszImageLoaderProcessName = NULL; } CloseHandle(hProcess); } if (bLog) EventWriteLOADED_IMAGE_LOGGED(dwProcessId, lpszImageLoaderProcessName, lpszFileName, szFileLogRuleNames, szMemoryLogRuleNames); if (bBlock) { EventWriteLOADED_IMAGE_BLOCKED(dwProcessId, lpszImageLoaderProcessName, lpszFileName, szFileBlockRuleNames, szMemoryBlockRuleNames); if (TerminateProcessByPid(dwProcessId, true, lpszFileName, szFileBlockRuleNames, szMemoryBlockRuleNames)) { bProcessBlocked = true; } } if (lpszImageLoaderProcessName) _freea(lpszImageLoaderProcessName); } } // Export post-scan notice to plugins ApiEventReinit(e, PROCFILTER_EVENT_YARA_SCAN_CLEANUP); e->dwProcessId = dwProcessId; e->dwParentProcessId = dwParentProcessId; e->lpszFileName = lpszFileName; e->dScanContext = dScanContext; e->srFileResult = bScanFile ? &srFileResult : NULL; e->srMemoryResult = bScanMemory ? &srMemoryResult : NULL; e->bBlockProcess = bBlock; e->bProcessBlocked = bProcessBlocked; e->lpvScanData = lpvScanDataArray; ApiEventExport(e); // Performance data update LONG64 llDuration = GetPerformanceCount() - llStart; MmaUpdate(&g_Stats[dScanContext].mma, llDuration); MmaUpdate(&g_Stats[PROCFILTER_NUM_CONTEXTS].mma, llDuration); }
void CInsertControlDlg::RefreshControlList() { BOOL tDone; HRESULT hResult; IEnumGUIDPtr pEnum; ULONG nImplementedCategories; CATID* pcatidImpl; ULONG nRequiredCategories; CATID* pcatidReq; CLSID clsid; LPOLESTR pszName; CString strName; ULONG iCategory; int iItem; POSITION posControl; CString strServerPath; CString strString; m_lbControls.ResetContent(); m_lControls.RemoveAll(); nImplementedCategories = (ULONG)m_aImplementedCategories.GetSize(); if( nImplementedCategories == 0 ) { nImplementedCategories = ULONG( -1 ); pcatidImpl = NULL; } else { pcatidImpl = (CATID*)_malloca( nImplementedCategories*sizeof( CATID ) ); for( iCategory = 0; iCategory < nImplementedCategories; iCategory++ ) { pcatidImpl[iCategory] = m_aImplementedCategories[iCategory]; } } if( m_butIgnoreRequiredCategories.GetCheck() ) { nRequiredCategories = ULONG( -1 ); pcatidReq = NULL; } else { nRequiredCategories = (ULONG)m_aRequiredCategories.GetSize(); if( nRequiredCategories == 0 ) { pcatidReq = NULL; } else { pcatidReq = (CATID*)_malloca( nRequiredCategories*sizeof( CATID ) ); for( iCategory = 0; iCategory < nRequiredCategories; iCategory++ ) { pcatidReq[iCategory] = m_aRequiredCategories[iCategory]; } } } hResult = m_pCatInfo->EnumClassesOfCategories( nImplementedCategories, pcatidImpl, nRequiredCategories, pcatidReq, &pEnum ); _freea(pcatidImpl); _freea(pcatidReq); if( FAILED( hResult ) ) { return; } tDone = FALSE; int nExtent = 0; TEXTMETRIC tm; ::ZeroMemory(&tm, sizeof(TEXTMETRIC)); CFont *pFont = NULL; CFont *pOldFont = NULL; CDC *pDC = m_lbControls.GetDC(); ASSERT(pDC); if (pDC) { pFont = m_lbControls.GetFont(); ASSERT(pFont); if (pFont) { pOldFont = pDC->SelectObject(pFont); VERIFY(pDC->GetTextMetrics(&tm)); } } while( !tDone ) { hResult = pEnum->Next( 1, &clsid, NULL ); if( hResult == S_OK ) { pszName = NULL; hResult = OleRegGetUserType( clsid, USERCLASSTYPE_FULL, &pszName ); if( SUCCEEDED( hResult ) ) { strName = pszName; CoTaskMemFree( pszName ); pszName = NULL; if (pDC && pFont) { CSize sz = pDC->GetTextExtent(strName); if (sz.cx > nExtent) nExtent = sz.cx; } iItem = m_lbControls.AddString( strName ); posControl = m_lControls.AddTail( clsid ); m_lbControls.SetItemDataPtr( iItem, posControl ); } } else { tDone = TRUE; } } if (pDC && pFont) { pDC->SelectObject(pOldFont); m_lbControls.SetHorizontalExtent(nExtent + tm.tmAveCharWidth); } OnControlsSelChange(); }
bool RunningAsAdministrator () { BOOL fAdmin; TOKEN_GROUPS *ptg = NULL; DWORD cbTokenGroups; DWORD dwGroup; PSID psidAdmin; SetLastError(0); HANDLE process=0; HANDLE Token=NULL; if (GetCurrentUserToken(process, Token)==1) return true; ON_BLOCK_EXIT(CloseHandle, process); ON_BLOCK_EXIT(CloseHandle, Token); SID_IDENTIFIER_AUTHORITY SystemSidAuthority= SECURITY_NT_AUTHORITY; // Then we must query the size of the group information associated with // the token. Note that we expect a FALSE result from GetTokenInformation // because we've given it a NULL buffer. On exit cbTokenGroups will tell // the size of the group information. if ( GetTokenInformation ( Token, TokenGroups, NULL, 0, &cbTokenGroups)) return ( FALSE); // Here we verify that GetTokenInformation failed for lack of a large // enough buffer. DWORD aa=GetLastError(); if ( aa != ERROR_INSUFFICIENT_BUFFER) return ( FALSE); // Now we allocate a buffer for the group information. // Since _alloca allocates on the stack, we don't have // to explicitly deallocate it. That happens automatically // when we exit this function. if ( ! ( ptg= (_TOKEN_GROUPS *) _malloca ( cbTokenGroups))) return ( FALSE); // Now we ask for the group information again. // This may fail if an administrator has added this account // to an additional group between our first call to // GetTokenInformation and this one. if (!GetTokenInformation(Token, TokenGroups, ptg, cbTokenGroups, &cbTokenGroups)) { _freea(ptg); return (FALSE); } // Now we must create a System Identifier for the Admin group. if (!AllocateAndInitializeSid(&SystemSidAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &psidAdmin)) { _freea(ptg); return (FALSE); } // Finally we'll iterate through the list of groups for this access // token looking for a match against the SID we created above. fAdmin= FALSE; for ( dwGroup= 0; dwGroup < ptg->GroupCount; dwGroup++) { if ( EqualSid ( ptg->Groups[dwGroup].Sid, psidAdmin)) { fAdmin = TRUE; break; } } // Before we exit we must explicity deallocate the SID we created. _freea(ptg); FreeSid ( psidAdmin); return (FALSE != fAdmin); }
HRESULT VisualizeFacetracker(IFTImage* pColorImg, IFTResult* pAAMRlt, UINT32 color) { if (!pColorImg->GetBuffer() || !pAAMRlt) { return E_POINTER; } // Insufficient data points to render face data FT_VECTOR2D* pPts2D; UINT pts2DCount; HRESULT hr = pAAMRlt->Get2DShapePoints(&pPts2D, &pts2DCount); if (FAILED(hr)) { return hr; } if (pts2DCount < 86) { return E_INVALIDARG; } POINT* pFaceModel2DPoint = reinterpret_cast<POINT*>(_malloca(sizeof(POINT) * pts2DCount)); if (!pFaceModel2DPoint) { return E_OUTOFMEMORY; } for (UINT ipt = 0; ipt < pts2DCount; ++ipt) { pFaceModel2DPoint[ipt].x = LONG(pPts2D[ipt].x + 0.5f); pFaceModel2DPoint[ipt].y = LONG(pPts2D[ipt].y + 0.5f); } for (UINT ipt = 0; ipt < 8; ++ipt) { POINT ptStart = pFaceModel2DPoint[ipt]; POINT ptEnd = pFaceModel2DPoint[(ipt+1)%8]; pColorImg->DrawLine(ptStart, ptEnd, color, 1); } for (UINT ipt = 8; ipt < 16; ++ipt) { POINT ptStart = pFaceModel2DPoint[ipt]; POINT ptEnd = pFaceModel2DPoint[(ipt-8+1)%8+8]; pColorImg->DrawLine(ptStart, ptEnd, color, 1); } for (UINT ipt = 16; ipt < 26; ++ipt) { POINT ptStart = pFaceModel2DPoint[ipt]; POINT ptEnd = pFaceModel2DPoint[(ipt-16+1)%10+16]; pColorImg->DrawLine(ptStart, ptEnd, color, 1); } for (UINT ipt = 26; ipt < 36; ++ipt) { POINT ptStart = pFaceModel2DPoint[ipt]; POINT ptEnd = pFaceModel2DPoint[(ipt-26+1)%10+26]; pColorImg->DrawLine(ptStart, ptEnd, color, 1); } for (UINT ipt = 36; ipt < 47; ++ipt) { POINT ptStart = pFaceModel2DPoint[ipt]; POINT ptEnd = pFaceModel2DPoint[ipt+1]; pColorImg->DrawLine(ptStart, ptEnd, color, 1); } for (UINT ipt = 48; ipt < 60; ++ipt) { POINT ptStart = pFaceModel2DPoint[ipt]; POINT ptEnd = pFaceModel2DPoint[(ipt-48+1)%12+48]; pColorImg->DrawLine(ptStart, ptEnd, color, 1); } for (UINT ipt = 60; ipt < 68; ++ipt) { POINT ptStart = pFaceModel2DPoint[ipt]; POINT ptEnd = pFaceModel2DPoint[(ipt-60+1)%8+60]; pColorImg->DrawLine(ptStart, ptEnd, color, 1); } for (UINT ipt = 68; ipt < 86; ++ipt) { POINT ptStart = pFaceModel2DPoint[ipt]; POINT ptEnd = pFaceModel2DPoint[ipt+1]; pColorImg->DrawLine(ptStart, ptEnd, color, 1); } _freea(pFaceModel2DPoint); return hr; }
// // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; int bufferSize=BUFFER_SIZE; TCHAR *inBuffer = (TCHAR *) _malloca (sizeof(TCHAR)*BUFFER_SIZE); RECT cRect = { 0 }; int userLength=100; clientStruct *tmpClient=&client; switch (message) { case WM_LBUTTONDOWN: { ShowWindow(userWin,SW_HIDE); } break; case WM_SIZE: { GetClientRect(hWnd,&cRect); // Get windows dimmensions if changed cRect.bottom-=50; SetWindowPos(chatWin,NULL,cRect.left,cRect.top,cRect.right,cRect.bottom,SWP_NOZORDER); // Resize all the windows` cRect.right-=50; SetWindowPos(inputWin,NULL,0,cRect.bottom,cRect.right,40,SWP_NOZORDER); SetWindowPos(sendBTN,NULL,cRect.right, cRect.bottom, 50, 40,SWP_NOZORDER); } break; case WM_CREATE: { RECT Rect, rChat; GetClientRect(hWnd,&Rect); // Get client window dimmensions rChat = Rect; rChat.left=0; rChat.top=0; rChat.bottom -=20; chatWin = CreateWindow( TEXT("LISTBOX"), NULL, WS_CHILD , rChat.left,rChat.top, rChat.right,rChat.bottom+5, hWnd, NULL, hInst, NULL); inputWin=CreateWindow( TEXT("EDIT"), NULL, WS_CHILD|ES_LEFT|ES_AUTOHSCROLL, 0,rChat.bottom, rChat.right-35,40, hWnd, HMENU(IDE_SEND_TEXT), hInst, NULL); sendBTN=CreateWindow( TEXT("BUTTON"), TEXT("Send"), WS_CHILD|ES_LEFT|WS_BORDER, rChat.right-50,rChat.bottom, 35,40, hWnd, HMENU(IDB_SEND_TEXT), hInst, NULL); EnableWindow(inputWin,FALSE); userWin = CreateWindow ( TEXT("LISTBOX"), TEXT("Users Online"), WS_CHILD|ES_LEFT|ES_AUTOHSCROLL, 200,0,200,500, hWnd, HMENU(IDC_LIST_USER), hInst, NULL); } break; case WM_CLIENT_SOCKET: { int wmEvent=WSAGETSELECTEVENT(lParam); int wmError=WSAGETSELECTERROR(lParam); switch(wmEvent) { case FD_CONNECT: { if(wmError!=NULL) DisplayError(NULL,TEXT("Connection Error"),wmError,ALL,ERRORFOUND); else { EnableWindow(GetDlgItem(hWnd,IDB_SEND_TEXT),TRUE); } } break; case FD_READ: { if(wmError!=NULL) DisplayError(NULL,TEXT("Read Error"),wmError,ALL,ERRORFOUND); ClientIncoming(toServer.inSocket,&client); } break; } } case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_LISTUSERS: { //DisplayUsers(userWin); } break; case IDB_SEND_TEXT: { _tcscpy(client.sendTo,_T("PUBLIC")); SendText(inputWin,toServer.inSocket,&client); SendMessage(userWin, LB_ADDSTRING, 0, (LPARAM)client.sendMSG); SendMessage(inputWin,WM_SETTEXT,256,(LPARAM)""); } break; case IDM_NICKNAME: DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_NICKNAME), hWnd, ChangeNickName,(LPARAM)tmpClient); break; case IDM_CONNECT: { if(toServer.isConnected) break; ConnectToServer(hWnd,&toServer,client); if(toServer.isConnected) { ShowWindow(chatWin,SW_SHOW); ShowWindow(inputWin,SW_SHOW); ShowWindow(sendBTN,SW_SHOW); EnableWindow(inputWin, TRUE); } } break; case IDM_DISCONNECT: { if(!toServer.isConnected) break; ShutDown(toServer.inSocket); ShowWindow(chatWin,SW_HIDE); ShowWindow(inputWin,SW_HIDE); ShowWindow(sendBTN,SW_HIDE); EnableWindow(inputWin, FALSE); toServer.isConnected=FALSE; } break; case IDM_LIST_SERVERS: DialogBox(hInst, MAKEINTRESOURCE(IDD_LIST_SERVERS), hWnd, ListtoServers); break; case IDM_SETTINGS: { //if(!toServer.isConnected) // ZeroMemory(&client,sizeof(client)); DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_SETTINGS), hWnd, Settings,(LPARAM)&toServer); } break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: { hdc = BeginPaint(hWnd, &ps); EndPaint(hWnd, &ps); } break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } client=(*tmpClient); _freea(inBuffer); return 0; }
static void fft(unsigned int n, bool inverse, const double *ri, const double *ii, double *ro, double *io) { if (!ri || !ro || !io) return; unsigned int bits; unsigned int i, j, k, m; unsigned int blockSize, blockEnd; double tr, ti; if (n < 2) return; if (n & (n-1)) return; double angle = 2.0 * M_PI; if (inverse) angle = -angle; for (i = 0; ; ++i) { if (n & (1 << i)) { bits = i; break; } } #ifdef _MSC_VER int *table = (int *)_malloca(n * sizeof(int)); #else int table[n]; #endif for (i = 0; i < n; ++i) { m = i; for (j = k = 0; j < bits; ++j) { k = (k << 1) | (m & 1); m >>= 1; } table[i] = k; } if (ii) { for (i = 0; i < n; ++i) { ro[table[i]] = ri[i]; io[table[i]] = ii[i]; } } else { for (i = 0; i < n; ++i) { ro[table[i]] = ri[i]; io[table[i]] = 0.0; } } blockEnd = 1; for (blockSize = 2; blockSize <= n; blockSize <<= 1) { double delta = angle / (double)blockSize; double sm2 = -sin(-2 * delta); double sm1 = -sin(-delta); double cm2 = cos(-2 * delta); double cm1 = cos(-delta); double w = 2 * cm1; double ar[3], ai[3]; for (i = 0; i < n; i += blockSize) { ar[2] = cm2; ar[1] = cm1; ai[2] = sm2; ai[1] = sm1; for (j = i, m = 0; m < blockEnd; j++, m++) { ar[0] = w * ar[1] - ar[2]; ar[2] = ar[1]; ar[1] = ar[0]; ai[0] = w * ai[1] - ai[2]; ai[2] = ai[1]; ai[1] = ai[0]; k = j + blockEnd; tr = ar[0] * ro[k] - ai[0] * io[k]; ti = ar[0] * io[k] + ai[0] * ro[k]; ro[k] = ro[j] - tr; io[k] = io[j] - ti; ro[j] += tr; io[j] += ti; } } blockEnd = blockSize; } if (inverse) { double denom = (double)n; for (i = 0; i < n; i++) { ro[i] /= denom; io[i] /= denom; } } #ifdef _MSC_VER _freea(table); #endif }
static BOOL __cdecl __crtGetStringTypeA_stat( _locale_t plocinfo, DWORD dwInfoType, LPCSTR lpSrcStr, int cchSrc, LPWORD lpCharType, int code_page, int lcid, BOOL bError ) { static int f_use = 0; /* * Look for unstubbed 'preferred' flavor. Otherwise use available * flavor. Must actually call the function to ensure it's not a stub. * (Always try wide version first so WinNT can process codepage correctly.) */ if (0 == f_use) { unsigned short dummy; if (0 != GetStringTypeW(CT_CTYPE1, L"\0", 1, &dummy)) f_use = USE_W; else if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED) f_use = USE_A; } /* Use "A" version */ if (USE_A == f_use || f_use == 0) { char *cbuffer = NULL; int ret; int AnsiCP; if (0 == lcid) lcid = plocinfo->locinfo->lc_handle[LC_CTYPE]; if (0 == code_page) code_page = plocinfo->locinfo->lc_codepage; if ( -1 == (AnsiCP = __ansicp(lcid))) return FALSE; /* If current code-page is not ansi code page, convert it to ansi code page * as GetStringTypeA uses ansi code page to find the strig type. */ if ( AnsiCP != code_page) { cbuffer = __convertcp(code_page, AnsiCP, lpSrcStr, &cchSrc, NULL, 0); if (cbuffer == NULL) return FALSE; lpSrcStr = cbuffer; } ret = GetStringTypeA(lcid, dwInfoType, lpSrcStr, cchSrc, lpCharType); if ( cbuffer != NULL) _free_crt(cbuffer); return ret; } /* Use "W" version */ if (USE_W == f_use) { int retval1; int buff_size; wchar_t *wbuffer; BOOL retval2 = FALSE; /* * Convert string and return the requested information. Note that * we are converting to a wide character string so there is not a * one-to-one correspondence between number of multibyte chars in the * input string and the number of wide chars in the buffer. However, * there had *better be* a one-to-one correspondence between the * number of multibyte characters and the number of WORDs in the * return buffer. */ /* * Use __lc_codepage for conversion if code_page not specified */ if (0 == code_page) code_page = plocinfo->locinfo->lc_codepage; /* find out how big a buffer we need */ if ( 0 == (buff_size = MultiByteToWideChar( code_page, bError ? MB_PRECOMPOSED | MB_ERR_INVALID_CHARS : MB_PRECOMPOSED, lpSrcStr, cchSrc, NULL, 0 )) ) return FALSE; /* allocate enough space for wide chars */ wbuffer = (wchar_t *)_calloca( sizeof(wchar_t), buff_size ); if ( wbuffer == NULL ) { return FALSE; } (void)memset( wbuffer, 0, sizeof(wchar_t) * buff_size ); /* do the conversion */ if ( 0 != (retval1 = MultiByteToWideChar( code_page, MB_PRECOMPOSED, lpSrcStr, cchSrc, wbuffer, buff_size )) ) /* obtain result */ retval2 = GetStringTypeW( dwInfoType, wbuffer, retval1, lpCharType ); _freea(wbuffer); return retval2; } else /* f_use is neither USE_A nor USE_W */ return FALSE; }