Back to home page

LXR

 
 

    


0001 /*
0002  *  linux/lib/kasprintf.c
0003  *
0004  *  Copyright (C) 1991, 1992  Linus Torvalds
0005  */
0006 
0007 #include <stdarg.h>
0008 #include <linux/export.h>
0009 #include <linux/slab.h>
0010 #include <linux/types.h>
0011 #include <linux/string.h>
0012 
0013 /* Simplified asprintf. */
0014 char *kvasprintf(gfp_t gfp, const char *fmt, va_list ap)
0015 {
0016     unsigned int first, second;
0017     char *p;
0018     va_list aq;
0019 
0020     va_copy(aq, ap);
0021     first = vsnprintf(NULL, 0, fmt, aq);
0022     va_end(aq);
0023 
0024     p = kmalloc_track_caller(first+1, gfp);
0025     if (!p)
0026         return NULL;
0027 
0028     second = vsnprintf(p, first+1, fmt, ap);
0029     WARN(first != second, "different return values (%u and %u) from vsnprintf(\"%s\", ...)",
0030          first, second, fmt);
0031 
0032     return p;
0033 }
0034 EXPORT_SYMBOL(kvasprintf);
0035 
0036 /*
0037  * If fmt contains no % (or is exactly %s), use kstrdup_const. If fmt
0038  * (or the sole vararg) points to rodata, we will then save a memory
0039  * allocation and string copy. In any case, the return value should be
0040  * freed using kfree_const().
0041  */
0042 const char *kvasprintf_const(gfp_t gfp, const char *fmt, va_list ap)
0043 {
0044     if (!strchr(fmt, '%'))
0045         return kstrdup_const(fmt, gfp);
0046     if (!strcmp(fmt, "%s"))
0047         return kstrdup_const(va_arg(ap, const char*), gfp);
0048     return kvasprintf(gfp, fmt, ap);
0049 }
0050 EXPORT_SYMBOL(kvasprintf_const);
0051 
0052 char *kasprintf(gfp_t gfp, const char *fmt, ...)
0053 {
0054     va_list ap;
0055     char *p;
0056 
0057     va_start(ap, fmt);
0058     p = kvasprintf(gfp, fmt, ap);
0059     va_end(ap);
0060 
0061     return p;
0062 }
0063 EXPORT_SYMBOL(kasprintf);