1 /* $OpenBSD: misc.c,v 1.3 2021/05/17 12:02:58 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
addargs(arglist * args,const char * fmt,...)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(ERR_NOMEM, "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,
58 sizeof(char *));
59 if (!args->list)
60 err(ERR_NOMEM, NULL);
61 args->nalloc = nalloc;
62 args->list[args->num++] = cp;
63 args->list[args->num] = NULL;
64 }
65
66 void
freeargs(arglist * args)67 freeargs(arglist *args)
68 {
69 u_int i;
70
71 if (args->list != NULL) {
72 for (i = 0; i < args->num; i++)
73 free(args->list[i]);
74 free(args->list);
75 args->nalloc = args->num = 0;
76 args->list = NULL;
77 }
78 }
79