xref: /freebsd/crypto/openssh/openbsd-compat/bsd-asprintf.c (revision ca86bcf2531c7b149c95244a67853d44323e7855)
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 "includes.h"
21 
22 #ifndef HAVE_VASPRINTF
23 
24 #include <errno.h>
25 #include <stdarg.h>
26 #include <stdlib.h>
27 
28 #define INIT_SZ	128
29 
30 int
31 vasprintf(char **str, const char *fmt, va_list ap)
32 {
33 	int ret = -1;
34 	va_list ap2;
35 	char *string, *newstr;
36 	size_t len;
37 
38 	VA_COPY(ap2, ap);
39 	if ((string = malloc(INIT_SZ)) == NULL)
40 		goto fail;
41 
42 	ret = vsnprintf(string, INIT_SZ, fmt, ap2);
43 	if (ret >= 0 && ret < INIT_SZ) { /* succeeded with initial alloc */
44 		*str = string;
45 	} else if (ret == INT_MAX || ret < 0) { /* Bad length */
46 		free(string);
47 		goto fail;
48 	} else {	/* bigger than initial, realloc allowing for nul */
49 		len = (size_t)ret + 1;
50 		if ((newstr = realloc(string, len)) == NULL) {
51 			free(string);
52 			goto fail;
53 		} else {
54 			va_end(ap2);
55 			VA_COPY(ap2, ap);
56 			ret = vsnprintf(newstr, len, fmt, ap2);
57 			if (ret >= 0 && (size_t)ret < len) {
58 				*str = newstr;
59 			} else { /* failed with realloc'ed string, give up */
60 				free(newstr);
61 				goto fail;
62 			}
63 		}
64 	}
65 	va_end(ap2);
66 	return (ret);
67 
68 fail:
69 	*str = NULL;
70 	errno = ENOMEM;
71 	va_end(ap2);
72 	return (-1);
73 }
74 #endif
75 
76 #ifndef HAVE_ASPRINTF
77 int asprintf(char **str, const char *fmt, ...)
78 {
79 	va_list ap;
80 	int ret;
81 
82 	*str = NULL;
83 	va_start(ap, fmt);
84 	ret = vasprintf(str, fmt, ap);
85 	va_end(ap);
86 
87 	return ret;
88 }
89 #endif
90