xref: /netbsd-src/usr.bin/xargs/xargs.c (revision ce63d6c20fc4ec8ddc95c84bb229e3c4ecf82b69)
1 /*-
2  * Copyright (c) 1990 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * John B. Roll Jr.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #ifndef lint
38 char copyright[] =
39 "@(#) Copyright (c) 1990 The Regents of the University of California.\n\
40  All rights reserved.\n";
41 #endif /* not lint */
42 
43 #ifndef lint
44 static char sccsid[] = "@(#)xargs.c	5.11 (Berkeley) 6/19/91";
45 #endif /* not lint */
46 
47 #include <sys/types.h>
48 #include <sys/wait.h>
49 #include <errno.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
54 #include <limits.h>
55 #include "pathnames.h"
56 
57 int fflag, tflag;
58 void err __P((const char *, ...));
59 void run(), usage();
60 
61 main(argc, argv)
62 	int argc;
63 	char **argv;
64 {
65 	extern int optind;
66 	extern char *optarg;
67 	register int ch;
68 	register char *p, *bbp, *ebp, **bxp, **exp, **xp;
69 	int cnt, indouble, insingle, nargs, nflag, nline, xflag;
70 	char **av, *argp;
71 
72 	/*
73 	 * POSIX.2 limits the exec line length to ARG_MAX - 2K.  Running that
74 	 * caused some E2BIG errors, so it was changed to ARG_MAX - 4K.  Given
75 	 * that the smallest argument is 2 bytes in length, this means that
76 	 * the number of arguments is limited to:
77 	 *
78 	 *	 (ARG_MAX - 4K - LENGTH(utility + arguments)) / 2.
79 	 *
80 	 * We arbitrarily limit the number of arguments to 5000.  This is
81 	 * allowed by POSIX.2 as long as the resulting minimum exec line is
82 	 * at least LINE_MAX.  Realloc'ing as necessary is possible, but
83 	 * probably not worthwhile.
84 	 */
85 	nargs = 5000;
86 	nline = ARG_MAX - 4 * 1024;
87 	nflag = xflag = 0;
88 	while ((ch = getopt(argc, argv, "fn:s:tx")) != EOF)
89 		switch(ch) {
90 		case 'f':
91 			fflag = 1;
92 			break;
93 		case 'n':
94 			nflag = 1;
95 			if ((nargs = atoi(optarg)) <= 0)
96 				err("illegal argument count");
97 			break;
98 		case 's':
99 			nline = atoi(optarg);
100 			break;
101 		case 't':
102 			tflag = 1;
103 			break;
104 		case 'x':
105 			xflag = 1;
106 			break;
107 		case '?':
108 		default:
109 			usage();
110 	}
111 	argc -= optind;
112 	argv += optind;
113 
114 	if (xflag && !nflag)
115 		usage();
116 
117 	/*
118 	 * Allocate pointers for the utility name, the utility arguments,
119 	 * the maximum arguments to be read from stdin and the trailing
120 	 * NULL.
121 	 */
122 	if (!(av = bxp =
123 	    malloc((u_int)(1 + argc + nargs + 1) * sizeof(char **))))
124 		err("%s", strerror(errno));
125 
126 	/*
127 	 * Use the user's name for the utility as argv[0], just like the
128 	 * shell.  Echo is the default.  Set up pointers for the user's
129 	 * arguments.
130 	 */
131 	if (!*argv)
132 		cnt = strlen(*bxp++ = _PATH_ECHO);
133 	else {
134 		cnt = 0;
135 		do {
136 			cnt += strlen(*bxp++ = *argv) + 1;
137 		} while (*++argv);
138 	}
139 
140 	/*
141 	 * Set up begin/end/traversing pointers into the array.  The -n
142 	 * count doesn't include the trailing NULL pointer, so the malloc
143 	 * added in an extra slot.
144 	 */
145 	exp = (xp = bxp) + nargs;
146 
147 	/*
148 	 * Allocate buffer space for the arguments read from stdin and the
149 	 * trailing NULL.  Buffer space is defined as the default or specified
150 	 * space, minus the length of the utility name and arguments.  Set up
151 	 * begin/end/traversing pointers into the array.  The -s count does
152 	 * include the trailing NULL, so the malloc didn't add in an extra
153 	 * slot.
154 	 */
155 	nline -= cnt;
156 	if (nline <= 0)
157 		err("insufficient space for command");
158 
159 	if (!(bbp = malloc((u_int)nline + 1)))
160 		err("%s", strerror(errno));
161 	ebp = (argp = p = bbp) + nline - 1;
162 
163 	for (insingle = indouble = 0;;)
164 		switch(ch = getchar()) {
165 		case EOF:
166 			/* No arguments since last exec. */
167 			if (p == bbp)
168 				exit(0);
169 
170 			/* Nothing since end of last argument. */
171 			if (argp == p) {
172 				*xp = NULL;
173 				run(av);
174 				exit(0);
175 			}
176 			goto arg1;
177 		case ' ':
178 		case '\t':
179 			/* Quotes escape tabs and spaces. */
180 			if (insingle || indouble)
181 				goto addch;
182 			goto arg2;
183 		case '\n':
184 			/* Empty lines are skipped. */
185 			if (argp == p)
186 				continue;
187 
188 			/* Quotes do not escape newlines. */
189 arg1:			if (insingle || indouble)
190 				 err("unterminated quote");
191 
192 arg2:			*p = '\0';
193 			*xp++ = argp;
194 
195 			/*
196 			 * If max'd out on args or buffer, or reached EOF,
197 			 * run the command.  If xflag and max'd out on buffer
198 			 * but not on args, object.
199 			 */
200 			if (xp == exp || p == ebp || ch == EOF) {
201 				if (xflag && xp != exp && p == ebp)
202 					err("insufficient space for arguments");
203 				*xp = NULL;
204 				run(av);
205 				if (ch == EOF)
206 					exit(0);
207 				p = bbp;
208 				xp = bxp;
209 			} else
210 				++p;
211 			argp = p;
212 			break;
213 		case '\'':
214 			if (indouble)
215 				goto addch;
216 			insingle = !insingle;
217 			break;
218 		case '"':
219 			if (insingle)
220 				goto addch;
221 			indouble = !indouble;
222 			break;
223 		case '\\':
224 			/* Backslash escapes anything, is escaped by quotes. */
225 			if (!insingle && !indouble && (ch = getchar()) == EOF)
226 				err("backslash at EOF");
227 			/* FALLTHROUGH */
228 		default:
229 addch:			if (p < ebp) {
230 				*p++ = ch;
231 				break;
232 			}
233 
234 			/* If only one argument, not enough buffer space. */
235 			if (bxp == xp)
236 				err("insufficient space for argument");
237 			/* Didn't hit argument limit, so if xflag object. */
238 			if (xflag)
239 				err("insufficient space for arguments");
240 
241 			*xp = NULL;
242 			run(av);
243 			xp = bxp;
244 			cnt = ebp - argp;
245 			bcopy(argp, bbp, cnt);
246 			p = (argp = bbp) + cnt;
247 			*p++ = ch;
248 			break;
249 		}
250 	/* NOTREACHED */
251 }
252 
253 void
254 run(argv)
255 	char **argv;
256 {
257 	register char **p;
258 	pid_t pid;
259 	volatile int noinvoke;
260 	int status;
261 
262 	if (tflag) {
263 		(void)fprintf(stderr, "%s", *argv);
264 		for (p = argv + 1; *p; ++p)
265 			(void)fprintf(stderr, " %s", *p);
266 		(void)fprintf(stderr, "\n");
267 		(void)fflush(stderr);
268 	}
269 	noinvoke = 0;
270 	switch(pid = vfork()) {
271 	case -1:
272 		err("vfork: %s", strerror(errno));
273 	case 0:
274 		execvp(argv[0], argv);
275 		(void)fprintf(stderr,
276 		    "xargs: %s: %s.\n", argv[0], strerror(errno));
277 		noinvoke = 1;
278 		_exit(1);
279 	}
280 	pid = waitpid(pid, &status, 0);
281 	if (pid == -1)
282 		err("waitpid: %s", strerror(errno));
283 	/*
284 	 * If we couldn't invoke the utility or the utility didn't exit
285 	 * properly, quit with 127.
286 	 * Otherwise, if not specified otherwise, and the utility exits
287 	 * non-zero, exit with that value.
288 	 */
289 	if (noinvoke || !WIFEXITED(status) || WIFSIGNALED(status))
290 		exit(127);
291 	if (!fflag && WEXITSTATUS(status))
292 		exit(WEXITSTATUS(status));
293 }
294 
295 void
296 usage()
297 {
298 	(void)fprintf(stderr,
299 "usage: xargs [-ft] [[-x] -n number] [-s size] [utility [argument ...]]\n");
300 	exit(1);
301 }
302 
303 #if __STDC__
304 #include <stdarg.h>
305 #else
306 #include <varargs.h>
307 #endif
308 
309 void
310 #if __STDC__
311 err(const char *fmt, ...)
312 #else
313 err(fmt, va_alist)
314 	char *fmt;
315         va_dcl
316 #endif
317 {
318 	va_list ap;
319 #if __STDC__
320 	va_start(ap, fmt);
321 #else
322 	va_start(ap);
323 #endif
324 	(void)fprintf(stderr, "xargs: ");
325 	(void)vfprintf(stderr, fmt, ap);
326 	va_end(ap);
327 	(void)fprintf(stderr, "\n");
328 	exit(1);
329 	/* NOTREACHED */
330 }
331