1 /* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
5 * Copyright 2003, 2004, 2005, 2007, 2008 Massachusetts Institute of Technology.
8 * Export of this software from the United States of America may
9 * require a specific license from the United States Government.
10 * It is the responsibility of any person or organization contemplating
11 * export to obtain such a license before exporting.
13 * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
14 * distribute this software and its documentation for any purpose and
15 * without fee is hereby granted, provided that the above copyright
16 * notice appear in all copies and that both that copyright notice and
17 * this permission notice appear in supporting documentation, and that
18 * the name of M.I.T. not be used in advertising or publicity pertaining
19 * to distribution of the software without specific, written prior
20 * permission. Furthermore if you modify this software you must label
21 * your software as modified software and not distribute it in such a
22 * fashion that it might be confused with the original M.I.T. software.
23 * M.I.T. makes no representations about the suitability of
24 * this software for any purpose. It is provided "as is" without express
25 * or implied warranty.
28 * Provide {,v}asprintf for platforms that don't have them.
37 # define SIZE_MAX ((size_t)((size_t)0 - 1))
39 #if defined(HAS_VA_COPY) || defined(va_copy)
41 #elif defined(CAN_COPY_VA_LIST)
42 #define va_copy(dest, src) ((dest) = (src))
44 /* Assume array type, but still simply copyable.
46 There is, theoretically, the possibility that va_start will
47 allocate some storage pointed to by the va_list, and in that case
48 we'll just lose. If anyone cares, we could try to devise a test
50 #define va_copy(dest, src) memcmp(dest, src, sizeof(va_list))
53 /* On error: BSD: Set *ret to NULL. GNU: *ret is undefined.
55 Since we want to be able to use the GNU version directly, we need
56 provide only the weaker guarantee in this version. */
58 vasprintf(char **ret, const char *format, va_list ap)
61 char *str = NULL, *nstr;
66 if (len >= SIZE_MAX || len == 0)
68 nstr = realloc(str, len);
73 len2 = vsnprintf(str, len, format, ap2);
75 /* ISO C vsnprintf returns the needed length. Some old
76 vsnprintf implementations return -1 on truncation. */
78 /* Don't know how much space we need, just that we didn't
79 supply enough; get a bigger buffer and try again. */
80 if (len <= SIZE_MAX/2)
82 else if (len < SIZE_MAX)
86 } else if ((unsigned int) len2 >= SIZE_MAX) {
87 /* Need more space than we can request. */
89 } else if ((size_t) len2 >= len) {
90 /* Need more space, but we know how much. */
91 len = (size_t) len2 + 1;
97 /* We might've allocated more than we need, if we're still using
98 the initial guess, or we got here by doubling. */
99 if ((size_t) len2 < len - 1) {
100 nstr = realloc(str, (size_t) len2 + 1);