1 /* $OpenBSD: misc.c,v 1.2 2021/03/22 11:14:42 claudio Exp $ */ 2 /* 3 * Copyright (c) 2000 Markus Friedl. All rights reserved. 4 * Copyright (c) 2005,2006 Damien Miller. All rights reserved. 5 * 6 * Redistribution and use in source and binary forms, with or without 7 * modification, are permitted provided that the following conditions 8 * are met: 9 * 1. Redistributions of source code must retain the above copyright 10 * notice, this list of conditions and the following disclaimer. 11 * 2. Redistributions in binary form must reproduce the above copyright 12 * notice, this list of conditions and the following disclaimer in the 13 * documentation and/or other materials provided with the distribution. 14 * 15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 */ 26 27 #include <stdlib.h> 28 #include <unistd.h> 29 #include <stdio.h> 30 #include <stdarg.h> 31 #include <err.h> 32 33 #include "extern.h" 34 35 /* function to assist building execv() arguments */ 36 void 37 addargs(arglist *args, const char *fmt, ...) 38 { 39 va_list ap; 40 char *cp; 41 u_int nalloc; 42 int r; 43 44 va_start(ap, fmt); 45 r = vasprintf(&cp, fmt, ap); 46 va_end(ap); 47 if (r == -1) 48 err(1, "addargs: argument too long"); 49 50 nalloc = args->nalloc; 51 if (args->list == NULL) { 52 nalloc = 32; 53 args->num = 0; 54 } else if (args->num+2 >= nalloc) 55 nalloc *= 2; 56 57 args->list = recallocarray(args->list, args->nalloc, nalloc, sizeof(char *)); 58 if (!args->list) 59 err(1, "malloc"); 60 args->nalloc = nalloc; 61 args->list[args->num++] = cp; 62 args->list[args->num] = NULL; 63 } 64 65 void 66 freeargs(arglist *args) 67 { 68 u_int i; 69 70 if (args->list != NULL) { 71 for (i = 0; i < args->num; i++) 72 free(args->list[i]); 73 free(args->list); 74 args->nalloc = args->num = 0; 75 args->list = NULL; 76 } 77 } 78