static void log_write_impl(const char *file, int line, const char *log_level_str, const char *format, va_list ap) { char buf_text[1024]; char buf_time[32]; memset(buf_text, 0, sizeof(buf_text)); memset(buf_time, 0, sizeof(buf_time)); int count_text; int count_time; /** * thus, no need to call a system call gettid() everytime */ static __thread int t_tid = -1; if(t_tid == -1) { t_tid = gettid(); } count_text = sprintf(buf_text, " %-6s %d %s:%d ", log_level_str, t_tid, file, line); count_text += vsprintf(buf_text + count_text, format, ap); if(buf_text[count_text-1] != '\n') { buf_text[count_text] = '\n'; buf_text[++count_text] = '\0'; } else { buf_text[count_text] = '\0'; } time_info_t ti; while(1) { pthread_mutex_lock(&mutex); /****************************************************************/ /** * 这个地方可以优化一下 * 当第一次失败后,返回来在写日志的时候,又重新写了一遍时间 * 是否合理,还需要在仔细琢磨一下 */ ti = get_cur_time(); count_time = sprintf(buf_time, "[ %02d:%02d:%02d.%06ld ]", ti.hour, ti.min, ti.sec, ti.usec); /****************************************************************/ /** * create a new log file */ if(ti.day_num > cur_log_day_num) { g_new_fd = 1; pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } /** * buf is full */ if(w_buf->pos + count_time + count_text >= MAX_BUF_SIZE) { pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } else { strncpy(w_buf->buf+w_buf->pos, buf_time, count_time); w_buf->pos += count_time; strncpy(w_buf->buf+w_buf->pos, buf_text, count_text); w_buf->pos += count_text; pthread_mutex_unlock(&mutex); break; } } }
void log_vwrite(log_context lc, int category, int level, const char *format, va_list args) { log_channel_list lcl; int pri, debugging, did_vsprintf = 0; int original_category; FILE *stream; log_channel chan; struct timeval tv; struct tm *local_tm; #ifdef HAVE_TIME_R struct tm tm_tmp; #endif time_t tt; const char *category_name; const char *level_str; char time_buf[256]; char level_buf[256]; REQUIRE(lc != NULL); debugging = (lc->flags & LOG_OPTION_DEBUG); /* * If not debugging, short circuit debugging messages very early. */ if (level > 0 && !debugging) return; if (category < 0 || category > lc->num_categories) category = 0; /*%< use default */ original_category = category; lcl = lc->categories[category]; if (lcl == NULL) { category = 0; lcl = lc->categories[0]; } /* * Get the current time and format it. */ time_buf[0]='\0'; if (gettimeofday(&tv, NULL) < 0) { syslog(LOG_INFO, "gettimeofday failed in log_vwrite()"); } else { tt = tv.tv_sec; #ifdef HAVE_TIME_R local_tm = localtime_r(&tt, &tm_tmp); #else local_tm = localtime(&tt); #endif if (local_tm != NULL) { sprintf(time_buf, "%02d-%s-%4d %02d:%02d:%02d.%03ld ", local_tm->tm_mday, months[local_tm->tm_mon], local_tm->tm_year+1900, local_tm->tm_hour, local_tm->tm_min, local_tm->tm_sec, (long)tv.tv_usec/1000); } } /* * Make a string representation of the current category and level */ if (lc->category_names != NULL && lc->category_names[original_category] != NULL) category_name = lc->category_names[original_category]; else category_name = ""; if (level >= log_critical) { if (level >= 0) { sprintf(level_buf, "debug %d: ", level); level_str = level_buf; } else level_str = level_text[-level-1]; } else { sprintf(level_buf, "level %d: ", level); level_str = level_buf; } /* * Write the message to channels. */ for ( /* nothing */; lcl != NULL; lcl = lcl->next) { chan = lcl->channel; if (!log_check_channel(lc, level, chan)) continue; if (!did_vsprintf) { (void)vsprintf(lc->buffer, format, args); if (strlen(lc->buffer) > (size_t)LOG_BUFFER_SIZE) { syslog(LOG_CRIT, "memory overrun in log_vwrite()"); exit(1); } did_vsprintf = 1; } switch (chan->type) { case log_syslog: if (level >= log_critical) pri = (level >= 0) ? 0 : -level; else pri = -log_critical; syslog(chan->out.facility|syslog_priority[pri], "%s%s%s%s", (chan->flags & LOG_TIMESTAMP) ? time_buf : "", (chan->flags & LOG_PRINT_CATEGORY) ? category_name : "", (chan->flags & LOG_PRINT_LEVEL) ? level_str : "", lc->buffer); break; case log_file: stream = chan->out.file.stream; if (stream == NULL) { stream = log_open_stream(chan); if (stream == NULL) break; } if (chan->out.file.max_size != ULONG_MAX) { long pos; pos = ftell(stream); if (pos >= 0 && (unsigned long)pos > chan->out.file.max_size) { /* * try to roll over the log files, * ignoring all all return codes * except the open (we don't want * to write any more anyway) */ log_close_stream(chan); version_rename(chan); stream = log_open_stream(chan); if (stream == NULL) break; } } fprintf(stream, "%s%s%s%s\n", (chan->flags & LOG_TIMESTAMP) ? time_buf : "", (chan->flags & LOG_PRINT_CATEGORY) ? category_name : "", (chan->flags & LOG_PRINT_LEVEL) ? level_str : "", lc->buffer); fflush(stream); break; case log_null: break; default: syslog(LOG_ERR, "unknown channel type in log_vwrite()"); } } }
int main(void) { char s[100]; vsprintf(s, "Nothing\n", va); printf("%s", s); }
intptr_t com64_api_entry(int __fn, intptr_t* packet){ switch(__fn){ case 0x00: // exit longjmp(jmp_exit_here,1+(0xFF&packet[0])); /* NOTREACHED */ case 0x01: // get tick count return sys_get_tick_count(); case 0x02: // return secutiry cookie return security_cookie; case 0x03: // puts return printf("%s\n", (char*)packet[0] ); case 0x04: // open file return gre_open( (char*)packet[0], packet[1], packet[2] ); case 0x05: // close file gre_close( packet[0] ); break; case 0x06: // read return gre_read( packet[0], (void*)packet[1], packet[2] ); case 0x07: // write return gre_write( packet[0], (void*)packet[1], packet[2] ); case 0x08: // lseek return gre_seek( packet[0], packet[1], packet[2] ); case 0x09: // strlen return strlen( (char*)packet[0] ); case 0x0A: // strcpy return (intptr_t)strcpy( (char*)packet[0], (char*)packet[1] ); case 0x0B: // strcmp return strcmp( (char*)packet[0], (char*)packet[1] ); case 0x0C: // memcpy return (intptr_t)memcpy( (void*)packet[0], (void*)packet[1], packet[2] ); case 0x0D: // memcmp return memcmp( (void*)packet[0], (void*)packet[1], packet[2] ); case 0x0E: // memset return (intptr_t)memset( (void*)packet[0], packet[1], packet[2] ); case 0x0F: // usleep usleep( packet[0] ); break; case 0x10: // printf return vprintf( (char*)packet[0], (va_list)packet[1] ); case 0x11: // sprintf return vsprintf( (char*)packet[0], (char*)packet[1], (va_list)packet[2] ); case 0x12: // malloc return (intptr_t)malloc( packet[0] ); case 0x13: // free free( (void*)packet[0] ); break; case 0x14: // setjmp return setjmp( (int*)packet[0] ); case 0x15: // longjmp longjmp( (int*)packet[0], packet[1]); /* NOTREACHED */ case 0x16: // MessageBox_show return gre_MessageBox_show( (const char*)packet[0], (const char*)packet[1] ); case 0x17: // strcasecmp return strcasecmp( (char*)packet[0], (char*)packet[1] ); case 0x18: // strchr return (intptr_t)strchr( (char*)packet[0], packet[1] ); case 0x19: // strrchr return (intptr_t)strrchr( (char*)packet[0], packet[1] ); case 0x1A: // tek_getsize return tek_getsize((unsigned char *)packet[0]); case 0x1B: // tek_decomp return tek_decomp((unsigned char *)packet[0], (char *)packet[1], packet[2]); case 0x1C: // strtol return strtol((const char*)packet[0], (char **)packet[1], packet[2]); case 0x7D: // display string for short program return gre_write(STDOUT_FILENO, (void*)packet, strlen((char*)packet)); case 0x7E: // getchar for short program { int c=0; gre_read(STDIN_FILENO, &c, 1); return c; } case 0x7F: // putchar for short program return gre_write(STDOUT_FILENO, &packet, 1); case 0xFFFFFFFF: // invoke main { // ctor if(packet[1]){ VOID_FUNC *p=(VOID_FUNC*)packet[1]; for(;*p;p++){ (*p)(); } } // main int r=setjmp(jmp_exit_here); if(!r){ r = 1+((MAIN_PROC)packet[0])(gre_argc,gre_argv); } // dtor if(packet[2]){ VOID_FUNC *p=(VOID_FUNC*)packet[2]; for(;*p;p++){ (*p)(); } } longjmp(gre_exit_process, r); /* NOTREACHED */ } default: printf("GRE: NOT SUPPORTED API (%0x)\n", __fn & (int8_t)__fn); } return 0; }
static int __init mount_nfs_root(void) { char *root_dev, *root_data; unsigned int timeout; int try, err; err = nfs_root_data(&root_dev, &root_data); if (err != 0) return 0; /* * The server or network may not be ready, so try several * times. Stop after a few tries in case the client wants * to fall back to other boot methods. */ timeout = NFSROOT_TIMEOUT_MIN; for (try = 1; ; try++) { err = do_mount_root(root_dev, "nfs", root_mountflags, root_data); if (err == 0) return 1; if (try > NFSROOT_RETRY_MAX) break; /* Wait, in case the server refused us immediately */ ssleep(timeout); timeout <<= 1; if (timeout > NFSROOT_TIMEOUT_MAX) timeout = NFSROOT_TIMEOUT_MAX; } return 0; } #endif #if defined(CONFIG_BLK_DEV_RAM) || defined(CONFIG_BLK_DEV_FD) void __init change_floppy(char *fmt, ...) { struct termios termios; char buf[80]; char c; int fd; va_list args; va_start(args, fmt); vsprintf(buf, fmt, args); va_end(args); fd = sys_open("/dev/root", O_RDWR | O_NDELAY, 0); if (fd >= 0) { sys_ioctl(fd, FDEJECT, 0); sys_close(fd); } printk(KERN_NOTICE "VFS: Insert %s and press ENTER\n", buf); fd = sys_open("/dev/console", O_RDWR, 0); if (fd >= 0) { sys_ioctl(fd, TCGETS, (long)&termios); termios.c_lflag &= ~ICANON; sys_ioctl(fd, TCSETSF, (long)&termios); sys_read(fd, &c, 1); termios.c_lflag |= ICANON; sys_ioctl(fd, TCSETSF, (long)&termios); sys_close(fd); } } #endif void __init mount_root(void) { #ifdef CONFIG_ROOT_NFS if (ROOT_DEV == Root_NFS) { if (mount_nfs_root()) return; printk(KERN_ERR "VFS: Unable to mount root fs via NFS, trying floppy.\n"); ROOT_DEV = Root_FD0; } #endif #ifdef CONFIG_BLK_DEV_FD if (MAJOR(ROOT_DEV) == FLOPPY_MAJOR) { /* rd_doload is 2 for a dual initrd/ramload setup */ if (rd_doload==2) { if (rd_load_disk(1)) { ROOT_DEV = Root_RAM1; root_device_name = NULL; } } else change_floppy("root floppy"); } #endif #ifdef CONFIG_BLOCK create_dev("/dev/root", ROOT_DEV); mount_block_root("/dev/root", root_mountflags); #endif } /* * Prepare the namespace - decide what/where to mount, load ramdisks, etc. */ void __init prepare_namespace(void) { int is_floppy; if (root_delay) { printk(KERN_INFO "Waiting %d sec before mounting root device...\n", root_delay); ssleep(root_delay); } /* * wait for the known devices to complete their probing * * Note: this is a potential source of long boot delays. * For example, it is not atypical to wait 5 seconds here * for the touchpad of a laptop to initialize. */ wait_for_device_probe(); md_run_setup(); if (saved_root_name[0]) { root_device_name = saved_root_name; if (!strncmp(root_device_name, "mtd", 3) || !strncmp(root_device_name, "ubi", 3)) { mount_block_root(root_device_name, root_mountflags); goto out; } ROOT_DEV = name_to_dev_t(root_device_name); if (strncmp(root_device_name, "/dev/", 5) == 0) root_device_name += 5; } if (initrd_load()) goto out; /* wait for any asynchronous scanning to complete */ if ((ROOT_DEV == 0) && root_wait) { printk(KERN_INFO "Waiting for root device %s...\n", saved_root_name); while (driver_probe_done() != 0 || (ROOT_DEV = name_to_dev_t(saved_root_name)) == 0) msleep(100); async_synchronize_full(); } is_floppy = MAJOR(ROOT_DEV) == FLOPPY_MAJOR; if (is_floppy && rd_doload && rd_load_disk(0)) ROOT_DEV = Root_RAM0; mount_root(); out: devtmpfs_mount("dev"); sys_mount(".", "/", NULL, MS_MOVE, NULL); sys_chroot("."); }
/** * @brief Print a formatted message to the console. * @details If the logging level is ERROR, this function will throw a * runtime exception * @param level the logging level for this message * @param format variable list of C++ formatted arguments */ void log_printf(logLevel level, const char* format, ...) { char message[1024]; std::string msg_string; if (level >= log_level) { va_list args; va_start(args, format); vsprintf(message, format, args); va_end(args); /* Append the log level to the message */ switch (level) { case (DEBUG): { std::string msg = std::string(message); std::string level_prefix = "[ DEBUG ] "; /* If message is too long for a line, split into many lines */ if (int(msg.length()) > line_length) msg_string = create_multiline_msg(level_prefix, msg); /* Puts message on single line */ else msg_string = level_prefix + msg + "\n"; break; } case (INFO): { std::string msg = std::string(message); std::string level_prefix = "[ INFO ] "; /* If message is too long for a line, split into many lines */ if (int(msg.length()) > line_length) msg_string = create_multiline_msg(level_prefix, msg); /* Puts message on single line */ else msg_string = level_prefix + msg + "\n"; break; } case (NORMAL): { std::string msg = std::string(message); std::string level_prefix = "[ NORMAL ] "; /* If message is too long for a line, split into many lines */ if (int(msg.length()) > line_length) msg_string = create_multiline_msg(level_prefix, msg); /* Puts message on single line */ else msg_string = level_prefix + msg + "\n"; break; } case (SEPARATOR): { std::string pad = std::string(line_length, separator_char); std::string prefix = std::string("[SEPARATOR] "); std::stringstream ss; ss << prefix << pad << "\n"; msg_string = ss.str(); break; } case (HEADER): { int size = strlen(message); int halfpad = (line_length - 4 - size) / 2; std::string pad1 = std::string(halfpad, header_char); std::string pad2 = std::string(halfpad + (line_length - 4 - size) % 2, header_char); std::string prefix = std::string("[ HEADER ] "); std::stringstream ss; ss << prefix << pad1 << " " << message << " " << pad2 << "\n"; msg_string = ss.str(); break; } case (TITLE): { int size = strlen(message); int halfpad = (line_length - size) / 2; std::string pad = std::string(halfpad, ' '); std::string prefix = std::string("[ TITLE ] "); std::stringstream ss; ss << prefix << std::string(line_length, title_char) << "\n"; ss << prefix << pad << message << pad << "\n"; ss << prefix << std::string(line_length, title_char) << "\n"; msg_string = ss.str(); break; } case (WARNING): { std::string msg = std::string(message); std::string level_prefix = "[ WARNING ] "; /* If message is too long for a line, split into many lines */ if (int(msg.length()) > line_length) msg_string = create_multiline_msg(level_prefix, msg); /* Puts message on single line */ else msg_string = level_prefix + msg + "\n"; break; } case (CRITICAL): { std::string msg = std::string(message); std::string level_prefix = "[ CRITICAL] "; /* If message is too long for a line, split into many lines */ if (int(msg.length()) > line_length) msg_string = create_multiline_msg(level_prefix, msg); /* Puts message on single line */ else msg_string = level_prefix + msg + "\n"; break; } case (RESULT): msg_string = std::string("[ RESULT ] ") + message + "\n"; break; case (UNITTEST): { std::string msg = std::string(message); std::string level_prefix = "[ TEST ] "; /* If message is too long for a line, split into many lines */ if (int(msg.length()) > line_length) msg_string = create_multiline_msg(level_prefix, msg); /* Puts message on single line */ else msg_string = level_prefix + msg + "\n"; break; } case (ERROR): { /* Create message based on runtime error stack */ va_start(args, format); vsprintf(message, format, args); va_end(args); std::string msg = std::string(message); std::string level_prefix = "[ ERROR ] "; /* If message is too long for a line, split into many lines */ if (int(msg.length()) > line_length) msg_string = create_multiline_msg(level_prefix, msg); /* Puts message on single line */ else msg_string = level_prefix + msg + "\n"; } } /* If this is our first time logging, add a header with date, time */ if (!logging) { /* If output directory was not defined by user, then log file is * written to a "log" subdirectory. Create it if it doesn't exist */ if (output_directory.compare(".") == 0) { struct stat st; if (!stat("log", &st) == 0) mkdir("log", S_IRWXU); } /* Write the message to the output file */ std::ofstream log_file; log_file.open((output_directory + "/" + log_filename).c_str(), std::ios::app); /* Append date, time to the top of log output file */ time_t rawtime; struct tm * timeinfo; time (&rawtime); timeinfo = localtime (&rawtime); log_file << "Current local time and date: " << asctime(timeinfo); logging = true; log_file.close(); } /* Write the log message to the log_file */ std::ofstream log_file; log_file.open((output_directory + "/" + log_filename).c_str(), std::ios::app); log_file << msg_string; log_file.close(); /* Write the log message to the shell */ printf(msg_string.c_str()); } /* If the message was a runtime error, exit the program */ if (level == ERROR) exit(1); }
void test (int arg, ...) { char buf2[20]; va_list ap; char *p = &buf1[10], *q; memcpy (&buf2[19], "ab", 1); memcpy (&buf2[19], "ab", 2); /* { dg-warning "will always overflow" "memcpy" } */ vx = mempcpy (&buf2[19], "ab", 1); vx = mempcpy (&buf2[19], "ab", 2); /* { dg-warning "will always overflow" "mempcpy" } */ memmove (&buf2[18], &buf1[10], 2); memmove (&buf2[18], &buf1[10], 3); /* { dg-warning "will always overflow" "memmove" } */ memset (&buf2[16], 'a', 4); memset (&buf2[15], 'b', 6); /* { dg-warning "will always overflow" "memset" } */ strcpy (&buf2[18], "a"); strcpy (&buf2[18], "ab"); /* { dg-warning "will always overflow" "strcpy" } */ vx = stpcpy (&buf2[18], "a"); vx = stpcpy (&buf2[18], "ab"); /* { dg-warning "will always overflow" "stpcpy" } */ strncpy (&buf2[18], "a", 2); strncpy (&buf2[18], "a", 3); /* { dg-warning "will always overflow" "strncpy" } */ strncpy (&buf2[18], "abc", 2); strncpy (&buf2[18], "abc", 3); /* { dg-warning "will always overflow" "strncpy" } */ memset (buf2, '\0', sizeof (buf2)); strcat (&buf2[18], "a"); memset (buf2, '\0', sizeof (buf2)); strcat (&buf2[18], "ab"); /* { dg-warning "will always overflow" "strcat" } */ sprintf (&buf2[18], "%s", buf1); sprintf (&buf2[18], "%s", "a"); sprintf (&buf2[18], "%s", "ab"); /* { dg-warning "will always overflow" "sprintf" } */ sprintf (&buf2[18], "a"); sprintf (&buf2[18], "ab"); /* { dg-warning "will always overflow" "sprintf" } */ snprintf (&buf2[18], 2, "%d", x); /* N argument to snprintf is the size of the buffer. Although this particular call wouldn't overflow buf2, incorrect buffer size was passed to it and therefore we want a warning and runtime failure. */ snprintf (&buf2[18], 3, "%d", x); /* { dg-warning "will always overflow" "snprintf" } */ va_start (ap, arg); vsprintf (&buf2[18], "a", ap); va_end (ap); va_start (ap, arg); vsprintf (&buf2[18], "ab", ap); /* { dg-warning "will always overflow" "vsprintf" } */ va_end (ap); va_start (ap, arg); vsnprintf (&buf2[18], 2, "%s", ap); va_end (ap); va_start (ap, arg); /* See snprintf above. */ vsnprintf (&buf2[18], 3, "%s", ap); /* { dg-warning "will always overflow" "vsnprintf" } */ va_end (ap); p = p + 10; memset (p, 'd', 0); q = strcpy (p, ""); /* { dg-warning "will always overflow" "strcpy" } */ /* This invokes undefined behaviour, since we are past the end of buf1. */ p = p + 10; memset (p, 'd', 1); /* { dg-warning "will always overflow" "memset" } */ memset (q, 'd', 0); memset (q, 'd', 1); /* { dg-warning "will always overflow" "memset" } */ q = q - 10; memset (q, 'd', 10); }
int vasprintf(char **ret, const char *fmt, va_list ap) { #if HAVE_VSNPRINTF int chunks; size_t buflen; char *buf; int len; chunks = ((strlen(fmt) + 1) / CHUNKSIZE) + 1; buflen = chunks * CHUNKSIZE; for (;;) { if ((buf = malloc(buflen)) == NULL) { *ret = NULL; return -1; } len = vsnprintf(buf, buflen, fmt, ap); if (len >= 0 && len < (buflen - 1)) { break; } free(buf); buflen = (++chunks) * CHUNKSIZE; if (len >= 0 && len >= buflen) { buflen = len + 1; } } *ret = buf; return len; #else /* HAVE_VSNPRINTF */ #ifdef _REENTRANT FILE *fp; #else /* !_REENTRANT */ static FILE *fp = NULL; #endif /* !_REENTRANT */ int len; char *buf; *ret = NULL; #ifdef _REENTRANT # ifdef WIN32 # error Win32 do not have /dev/null, should use vsnprintf version # endif if ((fp = fopen(_PATH_DEVNULL, "w")) == NULL) return -1; #else /* !_REENTRANT */ if ((fp == NULL) && ((fp = fopen(_PATH_DEVNULL, "w")) == NULL)) return -1; #endif /* !_REENTRANT */ len = vfprintf(fp, fmt, ap); #ifdef _REENTRANT if (fclose(fp) != 0) return -1; #endif /* _REENTRANT */ if (len < 0) return len; if ((buf = malloc(len + 1)) == NULL) return -1; if (vsprintf(buf, fmt, ap) != len) return -1; *ret = buf; return len; #endif /* HAVE_VSNPRINTF */ }
void CPLErrorV(CPLErr eErrClass, int err_no, const char *fmt, va_list args ) { CPLErrorContext *psCtx = CPLGetErrorContext(); /* -------------------------------------------------------------------- */ /* Expand the error message */ /* -------------------------------------------------------------------- */ #if defined(HAVE_VSNPRINTF) { int nPR; va_list wrk_args; #ifdef va_copy va_copy( wrk_args, args ); #else wrk_args = args; #endif while( ((nPR = vsnprintf( psCtx->szLastErrMsg, psCtx->nLastErrMsgMax, fmt, wrk_args )) == -1 || nPR >= psCtx->nLastErrMsgMax-1) && psCtx->nLastErrMsgMax < 1000000 ) { #ifdef va_copy va_end( wrk_args ); va_copy( wrk_args, args ); #else wrk_args = args; #endif psCtx->nLastErrMsgMax *= 3; psCtx = (CPLErrorContext *) CPLRealloc(psCtx, sizeof(CPLErrorContext) - DEFAULT_LAST_ERR_MSG_SIZE + psCtx->nLastErrMsgMax + 1); CPLSetTLS( CTLS_ERRORCONTEXT, psCtx, TRUE ); } va_end( wrk_args ); } #else vsprintf( psCtx->szLastErrMsg, fmt, args); #endif /* -------------------------------------------------------------------- */ /* If the user provided his own error handling function, then */ /* call it, otherwise print the error to stderr and return. */ /* -------------------------------------------------------------------- */ psCtx->nLastErrNo = err_no; psCtx->eLastErrType = eErrClass; if( CPLGetConfigOption("CPL_LOG_ERRORS",NULL) != NULL ) CPLDebug( "CPLError", "%s", psCtx->szLastErrMsg ); /* -------------------------------------------------------------------- */ /* Invoke the current error handler. */ /* -------------------------------------------------------------------- */ if( psCtx->psHandlerStack != NULL ) { psCtx->psHandlerStack->pfnHandler(eErrClass, err_no, psCtx->szLastErrMsg); } else { CPLMutexHolderD( &hErrorMutex ); if( pfnErrorHandler != NULL ) pfnErrorHandler(eErrClass, err_no, psCtx->szLastErrMsg); } if( eErrClass == CE_Fatal ) abort(); }
void vwriteStatusBarf(const char format[], va_list ap) { vsprintf(fileBuffer, format, ap); writeStatusBar(fileBuffer); }
void vsyslog(int pri, char *fmt, va_list ap) { extern int errno; register int cnt; register char *p; time_t now; int fd, saved_errno; char tbuf[2048], fmt_cpy[1024], *stdp; saved_errno = errno; /* see if we should just throw out this message */ if (!LOG_MASK(LOG_PRI(pri)) || (pri &~ (LOG_PRIMASK|LOG_FACMASK))) return; if (LogFile < 0 || !connected) openlog(LogTag, LogStat | LOG_NDELAY, 0); /* set default facility if none specified */ if ((pri & LOG_FACMASK) == 0) pri |= LogFacility; /* build the message */ (void)time(&now); (void)sprintf(tbuf, "<%d>%.15s ", pri, ctime(&now) + 4); for (p = tbuf; *p; ++p); if (LogStat & LOG_PERROR) stdp = p; if (LogTag) { (void)strcpy(p, LogTag); for (; *p; ++p); } if (LogStat & LOG_PID) { (void)sprintf(p, "[%d]", getpid() ); for (; *p; ++p); } if (LogTag) { *p++ = ':'; *p++ = ' '; } /* substitute error message for %m */ { register char ch, *t1, *t2; for (t1 = fmt_cpy; ch = *fmt; ++fmt) if (ch == '%' && fmt[1] == 'm') { ++fmt; for (t2 = mystrerror(saved_errno); *t1 = *t2++; ++t1); } else *t1++ = ch; *t1 = '\0'; } (void)vsprintf(p, fmt_cpy, ap); cnt = strlen(tbuf); /* output to stderr if requested */ if (LogStat & LOG_PERROR) { write(2, tbuf,cnt); write(2,"\r\n",2); } /* output the message to the local logger */ if (send(LogFile, tbuf, cnt, 0) >= 0 || !(LogStat&LOG_CONS)) return; }
/** * Compose a string with a format string in the buffer pointed to by buf. * * It is up to the caller to ensure that the allocated buffer is large enough * to hold the formatted result. * * Internally, the function retrieves arguments from the list identified by * args as if va_arg was used on it, and thus the state of args is likely to * be altered by the call. * * In any case, args should have been initialized by va_start at some point * before the call, and it is expected to be released by va_end at some point * after the call. * * This version ignores the current locale and uses the locale "C" for Linux, * FreeBSD, OSX and Android. * * @param buf Pointer to a buffer where the resulting C string is stored. * @param format C string that contains a format string (see printf). * @param args A value identifying a variable arguments list initialized with * va_start. * * @return On success, the number of characters that would have been written, * not counting the terminating NUL character. * * @since 0.6.0 */ SR_API int sr_vsprintf_ascii(char *buf, const char *format, va_list args) { #if defined(_WIN32) int ret; #if 0 /* * TODO: This part compiles with mingw-w64 but doesn't run with Win7. * Doesn't start because of "Procedure entry point _create_locale * not found in msvcrt.dll". * mingw-w64 should link to msvcr100.dll not msvcrt.dll! * See: https://msdn.microsoft.com/en-us/en-en/library/1kt27hek.aspx */ _locale_t locale; locale = _create_locale(LC_NUMERIC, "C"); ret = _vsprintf_l(buf, format, locale, args); _free_locale(locale); #endif /* vsprintf() uses the current locale, may not work correctly for floats. */ ret = vsprintf(buf, format, args); return ret; #elif defined(__APPLE__) /* * See: * https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/printf_l.3.html * https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/xlocale.3.html */ int ret; locale_t locale; locale = newlocale(LC_NUMERIC_MASK, "C", NULL); ret = vsprintf_l(buf, locale, format, args); freelocale(locale); return ret; #elif defined(__FreeBSD__) && __FreeBSD_version >= 901000 /* * See: * https://www.freebsd.org/cgi/man.cgi?query=printf_l&apropos=0&sektion=3&manpath=FreeBSD+9.1-RELEASE * https://www.freebsd.org/cgi/man.cgi?query=xlocale&apropos=0&sektion=3&manpath=FreeBSD+9.1-RELEASE */ int ret; locale_t locale; locale = newlocale(LC_NUMERIC_MASK, "C", NULL); ret = vsprintf_l(buf, locale, format, args); freelocale(locale); return ret; #elif defined(__ANDROID__) /* * The Bionic libc only has two locales ("C" aka "POSIX" and "C.UTF-8" * aka "en_US.UTF-8"). The decimal point is hard coded as "." * See: https://android.googlesource.com/platform/bionic/+/master/libc/bionic/locale.cpp */ int ret; ret = vsprintf(buf, format, args); return ret; #elif defined(__linux__) int ret; locale_t old_locale, temp_locale; /* Switch to C locale for proper float/double conversion. */ temp_locale = newlocale(LC_NUMERIC, "C", NULL); old_locale = uselocale(temp_locale); ret = vsprintf(buf, format, args); /* Switch back to original locale. */ uselocale(old_locale); freelocale(temp_locale); return ret; #elif defined(__unix__) || defined(__unix) /* * This is a fallback for all other BSDs, *nix and FreeBSD <= 9.0, by * using the current locale for snprintf(). This may not work correctly * for floats! */ int ret; ret = vsprintf(buf, format, args); return ret; #else /* No implementation for unknown systems! */ return -1; #endif }
void hgeGUIText::printf(const char *format, ...) { vsprintf(text, format, (char *)&format+sizeof(format)); }
/* ================= Message Generic output of warnings, stats, etc ================= */ void Message(int msgType, ...) { va_list argptr; char szBuffer[512]; char *szFmt; int WarnType; int Cur, Total; va_start(argptr, msgType); // Exit if necessary if ((msgType == msgStat || msgType == msgProgress) && (!options.fVerbose || options.fNoverbose)) return; else if (msgType == msgPercent && (options.fNopercent || options.fNoverbose)) return; if (fInPercent && msgType != msgPercent) { printf("\r"); fInPercent = false; } switch (msgType) { case msgWarning: WarnType = va_arg(argptr, int); if (WarnType >= cWarnings) printf("Internal error: unknown WarnType in Message!\n"); sprintf(szBuffer, "*** WARNING %02d: ", WarnType); vsprintf(szBuffer + strlen(szBuffer), rgszWarnings[WarnType], argptr); strcat(szBuffer, "\n"); break; case msgLiteral: // Output as-is to screen and log file szFmt = va_arg(argptr, char *); vsprintf(szBuffer, szFmt, argptr); break; case msgStat: // Output as-is to screen and log file szFmt = va_arg(argptr, char *); strcpy(szBuffer, "\t"); vsprintf(szBuffer + strlen(szBuffer), szFmt, argptr); // Concatenate strcat(szBuffer, "\n"); break; case msgProgress: // Output as-is to screen and log file szFmt = va_arg(argptr, char *); strcpy(szBuffer, "---- "); vsprintf(szBuffer + strlen(szBuffer), szFmt, argptr); // Concatenate strcat(szBuffer, " ----\n"); break; case msgPercent: // Calculate the percent complete. Only output if it changes. Cur = va_arg(argptr, int); Total = va_arg(argptr, int); if (((Cur + 1) * 100) / Total == (Cur * 100) / Total) return; sprintf(szBuffer, "\r%3d%%", ((Cur + 1) * 100) / Total); // Handle output formatting properly fInPercent = true; msgType = msgScreen; break; case msgFile: // Output only to the file szFmt = va_arg(argptr, char *); vsprintf(szBuffer, szFmt, argptr); break; case msgScreen: // Output only to the screen szFmt = va_arg(argptr, char *); vsprintf(szBuffer, szFmt, argptr); break; default: printf("Unhandled msgType in message!\n"); return; } if (msgType != msgFile) printf("%s", szBuffer); if (msgType != msgScreen && logfile) fprintf(logfile, "%s", szBuffer); va_end(argptr); fflush(stdout); }
static void PrintMessage ( INT8 *Type, INT8 *FileName, UINT32 LineNumber, UINT32 MessageCode, INT8 *Text, INT8 *MsgFmt, va_list List ) /*++ Routine Description: Worker routine for all the utility printing services. Prints the message in a format that Visual Studio will find when scanning build outputs for errors or warnings. Arguments: Type - "warning" or "error" string to insert into the message to be printed. The first character of this string (converted to uppercase) is used to preceed the MessageCode value in the output string. FileName - name of the file where the warning was detected, or the name of the application that detected the warning LineNumber - the line number where the warning was detected (parsers). 0 should be specified if the utility is not a parser. MessageCode - an application-specific warning code that can be referenced in other documentation. Text - part of the message to print MsgFmt - the format string for the message. Can contain formatting controls for use with varargs. List - the variable list. Returns: None. Notes: If FileName == NULL then this utility will use the string passed into SetUtilityName(). LineNumber is only used if the caller is a parser, in which case FileName refers to the file being parsed. Text and MsgFmt are both optional, though it would be of little use calling this function with them both NULL. Output will typically be of the form: <FileName>(<LineNumber>) : <Type> <Type[0]><MessageCode>: <Text> : <MsgFmt> Parser (LineNumber != 0) VfrCompile.cpp(330) : error E2660: AddVfrDataStructField : function does not take 2 parameters Generic utility (LineNumber == 0) UtilityName : error E1234 : Text string : MsgFmt string and args --*/ { INT8 Line[MAX_LINE_LEN]; INT8 Line2[MAX_LINE_LEN]; INT8 *Cptr; // // If given a filename, then add it (and the line number) to the string. // If there's no filename, then use the program name if provided. // if (FileName != NULL) { Cptr = FileName; } else if (mUtilityName[0] != 0) { Cptr = mUtilityName; } else { Cptr = "Unknown utility"; } strcpy (Line, Cptr); if (LineNumber != 0) { sprintf (Line2, "(%d)", LineNumber); strcat (Line, Line2); } // // Have to print an error code or Visual Studio won't find the // message for you. It has to be decimal digits too. // sprintf (Line2, " : %s %c%04d", Type, toupper (Type[0]), MessageCode); strcat (Line, Line2); fprintf (stdout, "%s", Line); // // If offending text was provided, then print it // if (Text != NULL) { fprintf (stdout, ": %s ", Text); } // // Print formatted message if provided // if (MsgFmt != NULL) { vsprintf (Line2, MsgFmt, List); fprintf (stdout, ": %s", Line2); } fprintf (stdout, "\n"); }
void logprintf(int prio, const char *format_str, ...) { struct timeval tv; struct tm *tm = NULL; va_list ap, apcpy; char fmt[64], buf[64], *line = MALLOC(128), nul; int save_errno = -1, pos = 0, bytes = 0; if(line == NULL) { fprintf(stderr, "out of memory"); exit(EXIT_FAILURE); } save_errno = errno; memset(line, '\0', 128); if(loglevel >= prio) { gettimeofday(&tv, NULL); if((tm = localtime(&tv.tv_sec)) != NULL) { strftime(fmt, sizeof(fmt), "%b %d %H:%M:%S", tm); snprintf(buf, sizeof(buf), "%s:%03u", fmt, (unsigned int)tv.tv_usec); } pos += sprintf(line, "[%22.22s] %s: ", buf, progname); switch(prio) { case LOG_WARNING: pos += sprintf(&line[pos], "WARNING: "); break; case LOG_ERR: pos += sprintf(&line[pos], "ERROR: "); break; case LOG_INFO: pos += sprintf(&line[pos], "INFO: "); break; case LOG_NOTICE: pos += sprintf(&line[pos], "NOTICE: "); break; case LOG_DEBUG: pos += sprintf(&line[pos], "DEBUG: "); break; case LOG_STACK: pos += sprintf(&line[pos], "STACK: "); break; default: break; } va_copy(apcpy, ap); va_start(apcpy, format_str); bytes = vsnprintf(&nul, 1, format_str, apcpy); if(bytes == -1) { fprintf(stderr, "ERROR: unproperly formatted logprintf message %s\n", format_str); } else { va_end(apcpy); if((line = REALLOC(line, (size_t)bytes+(size_t)pos+3)) == NULL) { fprintf(stderr, "out of memory"); exit(EXIT_FAILURE); } va_start(ap, format_str); pos += vsprintf(&line[pos], format_str, ap); va_end(ap); } line[pos++]='\n'; line[pos++]='\0'; } if(shelllog == 1) { fprintf(stderr, "%s", line); } if(stop == 0 && pos > 0) { if(prio < LOG_DEBUG) { pthread_mutex_lock(&logqueue_lock); if(logqueue_number < 1024) { struct logqueue_t *node = MALLOC(sizeof(logqueue_t)); if(node == NULL) { fprintf(stderr, "out of memory"); exit(EXIT_FAILURE); } if((node->line = MALLOC((size_t)pos+1)) == NULL) { fprintf(stderr, "out of memory"); exit(EXIT_FAILURE); } memset(node->line, '\0', (size_t)pos+1); strcpy(node->line, line); node->next = NULL; if(logqueue_number == 0) { logqueue = node; logqueue_head = node; } else { logqueue_head->next = node; logqueue_head = node; } logqueue_number++; } else { fprintf(stderr, "log queue full\n"); } pthread_mutex_unlock(&logqueue_lock); pthread_cond_signal(&logqueue_signal); } } FREE(line); errno = save_errno; }
size_t TFixedString_Format(char* pBuffer, size_t buffer_size, const char* szFormat, va_list vl ) { return vsprintf( pBuffer, szFormat, vl ); }
__FBSDID("$FreeBSD$"); #include <stdio.h> #include <stdarg.h> #include <limits.h> #include "local.h" #include "xlocale_private.h" int sprintf(char * __restrict str, char const * __restrict fmt, ...) { int ret; va_list ap; va_start(ap, fmt); ret = vsprintf(str, fmt, ap); va_end(ap); return (ret); } int sprintf_l(char * __restrict str, locale_t locale, char const * __restrict fmt, ...) { int ret; va_list ap; FIX_LOCALE(locale); va_start(ap, fmt); ret = vsprintf_l(str, locale, fmt, ap); va_end(ap); return (ret);
/*----------------------------------------------------------------------------*/ static void zrtp_log(uint8_t is_clean, const char *sender, uint32_t level, const char *format, va_list marker) { #if (defined(ZRTP_USE_STACK_MINIM) && (ZRTP_USE_STACK_MINIM == 1)) char *log_buffer = zrtp_sys_alloc(ZRTP_LOG_BUFFER_SIZE); #else char log_buffer[ZRTP_LOG_BUFFER_SIZE]; #endif char* sline = log_buffer; uint32_t offset = 0; int len = 0; if (!sline) { return; } if (!is_clean) { /* Print sender with left aligment */ uint32_t sender_len = strlen(sender); *sline++ = ' '; *sline++ = '['; if (sender_len <= ZRTP_LOG_SENDER_MAX_LEN) { while (sender_len < ZRTP_LOG_SENDER_MAX_LEN) { *sline++ = ' ', ++sender_len; } while (*sender) { *sline++ = *sender++; } } else { int i = 0; for (i=0; i<ZRTP_LOG_SENDER_MAX_LEN; ++i) { *sline++ = *sender++; } } *sline++ = ']'; *sline++ = ':'; offset += 3 + ZRTP_LOG_SENDER_MAX_LEN; *sline++ = ' '; offset += 1; } /* Print Message itself */ #if (ZRTP_PLATFORM == ZP_WIN32) || (ZRTP_PLATFORM == ZP_WIN64) || (ZRTP_PLATFORM == ZP_WINCE) # if (_MSC_VER >= 1400) && (ZRTP_PLATFORM != ZP_WINCE) len = _vsnprintf_s(sline, ZRTP_LOG_BUFFER_SIZE-offset-1, ZRTP_LOG_BUFFER_SIZE-offset-1, format, marker); # else len = _vsnprintf(sline, ZRTP_LOG_BUFFER_SIZE-offset, format, marker); # endif #elif (ZRTP_PLATFORM == ZP_WIN32_KERNEL) RtlStringCchVPrintfA(sline, ZRTP_LOG_BUFFER_SIZE-offset, format, marker); #elif (ZRTP_PLATFORM == ZP_LINUX) || (ZRTP_PLATFORM == ZP_DARWIN) || (ZRTP_PLATFORM == ZP_BSD) || (ZRTP_PLATFORM == ZP_ANDROID) len = vsnprintf(sline, ZRTP_LOG_BUFFER_SIZE-offset, format, marker); #elif (ZRTP_PLATFORM == ZP_SYMBIAN) len = vsprintf(sline, format, marker); #endif if ((len > 0) && log_writer) { (*log_writer)(level, log_buffer, len+offset, offset); } #if (defined(ZRTP_USE_STACK_MINIM) && (ZRTP_USE_STACK_MINIM == 1)) zrtp_sys_free(log_buffer); #endif }
struct hw * hw_tree_vparse (struct hw *current, const char *fmt, va_list ap) { char device_specifier[1024]; name_specifier spec; /* format the path */ vsprintf (device_specifier, fmt, ap); if (strlen (device_specifier) >= sizeof (device_specifier)) hw_abort (NULL, "device_tree_add_deviced: buffer overflow\n"); /* construct the tree down to the final struct hw */ current = split_fill_path (current, device_specifier, &spec); /* is there an interrupt spec */ if (spec.property == NULL && spec.value != NULL) { char *op = split_value (&spec); switch (op[0]) { case '>': { char *my_port_name = split_value (&spec); int my_port; char *dest_port_name = split_value (&spec); int dest_port; name_specifier dest_spec; char *dest_hw_name = split_value (&spec); struct hw *dest; /* find my name */ if (!hw_finished_p (current)) hw_finish (current); my_port = hw_port_decode (current, my_port_name, output_port); /* find the dest device and port */ dest = split_fill_path (current, dest_hw_name, &dest_spec); if (!hw_finished_p (dest)) hw_finish (dest); dest_port = hw_port_decode (dest, dest_port_name, input_port); /* connect the two */ hw_port_attach (current, my_port, dest, dest_port, permenant_object); break; } default: hw_abort (current, "unreconised interrupt spec %s\n", spec.value); break; } } /* is there a property */ if (spec.property != NULL) { if (strcmp (spec.value, "true") == 0) hw_add_boolean_property (current, spec.property, 1); else if (strcmp (spec.value, "false") == 0) hw_add_boolean_property (current, spec.property, 0); else { const struct hw_property *property; switch (spec.value[0]) { #if NOT_YET case '*': { parse_ihandle_property (current, spec.property, spec.value + 1); break; } #endif case '[': { unsigned8 words[1024]; char *curr = spec.value + 1; int nr_words = 0; while (1) { char *next; words[nr_words] = H2BE_1 (strtoul (curr, &next, 0)); if (curr == next) break; curr = next; nr_words += 1; } hw_add_array_property (current, spec.property, words, sizeof (words[0]) * nr_words); break; } case '"': { parse_string_property (current, spec.property, spec.value); break; } case '!': { spec.value++; property = hw_tree_find_property (current, spec.value); if (property == NULL) hw_abort (current, "property %s not found\n", spec.value); hw_add_duplicate_property (current, spec.property, property); break; } default: { if (strcmp (spec.property, "reg") == 0 || strcmp (spec.property, "assigned-addresses") == 0 || strcmp (spec.property, "alternate-reg") == 0) { parse_reg_property (current, spec.property, spec.value); } else if (strcmp (spec.property, "ranges") == 0) { parse_ranges_property (current, spec.property, spec.value); } else if (isdigit (spec.value[0]) || (spec.value[0] == '-' && isdigit (spec.value[1])) || (spec.value[0] == '+' && isdigit (spec.value[1]))) { parse_integer_property (current, spec.property, spec.value); } else parse_string_property (current, spec.property, spec.value); break; } } } } return current; }
int vprintf(const char* format, va_list args){ char buffer[4096]; int r=vsprintf(buffer, format, args); gre_write(STDOUT_FILENO, buffer, r); return r; }
char *converse(pam_handle_t *pamh, int echocode, const char *prompt) { const struct pam_message msg = {.msg_style = echocode, .msg = (char *)prompt}; const struct pam_message *msgs = &msg; struct pam_response *resp = NULL; int retval = _converse(pamh, 1, &msgs, &resp); char *ret = NULL; if (retval != PAM_SUCCESS || resp == NULL || resp->resp == NULL || *resp->resp == '\000') { if (retval == PAM_SUCCESS && resp && resp->resp) { ret = resp->resp; } } else { ret = resp->resp; } // Deallocate temporary storage. if (resp) { if (!ret) { free(resp->resp); } free(resp); } return ret; } #if defined(PAM_DEBUG) void _debug(FILE *debug_file, const char *file, int line, const char *func, const char *fmt, ...) { va_list ap; #ifdef __linux__ unsigned int size; char buffer[BUFSIZE]; char *out; size = (unsigned int)snprintf(NULL, 0, DEBUG_STR, file, line, func); va_start(ap, fmt); size += (unsigned int)vsnprintf(NULL, 0, fmt, ap); va_end(ap); va_start(ap, fmt); if (size < (BUFSIZE - 1)) { out = buffer; } else { out = malloc(size); } if (out) { size = (unsigned int)sprintf(out, DEBUG_STR, file, line, func); vsprintf(&out[size], fmt, ap); va_end(ap); } else { out = buffer; sprintf(out, "debug(pam_u2f): malloc failed when trying to log\n"); } if (debug_file == (FILE *)-1) { syslog(LOG_AUTHPRIV | LOG_DEBUG, "%s", out); } else { fprintf(debug_file, "%s\n", out); } if (out != buffer) { free(out); } #else /* Windows, MAC */ va_start(ap, fmt); fprintf(debug_file, DEBUG_STR, file, line, func ); vfprintf(debug_file, fmt, ap); fprintf(debug_file, "\n"); va_end(ap); #endif /* __linux__ */ }
void DebugPrintf(const char *format, ...) { va_list args; va_start( args, format ); vsprintf( DebugStr, format, args ); va_end( args ); }
void CPLErrorV(CPLErr eErrClass, int err_no, const char *fmt, va_list args ) { CPLErrorContext *psCtx = CPLGetErrorContext(); if (psCtx->nFailureIntoWarning > 0 && eErrClass == CE_Failure) eErrClass = CE_Warning; /* -------------------------------------------------------------------- */ /* Expand the error message */ /* -------------------------------------------------------------------- */ #if defined(HAVE_VSNPRINTF) { int nPR; va_list wrk_args; #ifdef va_copy va_copy( wrk_args, args ); #else wrk_args = args; #endif /* -------------------------------------------------------------------- */ /* If CPL_ACCUM_ERROR_MSG=ON accumulate the error messages, */ /* rather than just replacing the last error message. */ /* -------------------------------------------------------------------- */ int nPreviousSize = 0; if ( psCtx->psHandlerStack != NULL && EQUAL(CPLGetConfigOption( "CPL_ACCUM_ERROR_MSG", "" ), "ON")) { nPreviousSize = strlen(psCtx->szLastErrMsg); if (nPreviousSize) { if (nPreviousSize + 1 + 1 >= psCtx->nLastErrMsgMax) { psCtx->nLastErrMsgMax *= 3; psCtx = (CPLErrorContext *) CPLRealloc(psCtx, sizeof(CPLErrorContext) - DEFAULT_LAST_ERR_MSG_SIZE + psCtx->nLastErrMsgMax + 1); CPLSetTLS( CTLS_ERRORCONTEXT, psCtx, TRUE ); } psCtx->szLastErrMsg[nPreviousSize] = '\n'; psCtx->szLastErrMsg[nPreviousSize+1] = '0'; nPreviousSize ++; } } while( ((nPR = vsnprintf( psCtx->szLastErrMsg+nPreviousSize, psCtx->nLastErrMsgMax-nPreviousSize, fmt, wrk_args )) == -1 || nPR >= psCtx->nLastErrMsgMax-nPreviousSize-1) && psCtx->nLastErrMsgMax < 1000000 ) { #ifdef va_copy va_end( wrk_args ); va_copy( wrk_args, args ); #else wrk_args = args; #endif psCtx->nLastErrMsgMax *= 3; psCtx = (CPLErrorContext *) CPLRealloc(psCtx, sizeof(CPLErrorContext) - DEFAULT_LAST_ERR_MSG_SIZE + psCtx->nLastErrMsgMax + 1); CPLSetTLS( CTLS_ERRORCONTEXT, psCtx, TRUE ); } va_end( wrk_args ); } #else vsprintf( psCtx->szLastErrMsg, fmt, args); #endif /* -------------------------------------------------------------------- */ /* If the user provided his own error handling function, then */ /* call it, otherwise print the error to stderr and return. */ /* -------------------------------------------------------------------- */ psCtx->nLastErrNo = err_no; psCtx->eLastErrType = eErrClass; if( CPLGetConfigOption("CPL_LOG_ERRORS",NULL) != NULL ) CPLDebug( "CPLError", "%s", psCtx->szLastErrMsg ); /* -------------------------------------------------------------------- */ /* Invoke the current error handler. */ /* -------------------------------------------------------------------- */ if( psCtx->psHandlerStack != NULL ) { psCtx->psHandlerStack->pfnHandler(eErrClass, err_no, psCtx->szLastErrMsg); } else { CPLMutexHolderD( &hErrorMutex ); if( pfnErrorHandler != NULL ) pfnErrorHandler(eErrClass, err_no, psCtx->szLastErrMsg); } if( eErrClass == CE_Fatal ) abort(); }
void VHiSax_putstatus(struct IsdnCardState *cs, char *head, char *fmt, va_list args) { /* if head == NULL the fmt contains the full info */ u_long flags; int count, i; u_char *p; isdn_ctrl ic; int len; if (!cs) { printk(KERN_WARNING "HiSax: No CardStatus for message"); return; } spin_lock_irqsave(&cs->statlock, flags); p = tmpbuf; if (head) { p += jiftime(p, jiffies); p += sprintf(p, " %s", head); p += vsprintf(p, fmt, args); *p++ = '\n'; *p = 0; len = p - tmpbuf; p = tmpbuf; } else { p = fmt; len = strlen(fmt); } if (len > HISAX_STATUS_BUFSIZE) { spin_unlock_irqrestore(&cs->statlock, flags); printk(KERN_WARNING "HiSax: status overflow %d/%d\n", len, HISAX_STATUS_BUFSIZE); return; } count = len; i = cs->status_end - cs->status_write + 1; if (i >= len) i = len; len -= i; memcpy(cs->status_write, p, i); cs->status_write += i; if (cs->status_write > cs->status_end) cs->status_write = cs->status_buf; p += i; if (len) { memcpy(cs->status_write, p, len); cs->status_write += len; } #ifdef KERNELSTACK_DEBUG i = (ulong) & len - current->kernel_stack_page; sprintf(tmpbuf, "kstack %s %lx use %ld\n", current->comm, current->kernel_stack_page, i); len = strlen(tmpbuf); for (p = tmpbuf, i = len; i > 0; i--, p++) { *cs->status_write++ = *p; if (cs->status_write > cs->status_end) cs->status_write = cs->status_buf; count++; } #endif spin_unlock_irqrestore(&cs->statlock, flags); if (count) { ic.command = ISDN_STAT_STAVAIL; ic.driver = cs->myid; ic.arg = count; cs->iif.statcallb(&ic); } }
void CPLDebug( const char * pszCategory, const char * pszFormat, ... ) { CPLErrorContext *psCtx = CPLGetErrorContext(); char *pszMessage; va_list args; const char *pszDebug = CPLGetConfigOption("CPL_DEBUG",NULL); #define ERROR_MAX 25000 /* -------------------------------------------------------------------- */ /* Does this message pass our current criteria? */ /* -------------------------------------------------------------------- */ if( pszDebug == NULL ) return; if( !EQUAL(pszDebug,"ON") && !EQUAL(pszDebug,"") ) { size_t i, nLen = strlen(pszCategory); for( i = 0; pszDebug[i] != '\0'; i++ ) { if( EQUALN(pszCategory,pszDebug+i,nLen) ) break; } if( pszDebug[i] == '\0' ) return; } /* -------------------------------------------------------------------- */ /* Allocate a block for the error. */ /* -------------------------------------------------------------------- */ pszMessage = (char *) VSIMalloc( ERROR_MAX ); if( pszMessage == NULL ) return; /* -------------------------------------------------------------------- */ /* Dal -- always log a timestamp as the first part of the line */ /* to ensure one is looking at what one should be looking at! */ /* -------------------------------------------------------------------- */ pszMessage[0] = '\0'; #ifdef TIMESTAMP_DEBUG if( CPLGetConfigOption( "CPL_TIMESTAMP", NULL ) != NULL ) { strcpy( pszMessage, VSICTime( VSITime(NULL) ) ); // On windows anyway, ctime puts a \n at the end, but I'm not // convinced this is standard behaviour, so we'll get rid of it // carefully if (pszMessage[strlen(pszMessage) -1 ] == '\n') { pszMessage[strlen(pszMessage) - 1] = 0; // blow it out } strcat( pszMessage, ": " ); } #endif /* -------------------------------------------------------------------- */ /* Add the category. */ /* -------------------------------------------------------------------- */ strcat( pszMessage, pszCategory ); strcat( pszMessage, ": " ); /* -------------------------------------------------------------------- */ /* Format the application provided portion of the debug message. */ /* -------------------------------------------------------------------- */ va_start(args, pszFormat); #if defined(HAVE_VSNPRINTF) vsnprintf(pszMessage+strlen(pszMessage), ERROR_MAX - strlen(pszMessage), pszFormat, args); #else vsprintf(pszMessage+strlen(pszMessage), pszFormat, args); #endif va_end(args); /* -------------------------------------------------------------------- */ /* Invoke the current error handler. */ /* -------------------------------------------------------------------- */ if( psCtx->psHandlerStack != NULL ) { psCtx->psHandlerStack->pfnHandler( CE_Debug, CPLE_None, pszMessage ); } else { CPLMutexHolderD( &hErrorMutex ); if( pfnErrorHandler != NULL ) pfnErrorHandler( CE_Debug, CPLE_None, pszMessage ); } VSIFree( pszMessage ); }
/* * Usage: verror(priority, name, format, args...); * NB: don't pass more than 8K per call */ void verror(int priority, char *name, char *fmt, ...) { char buf[8192], tbuf[100], *bufp = buf; va_list args; time_t t = time(NULL); size_t l; static time_t last_time = 0; /* To improve error reporting */ if (priority == ERR_FATAL && t - last_time > 10) dump_tcl_stack(); last_time = t; if (noisy) bell(); fflush(stdout); va_start(args, fmt); /* Use static buffer for small output */ if ((l = vflen(fmt, args)) > 8192 - sizeof(tbuf)+2) { if (NULL == (bufp = (char *)xmalloc(l + sizeof(tbuf)+2))) { verror(ERR_FATAL, "verror", "out of memory"); return; } } strftime(tbuf, sizeof(tbuf)-1, "%a %d %b %H:%M:%S %Y", localtime(&t)); sprintf(bufp, "%s %s: ", tbuf, name); if (priority == ERR_FATAL && win_init) { fputs(bufp, stderr); vfprintf(stderr, fmt, args); fputc('\n', stderr); } l = strlen(bufp); vsprintf(&bufp[l], fmt, args); log_file(NULL, &bufp[l]); strcat(&bufp[l], "\n"); #ifdef _WIN32 if (priority == ERR_FATAL) { /* 7/1/99 johnt - log the messages to the Event Viewer on windows, as we don't always have stderr */ char *a[] = {bufp}; if( !eventLogHandle){ eventLogHandle = RegisterEventSource(NULL,EVENT_SOURCE); /* get default application handle */ } ReportEvent(eventLogHandle, priority==ERR_FATAL?EVENTLOG_ERROR_TYPE:EVENTLOG_WARNING_TYPE, 0, 0, NULL, 1, 0, a, NULL); } #endif tout_update_stream(2, bufp, 0, NULL); if (bufp != buf) { xfree(bufp); } va_end(args); }
void vsyslog(int pri, const char *fmt, va_list ap) { FILE *f; char *s; time_t now; char buf[1024]; char newfmt[1024]; int count = 0; char *p, *d; int fd; int send_error = 0; int saveerrno = errno; int savewinerror = GetLastError(); int savewinsockerror = WSAGetLastError(); switch(LOG_PRI(pri)) { case LOG_DEBUG: s = "DEBUG:"; break; case LOG_INFO: s = "INFO:"; break; case LOG_ERR: s = "ERROR:"; break; case LOG_NOTICE: s = "NOTICE:"; break; case LOG_WARNING: s = "WARNING:"; break; default: s = "UNKNOWN:"; break; } for(p = (char *)fmt, d = newfmt; *p;) { if(*p == '%') { if(p[1] == 'm') { if(saveerrno) d += sprintf(d, "%s", strerror(saveerrno)); else if(savewinerror) d += sprintf(d, "%s", winstrerror(savewinerror)); else if(savewinsockerror) d += sprintf(d, "%s", wsstrerror(savewinsockerror)); p += 2; } else if(p[1] == 'w') { if(savewinerror) d += sprintf(d, "%s", winstrerror(savewinerror)); else if(savewinsockerror) d += sprintf(d, "%s", wsstrerror(savewinsockerror)); p += 2; } else { *d++ = *p++; } } else { *d++ = *p++; } } *d = 0; time(&now); count = sprintf(buf, "<%d>%.15s %s", pri, ctime(&now) + 4, __LogTag, s); if(__LogStat & LOG_PID) count += sprintf(buf + count, "[%x]", getpid()); count += sprintf(buf + count, ":"); count += vsprintf(buf + count, newfmt, ap); if(buf[count - 1] != '\n') count += sprintf(buf + count, "\n"); /* output to stderr */ if(__LogStat & LOG_PERROR) fprintf(stderr, "%s: %s", s, buf); if(!__LogOpened) openlog(__LogTag, __LogStat | LOG_NDELAY, 0); #ifndef UNDER_CE if(sendto(LogSocket, buf, strlen(buf), 0, (struct sockaddr *)& LogAddr, sizeof(struct sockaddr_in)) == SOCKET_ERROR) { send_error = WSAGetLastError(); } if((__LogStat & LOG_CONS) && (fd = open(_PATH_CONSOLE, O_WRONLY, 0)) >= 0) { _write(fd, buf, strlen(buf)); _close(fd); } #endif if((fd = open(_PATH_LOG, O_WRONLY|O_APPEND|O_CREAT,666)) > 0) { write(fd, s, strlen(s)); write(fd, buf + 3, strlen(buf) - 3); close(fd); } }
void aiovFileLogger(int priority, const char *format, va_list optional_arguments) { int n = 0; int error = EXIT_SUCCESS; int internalError = EXIT_SUCCESS; const int LogMask = setlogmask(0); /* Check priority against setlogmask values. */ if ((LOG_MASK(LOG_PRI(priority)) & LogMask) != 0) { va_list optional_arguments; char logMsg[2048]; char logFormat[1024]; char *cursor = logFormat; struct tm now_tm; time_t now; (void) time(&now); cursor += strftime(cursor, sizeof (logFormat), "%h %e %T ", localtime_r(&now, &now_tm)); if (LogTag) { cursor += sprintf(cursor, "%s: ", LogTag); } if (LogStat & LOG_PID) { if (LogStat & LOG_TID) { const pid_t tid = gettid(); n = sprintf(cursor, "[%d:%d]", (int) getpid(), (int) tid); } else { n = sprintf(cursor, "[%d]", (int) getpid()); } cursor += n; } if (LogStat & LOG_RDTSC) { const unsigned long long int t = rdtsc(); cursor += sprintf(cursor, "(%llu)", t); } /* (LogStat & LOG_CLOCK) */ if (LogStat & LOG_LEVEL) { switch (LOG_PRI(priority)) { case LOG_EMERG: n = sprintf(cursor, "* Emergency * %s", format); break; case LOG_ALERT: n = sprintf(cursor, "* Alert * %s", format); break; case LOG_CRIT: n = sprintf(cursor, "* Critical * %s", format); break; case LOG_ERR: n = sprintf(cursor, "* Error * %s", format); break; case LOG_WARNING: n = sprintf(cursor, "* Warning * %s", format); break; case LOG_NOTICE: n = sprintf(cursor, "* Notice * %s", format); break; case LOG_INFO: n = sprintf(cursor, "* Info * %s", format); break; case LOG_DEBUG: n = sprintf(cursor, "* Debug * %s", format); break; default: n = sprintf(cursor, "* <%d> * %s", priority, format); } /* switch(priority) */ } /* (LogStat & LOG_LEVEL) */ n = vsprintf(logMsg, logFormat, optional_arguments); #if 0 error = pthread_mutex_lock(&fileLock); if (likely(EXIT_SUCCESS == error)) { if (unlikely(-1 == logFile)) { error = createFile(); /* error already logged */ } if (likely(EXIT_SUCCESS == error)) { ssize_t written = write(logFile, logMsg, n); if (written > 0) { if (unlikely(written != n)) { ERROR_MSG("only %d byte(s) of %d has been written to %s", written, n, fullFileName); } fileSize += written; if ((LOG_FILE_ROTATE & LogStat) || (LOG_FILE_HISTO & LogStat)) { if (fileSize >= MaxSize) { close(logFile); logFile = -1; } } } else if (0 == written) { WARNING_MSG("nothing has been written in %s", fullFileName); } else { error = errno; ERROR_MSG("write to %s error %d (%m)", fullFileName, error); } } internalError = pthread_mutex_unlock(&fileLock); if (internalError != EXIT_SUCCESS) { ERROR_MSG("pthread_mutex_lock fileLock error %d (%s)", internalError, strerror(internalError)); if (EXIT_SUCCESS == error) { error = internalError; } } #endif } else { ERROR_MSG("pthread_mutex_lock fileLock error %d (%s)", error, strerror(error)); } } /*return n;*/ }
int sprintf_s(char *buffer, const char *str, va_list args) { return vsprintf(buffer, str, args); }