Sam Ravnborg | 96e3e18 | 2007-07-31 00:38:13 -0700 | [diff] [blame] | 1 | /* |
| 2 | * linux/lib/kasprintf.c |
| 3 | * |
| 4 | * Copyright (C) 1991, 1992 Linus Torvalds |
| 5 | */ |
| 6 | |
| 7 | #include <stdarg.h> |
Paul Gortmaker | 8bc3bcc | 2011-11-16 21:29:17 -0500 | [diff] [blame] | 8 | #include <linux/export.h> |
Tejun Heo | 5a0e3ad | 2010-03-24 17:04:11 +0900 | [diff] [blame] | 9 | #include <linux/slab.h> |
Sam Ravnborg | 96e3e18 | 2007-07-31 00:38:13 -0700 | [diff] [blame] | 10 | #include <linux/types.h> |
| 11 | #include <linux/string.h> |
| 12 | |
| 13 | /* Simplified asprintf. */ |
| 14 | char *kvasprintf(gfp_t gfp, const char *fmt, va_list ap) |
| 15 | { |
| 16 | unsigned int len; |
| 17 | char *p; |
| 18 | va_list aq; |
| 19 | |
| 20 | va_copy(aq, ap); |
| 21 | len = vsnprintf(NULL, 0, fmt, aq); |
| 22 | va_end(aq); |
| 23 | |
Ezequiel Garcia | 3e1aa66 | 2012-10-10 15:54:04 -0700 | [diff] [blame] | 24 | p = kmalloc_track_caller(len+1, gfp); |
Sam Ravnborg | 96e3e18 | 2007-07-31 00:38:13 -0700 | [diff] [blame] | 25 | if (!p) |
| 26 | return NULL; |
| 27 | |
| 28 | vsnprintf(p, len+1, fmt, ap); |
| 29 | |
| 30 | return p; |
| 31 | } |
| 32 | EXPORT_SYMBOL(kvasprintf); |
| 33 | |
Rasmus Villemoes | 0a9df78 | 2015-11-06 16:31:20 -0800 | [diff] [blame^] | 34 | /* |
| 35 | * If fmt contains no % (or is exactly %s), use kstrdup_const. If fmt |
| 36 | * (or the sole vararg) points to rodata, we will then save a memory |
| 37 | * allocation and string copy. In any case, the return value should be |
| 38 | * freed using kfree_const(). |
| 39 | */ |
| 40 | const char *kvasprintf_const(gfp_t gfp, const char *fmt, va_list ap) |
| 41 | { |
| 42 | if (!strchr(fmt, '%')) |
| 43 | return kstrdup_const(fmt, gfp); |
| 44 | if (!strcmp(fmt, "%s")) |
| 45 | return kstrdup_const(va_arg(ap, const char*), gfp); |
| 46 | return kvasprintf(gfp, fmt, ap); |
| 47 | } |
| 48 | EXPORT_SYMBOL(kvasprintf_const); |
| 49 | |
Sam Ravnborg | 96e3e18 | 2007-07-31 00:38:13 -0700 | [diff] [blame] | 50 | char *kasprintf(gfp_t gfp, const char *fmt, ...) |
| 51 | { |
| 52 | va_list ap; |
| 53 | char *p; |
| 54 | |
| 55 | va_start(ap, fmt); |
| 56 | p = kvasprintf(gfp, fmt, ap); |
| 57 | va_end(ap); |
| 58 | |
| 59 | return p; |
| 60 | } |
| 61 | EXPORT_SYMBOL(kasprintf); |