xref: /titanic_50/usr/src/cmd/ssh/libopenbsd-compat/common/bsd-asprintf.c (revision 09cb82ca24006b806e9f17e2135eef96364facfe)
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 #pragma ident	"%Z%%M%	%I%	%E% SMI"
21 
22 #include "includes.h"
23 
24 #ifndef HAVE_VASPRINTF
25 
26 #include <errno.h>
27 #include <stdarg.h>
28 #include <stdlib.h>
29 
30 #ifndef VA_COPY
31 #ifdef HAVE_VA_COPY
32 #define	VA_COPY(dest, src) va_copy(dest, src)
33 #else
34 #ifdef HAVE___VA_COPY
35 #define	VA_COPY(dest, src) __va_copy(dest, src)
36 #else
37 #define	VA_COPY(dest, src) (dest) = (src)
38 #endif
39 #endif
40 #endif
41 
42 #define	INIT_SZ	128
43 
44 int
45 vasprintf(char **str, const char *fmt, va_list ap)
46 {
47 	int ret = -1;
48 	va_list ap2;
49 	char *string, *newstr;
50 	size_t len;
51 
52 	VA_COPY(ap2, ap);
53 	if ((string = malloc(INIT_SZ)) == NULL)
54 		goto fail;
55 
56 	ret = vsnprintf(string, INIT_SZ, fmt, ap2);
57 	if (ret >= 0 && ret < INIT_SZ) { /* succeeded with initial alloc */
58 		*str = string;
59 	} else if (ret == INT_MAX || ret < 0) { /* Bad length */
60 		free(string);
61 		goto fail;
62 	} else {	/* bigger than initial, realloc allowing for nul */
63 		len = (size_t)ret + 1;
64 		if ((newstr = realloc(string, len)) == NULL) {
65 			free(string);
66 			goto fail;
67 		} else {
68 			va_end(ap2);
69 			VA_COPY(ap2, ap);
70 			ret = vsnprintf(newstr, len, fmt, ap2);
71 			if (ret >= 0 && (size_t)ret < len) {
72 				*str = newstr;
73 			} else { /* failed with realloc'ed string, give up */
74 				free(newstr);
75 				goto fail;
76 			}
77 		}
78 	}
79 	va_end(ap2);
80 	return (ret);
81 
82 fail:
83 	*str = NULL;
84 	errno = ENOMEM;
85 	va_end(ap2);
86 	return (-1);
87 }
88 #endif
89 
90 #ifndef HAVE_ASPRINTF
91 int
92 asprintf(char **str, const char *fmt, ...)
93 {
94 	va_list ap;
95 	int ret;
96 
97 	*str = NULL;
98 	va_start(ap, fmt);
99 	ret = vasprintf(str, fmt, ap);
100 	va_end(ap);
101 
102 	return (ret);
103 }
104 #endif
105