blob: 7f6c506a494226479af1152f13f99f1870f554d1 [file] [log] [blame]
Sam Ravnborg96e3e182007-07-31 00:38:13 -07001/*
2 * linux/lib/kasprintf.c
3 *
4 * Copyright (C) 1991, 1992 Linus Torvalds
5 */
6
7#include <stdarg.h>
Paul Gortmaker8bc3bcc2011-11-16 21:29:17 -05008#include <linux/export.h>
Tejun Heo5a0e3ad2010-03-24 17:04:11 +09009#include <linux/slab.h>
Sam Ravnborg96e3e182007-07-31 00:38:13 -070010#include <linux/types.h>
11#include <linux/string.h>
12
13/* Simplified asprintf. */
14char *kvasprintf(gfp_t gfp, const char *fmt, va_list ap)
15{
Rasmus Villemoes8e2a2bf2016-01-15 16:58:47 -080016 unsigned int first, second;
Sam Ravnborg96e3e182007-07-31 00:38:13 -070017 char *p;
18 va_list aq;
19
20 va_copy(aq, ap);
Rasmus Villemoes8e2a2bf2016-01-15 16:58:47 -080021 first = vsnprintf(NULL, 0, fmt, aq);
Sam Ravnborg96e3e182007-07-31 00:38:13 -070022 va_end(aq);
23
Rasmus Villemoes8e2a2bf2016-01-15 16:58:47 -080024 p = kmalloc_track_caller(first+1, gfp);
Sam Ravnborg96e3e182007-07-31 00:38:13 -070025 if (!p)
26 return NULL;
27
Rasmus Villemoes8e2a2bf2016-01-15 16:58:47 -080028 second = vsnprintf(p, first+1, fmt, ap);
29 WARN(first != second, "different return values (%u and %u) from vsnprintf(\"%s\", ...)",
30 first, second, fmt);
Sam Ravnborg96e3e182007-07-31 00:38:13 -070031
32 return p;
33}
34EXPORT_SYMBOL(kvasprintf);
35
Rasmus Villemoes0a9df782015-11-06 16:31:20 -080036/*
37 * If fmt contains no % (or is exactly %s), use kstrdup_const. If fmt
38 * (or the sole vararg) points to rodata, we will then save a memory
39 * allocation and string copy. In any case, the return value should be
40 * freed using kfree_const().
41 */
42const char *kvasprintf_const(gfp_t gfp, const char *fmt, va_list ap)
43{
44 if (!strchr(fmt, '%'))
45 return kstrdup_const(fmt, gfp);
46 if (!strcmp(fmt, "%s"))
47 return kstrdup_const(va_arg(ap, const char*), gfp);
48 return kvasprintf(gfp, fmt, ap);
49}
50EXPORT_SYMBOL(kvasprintf_const);
51
Sam Ravnborg96e3e182007-07-31 00:38:13 -070052char *kasprintf(gfp_t gfp, const char *fmt, ...)
53{
54 va_list ap;
55 char *p;
56
57 va_start(ap, fmt);
58 p = kvasprintf(gfp, fmt, ap);
59 va_end(ap);
60
61 return p;
62}
63EXPORT_SYMBOL(kasprintf);