wchar_t* TruncStrFromEnd(wchar_t *Str,int MaxLength) { assert(MaxLength >= 0); MaxLength=Max(0, MaxLength); if (Str) { int Length = StrLength(Str); if (Length > MaxLength) { if (MaxLength>3) wmemcpy(Str+MaxLength-3, L"...", 3); Str[MaxLength]=0; } } return Str; }
TInt CTestLibcwchar::wmemcpy3L( ) { wchar_t ws1[50]=L"abcdegghij",*retval,ws2[50]; retval = wmemcpy(ws2,ws1,7); INFO_PRINTF1(_L("wmemcpy3 result is")); for(int i=0;i<7;i++) { INFO_PRINTF7(_L("retval[%d]=%x ws1[%d]=%x ws2[%d]=%x"),i,retval[i],i,ws1[i],i,ws2[i]); if(retval[i] != ws2[i] || ws1[i] != ws2[i]) { return KErrGeneral; } } return KErrNone; }
EXPORT_C int Tptr16ToCharp (const TDes16& aSrc, char* aDes, int& n_size) { unsigned int ilen = 0 ; int retval = ESuccess; ilen = aSrc.Length(); wchar_t* temp16String = NULL; int minusone = -1; if ( !aDes ) { return EInvalidPointer; } else if (n_size < ilen*2+1) { n_size = ilen*2 + 1; return EInvalidSize; } temp16String = new wchar_t [ilen+1]; if (!temp16String) { return EInsufficientSystemMemory; } wmemcpy(temp16String, (const wchar_t *)aSrc.Ptr(), ilen); temp16String[ilen] = L'\0'; if(minusone != wcstombs(aDes, temp16String, ilen*2)) { aDes[ilen*2] = '\0'; } else { retval = EInvalidWCSSequence; } delete []temp16String; return retval; }
/* copies history item at hst_pos to line. Sets pos and len to the len of the history item. hst_pos is decremented or incremented depending on key_dir. resets line if at end of history */ void fetch_hist_item(ChatContext *ctx, int key_dir) { if (key_dir == KEY_UP) { if (--ctx->hst_pos < 0) { ctx->hst_pos = 0; sound_notify(NULL, notif_error, NT_ALWAYS, NULL); } } else { if (++ctx->hst_pos >= ctx->hst_tot) { ctx->hst_pos = ctx->hst_tot; reset_buf(ctx); return; } } const wchar_t *hst_line = ctx->ln_history[ctx->hst_pos]; size_t h_len = wcslen(hst_line); wmemcpy(ctx->line, hst_line, h_len + 1); ctx->pos = h_len; ctx->len = h_len; }
/** * Converts a descriptor of type RBuf16 to Wstring * * @param aSrc is the descriptor to be converted , aDes is the * reference to the Wstring array where the result of conversion * is stored * @return Status code (0 is ESuccess, -1 is EInsufficientMemory, * -2 is EInvalidSize , -4 is EInvalidPointer , -5 is EDescriptorNoData) */ EXPORT_C int Rbuf16ToWstring(TDes16& aSrc, wstring& aDes) { unsigned int ilen = aSrc.Length(); if (0 == ilen) { return EDescriptorNoData; } wchar_t* buf = new wchar_t[ilen+1]; if(!buf) { return EInsufficientSystemMemory; } wmemcpy (buf,(wchar_t *)aSrc.Ptr(), ilen); buf[ilen]=L'\0'; aDes.assign(buf); delete[] buf; return ESuccess; }
CLogicInt CViewCommander::ConvertEol(const wchar_t* pszText, CLogicInt nTextLen, wchar_t* pszConvertedText) { // original by 2009.02.28 salarm CLogicInt nConvertedTextLen; CEol eol = GetDocument()->m_cDocEditor.GetNewLineCode(); nConvertedTextLen = 0; bool bExtEol = GetDllShareData().m_Common.m_sEdit.m_bEnableExtEol; if( pszConvertedText == NULL ){ for( int i = 0; i < nTextLen; i++ ){ if( WCODE::IsLineDelimiter(pszText[i], bExtEol) ){ if( pszText[i] == WCODE::CR ){ if( i + 1 < nTextLen && pszText[i + 1] == WCODE::LF ){ i++; } } nConvertedTextLen += eol.GetLen(); } else { nConvertedTextLen++; } } }else{ for( int i = 0; i < nTextLen; i++ ){ if( WCODE::IsLineDelimiter(pszText[i], bExtEol) ){ if( pszText[i] == WCODE::CR ){ if( i + 1 < nTextLen && pszText[i + 1] == WCODE::LF ){ i++; } } wmemcpy( &pszConvertedText[nConvertedTextLen], eol.GetValue2(), eol.GetLen() ); nConvertedTextLen += eol.GetLen(); } else { pszConvertedText[nConvertedTextLen++] = pszText[i]; } } } return nConvertedTextLen; }
/* 全行データを返す 改行コードは、CRLFに統一される。 @retval 全行データ。freeで解放しなければならない。 @note Debug版のテストにのみ使用している。 */ wchar_t* CDocReader::GetAllData(int* pnDataLen) { int nDataLen; int nLineLen; const CDocLine* pDocLine; pDocLine = m_pcDocLineMgr->GetDocLineTop(); nDataLen = 0; while( NULL != pDocLine ){ // Oct. 7, 2002 YAZAKI nDataLen += pDocLine->GetLengthWithoutEOL() + 2; // \r\nを追加して返すため+2する。 pDocLine = pDocLine->GetNextLine(); } wchar_t* pData; pData = (wchar_t*)malloc( (nDataLen + 1) * sizeof(wchar_t) ); if( NULL == pData ){ TopErrorMessage( NULL, LS(STR_ERR_DLGDOCLM6), nDataLen + 1 ); return NULL; } pDocLine = m_pcDocLineMgr->GetDocLineTop(); nDataLen = 0; while( NULL != pDocLine ){ // Oct. 7, 2002 YAZAKI nLineLen = pDocLine->GetLengthWithoutEOL(); if( 0 < nLineLen ){ wmemcpy( &pData[nDataLen], pDocLine->GetPtr(), nLineLen ); nDataLen += nLineLen; } pData[nDataLen++] = L'\r'; pData[nDataLen++] = L'\n'; pDocLine = pDocLine->GetNextLine(); } pData[nDataLen] = L'\0'; *pnDataLen = nDataLen; return pData; }
static int brl_writeWindow (BrailleDisplay *brl, const wchar_t *text) { if (text) { if (wmemcmp(text, textCharacters, brailleCount) != 0) { const wchar_t *address = text; int count = brailleCount; writeString("Visual \""); while (count-- > 0) { wchar_t character = *address++; switch (character) { case WC_C('"'): case WC_C('\\'): writeCharacter(WC_C('\\')); default: writeCharacter(character); break; } } writeString("\""); writeLine(); wmemcpy(textCharacters, text, brailleCount); } } if (cellsHaveChanged(brailleCells, brl->buffer, brailleCount, NULL, NULL, NULL)) { writeString("Braille \""); writeDots(brl->buffer, brailleCount); writeString("\""); writeLine(); } return 1; }
static TACommandVerdict wmemcpy_cmd(TAThread thread,TAInputStream stream) { wchar_t* ws1; wchar_t* ws2; size_t n; wchar_t* res; // Prepare ws1 = readPointer(&stream); ws2 = readPointer(&stream); n = readSize(&stream); // Execute START_TARGET_OPERATION(thread); res = wmemcpy( ws1, ws2, n); END_TARGET_OPERATION(thread); // Response writePointer(thread, res); sendResponse(thread); return taDefaultVerdict; }
EXPORT_C int Tbuf16ToWstring(TDes16& aSrc, wstring& aDes) { unsigned int ilen = aSrc.Length(); if (0 == ilen) { return EDescriptorNoData; } wchar_t* wcharString = new wchar_t[ilen+1]; if (!wcharString) { return EInsufficientSystemMemory; } wmemcpy((wchar_t*)wcharString, (const wchar_t*)aSrc.Ptr(), ilen); wcharString[ilen] = L'\0'; aDes.assign(wcharString); delete []wcharString; return ESuccess; }
wxWCharBuffer wxStringOperationsWchar::EncodeNChars(size_t n, const wxUniChar& ch) { if ( ch.IsSupplementary() ) { wxWCharBuffer buf(n * 2); wchar_t s[2] = { (wchar_t)ch.HighSurrogate(), (wchar_t)ch.LowSurrogate(), }; wchar_t *ptr = buf.data(); for (size_t i = 0; i < n; i++, ptr += 2) { wmemcpy(ptr, s, 2); } return buf; } else { // Assume ch is a BMP character wxWCharBuffer buf(n); wmemset(buf.data(), (wchar_t)ch, n); return buf; } }
int CComport::Open(int num) { COMMTIMEOUTS timeouts; DCB dcb; wchar_t port[64] = {NULL}; // initialise the comm port // was TEXT("COM8") wsprintf(port, L"%s%d", L"\\\\.\\COM", num); hComm = CreateFile(port, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, NULL); // exit as a failure if(hComm == INVALID_HANDLE_VALUE) return -1; // store the port name for closure wmemcpy(com_name, port, wcslen(port)); // set com port params FillMemory(&dcb, sizeof(dcb), 0); dcb.DCBlength = sizeof(dcb); // change the port identity and parameters if(GetCommState(hComm, &dcb)){ dcb.BaudRate = (CBR_57600); dcb.Parity = NOPARITY; dcb.StopBits = ONESTOPBIT; dcb.ByteSize = 8; SetCommState(hComm, &dcb); } // set communication timeouts timeouts.ReadIntervalTimeout = 0; timeouts.ReadTotalTimeoutMultiplier = 0; timeouts.ReadTotalTimeoutConstant = 1; timeouts.WriteTotalTimeoutMultiplier = 0; timeouts.WriteTotalTimeoutConstant = 0; SetCommTimeouts(hComm, &timeouts); return 1; }
/* copies history item at hst_pos to buf. Sets pos and len to the len of the history item. hst_pos is decremented or incremented depending on key_dir. resets buffer if at end of history */ void fetch_hist_item(wchar_t *buf, size_t *pos, size_t *len, wchar_t (*hst)[MAX_STR_SIZE], int hst_tot, int *hst_pos, int key_dir) { if (key_dir == MOVE_UP) { if (--(*hst_pos) < 0) { *hst_pos = 0; beep(); } } else { if (++(*hst_pos) >= hst_tot) { *hst_pos = hst_tot; reset_buf(buf, pos, len); return; } } const wchar_t *hst_line = hst[*hst_pos]; size_t h_len = wcslen(hst_line); wmemcpy(buf, hst_line, h_len + 1); *pos = h_len; *len = h_len; }
int main() { mbstate_t mb = {0}; size_t s = 0; tm tm = {0}; wint_t w = 0; ::FILE* fp = 0; __darwin_va_list va; 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(vwprintf(L"", va)), int>::value), ""); static_assert((std::is_same<decltype(vwscanf(L"", va)), int>::value), ""); static_assert((std::is_same<decltype(wprintf(L"")), int>::value), ""); static_assert((std::is_same<decltype(wscanf(L"")), 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(getwchar()), wint_t>::value), ""); static_assert((std::is_same<decltype(putwc(L' ', fp)), wint_t>::value), ""); static_assert((std::is_same<decltype(putwchar(L' ')), 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), ""); }
void SppLog::LogAudioUnit(int Code, int source, int Severity, LPVOID Data) { if (!m_hLogDlg) return; // Initialize LRESULT lr; HWND hEdit=NULL; WCHAR prefix[6], prtcode[20], src[20]; GETTEXTLENGTHEX tl; CHARFORMAT cf; tl.codepage = CP_ACP; tl.flags = GTL_DEFAULT; hEdit = GetDlgItem(m_hLogDlg, IDC_EDIT_LOG); SendMessage(hEdit,EM_SHOWSCROLLBAR , (WPARAM)SB_VERT, TRUE); // Severity to colour and Prefix lr = SendMessage(hEdit,EM_GETTEXTLENGTHEX , (WPARAM)&tl,0); cf.cbSize = sizeof(CHARFORMAT); cf.dwMask = CFM_COLOR; cf.dwEffects = 0; switch (Severity) { case ERR: cf.crTextColor = RGB(180,0,0); wmemcpy(prefix,L"[E] ",5); break; case FATAL: cf.crTextColor = RGB(250,0,0); wmemcpy(prefix,L"[F] ",5); break; case WARN: cf.crTextColor = RGB(255,140,0); wmemcpy(prefix,L"[W] ",5); break; default: cf.dwEffects = CFE_AUTOCOLOR; wmemcpy(prefix,L"[I] ",5); } switch (source) { case WMSPP_LOG_CNTRL: wmemcpy(src,L"<Cntrl ",sizeof(L"<Cntrl ")/sizeof(TCHAR)); break; case WMSPP_LOG_AUDIO: wmemcpy(src,L"<Audio ",sizeof(L"<Audio ")/sizeof(TCHAR)); break; case WMSPP_LOG_PRSC: wmemcpy(src,L"<Prcss ",sizeof(L"<Prcss ")/sizeof(TCHAR)); break; default: wmemcpy(src,L"<????? ",sizeof(L"<????? ")/sizeof(TCHAR)); } SendMessage(hEdit,EM_SETCHARFORMAT, (WPARAM)SCF_SELECTION, (LPARAM)&cf); // Print one Line // Prefix lr = SendMessage(hEdit,EM_GETTEXTLENGTHEX , (WPARAM)&tl,0); SendMessage(hEdit,EM_SETSEL , lr, lr); SendMessage(hEdit,EM_REPLACESEL , TRUE, (LPARAM)prefix); // Source lr = SendMessage(hEdit,EM_GETTEXTLENGTHEX , (WPARAM)&tl,0); SendMessage(hEdit,EM_SETSEL , lr, lr); SendMessage(hEdit,EM_REPLACESEL , TRUE, (LPARAM)src); // Code swprintf_s(prtcode, 10,L"%d>: ", Code); lr = SendMessage(hEdit,EM_GETTEXTLENGTHEX , (WPARAM)&tl,0); SendMessage(hEdit,EM_SETSEL , lr, lr); SendMessage(hEdit,EM_REPLACESEL , TRUE, (LPARAM)prtcode); // Data lr = SendMessage(hEdit,EM_GETTEXTLENGTHEX , (WPARAM)&tl,0); SendMessage(hEdit,EM_SETSEL , lr, lr); SendMessage(hEdit,EM_REPLACESEL , TRUE, (LPARAM)(LPCWSTR)Data); // New line lr = SendMessage(hEdit,EM_GETTEXTLENGTHEX , (WPARAM)&tl,0); SendMessage(hEdit,EM_SETSEL , lr, lr); SendMessage(hEdit,EM_REPLACESEL , TRUE, (LPARAM)L"\r\n"); // Scroll to bottom SendMessage(hEdit,EM_SCROLLCARET , 0, 0); }
void _WLdtob(_WPft *px, wchar_t code) { /* convert long double to wide text */ wchar_t ac[MAXDIG]; wchar_t *p = ac; long double ldval = px->v.ld; short errx, nsig, xexp; static const wchar_t inf[] = {L'i', L'n', L'f', L'\0'}; static const wchar_t Inf[] = {L'I', L'N', L'F', L'\0'}; static const wchar_t nan_str[] = {L'n', L'a', L'n', L'\0'}; static const wchar_t Nan[] = {L'N', L'A', L'N', L'\0'}; static const wchar_t xdigs[] = {L'0', L'1', L'2', L'3', L'4', L'5', L'6', L'7', L'8', L'9', L'a', L'b', L'c', L'd', L'e', L'f'}; static const wchar_t Xdigs[] = {L'0', L'1', L'2', L'3', L'4', L'5', L'6', L'7', L'8', L'9', L'A', L'B', L'C', L'D', L'E', L'F'}; if (code == L'a' || code == L'A') ; else if (px->prec < 0) px->prec = 6; else if (px->prec == 0 && (code == L'g' || code == L'G')) px->prec = 1; if ((errx = _LDunscale(&xexp, &px->v.ld)) == _NANCODE) { /* x == NaN */ wmemcpy(px->s, code == L'a' || code == L'e' || code == L'f' || code == L'g' ? nan_str : Nan, px->n1 = 3); return; } else if (0 < errx) { /* x == INF */ wmemcpy(px->s, code == L'a' || code == L'e' || code == L'f' || code == L'g' ? inf : Inf, px->n1 = 3); return; } if (code == L'a' || code == L'A') { /* put "0x" */ *px->s++ = L'0'; *px->s++ = code == L'a' ? L'x' : L'X'; px->n0 +=2; } if (0 == errx) /* x == 0 */ nsig = 0, xexp = 0; else if (code == L'a' || code == L'A') { /* 0 < |x|, generate hex fraction, binary exponent */ const wchar_t *digits = code == L'a' ? xdigs : Xdigs; int gen; nsig = px->prec < 0 ? MAXDIG - NXDIG : px->prec + 1; gen = nsig + 1; ldval = ldval < 0 ? -px->v.ld : px->v.ld; xexp -= 4; /* one leading nonzero hex digit */ for (*p++ = 0x0; 0 < gen && 0 < ldval; p += NXDIG) { /* convert NXDIG at a time */ int j; long lo; _LDscale(&ldval, 4 * NXDIG); lo = (long)ldval; if (0 < (gen -= NXDIG)) ldval -= (long double)lo; for (p += NXDIG, j = NXDIG; 0 < lo && 0 <= --j; ) *--p = (int)(lo & 0xf), lo >>= 4; while (0 <= --j) *--p = 0; } gen = p - &ac[1]; p = &ac[1]; if (gen < nsig) nsig = gen; if (0 <= nsig) { /* round and strip trailing zeros */ const char drop = nsig < gen && 0x8 <= p[nsig] ? 0xf : 0x0; int n; for (n = nsig; p[--n] == drop; ) --nsig; if (drop == 0xf) ++p[n]; if (n < 0) --p, ++nsig, xexp += 4; for (n = nsig; 0 <= --n; ) p[n] = digits[p[n]]; } if (px->prec < 0) px->prec = nsig - 1; } else { /* 0 < |x|, generate decimal fraction and exponent */ { /* scale ldval to ~~10^(NDIG/2) */
_IO_size_t _IO_getwline_info (_IO_FILE *fp, wchar_t *buf, _IO_size_t n, wint_t delim, int extract_delim, wint_t *eof) { wchar_t *ptr = buf; if (eof != NULL) *eof = 0; if (__builtin_expect (fp->_mode, 1) == 0) _IO_fwide (fp, 1); while (n != 0) { _IO_ssize_t len = (fp->_wide_data->_IO_read_end - fp->_wide_data->_IO_read_ptr); if (len <= 0) { wint_t wc = __wuflow (fp); if (wc == WEOF) { if (eof) *eof = wc; break; } if (wc == delim) { if (extract_delim > 0) *ptr++ = wc; else if (extract_delim < 0) _IO_sputbackc (fp, wc); if (extract_delim > 0) ++len; return ptr - buf; } *ptr++ = wc; n--; } else { wchar_t *t; if ((_IO_size_t) len >= n) len = n; t = wmemchr ((void *) fp->_wide_data->_IO_read_ptr, delim, len); if (t != NULL) { _IO_size_t old_len = ptr - buf; len = t - fp->_wide_data->_IO_read_ptr; if (extract_delim >= 0) { ++t; if (extract_delim > 0) ++len; } wmemcpy ((void *) ptr, (void *) fp->_wide_data->_IO_read_ptr, len); fp->_wide_data->_IO_read_ptr = t; return old_len + len; } wmemcpy ((void *) ptr, (void *) fp->_wide_data->_IO_read_ptr, len); fp->_wide_data->_IO_read_ptr += len; ptr += len; n -= len; } } return ptr - buf; }
static int listKeyContext (ListGenerationData *lgd, const KeyContext *ctx, const wchar_t *keysPrefix) { { const HotkeyEntry *hotkey = ctx->hotkeyTable; unsigned int count = ctx->hotkeyCount; while (count) { if (!(hotkey->flags & HKF_HIDDEN)) { if (!listHotkeyEvent(lgd, &hotkey->keyValue, "press", hotkey->pressCommand)) return 0; if (!listHotkeyEvent(lgd, &hotkey->keyValue, "release", hotkey->releaseCommand)) return 0; } hotkey += 1, count -= 1; } } { const KeyBinding *binding = ctx->keyBindingTable; unsigned int count = ctx->keyBindingCount; while (count) { if (!(binding->flags & KBF_HIDDEN)) { size_t keysOffset; if (!putCommandDescription(lgd, binding->command, !binding->combination.anyKeyCount)) return 0; if (!putCharacterString(lgd, WS_C(": "))) return 0; keysOffset = lgd->lineLength; if (keysPrefix) { if (!putCharacterString(lgd, keysPrefix)) return 0; if (!putCharacterString(lgd, WS_C(", "))) return 0; } if (!putKeyCombination(lgd, &binding->combination)) return 0; if ((binding->command & BRL_MSK_BLK) == BRL_BLK_CONTEXT) { const KeyContext *c = getKeyContext(lgd->keyTable, (KTB_CTX_DEFAULT + (binding->command & BRL_MSK_ARG))); if (!c) return 0; { size_t length = lgd->lineLength - keysOffset; wchar_t keys[length + 1]; wmemcpy(keys, &lgd->lineCharacters[keysOffset], length); keys[length] = 0; lgd->lineLength = 0; if (isTemporaryKeyContext(lgd->keyTable, c)) { if (!listKeyContext(lgd, c, keys)) return 0; } else { if (!putCharacterString(lgd, WS_C("switch to "))) return 0; if (!putCharacterString(lgd, c->title)) return 0; if (!putCharacterString(lgd, WS_C(": "))) return 0; if (!putCharacterString(lgd, keys)) return 0; if (!endLine(lgd)) return 0; } } } else { if (!endLine(lgd)) return 0; } } binding += 1, count -= 1; } } if (!listKeyboardFunctions(lgd, ctx)) return 0; return 1; }
/** * Duplicate a string. * * This is a slibc extension added for completeness. * It is only available if GNU extensions are available. * * @param string The string to duplicate. * @param maxlen Truncate the string to this length, if it is longer. * A NUL wide character is guaranteed to always be * written upon successful completion. * @return The new string. `NULL` is returned on error * and `errno` is set to indicate the error. * * @throws ENOMEM The process could not allocate sufficient amount of memory. * * @since Always. */ wchar_t* wcsndup(const wchar_t* string, size_t maxlen) { size_t n = wcsnlen(string, maxlen) + 1; wchar_t* r = malloc(n * sizeof(wchar_t)); return r == NULL ? NULL : wmemcpy(r, string, n); }
static void updateCache (BrailleContractionData *bcd) { { unsigned int count = getInputCount(bcd); if (count > bcd->table->cache.input.size) { unsigned int newSize = count | 0X7F; wchar_t *newCharacters = malloc(ARRAY_SIZE(newCharacters, newSize)); if (!newCharacters) { logMallocError(); bcd->table->cache.input.count = 0; goto inputDone; } if (bcd->table->cache.input.characters) free(bcd->table->cache.input.characters); bcd->table->cache.input.characters = newCharacters; bcd->table->cache.input.size = newSize; } wmemcpy(bcd->table->cache.input.characters, bcd->input.begin, count); bcd->table->cache.input.count = count; bcd->table->cache.input.consumed = getInputConsumed(bcd); } inputDone: { unsigned int count = getOutputConsumed(bcd); if (count > bcd->table->cache.output.size) { unsigned int newSize = count | 0X7F; unsigned char *newCells = malloc(ARRAY_SIZE(newCells, newSize)); if (!newCells) { logMallocError(); bcd->table->cache.output.count = 0; goto outputDone; } if (bcd->table->cache.output.cells) free(bcd->table->cache.output.cells); bcd->table->cache.output.cells = newCells; bcd->table->cache.output.size = newSize; } memcpy(bcd->table->cache.output.cells, bcd->output.begin, count); bcd->table->cache.output.count = count; bcd->table->cache.output.maximum = getOutputCount(bcd); } outputDone: if (bcd->input.offsets) { unsigned int count = getInputCount(bcd); if (count > bcd->table->cache.offsets.size) { unsigned int newSize = count | 0X7F; int *newArray = malloc(ARRAY_SIZE(newArray, newSize)); if (!newArray) { logMallocError(); bcd->table->cache.offsets.count = 0; goto offsetsDone; } if (bcd->table->cache.offsets.array) free(bcd->table->cache.offsets.array); bcd->table->cache.offsets.array = newArray; bcd->table->cache.offsets.size = newSize; } memcpy(bcd->table->cache.offsets.array, bcd->input.offsets, ARRAY_SIZE(bcd->input.offsets, count)); bcd->table->cache.offsets.count = count; } else { bcd->table->cache.offsets.count = 0; } offsetsDone: bcd->table->cache.cursorOffset = makeCachedCursorOffset(bcd); bcd->table->cache.expandCurrentWord = prefs.expandCurrentWord; bcd->table->cache.capitalizationMode = prefs.capitalizationMode; }
static int do_test (void) { struct sigaction sa; sa.sa_handler = handler; sa.sa_flags = 0; sigemptyset (&sa.sa_mask); sigaction (SIGABRT, &sa, NULL); /* Avoid all the buffer overflow messages on stderr. */ int fd = open (_PATH_DEVNULL, O_WRONLY); if (fd == -1) close (STDERR_FILENO); else { dup2 (fd, STDERR_FILENO); close (fd); } setenv ("LIBC_FATAL_STDERR_", "1", 1); struct A { char buf1[9]; char buf2[1]; } a; struct wA { wchar_t buf1[9]; wchar_t buf2[1]; } wa; printf ("Test checking routines at fortify level %d\n", #ifdef __USE_FORTIFY_LEVEL (int) __USE_FORTIFY_LEVEL #else 0 #endif ); /* These ops can be done without runtime checking of object size. */ memcpy (buf, "abcdefghij", 10); memmove (buf + 1, buf, 9); if (memcmp (buf, "aabcdefghi", 10)) FAIL (); if (mempcpy (buf + 5, "abcde", 5) != buf + 10 || memcmp (buf, "aabcdabcde", 10)) FAIL (); memset (buf + 8, 'j', 2); if (memcmp (buf, "aabcdabcjj", 10)) FAIL (); strcpy (buf + 4, "EDCBA"); if (memcmp (buf, "aabcEDCBA", 10)) FAIL (); if (stpcpy (buf + 8, "F") != buf + 9 || memcmp (buf, "aabcEDCBF", 10)) FAIL (); strncpy (buf + 6, "X", 4); if (memcmp (buf, "aabcEDX\0\0", 10)) FAIL (); if (sprintf (buf + 7, "%s", "67") != 2 || memcmp (buf, "aabcEDX67", 10)) FAIL (); if (snprintf (buf + 7, 3, "%s", "987654") != 6 || memcmp (buf, "aabcEDX98", 10)) FAIL (); /* These ops need runtime checking, but shouldn't __chk_fail. */ memcpy (buf, "abcdefghij", l0 + 10); memmove (buf + 1, buf, l0 + 9); if (memcmp (buf, "aabcdefghi", 10)) FAIL (); if (mempcpy (buf + 5, "abcde", l0 + 5) != buf + 10 || memcmp (buf, "aabcdabcde", 10)) FAIL (); memset (buf + 8, 'j', l0 + 2); if (memcmp (buf, "aabcdabcjj", 10)) FAIL (); strcpy (buf + 4, str1 + 5); if (memcmp (buf, "aabcEDCBA", 10)) FAIL (); if (stpcpy (buf + 8, str2) != buf + 9 || memcmp (buf, "aabcEDCBF", 10)) FAIL (); strncpy (buf + 6, "X", l0 + 4); if (memcmp (buf, "aabcEDX\0\0", 10)) FAIL (); if (stpncpy (buf + 5, "cd", l0 + 5) != buf + 7 || memcmp (buf, "aabcEcd\0\0", 10)) FAIL (); if (sprintf (buf + 7, "%d", num1) != 2 || memcmp (buf, "aabcEcd67", 10)) FAIL (); if (snprintf (buf + 7, 3, "%d", num2) != 6 || memcmp (buf, "aabcEcd98", 10)) FAIL (); buf[l0 + 8] = '\0'; strcat (buf, "A"); if (memcmp (buf, "aabcEcd9A", 10)) FAIL (); buf[l0 + 7] = '\0'; strncat (buf, "ZYXWV", l0 + 2); if (memcmp (buf, "aabcEcdZY", 10)) FAIL (); memcpy (a.buf1, "abcdefghij", l0 + 10); memmove (a.buf1 + 1, a.buf1, l0 + 9); if (memcmp (a.buf1, "aabcdefghi", 10)) FAIL (); if (mempcpy (a.buf1 + 5, "abcde", l0 + 5) != a.buf1 + 10 || memcmp (a.buf1, "aabcdabcde", 10)) FAIL (); memset (a.buf1 + 8, 'j', l0 + 2); if (memcmp (a.buf1, "aabcdabcjj", 10)) FAIL (); #if __USE_FORTIFY_LEVEL < 2 /* The following tests are supposed to crash with -D_FORTIFY_SOURCE=2 and sufficient GCC support, as the string operations overflow from a.buf1 into a.buf2. */ strcpy (a.buf1 + 4, str1 + 5); if (memcmp (a.buf1, "aabcEDCBA", 10)) FAIL (); if (stpcpy (a.buf1 + 8, str2) != a.buf1 + 9 || memcmp (a.buf1, "aabcEDCBF", 10)) FAIL (); strncpy (a.buf1 + 6, "X", l0 + 4); if (memcmp (a.buf1, "aabcEDX\0\0", 10)) FAIL (); if (sprintf (a.buf1 + 7, "%d", num1) != 2 || memcmp (a.buf1, "aabcEDX67", 10)) FAIL (); if (snprintf (a.buf1 + 7, 3, "%d", num2) != 6 || memcmp (a.buf1, "aabcEDX98", 10)) FAIL (); a.buf1[l0 + 8] = '\0'; strcat (a.buf1, "A"); if (memcmp (a.buf1, "aabcEDX9A", 10)) FAIL (); a.buf1[l0 + 7] = '\0'; strncat (a.buf1, "ZYXWV", l0 + 2); if (memcmp (a.buf1, "aabcEDXZY", 10)) FAIL (); #endif #if __USE_FORTIFY_LEVEL >= 1 /* Now check if all buffer overflows are caught at runtime. */ CHK_FAIL_START memcpy (buf + 1, "abcdefghij", l0 + 10); CHK_FAIL_END CHK_FAIL_START memmove (buf + 2, buf + 1, l0 + 9); CHK_FAIL_END CHK_FAIL_START p = mempcpy (buf + 6, "abcde", l0 + 5); CHK_FAIL_END CHK_FAIL_START memset (buf + 9, 'j', l0 + 2); CHK_FAIL_END CHK_FAIL_START strcpy (buf + 5, str1 + 5); CHK_FAIL_END CHK_FAIL_START p = stpcpy (buf + 9, str2); CHK_FAIL_END CHK_FAIL_START strncpy (buf + 7, "X", l0 + 4); CHK_FAIL_END CHK_FAIL_START stpncpy (buf + 6, "cd", l0 + 5); CHK_FAIL_END CHK_FAIL_START sprintf (buf + 8, "%d", num1); CHK_FAIL_END CHK_FAIL_START snprintf (buf + 8, l0 + 3, "%d", num2); CHK_FAIL_END memcpy (buf, str1 + 2, l0 + 9); CHK_FAIL_START strcat (buf, "AB"); CHK_FAIL_END memcpy (buf, str1 + 3, l0 + 8); CHK_FAIL_START strncat (buf, "ZYXWV", l0 + 3); CHK_FAIL_END CHK_FAIL_START memcpy (a.buf1 + 1, "abcdefghij", l0 + 10); CHK_FAIL_END CHK_FAIL_START memmove (a.buf1 + 2, a.buf1 + 1, l0 + 9); CHK_FAIL_END CHK_FAIL_START p = mempcpy (a.buf1 + 6, "abcde", l0 + 5); CHK_FAIL_END CHK_FAIL_START memset (a.buf1 + 9, 'j', l0 + 2); CHK_FAIL_END #if __USE_FORTIFY_LEVEL >= 2 # define O 0 #else # define O 1 #endif CHK_FAIL_START strcpy (a.buf1 + (O + 4), str1 + 5); CHK_FAIL_END CHK_FAIL_START p = stpcpy (a.buf1 + (O + 8), str2); CHK_FAIL_END CHK_FAIL_START strncpy (a.buf1 + (O + 6), "X", l0 + 4); CHK_FAIL_END CHK_FAIL_START sprintf (a.buf1 + (O + 7), "%d", num1); CHK_FAIL_END CHK_FAIL_START snprintf (a.buf1 + (O + 7), l0 + 3, "%d", num2); CHK_FAIL_END memcpy (a.buf1, str1 + (3 - O), l0 + 8 + O); CHK_FAIL_START strcat (a.buf1, "AB"); CHK_FAIL_END memcpy (a.buf1, str1 + (4 - O), l0 + 7 + O); CHK_FAIL_START strncat (a.buf1, "ZYXWV", l0 + 3); CHK_FAIL_END #endif /* These ops can be done without runtime checking of object size. */ wmemcpy (wbuf, L"abcdefghij", 10); wmemmove (wbuf + 1, wbuf, 9); if (wmemcmp (wbuf, L"aabcdefghi", 10)) FAIL (); if (wmempcpy (wbuf + 5, L"abcde", 5) != wbuf + 10 || wmemcmp (wbuf, L"aabcdabcde", 10)) FAIL (); wmemset (wbuf + 8, L'j', 2); if (wmemcmp (wbuf, L"aabcdabcjj", 10)) FAIL (); wcscpy (wbuf + 4, L"EDCBA"); if (wmemcmp (wbuf, L"aabcEDCBA", 10)) FAIL (); if (wcpcpy (wbuf + 8, L"F") != wbuf + 9 || wmemcmp (wbuf, L"aabcEDCBF", 10)) FAIL (); wcsncpy (wbuf + 6, L"X", 4); if (wmemcmp (wbuf, L"aabcEDX\0\0", 10)) FAIL (); if (swprintf (wbuf + 7, 3, L"%ls", L"987654") >= 0 || wmemcmp (wbuf, L"aabcEDX98", 10)) FAIL (); if (swprintf (wbuf + 7, 3, L"64") != 2 || wmemcmp (wbuf, L"aabcEDX64", 10)) FAIL (); /* These ops need runtime checking, but shouldn't __chk_fail. */ wmemcpy (wbuf, L"abcdefghij", l0 + 10); wmemmove (wbuf + 1, wbuf, l0 + 9); if (wmemcmp (wbuf, L"aabcdefghi", 10)) FAIL (); if (wmempcpy (wbuf + 5, L"abcde", l0 + 5) != wbuf + 10 || wmemcmp (wbuf, L"aabcdabcde", 10)) FAIL (); wmemset (wbuf + 8, L'j', l0 + 2); if (wmemcmp (wbuf, L"aabcdabcjj", 10)) FAIL (); wcscpy (wbuf + 4, wstr1 + 5); if (wmemcmp (wbuf, L"aabcEDCBA", 10)) FAIL (); if (wcpcpy (wbuf + 8, wstr2) != wbuf + 9 || wmemcmp (wbuf, L"aabcEDCBF", 10)) FAIL (); wcsncpy (wbuf + 6, L"X", l0 + 4); if (wmemcmp (wbuf, L"aabcEDX\0\0", 10)) FAIL (); if (wcpncpy (wbuf + 5, L"cd", l0 + 5) != wbuf + 7 || wmemcmp (wbuf, L"aabcEcd\0\0", 10)) FAIL (); if (swprintf (wbuf + 7, 3, L"%d", num2) >= 0 || wmemcmp (wbuf, L"aabcEcd98", 10)) FAIL (); wbuf[l0 + 8] = L'\0'; wcscat (wbuf, L"A"); if (wmemcmp (wbuf, L"aabcEcd9A", 10)) FAIL (); wbuf[l0 + 7] = L'\0'; wcsncat (wbuf, L"ZYXWV", l0 + 2); if (wmemcmp (wbuf, L"aabcEcdZY", 10)) FAIL (); wmemcpy (wa.buf1, L"abcdefghij", l0 + 10); wmemmove (wa.buf1 + 1, wa.buf1, l0 + 9); if (wmemcmp (wa.buf1, L"aabcdefghi", 10)) FAIL (); if (wmempcpy (wa.buf1 + 5, L"abcde", l0 + 5) != wa.buf1 + 10 || wmemcmp (wa.buf1, L"aabcdabcde", 10)) FAIL (); wmemset (wa.buf1 + 8, L'j', l0 + 2); if (wmemcmp (wa.buf1, L"aabcdabcjj", 10)) FAIL (); #if __USE_FORTIFY_LEVEL < 2 /* The following tests are supposed to crash with -D_FORTIFY_SOURCE=2 and sufficient GCC support, as the string operations overflow from a.buf1 into a.buf2. */ wcscpy (wa.buf1 + 4, wstr1 + 5); if (wmemcmp (wa.buf1, L"aabcEDCBA", 10)) FAIL (); if (wcpcpy (wa.buf1 + 8, wstr2) != wa.buf1 + 9 || wmemcmp (wa.buf1, L"aabcEDCBF", 10)) FAIL (); wcsncpy (wa.buf1 + 6, L"X", l0 + 4); if (wmemcmp (wa.buf1, L"aabcEDX\0\0", 10)) FAIL (); if (swprintf (wa.buf1 + 7, 3, L"%d", num2) >= 0 || wmemcmp (wa.buf1, L"aabcEDX98", 10)) FAIL (); wa.buf1[l0 + 8] = L'\0'; wcscat (wa.buf1, L"A"); if (wmemcmp (wa.buf1, L"aabcEDX9A", 10)) FAIL (); wa.buf1[l0 + 7] = L'\0'; wcsncat (wa.buf1, L"ZYXWV", l0 + 2); if (wmemcmp (wa.buf1, L"aabcEDXZY", 10)) FAIL (); #endif #if __USE_FORTIFY_LEVEL >= 1 /* Now check if all buffer overflows are caught at runtime. */ CHK_FAIL_START wmemcpy (wbuf + 1, L"abcdefghij", l0 + 10); CHK_FAIL_END CHK_FAIL_START wmemmove (wbuf + 2, wbuf + 1, l0 + 9); CHK_FAIL_END CHK_FAIL_START wp = wmempcpy (wbuf + 6, L"abcde", l0 + 5); CHK_FAIL_END CHK_FAIL_START wmemset (wbuf + 9, L'j', l0 + 2); CHK_FAIL_END CHK_FAIL_START wcscpy (wbuf + 5, wstr1 + 5); CHK_FAIL_END CHK_FAIL_START wp = wcpcpy (wbuf + 9, wstr2); CHK_FAIL_END CHK_FAIL_START wcsncpy (wbuf + 7, L"X", l0 + 4); CHK_FAIL_END CHK_FAIL_START wcpncpy (wbuf + 6, L"cd", l0 + 5); CHK_FAIL_END wmemcpy (wbuf, wstr1 + 2, l0 + 9); CHK_FAIL_START wcscat (wbuf, L"AB"); CHK_FAIL_END wmemcpy (wbuf, wstr1 + 3, l0 + 8); CHK_FAIL_START wcsncat (wbuf, L"ZYXWV", l0 + 3); CHK_FAIL_END CHK_FAIL_START wmemcpy (wa.buf1 + 1, L"abcdefghij", l0 + 10); CHK_FAIL_END CHK_FAIL_START wmemmove (wa.buf1 + 2, wa.buf1 + 1, l0 + 9); CHK_FAIL_END CHK_FAIL_START wp = wmempcpy (wa.buf1 + 6, L"abcde", l0 + 5); CHK_FAIL_END CHK_FAIL_START wmemset (wa.buf1 + 9, L'j', l0 + 2); CHK_FAIL_END #if __USE_FORTIFY_LEVEL >= 2 # define O 0 #else # define O 1 #endif CHK_FAIL_START wcscpy (wa.buf1 + (O + 4), wstr1 + 5); CHK_FAIL_END CHK_FAIL_START wp = wcpcpy (wa.buf1 + (O + 8), wstr2); CHK_FAIL_END CHK_FAIL_START wcsncpy (wa.buf1 + (O + 6), L"X", l0 + 4); CHK_FAIL_END wmemcpy (wa.buf1, wstr1 + (3 - O), l0 + 8 + O); CHK_FAIL_START wcscat (wa.buf1, L"AB"); CHK_FAIL_END wmemcpy (wa.buf1, wstr1 + (4 - O), l0 + 7 + O); CHK_FAIL_START wcsncat (wa.buf1, L"ZYXWV", l0 + 3); CHK_FAIL_END #endif /* Now checks for %n protection. */ /* Constant literals passed directly are always ok (even with warnings about possible bugs from GCC). */ int n1, n2; if (sprintf (buf, "%s%n%s%n", str2, &n1, str2, &n2) != 2 || n1 != 1 || n2 != 2) FAIL (); /* In this case the format string is not known at compile time, but resides in read-only memory, so is ok. */ if (snprintf (buf, 4, str3, str2, &n1, str2, &n2) != 2 || n1 != 1 || n2 != 2) FAIL (); strcpy (buf2 + 2, "%n%s%n"); /* When the format string is writable and contains %n, with -D_FORTIFY_SOURCE=2 it causes __chk_fail. */ CHK_FAIL2_START if (sprintf (buf, buf2, str2, &n1, str2, &n1) != 2) FAIL (); CHK_FAIL2_END CHK_FAIL2_START if (snprintf (buf, 3, buf2, str2, &n1, str2, &n1) != 2) FAIL (); CHK_FAIL2_END /* But if there is no %n, even writable format string should work. */ buf2[6] = '\0'; if (sprintf (buf, buf2 + 4, str2) != 1) FAIL (); /* Constant literals passed directly are always ok (even with warnings about possible bugs from GCC). */ if (printf ("%s%n%s%n", str4, &n1, str5, &n2) != 14 || n1 != 7 || n2 != 14) FAIL (); /* In this case the format string is not known at compile time, but resides in read-only memory, so is ok. */ if (printf (str3, str4, &n1, str5, &n2) != 14 || n1 != 7 || n2 != 14) FAIL (); strcpy (buf2 + 2, "%n%s%n"); /* When the format string is writable and contains %n, with -D_FORTIFY_SOURCE=2 it causes __chk_fail. */ CHK_FAIL2_START if (printf (buf2, str4, &n1, str5, &n1) != 14) FAIL (); CHK_FAIL2_END /* But if there is no %n, even writable format string should work. */ buf2[6] = '\0'; if (printf (buf2 + 4, str5) != 7) FAIL (); FILE *fp = stdout; /* Constant literals passed directly are always ok (even with warnings about possible bugs from GCC). */ if (fprintf (fp, "%s%n%s%n", str4, &n1, str5, &n2) != 14 || n1 != 7 || n2 != 14) FAIL (); /* In this case the format string is not known at compile time, but resides in read-only memory, so is ok. */ if (fprintf (fp, str3, str4, &n1, str5, &n2) != 14 || n1 != 7 || n2 != 14) FAIL (); strcpy (buf2 + 2, "%n%s%n"); /* When the format string is writable and contains %n, with -D_FORTIFY_SOURCE=2 it causes __chk_fail. */ CHK_FAIL2_START if (fprintf (fp, buf2, str4, &n1, str5, &n1) != 14) FAIL (); CHK_FAIL2_END /* But if there is no %n, even writable format string should work. */ buf2[6] = '\0'; if (fprintf (fp, buf2 + 4, str5) != 7) FAIL (); if (freopen (temp_filename, "r", stdin) == NULL) { puts ("could not open temporary file"); exit (1); } if (gets (buf) != buf || memcmp (buf, "abcdefgh", 9)) FAIL (); if (gets (buf) != buf || memcmp (buf, "ABCDEFGHI", 10)) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (gets (buf) != buf) FAIL (); CHK_FAIL_END #endif rewind (stdin); if (fgets (buf, sizeof (buf), stdin) != buf || memcmp (buf, "abcdefgh\n", 10)) FAIL (); if (fgets (buf, sizeof (buf), stdin) != buf || memcmp (buf, "ABCDEFGHI", 10)) FAIL (); rewind (stdin); if (fgets (buf, l0 + sizeof (buf), stdin) != buf || memcmp (buf, "abcdefgh\n", 10)) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (fgets (buf, sizeof (buf) + 1, stdin) != buf) FAIL (); CHK_FAIL_END CHK_FAIL_START if (fgets (buf, l0 + sizeof (buf) + 1, stdin) != buf) FAIL (); CHK_FAIL_END #endif rewind (stdin); if (fgets_unlocked (buf, sizeof (buf), stdin) != buf || memcmp (buf, "abcdefgh\n", 10)) FAIL (); if (fgets_unlocked (buf, sizeof (buf), stdin) != buf || memcmp (buf, "ABCDEFGHI", 10)) FAIL (); rewind (stdin); if (fgets_unlocked (buf, l0 + sizeof (buf), stdin) != buf || memcmp (buf, "abcdefgh\n", 10)) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (fgets_unlocked (buf, sizeof (buf) + 1, stdin) != buf) FAIL (); CHK_FAIL_END CHK_FAIL_START if (fgets_unlocked (buf, l0 + sizeof (buf) + 1, stdin) != buf) FAIL (); CHK_FAIL_END #endif lseek (fileno (stdin), 0, SEEK_SET); if (read (fileno (stdin), buf, sizeof (buf) - 1) != sizeof (buf) - 1 || memcmp (buf, "abcdefgh\n", 9)) FAIL (); if (read (fileno (stdin), buf, sizeof (buf) - 1) != sizeof (buf) - 1 || memcmp (buf, "ABCDEFGHI", 9)) FAIL (); lseek (fileno (stdin), 0, SEEK_SET); if (read (fileno (stdin), buf, l0 + sizeof (buf) - 1) != sizeof (buf) - 1 || memcmp (buf, "abcdefgh\n", 9)) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (read (fileno (stdin), buf, sizeof (buf) + 1) != sizeof (buf) + 1) FAIL (); CHK_FAIL_END #endif if (pread (fileno (stdin), buf, sizeof (buf) - 1, sizeof (buf) - 2) != sizeof (buf) - 1 || memcmp (buf, "\nABCDEFGH", 9)) FAIL (); if (pread (fileno (stdin), buf, sizeof (buf) - 1, 0) != sizeof (buf) - 1 || memcmp (buf, "abcdefgh\n", 9)) FAIL (); if (pread (fileno (stdin), buf, l0 + sizeof (buf) - 1, sizeof (buf) - 3) != sizeof (buf) - 1 || memcmp (buf, "h\nABCDEFG", 9)) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (pread (fileno (stdin), buf, sizeof (buf) + 1, 2 * sizeof (buf)) != sizeof (buf) + 1) FAIL (); CHK_FAIL_END #endif if (pread64 (fileno (stdin), buf, sizeof (buf) - 1, sizeof (buf) - 2) != sizeof (buf) - 1 || memcmp (buf, "\nABCDEFGH", 9)) FAIL (); if (pread64 (fileno (stdin), buf, sizeof (buf) - 1, 0) != sizeof (buf) - 1 || memcmp (buf, "abcdefgh\n", 9)) FAIL (); if (pread64 (fileno (stdin), buf, l0 + sizeof (buf) - 1, sizeof (buf) - 3) != sizeof (buf) - 1 || memcmp (buf, "h\nABCDEFG", 9)) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (pread64 (fileno (stdin), buf, sizeof (buf) + 1, 2 * sizeof (buf)) != sizeof (buf) + 1) FAIL (); CHK_FAIL_END #endif if (freopen (temp_filename, "r", stdin) == NULL) { puts ("could not open temporary file"); exit (1); } if (fseek (stdin, 9 + 10 + 11, SEEK_SET)) { puts ("could not seek in test file"); exit (1); } #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (gets (buf) != buf) FAIL (); CHK_FAIL_END #endif /* Check whether missing N$ formats are detected. */ CHK_FAIL2_START printf ("%3$d\n", 1, 2, 3, 4); CHK_FAIL2_END CHK_FAIL2_START fprintf (stdout, "%3$d\n", 1, 2, 3, 4); CHK_FAIL2_END CHK_FAIL2_START sprintf (buf, "%3$d\n", 1, 2, 3, 4); CHK_FAIL2_END CHK_FAIL2_START snprintf (buf, sizeof (buf), "%3$d\n", 1, 2, 3, 4); CHK_FAIL2_END int sp[2]; if (socketpair (PF_UNIX, SOCK_STREAM, 0, sp)) FAIL (); else { const char *sendstr = "abcdefgh\nABCDEFGH\n0123456789\n"; if (send (sp[0], sendstr, strlen (sendstr), 0) != strlen (sendstr)) FAIL (); char recvbuf[12]; if (recv (sp[1], recvbuf, sizeof recvbuf, MSG_PEEK) != sizeof recvbuf || memcmp (recvbuf, sendstr, sizeof recvbuf) != 0) FAIL (); if (recv (sp[1], recvbuf + 6, l0 + sizeof recvbuf - 7, MSG_PEEK) != sizeof recvbuf - 7 || memcmp (recvbuf + 6, sendstr, sizeof recvbuf - 7) != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (recv (sp[1], recvbuf + 1, sizeof recvbuf, MSG_PEEK) != sizeof recvbuf) FAIL (); CHK_FAIL_END CHK_FAIL_START if (recv (sp[1], recvbuf + 4, l0 + sizeof recvbuf - 3, MSG_PEEK) != sizeof recvbuf - 3) FAIL (); CHK_FAIL_END #endif socklen_t sl; struct sockaddr_un sa_un; sl = sizeof (sa_un); if (recvfrom (sp[1], recvbuf, sizeof recvbuf, MSG_PEEK, &sa_un, &sl) != sizeof recvbuf || memcmp (recvbuf, sendstr, sizeof recvbuf) != 0) FAIL (); sl = sizeof (sa_un); if (recvfrom (sp[1], recvbuf + 6, l0 + sizeof recvbuf - 7, MSG_PEEK, &sa_un, &sl) != sizeof recvbuf - 7 || memcmp (recvbuf + 6, sendstr, sizeof recvbuf - 7) != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START sl = sizeof (sa_un); if (recvfrom (sp[1], recvbuf + 1, sizeof recvbuf, MSG_PEEK, &sa_un, &sl) != sizeof recvbuf) FAIL (); CHK_FAIL_END CHK_FAIL_START sl = sizeof (sa_un); if (recvfrom (sp[1], recvbuf + 4, l0 + sizeof recvbuf - 3, MSG_PEEK, &sa_un, &sl) != sizeof recvbuf - 3) FAIL (); CHK_FAIL_END #endif close (sp[0]); close (sp[1]); } char fname[] = "/tmp/tst-chk1-dir-XXXXXX\0foo"; char *enddir = strchr (fname, '\0'); if (mkdtemp (fname) == NULL) { printf ("mkdtemp failed: %m\n"); return 1; } *enddir = '/'; if (symlink ("bar", fname) != 0) FAIL (); char readlinkbuf[4]; if (readlink (fname, readlinkbuf, 4) != 3 || memcmp (readlinkbuf, "bar", 3) != 0) FAIL (); if (readlink (fname, readlinkbuf + 1, l0 + 3) != 3 || memcmp (readlinkbuf, "bbar", 4) != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (readlink (fname, readlinkbuf + 2, l0 + 3) != 3) FAIL (); CHK_FAIL_END CHK_FAIL_START if (readlink (fname, readlinkbuf + 3, 4) != 3) FAIL (); CHK_FAIL_END #endif char *cwd1 = getcwd (NULL, 0); if (cwd1 == NULL) FAIL (); char *cwd2 = getcwd (NULL, 250); if (cwd2 == NULL) FAIL (); if (cwd1 && cwd2) { if (strcmp (cwd1, cwd2) != 0) FAIL (); *enddir = '\0'; if (chdir (fname)) FAIL (); char *cwd3 = getcwd (NULL, 0); if (cwd3 == NULL) FAIL (); if (strcmp (fname, cwd3) != 0) printf ("getcwd after chdir is '%s' != '%s'," "get{c,}wd tests skipped\n", cwd3, fname); else { char getcwdbuf[sizeof fname - 3]; char *cwd4 = getcwd (getcwdbuf, sizeof getcwdbuf); if (cwd4 != getcwdbuf || strcmp (getcwdbuf, fname) != 0) FAIL (); cwd4 = getcwd (getcwdbuf + 1, l0 + sizeof getcwdbuf - 1); if (cwd4 != getcwdbuf + 1 || getcwdbuf[0] != fname[0] || strcmp (getcwdbuf + 1, fname) != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (getcwd (getcwdbuf + 2, l0 + sizeof getcwdbuf) != getcwdbuf + 2) FAIL (); CHK_FAIL_END CHK_FAIL_START if (getcwd (getcwdbuf + 2, sizeof getcwdbuf) != getcwdbuf + 2) FAIL (); CHK_FAIL_END #endif if (getwd (getcwdbuf) != getcwdbuf || strcmp (getcwdbuf, fname) != 0) FAIL (); if (getwd (getcwdbuf + 1) != getcwdbuf + 1 || strcmp (getcwdbuf + 1, fname) != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (getwd (getcwdbuf + 2) != getcwdbuf + 2) FAIL (); CHK_FAIL_END #endif } if (chdir (cwd1) != 0) FAIL (); free (cwd3); } free (cwd1); free (cwd2); *enddir = '/'; if (unlink (fname) != 0) FAIL (); *enddir = '\0'; if (rmdir (fname) != 0) FAIL (); #if PATH_MAX > 0 char largebuf[PATH_MAX]; char *realres = realpath (".", largebuf); if (realres != largebuf) FAIL (); # if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START char realbuf[1]; realres = realpath (".", realbuf); if (realres != realbuf) FAIL (); CHK_FAIL_END # endif #endif if (setlocale (LC_ALL, "de_DE.UTF-8") != NULL) { assert (MB_CUR_MAX <= 10); /* First a simple test. */ char enough[10]; if (wctomb (enough, L'A') != 1) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 /* We know the wchar_t encoding is ISO 10646. So pick a character which has a multibyte representation which does not fit. */ CHK_FAIL_START char smallbuf[2]; if (wctomb (smallbuf, L'\x100') != 2) FAIL (); CHK_FAIL_END #endif mbstate_t s; memset (&s, '\0', sizeof (s)); if (wcrtomb (enough, L'D', &s) != 1 || enough[0] != 'D') FAIL (); #if __USE_FORTIFY_LEVEL >= 1 /* We know the wchar_t encoding is ISO 10646. So pick a character which has a multibyte representation which does not fit. */ CHK_FAIL_START char smallbuf[2]; if (wcrtomb (smallbuf, L'\x100', &s) != 2) FAIL (); CHK_FAIL_END #endif wchar_t wenough[10]; memset (&s, '\0', sizeof (s)); const char *cp = "A"; if (mbsrtowcs (wenough, &cp, 10, &s) != 1 || wcscmp (wenough, L"A") != 0) FAIL (); cp = "BC"; if (mbsrtowcs (wenough, &cp, l0 + 10, &s) != 2 || wcscmp (wenough, L"BC") != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START wchar_t wsmallbuf[2]; cp = "ABC"; mbsrtowcs (wsmallbuf, &cp, 10, &s); CHK_FAIL_END #endif cp = "A"; if (mbstowcs (wenough, cp, 10) != 1 || wcscmp (wenough, L"A") != 0) FAIL (); cp = "DEF"; if (mbstowcs (wenough, cp, l0 + 10) != 3 || wcscmp (wenough, L"DEF") != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START wchar_t wsmallbuf[2]; cp = "ABC"; mbstowcs (wsmallbuf, cp, 10); CHK_FAIL_END #endif memset (&s, '\0', sizeof (s)); cp = "ABC"; wcscpy (wenough, L"DEF"); if (mbsnrtowcs (wenough, &cp, 1, 10, &s) != 1 || wcscmp (wenough, L"AEF") != 0) FAIL (); cp = "IJ"; if (mbsnrtowcs (wenough, &cp, 1, l0 + 10, &s) != 1 || wcscmp (wenough, L"IEF") != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START wchar_t wsmallbuf[2]; cp = "ABC"; mbsnrtowcs (wsmallbuf, &cp, 3, 10, &s); CHK_FAIL_END #endif memset (&s, '\0', sizeof (s)); const wchar_t *wcp = L"A"; if (wcsrtombs (enough, &wcp, 10, &s) != 1 || strcmp (enough, "A") != 0) FAIL (); wcp = L"BC"; if (wcsrtombs (enough, &wcp, l0 + 10, &s) != 2 || strcmp (enough, "BC") != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START char smallbuf[2]; wcp = L"ABC"; wcsrtombs (smallbuf, &wcp, 10, &s); CHK_FAIL_END #endif memset (enough, 'Z', sizeof (enough)); wcp = L"EF"; if (wcstombs (enough, wcp, 10) != 2 || strcmp (enough, "EF") != 0) FAIL (); wcp = L"G"; if (wcstombs (enough, wcp, l0 + 10) != 1 || strcmp (enough, "G") != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START char smallbuf[2]; wcp = L"ABC"; wcstombs (smallbuf, wcp, 10); CHK_FAIL_END #endif memset (&s, '\0', sizeof (s)); wcp = L"AB"; if (wcsnrtombs (enough, &wcp, 1, 10, &s) != 1 || strcmp (enough, "A") != 0) FAIL (); wcp = L"BCD"; if (wcsnrtombs (enough, &wcp, 1, l0 + 10, &s) != 1 || strcmp (enough, "B") != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START char smallbuf[2]; wcp = L"ABC"; wcsnrtombs (smallbuf, &wcp, 3, 10, &s); CHK_FAIL_END #endif }
/** * Duplicate a string. * * This is a GNU-compliant slibc extension. * * @param string The string to duplicate. * @return The new string. `NULL` is returned on error * and `errno` is set to indicate the error. * * @throws ENOMEM The process could not allocate sufficient amount of memory. * * @since Always. */ wchar_t* wcsdup(const wchar_t* string) { size_t n = wcslen(string) + 1; wchar_t* r = malloc(n * sizeof(char)); return r == NULL ? NULL : wmemcpy(r, string, n); }
UINT CIniFile::GetAllKeyWordsAndValues(const wchar_t *const pwchSection, std::map<std::wstring, std::wstring> &mKeyWordsAndValues) { assert(NULL != pwchSection); // 清空map mKeyWordsAndValues.erase(mKeyWordsAndValues.begin(), mKeyWordsAndValues.end()); const DWORD dwMaxSize(MAX_PATH*5); wchar_t wchAllKeyWordsAndValues[dwMaxSize]; wchar_t wchKeyWordAndValue[dwMaxSize]; wmemset(wchAllKeyWordsAndValues, L'\0', _countof(wchAllKeyWordsAndValues)); wmemset(wchKeyWordAndValue, L'\0', _countof(wchKeyWordAndValue)); DWORD dwReturn = GetSection(pwchSection, wchAllKeyWordsAndValues, dwMaxSize); if (L'\0' == wchAllKeyWordsAndValues[0]) { // 第一个等于L'\0' // 无该Section } else { // 第一个不等于L'\0' // 有该Section // 分离出有用信息 // 因为Section在数组中的存放形式为“KeyWord1=Value1”,“\0”,“KeyWord2=Value2”,“\0”,“\0”。 // 所以如果检测到连续两个0,则break int i(0); for (i=0; i<dwMaxSize; i++) { if (wchAllKeyWordsAndValues[i] == L'\0') { if (wchAllKeyWordsAndValues[i] == wchAllKeyWordsAndValues[i+1]) { break; } } } i++; // 将有用信息进行分解 const int nActualSize(i); int j(0); int nPos(0); for(j=0; j<nActualSize; j++) { wchKeyWordAndValue[nPos++] = wchAllKeyWordsAndValues[j]; if (wchAllKeyWordsAndValues[j] == L'\0') { std::wstring wstrKeyWord; std::wstring wstrValue; const wchar_t *pwchEqualSign = wcschr(wchKeyWordAndValue, L'='); const int nCopySize = pwchEqualSign - wchKeyWordAndValue; wchar_t *pwch = new wchar_t[nCopySize+1](); wmemcpy(pwch, wchKeyWordAndValue, nCopySize); wstrKeyWord = pwch; wstrValue = ++pwchEqualSign; if (NULL != pwch) { delete[] pwch; pwch = NULL; } mKeyWordsAndValues.insert(std::map<std::wstring, std::wstring>::value_type(wstrKeyWord, wstrValue)); wmemset(wchKeyWordAndValue, L'\0', _countof(wchKeyWordAndValue)); nPos = 0; } } } return mKeyWordsAndValues.size(); }
wchar_t *repl_wcs(const wchar_t *str, const wchar_t *old, const wchar_t *new_s) { /* Adjust each of the below values to suit your needs. */ /* Increment positions cache size initially by this number. */ size_t cache_sz_inc = 16; /* Thereafter, each time capacity needs to be increased, * multiply the increment by this factor. */ const size_t cache_sz_inc_factor = 3; /* But never increment capacity by more than this number. */ const size_t cache_sz_inc_max = 1048576; wchar_t *pret, *ret = NULL; const wchar_t *pstr2, *pstr = str; size_t i, count = 0; ptrdiff_t *pos_cache = NULL; size_t cache_sz = 0; size_t cpylen, orglen, retlen, newlen, oldlen = wcslen(old); /* Find all matches and cache their positions. */ while ((pstr2 = wcsstr(pstr, old)) != NULL) { count++; /* Increase the cache size when necessary. */ if (cache_sz < count) { cache_sz += cache_sz_inc; pos_cache = (ptrdiff_t*)realloc(pos_cache, sizeof(*pos_cache) * cache_sz); if (pos_cache == NULL) { goto end_repl_wcs; } cache_sz_inc *= cache_sz_inc_factor; if (cache_sz_inc > cache_sz_inc_max) { cache_sz_inc = cache_sz_inc_max; } } pos_cache[count-1] = pstr2 - str; pstr = pstr2 + oldlen; } orglen = pstr - str + wcslen(pstr); /* Allocate memory for the post-replacement string. */ if (count > 0) { newlen = wcslen(new_s); retlen = orglen + (newlen - oldlen) * count; } else retlen = orglen; ret = (wchar_t*)malloc((retlen + 1) * sizeof(wchar_t)); if (ret == NULL) { goto end_repl_wcs; } if (count == 0) { /* If no matches, then just duplicate the string. */ wcscpy(ret, str); } else { /* Otherwise, duplicate the string whilst performing * the replacements using the position cache. */ pret = ret; wmemcpy(pret, str, pos_cache[0]); pret += pos_cache[0]; for (i = 0; i < count; i++) { wmemcpy(pret, new_s, newlen); pret += newlen; pstr = str + pos_cache[i] + oldlen; cpylen = (i == count-1 ? orglen : pos_cache[i+1]) - pos_cache[i] - oldlen; wmemcpy(pret, pstr, cpylen); pret += cpylen; } ret[retlen] = L'\0'; } end_repl_wcs: /* Free the cache and return the post-replacement string, * which will be NULL in the event of an error. */ free(pos_cache); return ret; }
//线程静态函数 DWORD WINAPI CCommClient::StaticThreadFunc(LPVOID lpParam) { CCommClient *pChannel = (CCommClient*)lpParam; SOCKET ClientSocket = pChannel->m_socket; int bytesRecv = SOCKET_ERROR; TCHAR recvbuf[8192] = {0}; //接收区 DWORD dwPackteCount = 0; TCHAR *pDataBuff = NULL; //缓冲区 DWORD dwDataBuffLen = 0; //缓冲区长度 if(ClientSocket==NULL) { return 0; } while(!pChannel->StopIsSet()) { bytesRecv = recv( ClientSocket, (char*)recvbuf, 8192, 0 ); if( bytesRecv <= 0 ) //服务端断开连接 等待连接 { g_commLog.Trace(LOGL_TOP,LOGT_PROMPT, __TFILE__,__LINE__, _T("服务器断开连接 err:%d"), WSAGetLastError()); //这里崩溃,主动关闭内核的时候 pChannel->m_pfnDataHandler(_T("DISCONNECT"),10); ClientSocket = NULL; return 0; } #ifdef _UNICODE bytesRecv /= 2; //UNICODE下收到的字符数为字节数/2 if(pDataBuff == NULL) { pDataBuff = new TCHAR[bytesRecv]; wmemcpy(pDataBuff,recvbuf,bytesRecv); dwDataBuffLen = bytesRecv; } else { TCHAR *tmpBuff = new TCHAR[dwDataBuffLen]; wmemcpy(tmpBuff,pDataBuff,dwDataBuffLen); delete []pDataBuff; pDataBuff = new TCHAR[dwDataBuffLen + bytesRecv]; wmemcpy(pDataBuff,tmpBuff,dwDataBuffLen); delete []tmpBuff; wmemcpy(&(pDataBuff[dwDataBuffLen]),recvbuf,bytesRecv); dwDataBuffLen += bytesRecv; } //包处理 if(dwDataBuffLen<sizeof(DWORD)*2)continue; //小于最小包头不做如下处理 DWORD dwPacketSize = 0; //包大小 while(TRUE) { if(dwDataBuffLen == 0)break; //缓冲区没有数据 memcpy(&dwPacketSize,pDataBuff,sizeof(DWORD)); dwPacketSize /= 2; //UNICODE下接收到包的实际长度为收到的字符数*2 if(dwPacketSize > dwDataBuffLen) break; //包长度大于缓冲区长度不做处理 TCHAR *pData = new TCHAR[dwPacketSize]; //拼一个包 wmemcpy(pData,pDataBuff + 4,dwPacketSize - 4); pChannel->m_pfnDataHandler(pData,dwPacketSize - 4); delete []pData; TCHAR *tmpBuff = new TCHAR[dwDataBuffLen]; wmemcpy(tmpBuff,pDataBuff,dwDataBuffLen); delete []pDataBuff; pDataBuff = NULL; dwDataBuffLen = dwDataBuffLen - dwPacketSize; pDataBuff = new TCHAR[dwDataBuffLen]; wmemcpy(pDataBuff,&(tmpBuff[dwPacketSize]),dwDataBuffLen); delete []tmpBuff; dwPackteCount ++ ; //包计数器 } printf("总共收到数据包 %d\n",dwPackteCount); //包计数器 //Sleep(200); //线程切换 } #else if(pDataBuff == NULL) { pDataBuff = new TCHAR[bytesRecv]; memcpy(pDataBuff,recvbuf,bytesRecv); dwDataBuffLen = bytesRecv; } else { TCHAR *tmpBuff = new TCHAR[dwDataBuffLen]; memcpy(tmpBuff,pDataBuff,dwDataBuffLen); delete []pDataBuff; pDataBuff = new TCHAR[dwDataBuffLen + bytesRecv]; memcpy(pDataBuff,tmpBuff,dwDataBuffLen); delete []tmpBuff; memcpy(&(pDataBuff[dwDataBuffLen]),recvbuf,bytesRecv); dwDataBuffLen += bytesRecv; } //包处理 if(dwDataBuffLen<sizeof(DWORD)*2)continue; //小于最小包头不做如下处理 DWORD dwPacketSize = 0; //包大小 while(TRUE) { //if(dwDataBuffLen == 0)break; //缓冲区没有数据 memcpy((WCHAR*)&dwPacketSize,pDataBuff,sizeof(DWORD)); if(dwPacketSize > dwDataBuffLen) break; //包长度大于缓冲区长度不做处理 TCHAR *pData = new TCHAR[dwPacketSize]; //拼一个包 memcpy(pData,pDataBuff + 4,dwPacketSize); pChannel->m_pfnDataHandler(pData,dwPacketSize); delete []pData; TCHAR *tmpBuff = new TCHAR[dwDataBuffLen]; memcpy(tmpBuff,pDataBuff,dwDataBuffLen); delete []pDataBuff; pDataBuff = NULL; dwDataBuffLen = dwDataBuffLen - dwPacketSize; pDataBuff = new TCHAR[dwDataBuffLen]; memcpy(pDataBuff,&(tmpBuff[dwPacketSize]),dwDataBuffLen); delete []tmpBuff; dwPackteCount ++ ; //包计数器 } printf("总共收到数据包 %d\n",dwPackteCount); //包计数器 //Sleep(200); //线程切换 }
bool CHttp::BreakUrl () { wyWChar temp[1]; wyWChar *canonicalurl; DWORD requiredlen = 1; URL_COMPONENTS urlcmp; urlcmp.dwStructSize = sizeof(urlcmp); // when initialized with NULL, the members of the structure will contain the // pointer to a the first char within the string. NO DYNAMIC ALLOCATION IS DONE urlcmp.lpszScheme = NULL; urlcmp.lpszHostName = NULL; urlcmp.lpszUserName = NULL; urlcmp.lpszPassword = NULL; urlcmp.lpszUrlPath = NULL; urlcmp.lpszExtraInfo = NULL; // The following lines set which components will be displayed. urlcmp.dwSchemeLength = 1; urlcmp.dwHostNameLength = 1; urlcmp.dwUserNameLength = 1; urlcmp.dwPasswordLength = 1; urlcmp.dwUrlPathLength = 1; urlcmp.dwExtraInfoLength= 1; // Canonicalize URLs - remove unsafe chars // find out the space required InternetCanonicalizeUrl (m_url, temp, &requiredlen, 0); canonicalurl = new wyWChar[requiredlen + 1]; InternetCanonicalizeUrl (m_url, canonicalurl, &requiredlen, 0); canonicalurl[requiredlen] = 0; // delete the prev url buffer and copy the new contents delete[] m_url; m_url = new wyWChar[requiredlen + 1]; wcscpy (m_url, canonicalurl ); delete[] canonicalurl; if (!InternetCrackUrl (m_url, wcslen(m_url), 0, &urlcmp )) { return false; } else { if (urlcmp.lpszScheme != 0) { m_Protocol = new wyWChar[urlcmp.dwSchemeLength + 1]; wcsncpy(m_Protocol, urlcmp.lpszScheme, urlcmp.dwSchemeLength); m_Protocol[urlcmp.dwSchemeLength] = 0; } else m_Protocol = NULL; if (urlcmp.lpszHostName != 0) { m_HostName = new wyWChar[urlcmp.dwHostNameLength + 1]; wcsncpy(m_HostName, urlcmp.lpszHostName, urlcmp.dwHostNameLength); m_HostName[urlcmp.dwHostNameLength] = '\0'; } else m_HostName = NULL; m_Port = urlcmp.nPort; if (urlcmp.lpszUserName != 0) { m_UserName = new wyWChar[urlcmp.dwUserNameLength + 1]; wcsncpy(m_UserName, urlcmp.lpszUserName, urlcmp.dwUserNameLength); m_UserName[urlcmp.dwUserNameLength] = '\0'; } else m_UserName = NULL; if (urlcmp.lpszPassword != 0) { m_Password = new wyWChar[urlcmp.dwPasswordLength + 1]; wcsncpy(m_Password, urlcmp.lpszPassword, urlcmp.dwPasswordLength); m_Password[urlcmp.dwPasswordLength] = '\0'; } else m_Password = NULL; if (urlcmp.lpszUrlPath != 0) { m_FileName = new wyWChar[urlcmp.dwUrlPathLength + 1]; wcsncpy(m_FileName, urlcmp.lpszUrlPath, urlcmp.dwUrlPathLength); m_FileName[urlcmp.dwUrlPathLength] = NULL; } else m_FileName = NULL; // append querystring to urlpath if (m_FileName && urlcmp.lpszExtraInfo ) { wyWChar *temp = m_FileName; m_FileName = new wyWChar[urlcmp.dwUrlPathLength + urlcmp.dwExtraInfoLength + 1]; wmemcpy (m_FileName, urlcmp.lpszUrlPath, urlcmp.dwUrlPathLength ); wmemcpy (m_FileName + urlcmp.dwUrlPathLength, urlcmp.lpszExtraInfo, urlcmp.dwExtraInfoLength ); m_FileName[urlcmp.dwUrlPathLength + urlcmp.dwExtraInfoLength] = NULL; delete[] temp; } } return true; }
void Grabber::CopyGrabbedArea(int Append, int VerticalBlock) { if (GArea.X1 < 0) return; int X1,Y1,X2,Y2; X1=Min(GArea.X1,GArea.X2); X2=Max(GArea.X1,GArea.X2); Y1=Min(GArea.Y1,GArea.Y2); Y2=Max(GArea.Y1,GArea.Y2); int GWidth=X2-X1+1,GHeight=Y2-Y1+1; int BufSize=(GWidth+3)*GHeight; FAR_CHAR_INFO* CharBuf=new FAR_CHAR_INFO[BufSize], *PtrCharBuf; wchar_t *CopyBuf=(wchar_t *)xf_malloc(BufSize*sizeof(wchar_t)), *PtrCopyBuf; WORD Chr; GetText(X1,Y1,X2,Y2,CharBuf,BufSize*sizeof(FAR_CHAR_INFO)); *CopyBuf=0; PtrCharBuf=CharBuf; PtrCopyBuf=CopyBuf; for (int I=0; I<GHeight; I++) { if (I>0) { *PtrCopyBuf++=L'\r'; *PtrCopyBuf++=L'\n'; *PtrCopyBuf=0; } for (int J=0; J<GWidth; J++, ++PtrCharBuf) { WORD Chr2 = PtrCharBuf->Char; Chr=PtrCharBuf->Char; if (Opt.CleanAscii) { switch (Chr2) { case L'.': Chr=L'.'; break; case 0x07: Chr=L'*'; break; case 0x10: Chr=L'>'; break; case 0x11: Chr=L'<'; break; case 0x18: case 0x19: Chr=L'|'; break; case 0x1E: case 0x1F: Chr=L'X'; break; case 0xFF: Chr=L' '; break; default: if (Chr2 < 0x20) Chr=L'.'; else if (Chr2 < 0x100) Chr=Chr2; break; } } if (Opt.NoGraphics && Chr2 >=0xB3 && Chr2 <= 0xDA) { switch (Chr2) { case 0xB3: case 0xBA: Chr=L'|'; break; case 0xC4: Chr=L'-'; break; case 0xCD: Chr=L'='; break; default: Chr=L'+'; break; } } *PtrCopyBuf++=Chr; *PtrCopyBuf=0; } for (int K=StrLength(CopyBuf)-1; K>=0 && CopyBuf[K]==L' '; K--) CopyBuf[K]=0; PtrCopyBuf=CopyBuf+StrLength(CopyBuf); } Clipboard clip; if (clip.Open()) { if (Append) { wchar_t *AppendBuf=clip.Paste(); if (AppendBuf) { int add=0; size_t DataSize=StrLength(AppendBuf); if (AppendBuf[DataSize-1]!=L'\n') { add=2; } AppendBuf=(wchar_t *)xf_realloc(AppendBuf,(DataSize+BufSize+add)*sizeof(wchar_t)); wmemcpy(AppendBuf+DataSize+add,CopyBuf,BufSize); if (add) wmemcpy(AppendBuf+DataSize,L"\r\n",2); xf_free(CopyBuf); CopyBuf=AppendBuf; } } if (VerticalBlock) clip.CopyFormat(FAR_VerticalBlock_Unicode,CopyBuf); else clip.Copy(CopyBuf); clip.Close(); } if (CopyBuf) xf_free(CopyBuf); delete[] CharBuf; }
/** Parse a path producing the target device, device instance, and file path. It is the caller's responsibility to free() FullPath and MapPath when they are no longer needed. @param[in] path @param[out] FullPath @param[out] DevNode @param[out] Which @param[out] MapPath OPTIONAL. If not NULL, it points to the place to save a pointer to the extracted map name. If the path didn't have a map name, then *MapPath is set to NULL. @retval RETURN_SUCCESS The path was parsed successfully. @retval RETURN_NOT_FOUND The path does not map to a valid device. @retval RETURN_OUT_OF_RESOURCES Insufficient memory to calloc a MapName buffer. The errno variable is set to ENOMEM. @retval RETURN_INVALID_PARAMETER The path parameter is not valid. The errno variable is set to EINVAL. **/ RETURN_STATUS EFIAPI ParsePath( IN const char *path, OUT wchar_t **FullPath, OUT DeviceNode **DevNode, OUT int *Which, OUT wchar_t **MapPath ) { int MapLen; PATH_CLASS PathClass; wchar_t *NewPath; wchar_t *WPath = NULL; wchar_t *MPath = NULL; DeviceNode *Node = NULL; RETURN_STATUS Status = RETURN_NOT_FOUND; int Instance = 0; BOOLEAN ReMapped; ReMapped = FALSE; // Convert name from MBCS to WCS and change '/' to '\\' WPath = NormalizePath( path); PathClass = ClassifyPath(WPath, &NewPath, &MapLen); reclassify: switch(PathClass) { case PathMapping: if(!ReMapped) { if((NewPath == NULL) || (*NewPath == L'\0')) { /* Nothing after the ':' */ PathClass = PathAbsolute; } else { Instance = PathInstance(WPath, MapLen); PathClass = ClassifyPath(NewPath, NULL, NULL); } ReMapped = TRUE; if(WPath[MapLen] == L':') { // Get the Map Name, including the trailing ':'. */ MPath = calloc(MapLen+2, sizeof(wchar_t)); if(MPath != NULL) { wmemcpy(MPath, WPath, MapLen+1); } else { errno = ENOMEM; Status = RETURN_OUT_OF_RESOURCES; break; // Exit the switch(PathClass) statement. } } if(WPath != NewPath) { /* Shift the RHS of the path down to the start of the buffer. */ wmemmove(WPath, NewPath, wcslen(NewPath)+1); NewPath = WPath; } goto reclassify; } /* Fall through to PathError if Remapped. This means that the path looked like "foo:bar:something". */ case PathError: errno = EINVAL; Status = RETURN_INVALID_PARAMETER; break; case PathRelative: /* Transform a relative path into an Absolute path. Prepends CWD and handles ./ and ../ entries. It is the caller's responsibility to free the space allocated to WPath. */ WPath = PathAdjust(NewPath); // WPath was malloc()ed by PathAdjust case PathAbsolute: /* Perform any path aliasing. For example: /dev/foo -> { node.foo, "" } The current volume and directory are updated in the path as needed. It is the caller's responsibility to free the space allocated to WPath. */ Status = RETURN_SUCCESS; WPath = PathAlias(WPath, &Node); // PathAlias frees its argument and malloc()s a new one. break; } if(!RETURN_ERROR(Status)) { *FullPath = WPath; *Which = Instance; if(MapPath != NULL) { *MapPath = MPath; } else if(MPath != NULL) { free(MPath); /* Caller doesn't want it so let MPath go free */ } /* At this point, WPath is an absolute path, MPath is either NULL or points to the Map Name, and Instance is the instance number. */ if(MPath == NULL) { /* This is NOT a mapped path. */ if(Node == NULL) { Node = daDefaultDevice; } if(Node != NULL) { Status = RETURN_SUCCESS; } else { Status = RETURN_NOT_FOUND; } } else { /* This is a mapped path. */ Status = __DevSearch( MPath, NULL, &Node); if(Status == RETURN_NOT_FOUND) { Node = daDefaultDevice; if(Node != NULL) { Status = RETURN_SUCCESS; } } } if(DevNode != NULL) { *DevNode = Node; } } return Status; }
BOOL Set_ImgRes(INT nIdx) { TCHAR waMenuItemStr[BUF_LENGTH]; TCHAR waWidth[BUF_LENGTH], waHeight[BUF_LENGTH]; TCHAR* pwChar; ImageRes tIRes; g_ResIdx = nIdx; // Store the current resolution point globally g_hmnuCurr = (HMENU) SendMessage(g_hwndMenuBar, SHCMBM_GETSUBMENU, 0, IDM_SETTINGS); RemoveMenu(g_hmnuCurr, 12, MF_BYPOSITION); if(g_bVideoMode) { AppendMenu(g_hmnuCurr, MF_STRING | MF_POPUP, (UINT)g_ahmnuVdoColorFmts[nIdx], L"&ColorFmts"); g_hmnuCurr = g_ahmnuVdoColorFmts[nIdx]; CheckMenuRadioItem(g_hmnuCurr, 0, (g_nNoOfVdoCap-1), 0, MF_BYPOSITION); GetMenuString(g_hmnuCurr, 0, waMenuItemStr, BUF_LENGTH, MF_BYPOSITION); g_wsColorFmt = waMenuItemStr; g_hmnuCurr = g_hmnuVideoSub; CheckMenuRadioItem(g_hmnuCurr, 0, (g_nNoOfVdoCap-1), nIdx, MF_BYPOSITION); } else { AppendMenu(g_hmnuCurr, MF_STRING | MF_POPUP, (UINT)g_ahmnuStillColorFmts[nIdx], L"&ColorFmts"); g_hmnuCurr = g_ahmnuStillColorFmts[nIdx]; CheckMenuRadioItem(g_hmnuCurr, 0, (g_nNoOfStillCap-1), 0, MF_BYPOSITION); GetMenuString(g_hmnuCurr, 0, waMenuItemStr, BUF_LENGTH, MF_BYPOSITION); g_wsColorFmt = waMenuItemStr; g_hmnuCurr = g_hmnuStillSub; CheckMenuRadioItem(g_hmnuCurr, 0, (g_nNoOfStillCap-1), nIdx, MF_BYPOSITION); } GetMenuString(g_hmnuCurr, nIdx, waMenuItemStr, BUF_LENGTH, MF_BYPOSITION); OutputDebugString(waMenuItemStr); pwChar = wcsstr(waMenuItemStr, L"X"); wcscpy(waHeight, (pwChar+2)); wmemcpy(waWidth, waMenuItemStr, ((pwChar-1)-waMenuItemStr)); waWidth[(pwChar-1)-waMenuItemStr]='\0'; #ifdef DEBUG_MODE OutputDebugString(L"\n---------------------\n"); OutputDebugString(waMenuItemStr); OutputDebugString(L"\n|"); OutputDebugString(waWidth); OutputDebugString(L"|"); OutputDebugString(L"\n|"); OutputDebugString(waHeight); OutputDebugString(L"|\n---------------------"); #endif tIRes.nWidth = atoi(waWidth); tIRes.nHeight = _wtoi(waHeight); //tIRes.nHeight = atoi(waHeight); if(!((tIRes.nWidth==g_tImgRes.nWidth)&&(tIRes.nHeight==g_tImgRes.nHeight)&& (g_bVMod==g_bVideoMode))) { //Record the selected resolution gloablly g_tImgRes.nWidth = tIRes.nWidth; g_tImgRes.nHeight = tIRes.nHeight; g_bVMod = g_bVideoMode; //wsprintf(test, L"\nWidth :- %d Height :- %d", tIRes.nWidth, tIRes.nHeight); //OutputDebugString(test); //g_Prop.Set_Resolution(&tIRes, P); /* ImageRes ptRes; ptRes.nHeight=240; ptRes.nWidth=320; g_Prop.Set_Resolution(&ptRes, P); */ if(g_bVideoMode) g_Prop.Set_Resolution(&tIRes, V); else g_Prop.Set_Resolution(&tIRes, S); OutputDebugString(L"\n-----------Resolution Change OK-----------"); } else { OutputDebugString(L"\n-----------Same Resolution-----------"); } return TRUE; }
/* * The way windows takes environment variables is different than what C does; * Windows wants a contiguous block of null-terminated strings, terminated * with an additional null. * * Windows has a few "essential" environment variables. winsock will fail * to initialize if SYSTEMROOT is not defined; some APIs make reference to * TEMP. SYSTEMDRIVE is probably also important. We therefore ensure that * these get defined if the input environment block does not contain any * values for them. * * Also add variables known to Cygwin to be required for correct * subprocess operation in many cases: * https://github.com/Alexpux/Cygwin/blob/b266b04fbbd3a595f02ea149e4306d3ab9b1fe3d/winsup/cygwin/environ.cc#L955 * */ int make_program_env(char* env_block[], WCHAR** dst_ptr) { WCHAR* dst; WCHAR* ptr; char** env; size_t env_len = 0; int len; size_t i; DWORD var_size; size_t env_block_count = 1; /* 1 for null-terminator */ WCHAR* dst_copy; WCHAR** ptr_copy; WCHAR** env_copy; DWORD* required_vars_value_len = alloca(n_required_vars * sizeof(DWORD*)); /* first pass: determine size in UTF-16 */ for (env = env_block; *env; env++) { int len; if (strchr(*env, '=')) { len = MultiByteToWideChar(CP_UTF8, 0, *env, -1, NULL, 0); if (len <= 0) { return GetLastError(); } env_len += len; env_block_count++; } } /* second pass: copy to UTF-16 environment block */ dst_copy = (WCHAR*)uv__malloc(env_len * sizeof(WCHAR)); if (!dst_copy) { return ERROR_OUTOFMEMORY; } env_copy = alloca(env_block_count * sizeof(WCHAR*)); ptr = dst_copy; ptr_copy = env_copy; for (env = env_block; *env; env++) { if (strchr(*env, '=')) { len = MultiByteToWideChar(CP_UTF8, 0, *env, -1, ptr, (int) (env_len - (ptr - dst_copy))); if (len <= 0) { DWORD err = GetLastError(); uv__free(dst_copy); return err; } *ptr_copy++ = ptr; ptr += len; } } *ptr_copy = NULL; assert(env_len == ptr - dst_copy); /* sort our (UTF-16) copy */ qsort(env_copy, env_block_count-1, sizeof(wchar_t*), qsort_wcscmp); /* third pass: check for required variables */ for (ptr_copy = env_copy, i = 0; i < n_required_vars; ) { int cmp; if (!*ptr_copy) { cmp = -1; } else { cmp = env_strncmp(required_vars[i].wide_eq, required_vars[i].len, *ptr_copy); } if (cmp < 0) { /* missing required var */ var_size = GetEnvironmentVariableW(required_vars[i].wide, NULL, 0); required_vars_value_len[i] = var_size; if (var_size != 0) { env_len += required_vars[i].len; env_len += var_size; } i++; } else { ptr_copy++; if (cmp == 0) i++; } } /* final pass: copy, in sort order, and inserting required variables */ dst = uv__malloc((1+env_len) * sizeof(WCHAR)); if (!dst) { uv__free(dst_copy); return ERROR_OUTOFMEMORY; } for (ptr = dst, ptr_copy = env_copy, i = 0; *ptr_copy || i < n_required_vars; ptr += len) { int cmp; if (i >= n_required_vars) { cmp = 1; } else if (!*ptr_copy) { cmp = -1; } else { cmp = env_strncmp(required_vars[i].wide_eq, required_vars[i].len, *ptr_copy); } if (cmp < 0) { /* missing required var */ len = required_vars_value_len[i]; if (len) { wcscpy(ptr, required_vars[i].wide_eq); ptr += required_vars[i].len; var_size = GetEnvironmentVariableW(required_vars[i].wide, ptr, (int) (env_len - (ptr - dst))); if (var_size != len-1) { /* race condition? */ uv_fatal_error(GetLastError(), "GetEnvironmentVariableW"); } } i++; } else { /* copy var from env_block */ len = wcslen(*ptr_copy) + 1; wmemcpy(ptr, *ptr_copy, len); ptr_copy++; if (cmp == 0) i++; } } /* Terminate with an extra NULL. */ assert(env_len == (ptr - dst)); *ptr = L'\0'; uv__free(dst_copy); *dst_ptr = dst; return 0; }