1/*	$OpenBSD: vasprintf.c,v 1.23 2019/01/25 00:19:25 millert Exp $	*/
2
3/*
4 * Copyright (c) 1997 Todd C. Miller <millert@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19#include <stdio.h>
20#include <stdlib.h>
21#include <string.h>
22#include <errno.h>
23#include <unistd.h>
24#include "local.h"
25
26#define	INITIAL_SIZE	128
27
28int
29vasprintf(char **str, const char *fmt, __va_list ap)
30{
31	int ret;
32	FILE f;
33	struct __sfileext fext;
34	const int pgsz = getpagesize();
35
36	_FILEEXT_SETUP(&f, &fext);
37	f._file = -1;
38	f._flags = __SWR | __SSTR | __SALC;
39	f._bf._base = f._p = malloc(INITIAL_SIZE);
40	if (f._bf._base == NULL)
41		goto err;
42	f._bf._size = f._w = INITIAL_SIZE - 1;	/* leave room for the NUL */
43	ret = __vfprintf(&f, fmt, ap);
44	if (ret == -1)
45		goto err;
46	*f._p = '\0';
47	if (ret + 1 > INITIAL_SIZE && ret + 1 < pgsz / 2) {
48		/* midsize allocations can try to conserve memory */
49		unsigned char *_base = recallocarray(f._bf._base,
50		    f._bf._size + 1, ret + 1, 1);
51
52		if (_base == NULL)
53			goto err;
54		*str = (char *)_base;
55	} else
56		*str = (char *)f._bf._base;
57	return (ret);
58
59err:
60	free(f._bf._base);
61	f._bf._base = NULL;
62	*str = NULL;
63	errno = ENOMEM;
64	return (-1);
65}
66DEF_WEAK(vasprintf);
67