/* Modified to work properly on ALL systems, not just UNIX */ int pvasprintf(char **ret, const char *fmt, va_list ap) { char *buf = NULL; size_t bufsize = 0; char *newbuf = NULL; size_t nextsize = 0; int outsize = 0; bufsize = 0; for (;;) { if (bufsize == 0) { if ((buf = (char *)malloc(FIRSTSIZE)) == NULL) { *ret = NULL; return -1; } bufsize = 1; } else if ((newbuf = (char *)realloc(buf, nextsize)) != NULL) { buf = newbuf; bufsize = nextsize; } else { free(buf); buf = NULL; *ret = NULL; return -1; } #ifdef _WINDOWS outsize = _vsnprintf(buf, bufsize, fmt, ap); #else { va_list copy; va_copy(copy, ap); outsize = vsnprintf(buf, bufsize, fmt, copy); va_end(copy); } #endif if (outsize == -1) { /* Clear indication that output was truncated, but no * clear indication of how big buffer needs to be, so * simply double existing buffer size for next time. */ nextsize = (int)bufsize * 2; } else if (outsize == (int)bufsize) { /* Output was truncated (since at least the \0 could * not fit), but no indication of how big the buffer * needs to be, so just double existing buffer size * for next time. */ nextsize = (int)bufsize * 2; } else if (outsize > (int)bufsize) { /* Output was truncated, but we were told exactly how * big the buffer needs to be next time. Add two chars * to the returned size. One for the \0, and one to * prevent ambiguity in the next case below. */ nextsize = outsize + 2; } else if (outsize == (int)bufsize - 1) { /* This is ambiguous. May mean that the output string * exactly fits, but on some systems the output string * may have been trucated. We can't tell. * Just double the buffer size for next time. */ nextsize = (int)bufsize * 2; } else { /* Output was not truncated */ break; } } *ret = buf; return (int)strlen(buf); }
IWindowLog* CLogWnd::AddMessage(LPCSTR fmt, ...) { //TODO: Add a way to free this up, later ! static char *fmt2 = NULL; static size_t fmt2_sz = 0; va_list vlist; // Get output string va_start(vlist, fmt); int retval; //size_t sz = strlen(fmt)+1; if(!fmt2) { fmt2_sz = 2048; fmt2 = (char*)malloc(fmt2_sz); } while((retval = _vsnprintf(fmt2, fmt2_sz, fmt, vlist)) < 0) // means there wasn't anough room { fmt2_sz *= 2; if(fmt2) free(fmt2); fmt2 = (char*)malloc(fmt2_sz); } #ifdef USEPLUGS m_pluglogstr.setValue(fmt2); #else m_lastlogstr = fmt2; CString strbuff(m_lastlogstr.c_str()); int pos, img; do { img = 0; // // Get a line // CString aaa = strbuff.SpanExcluding("\n"); // // Find a header // pos = aaa.Find(">>"); if(pos > 0) { CString header; header = aaa.Left(pos); aaa = aaa.Right(aaa.GetLength() - pos-2); img = GetImageId(header); } // // Insert it into the list of messages // if(aaa.GetLength() > 0) { CString bbb = aaa.SpanExcluding("||"); int ic = m_ListLog.GetItemCount(); m_ListLog.InsertItem(ic , bbb, img); // For now let's do it once... int subi = aaa.Find("||",0); if(subi >= 0) { bbb = aaa.Right(aaa.GetLength() - subi - 2); m_ListLog.SetItemText(ic, 1, bbb); } } // // Go to next one. // pos = strbuff.Find("\n",0); if(pos >= 0) { aaa = strbuff.Right(strbuff.GetLength() - pos-1); strbuff = aaa; } } while(pos >= 0); m_ListLog.EnsureVisible(m_ListLog.GetItemCount()-1, TRUE); #endif va_end(vlist); //PeekMyself(); return this; }
static void vprintf_stderr_common(const char* format, va_list args) { #if PLATFORM(MAC) if (strstr(format, "%@")) { CFStringRef cfFormat = CFStringCreateWithCString(NULL, format, kCFStringEncodingUTF8); CFStringRef str = CFStringCreateWithFormatAndArguments(NULL, NULL, cfFormat, args); int length = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8); char* buffer = (char*)malloc(length + 1); CFStringGetCString(str, buffer, length, kCFStringEncodingUTF8); fputs(buffer, stderr); free(buffer); CFRelease(str); CFRelease(cfFormat); } else #elif PLATFORM(BREWMP) // When str is 0, the return value is the number of bytes needed // to accept the result including null termination. int size = vsnprintf(0, 0, format, args); if (size > 0) { Vector<char> buffer(size); vsnprintf(buffer.data(), size, format, args); printLog(buffer); } #elif HAVE(ISDEBUGGERPRESENT) if (IsDebuggerPresent()) { size_t size = 1024; do { char* buffer = (char*)malloc(size); if (buffer == NULL) break; if (_vsnprintf(buffer, size, format, args) != -1) { #if OS(WINCE) // WinCE only supports wide chars wchar_t* wideBuffer = (wchar_t*)malloc(size * sizeof(wchar_t)); if (wideBuffer == NULL) break; for (unsigned int i = 0; i < size; ++i) { if (!(wideBuffer[i] = buffer[i])) break; } OutputDebugStringW(wideBuffer); free(wideBuffer); #else OutputDebugStringA(buffer); #endif free(buffer); break; } free(buffer); size *= 2; } while (size > 1024); } #endif #if OS(SYMBIAN) vfprintf(stdout, format, args); #else vfprintf(stderr, format, args); #endif }
static inline int vsnprintf(char *str, size_t size, const char *format, va_list ap) { return _vsnprintf(str, size, format, ap); }
int ftk_vsnprintf(char *str, size_t size, const char *format, va_list ap) { return _vsnprintf(str, size-1, format, ap); }
void log_it(VMINT level, char* fmt, va_list ap) { vm_time_t tm; VM_P_HANDLE phandle; char text[MAX_APP_NAME_LEN], level_text[10] = {0}; VMUINT written; memset(text, 0x00, sizeof(text)); memset(level_text, 0x00, sizeof(level_text)); switch(level) { case VM_DEBUG_LEVEL: strcpy(level_text, "DEBUG"); break; case VM_INFO_LEVEL: strcpy(level_text, "INFO"); break; case VM_WARN_LEVEL: strcpy(level_text, "WARN"); break; case VM_ERROR_LEVEL: strcpy(level_text, "ERROR"); break; default: strcpy(level_text, "FATAL"); break; }; vm_get_time(&tm); phandle = vm_pmng_get_current_handle_ignore_status(); sprintf(text, "%d-%02.2d-%02.2d %02.2d:%02.2d:%02.2d [%s][PID:%d][%s:%d]- ", tm.year, tm.mon, tm.day, tm.hour, tm.min, tm.sec, level_text, phandle, _modFile, _lineNo); //vsprintf(text + strlen(text), fmt, ap); #ifdef __MTK_TARGET__ vsnprintf(text + strlen(text), 150, fmt, ap); #else _vsnprintf(text + strlen(text), 150, fmt, ap); #endif strcat(text, "\n\0"); MMI_PRINT(MOD_MRE, TRACE_INFO,"%s", text); if(log_init && def_log_mtk == 1) { if (FS_Write(log_file, text, (VMUINT)strlen(text), &written) < 0) { FS_Close(log_file); log_init = 0; return; } if (FS_Commit(log_file) < 0) { FS_Close(log_file); log_init = 0; return; } } }
void FakeClientCommand (edict_t *fakeClient, const char *format, ...) { // the purpose of this function is to provide fakeclients (bots) with the same client // command-scripting advantages (putting multiple commands in one line between semicolons) // as real players. It is an improved version of botman's FakeClientCommand, in which you // supply directly the whole string as if you were typing it in the bot's "console". It // is supposed to work exactly like the pfnClientCommand (server-sided client command). va_list ap; static char command[256]; int start, stop, i, index, stringIndex = 0; if (FNullEnt (fakeClient)) return; // reliability check // concatenate all the arguments in one string va_start (ap, format); _vsnprintf (command, sizeof (command), format, ap); va_end (ap); if (IsNullString (command)) return; // if nothing in the command buffer, return g_isFakeCommand = true; // set the "fakeclient command" flag int length = strlen (command); // get the total length of the command string // process all individual commands (separated by a semicolon) one each a time while (stringIndex < length) { start = stringIndex; // save field start position (first character) while (stringIndex < length && command[stringIndex] != ';') stringIndex++; // reach end of field if (command[stringIndex - 1] == '\n') stop = stringIndex - 2; // discard any trailing '\n' if needed else stop = stringIndex - 1; // save field stop position (last character before semicolon or end) for (i = start; i <= stop; i++) g_fakeArgv[i - start] = command[i]; // store the field value in the g_fakeArgv global string g_fakeArgv[i - start] = 0; // terminate the string stringIndex++; // move the overall string index one step further to bypass the semicolon index = 0; g_fakeArgc = 0; // let's now parse that command and count the different arguments // count the number of arguments while (index < i - start) { while (index < i - start && g_fakeArgv[index] == ' ') index++; // ignore spaces // is this field a group of words between quotes or a single word ? if (g_fakeArgv[index] == '"') { index++; // move one step further to bypass the quote while (index < i - start && g_fakeArgv[index] != '"') index++; // reach end of field index++; // move one step further to bypass the quote } else while (index < i - start && g_fakeArgv[index] != ' ') index++; // this is a single word, so reach the end of field g_fakeArgc++; // we have processed one argument more } // tell now the MOD DLL to execute this ClientCommand... MDLL_ClientCommand (fakeClient); } g_fakeArgv[0] = 0; // when it's done, reset the g_fakeArgv field g_isFakeCommand = false; // reset the "fakeclient command" flag g_fakeArgc = 0; // and the argument count }
int md_vsnprintf(char *s, int n, const char *format, va_list ap) { return _vsnprintf(s, n, format, ap); }
int snprintf(char *output, size_t size, const char *format, ...) { va_list ap; va_start(ap, format); return _vsnprintf(output, size, format, ap); }
inline int rpsVSprintf(char (&buf)[N], const char *format, va_list vl) { return _vsnprintf(buf, N, format, vl); }
unsigned char logger_log (LOGGER_VOICE *p_pstLog, unsigned char p_ucLogLevel, char *p_pcMsg, ...) { unsigned char ucRet = 0x01; int iTemp, iLen; #if defined (WIN32) long lThreadID; #endif va_list args; if (p_ucLogLevel < p_pstLog->ucLogLevel || 0 == p_pcMsg) { return 0x00; } // ======================= // ** Lock share buffer ** // ======================= #if defined (WIN32) lThreadID = GetCurrentThreadId (); while (p_pstLog->hLock != lThreadID) { if (0 == p_pstLog->hLock) { // The return value must be same as previous value (0) else it might locked by other if (0 == InterlockedExchange (&(p_pstLog->hLock), lThreadID)) { break; } } else { SLEEP (1); } } #elif defined (LINUX) || defined (UCLINUX) if (0 != pthread_mutex_lock (&(p_pstLog->hLock))) { return 0x01; } #endif ftime (&(p_pstLog->stTime)); p_pstLog->pstTime = localtime (&(p_pstLog->stTime.time)); // Manually form the DateTime String (200% faster than sprintf) iTemp = (p_pstLog->pstTime)->tm_year + 1900; // Year iLen = (iTemp / 1000); p_pstLog->acLogDateTime [0] = '0' + iLen; iTemp = iTemp - (1000 * iLen); iLen = (iTemp / 100); p_pstLog->acLogDateTime [1] = '0' + iLen; iTemp = iTemp - (100 * iLen); iLen = (iTemp / 10); p_pstLog->acLogDateTime [2] = '0' + iLen; iTemp = iTemp - (10 * iLen); p_pstLog->acLogDateTime [3] = '0' + iTemp; p_pstLog->acLogDateTime [4] = '-'; iTemp = (p_pstLog->pstTime)->tm_mon + 1; // Month iLen = (iTemp / 10); p_pstLog->acLogDateTime [5] = '0' + iLen; iTemp = iTemp - (10 * iLen); p_pstLog->acLogDateTime [6] = '0' + iTemp; p_pstLog->acLogDateTime [7] = '-'; iTemp = (p_pstLog->pstTime)->tm_mday; // Day iLen = (iTemp / 10); p_pstLog->acLogDateTime [8] = '0' + iLen; iTemp = iTemp - (10 * iLen); p_pstLog->acLogDateTime [9] = '0' + iTemp; p_pstLog->acLogDateTime [10] = ' '; iTemp = (p_pstLog->pstTime)->tm_hour; // Hour iLen = (iTemp / 10); p_pstLog->acLogDateTime [11] = '0' + iLen; iTemp = iTemp - (10 * iLen); p_pstLog->acLogDateTime [12] = '0' + iTemp; p_pstLog->acLogDateTime [13] = ':'; iTemp = (p_pstLog->pstTime)->tm_min; // Minute iLen = (iTemp / 10); p_pstLog->acLogDateTime [14] = '0' + iLen; iTemp = iTemp - (10 * iLen); p_pstLog->acLogDateTime [15] = '0' + iTemp; p_pstLog->acLogDateTime [16] = ':'; iTemp = (p_pstLog->pstTime)->tm_sec; // Second iLen = (iTemp / 10); p_pstLog->acLogDateTime [17] = '0' + iLen; iTemp = iTemp - (10 * iLen); p_pstLog->acLogDateTime [18] = '0' + iTemp; p_pstLog->acLogDateTime [19] = '.'; iTemp = p_pstLog->stTime.millitm; // Millisecond iLen = (iTemp / 100) % 10; p_pstLog->acLogDateTime [20] = '0' + iLen; iTemp = iTemp - (100 * iLen); iLen = (iTemp / 10); p_pstLog->acLogDateTime [21] = '0' + iLen; iTemp = iTemp - (10 * iLen); p_pstLog->acLogDateTime [22] = '0' + iTemp; p_pstLog->acLogDateTime [23] = 0; if (0x00 == p_pstLog->ucHeader) { p_pstLog->ucHeader = 0x01; #if defined (WIN32) iTemp = sprintf (p_pstLog->acLogBuf, "-------Date Time------- -Thread- L Message - START %s\n\n%s 00000000:%08X %c ", p_pstLog->acLogDateTime, p_pstLog->acLogDateTime, GetCurrentThreadId (), g_acLogLevel [p_ucLogLevel]); #elif defined (LINUX) || defined (UCLINUX) iTemp = sprintf (p_pstLog->acLogBuf, "-------Date Time------- -Thread- L Message - START %s\n\n%s %08d:%08X %c ", p_pstLog->acLogDateTime, p_pstLog->acLogDateTime, getpid (), (unsigned int) pthread_self (), g_acLogLevel [p_ucLogLevel]); #endif } else { #if defined (WIN32) iTemp = sprintf (p_pstLog->acLogBuf, "%s 00000000:%08X %c ", p_pstLog->acLogDateTime, GetCurrentThreadId (), g_acLogLevel [p_ucLogLevel]); #elif defined (LINUX) || defined (UCLINUX) iTemp = sprintf (p_pstLog->acLogBuf, "%s %08d:%08X %c ", p_pstLog->acLogDateTime, getpid (), (unsigned int) pthread_self (), g_acLogLevel [p_ucLogLevel]); #endif } if (0 > iTemp) { ucRet = 0x02; goto CleanUp; } iLen = iTemp; va_start (args, p_pcMsg); #if defined (WIN32) iTemp = _vsnprintf (p_pstLog->acLogBuf + iLen, LOG_MESSAGE_BUFFER_SIZE - iLen, p_pcMsg, args); #elif defined (LINUX) || defined (UCLINUX) iTemp = vsnprintf (p_pstLog->acLogBuf + iLen, LOG_MESSAGE_BUFFER_SIZE - iLen, p_pcMsg, args); #endif va_end (args); if (0 > iTemp) { ucRet = 0x03; goto CleanUp; } // Mute if duplicated log message if (0x00 != p_pstLog->ucMute) { if (0 < p_pstLog->iMuteLen && iTemp == p_pstLog->iMuteLen) { if (0 == memcmp (p_pstLog->acLogBuf + iLen, p_pstLog->acLogMute, p_pstLog->iMuteLen)) { ucRet = 0x00; goto CleanUp; } } p_pstLog->iMuteLen = iTemp; memcpy (p_pstLog->acLogMute, p_pstLog->acLogBuf + iLen, p_pstLog->iMuteLen); } iLen += iTemp; p_pstLog->acLogBuf [iLen++] = '\n'; // =================== // ** Write to file ** // =================== if (0 != p_pstLog->ulFileSize && p_pstLog->ulFileSize < p_pstLog->ulCurSize) { logger_truncate_voice (p_pstLog); } else { if (0 == p_pstLog->pfdLog) { if (0 != p_pstLog->acLogFileName [0]) { // Open file FOPEN (p_pstLog->pfdLog, p_pstLog->acLogFileName, "a+"); if (0 == p_pstLog->pfdLog) { ucRet = 0x04; goto CleanUp; } fseek (p_pstLog->pfdLog, 0, SEEK_END); p_pstLog->ulCurSize = ftell (p_pstLog->pfdLog); } } } if (0 == p_pstLog->pfdLog) { ucRet = 0x04; goto CleanUp; } if (0x01 == p_pstLog->ucConsole) { fwrite (p_pstLog->acLogBuf, sizeof (char), iLen, stderr); // Print to console } iTemp = fwrite (p_pstLog->acLogBuf, sizeof (char), iLen, p_pstLog->pfdLog); if (iLen == iTemp) { p_pstLog->ulCurSize += iTemp; fflush (p_pstLog->pfdLog); } else { FCLOSE (p_pstLog->pfdLog); } ucRet = 0x00; CleanUp: #if defined (WIN32) lThreadID = (long) GetCurrentThreadId (); if (lThreadID == p_pstLog->hLock) { InterlockedExchange (&(p_pstLog->hLock), 0); } #elif defined (LINUX) || defined (UCLINUX) if (0 != pthread_mutex_unlock (&(p_pstLog->hLock))) { ucRet = 0x04; } #endif return ucRet; }
static int VPrintf(char* buffer, size_t count, const char* format, va_list argptr) { return _vsnprintf(buffer, count, format, argptr); }
/**************************************************************************** * * ROUTINE : xprintf * * INPUTS : const PB_INSTANCE *ppbi : Pointer to decoder instance. * long n_pixel : Offset into buffer to write text. * const char *format : Format string for print. * ... : Variable length argument list. * * OUTPUTS : None. * * RETURNS : int: Size (in bytes) of the formatted text. * * FUNCTION : Display a printf style message on the current video frame. * * SPECIAL NOTES : None. * ****************************************************************************/ int onyx_xprintf(unsigned char *ppbuffer, long n_pixel, long n_size, long n_stride, const char *format, ...) { BOOL b_rc; va_list arglist; HFONT hfont, hfonto; int rc = 0; char sz_formatted[256] = ""; unsigned char *p_dest = &ppbuffer[n_pixel]; #ifdef _WIN32_WCE // Set up temporary bitmap HDC hdc_memory = NULL; HBITMAP hbm_temp = NULL; HBITMAP hbm_orig = NULL; RECT rect; // Copy bitmap to video frame long x; long y; // Format text va_start(arglist, format); _vsnprintf(sz_formatted, sizeof(sz_formatted), format, arglist); va_end(arglist); rect.left = 0; rect.top = 0; rect.right = 8 * strlen(sz_formatted); rect.bottom = 8; hdc_memory = create_compatible_dc(NULL); if (hdc_memory == NULL) goto Exit; hbm_temp = create_bitmap(rect.right, rect.bottom, 1, 1, NULL); if (hbm_temp == NULL) goto Exit; hbm_orig = (HBITMAP)(select_object(hdc_memory, hbm_temp)); if (!hbm_orig) goto Exit; // Write text into bitmap // font? hfont = create_font(8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, VARIABLE_PITCH | FF_SWISS, ""); if (hfont == NULL) goto Exit; hfonto = (HFONT)(select_object(hdc_memory, hbm_temp)); if (!hfonto) goto Exit; select_object(hdc_memory, hfont); set_text_color(hdc_memory, 1); set_bk_color(hdc_memory, 0); set_bk_mode(hdc_memory, TRANSPARENT); b_rc = bit_blt(hdc_memory, rect.left, rect.top, rect.right, rect.bottom, hdc_memory, rect.left, rect.top, BLACKNESS); if (!b_rc) goto Exit; b_rc = ext_text_out(hdc_memory, 0, 0, ETO_CLIPPED, &rect, sz_formatted, strlen(sz_formatted), NULL); if (!b_rc) goto Exit; for (y = rect.top; y < rect.bottom; ++y) { for (x = rect.left; x < rect.right; ++x) { if (get_pixel(hdc_memory, x, rect.bottom - 1 - y)) p_dest[x] = 255; } p_dest += n_stride; } rc = strlen(sz_formatted); Exit: if (hbm_temp != NULL) { if (hbm_orig != NULL) { select_object(hdc_memory, hbm_orig); } delete_object(hbm_temp); } if (hfont != NULL) { if (hfonto != NULL) select_object(hdc_memory, hfonto); delete_object(hfont); } if (hdc_memory != NULL) delete_dc(hdc_memory); hdc_memory = 0; #endif return rc; }
int ProjectContextFormatString(char *outbuf, size_t outbuf_size, const char *fmt, va_list va) { int wroffs=0; while (*fmt && outbuf_size > 1) { char c = *fmt++; if (c != '%') { outbuf[wroffs++] = c; outbuf_size--; continue; } if (*fmt == '%') { outbuf[wroffs++] = '%'; outbuf_size--; fmt++; continue; } const char *ofmt = fmt-1; bool want_abort=false; int has_prec=0; int prec=0; if (*fmt == '.') { has_prec=1; fmt++; while (*fmt >= '0' && *fmt <= '9') prec = prec*10 + (*fmt++-'0'); if (*fmt != 'f' || prec < 0 || prec>20) { want_abort=true; } } else if (*fmt == '0') { has_prec=2; fmt++; while (*fmt >= '0' && *fmt <= '9') prec = prec*10 + (*fmt++-'0'); if (*fmt != 'x' && *fmt != 'X' && *fmt != 'd' && *fmt != 'u') { want_abort=true; } } c = *fmt++; if (!want_abort) switch (c) { case '@': case 'p': case 's': { const char *str=va_arg(va,const char *); const char qc = outbuf_size >= 3 && c != 's' ? getConfigStringQuoteChar(str) : ' '; if (qc != ' ') { outbuf[wroffs++] = qc ? qc : '`'; outbuf_size-=2; // will add trailing quote below } if (str) while (outbuf_size > 1 && *str) { char v = *str++; if (!qc && v == '`') v = '\''; outbuf[wroffs++] = v; outbuf_size--; } if (qc != ' ') { outbuf[wroffs++] = qc ? qc : '`'; // outbuf_size already decreased above } } break; case 'c': { int v = va_arg(va,int); outbuf[wroffs++] = v&0xff; outbuf_size--; } break; case 'd': { int v = va_arg(va,int); if (v<0) { outbuf[wroffs++] = '-'; outbuf_size--; v=-v; // this won't handle -2147483648 right, todo special case? } char tab[32]; int x=0; do { tab[x++] = v%10; v/=10; } while (v); if (has_prec == 2) while (x<prec) { tab[x++] = 0; } while (--x >= 0 && outbuf_size>1) { outbuf[wroffs++] = '0' + tab[x]; outbuf_size--; } } break; case 'u': { unsigned int v = va_arg(va,unsigned int); char tab[32]; int x=0; do { tab[x++] = v%10; v/=10; } while (v); if (has_prec == 2) while (x<prec) { tab[x++] = 0; } while (--x >= 0 && outbuf_size>1) { outbuf[wroffs++] = '0' + tab[x]; outbuf_size--; } } break; case 'x': case 'X': { const char base = (c - 'x') + 'a'; unsigned int v = va_arg(va,unsigned int); char tab[32]; int x=0; do { tab[x++] = v&0xf; v>>=4; } while (v); if (has_prec == 2) while (x<prec) { tab[x++] = 0; } while (--x >= 0 && outbuf_size>1) { if (tab[x] < 10) outbuf[wroffs++] = '0' + tab[x]; else outbuf[wroffs++] = base + tab[x] - 10; outbuf_size--; } } break; case 'f': { double v = va_arg(va,double); if (outbuf_size<64) { char tmp[64]; projectcontext_fastDoubleToString(v,tmp,has_prec?prec:6); const char *str = tmp; while (outbuf_size > 1 && *str) { outbuf[wroffs++] = *str++; outbuf_size--; } } else { const char *p=projectcontext_fastDoubleToString(v,outbuf+wroffs,has_prec?prec:6); int amt = (int) (p-(outbuf+wroffs)); wroffs += amt; outbuf_size-=amt; } } break; default: want_abort=true; break; } if (want_abort) { #if defined(_WIN32) && defined(_DEBUG) OutputDebugString("ProjectContextFormatString(): falling back to stock vsnprintf because of:"); OutputDebugString(ofmt); #endif fmt=ofmt; break; } } outbuf += wroffs; outbuf[0] = 0; if (outbuf_size<2||!*fmt) return wroffs; #if defined(_WIN32) && defined(_MSC_VER) const int l = _vsnprintf(outbuf,outbuf_size,fmt,va); // _vsnprintf() does not always null terminate if (l < 0 || l >= (int)outbuf_size) { outbuf[outbuf_size-1] = 0; return wroffs + (int)strlen(outbuf); } #else // vsnprintf() on non-win32, always null terminates const int l = vsnprintf(outbuf,outbuf_size,fmt,va); if (l >= (int)outbuf_size-1) return wroffs + (int)outbuf_size-1; #endif return wroffs+l; }
void CDynPatcher::Error(const char *File, const char *Func, int Line, bool IsCritical, char *Fmt, ...) { static char Buff[0x1000]; int len=0; len+=_snprintf(&Buff[len],sizeof(Buff)-len-1,"[CDynPatcher] %serror",IsCritical?"critical":""); if(File&&Func&&Line&&strlen(File)<MAX_PATH&&strlen(Func)<300) { len+=_snprintf(&Buff[len],sizeof(Buff)-len-1," at %s(%s:%i)",CSectionData::GetFileName(File),Func,Line); } len+=_snprintf(&Buff[len],sizeof(Buff)-len-1,":"); va_list marker; if(!Fmt) { len+=_snprintf(&Buff[len],sizeof(Buff)-len-1,"(NO DESCRIPTION)\r\n"); } else { va_start( marker, Fmt ); len+=_vsnprintf(&Buff[len],sizeof(Buff)-len-1, Fmt, marker ); } len+=_snprintf(&Buff[len],sizeof(Buff)-len-1,"\r\n"); printf("%s",Buff); if(IsCritical) { #ifdef WIN32 __asm{int 3}; if(!IsDebuggerPresent()) { exit(0); } #else exit(0); #endif } } void CDynPatcher::Message(const char *File, const char *Func, int Line, char *Fmt, ...) { static char Buff[0x1000]; int len=0; len+=_snprintf(&Buff[len],sizeof(Buff)-len-1,"[CDynPatcher]"); if(File&&Func&&Line&&strlen(File)<MAX_PATH&&strlen(Func)<300) { len+=_snprintf(&Buff[len],sizeof(Buff)-len-1," at %s(%s:%i)",CSectionData::GetFileName(File),Func,Line); } len+=_snprintf(&Buff[len],sizeof(Buff)-len-1,":"); va_list marker; if(!Fmt) { len+=_snprintf(&Buff[len],sizeof(Buff)-len-1,"(NO DESCRIPTION)\r\n"); } else { va_start( marker, Fmt ); len+=_vsnprintf(&Buff[len],sizeof(Buff)-len-1, Fmt, marker ); } len+=_snprintf(&Buff[len],sizeof(Buff)-len-1,"\r\n"); printf("%s",Buff); } bool CDynPatcher::Init(const char *LibName,bool ForceLoad) { if (!LibName) { szLibName = "<<===NO LIBRARY NAME===>>"; return false; } if(!LoadLib(LibName,ForceLoad)) { DynErr(false,"Unable to load \"%s\"",LibName); return false; } #ifdef WIN32 if(!ParseGenericDllData_PE()) { DynErr(false,"Failed to parse \"%s\"",szLibName); return false; } DynMsg("\"%s\" parsed",szLibName); #else FILE *fl = fopen(szLibName, "rb"); int LibSize; void* LibBuf; if (fl == NULL) { DynErr(false,"Failed to open '%s' for read\n", szLibName); return false; } fseek(fl, 0, SEEK_END); LibSize = ftell(fl); fseek(fl, 0, SEEK_SET); if (LibSize < 0) LibSize = 0; LibBuf = malloc(LibSize + 4); fread(LibBuf, 1, LibSize, fl); fclose(fl); if(!ParseGenericDllData_ELF(LibBuf, LibSize)) { DynErr(false,"Failed to parse \"%s\"",szLibName); return false; } #endif return true; } bool CDynPatcher::Init(const wchar_t *LibName, bool ForceLoad /*= false*/) { return 0; static char UTF8LibName[MAX_PATH]; //Q_UnicodeToUTF8(LibName, UTF8LibName, MAX_PATH-1); return Init(UTF8LibName, ForceLoad); } bool CDynPatcher::Init(void *FuncAddr) { char szTmpName[400]; sprintf(szTmpName, "Unk_load_by_func_addr_%p", FuncAddr); szLibName = new char[strlen(szTmpName) + 1]; strcpy(szLibName, szTmpName); bSelfLoaded = false; #ifdef _WIN32 MEMORY_BASIC_INFORMATION mem; VirtualQuery(FuncAddr, &mem, sizeof(mem)); szTmpName[0] = 0; GetModuleFileNameA(reinterpret_cast<HMODULE>(mem.AllocationBase ), szTmpName, sizeof(szTmpName) - 1); if (szTmpName[0] != 0) { delete[]szLibName; szLibName = new char[strlen(CSectionData::GetFileName(szTmpName)) + 1]; strcpy(szLibName, CSectionData::GetFileName(szTmpName)); } IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER*)mem.AllocationBase; IMAGE_NT_HEADERS *pe = (IMAGE_NT_HEADERS*)((unsigned long)dos + (unsigned long)dos->e_lfanew); if (pe->Signature == IMAGE_NT_SIGNATURE) { this->DllHandler = mem.AllocationBase; if (!ParseGenericDllData_PE()) { DynErr(false, "Failed to parse \"%s\"", szLibName); return false; } DynMsg("\"%s\" parsed",szLibName); } #else Dl_info info; if (dladdr(FuncAddr, &info) && info.dli_fbase &&info.dli_fname) { delete [] szLibName; szLibName = new char[strlen(info.dli_fname) + 1]; strcpy(szLibName, info.dli_fname); bool ParseOK=false; size_t LoadLibSize=0; DllBase = info.dli_fbase; LoadLibSize = (size_t)GetBaseLen(DllBase); DllHandler = dlopen(info.dli_fname, RTLD_NOW); dlclose(DllHandler); DynMsg("Found library \"%s\" at addr %p. Base=%p, size=%x, handler=%p",szLibName,FuncAddr,DllBase,LoadLibSize,DllHandler); FILE *fl = fopen(szLibName, "rb"); int LibSize; void* LibBuf; if (fl) { fseek(fl, 0, SEEK_END); LibSize = ftell(fl); fseek(fl, 0, SEEK_SET); DynMsg("Reading \"%s\" as file. Size=%x",szLibName,LibSize); if (LibSize < 0) LibSize = 0; LibBuf = malloc(LibSize + 4); fread(LibBuf, 1, LibSize, fl); fclose(fl); ParseOK=ParseGenericDllData_ELF(LibBuf, LibSize); free(LibBuf); } else { DynMsg("Unable to read \"%s\" as file. Trying to use information from Dl_info.",szLibName); ParseOK=ParseGenericDllData_ELF(DllBase, LoadLibSize); } if (!ParseOK) { DynErr(false, "Failed to parse \"%s\"", szLibName); return false; } } #endif else { DynErr(false, "Failed find library at %p",FuncAddr); return false; } return true; }
MyWin32Error::MyWin32Error(const char *format, uint32 err, ...) : mWin32Error(err) { char szError[1024]; char szTemp[1024]; va_list val; va_start(val, err); szError[(sizeof szError)-1] = 0; _vsnprintf(szError, (sizeof szError)-1, format, val); va_end(val); // Determine the position of the last %s, and escape everything else. This doesn't // track escaped % signs properly, but it works for the strings that we receive (and at // worst just produces a funny message). const char *keep = strstr(szError, "%s"); if (keep) { for(;;) { const char *test = strstr(keep + 1, "%s"); if (!test) break; keep = test; } } char *t = szTemp; char *end = szTemp + (sizeof szTemp) - 1; const char *s = szError; while(char c = *s++) { if (c == '%') { // We allow one %s to go through. Everything else gets escaped. if (s-1 != keep) { if (t >= end) break; *t++ = '%'; } } if (t >= end) break; *t++ = c; } *t = 0; if (!FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), szError, sizeof szError, NULL)) { szError[0] = 0; } if (szError[0]) { long l = strlen(szError); if (l>1 && szError[l-2] == '\r') szError[l-2] = 0; else if (szError[l-1] == '\n') szError[l-1] = 0; } setf(szTemp, szError); }
void CSyslog::_log(PHRASEA_LOG_LEVEL level, PHRASEA_LOG_CATEGORY category, TCHAR *fmt, ...) //void CSyslog::_log(PHRASEA_LOG_LEVEL level, PHRASEA_LOG_CATEGORY category, const char *fmt, ...) { extern int debug_flag; if(!(debug_flag & (1<<level))) return; va_list vl; char buff[5000]; va_start(vl, fmt); #ifdef UNICODE _vsnwprintf(buff, 5000, fmt, vl); #else _vsnprintf(buff, 5000, fmt, vl); #endif // printf("%s\n", buff); if(where == TOLOG) { if(!this->hEventLog) return; const TCHAR *aInsertions[] = { buff }; switch(level) { case CSyslog::LOGL_PARSE: case CSyslog::LOGL_SQLOK: case CSyslog::LOGL_ALLOC: ReportEvent( this->hEventLog, // Handle to the eventlog EVENTLOG_INFORMATION_TYPE, // Type of event this->category[category], // Category (could also be 0) EVENT_ALL, // Event id NULL, // User's sid (NULL for none) 1, // Number of insertion strings 0, // Number of additional bytes aInsertions, // Array of insertion strings NULL // Pointer to additional bytes ); break; case CSyslog::LOGL_RECORD: case CSyslog::LOGL_THESAURUS: case CSyslog::LOGL_INFO: ReportEvent( this->hEventLog, // Handle to the eventlog EVENTLOG_WARNING_TYPE, // Type of event this->category[category], // Category (could also be 0) EVENT_ALL, // Event id NULL, // User's sid (NULL for none) 1, // Number of insertion strings 0, // Number of additional bytes aInsertions, // Array of insertion strings NULL // Pointer to additional bytes ); break; case CSyslog::LOGL_ERR: ReportEvent( this->hEventLog, // Handle to the eventlog EVENTLOG_ERROR_TYPE, // Type of event this->category[category], // Category (could also be 0) EVENT_ALL, // Event id NULL, // User's sid (NULL for none) 1, // Number of insertion strings 0, // Number of additional bytes aInsertions, // Array of insertion strings NULL // Pointer to additional bytes ); break; default: break; } } else { // TOTTY printf("[%s].[%s] :\n%s\n", this->libLevel[level], this->libCategory[category], buff); // printf("%s\n", buff); } }
/* * Just like JLI_ReportErrorMessage, except that it concatenates the system * error message if any, its upto the calling routine to correctly * format the separation of the messages. */ void JLI_ReportErrorMessageSys(const char *fmt, ...) { va_list vl; int save_errno = errno; DWORD errval; jboolean freeit = JNI_FALSE; char *errtext = NULL; va_start(vl, fmt); if ((errval = GetLastError()) != 0) { /* Platform SDK / DOS Error */ int n = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM| FORMAT_MESSAGE_IGNORE_INSERTS|FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, errval, 0, (LPTSTR)&errtext, 0, NULL); if (errtext == NULL || n == 0) { /* Paranoia check */ errtext = ""; n = 0; } else { freeit = JNI_TRUE; if (n > 2) { /* Drop final CR, LF */ if (errtext[n - 1] == '\n') n--; if (errtext[n - 1] == '\r') n--; errtext[n] = '\0'; } } } else { /* C runtime error that has no corresponding DOS error code */ errtext = strerror(save_errno); } if (IsJavaw()) { char *message; int mlen; /* get the length of the string we need */ int len = mlen = _vscprintf(fmt, vl) + 1; if (freeit) { mlen += (int)JLI_StrLen(errtext); } message = (char *)JLI_MemAlloc(mlen); _vsnprintf(message, len, fmt, vl); message[len]='\0'; if (freeit) { JLI_StrCat(message, errtext); } MessageBox(NULL, message, "Java Virtual Machine Launcher", (MB_OK|MB_ICONSTOP|MB_APPLMODAL)); JLI_MemFree(message); } else { vfprintf(stderr, fmt, vl); if (freeit) { fprintf(stderr, "%s", errtext); } } if (freeit) { (void)LocalFree((HLOCAL)errtext); } va_end(vl); }
static void vprintf_stderr_common(const char* format, va_list args) { #if USE(CF) && !OS(WIN) if (strstr(format, "%@")) { CFStringRef cfFormat = CFStringCreateWithCString(NULL, format, kCFStringEncodingUTF8); #if COMPILER(CLANG) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wformat-nonliteral" #endif CFStringRef str = CFStringCreateWithFormatAndArguments(NULL, NULL, cfFormat, args); #if COMPILER(CLANG) #pragma clang diagnostic pop #endif CFIndex length = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8); char* buffer = (char*)malloc(length + 1); CFStringGetCString(str, buffer, length, kCFStringEncodingUTF8); #if USE(APPLE_SYSTEM_LOG) asl_log(0, 0, ASL_LEVEL_NOTICE, "%s", buffer); #endif fputs(buffer, stderr); free(buffer); CFRelease(str); CFRelease(cfFormat); return; } #if USE(APPLE_SYSTEM_LOG) va_list copyOfArgs; va_copy(copyOfArgs, args); asl_vlog(0, 0, ASL_LEVEL_NOTICE, format, copyOfArgs); va_end(copyOfArgs); #endif // Fall through to write to stderr in the same manner as other platforms. #elif OS(ANDROID) __android_log_vprint(ANDROID_LOG_WARN, "WebKit", format, args); #elif HAVE(ISDEBUGGERPRESENT) if (IsDebuggerPresent()) { size_t size = 1024; do { char* buffer = (char*)malloc(size); if (buffer == NULL) break; if (_vsnprintf(buffer, size, format, args) != -1) { #if 1 // def MINIBLINK_NOT_IMPLEMENTED int cbMultiByte = (int)strlen(buffer); DWORD dwMinSize = MultiByteToWideChar(CP_UTF8, 0, buffer, cbMultiByte, NULL, 0); WCHAR* wbuffer = (WCHAR*)malloc((dwMinSize + 1) * sizeof(WCHAR)); memset(wbuffer, 0, (dwMinSize + 1) * sizeof(WCHAR)); MultiByteToWideChar(CP_UTF8, 0, buffer, cbMultiByte, wbuffer, dwMinSize); OutputDebugStringW(wbuffer); free(wbuffer); #else String utf8 = String::fromUTF8(buffer); OutputDebugStringW(utf8.charactersWithNullTermination().data()); #endif // MINIBLINK_NOT_IMPLEMENTED free(buffer); break; } free(buffer); size *= 2; } while (size > 1024); } #endif vfprintf(stderr, format, args); }
/** * @brief Provides a basic logging facility for Protlib that uses the typical logging levels * to allow different levels for logging and run-time debugging of protolib applications. */ void PLOG(ProtoDebugLevel level, const char *format, ...) { if (((unsigned int)level <= DebugLevel()) || (PL_ALWAYS == level)) { va_list args; va_start(args, format); const char * header = ""; switch(level) { // Print out the Logging Type before the message case PL_FATAL: header = "Proto Fatal: "; break; case PL_ERROR: header = "Proto Error: "; break; case PL_WARN: header = "Proto Warn: "; break; case PL_INFO: header = "Proto Info: "; break; case PL_DEBUG: header = "Proto Debug: "; break; case PL_TRACE: header = "Proto Trace: "; break; case PL_DETAIL: header = "Proto Detail: "; break; case PL_MAX: header = "Proto Max: "; break; default: break; } size_t headerLen = strlen(header); FILE* debugLog = DebugLog(); #ifdef _WIN32_WCE if (debug_window.IsOpen() && !debug_pipe.IsOpen() && ((stderr == debugLog) || (stdout == debugLog))) { char charBuffer[8192]; charBuffer[8192] = '\0'; int count = _vsnprintf(charBuffer, 8191, format, args); #ifdef _UNICODE wchar_t wideBuffer[8192]; count = mbstowcs(wideBuffer, charBuffer, count); count *= sizeof(wchar_t); const char* theBuffer = (char*)wideBuffer; #else const char* theBuffer = charBuffer; #endif // if/else _UNICODE debug_window.Print(theBuffer, count); } else #endif // _WIN32_WCE #ifndef SIMULATE if (debug_pipe.IsOpen()) #else if (false)//always fails for simulation #endif // if/else n SIMULATE { char buffer[8192]; buffer[8191] = '\0'; #ifdef _WIN32_WCE unsigned int count = (unsigned int)_vsnprintf(buffer, 8191, format, args) + 1; #else #ifdef WIN32 strcpy(buffer, header); unsigned int count = (unsigned int)_vsnprintf(buffer + headerLen, 8191-headerLen, format, args) + 1; count += (unsigned int)headerLen; #else strcpy(buffer, header); unsigned int count = (unsigned int)vsnprintf(buffer + headerLen, 8191-headerLen, format, args) + 1; count += headerLen; #endif #endif // if/else _WIN32_WCE if (count > 8192) count = 8192; #ifndef SIMULATE if (!debug_pipe.Send(buffer, count)) #else if (true) #endif //if/else n SIMULATE { // We have no recourse but to go to stderr here fprintf(stderr, "PLOG() error: unable to send to debug pipe!!!\n"); vfprintf(stderr, format, args); fflush(stderr); } } else { #ifdef __ANDROID__ android_LogPriority prio; switch(level) { case PL_FATAL: prio = ANDROID_LOG_FATAL; break; case PL_ERROR: prio = ANDROID_LOG_ERROR; break; case PL_WARN: prio = ANDROID_LOG_WARN; break; case PL_INFO: prio = ANDROID_LOG_INFO; break; case PL_DEBUG: prio = ANDROID_LOG_DEBUG; break; case PL_TRACE: prio = ANDROID_LOG_VERBOSE; case PL_DETAIL: /* explicit fallthrough */ case PL_MAX: /* explicit fallthrough */ case PL_ALWAYS: /* explicit fallthrough */ default: prio = ANDROID_LOG_DEFAULT; break; } __android_log_vprint(prio, "protolib", format, args); #else fprintf(debugLog, "%s", header); vfprintf(debugLog, format, args); fflush(debugLog); #endif } va_end(args); } } // End PLOG
void CGString::FormatV(LPCTSTR pszFormat, va_list args) { TemporaryString pszTemp; _vsnprintf(static_cast<char *>(pszTemp), pszTemp.realLength(), pszFormat, args); Copy(pszTemp); }
int __cdecl __mingw_vsnprintf (char * s, size_t n, const char * format, va_list arg) { return _vsnprintf(s, n, format, arg); }
inline int OutputDebugStringF(const char* pszFormat, ...) { int ret = 0; if (fPrintToConsole) { // print to console va_list arg_ptr; va_start(arg_ptr, pszFormat); ret = vprintf(pszFormat, arg_ptr); va_end(arg_ptr); } else { // print to debug.log static FILE* fileout = NULL; if (!fileout) { char pszFile[MAX_PATH+100]; GetDataDir(pszFile); strlcat(pszFile, "/debug.log", sizeof(pszFile)); fileout = fopen(pszFile, "a"); if (fileout) setbuf(fileout, NULL); // unbuffered } if (fileout) { //// Debug print useful for profiling //fprintf(fileout, " %"PRI64d" ", GetTimeMillis()); va_list arg_ptr; va_start(arg_ptr, pszFormat); ret = vfprintf(fileout, pszFormat, arg_ptr); va_end(arg_ptr); } } #ifdef __WXMSW__ if (fPrintToDebugger) { static CCriticalSection cs_OutputDebugStringF; // accumulate a line at a time CRITICAL_BLOCK(cs_OutputDebugStringF) { static char pszBuffer[50000]; static char* pend; if (pend == NULL) pend = pszBuffer; va_list arg_ptr; va_start(arg_ptr, pszFormat); int limit = END(pszBuffer) - pend - 2; int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr); va_end(arg_ptr); if (ret < 0 || ret >= limit) { pend = END(pszBuffer) - 2; *pend++ = '\n'; } else pend += ret; *pend = '\0'; char* p1 = pszBuffer; char* p2; while (p2 = strchr(p1, '\n')) { p2++; char c = *p2; *p2 = '\0'; OutputDebugStringA(p1); *p2 = c; p1 = p2; } if (p1 != pszBuffer) memmove(pszBuffer, p1, pend - p1 + 1); pend -= (p1 - pszBuffer); } } #endif return ret; }
/** * Logging function. * * We provide a timestamp from hours to milliseconds, which can be * used to help with performance, and to detect large, unexpected * idle times. The filename and line number in the source code is * provided. GetLastError or errno may offer a hint about a problem * with a system call, but be careful, since it's not cleared and so * it may report a message that has nothing to do with the current * calls, or anything going on in the DSM. The id of the thread that * called us is useful for finding problems with unsafe use, or use * that crosses thread boundaries in a bad way (like on Windows, when * one has to stay in the same thread as the HWND if the DAT_NULL * messages are going to work)... */ void CTwnDsmLog::Log(const int _doassert, const char* const _file, const int _line, const char* const _format, ...) { // We've nothing to do, so bail... if (0 == m_ptwndsmlogimpl->pod.m_logpath[0]) { return; } // Okay, now use the stack... UINT nError; UINT nChars; char *message; const char *file; // Grab the system error, this can be really useful... #if (TWNDSM_CMP == TWNDSM_CMP_VISUALCPP) nError = GetLastError(); if (nError == 0) { // Yeah, yeah...this is dumb, but I like a clean prefast log... :) nError = 0; } #elif (TWNDSM_CMP == TWNDSM_CMP_GNUGPP) nError = errno; #else #error Sorry, we do not recognize this system... #endif // If we have no log yet, try to get one... if (0 == m_ptwndsmlogimpl->pod.m_plog) { FOPEN(m_ptwndsmlogimpl->pod.m_plog,m_ptwndsmlogimpl->pod.m_logpath,m_ptwndsmlogimpl->pod.m_logmode); if (0 == m_ptwndsmlogimpl->pod.m_plog) { fprintf(stderr,"DSM: Error - logging has been disabled because logfile could not be opened: %s,%s\r\n",m_ptwndsmlogimpl->pod.m_logpath,m_ptwndsmlogimpl->pod.m_logmode); m_ptwndsmlogimpl->pod.m_logpath[0] = 0; } return; } // Trim the filename down to just the filename, no path... file = 0; #if (TWNDSM_CMP == TWNDSM_CMP_VISUALCPP) // Only look for this on Windows... file = strrchr(_file,'\\'); #endif if (!file) { // If we didn't find a backslash, try a forward slash... file = strrchr(_file,'/'); } if (file) { // skip the slash... file = &file[1]; } else { // Couldn't find any slashes... file = (char*)_file; } // Build the message header... #if (TWNDSM_CMP == TWNDSM_CMP_VISUALCPP) SYSTEMTIME st; GetLocalTime(&st); nChars = SNPRINTF(m_ptwndsmlogimpl->pod.m_message, TWNDSM_MAX_MSG, #if (TWNDSM_CMP_VERSION >= 1400) TWNDSM_MAX_MSG, #endif "[%02d%02d%02d%03d %-8s %4d %5d %p] ", st.wHour,st.wMinute,st.wSecond,st.wMilliseconds, file,_line, nError, (void*)(UINT_PTR)GETTHREADID()); #elif (TWNDSM_CMP == TWNDSM_CMP_GNUGPP) timeval tv; tm tm; gettimeofday(&tv,NULL); tzset(); localtime_r(&tv.tv_sec,&tm); nChars = SNPRINTF(m_ptwndsmlogimpl->pod.m_message, TWNDSM_MAX_MSG, "[%02d%02d%02d%03ld %-8s %4d %5d %p] ", tm.tm_hour,tm.tm_min,tm.tm_sec,tv.tv_usec / 1000, file,_line, nError, (void*)GETTHREADID()); #else #error Sorry, we do not recognize this system... #endif // This is the room remaining in the buffer, with room for a null... nChars = (TWNDSM_MAX_MSG - nChars) - 1; message = &m_ptwndsmlogimpl->pod.m_message[strlen(m_ptwndsmlogimpl->pod.m_message)]; // Finally, tack on the user portion of the message... va_list valist; va_start(valist,_format); #if (TWNDSM_CMP == TWNDSM_CMP_VISUALCPP) && (TWNDSM_CMP_VERSION >= 1400) _vsnprintf_s(message,nChars,nChars,_format,valist); #elif (TWNDSM_CMP == TWNDSM_CMP_VISUALCPP) _vsnprintf(message,nChars,_format,valist); #elif (TWNDSM_CMP == TWNDSM_CMP_GNUGPP) vsnprintf(message,nChars,_format,valist); #else #error Sorry, we do not recognize this system... #endif va_end(valist); // Write the message... fprintf(m_ptwndsmlogimpl->pod.m_plog,"%s\r\n",m_ptwndsmlogimpl->pod.m_message); // Do the assert, if asked for... if (_doassert) { assert(0); } }
static void vprintf_stderr_common(const char* format, va_list args) { #if USE(CF) && !OS(WINDOWS) if (strstr(format, "%@")) { CFStringRef cfFormat = CFStringCreateWithCString(NULL, format, kCFStringEncodingUTF8); #if COMPILER(CLANG) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wformat-nonliteral" #endif CFStringRef str = CFStringCreateWithFormatAndArguments(NULL, NULL, cfFormat, args); #if COMPILER(CLANG) #pragma clang diagnostic pop #endif CFIndex length = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8); char* buffer = (char*)malloc(length + 1); CFStringGetCString(str, buffer, length, kCFStringEncodingUTF8); #if USE(APPLE_SYSTEM_LOG) asl_log(0, 0, ASL_LEVEL_NOTICE, "%s", buffer); #endif fputs(buffer, stderr); free(buffer); CFRelease(str); CFRelease(cfFormat); return; } #if USE(APPLE_SYSTEM_LOG) va_list copyOfArgs; va_copy(copyOfArgs, args); asl_vlog(0, 0, ASL_LEVEL_NOTICE, format, copyOfArgs); va_end(copyOfArgs); #endif // Fall through to write to stderr in the same manner as other platforms. #elif PLATFORM(BLACKBERRY) BBLOGV(BlackBerry::Platform::LogLevelCritical, format, args); #elif HAVE(ISDEBUGGERPRESENT) if (IsDebuggerPresent()) { size_t size = 1024; do { char* buffer = (char*)malloc(size); if (buffer == NULL) break; if (_vsnprintf(buffer, size, format, args) != -1) { #if OS(WINCE) // WinCE only supports wide chars wchar_t* wideBuffer = (wchar_t*)malloc(size * sizeof(wchar_t)); if (wideBuffer == NULL) break; for (unsigned int i = 0; i < size; ++i) { if (!(wideBuffer[i] = buffer[i])) break; } OutputDebugStringW(wideBuffer); free(wideBuffer); #else OutputDebugStringA(buffer); #endif free(buffer); break; } free(buffer); size *= 2; } while (size > 1024); } #endif #if !PLATFORM(BLACKBERRY) vfprintf(stderr, format, args); #endif }
void _usb_log_v(enum USB_LOG_LEVEL level, const char* app_name, const char* function, const char* format, va_list args) { char local_buffer[LOGBUF_SIZE]; int totalCount, count; const char* prefix; const char* func; char* buffer; int masked_level; int app_prefix_func_end; #ifndef LOG_STYLE_SHORT const char** skip_list = NULL; #endif masked_level = GetLogLevel(level); if (__usb_log_level < masked_level && masked_level != LOG_ERROR) return; buffer = local_buffer; totalCount = 0; count = 0; prefix = log_level_string[masked_level]; func = function; app_prefix_func_end = 0; if (masked_level > LOG_LEVEL_MAX) masked_level = LOG_LEVEL_MAX; if ((level & LOG_RAW) == LOG_RAW) { count = _vsnprintf(buffer, LOGBUF_SIZE-1, format, args); if (count > 0) { buffer += count; totalCount += count; } } else { #ifdef LOG_STYLE_SHORT if ((prefix) && strlen(prefix)) { count = _snprintf(buffer, (LOGBUF_SIZE-1), "%s: ", prefix); } else { count = 0; } func = ""; #else func = function; if (func) { // strip some prefixes to shorten function names skip_list=skipped_function_prefix; while(*skip_list && ((func)) && func[0]) { func = STRIP_PREFIX(func,skip_list[0]); skip_list++; } } if(!func) func="none"; // print app name, level string and short function name if ((prefix) && strlen(prefix)) { count = _snprintf(buffer, (LOGBUF_SIZE-1), "%s:%s [%s] ", app_name, prefix, func); } else { count = _snprintf(buffer, (LOGBUF_SIZE-1), "%s:[%s] ", app_name, func); } #endif if (count >= 0) { app_prefix_func_end = count; buffer += count; totalCount += count; count = _vsnprintf(buffer, (LOGBUF_SIZE-1) - totalCount, format, args); if (count > 0) { buffer += count; totalCount += count; } } } if (count < 0) totalCount = LOGBUF_SIZE - 1; // make sure its null terminated local_buffer[totalCount] = 0; #if (!IS_DRIVER) if (masked_level == LOG_ERROR) { // if this is an error message then store it strncpy(usb_error_str, local_buffer, totalCount); usb_error_str[totalCount] = '\0'; usb_error_type = USB_ERROR_TYPE_STRING; } #endif if (user_log_hander) { if (user_log_hander(level, app_name, prefix, func, app_prefix_func_end, local_buffer, totalCount)) return; } if (__usb_log_level >= masked_level) { usb_log_def_handler(level, app_name, prefix, func, app_prefix_func_end, local_buffer, totalCount); } }
static void vprintf_stderr_common(const char* format, va_list args) { #if OS(DARWIN) if (strstr(format, "%@")) { CFStringRef cfFormat = CFStringCreateWithCString(NULL, format, kCFStringEncodingUTF8); #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wformat-nonliteral" #endif CFStringRef str = CFStringCreateWithFormatAndArguments(NULL, NULL, cfFormat, args); #ifdef __clang__ #pragma clang diagnostic pop #endif int length = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8); char* buffer = (char*)malloc(length + 1); CFStringGetCString(str, buffer, length, kCFStringEncodingUTF8); #if !PLATFORM(APOLLO) fputs(buffer, stderr); #endif free(buffer); CFRelease(str); CFRelease(cfFormat); } else #elif COMPILER(MSVC) && !defined(WINCEBASIC) if (IsDebuggerPresent()) { size_t size = 1024; do { char* buffer = (char*)malloc(size); if (buffer == NULL) break; if (_vsnprintf(buffer, size, format, args) != -1) { #if OS(WINCE) // WinCE only supports wide chars wchar_t* wideBuffer = (wchar_t*)malloc(size * sizeof(wchar_t)); if (wideBuffer == NULL) break; for (unsigned int i = 0; i < size; ++i) { if (!(wideBuffer[i] = buffer[i])) break; } OutputDebugStringW(wideBuffer); free(wideBuffer); #else OutputDebugStringA(buffer); #endif free(buffer); break; } free(buffer); size *= 2; } while (size > 1024); } #endif #if OS(SYMBIAN) vfprintf(stdout, format, args); #else vfprintf(stderr, format, args); #endif }
/** * writeLog - 写日志文件 * * @log_type [in] 写日志的等级(信息/警告/出错) * @fmt [in] 需要写的日志信息 * * return * 无 */ void MWriteLog::writeLog(unsigned char log_type, const char *fmt, ...) { #define MAX_LOG_LEN 10240 #define LOG_LINE "\n" char buffer[MAX_LOG_LEN] = {0}; va_list ap; int rc; int err; SYSTEMTIME sys; MLocalSection locSec; locSec.Attch(&m_Lock); if(!m_bNeedWriteDisk) return; GetLocalTime(&sys); if(detectLogFile(sys) != 0) return; switch (log_type) { case LOG_TYPE_INFO: rc = _snprintf(buffer, sizeof(buffer), "[信息] (%04d-%02d-%02d %02d:%02d:%02d-%03d)<%s>\t\t", sys.wYear,sys.wMonth,sys.wDay,sys.wHour, sys.wMinute,sys.wSecond,sys.wMilliseconds, m_cLogPreName); break; case LOG_TYPE_WARN: rc = _snprintf(buffer, sizeof(buffer), "[警告] (%04d-%02d-%02d %02d:%02d:%02d-%03d)<%s>\t\t", sys.wYear,sys.wMonth,sys.wDay,sys.wHour, sys.wMinute,sys.wSecond,sys.wMilliseconds, m_cLogPreName); break; case LOG_TYPE_ERROR: rc = _snprintf(buffer, sizeof(buffer), "[错误] (%04d-%02d-%02d %02d:%02d:%02d-%03d)<%s>\t\t", sys.wYear,sys.wMonth,sys.wDay,sys.wHour, sys.wMinute,sys.wSecond,sys.wMilliseconds, m_cLogPreName); break; default: rc = -1; break; } if(rc < 0) return; va_start(ap, fmt); err = _vsnprintf(buffer+rc, MAX_LOG_LEN-rc-2, fmt, ap); if(err < 0) rc += _snprintf(buffer+rc, MAX_LOG_LEN-rc-2, "写日志文件时传入的长度过大,写日志缓冲区不够"); else rc += err; rc += _snprintf(buffer+rc, sizeof(LOG_LINE), LOG_LINE); va_end(ap); if(m_pFile != NULL && rc < MAX_LOG_LEN) { fwrite(buffer, sizeof(char), rc, m_pFile); fflush(m_pFile); } #ifdef _DEBUG printf("%s\n", buffer); #endif #undef MAX_LOG_LEN #undef LOG_LINE }
int osip_trace(char *filename_long, int li, osip_trace_level_t level, FILE * f, char *chfr, ...) { #ifdef ENABLE_TRACE va_list ap; int relative_time = 0; char *fi=NULL; if (filename_long!=NULL) { fi = strrchr(filename_long, '/'); if (fi==NULL) fi = strrchr(filename_long, '\\'); if (fi!=NULL) fi++; if (fi==NULL) fi=filename_long; } #if (defined(WIN32) && !defined(_WIN32_WCE)) || defined(__linux) static struct timeval start = { 0, 0 }; struct timeval now; if (start.tv_sec == 0 && start.tv_usec == 0) { __osip_port_gettimeofday(&start, NULL); } __osip_port_gettimeofday(&now, NULL); relative_time = 1000 * (now.tv_sec - start.tv_sec); if (now.tv_usec - start.tv_usec > 0) relative_time = relative_time + ((now.tv_usec - start.tv_usec) / 1000); else relative_time = relative_time - 1 + ((now.tv_usec - start.tv_usec) / 1000); #endif #if !defined(WIN32) && !defined(SYSTEM_LOGGER_ENABLED) if (logfile == NULL && use_syslog == 0 && trace_func == NULL) { /* user did not initialize logger.. */ return 1; } #endif if (tracing_table[level] == LOG_FALSE) return OSIP_SUCCESS; if (f == NULL && trace_func == NULL) f = logfile; VA_START(ap, chfr); #if defined(__VXWORKS_OS__) || defined(__rtems__) /* vxworks can't have a local file */ f = stdout; #endif if (0) {} #ifdef ANDROID else if (trace_func == 0) { int lev; switch(level){ case OSIP_INFO3: lev = ANDROID_LOG_DEBUG; break; case OSIP_INFO4: lev = ANDROID_LOG_DEBUG; break; case OSIP_INFO2: lev = ANDROID_LOG_INFO; break; case OSIP_INFO1: lev = ANDROID_LOG_INFO; break; case OSIP_WARNING: lev = ANDROID_LOG_WARN; break; case OSIP_ERROR: lev = ANDROID_LOG_ERROR; break; case OSIP_BUG: lev = ANDROID_LOG_FATAL; break; case OSIP_FATAL: lev = ANDROID_LOG_FATAL; break; default: lev = ANDROID_LOG_DEFAULT; break; } __android_log_vprint(lev, "osip2", chfr, ap); } #elif defined(__APPLE__) && defined(__OBJC__) else if (trace_func == 0) { char buffer[MAX_LENGTH_TR]; int in = 0; memset(buffer, 0, sizeof(buffer)); if (level == OSIP_FATAL) in = snprintf(buffer, MAX_LENGTH_TR-1, "| FATAL | <%s: %i> ", fi, li); else if (level == OSIP_BUG) in = snprintf(buffer, MAX_LENGTH_TR-1, "| BUG | <%s: %i> ", fi, li); else if (level == OSIP_ERROR) in = snprintf(buffer, MAX_LENGTH_TR-1, "| ERROR | <%s: %i> ", fi, li); else if (level == OSIP_WARNING) in = snprintf(buffer, MAX_LENGTH_TR-1, "|WARNING| <%s: %i> ", fi, li); else if (level == OSIP_INFO1) in = snprintf(buffer, MAX_LENGTH_TR-1, "| INFO1 | <%s: %i> ", fi, li); else if (level == OSIP_INFO2) in = snprintf(buffer, MAX_LENGTH_TR-1, "| INFO2 | <%s: %i> ", fi, li); else if (level == OSIP_INFO3) in = snprintf(buffer, MAX_LENGTH_TR-1, "| INFO3 | <%s: %i> ", fi, li); else if (level == OSIP_INFO4) in = snprintf(buffer, MAX_LENGTH_TR-1, "| INFO4 | <%s: %i> ", fi, li); vsnprintf(buffer + in, MAX_LENGTH_TR-1 - in, chfr, ap); NSLog(@"%s", buffer); } #endif else if (f && use_syslog == 0) { if (level == OSIP_FATAL) fprintf(f, "| FATAL | %i <%s: %i> ", relative_time, fi, li); else if (level == OSIP_BUG) fprintf(f, "| BUG | %i <%s: %i> ", relative_time, fi, li); else if (level == OSIP_ERROR) fprintf(f, "| ERROR | %i <%s: %i> ", relative_time, fi, li); else if (level == OSIP_WARNING) fprintf(f, "|WARNING| %i <%s: %i> ", relative_time, fi, li); else if (level == OSIP_INFO1) fprintf(f, "| INFO1 | %i <%s: %i> ", relative_time, fi, li); else if (level == OSIP_INFO2) fprintf(f, "| INFO2 | %i <%s: %i> ", relative_time, fi, li); else if (level == OSIP_INFO3) fprintf(f, "| INFO3 | %i <%s: %i> ", relative_time, fi, li); else if (level == OSIP_INFO4) fprintf(f, "| INFO4 | %i <%s: %i> ", relative_time, fi, li); vfprintf(f, chfr, ap); fflush(f); } else if (trace_func) { trace_func(fi, li, level, chfr, ap); } #if defined (HAVE_SYSLOG_H) && !defined(__arc__) else if (use_syslog == 1) { char buffer[MAX_LENGTH_TR]; int in = 0; memset(buffer, 0, sizeof(buffer)); if (level == OSIP_FATAL) in = snprintf(buffer, MAX_LENGTH_TR-1, "| FATAL | <%s: %i> ", fi, li); else if (level == OSIP_BUG) in = snprintf(buffer, MAX_LENGTH_TR-1, "| BUG | <%s: %i> ", fi, li); else if (level == OSIP_ERROR) in = snprintf(buffer, MAX_LENGTH_TR-1, "| ERROR | <%s: %i> ", fi, li); else if (level == OSIP_WARNING) in = snprintf(buffer, MAX_LENGTH_TR-1, "|WARNING| <%s: %i> ", fi, li); else if (level == OSIP_INFO1) in = snprintf(buffer, MAX_LENGTH_TR-1, "| INFO1 | <%s: %i> ", fi, li); else if (level == OSIP_INFO2) in = snprintf(buffer, MAX_LENGTH_TR-1, "| INFO2 | <%s: %i> ", fi, li); else if (level == OSIP_INFO3) in = snprintf(buffer, MAX_LENGTH_TR-1, "| INFO3 | <%s: %i> ", fi, li); else if (level == OSIP_INFO4) in = snprintf(buffer, MAX_LENGTH_TR-1, "| INFO4 | <%s: %i> ", fi, li); vsnprintf(buffer + in, MAX_LENGTH_TR-1 - in, chfr, ap); if (level == OSIP_FATAL) syslog(LOG_ERR, "%s", buffer); else if (level == OSIP_BUG) syslog(LOG_ERR, "%s", buffer); else if (level == OSIP_ERROR) syslog(LOG_ERR, "%s", buffer); else if (level == OSIP_WARNING) syslog(LOG_WARNING, "%s", buffer); else if (level == OSIP_INFO1) syslog(LOG_INFO, "%s", buffer); else if (level == OSIP_INFO2) syslog(LOG_INFO, "%s", buffer); else if (level == OSIP_INFO3) syslog(LOG_DEBUG, "%s", buffer); else if (level == OSIP_INFO4) syslog(LOG_DEBUG, "%s", buffer); } #endif #ifdef SYSTEM_LOGGER_ENABLED else { char buffer[MAX_LENGTH_TR]; int in = 0; #ifdef DISPLAY_TIME int relative_time; #endif memset(buffer, 0, sizeof(buffer)); if (level == OSIP_FATAL) in = _snprintf(buffer, MAX_LENGTH_TR-1, "| FATAL | %i <%s: %i> ", relative_time, fi, li); else if (level == OSIP_BUG) in = _snprintf(buffer, MAX_LENGTH_TR-1, "| BUG | %i <%s: %i> ", relative_time, fi, li); else if (level == OSIP_ERROR) in = _snprintf(buffer, MAX_LENGTH_TR-1, "| ERROR | %i <%s: %i> ", relative_time, fi, li); else if (level == OSIP_WARNING) in = _snprintf(buffer, MAX_LENGTH_TR-1, "|WARNING| %i <%s: %i> ", relative_time, fi, li); else if (level == OSIP_INFO1) in = _snprintf(buffer, MAX_LENGTH_TR-1, "| INFO1 | %i <%s: %i> ", relative_time, fi, li); else if (level == OSIP_INFO2) in = _snprintf(buffer, MAX_LENGTH_TR-1, "| INFO2 | %i <%s: %i> ", relative_time, fi, li); else if (level == OSIP_INFO3) in = _snprintf(buffer, MAX_LENGTH_TR-1, "| INFO3 | %i <%s: %i> ", relative_time, fi, li); else if (level == OSIP_INFO4) in = _snprintf(buffer, MAX_LENGTH_TR-1, "| INFO4 | %i <%s: %i> ", relative_time, fi, li); _vsnprintf(buffer + in, MAX_LENGTH_TR-1 - in, chfr, ap); #ifdef UNICODE { WCHAR wUnicode[MAX_LENGTH_TR*2]; MultiByteToWideChar(CP_UTF8, 0, buffer, -1, wUnicode, MAX_LENGTH_TR*2); OutputDebugString(wUnicode); } #else OutputDebugString(buffer); #endif } #endif va_end(ap); #endif return OSIP_SUCCESS; }
void hgeFont::printfb(float x, float y, float w, float h, int align, const char *format, ...) { char chr, *pbuf, *prevword, *linestart; int i,lines=0; float tx, ty, hh, ww; char *pArg=(char *) &format+sizeof(format); _vsnprintf(buffer, sizeof(buffer)-1, format, pArg); buffer[sizeof(buffer)-1]=0; //vsprintf(buffer, format, pArg); linestart=buffer; pbuf=buffer; prevword=0; for(;;) { i=0; while(pbuf[i] && pbuf[i]!=' ' && pbuf[i]!='\n') i++; chr=pbuf[i]; pbuf[i]=0; ww=GetStringWidth(linestart); pbuf[i]=chr; if(ww > w) { if(pbuf==linestart) { pbuf[i]='\n'; linestart=&pbuf[i+1]; } else { *prevword='\n'; linestart=prevword+1; } lines++; } if(pbuf[i]=='\n') { prevword=&pbuf[i]; linestart=&pbuf[i+1]; pbuf=&pbuf[i+1]; lines++; continue; } if(!pbuf[i]) {lines++;break;} prevword=&pbuf[i]; pbuf=&pbuf[i+1]; } tx=x; ty=y; hh=fHeight*fSpacing*fScale*lines; switch(align & HGETEXT_HORZMASK) { case HGETEXT_LEFT: break; case HGETEXT_RIGHT: tx+=w; break; case HGETEXT_CENTER: tx+=int(w/2); break; } switch(align & HGETEXT_VERTMASK) { case HGETEXT_TOP: break; case HGETEXT_BOTTOM: ty+=h-hh; break; case HGETEXT_MIDDLE: ty+=int((h-hh)/2); break; } Render(tx,ty,align,buffer); }