]> eyrie.org Git - kerberos/krb5-strength.git/blob - portable/asprintf.c
Enable all hardening flags
[kerberos/krb5-strength.git] / portable / asprintf.c
1 /*
2  * Replacement for a missing asprintf and vasprintf.
3  *
4  * Provides the same functionality as the standard GNU library routines
5  * asprintf and vasprintf for those platforms that don't have them.
6  *
7  * The canonical version of this file is maintained in the rra-c-util package,
8  * which can be found at <https://www.eyrie.org/~eagle/software/rra-c-util/>.
9  *
10  * Written by Russ Allbery <eagle@eyrie.org>
11  *
12  * The authors hereby relinquish any claim to any copyright that they may have
13  * in this work, whether granted under contract or by operation of law or
14  * international treaty, and hereby commit to the public, at large, that they
15  * shall not, at any time in the future, seek to enforce any copyright in this
16  * work against any person or entity, or prevent any person or entity from
17  * copying, publishing, distributing or creating derivative works of this
18  * work.
19  */
20
21 #include <config.h>
22 #include <portable/macros.h>
23 #include <portable/system.h>
24
25 #include <errno.h>
26
27 /*
28  * If we're running the test suite, rename the functions to avoid conflicts
29  * with the system versions.
30  */
31 #if TESTING
32 # undef asprintf
33 # undef vasprintf
34 # define asprintf test_asprintf
35 # define vasprintf test_vasprintf
36 int test_asprintf(char **, const char *, ...)
37     __attribute__((__format__(printf, 2, 3)));
38 int test_vasprintf(char **, const char *, va_list)
39     __attribute__((__format__(printf, 2, 0)));
40 #endif
41
42
43 int
44 asprintf(char **strp, const char *fmt, ...)
45 {
46     va_list args;
47     int status;
48
49     va_start(args, fmt);
50     status = vasprintf(strp, fmt, args);
51     va_end(args);
52     return status;
53 }
54
55
56 int
57 vasprintf(char **strp, const char *fmt, va_list args)
58 {
59     va_list args_copy;
60     int status, needed, oerrno;
61
62     va_copy(args_copy, args);
63     needed = vsnprintf(NULL, 0, fmt, args_copy);
64     va_end(args_copy);
65     if (needed < 0) {
66         *strp = NULL;
67         return needed;
68     }
69     *strp = malloc(needed + 1);
70     if (*strp == NULL)
71         return -1;
72     status = vsnprintf(*strp, needed + 1, fmt, args);
73     if (status >= 0)
74         return status;
75     else {
76         oerrno = errno;
77         free(*strp);
78         *strp = NULL;
79         errno = oerrno;
80         return status;
81     }
82 }