1 1.1.1.2 wiz /* Id: compat_vasprintf.c,v 1.4 2020/06/15 01:37:15 schwarze Exp */ 2 1.1 christos /* 3 1.1 christos * Copyright (c) 2015 Ingo Schwarze <schwarze (at) openbsd.org> 4 1.1 christos * 5 1.1 christos * Permission to use, copy, modify, and distribute this software for any 6 1.1 christos * purpose with or without fee is hereby granted, provided that the above 7 1.1 christos * copyright notice and this permission notice appear in all copies. 8 1.1 christos * 9 1.1 christos * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 10 1.1 christos * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 11 1.1 christos * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 12 1.1 christos * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 13 1.1 christos * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 14 1.1 christos * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 15 1.1 christos * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 16 1.1 christos * 17 1.1 christos * This fallback implementation is not efficient: 18 1.1 christos * It does the formatting twice. 19 1.1 christos * Short of fiddling with the unknown internals of the system's 20 1.1 christos * printf(3) or completely reimplementing printf(3), i can't think 21 1.1 christos * of another portable solution. 22 1.1 christos */ 23 1.1.1.2 wiz #include "config.h" 24 1.1 christos 25 1.1 christos #include <stdarg.h> 26 1.1 christos #include <stdio.h> 27 1.1 christos #include <stdlib.h> 28 1.1 christos 29 1.1 christos int 30 1.1 christos vasprintf(char **ret, const char *format, va_list ap) 31 1.1 christos { 32 1.1 christos char buf[2]; 33 1.1 christos va_list ap2; 34 1.1 christos int sz; 35 1.1 christos 36 1.1 christos va_copy(ap2, ap); 37 1.1 christos sz = vsnprintf(buf, sizeof(buf), format, ap2); 38 1.1 christos va_end(ap2); 39 1.1 christos 40 1.1 christos if (sz != -1 && (*ret = malloc(sz + 1)) != NULL) { 41 1.1 christos if (vsnprintf(*ret, sz + 1, format, ap) == sz) 42 1.1 christos return sz; 43 1.1 christos free(*ret); 44 1.1 christos } 45 1.1 christos *ret = NULL; 46 1.1 christos return -1; 47 1.1 christos } 48