xref: /freebsd/usr.bin/xargs/xargs.c (revision 23583c4fe122ebaebadb95162edd18a40d5eb963)
19b50d902SRodney W. Grimes /*-
29b50d902SRodney W. Grimes  * Copyright (c) 1990, 1993
39b50d902SRodney W. Grimes  *	The Regents of the University of California.  All rights reserved.
49b50d902SRodney W. Grimes  *
59b50d902SRodney W. Grimes  * This code is derived from software contributed to Berkeley by
69b50d902SRodney W. Grimes  * John B. Roll Jr.
79b50d902SRodney W. Grimes  *
89b50d902SRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
99b50d902SRodney W. Grimes  * modification, are permitted provided that the following conditions
109b50d902SRodney W. Grimes  * are met:
119b50d902SRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
129b50d902SRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
139b50d902SRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
149b50d902SRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
159b50d902SRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
169b50d902SRodney W. Grimes  * 4. Neither the name of the University nor the names of its contributors
179b50d902SRodney W. Grimes  *    may be used to endorse or promote products derived from this software
189b50d902SRodney W. Grimes  *    without specific prior written permission.
199b50d902SRodney W. Grimes  *
209b50d902SRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
219b50d902SRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
229b50d902SRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
239b50d902SRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
249b50d902SRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
259b50d902SRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
269b50d902SRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
279b50d902SRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
289b50d902SRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
299b50d902SRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
309b50d902SRodney W. Grimes  * SUCH DAMAGE.
31fc17b349SJuli Mallett  *
32fc17b349SJuli Mallett  * $xMach: xargs.c,v 1.6 2002/02/23 05:27:47 tim Exp $
339b50d902SRodney W. Grimes  */
349b50d902SRodney W. Grimes 
358eb2a3deSDavid E. O'Brien #if 0
36d7a43b24SJuli Mallett #ifndef lint
37d7a43b24SJuli Mallett static const char copyright[] =
38d7a43b24SJuli Mallett "@(#) Copyright (c) 1990, 1993\n\
39d7a43b24SJuli Mallett 	The Regents of the University of California.  All rights reserved.\n";
40d7a43b24SJuli Mallett #endif /* not lint */
41d7a43b24SJuli Mallett 
42d7a43b24SJuli Mallett #ifndef lint
43d7a43b24SJuli Mallett static char sccsid[] = "@(#)xargs.c	8.1 (Berkeley) 6/6/93";
44d7a43b24SJuli Mallett #endif /* not lint */
45d7a43b24SJuli Mallett #endif
4651883012SMike Barcroft #include <sys/cdefs.h>
4751883012SMike Barcroft __FBSDID("$FreeBSD$");
4851883012SMike Barcroft 
4940c6b893SRuslan Ermilov #include <sys/param.h>
509b50d902SRodney W. Grimes #include <sys/wait.h>
5116b07a33SMark Murray 
52a51024e2SPhilippe Charnier #include <err.h>
538ad749a4SDag-Erling Smørgrav #include <errno.h>
5498186e89SMaxime Henrion #include <fcntl.h>
55305e39f4SJuli Mallett #include <langinfo.h>
56305e39f4SJuli Mallett #include <locale.h>
57305e39f4SJuli Mallett #include <paths.h>
58305e39f4SJuli Mallett #include <regex.h>
599b50d902SRodney W. Grimes #include <stdio.h>
609b50d902SRodney W. Grimes #include <stdlib.h>
619b50d902SRodney W. Grimes #include <string.h>
629b50d902SRodney W. Grimes #include <unistd.h>
6316b07a33SMark Murray 
649b50d902SRodney W. Grimes #include "pathnames.h"
659b50d902SRodney W. Grimes 
661926d4aaSJuli Mallett static void	parse_input(int, char *[]);
671926d4aaSJuli Mallett static void	prerun(int, char *[]);
68305e39f4SJuli Mallett static int	prompt(void);
69fc17b349SJuli Mallett static void	run(char **);
7073385ac6SJuli Mallett static void	usage(void);
71fc17b349SJuli Mallett void		strnsubst(char **, const char *, const char *, size_t);
7292095ab6SStephen McKay static pid_t	xwait(int block, int *status);
73330d23f5STim J. Robbins static void	waitchildren(const char *, int);
7492095ab6SStephen McKay static void	pids_init(void);
7592095ab6SStephen McKay static int	pids_empty(void);
7692095ab6SStephen McKay static int	pids_full(void);
7792095ab6SStephen McKay static void	pids_add(pid_t pid);
7892095ab6SStephen McKay static int	pids_remove(pid_t pid);
7992095ab6SStephen McKay static int	findslot(pid_t pid);
8092095ab6SStephen McKay static int	findfreeslot(void);
8192095ab6SStephen McKay static void	clearslot(int slot);
829b50d902SRodney W. Grimes 
8316b07a33SMark Murray static char echo[] = _PATH_ECHO;
848eb2a3deSDavid E. O'Brien static char **av, **bxp, **ep, **endxp, **xp;
8591045075SJuli Mallett static char *argp, *bbp, *ebp, *inpline, *p, *replstr;
8691045075SJuli Mallett static const char *eofstr;
8798186e89SMaxime Henrion static int count, insingle, indouble, oflag, pflag, tflag, Rflag, rval, zflag;
88ba084f6aSJuli Mallett static int cnt, Iflag, jfound, Lflag, Sflag, wasquoted, xflag;
89330d23f5STim J. Robbins static int curprocs, maxprocs;
9092095ab6SStephen McKay static pid_t *childpids;
91330d23f5STim J. Robbins 
92330d23f5STim J. Robbins static volatile int childerr;
9316b07a33SMark Murray 
9499a84ce1STim J. Robbins extern char **environ;
9573385ac6SJuli Mallett 
96a51024e2SPhilippe Charnier int
971926d4aaSJuli Mallett main(int argc, char *argv[])
989b50d902SRodney W. Grimes {
99a3e5bc4fSJoseph Koshy 	long arg_max;
10091045075SJuli Mallett 	int ch, Jflag, nargs, nflag, nline;
101fc17b349SJuli Mallett 	size_t linelen;
1023c675167SJuli Mallett 	char *endptr;
1039b50d902SRodney W. Grimes 
104fc17b349SJuli Mallett 	inpline = replstr = NULL;
10591045075SJuli Mallett 	ep = environ;
106fc17b349SJuli Mallett 	eofstr = "";
10791045075SJuli Mallett 	Jflag = nflag = 0;
1088d904f15SDima Dorfman 
109f58b94cbSTim J. Robbins 	(void)setlocale(LC_ALL, "");
110305e39f4SJuli Mallett 
1119b50d902SRodney W. Grimes 	/*
1129b50d902SRodney W. Grimes 	 * POSIX.2 limits the exec line length to ARG_MAX - 2K.  Running that
1139b50d902SRodney W. Grimes 	 * caused some E2BIG errors, so it was changed to ARG_MAX - 4K.  Given
1149b50d902SRodney W. Grimes 	 * that the smallest argument is 2 bytes in length, this means that
1159b50d902SRodney W. Grimes 	 * the number of arguments is limited to:
1169b50d902SRodney W. Grimes 	 *
1179b50d902SRodney W. Grimes 	 *	 (ARG_MAX - 4K - LENGTH(utility + arguments)) / 2.
1189b50d902SRodney W. Grimes 	 *
1199b50d902SRodney W. Grimes 	 * We arbitrarily limit the number of arguments to 5000.  This is
1209b50d902SRodney W. Grimes 	 * allowed by POSIX.2 as long as the resulting minimum exec line is
1219b50d902SRodney W. Grimes 	 * at least LINE_MAX.  Realloc'ing as necessary is possible, but
1229b50d902SRodney W. Grimes 	 * probably not worthwhile.
1239b50d902SRodney W. Grimes 	 */
1249b50d902SRodney W. Grimes 	nargs = 5000;
125a3e5bc4fSJoseph Koshy 	if ((arg_max = sysconf(_SC_ARG_MAX)) == -1)
126a3e5bc4fSJoseph Koshy 		errx(1, "sysconf(_SC_ARG_MAX) failed");
127a3e5bc4fSJoseph Koshy 	nline = arg_max - 4 * 1024;
12891045075SJuli Mallett 	while (*ep != NULL) {
129e5009da0SSatoshi Asami 		/* 1 byte for each '\0' */
130e5009da0SSatoshi Asami 		nline -= strlen(*ep++) + 1 + sizeof(*ep);
131e5009da0SSatoshi Asami 	}
132330d23f5STim J. Robbins 	maxprocs = 1;
133ba084f6aSJuli Mallett 	while ((ch = getopt(argc, argv, "0E:I:J:L:n:oP:pR:S:s:rtx")) != -1)
1349b50d902SRodney W. Grimes 		switch (ch) {
135fc17b349SJuli Mallett 		case 'E':
136fc17b349SJuli Mallett 			eofstr = optarg;
137fc17b349SJuli Mallett 			break;
138fc17b349SJuli Mallett 		case 'I':
1396ea89183SJuli Mallett 			Jflag = 0;
140fc17b349SJuli Mallett 			Iflag = 1;
1414f49da74SJuli Mallett 			Lflag = 1;
142fc17b349SJuli Mallett 			replstr = optarg;
143fc17b349SJuli Mallett 			break;
1448d904f15SDima Dorfman 		case 'J':
1456ea89183SJuli Mallett 			Iflag = 0;
146b50a7286SJuli Mallett 			Jflag = 1;
1478d904f15SDima Dorfman 			replstr = optarg;
1488d904f15SDima Dorfman 			break;
149fc17b349SJuli Mallett 		case 'L':
1504f49da74SJuli Mallett 			Lflag = atoi(optarg);
151fc17b349SJuli Mallett 			break;
1529b50d902SRodney W. Grimes 		case 'n':
1539b50d902SRodney W. Grimes 			nflag = 1;
1549b50d902SRodney W. Grimes 			if ((nargs = atoi(optarg)) <= 0)
155a51024e2SPhilippe Charnier 				errx(1, "illegal argument count");
1569b50d902SRodney W. Grimes 			break;
15798186e89SMaxime Henrion 		case 'o':
15898186e89SMaxime Henrion 			oflag = 1;
15998186e89SMaxime Henrion 			break;
160330d23f5STim J. Robbins 		case 'P':
161330d23f5STim J. Robbins 			if ((maxprocs = atoi(optarg)) <= 0)
162330d23f5STim J. Robbins 				errx(1, "max. processes must be >0");
163330d23f5STim J. Robbins 			break;
164fc17b349SJuli Mallett 		case 'p':
165fc17b349SJuli Mallett 			pflag = 1;
166fc17b349SJuli Mallett 			break;
167b50a7286SJuli Mallett 		case 'R':
1683c675167SJuli Mallett 			Rflag = strtol(optarg, &endptr, 10);
1693c675167SJuli Mallett 			if (*endptr != '\0')
1703c675167SJuli Mallett 				errx(1, "replacements must be a number");
171b50a7286SJuli Mallett 			break;
1722d14e0e5SDag-Erling Smørgrav 		case 'r':
1732d14e0e5SDag-Erling Smørgrav 			/* GNU compatibility */
1742d14e0e5SDag-Erling Smørgrav 			break;
175ba084f6aSJuli Mallett 		case 'S':
176ba084f6aSJuli Mallett 			Sflag = strtoul(optarg, &endptr, 10);
177ba084f6aSJuli Mallett 			if (*endptr != '\0')
178ba084f6aSJuli Mallett 				errx(1, "replsize must be a number");
179ba084f6aSJuli Mallett 			break;
1809b50d902SRodney W. Grimes 		case 's':
1819b50d902SRodney W. Grimes 			nline = atoi(optarg);
1829b50d902SRodney W. Grimes 			break;
1839b50d902SRodney W. Grimes 		case 't':
1849b50d902SRodney W. Grimes 			tflag = 1;
1859b50d902SRodney W. Grimes 			break;
1869b50d902SRodney W. Grimes 		case 'x':
1879b50d902SRodney W. Grimes 			xflag = 1;
1889b50d902SRodney W. Grimes 			break;
189d9198881SWarner Losh 		case '0':
190d9198881SWarner Losh 			zflag = 1;
191d9198881SWarner Losh 			break;
1929b50d902SRodney W. Grimes 		case '?':
1939b50d902SRodney W. Grimes 		default:
1949b50d902SRodney W. Grimes 			usage();
1959b50d902SRodney W. Grimes 	}
1969b50d902SRodney W. Grimes 	argc -= optind;
1979b50d902SRodney W. Grimes 	argv += optind;
1989b50d902SRodney W. Grimes 
1996ea89183SJuli Mallett 	if (!Iflag && Rflag)
2006ea89183SJuli Mallett 		usage();
201ba084f6aSJuli Mallett 	if (!Iflag && Sflag)
202ba084f6aSJuli Mallett 		usage();
2036ea89183SJuli Mallett 	if (Iflag && !Rflag)
2046ea89183SJuli Mallett 		Rflag = 5;
205ba084f6aSJuli Mallett 	if (Iflag && !Sflag)
206ba084f6aSJuli Mallett 		Sflag = 255;
2079b50d902SRodney W. Grimes 	if (xflag && !nflag)
2089b50d902SRodney W. Grimes 		usage();
2094f49da74SJuli Mallett 	if (Iflag || Lflag)
210fc17b349SJuli Mallett 		xflag = 1;
211fc17b349SJuli Mallett 	if (replstr != NULL && *replstr == '\0')
212fc17b349SJuli Mallett 		errx(1, "replstr may not be empty");
2139b50d902SRodney W. Grimes 
21492095ab6SStephen McKay 	pids_init();
21592095ab6SStephen McKay 
2169b50d902SRodney W. Grimes 	/*
2179b50d902SRodney W. Grimes 	 * Allocate pointers for the utility name, the utility arguments,
2189b50d902SRodney W. Grimes 	 * the maximum arguments to be read from stdin and the trailing
2199b50d902SRodney W. Grimes 	 * NULL.
2209b50d902SRodney W. Grimes 	 */
221fc17b349SJuli Mallett 	linelen = 1 + argc + nargs + 1;
2220fa5e8dcSJuli Mallett 	if ((av = bxp = malloc(linelen * sizeof(char **))) == NULL)
22391045075SJuli Mallett 		errx(1, "malloc failed");
2249b50d902SRodney W. Grimes 
2259b50d902SRodney W. Grimes 	/*
2269b50d902SRodney W. Grimes 	 * Use the user's name for the utility as argv[0], just like the
2279b50d902SRodney W. Grimes 	 * shell.  Echo is the default.  Set up pointers for the user's
2289b50d902SRodney W. Grimes 	 * arguments.
2299b50d902SRodney W. Grimes 	 */
2303dca1afcSJuli Mallett 	if (*argv == NULL)
2319bf450b8SJuli Mallett 		cnt = strlen(*bxp++ = echo);
2329b50d902SRodney W. Grimes 	else {
2339b50d902SRodney W. Grimes 		do {
234b50a7286SJuli Mallett 			if (Jflag && strcmp(*argv, replstr) == 0) {
23591045075SJuli Mallett 				char **avj;
2368d904f15SDima Dorfman 				jfound = 1;
2378d904f15SDima Dorfman 				argv++;
2388d904f15SDima Dorfman 				for (avj = argv; *avj; avj++)
2398d904f15SDima Dorfman 					cnt += strlen(*avj) + 1;
2408d904f15SDima Dorfman 				break;
2418d904f15SDima Dorfman 			}
2429b50d902SRodney W. Grimes 			cnt += strlen(*bxp++ = *argv) + 1;
2433dca1afcSJuli Mallett 		} while (*++argv != NULL);
2449b50d902SRodney W. Grimes 	}
2459b50d902SRodney W. Grimes 
2469b50d902SRodney W. Grimes 	/*
2479b50d902SRodney W. Grimes 	 * Set up begin/end/traversing pointers into the array.  The -n
2489b50d902SRodney W. Grimes 	 * count doesn't include the trailing NULL pointer, so the malloc
2499b50d902SRodney W. Grimes 	 * added in an extra slot.
2509b50d902SRodney W. Grimes 	 */
2518eb2a3deSDavid E. O'Brien 	endxp = (xp = bxp) + nargs;
2529b50d902SRodney W. Grimes 
2539b50d902SRodney W. Grimes 	/*
2549b50d902SRodney W. Grimes 	 * Allocate buffer space for the arguments read from stdin and the
2559b50d902SRodney W. Grimes 	 * trailing NULL.  Buffer space is defined as the default or specified
2569b50d902SRodney W. Grimes 	 * space, minus the length of the utility name and arguments.  Set up
2579b50d902SRodney W. Grimes 	 * begin/end/traversing pointers into the array.  The -s count does
2589b50d902SRodney W. Grimes 	 * include the trailing NULL, so the malloc didn't add in an extra
2599b50d902SRodney W. Grimes 	 * slot.
2609b50d902SRodney W. Grimes 	 */
2619b50d902SRodney W. Grimes 	nline -= cnt;
2629b50d902SRodney W. Grimes 	if (nline <= 0)
263a51024e2SPhilippe Charnier 		errx(1, "insufficient space for command");
2649b50d902SRodney W. Grimes 
2659bf450b8SJuli Mallett 	if ((bbp = malloc((size_t)(nline + 1))) == NULL)
26691045075SJuli Mallett 		errx(1, "malloc failed");
2679b50d902SRodney W. Grimes 	ebp = (argp = p = bbp) + nline - 1;
26891045075SJuli Mallett 	for (;;)
26991045075SJuli Mallett 		parse_input(argc, argv);
27091045075SJuli Mallett }
2719b50d902SRodney W. Grimes 
27291045075SJuli Mallett static void
2731926d4aaSJuli Mallett parse_input(int argc, char *argv[])
27491045075SJuli Mallett {
27591045075SJuli Mallett 	int ch, foundeof;
27691045075SJuli Mallett 	char **avj;
27791045075SJuli Mallett 
27891045075SJuli Mallett 	foundeof = 0;
27991045075SJuli Mallett 
2809b50d902SRodney W. Grimes 	switch (ch = getchar()) {
2819b50d902SRodney W. Grimes 	case EOF:
2829b50d902SRodney W. Grimes 		/* No arguments since last exec. */
283330d23f5STim J. Robbins 		if (p == bbp) {
284*23583c4fSJilles Tjoelker 			waitchildren(*av, 1);
2859b50d902SRodney W. Grimes 			exit(rval);
286330d23f5STim J. Robbins 		}
2879b50d902SRodney W. Grimes 		goto arg1;
2889b50d902SRodney W. Grimes 	case ' ':
2899b50d902SRodney W. Grimes 	case '\t':
2909b50d902SRodney W. Grimes 		/* Quotes escape tabs and spaces. */
291d9198881SWarner Losh 		if (insingle || indouble || zflag)
2929b50d902SRodney W. Grimes 			goto addch;
2939b50d902SRodney W. Grimes 		goto arg2;
294d9198881SWarner Losh 	case '\0':
29546793db9SGarance A Drosehn 		if (zflag) {
29646793db9SGarance A Drosehn 			/*
29746793db9SGarance A Drosehn 			 * Increment 'count', so that nulls will be treated
29846793db9SGarance A Drosehn 			 * as end-of-line, as well as end-of-argument.  This
29946793db9SGarance A Drosehn 			 * is needed so -0 works properly with -I and -L.
30046793db9SGarance A Drosehn 			 */
30146793db9SGarance A Drosehn 			count++;
302d9198881SWarner Losh 			goto arg2;
30346793db9SGarance A Drosehn 		}
304d9198881SWarner Losh 		goto addch;
3059b50d902SRodney W. Grimes 	case '\n':
306d9198881SWarner Losh 		if (zflag)
307d9198881SWarner Losh 			goto addch;
30846793db9SGarance A Drosehn 		count++;	    /* Indicate end-of-line (used by -L) */
309d9198881SWarner Losh 
3109b50d902SRodney W. Grimes 		/* Quotes do not escape newlines. */
3119b50d902SRodney W. Grimes arg1:		if (insingle || indouble)
312a51024e2SPhilippe Charnier 			errx(1, "unterminated quote");
313ef9866beSJean-Marc Zucconi arg2:
314fc17b349SJuli Mallett 		foundeof = *eofstr != '\0' &&
3154aeb6382SJuli Mallett 		    strncmp(argp, eofstr, p - argp) == 0;
316fc17b349SJuli Mallett 
317ef9866beSJean-Marc Zucconi 		/* Do not make empty args unless they are quoted */
318fc17b349SJuli Mallett 		if ((argp != p || wasquoted) && !foundeof) {
319ef9866beSJean-Marc Zucconi 			*p++ = '\0';
3209b50d902SRodney W. Grimes 			*xp++ = argp;
321fc17b349SJuli Mallett 			if (Iflag) {
322fc17b349SJuli Mallett 				size_t curlen;
323b9b03ba0SJuli Mallett 
324b9b03ba0SJuli Mallett 				if (inpline == NULL)
325fc17b349SJuli Mallett 					curlen = 0;
326fc17b349SJuli Mallett 				else {
3271925cb24SJuli Mallett 					/*
3281925cb24SJuli Mallett 					 * If this string is not zero
3291925cb24SJuli Mallett 					 * length, append a space for
3302b239dd1SJens Schweikhardt 					 * separation before the next
3311925cb24SJuli Mallett 					 * argument.
3321925cb24SJuli Mallett 					 */
333b9b03ba0SJuli Mallett 					if ((curlen = strlen(inpline)))
334fc17b349SJuli Mallett 						strcat(inpline, " ");
335fc17b349SJuli Mallett 				}
336fc17b349SJuli Mallett 				curlen++;
3371925cb24SJuli Mallett 				/*
3381925cb24SJuli Mallett 				 * Allocate enough to hold what we will
3395eb40323SJuli Mallett 				 * be holding in a second, and to append
3401925cb24SJuli Mallett 				 * a space next time through, if we have
3411925cb24SJuli Mallett 				 * to.
3421925cb24SJuli Mallett 				 */
343b9b03ba0SJuli Mallett 				inpline = realloc(inpline, curlen + 2 +
344b9b03ba0SJuli Mallett 				    strlen(argp));
345fc17b349SJuli Mallett 				if (inpline == NULL)
34691045075SJuli Mallett 					errx(1, "realloc failed");
347fc17b349SJuli Mallett 				if (curlen == 1)
348fc17b349SJuli Mallett 					strcpy(inpline, argp);
349fc17b349SJuli Mallett 				else
350fc17b349SJuli Mallett 					strcat(inpline, argp);
351fc17b349SJuli Mallett 			}
352ef9866beSJean-Marc Zucconi 		}
3539b50d902SRodney W. Grimes 
3549b50d902SRodney W. Grimes 		/*
3559b50d902SRodney W. Grimes 		 * If max'd out on args or buffer, or reached EOF,
3569b50d902SRodney W. Grimes 		 * run the command.  If xflag and max'd out on buffer
3571925cb24SJuli Mallett 		 * but not on args, object.  Having reached the limit
3581925cb24SJuli Mallett 		 * of input lines, as specified by -L is the same as
3591925cb24SJuli Mallett 		 * maxing out on arguments.
3609b50d902SRodney W. Grimes 		 */
3618eb2a3deSDavid E. O'Brien 		if (xp == endxp || p > ebp || ch == EOF ||
3625eb40323SJuli Mallett 		    (Lflag <= count && xflag) || foundeof) {
3638eb2a3deSDavid E. O'Brien 			if (xflag && xp != endxp && p > ebp)
364a51024e2SPhilippe Charnier 				errx(1, "insufficient space for arguments");
3658d904f15SDima Dorfman 			if (jfound) {
3668d904f15SDima Dorfman 				for (avj = argv; *avj; avj++)
3678d904f15SDima Dorfman 					*xp++ = *avj;
3688d904f15SDima Dorfman 			}
36991045075SJuli Mallett 			prerun(argc, av);
370330d23f5STim J. Robbins 			if (ch == EOF || foundeof) {
371*23583c4fSJilles Tjoelker 				waitchildren(*av, 1);
3729b50d902SRodney W. Grimes 				exit(rval);
373330d23f5STim J. Robbins 			}
3749b50d902SRodney W. Grimes 			p = bbp;
3759b50d902SRodney W. Grimes 			xp = bxp;
376fc17b349SJuli Mallett 			count = 0;
377ef9866beSJean-Marc Zucconi 		}
3789b50d902SRodney W. Grimes 		argp = p;
379ef9866beSJean-Marc Zucconi 		wasquoted = 0;
3809b50d902SRodney W. Grimes 		break;
3819b50d902SRodney W. Grimes 	case '\'':
382d9198881SWarner Losh 		if (indouble || zflag)
3839b50d902SRodney W. Grimes 			goto addch;
3849b50d902SRodney W. Grimes 		insingle = !insingle;
385ef9866beSJean-Marc Zucconi 		wasquoted = 1;
3869b50d902SRodney W. Grimes 		break;
3879b50d902SRodney W. Grimes 	case '"':
388d9198881SWarner Losh 		if (insingle || zflag)
3899b50d902SRodney W. Grimes 			goto addch;
3909b50d902SRodney W. Grimes 		indouble = !indouble;
391ef9866beSJean-Marc Zucconi 		wasquoted = 1;
3929b50d902SRodney W. Grimes 		break;
3939b50d902SRodney W. Grimes 	case '\\':
394d9198881SWarner Losh 		if (zflag)
395d9198881SWarner Losh 			goto addch;
3969b50d902SRodney W. Grimes 		/* Backslash escapes anything, is escaped by quotes. */
3979b50d902SRodney W. Grimes 		if (!insingle && !indouble && (ch = getchar()) == EOF)
398a51024e2SPhilippe Charnier 			errx(1, "backslash at EOF");
3999b50d902SRodney W. Grimes 		/* FALLTHROUGH */
4009b50d902SRodney W. Grimes 	default:
4019b50d902SRodney W. Grimes addch:		if (p < ebp) {
4029b50d902SRodney W. Grimes 			*p++ = ch;
4039b50d902SRodney W. Grimes 			break;
4049b50d902SRodney W. Grimes 		}
4059b50d902SRodney W. Grimes 
4069b50d902SRodney W. Grimes 		/* If only one argument, not enough buffer space. */
4079b50d902SRodney W. Grimes 		if (bxp == xp)
408a51024e2SPhilippe Charnier 			errx(1, "insufficient space for argument");
4099b50d902SRodney W. Grimes 		/* Didn't hit argument limit, so if xflag object. */
4109b50d902SRodney W. Grimes 		if (xflag)
411a51024e2SPhilippe Charnier 			errx(1, "insufficient space for arguments");
4129b50d902SRodney W. Grimes 
4138d904f15SDima Dorfman 		if (jfound) {
4148d904f15SDima Dorfman 			for (avj = argv; *avj; avj++)
4158d904f15SDima Dorfman 				*xp++ = *avj;
4168d904f15SDima Dorfman 		}
41791045075SJuli Mallett 		prerun(argc, av);
4189b50d902SRodney W. Grimes 		xp = bxp;
4199b50d902SRodney W. Grimes 		cnt = ebp - argp;
420fc17b349SJuli Mallett 		memcpy(bbp, argp, (size_t)cnt);
4219b50d902SRodney W. Grimes 		p = (argp = bbp) + cnt;
4229b50d902SRodney W. Grimes 		*p++ = ch;
4239b50d902SRodney W. Grimes 		break;
4249b50d902SRodney W. Grimes 	}
4259b50d902SRodney W. Grimes }
4269b50d902SRodney W. Grimes 
427263dc775SJuli Mallett /*
428263dc775SJuli Mallett  * Do things necessary before run()'ing, such as -I substitution,
429263dc775SJuli Mallett  * and then call run().
430263dc775SJuli Mallett  */
431263dc775SJuli Mallett static void
4321926d4aaSJuli Mallett prerun(int argc, char *argv[])
433263dc775SJuli Mallett {
434263dc775SJuli Mallett 	char **tmp, **tmp2, **avj;
43591045075SJuli Mallett 	int repls;
43691045075SJuli Mallett 
43791045075SJuli Mallett 	repls = Rflag;
438263dc775SJuli Mallett 
439be70f7d4SJuli Mallett 	if (argc == 0 || repls == 0) {
440263dc775SJuli Mallett 		*xp = NULL;
441263dc775SJuli Mallett 		run(argv);
442263dc775SJuli Mallett 		return;
443263dc775SJuli Mallett 	}
444263dc775SJuli Mallett 
445263dc775SJuli Mallett 	avj = argv;
446263dc775SJuli Mallett 
447263dc775SJuli Mallett 	/*
448263dc775SJuli Mallett 	 * Allocate memory to hold the argument list, and
449263dc775SJuli Mallett 	 * a NULL at the tail.
450263dc775SJuli Mallett 	 */
451b6594dbaSJuli Mallett 	tmp = malloc((argc + 1) * sizeof(char**));
452263dc775SJuli Mallett 	if (tmp == NULL)
45391045075SJuli Mallett 		errx(1, "malloc failed");
454263dc775SJuli Mallett 	tmp2 = tmp;
455263dc775SJuli Mallett 
456263dc775SJuli Mallett 	/*
457263dc775SJuli Mallett 	 * Save the first argument and iterate over it, we
458263dc775SJuli Mallett 	 * cannot do strnsubst() to it.
459263dc775SJuli Mallett 	 */
460263dc775SJuli Mallett 	if ((*tmp++ = strdup(*avj++)) == NULL)
46191045075SJuli Mallett 		errx(1, "strdup failed");
462263dc775SJuli Mallett 
463263dc775SJuli Mallett 	/*
464263dc775SJuli Mallett 	 * For each argument to utility, if we have not used up
465263dc775SJuli Mallett 	 * the number of replacements we are allowed to do, and
4662b239dd1SJens Schweikhardt 	 * if the argument contains at least one occurrence of
467263dc775SJuli Mallett 	 * replstr, call strnsubst(), else just save the string.
468263dc775SJuli Mallett 	 * Iterations over elements of avj and tmp are done
469263dc775SJuli Mallett 	 * where appropriate.
470263dc775SJuli Mallett 	 */
471263dc775SJuli Mallett 	while (--argc) {
472263dc775SJuli Mallett 		*tmp = *avj++;
473263dc775SJuli Mallett 		if (repls && strstr(*tmp, replstr) != NULL) {
474ba084f6aSJuli Mallett 			strnsubst(tmp++, replstr, inpline, (size_t)Sflag);
4753c675167SJuli Mallett 			if (repls > 0)
476263dc775SJuli Mallett 				repls--;
477263dc775SJuli Mallett 		} else {
478263dc775SJuli Mallett 			if ((*tmp = strdup(*tmp)) == NULL)
47991045075SJuli Mallett 				errx(1, "strdup failed");
480263dc775SJuli Mallett 			tmp++;
481263dc775SJuli Mallett 		}
482263dc775SJuli Mallett 	}
483263dc775SJuli Mallett 
484263dc775SJuli Mallett 	/*
485263dc775SJuli Mallett 	 * Run it.
486263dc775SJuli Mallett 	 */
487b6594dbaSJuli Mallett 	*tmp = NULL;
488263dc775SJuli Mallett 	run(tmp2);
489263dc775SJuli Mallett 
490263dc775SJuli Mallett 	/*
491263dc775SJuli Mallett 	 * Walk from the tail to the head, free along the way.
492263dc775SJuli Mallett 	 */
493263dc775SJuli Mallett 	for (; tmp2 != tmp; tmp--)
494263dc775SJuli Mallett 		free(*tmp);
495263dc775SJuli Mallett 	/*
496263dc775SJuli Mallett 	 * Now free the list itself.
497263dc775SJuli Mallett 	 */
498263dc775SJuli Mallett 	free(tmp2);
499263dc775SJuli Mallett 
500263dc775SJuli Mallett 	/*
501986d829bSJuli Mallett 	 * Free the input line buffer, if we have one.
502263dc775SJuli Mallett 	 */
50351f7a48bSJuli Mallett 	if (inpline != NULL) {
50491045075SJuli Mallett 		free(inpline);
50551f7a48bSJuli Mallett 		inpline = NULL;
50651f7a48bSJuli Mallett 	}
507263dc775SJuli Mallett }
508263dc775SJuli Mallett 
509fc17b349SJuli Mallett static void
51073385ac6SJuli Mallett run(char **argv)
5119b50d902SRodney W. Grimes {
5129b50d902SRodney W. Grimes 	pid_t pid;
5130792992cSMaxime Henrion 	int fd;
514330d23f5STim J. Robbins 	char **avec;
5159b50d902SRodney W. Grimes 
516305e39f4SJuli Mallett 	/*
517305e39f4SJuli Mallett 	 * If the user wants to be notified of each command before it is
518305e39f4SJuli Mallett 	 * executed, notify them.  If they want the notification to be
519305e39f4SJuli Mallett 	 * followed by a prompt, then prompt them.
520305e39f4SJuli Mallett 	 */
521fc17b349SJuli Mallett 	if (tflag || pflag) {
5229b50d902SRodney W. Grimes 		(void)fprintf(stderr, "%s", *argv);
52391045075SJuli Mallett 		for (avec = argv + 1; *avec != NULL; ++avec)
52491045075SJuli Mallett 			(void)fprintf(stderr, " %s", *avec);
525305e39f4SJuli Mallett 		/*
526305e39f4SJuli Mallett 		 * If the user has asked to be prompted, do so.
527305e39f4SJuli Mallett 		 */
528305e39f4SJuli Mallett 		if (pflag)
529305e39f4SJuli Mallett 			/*
530305e39f4SJuli Mallett 			 * If they asked not to exec, return without execution
531305e39f4SJuli Mallett 			 * but if they asked to, go to the execution.  If we
532305e39f4SJuli Mallett 			 * could not open their tty, break the switch and drop
533305e39f4SJuli Mallett 			 * back to -t behaviour.
534305e39f4SJuli Mallett 			 */
535305e39f4SJuli Mallett 			switch (prompt()) {
536305e39f4SJuli Mallett 			case 0:
537fc17b349SJuli Mallett 				return;
538305e39f4SJuli Mallett 			case 1:
539305e39f4SJuli Mallett 				goto exec;
540305e39f4SJuli Mallett 			case 2:
541305e39f4SJuli Mallett 				break;
542305e39f4SJuli Mallett 			}
5439b50d902SRodney W. Grimes 		(void)fprintf(stderr, "\n");
5449b50d902SRodney W. Grimes 		(void)fflush(stderr);
5459b50d902SRodney W. Grimes 	}
546305e39f4SJuli Mallett exec:
5478ad749a4SDag-Erling Smørgrav 	childerr = 0;
5488ad749a4SDag-Erling Smørgrav 	switch (pid = vfork()) {
5499b50d902SRodney W. Grimes 	case -1:
5508ad749a4SDag-Erling Smørgrav 		err(1, "vfork");
5519b50d902SRodney W. Grimes 	case 0:
552cec1ba8cSMaxime Henrion 		if (oflag) {
5530792992cSMaxime Henrion 			if ((fd = open(_PATH_TTY, O_RDONLY)) == -1)
5540792992cSMaxime Henrion 				err(1, "can't open /dev/tty");
555cec1ba8cSMaxime Henrion 		} else {
5560792992cSMaxime Henrion 			fd = open(_PATH_DEVNULL, O_RDONLY);
5570792992cSMaxime Henrion 		}
5580792992cSMaxime Henrion 		if (fd > STDIN_FILENO) {
5590792992cSMaxime Henrion 			if (dup2(fd, STDIN_FILENO) != 0)
5600792992cSMaxime Henrion 				err(1, "can't dup2 to stdin");
5610792992cSMaxime Henrion 			close(fd);
56298186e89SMaxime Henrion 		}
5639b50d902SRodney W. Grimes 		execvp(argv[0], argv);
5648ad749a4SDag-Erling Smørgrav 		childerr = errno;
5659b50d902SRodney W. Grimes 		_exit(1);
5669b50d902SRodney W. Grimes 	}
56792095ab6SStephen McKay 	pids_add(pid);
568330d23f5STim J. Robbins 	waitchildren(*argv, 0);
569330d23f5STim J. Robbins }
570330d23f5STim J. Robbins 
57192095ab6SStephen McKay /*
57292095ab6SStephen McKay  * Wait for a tracked child to exit and return its pid and exit status.
57392095ab6SStephen McKay  *
57492095ab6SStephen McKay  * Ignores (discards) all untracked child processes.
57592095ab6SStephen McKay  * Returns -1 and sets errno to ECHILD if no tracked children exist.
57692095ab6SStephen McKay  * If block is set, waits indefinitely for a child process to exit.
57792095ab6SStephen McKay  * If block is not set and no children have exited, returns 0 immediately.
57892095ab6SStephen McKay  */
57992095ab6SStephen McKay static pid_t
58092095ab6SStephen McKay xwait(int block, int *status) {
58192095ab6SStephen McKay 	pid_t pid;
58292095ab6SStephen McKay 
58392095ab6SStephen McKay 	if (pids_empty()) {
58492095ab6SStephen McKay 		errno = ECHILD;
58529afe03fSStephen McKay 		return (-1);
58692095ab6SStephen McKay 	}
58792095ab6SStephen McKay 
58892095ab6SStephen McKay 	while ((pid = waitpid(-1, status, block ? 0 : WNOHANG)) > 0)
58992095ab6SStephen McKay 		if (pids_remove(pid))
59092095ab6SStephen McKay 			break;
59192095ab6SStephen McKay 
59229afe03fSStephen McKay 	return (pid);
59392095ab6SStephen McKay }
59492095ab6SStephen McKay 
595330d23f5STim J. Robbins static void
596330d23f5STim J. Robbins waitchildren(const char *name, int waitall)
597330d23f5STim J. Robbins {
598330d23f5STim J. Robbins 	pid_t pid;
599330d23f5STim J. Robbins 	int status;
600330d23f5STim J. Robbins 
60192095ab6SStephen McKay 	while ((pid = xwait(waitall || pids_full(), &status)) > 0) {
602fc17b349SJuli Mallett 		/* If we couldn't invoke the utility, exit. */
603330d23f5STim J. Robbins 		if (childerr != 0) {
604330d23f5STim J. Robbins 			errno = childerr;
605330d23f5STim J. Robbins 			err(errno == ENOENT ? 127 : 126, "%s", name);
606330d23f5STim J. Robbins 		}
607330d23f5STim J. Robbins 		/*
608330d23f5STim J. Robbins 		 * If utility signaled or exited with a value of 255,
609330d23f5STim J. Robbins 		 * exit 1-125.
610330d23f5STim J. Robbins 		 */
611*23583c4fSJilles Tjoelker 		if (WIFSIGNALED(status))
612*23583c4fSJilles Tjoelker 			errx(1, "%s: terminated with signal %d, aborting",
613*23583c4fSJilles Tjoelker 			    name, WTERMSIG(status));
614*23583c4fSJilles Tjoelker 		if (WEXITSTATUS(status) == 255)
615*23583c4fSJilles Tjoelker 			errx(1, "%s: exited with status 255, aborting", name);
6169b50d902SRodney W. Grimes 		if (WEXITSTATUS(status))
6179b50d902SRodney W. Grimes 			rval = 1;
6189b50d902SRodney W. Grimes 	}
61992095ab6SStephen McKay 
620330d23f5STim J. Robbins 	if (pid == -1 && errno != ECHILD)
62192095ab6SStephen McKay 		err(1, "waitpid");
62292095ab6SStephen McKay }
62392095ab6SStephen McKay 
62492095ab6SStephen McKay #define	NOPID	(0)
62592095ab6SStephen McKay 
62692095ab6SStephen McKay static void
62729afe03fSStephen McKay pids_init(void)
62892095ab6SStephen McKay {
62992095ab6SStephen McKay 	int i;
63092095ab6SStephen McKay 
63192095ab6SStephen McKay 	if ((childpids = malloc(maxprocs * sizeof(*childpids))) == NULL)
63292095ab6SStephen McKay 		errx(1, "malloc failed");
63392095ab6SStephen McKay 
63492095ab6SStephen McKay 	for (i = 0; i < maxprocs; i++)
63592095ab6SStephen McKay 		clearslot(i);
63692095ab6SStephen McKay }
63792095ab6SStephen McKay 
63892095ab6SStephen McKay static int
63929afe03fSStephen McKay pids_empty(void)
64092095ab6SStephen McKay {
64129afe03fSStephen McKay 	return (curprocs == 0);
64292095ab6SStephen McKay }
64392095ab6SStephen McKay 
64492095ab6SStephen McKay static int
64529afe03fSStephen McKay pids_full(void)
64692095ab6SStephen McKay {
64729afe03fSStephen McKay 	return (curprocs >= maxprocs);
64892095ab6SStephen McKay }
64992095ab6SStephen McKay 
65092095ab6SStephen McKay static void
65192095ab6SStephen McKay pids_add(pid_t pid)
65292095ab6SStephen McKay {
65392095ab6SStephen McKay 	int slot;
65492095ab6SStephen McKay 
65592095ab6SStephen McKay 	slot = findfreeslot();
65692095ab6SStephen McKay 	childpids[slot] = pid;
65792095ab6SStephen McKay 	curprocs++;
65892095ab6SStephen McKay }
65992095ab6SStephen McKay 
66092095ab6SStephen McKay static int
66192095ab6SStephen McKay pids_remove(pid_t pid)
66292095ab6SStephen McKay {
66392095ab6SStephen McKay 	int slot;
66492095ab6SStephen McKay 
66592095ab6SStephen McKay 	if ((slot = findslot(pid)) < 0)
66629afe03fSStephen McKay 		return (0);
66792095ab6SStephen McKay 
66892095ab6SStephen McKay 	clearslot(slot);
66992095ab6SStephen McKay 	curprocs--;
67029afe03fSStephen McKay 	return (1);
67192095ab6SStephen McKay }
67292095ab6SStephen McKay 
67392095ab6SStephen McKay static int
67429afe03fSStephen McKay findfreeslot(void)
67592095ab6SStephen McKay {
67692095ab6SStephen McKay 	int slot;
67792095ab6SStephen McKay 
67892095ab6SStephen McKay 	if ((slot = findslot(NOPID)) < 0)
67992095ab6SStephen McKay 		errx(1, "internal error: no free pid slot");
68092095ab6SStephen McKay 
68129afe03fSStephen McKay 	return (slot);
68292095ab6SStephen McKay }
68392095ab6SStephen McKay 
68492095ab6SStephen McKay static int
68592095ab6SStephen McKay findslot(pid_t pid)
68692095ab6SStephen McKay {
68792095ab6SStephen McKay 	int slot;
68892095ab6SStephen McKay 
68992095ab6SStephen McKay 	for (slot = 0; slot < maxprocs; slot++)
69092095ab6SStephen McKay 		if (childpids[slot] == pid)
69129afe03fSStephen McKay 			return (slot);
69292095ab6SStephen McKay 
69329afe03fSStephen McKay 	return (-1);
69492095ab6SStephen McKay }
69592095ab6SStephen McKay 
69692095ab6SStephen McKay static void
69792095ab6SStephen McKay clearslot(int slot)
69892095ab6SStephen McKay {
69992095ab6SStephen McKay 	childpids[slot] = NOPID;
700330d23f5STim J. Robbins }
7019b50d902SRodney W. Grimes 
702305e39f4SJuli Mallett /*
703305e39f4SJuli Mallett  * Prompt the user about running a command.
704305e39f4SJuli Mallett  */
705305e39f4SJuli Mallett static int
706305e39f4SJuli Mallett prompt(void)
707305e39f4SJuli Mallett {
708305e39f4SJuli Mallett 	regex_t cre;
709305e39f4SJuli Mallett 	size_t rsize;
710305e39f4SJuli Mallett 	int match;
711305e39f4SJuli Mallett 	char *response;
712305e39f4SJuli Mallett 	FILE *ttyfp;
713305e39f4SJuli Mallett 
714305e39f4SJuli Mallett 	if ((ttyfp = fopen(_PATH_TTY, "r")) == NULL)
715305e39f4SJuli Mallett 		return (2);	/* Indicate that the TTY failed to open. */
716305e39f4SJuli Mallett 	(void)fprintf(stderr, "?...");
717305e39f4SJuli Mallett 	(void)fflush(stderr);
718305e39f4SJuli Mallett 	if ((response = fgetln(ttyfp, &rsize)) == NULL ||
71930aaff11SWarner Losh 	    regcomp(&cre, nl_langinfo(YESEXPR), REG_BASIC) != 0) {
720305e39f4SJuli Mallett 		(void)fclose(ttyfp);
721305e39f4SJuli Mallett 		return (0);
722305e39f4SJuli Mallett 	}
723b65bc267SJuli Mallett 	response[rsize - 1] = '\0';
724305e39f4SJuli Mallett 	match = regexec(&cre, response, 0, NULL, 0);
725305e39f4SJuli Mallett 	(void)fclose(ttyfp);
726305e39f4SJuli Mallett 	regfree(&cre);
727305e39f4SJuli Mallett 	return (match == 0);
728305e39f4SJuli Mallett }
729305e39f4SJuli Mallett 
730a51024e2SPhilippe Charnier static void
73173385ac6SJuli Mallett usage(void)
7329b50d902SRodney W. Grimes {
7338d904f15SDima Dorfman 	fprintf(stderr,
734ba084f6aSJuli Mallett "usage: xargs [-0opt] [-E eofstr] [-I replstr [-R replacements] [-S replsize]]\n"
735ba084f6aSJuli Mallett "             [-J replstr] [-L number] [-n number [-x]] [-P maxprocs]\n"
736ba084f6aSJuli Mallett "             [-s size] [utility [argument ...]]\n");
7379b50d902SRodney W. Grimes 	exit(1);
7389b50d902SRodney W. Grimes }
739