xref: /netbsd-src/usr.bin/xargs/xargs.c (revision 5f7096188587a2c7c95fa3c69b78e1ec9c7923d0)
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[] = "from: @(#)xargs.c	5.11 (Berkeley) 6/19/91";*/
45 static char rcsid[] = "$Id: xargs.c,v 1.5 1993/08/27 22:31:12 jtc Exp $";
46 #endif /* not lint */
47 
48 #include <sys/types.h>
49 #include <sys/wait.h>
50 #include <errno.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <unistd.h>
55 #include <limits.h>
56 #include "pathnames.h"
57 
58 int exit_status = 0;
59 int tflag;
60 void err __P((const char *, ...));
61 void run(), usage();
62 
63 int
64 main(argc, argv)
65 	int argc;
66 	char **argv;
67 {
68 	extern int optind;
69 	extern char *optarg;
70 	register int ch;
71 	register char *p, *bbp, *ebp, **bxp, **exp, **xp;
72 	int cnt, indouble, insingle, nargs, nflag, nline, xflag;
73 	char **av, *argp;
74 
75 	/*
76 	 * POSIX.2 limits the exec line length to ARG_MAX - 2K.  Running that
77 	 * caused some E2BIG errors, so it was changed to ARG_MAX - 4K.  Given
78 	 * that the smallest argument is 2 bytes in length, this means that
79 	 * the number of arguments is limited to:
80 	 *
81 	 *	 (ARG_MAX - 4K - LENGTH(utility + arguments)) / 2.
82 	 *
83 	 * We arbitrarily limit the number of arguments to 5000.  This is
84 	 * allowed by POSIX.2 as long as the resulting minimum exec line is
85 	 * at least LINE_MAX.  Realloc'ing as necessary is possible, but
86 	 * probably not worthwhile.
87 	 */
88 	nargs = 5000;
89 	nline = ARG_MAX - 4 * 1024;
90 	nflag = xflag = 0;
91 	while ((ch = getopt(argc, argv, "n:s:tx")) != EOF)
92 		switch(ch) {
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(exit_status);
169 
170 			/* Nothing since end of last argument. */
171 			if (argp == p) {
172 				*xp = NULL;
173 				run(av);
174 				exit(exit_status);
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(exit_status);
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 		noinvoke = (errno == ENOENT) ? 127 : 126;
276 		(void)fprintf(stderr,
277 		    "xargs: %s: %s.\n", argv[0], strerror(errno));
278 		_exit(1);
279 	}
280 	pid = waitpid(pid, &status, 0);
281 	if (pid == -1)
282 		err("waitpid: %s", strerror(errno));
283 
284 	/*
285 	 * If we couldn't invoke the utility or the utility didn't exit
286 	 * properly, quit with 127 or 126 respectively.
287 	 */
288 	if (noinvoke)
289 		exit(noinvoke);
290 
291 	/*
292 	 * According to POSIX, we have to exit if the utility exits with
293 	 * a 255 status, or is interrupted by a signal.   xargs is allowed
294 	 * to return any exit status between 1 and 125 in these cases, but
295 	 * we'll use 124 and 125, the same values used by GNU xargs.
296 	 */
297 	if (WIFEXITED(status)) {
298 		if (WEXITSTATUS (status) == 255) {
299 			fprintf (stderr, "xargs: %s exited with status 255\n",
300 				 argv[0]);
301 			exit(124);
302 		} else if (WEXITSTATUS (status) != 0) {
303 			exit_status = 123;
304 		}
305 	} else if (WIFSTOPPED (status)) {
306 		fprintf (stderr, "xargs: %s terminated by signal %d\n",
307 			 argv[0], WSTOPSIG (status));
308 		exit(125);
309 	} else if (WIFSIGNALED (status)) {
310 		fprintf (stderr, "xargs: %s terminated by signal %d\n",
311 			 argv[0], WTERMSIG (status));
312 		exit(125);
313 	}
314 }
315 
316 void
317 usage()
318 {
319 	(void)fprintf(stderr,
320 "usage: xargs [-t] [[-x] -n number] [-s size] [utility [argument ...]]\n");
321 	exit(1);
322 }
323 
324 #if __STDC__
325 #include <stdarg.h>
326 #else
327 #include <varargs.h>
328 #endif
329 
330 void
331 #if __STDC__
332 err(const char *fmt, ...)
333 #else
334 err(fmt, va_alist)
335 	char *fmt;
336         va_dcl
337 #endif
338 {
339 	va_list ap;
340 #if __STDC__
341 	va_start(ap, fmt);
342 #else
343 	va_start(ap);
344 #endif
345 	(void)fprintf(stderr, "xargs: ");
346 	(void)vfprintf(stderr, fmt, ap);
347 	va_end(ap);
348 	(void)fprintf(stderr, "\n");
349 	exit(1);
350 	/* NOTREACHED */
351 }
352