xref: /freebsd/contrib/libfido2/openbsd-compat/bsd-asprintf.c (revision 95eb4b873b6a8b527c5bd78d7191975dfca38998)
1 /*
2  * Copyright (c) 2004 Darren Tucker.
3  *
4  * Based originally on asprintf.c from OpenBSD:
5  * Copyright (c) 1997 Todd C. Miller <Todd.Miller@courtesan.com>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #include "openbsd-compat.h"
21 
22 #ifndef HAVE_ASPRINTF
23 
24 #include <errno.h>
25 #include <limits.h> /* for INT_MAX */
26 #include <stdarg.h>
27 #include <stdio.h> /* for vsnprintf */
28 #include <stdlib.h>
29 
30 #define VA_COPY(dest, src) va_copy(dest, src)
31 
32 #define INIT_SZ	128
33 
34 int
35 vasprintf(char **str, const char *fmt, va_list ap)
36 {
37 	int ret;
38 	va_list ap2;
39 	char *string, *newstr;
40 	size_t len;
41 
42 	if ((string = malloc(INIT_SZ)) == NULL)
43 		goto fail;
44 
45 	VA_COPY(ap2, ap);
46 	ret = vsnprintf(string, INIT_SZ, fmt, ap2);
47 	va_end(ap2);
48 	if (ret >= 0 && ret < INIT_SZ) { /* succeeded with initial alloc */
49 		*str = string;
50 	} else if (ret == INT_MAX || ret < 0) { /* Bad length */
51 		free(string);
52 		goto fail;
53 	} else {	/* bigger than initial, realloc allowing for nul */
54 		len = (size_t)ret + 1;
55 		if ((newstr = realloc(string, len)) == NULL) {
56 			free(string);
57 			goto fail;
58 		}
59 		VA_COPY(ap2, ap);
60 		ret = vsnprintf(newstr, len, fmt, ap2);
61 		va_end(ap2);
62 		if (ret < 0 || (size_t)ret >= len) { /* failed with realloc'ed string */
63 			free(newstr);
64 			goto fail;
65 		}
66 		*str = newstr;
67 	}
68 	return (ret);
69 
70 fail:
71 	*str = NULL;
72 	errno = ENOMEM;
73 	return (-1);
74 }
75 
76 int asprintf(char **str, const char *fmt, ...)
77 {
78 	va_list ap;
79 	int ret;
80 
81 	*str = NULL;
82 	va_start(ap, fmt);
83 	ret = vasprintf(str, fmt, ap);
84 	va_end(ap);
85 
86 	return ret;
87 }
88 #endif
89