void safe_fprintf(FILE *f, const char *fmt, ...) { char fmtbuff_stack[256]; /* Place to format the printf() string. */ char outbuff[256]; /* Buffer for outgoing characters. */ char *fmtbuff_heap; /* If fmtbuff_stack is too small, we use malloc */ char *fmtbuff; /* Pointer to fmtbuff_stack or fmtbuff_heap. */ int fmtbuff_length; int length, n; va_list ap; const char *p; unsigned i; wchar_t wc; char try_wc; /* Use a stack-allocated buffer if we can, for speed and safety. */ fmtbuff_heap = NULL; fmtbuff_length = sizeof(fmtbuff_stack); fmtbuff = fmtbuff_stack; /* Try formatting into the stack buffer. */ va_start(ap, fmt); length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap); va_end(ap); /* If the result was too large, allocate a buffer on the heap. */ while (length < 0 || length >= fmtbuff_length) { if (length >= fmtbuff_length) fmtbuff_length = length+1; else if (fmtbuff_length < 8192) fmtbuff_length *= 2; else if (fmtbuff_length < 1000000) fmtbuff_length += fmtbuff_length / 4; else { length = fmtbuff_length; fmtbuff_heap[length-1] = '\0'; break; } free(fmtbuff_heap); fmtbuff_heap = malloc(fmtbuff_length); /* Reformat the result into the heap buffer if we can. */ if (fmtbuff_heap != NULL) { fmtbuff = fmtbuff_heap; va_start(ap, fmt); length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap); va_end(ap); } else { /* Leave fmtbuff pointing to the truncated * string in fmtbuff_stack. */ length = sizeof(fmtbuff_stack) - 1; break; } } /* Note: mbrtowc() has a cleaner API, but mbtowc() seems a bit * more portable, so we use that here instead. */ if (mbtowc(NULL, NULL, 1) == -1) { /* Reset the shift state. */ /* mbtowc() should never fail in practice, but * handle the theoretical error anyway. */ free(fmtbuff_heap); return; } /* Write data, expanding unprintable characters. */ p = fmtbuff; i = 0; try_wc = 1; while (*p != '\0') { /* Convert to wide char, test if the wide * char is printable in the current locale. */ if (try_wc && (n = mbtowc(&wc, p, length)) != -1) { length -= n; if (iswprint(wc) && wc != L'\\') { /* Printable, copy the bytes through. */ while (n-- > 0) outbuff[i++] = *p++; } else { /* Not printable, format the bytes. */ while (n-- > 0) i += (unsigned)bsdtar_expand_char( outbuff, i, *p++); } } else { /* After any conversion failure, don't bother * trying to convert the rest. */ i += (unsigned)bsdtar_expand_char(outbuff, i, *p++); try_wc = 0; } /* If our output buffer is full, dump it and keep going. */ if (i > (sizeof(outbuff) - 20)) { outbuff[i] = '\0'; fprintf(f, "%s", outbuff); i = 0; } } outbuff[i] = '\0'; fprintf(f, "%s", outbuff); /* If we allocated a heap-based formatting buffer, free it now. */ free(fmtbuff_heap); }
/* * Log the message to the logfile. Include the severity and * a time stamp. */ int vradlog(int lvl, const char *fmt, va_list ap) { struct main_config_t *myconfig = &mainconfig; unsigned char *p; char buffer[8192]; int len; /* * NOT debugging, and trying to log debug messages. * * Throw the message away. */ if (!debug_flag && (lvl == L_DBG)) { return 0; } /* * If we don't want any messages, then * throw them away. */ if (myconfig->radlog_dest == RADLOG_NULL) { return 0; } *buffer = '\0'; len = 0; /* * Don't print timestamps to syslog, it does that for us. * Don't print timestamps for low levels of debugging. * * Print timestamps for non-debugging, and for high levels * of debugging. */ if ((myconfig->radlog_dest != RADLOG_SYSLOG) && (debug_flag != 1) && (debug_flag != 2)) { const char *s; time_t timeval; timeval = time(NULL); CTIME_R(&timeval, buffer + len, sizeof(buffer) - len - 1); s = fr_int2str(levels, (lvl & ~L_CONS), ": "); strcat(buffer, s); len = strlen(buffer); } vsnprintf(buffer + len, sizeof(buffer) - len - 1, fmt, ap); /* * Filter out characters not in Latin-1. */ for (p = (unsigned char *)buffer; *p != '\0'; p++) { if (*p == '\r' || *p == '\n') *p = ' '; else if (*p == '\t') continue; else if (*p < 32 || (*p >= 128 && *p <= 160)) *p = '?'; } strcat(buffer, "\n"); switch (myconfig->radlog_dest) { #ifdef HAVE_SYSLOG_H case RADLOG_SYSLOG: switch(lvl & ~L_CONS) { case L_DBG: lvl = LOG_DEBUG; break; case L_AUTH: lvl = LOG_NOTICE; break; case L_PROXY: lvl = LOG_NOTICE; break; case L_ACCT: lvl = LOG_NOTICE; break; case L_INFO: lvl = LOG_INFO; break; case L_ERR: lvl = LOG_ERR; break; } syslog(lvl, "%s", buffer); break; #endif case RADLOG_FILES: case RADLOG_STDOUT: case RADLOG_STDERR: write(myconfig->radlog_fd, buffer, strlen(buffer)); break; default: case RADLOG_NULL: /* should have been caught above */ break; } return 0; }
void setproctitle(const char *fmt, ...) { static struct ps_strings *ps_strings; static char *buf = NULL; static char *obuf = NULL; static char **oargv, *kbuf; static int oargc = -1; static char *nargv[2] = { NULL, NULL }; char **nargvp; int nargc; int i; va_list ap; size_t len; unsigned long ul_ps_strings; int oid[4]; if (buf == NULL) { buf = malloc(SPT_BUFSIZE); if (buf == NULL) return; nargv[0] = buf; } if (obuf == NULL ) { obuf = malloc(SPT_BUFSIZE); if (obuf == NULL) return; *obuf = '\0'; } va_start(ap, fmt); if (fmt) { buf[SPT_BUFSIZE - 1] = '\0'; if (fmt[0] == '-') { /* skip program name prefix */ fmt++; len = 0; } else { /* print program name heading for grep */ (void)snprintf(buf, SPT_BUFSIZE, "%s: ", _getprogname()); len = strlen(buf); } /* print the argument string */ (void) vsnprintf(buf + len, SPT_BUFSIZE - len, fmt, ap); nargvp = nargv; nargc = 1; kbuf = buf; } else if (*obuf != '\0') { /* Idea from NetBSD - reset the title on fmt == NULL */ nargvp = oargv; nargc = oargc; kbuf = obuf; } else /* Nothing to restore */ return; va_end(ap); /* Set the title into the kernel cached command line */ oid[0] = CTL_KERN; oid[1] = KERN_PROC; oid[2] = KERN_PROC_ARGS; oid[3] = getpid(); sysctl(oid, 4, 0, 0, kbuf, strlen(kbuf) + 1); if (ps_strings == NULL) { len = sizeof(ul_ps_strings); if (sysctlbyname("kern.ps_strings", &ul_ps_strings, &len, NULL, 0) == -1) ul_ps_strings = PS_STRINGS; ps_strings = (struct ps_strings *)ul_ps_strings; } /* PS_STRINGS points to zeroed memory on a style #2 kernel */ if (ps_strings->ps_argvstr) { /* style #3 */ if (oargc == -1) { /* Record our original args */ oargc = ps_strings->ps_nargvstr; oargv = ps_strings->ps_argvstr; for (i = len = 0; i < oargc; i++) { /* * The program may have scribbled into its * argv array, e.g., to remove some arguments. * If that has happened, break out before * trying to call strlen on a NULL pointer. */ if (oargv[i] == NULL) { oargc = i; break; } snprintf(obuf + len, SPT_BUFSIZE - len, "%s%s", len ? " " : "", oargv[i]); if (len) len++; len += strlen(oargv[i]); if (len >= SPT_BUFSIZE) break; } } ps_strings->ps_nargvstr = nargc; ps_strings->ps_argvstr = nargvp; } else { /* style #2 - we can only restore our first arg :-( */ if (*obuf == '\0') strncpy(obuf, OLD_PS_STRINGS->old_ps_argvstr, SPT_BUFSIZE - 1); OLD_PS_STRINGS->old_ps_nargvstr = 1; OLD_PS_STRINGS->old_ps_argvstr = nargvp[0]; } }
int Mtrace(char *fmt,...) { static int inMtraceNow; int len; char *eolp; va_list argp; /* Mtrace not configured or disabled, so just return. */ if (!Mip || Mip->off) return(0); /* This may be called from interrupt and/or non-interrupt space of * an application, so we must deal with possible reentrancy here. */ if (inMtraceNow) { Mip->reentered++; return(0); } inMtraceNow = 1; Mip->ptr += snprintf(Mip->ptr,MAXLINSIZE,"\n<%04d> ",Mip->sno++); va_start(argp,fmt); len = vsnprintf(Mip->ptr,MAXLINSIZE,fmt,argp); va_end(argp); /* Strip all CR/LFs from the incoming string. * The incoming string can have CR/LFs in it; however, they are stripped * so that the format of the dump is stable (one line per Mtrace call). * Notice that the top line of this function inserts a newline ahead * of the sequence number; hence, additional CR/LFs in the text would * just confuse the output. */ eolp = Mip->ptr; while(*eolp) { if ((*eolp == '\r') || (*eolp == '\n')) { strcpy(eolp,eolp+1); len--; } else eolp++; } /* If print flag is set, then dump to the console... */ if (Mip->mode & MODE_PRINT) { int i; for(i=0;i<len;i++) putchar(*Mip->ptr++); putchar('\n'); } else Mip->ptr += len; if (Mip->ptr >= Mip->end) { Mip->ptr = Mip->base; if (Mip->mode & MODE_NOWRAP) Mip->off = 1; else Mip->wrap++; } /* Flush the d-cache of the mtrace buffer and Mip structure after each * transfer... * This is important because if this is being accessed from an * application that has d-cache enabled, then the hardware is reset, * there is a chance that the data written was in cache and would be * lost. */ flushDcache((char *)Mip,sizeof(struct mtInfo)); flushDcache((char *)Mip->base,Mip->end - Mip->base); inMtraceNow = 0; return(len); }
void Log::vlog(LogFilterType filter, LogLevel level, char const* str, va_list argptr) { char text[MAX_QUERY_LEN]; vsnprintf(text, MAX_QUERY_LEN, str, argptr); write(new LogMessage(level, filter, text)); }
/** * kthread_create - create a kthread. * @threadfn: the function to run until signal_pending(current). * @data: data ptr for @threadfn. * @namefmt: printf-style name for the thread. * * Description: This helper function creates and names a kernel * thread. The thread will be stopped: use wake_up_process() to start * it. See also kthread_run(), kthread_create_on_cpu(). * * When woken, the thread will run @threadfn() with @data as its * argument. @threadfn() can either call do_exit() directly if it is a * standalone thread for which noone will call kthread_stop(), or * return when 'kthread_should_stop()' is true (which means * kthread_stop() has been called). The return value should be zero * or a negative error number; it will be passed to kthread_stop(). * * Returns a task_struct or ERR_PTR(-ENOMEM). */ struct task_struct *kthread_create(int (*threadfn)(void *data), void *data, const char namefmt[], ...) { struct kthread_create_info create; create.threadfn = threadfn; create.data = data; init_completion(&create.done); spin_lock(&kthread_create_lock); list_add_tail(&create.list, &kthread_create_list); spin_unlock(&kthread_create_lock); wake_up_process(kthreadd_task); wait_for_completion(&create.done); if (!IS_ERR(create.result)) { struct sched_param param = { .sched_priority = 0 }; va_list args; va_start(args, namefmt); vsnprintf(create.result->comm, sizeof(create.result->comm), namefmt, args); va_end(args); int policy = SCHED_NORMAL; #ifdef CONFIG_TIVO int i; int bFound = 0; for (i=0; i<sizeof(s_tvKthreadInfoTable)/sizeof(TvKthreadInfo); i++) { if (!strcmp(s_tvKthreadInfoTable[i].name, create.result->comm)) { if (s_tvKthreadInfoTable[i].policy != -1) { policy = s_tvKthreadInfoTable[i].policy; param.sched_priority = s_tvKthreadInfoTable[i].rt_priority; } bFound = 1; break; } } if (!bFound) { printk("--- Unknown kthread %s is lanched?\n", create.result->comm); } #endif /* * root may have changed our (kthreadd's) priority or CPU mask. * The kernel thread should not inherit these properties, and should * use specific RT priorities for some threads. */ sched_setscheduler_nocheck(create.result, policy, ¶m); set_user_nice(create.result, KTHREAD_NICE_LEVEL); set_cpus_allowed_ptr(create.result, cpu_all_mask); } return create.result; } EXPORT_SYMBOL(kthread_create); /** * kthread_bind - bind a just-created kthread to a cpu. * @k: thread created by kthread_create(). * @cpu: cpu (might not be online, must be possible) for @k to run on. * * Description: This function is equivalent to set_cpus_allowed(), * except that @cpu doesn't need to be online, and the thread must be * stopped (i.e., just returned from kthread_create()). */ void kthread_bind(struct task_struct *k, unsigned int cpu) { /* Must have done schedule() in kthread() before we set_task_cpu */ if (!wait_task_inactive(k, TASK_UNINTERRUPTIBLE)) { WARN_ON(1); return; } set_task_cpu(k, cpu); k->cpus_allowed = cpumask_of_cpu(cpu); k->rt.nr_cpus_allowed = 1; k->flags |= PF_THREAD_BOUND; } EXPORT_SYMBOL(kthread_bind); /** * kthread_stop - stop a thread created by kthread_create(). * @k: thread created by kthread_create(). * * Sets kthread_should_stop() for @k to return true, wakes it, and * waits for it to exit. This can also be called after kthread_create() * instead of calling wake_up_process(): the thread will exit without * calling threadfn(). * * If threadfn() may call do_exit() itself, the caller must ensure * task_struct can't go away. * * Returns the result of threadfn(), or %-EINTR if wake_up_process() * was never called. */ int kthread_stop(struct task_struct *k) { struct kthread *kthread; int ret; trace_sched_kthread_stop(k); get_task_struct(k); kthread = to_kthread(k); barrier(); /* it might have exited */ if (k->vfork_done != NULL) { kthread->should_stop = 1; wake_up_process(k); wait_for_completion(&kthread->exited); } ret = k->exit_code; put_task_struct(k); trace_sched_kthread_stop_ret(ret); return ret; } EXPORT_SYMBOL(kthread_stop); int kthreadd(void *unused) { struct task_struct *tsk = current; /* Setup a clean context for our children to inherit. */ set_task_comm(tsk, "kthreadd"); ignore_signals(tsk); set_user_nice(tsk, KTHREAD_NICE_LEVEL); set_cpus_allowed_ptr(tsk, cpu_all_mask); set_mems_allowed(node_possible_map); current->flags |= PF_NOFREEZE | PF_FREEZER_NOSIG; for (;;) { set_current_state(TASK_INTERRUPTIBLE); if (list_empty(&kthread_create_list)) schedule(); __set_current_state(TASK_RUNNING); spin_lock(&kthread_create_lock); while (!list_empty(&kthread_create_list)) { struct kthread_create_info *create; create = list_entry(kthread_create_list.next, struct kthread_create_info, list); list_del_init(&create->list); spin_unlock(&kthread_create_lock); create_kthread(create); spin_lock(&kthread_create_lock); } spin_unlock(&kthread_create_lock); } return 0; }
/* Copyright (C) 2004 Manuel Novoa III <*****@*****.**> * * GNU Library General Public License (LGPL) version 2 or later. * * Dedicated to Toni. See uClibc/DEDICATION.mjn3 for details. */ #include "_stdio.h" #include <stdarg.h> #ifndef __STDIO_HAS_VSNPRINTF #warning Skipping snprintf since no vsnprintf! #else int snprintf(char *__restrict buf, size_t size, const char * __restrict format, ...) { va_list arg; int rv; va_start(arg, format); rv = vsnprintf(buf, size, format, arg); va_end(arg); return rv; } #endif
//inline bool vformat(const char * fmt, va_list vl, std::string & str_output) //static bool OTString::vformat(const char * fmt, va_list * pvl, std::string & str_Output) { OT_ASSERT(NULL != fmt); OT_ASSERT(NULL != pvl); // ------------------ int32_t size=0; int32_t nsize=0; char * buffer = NULL; va_list args; #ifdef _WIN32 va_list args_2 = *pvl; //windows only. args = *pvl; size = _vscprintf(fmt,args) + 1; #else va_copy(args, *pvl); size = 512; #endif // ------------------------------------ buffer = new char[size+100]; OT_ASSERT(NULL != buffer); OTPassword::zeroMemory(buffer, size+100); // ------------------------------------ #ifdef _WIN32 nsize = vsnprintf_s(buffer,size,size,fmt,args_2); #else nsize = vsnprintf(buffer,size,fmt,args); va_end(args); #endif OT_ASSERT(nsize >= 0); // fail -- delete buffer and try again // If nsize was 1024 bytes, then that would mean that it printed 1024 characters, // even though the actual string must be 1025 in length (to have room for the null // terminator.) // If size, the ACTUAL buffer, was 1024 (that is, if size <= nsize) then size would // LACK the necessary space to store the 1025th byte containing the null terminator. // Therefore we are forced to delete the buffer and make one that is nsize+1, so that // it will be 1025 bytes and thus have the necessary space for the terminator // if (size <= nsize) { size = nsize+1; delete buffer; buffer = NULL; buffer = new char[size+100]; OT_ASSERT(NULL != buffer); OTPassword::zeroMemory(buffer, size+100); // ------------------------------------ #ifdef _WIN32 nsize = vsnprintf_s(buffer,size,size,fmt,*pvl); va_end(args); va_end(args_2); #else nsize = vsnprintf(buffer,size,fmt,*pvl); #endif // ------------------------------------ OT_ASSERT( nsize >= 0 ); } OT_ASSERT( size > nsize); // ------------------------------------ str_Output = buffer; delete buffer; buffer = NULL; return true; }
static void dump_kernel_log(struct fiq_debugger_state *state) { char buf[512]; size_t len; struct kmsg_dumper dumper = { .active = true }; kmsg_dump_rewind_nolock(&dumper); while (kmsg_dump_get_line_nolock(&dumper, true, buf, sizeof(buf) - 1, &len)) { buf[len] = 0; debug_puts(state, buf); } } static char *mode_name(unsigned cpsr) { switch (cpsr & MODE_MASK) { case USR_MODE: return "USR"; case FIQ_MODE: return "FIQ"; case IRQ_MODE: return "IRQ"; case SVC_MODE: return "SVC"; case ABT_MODE: return "ABT"; case UND_MODE: return "UND"; case SYSTEM_MODE: return "SYS"; default: return "???"; } } static int debug_printf(void *cookie, const char *fmt, ...) { struct fiq_debugger_state *state = cookie; char buf[256]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); debug_puts(state, buf); return state->debug_abort; } /* Safe outside fiq context */ static int debug_printf_nfiq(void *cookie, const char *fmt, ...) { struct fiq_debugger_state *state = cookie; char buf[256]; va_list ap; unsigned long irq_flags; va_start(ap, fmt); vsnprintf(buf, 128, fmt, ap); va_end(ap); local_irq_save(irq_flags); debug_puts(state, buf); debug_uart_flush(state); local_irq_restore(irq_flags); return state->debug_abort; } static void dump_regs(struct fiq_debugger_state *state, unsigned *regs) { debug_printf(state, " r0 %08x r1 %08x r2 %08x r3 %08x\n", regs[0], regs[1], regs[2], regs[3]); debug_printf(state, " r4 %08x r5 %08x r6 %08x r7 %08x\n", regs[4], regs[5], regs[6], regs[7]); debug_printf(state, " r8 %08x r9 %08x r10 %08x r11 %08x mode %s\n", regs[8], regs[9], regs[10], regs[11], mode_name(regs[16])); if ((regs[16] & MODE_MASK) == USR_MODE) debug_printf(state, " ip %08x sp %08x lr %08x pc %08x " "cpsr %08x\n", regs[12], regs[13], regs[14], regs[15], regs[16]); else debug_printf(state, " ip %08x sp %08x lr %08x pc %08x " "cpsr %08x spsr %08x\n", regs[12], regs[13], regs[14], regs[15], regs[16], regs[17]); }
/* * Add an environment variable for [eid] to the container [zsp]. * * The variable name is the concatenation of [prefix] and [name] converted to * uppercase with non-alphanumeric characters converted to underscores; * [prefix] is optional, and [name] must begin with an alphabetic character. * If the converted variable name already exists within the container [zsp], * its existing value will be replaced with the new value. * * The variable value is specified by the format string [fmt]. * * Returns 0 on success, and -1 on error (with errno set). * * All environment variables in [zsp] should be added through this function. */ static int _zed_event_add_var(uint64_t eid, zed_strings_t *zsp, const char *prefix, const char *name, const char *fmt, ...) { char keybuf[MAXBUF]; char valbuf[MAXBUF]; char *dstp; const char *srcp; const char *lastp; int n; int buflen; va_list vargs; assert(zsp != NULL); assert(fmt != NULL); if (!name) { errno = EINVAL; zed_log_msg(LOG_WARNING, "Failed to add variable for eid=%llu: Name is empty", eid); return (-1); } else if (!isalpha(name[0])) { errno = EINVAL; zed_log_msg(LOG_WARNING, "Failed to add variable for eid=%llu: " "Name \"%s\" is invalid", eid, name); return (-1); } /* * Construct the string key by converting PREFIX (if present) and NAME. */ dstp = keybuf; lastp = keybuf + sizeof (keybuf); if (prefix) { for (srcp = prefix; *srcp && (dstp < lastp); srcp++) *dstp++ = isalnum(*srcp) ? toupper(*srcp) : '_'; } for (srcp = name; *srcp && (dstp < lastp); srcp++) *dstp++ = isalnum(*srcp) ? toupper(*srcp) : '_'; if (dstp == lastp) { errno = ENAMETOOLONG; zed_log_msg(LOG_WARNING, "Failed to add variable for eid=%llu: Name too long", eid); return (-1); } *dstp = '\0'; /* * Construct the string specified by "[PREFIX][NAME]=[FMT]". */ dstp = valbuf; buflen = sizeof (valbuf); n = strlcpy(dstp, keybuf, buflen); if (n >= sizeof (valbuf)) { errno = EMSGSIZE; zed_log_msg(LOG_WARNING, "Failed to add %s for eid=%llu: %s", keybuf, eid, "Exceeded buffer size"); return (-1); } dstp += n; buflen -= n; *dstp++ = '='; buflen--; if (buflen <= 0) { errno = EMSGSIZE; zed_log_msg(LOG_WARNING, "Failed to add %s for eid=%llu: %s", keybuf, eid, "Exceeded buffer size"); return (-1); } va_start(vargs, fmt); n = vsnprintf(dstp, buflen, fmt, vargs); va_end(vargs); if ((n < 0) || (n >= buflen)) { errno = EMSGSIZE; zed_log_msg(LOG_WARNING, "Failed to add %s for eid=%llu: %s", keybuf, eid, "Exceeded buffer size"); return (-1); } else if (zed_strings_add(zsp, keybuf, valbuf) < 0) { zed_log_msg(LOG_WARNING, "Failed to add %s for eid=%llu: %s", keybuf, eid, strerror(errno)); return (-1); } return (0); }
/** * Adds a variadic log-message to the message-list for the current thread. * * This function is thread-safe. * * @retval 0 Success * @retval EAGAIN Failure due to the buffer being too small for the * message. The buffer has been expanded and the client * should call this function again. * @retval EINVAL There are insufficient arguments. Error message logged. * @retval EILSEQ A wide-character code that doesn't correspond to a * valid character has been detected. Error message logged. * @retval ENOMEM Out-of-memory. Error message logged. * @retval EOVERFLOW The length of the message is greater than {INT_MAX}. * Error message logged. */ int nplVadd( const char* const fmt, /**< The message format or NULL for no message */ va_list args) /**< The arguments referenced by the format. */ { int status = 0; /* default success */ if (NULL != fmt) { List* list = getList(); if (NULL != list) { Message* msg = (NULL == list->last) ? list->first : list->last->next; status = 0; if (msg == NULL) { msg = (Message*)malloc(sizeof(Message)); if (msg == NULL) { status = errno; lock(); serror("nplVadd(): malloc(%lu) failure", (unsigned long)sizeof(Message)); unlock(); } else { char* string = (char*)malloc(DEFAULT_STRING_SIZE); if (NULL == string) { status = errno; lock(); serror("nplVadd(): malloc(%lu) failure", (unsigned long)DEFAULT_STRING_SIZE); unlock(); } else { msg->string = string; msg->size = DEFAULT_STRING_SIZE; msg->next = NULL; if (NULL == list->first) list->first = msg; /* very first message */ } } } if (0 == status) { int nbytes = vsnprintf(msg->string, msg->size, fmt, args); if (0 > nbytes) { status = errno; lock(); serror("nplVadd(): vsnprintf() failure"); unlock(); } else if (msg->size <= nbytes) { /* The buffer is too small for the message */ size_t size = nbytes + 1; char* string = (char*)malloc(size); if (NULL == string) { status = errno; lock(); serror("nplVadd(): malloc(%lu) failure", (unsigned long)size); unlock(); } else { free(msg->string); msg->string = string; msg->size = size; status = EAGAIN; } } else { if (NULL != list->last) list->last->next = msg; list->last = msg; } } /* have a message structure */ } /* message-list isn't NULL */ } /* arguments aren't NULL */ return status; }
int core_vfprintf(core_file *f, const char *fmt, va_list va) { char buf[1024]; vsnprintf(buf, sizeof(buf), fmt, va); return core_fputs(f, buf); }
static void R_warnHandler(char *format, va_list args) { char warn_buf[WARN_BUF_SIZE]; vsnprintf(warn_buf, WARN_BUF_SIZE, format, args); warning(warn_buf); }
/** * kthread_create_on_node - create a kthread. * @threadfn: the function to run until signal_pending(current). * @data: data ptr for @threadfn. * @node: memory node number. * @namefmt: printf-style name for the thread. * * Description: This helper function creates and names a kernel * thread. The thread will be stopped: use wake_up_process() to start * it. See also kthread_run(). * * If thread is going to be bound on a particular cpu, give its node * in @node, to get NUMA affinity for kthread stack, or else give -1. * When woken, the thread will run @threadfn() with @data as its * argument. @threadfn() can either call do_exit() directly if it is a * standalone thread for which no one will call kthread_stop(), or * return when 'kthread_should_stop()' is true (which means * kthread_stop() has been called). The return value should be zero * or a negative error number; it will be passed to kthread_stop(). * * Returns a task_struct or ERR_PTR(-ENOMEM). */ struct task_struct *kthread_create_on_node(int (*threadfn)(void *data), void *data, int node, const char namefmt[], ...) { struct kthread_create_info create; create.threadfn = threadfn; create.data = data; create.node = node; init_completion(&create.done); spin_lock(&kthread_create_lock); list_add_tail(&create.list, &kthread_create_list); spin_unlock(&kthread_create_lock); wake_up_process(kthreadd_task); wait_for_completion(&create.done); if (!IS_ERR(create.result)) { static const struct sched_param param = { .sched_priority = 0 }; va_list args; va_start(args, namefmt); vsnprintf(create.result->comm, sizeof(create.result->comm), namefmt, args); va_end(args); /* * root may have changed our (kthreadd's) priority or CPU mask. * The kernel thread should not inherit these properties. */ sched_setscheduler_nocheck(create.result, SCHED_NORMAL, ¶m); set_cpus_allowed_ptr(create.result, cpu_all_mask); } return create.result; } EXPORT_SYMBOL(kthread_create_on_node); /** * kthread_bind - bind a just-created kthread to a cpu. * @p: thread created by kthread_create(). * @cpu: cpu (might not be online, must be possible) for @k to run on. * * Description: This function is equivalent to set_cpus_allowed(), * except that @cpu doesn't need to be online, and the thread must be * stopped (i.e., just returned from kthread_create()). */ void kthread_bind(struct task_struct *p, unsigned int cpu) { /* Must have done schedule() in kthread() before we set_task_cpu */ if (!wait_task_inactive(p, TASK_UNINTERRUPTIBLE)) { WARN_ON(1); return; } /* It's safe because the task is inactive. */ do_set_cpus_allowed(p, cpumask_of(cpu)); p->flags |= PF_THREAD_BOUND; } EXPORT_SYMBOL(kthread_bind); /** * kthread_stop - stop a thread created by kthread_create(). * @k: thread created by kthread_create(). * * Sets kthread_should_stop() for @k to return true, wakes it, and * waits for it to exit. This can also be called after kthread_create() * instead of calling wake_up_process(): the thread will exit without * calling threadfn(). * * If threadfn() may call do_exit() itself, the caller must ensure * task_struct can't go away. * * Returns the result of threadfn(), or %-EINTR if wake_up_process() * was never called. */ int kthread_stop(struct task_struct *k) { struct kthread *kthread; int ret; trace_sched_kthread_stop(k); get_task_struct(k); kthread = to_kthread(k); barrier(); /* it might have exited */ if (k->vfork_done != NULL) { kthread->should_stop = 1; wake_up_process(k); wait_for_completion(&kthread->exited); } ret = k->exit_code; put_task_struct(k); trace_sched_kthread_stop_ret(ret); return ret; } EXPORT_SYMBOL(kthread_stop); int kthreadd(void *unused) { struct task_struct *tsk = current; /* Setup a clean context for our children to inherit. */ set_task_comm(tsk, "kthreadd"); ignore_signals(tsk); set_cpus_allowed_ptr(tsk, cpu_all_mask); set_mems_allowed(node_states[N_HIGH_MEMORY]); current->flags |= PF_NOFREEZE; for (;;) { set_current_state(TASK_INTERRUPTIBLE); if (list_empty(&kthread_create_list)) schedule(); __set_current_state(TASK_RUNNING); spin_lock(&kthread_create_lock); while (!list_empty(&kthread_create_list)) { struct kthread_create_info *create; create = list_entry(kthread_create_list.next, struct kthread_create_info, list); list_del_init(&create->list); spin_unlock(&kthread_create_lock); create_kthread(create); spin_lock(&kthread_create_lock); } spin_unlock(&kthread_create_lock); } return 0; } void __init_kthread_worker(struct kthread_worker *worker, const char *name, struct lock_class_key *key) { spin_lock_init(&worker->lock); lockdep_set_class_and_name(&worker->lock, key, name); INIT_LIST_HEAD(&worker->work_list); worker->task = NULL; }
void Log::outCommand(uint32 account, const char * str, ...) { if (!str) return; // TODO: support accountid if (m_enableLogDB && m_dbGM) { va_list ap2; va_start(ap2, str); char nnew_str[MAX_QUERY_LEN]; vsnprintf(nnew_str, MAX_QUERY_LEN, str, ap2); outDB(LOG_TYPE_GM, nnew_str); va_end(ap2); } if (m_logLevel > LOGL_NORMAL) { if (m_colored) SetColor(true, m_colors[LOGL_BASIC]); va_list ap; va_start(ap, str); vutf8printf(stdout, str, &ap); va_end(ap); if (m_colored) ResetColor(true); printf("\n"); if (logfile) { outTimestamp(logfile); va_list ap; va_start(ap, str); vfprintf(logfile, str, ap); fprintf(logfile, "\n" ); va_end(ap); fflush(logfile); } } if (m_gmlog_per_account) { if (FILE* per_file = openGmlogPerAccount (account)) { outTimestamp(per_file); va_list ap; va_start(ap, str); vfprintf(per_file, str, ap); fprintf(per_file, "\n" ); va_end(ap); fclose(per_file); } } else if (gmLogfile) { outTimestamp(gmLogfile); va_list ap; va_start(ap, str); vfprintf(gmLogfile, str, ap); fprintf(gmLogfile, "\n" ); va_end(ap); fflush(gmLogfile); } fflush(stdout); }
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 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) { OutputDebugStringA(buffer); free(buffer); break; } free(buffer); size *= 2; } while (size > 1024); } #endif vfprintf(stderr, format, args); }
/** * Safer implementation of vsnprintf; same as vsnprintf except: * - last instead of size, i.e. replace sizeof with lastof. * - return gives the amount of characters added, not what it would add. * @param str buffer to write to up to last * @param last last character we may write to * @param format the formatting (see snprintf) * @param ap the list of arguments for the format * @return the number of added characters */ static int CDECL vseprintf(char *str, const char *last, const char *format, va_list ap) { ptrdiff_t diff = last - str; if (diff < 0) return 0; return min((int)diff, vsnprintf(str, diff + 1, format, ap)); }
static void ATTRIBUTE_NORETURN __report_error (const char *msg, ...) { #ifdef __CYGWIN__ /* This function is used to print short error messages * to stderr, which may occur during DLL initialization * while fixing up 'pseudo' relocations. This early, we * may not be able to use cygwin stdio functions, so we * use the win32 WriteFile api. This should work with both * normal win32 console IO handles, redirected ones, and * cygwin ptys. */ char buf[SHORT_MSG_BUF_SZ]; wchar_t module[MAX_PATH]; char * posix_module = NULL; static const char UNKNOWN_MODULE[] = "<unknown module>: "; static const size_t UNKNOWN_MODULE_LEN = sizeof (UNKNOWN_MODULE) - 1; static const char CYGWIN_FAILURE_MSG[] = "Cygwin runtime failure: "; static const size_t CYGWIN_FAILURE_MSG_LEN = sizeof (CYGWIN_FAILURE_MSG) - 1; DWORD len; DWORD done; va_list args; HANDLE errh = GetStdHandle (STD_ERROR_HANDLE); ssize_t modulelen = GetModuleFileNameW (NULL, module, sizeof (module)); if (errh == INVALID_HANDLE_VALUE) cygwin_internal (CW_EXIT_PROCESS, STATUS_ILLEGAL_DLL_PSEUDO_RELOCATION, 1); if (modulelen > 0) posix_module = cygwin_create_path (CCP_WIN_W_TO_POSIX, module); va_start (args, msg); len = (DWORD) vsnprintf (buf, SHORT_MSG_BUF_SZ, msg, args); va_end (args); buf[SHORT_MSG_BUF_SZ-1] = '\0'; /* paranoia */ if (posix_module) { WriteFile (errh, (PCVOID)CYGWIN_FAILURE_MSG, CYGWIN_FAILURE_MSG_LEN, &done, NULL); WriteFile (errh, (PCVOID)posix_module, strlen(posix_module), &done, NULL); WriteFile (errh, (PCVOID)": ", 2, &done, NULL); WriteFile (errh, (PCVOID)buf, len, &done, NULL); free (posix_module); } else { WriteFile (errh, (PCVOID)CYGWIN_FAILURE_MSG, CYGWIN_FAILURE_MSG_LEN, &done, NULL); WriteFile (errh, (PCVOID)UNKNOWN_MODULE, UNKNOWN_MODULE_LEN, &done, NULL); WriteFile (errh, (PCVOID)buf, len, &done, NULL); } WriteFile (errh, (PCVOID)"\n", 1, &done, NULL); cygwin_internal (CW_EXIT_PROCESS, STATUS_ILLEGAL_DLL_PSEUDO_RELOCATION, 1); /* not reached, but silences noreturn warning */ abort (); #else va_list argp; va_start (argp, msg); # ifdef __MINGW64_VERSION_MAJOR fprintf (stderr, "Mingw-w64 runtime failure:\n"); # else fprintf (stderr, "Mingw runtime failure:\n"); # endif vfprintf (stderr, msg, argp); va_end (argp); abort (); #endif }
void csp_debug_ex(csp_debug_level_t level, const char * format, ...) { const char * color = ""; va_list args; va_start(args, format); /* Don't print anything if log level is disabled */ switch(level) { case CSP_INFO: if (!levels_enable[CSP_INFO]) return; break; case CSP_ERROR: if (!levels_enable[CSP_ERROR]) return; color = "\E[1;31m"; break; case CSP_WARN: if (!levels_enable[CSP_WARN]) return; color = "\E[0;33m"; break; case CSP_BUFFER: if (!levels_enable[CSP_BUFFER]) return; color = "\E[0;33m"; break; case CSP_PACKET: if (!levels_enable[CSP_PACKET]) return; color = "\E[0;32m"; break; case CSP_PROTOCOL: if (!levels_enable[CSP_PROTOCOL]) return; color = "\E[0;34m"; break; case CSP_LOCK: if (!levels_enable[CSP_LOCK]) return; color = "\E[0;36m"; break; } /* If csp_debug_hook symbol is defined, pass on the message. * Otherwise, just print with pretty colors ... */ if (csp_debug_hook || csp_debug_hook_func) { char buf[250]; vsnprintf(buf, 250, format, args); if (csp_debug_hook) { csp_debug_hook(level, buf); } else if (csp_debug_hook_func) { csp_debug_hook_func(level, buf); } } else { if (csp_debug_printf_hook) csp_debug_printf_hook(level); #if defined(CSP_WINDOWS) vprintf(format, args); #else printf("%s", color); vprintf(format, args); printf("\E[0m"); #endif } va_end(args); }
void log_category_vlog(struct log_category *category, enum log_priority priority, const char *format, va_list args) { struct timeval t; struct tm tm; char *buf = alloca(LOG_BUFFER_SIZE); vsnprintf(buf, LOG_BUFFER_SIZE, format, args); if (appender_stdout >= priority) { char *color; gettimeofday(&t, NULL); gmtime_r(&t.tv_sec, &tm); switch (priority) { case LOG_PRIORITY_ERROR: color = "\033[0;31m"; break; case LOG_PRIORITY_WARN: color = "\033[0;32m"; break; case LOG_PRIORITY_INFO: color = "\033[0;33m"; break; default: case LOG_PRIORITY_DEBUG: color = "\033[0;34m"; } #if defined(WIN32) printf("%02d.%03ld %-6s %s - %s\n", t.tv_sec, (long)(t.tv_usec / 1000), log_priority_to_string(priority), category->name, buf); #else printf("%s%04d%02d%02d %02d:%02d:%02d.%03ld %-6s %s - %s\033[0m\n", color, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, (long)(t.tv_usec / 1000), log_priority_to_string(priority), category->name, buf); #endif } #ifdef HAVE_SYSLOG if (appender_syslog >= priority) { char *ptr, *lasts = NULL; /* log individual lines to syslog */ ptr = strtok_r(buf, "\n", &lasts); syslog(priority, "%-6s %s - %s", log_priority_to_string(priority), category->name, ptr); ptr = strtok_r(NULL, "\n", &lasts); while (ptr) { syslog(priority, "%s", ptr); ptr = strtok_r(NULL, "\n", &lasts); } } #endif return; }
void vsyslog( int pri, const char *fmt, va_list ap ) { register char *p; char *last_chr, *head_end, *end, *stdp; time_t now; int fd, saved_errno; int rc; char tbuf[1024]; /* syslogd is unable to handle longer messages */ struct sigaction action, oldaction; int sigpipe; int try_num = 5; memset (&action, 0, sizeof (action)); action.sa_handler = sigpipe_handler; sigemptyset (&action.sa_mask); sigpipe = sigaction (SIGPIPE, &action, &oldaction); saved_errno = errno; LOCK; /* See if we should just throw out this message. */ if (!(LogMask & LOG_MASK(LOG_PRI(pri))) || (pri &~ (LOG_PRIMASK|LOG_FACMASK))) goto getout; 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. We know the starting part of the message can take * no longer than 64 characters plus length of the LogTag. So it's * safe to test only LogTag and use normal sprintf everywhere else. */ (void)time(&now); stdp = p = tbuf + sprintf(tbuf, "<%d>%.15s ", pri, ctime(&now) + 4); if (LogTag) { if (strlen(LogTag) < sizeof(tbuf) - 64) p += sprintf(p, "%s", LogTag); else p += sprintf(p, "<BUFFER OVERRUN ATTEMPT>"); } if (LogStat & LOG_PID) p += sprintf(p, "[%d]", getpid()); if (LogTag) { *p++ = ':'; *p++ = ' '; } head_end = p; /* We format the rest of the message. If the buffer becomes full, we mark * the message as truncated. Note that we require at least 2 free bytes * in the buffer as we might want to add "\r\n" there. */ end = tbuf + sizeof(tbuf) - 1; __set_errno(saved_errno); p += vsnprintf(p, end - p, fmt, ap); if (p >= end || p < head_end) { /* Returned -1 in case of error... */ static const char truncate_msg[12] = "[truncated] "; memmove(head_end + sizeof(truncate_msg), head_end, end - head_end - sizeof(truncate_msg)); memcpy(head_end, truncate_msg, sizeof(truncate_msg)); if (p < head_end) { while (p < end && *p) { p++; } } else { p = end - 1; } } last_chr = p; /* Output to stderr if requested. */ if (LogStat & LOG_PERROR) { *last_chr = '\n'; (void)write(STDERR_FILENO, stdp, last_chr - stdp + 1); } /* Output the message to the local logger using NUL as a message delimiter. */ p = tbuf; *last_chr = 0; do { rc = write(LogFile, p, last_chr + 1 - p); if (rc < 0) { if ((errno==EAGAIN) || (errno==EINTR)) rc=0; else { closelog_intern(0); break; } } p+=rc; } while (p <= last_chr && try_num--); if (rc >= 0) goto getout; /* * Output the message to the console; don't worry about blocking, * if console blocks everything will. Make sure the error reported * is the one from the syslogd failure. */ /* should mode be `O_WRONLY | O_NOCTTY' ? -- Uli */ if (LogStat & LOG_CONS && (fd = open(_PATH_CONSOLE, O_WRONLY, 0)) >= 0) { p = index(tbuf, '>') + 1; last_chr[0] = '\r'; last_chr[1] = '\n'; (void)write(fd, p, last_chr - p + 2); (void)close(fd); } getout: UNLOCK; if (sigpipe == 0) sigaction (SIGPIPE, &oldaction, (struct sigaction *) NULL); }
/* This is the final, internal function for printing text to a console */ void OGLCONSOLE_Output(OGLCONSOLE_Console console, const char *s, ...) { va_list argument; /* cache some console properties */ int lineQueueIndex = C->lineQueueIndex; int lineScrollIndex = C->lineScrollIndex; int textWidth = C->textWidth; int maxLines = C->maxLines; /* String buffer */ char output[4096]; /* string copy cursors */ char *consoleCursor, *outputCursor = output; /* Acrue arguments in argument list */ va_start(argument, s); vsnprintf(output, 4096, s, argument); va_end(argument); /* This cursor tells us where in the console display we are currently * copying text into from the "output" string */ consoleCursor = C->outputCursor; while (*outputCursor) { /* Here we check to see if any conditions require console line * advancement. These two conditions are: 1) Hitting the end of the screen 2) Getting a newline character (indicated by "outputNewline") */ if((C->outputNewline) || (consoleCursor - (C->lines + lineQueueIndex * textWidth)) >= (textWidth - 1)) { C->outputNewline = 0; //puts("incrementing to the next line"); /* Inrement text-line index, with wrapping */ if (++lineQueueIndex >= maxLines) lineQueueIndex = 0; /* Scroll the console display one line TODO: Don't scroll if the console is * currently scrolled away from the end of output? */ if (++lineScrollIndex >= maxLines) lineScrollIndex = 0; /* Reposition the cursor at the beginning of the new line */ consoleCursor = C->lines + lineQueueIndex * C->textWidth; } /* If we encounter a newline character, we set the newline flag, which * tells the console to advance one line before it prints the next * character. The reason we do it this way is to defer line-advancement, * and thus we needn't suffer through a needless blank line between * console output and the command line, wasting precious screen * real-estate */ if (*outputCursor == '\n') { C->outputNewline = 1; outputCursor++; continue; } /* If we encounter a tab character we must expand that character * appropriately */ if (*outputCursor == '\t') { const int TAB_WIDTH = 8; int n = (consoleCursor - (C->lines + lineQueueIndex * textWidth)) % TAB_WIDTH; /* Are we indenting our way off the edge of the screen? */ if (textWidth - n <= TAB_WIDTH) { /* Switch on the console's newline bit, and advance through the * string output we've been given */ C->outputNewline = 1; outputCursor++; continue; } /* Normal indent */ else { n = TAB_WIDTH - n % TAB_WIDTH; while (n--) *(consoleCursor++) = ' '; outputCursor++; continue; } } /* copy a single character */ *(consoleCursor++) = *(outputCursor++); } /* Unless we're at the very end of our current line, we finish up by capping * a NULL terminator on the current line */ if (consoleCursor != C->lines + (lineQueueIndex+1) *C->textWidth -1) *consoleCursor = '\0'; /* Restore cached values */ C->lineQueueIndex = lineQueueIndex; C->lineScrollIndex = lineScrollIndex; C->outputCursor = consoleCursor; // TODO: confusing variable names /* old way of copying the text into the console */ //strcpy(C->lines[C->lineQueueIndex], output); #ifdef DEBUG printf("Copied \"%s\" into line %i\n", output, C->lineQueueIndex); #endif }
NORET_TYPE void panic(const char * fmt, ...) { long i; static char buf[1024]; va_list args; #if defined(CONFIG_S390) unsigned long caller = (unsigned long) __builtin_return_address(0); #endif /* * It's possible to come here directly from a panic-assertion and not * have preempt disabled. Some functions called from here want * preempt to be disabled. No point enabling it later though... */ preempt_disable(); bust_spinlocks(1); va_start(args, fmt); vsnprintf(buf, sizeof(buf), fmt, args); va_end(args); printk(KERN_EMERG "Kernel panic - not syncing: %s\n",buf); bust_spinlocks(0); /* * If we have crashed and we have a crash kernel loaded let it handle * everything else. * Do we want to call this before we try to display a message? */ crash_kexec(NULL); #ifdef CONFIG_SMP /* * Note smp_send_stop is the usual smp shutdown function, which * unfortunately means it may not be hardened to work in a panic * situation. */ smp_send_stop(); #endif atomic_notifier_call_chain(&panic_notifier_list, 0, buf); if (!panic_blink) panic_blink = no_blink; if (panic_timeout > 0) { /* * Delay timeout seconds before rebooting the machine. * We can't use the "normal" timers since we just panicked.. */ printk(KERN_EMERG "Rebooting in %d seconds..",panic_timeout); for (i = 0; i < panic_timeout*1000; ) { touch_nmi_watchdog(); i += panic_blink(i); mdelay(1); i++; } /* This will not be a clean reboot, with everything * shutting down. But if there is a chance of * rebooting the system it will be rebooted. */ emergency_restart(); } #ifdef __sparc__ { extern int stop_a_enabled; /* Make sure the user can actually press Stop-A (L1-A) */ stop_a_enabled = 1; printk(KERN_EMERG "Press Stop-A (L1-A) to return to the boot prom\n"); } #endif #if defined(CONFIG_S390) disabled_wait(caller); #endif local_irq_enable(); for (i = 0;;) { touch_softlockup_watchdog(); i += panic_blink(i); mdelay(1); i++; } }
int vsprintf(char *str, const char *fmt, va_list ap) { return vsnprintf(str, 0x10000, fmt, ap); // support max 64KB buffer }
void radlog_request(int lvl, int priority, REQUEST *request, const char *msg, ...) { size_t len = 0; const char *filename = request_log_file; FILE *fp = NULL; va_list ap; char buffer[1024]; va_start(ap, msg); /* * Debug messages get treated specially. */ if (lvl == L_DBG) { /* * There is log function, but the debug level * isn't high enough. OR, we're in debug mode, * and the debug level isn't high enough. Return. */ if ((request && request->radlog && (priority > request->options)) || ((debug_flag != 0) && (priority > debug_flag))) { va_end(ap); return; } /* * Use the debug output file, if specified, * otherwise leave it as "request_log_file". */ #ifdef WITH_COMMAND_SOCKET filename = debug_log_file; if (!filename) #endif filename = request_log_file; /* * Debug messages get mashed to L_INFO for * radius.log. */ if (!filename) lvl = L_INFO; } if (request && filename) { char *p; radlog_func_t rl = request->radlog; request->radlog = NULL; /* * This is SLOW! Doing it for every log message * in every request is NOT recommended! */ radius_xlat(buffer, sizeof(buffer), filename, request, NULL); /* FIXME: escape chars! */ request->radlog = rl; p = strrchr(buffer, FR_DIR_SEP); if (p) { *p = '\0'; if (rad_mkdir(buffer, S_IRWXU) < 0) { radlog(L_ERR, "Failed creating %s: %s", buffer,strerror(errno)); va_end(ap); return; } *p = FR_DIR_SEP; } fp = fopen(buffer, "a"); } /* * Print timestamps to the file. */ if (fp) { char *s; time_t timeval; timeval = time(NULL); CTIME_R(&timeval, buffer + len, sizeof(buffer) - len - 1); s = strrchr(buffer, '\n'); if (s) { s[0] = ' '; s[1] = '\0'; } s = fr_int2str(levels, (lvl & ~L_CONS), ": "); strcat(buffer, s); len = strlen(buffer); } if (request && request->module[0]) { snprintf(buffer + len, sizeof(buffer) + len, "%s : ", request->module); len = strlen(buffer); } vsnprintf(buffer + len, sizeof(buffer) - len, msg, ap); if (!fp) { if (request) { radlog(lvl, "(%u) %s", request->number, buffer); } else { radlog(lvl, "%s", buffer); } } else { if (request) fprintf(fp, "(%u) ", request->number); fputs(buffer, fp); fputc('\n', fp); fclose(fp); } va_end(ap); }
static int xbt_log_layout_format_doit(xbt_log_layout_t l, xbt_log_event_t ev, const char *msg_fmt) { char *p = ev->buffer; int rem_size = ev->buffer_size; int precision = -1; int length = -1; char *q; for (q = l->data ; *q != '\0' ; q++) { if (*q == '%') { q++; handle_modifier: switch (*q) { case '\0': fprintf(stderr, "Layout format (%s) ending with %%\n", (char *)l->data); xbt_abort(); case '%': *p = '%'; check_overflow(1); break; case 'n': /* platform-dependant line separator; LOG4J compliant */ *p = '\n'; check_overflow(1); break; case 'e': /* plain space; SimGrid extension */ *p = ' '; check_overflow(1); break; case '.': /* precision specifier */ precision = strtol(q + 1, &q, 10); goto handle_modifier; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': /* length modifier */ length = strtol(q, &q, 10); goto handle_modifier; case 'c': /* category name; LOG4J compliant should accept a precision postfix to show the hierarchy */ show_string(ev->cat->name); break; case 'p': /* priority name; LOG4J compliant */ show_string(xbt_log_priority_names[ev->priority]); break; case 'h': /* host name; SimGrid extension */ show_string(SIMIX_host_self_get_name()); break; case 't': /* thread name; LOG4J compliant */ show_string(xbt_thread_self_name()); break; case 'P': /* process name; SimGrid extension */ show_string(xbt_procname()); break; case 'i': /* process PID name; SimGrid extension */ show_int(xbt_getpid()); break; case 'F': /* file name; LOG4J compliant */ show_string(ev->fileName); break; case 'l': { /* location; LOG4J compliant */ int len, sz; set_sz_from_precision(); len = snprintf(p, sz, "%s:%d", ev->fileName, ev->lineNum); check_overflow(MIN(sz, len)); break; } case 'L': /* line number; LOG4J compliant */ show_int(ev->lineNum); break; case 'M': /* method (ie, function) name; LOG4J compliant */ show_string(ev->functionName); break; case 'b': /* backtrace; called %throwable in LOG4J */ case 'B': /* short backtrace; called %throwable{short} in LOG4J */ #if defined(HAVE_EXECINFO_H) && defined(HAVE_POPEN) && defined(ADDR2LINE) { xbt_ex_t e; e.used = backtrace((void **) e.bt, XBT_BACKTRACE_SIZE); e.bt_strings = NULL; e.msg = NULL; xbt_ex_setup_backtrace(&e); if (*q == 'B') { show_string(e.bt_strings[1] + 8); } else { xbt_strbuff_t buff = xbt_strbuff_new(); int i; xbt_strbuff_append(buff, e.bt_strings[1] + 8); for (i = 2; i < e.used; i++) { xbt_strbuff_append(buff, "\n"); xbt_strbuff_append(buff, e.bt_strings[i] + 8); } show_string(buff->data); xbt_strbuff_free(buff); } xbt_ex_free(e); } #else show_string("(no backtrace on this arch)"); #endif break; case 'd': /* date; LOG4J compliant */ show_double(surf_get_clock()); break; case 'r': /* application age; LOG4J compliant */ show_double(surf_get_clock() - format_begin_of_time); break; case 'm': { /* user-provided message; LOG4J compliant */ int len, sz; set_sz_from_precision(); len = vsnprintf(p, sz, msg_fmt, ev->ap); check_overflow(MIN(sz, len)); break; } default: fprintf(stderr, ERRMSG, *q, (char *)l->data); xbt_abort(); } } else { *p = *q; check_overflow(1); } } *p = '\0'; return 1; }
/* * This is printk. It can be called from any context. We want it to work. * * We try to grab the console_sem. If we succeed, it's easy - we log the output and * call the console drivers. If we fail to get the semaphore we place the output * into the log buffer and return. The current holder of the console_sem will * notice the new output in release_console_sem() and will send it to the * consoles before releasing the semaphore. * * One effect of this deferred printing is that code which calls printk() and * then changes console_loglevel may break. This is because console_loglevel * is inspected when the actual printing occurs. */ asmlinkage int printk(const char *fmt, ...) { va_list args; unsigned long flags; int printed_len; char *p; static char printk_buf[1024]; static int log_level_unknown = 1; if (oops_in_progress) { /* If a crash is occurring, make sure we can't deadlock */ spin_lock_init(&logbuf_lock); /* And make sure that we print immediately */ init_MUTEX(&console_sem); } /* This stops the holder of console_sem just where we want him */ spin_lock_irqsave(&logbuf_lock, flags); /* Emit the output into the temporary buffer */ va_start(args, fmt); printed_len = vsnprintf(printk_buf, sizeof(printk_buf), fmt, args); va_end(args); /* * Copy the output into log_buf. If the caller didn't provide * appropriate log level tags, we insert them here */ for (p = printk_buf; *p; p++) { if (log_level_unknown) { if (p[0] != '<' || p[1] < '0' || p[1] > '7' || p[2] != '>') { emit_log_char('<'); emit_log_char(default_message_loglevel + '0'); emit_log_char('>'); } log_level_unknown = 0; } emit_log_char(*p); if (*p == '\n') log_level_unknown = 1; } if (!arch_consoles_callable()) { /* * On some architectures, the consoles are not usable * on secondary CPUs early in the boot process. */ spin_unlock_irqrestore(&logbuf_lock, flags); goto out; } if (!down_trylock(&console_sem)) { /* * We own the drivers. We can drop the spinlock and let * release_console_sem() print the text */ spin_unlock_irqrestore(&logbuf_lock, flags); console_may_schedule = 0; release_console_sem(); } else { /* * Someone else owns the drivers. We drop the spinlock, which * allows the semaphore holder to proceed and to call the * console drivers with the output which we just produced. */ spin_unlock_irqrestore(&logbuf_lock, flags); } out: return printed_len; }
int PlatformSpecificVSNprintf(char *str, size_t size, const char* format, va_list args) { return vsnprintf( str, size, format, args); }
int BufferVPrintf(Buffer *buffer, const char *format, va_list ap) { va_list aq; va_copy(aq, ap); if (!buffer || !format) { return -1; } int printed = 0; /* * We don't know how big of a buffer we will need. It might be that we have enough space * or it might be that we don't have enough space. Unfortunately, we cannot reiterate over * a va_list, so our only solution is to tell the caller to retry the call. We signal this * by returning zero. Before doing that we increase the buffer to a suitable size. * The tricky part is the implicit sharing and the reference counting, if we are not shared then * everything is easy, however if we are shared then we need a different strategy. */ if (RefCountIsShared(buffer->ref_count)) { char *new_buffer = NULL; new_buffer = (char *)xmalloc(buffer->capacity); /* * Make a local copy of the variables that are required to restore to normality. */ RefCount *ref_count = buffer->ref_count; /* * We try to attach first, since it is more likely that Attach might fail than * detach. */ int result = 0; buffer->ref_count = NULL; RefCountNew(&buffer->ref_count); result = RefCountAttach(buffer->ref_count, buffer); if (result < 0) { /* * Restore and signal the error. */ free (new_buffer); RefCountDestroy(&buffer->ref_count); buffer->ref_count = ref_count; return -1; } /* * Detach. This operation might fail, although it is very rare. */ result = RefCountDetach(ref_count, buffer); if (result < 0) { /* * The ref_count structure has not been modified, therefore * we can reuse it. * We need to destroy the other ref_count though. */ free (new_buffer); RefCountDestroy(&buffer->ref_count); buffer->ref_count = ref_count; return -1; } /* * Ok, now we need to take care of the buffer. */ unsigned int i = 0; unsigned int used = 0; for (i = 0; i < buffer->used; ++i) { new_buffer[i] = buffer->buffer[i]; if ((buffer->buffer[i] == '\0') && (buffer->mode == BUFFER_BEHAVIOR_CSTRING)) { break; } ++used; } buffer->buffer = new_buffer; buffer->used = used; } printed = vsnprintf(buffer->buffer, buffer->capacity, format, aq); if (printed >= buffer->capacity) { /* * Allocate a larger buffer and retry. * We use the copy of the list. */ if (printed > buffer->memory_cap) { /* * We would go over the memory_cap limit. */ return -1; } unsigned int required_blocks = (printed / DEFAULT_BUFFER_SIZE) + 1; buffer->buffer = (char *)xrealloc(buffer->buffer, required_blocks * DEFAULT_BUFFER_SIZE); buffer->capacity = required_blocks * DEFAULT_BUFFER_SIZE; buffer->used = 0; printed = vsnprintf(buffer->buffer, buffer->capacity, format, ap); buffer->used = printed; } else { buffer->used = printed; } return printed; }
//log record, format, and print: executed in the main thread (mt) void logRecord_mt(const char *file, const char *func, int line, int comp, int level, char *format, ...) { int len = 0; va_list args; log_component_t *c; char *log_start; char *log_end; c = &g_log->log_component[comp]; // do not apply filtering for LOG_F // only log messages which are enabled and are below the global log level and component's level threshold if ((level != LOG_FILE) && ((level > c->level) || (level > g_log->level))) { /* if ((level != LOG_FILE) && ((level > c->level) || (level > g_log->level) || ( c->level > g_log->level))) { */ return; } vcd_signal_dumper_dump_function_by_name(VCD_SIGNAL_DUMPER_FUNCTIONS_LOG_RECORD, VCD_FUNCTION_IN); va_start(args, format); // adjust syslog level for TRACE messages if (g_log->syslog) { if (g_log->level > LOG_DEBUG) { g_log->level = LOG_DEBUG; } } // make sure that for log trace the extra info is only printed once, reset when the level changes if ((level == LOG_FILE) || (c->flag == LOG_NONE) || (level == LOG_TRACE)) { log_start = c->log_buffer; len = vsnprintf(c->log_buffer, MAX_LOG_TOTAL-1, format, args); log_end = c->log_buffer + len; } else { if ( (g_log->flag & FLAG_COLOR) || (c->flag & FLAG_COLOR) ) { len += snprintf(&c->log_buffer[len], MAX_LOG_TOTAL - len, "%s", log_level_highlight_start[level]); } log_start = c->log_buffer + len; if ( (g_log->flag & FLAG_COMP) || (c->flag & FLAG_COMP) ) { len += snprintf(&c->log_buffer[len], MAX_LOG_TOTAL - len, "[%s]", g_log->log_component[comp].name); } if ( (g_log->flag & FLAG_LEVEL) || (c->flag & FLAG_LEVEL) ) { len += snprintf(&c->log_buffer[len], MAX_LOG_TOTAL - len, "[%s]", g_log->level2string[level]); } if ( (g_log->flag & FLAG_FUNCT) || (c->flag & FLAG_FUNCT) ) { len += snprintf(&c->log_buffer[len], MAX_LOG_TOTAL - len, "[%s] ", func); } if ( (g_log->flag & FLAG_FILE_LINE) || (c->flag & FLAG_FILE_LINE) ) { len += snprintf(&c->log_buffer[len], MAX_LOG_TOTAL - len, "[%s:%d]", file, line); } len += vsnprintf(&c->log_buffer[len], MAX_LOG_TOTAL - len, format, args); log_end = c->log_buffer + len; if ( (g_log->flag & FLAG_COLOR) || (c->flag & FLAG_COLOR) ) { len += snprintf(&c->log_buffer[len], MAX_LOG_TOTAL - len, "%s", log_level_highlight_end[level]); } } va_end(args); // OAI printf compatibility if ((g_log->onlinelog == 1) && (level != LOG_FILE)) #ifdef RTAI if (len > MAX_LOG_TOTAL) { rt_printk ("[OPENAIR] FIFO_PRINTF WROTE OUTSIDE ITS MEMORY BOUNDARY : ERRORS WILL OCCUR\n"); } if (len > 0) { rtf_put (FIFO_PRINTF_NO, c->log_buffer, len); } #else fwrite(c->log_buffer, len, 1, stdout); #endif #ifndef RTAI if (g_log->syslog) { syslog(g_log->level, "%s", c->log_buffer); } if (g_log->filelog) { if (write(gfd, c->log_buffer, len) < len){ // TODO assert ? } } if ((g_log->log_component[comp].filelog) && (level == LOG_FILE)) { if (write(g_log->log_component[comp].fd, c->log_buffer, len) < len) { // TODO assert ? } } #else // online print messges if ((g_log->log_component[comp].filelog) && (level == LOG_FILE)) { printf(c->log_buffer); } #endif #if defined(ENABLE_ITTI) if (level <= LOG_DEBUG) { task_id_t origin_task_id = TASK_UNKNOWN; MessagesIds messages_id; MessageDef *message_p; size_t message_string_size; char *message_msg_p; message_string_size = log_end - log_start; #if !defined(DISABLE_ITTI_DETECT_SUB_TASK_ID) /* Try to identify sub task ID from log information (comp, log_instance_type) */ switch (comp) { case PHY: switch (log_instance_type) { case LOG_INSTANCE_ENB: origin_task_id = TASK_PHY_ENB; break; case LOG_INSTANCE_UE: origin_task_id = TASK_PHY_UE; break; default: break; } break; case MAC: switch (log_instance_type) { case LOG_INSTANCE_ENB: origin_task_id = TASK_MAC_ENB; break; case LOG_INSTANCE_UE: origin_task_id = TASK_MAC_UE; default: break; } break; case RLC: switch (log_instance_type) { case LOG_INSTANCE_ENB: origin_task_id = TASK_RLC_ENB; break; case LOG_INSTANCE_UE: origin_task_id = TASK_RLC_UE; default: break; } break; case PDCP: switch (log_instance_type) { case LOG_INSTANCE_ENB: origin_task_id = TASK_PDCP_ENB; break; case LOG_INSTANCE_UE: origin_task_id = TASK_PDCP_UE; default: break; } break; default: break; } #endif switch (level) { case LOG_EMERG: case LOG_ALERT: case LOG_CRIT: case LOG_ERR: messages_id = ERROR_LOG; break; case LOG_WARNING: messages_id = WARNING_LOG; break; case LOG_NOTICE: messages_id = NOTICE_LOG; break; case LOG_INFO: messages_id = INFO_LOG; break; default: messages_id = DEBUG_LOG; break; } message_p = itti_alloc_new_message_sized(origin_task_id, messages_id, message_string_size); switch (level) { case LOG_EMERG: case LOG_ALERT: case LOG_CRIT: case LOG_ERR: message_msg_p = (char *) &message_p->ittiMsg.error_log; break; case LOG_WARNING: message_msg_p = (char *) &message_p->ittiMsg.warning_log; break; case LOG_NOTICE: message_msg_p = (char *) &message_p->ittiMsg.notice_log; break; case LOG_INFO: message_msg_p = (char *) &message_p->ittiMsg.info_log; break; default: message_msg_p = (char *) &message_p->ittiMsg.debug_log; break; } memcpy(message_msg_p, log_start, message_string_size); itti_send_msg_to_task(TASK_UNKNOWN, INSTANCE_DEFAULT, message_p); } #endif vcd_signal_dumper_dump_function_by_name(VCD_SIGNAL_DUMPER_FUNCTIONS_LOG_RECORD, VCD_FUNCTION_OUT); }