xref: /freebsd/usr.bin/xargs/xargs.c (revision afe61c15161c324a7af299a9b8457aba5afc92db)
1 /*-
2  * Copyright (c) 1990, 1993
3  *	The Regents of the University of California.  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 static char copyright[] =
39 "@(#) Copyright (c) 1990, 1993\n\
40 	The Regents of the University of California.  All rights reserved.\n";
41 #endif /* not lint */
42 
43 #ifndef lint
44 static char sccsid[] = "@(#)xargs.c	8.1 (Berkeley) 6/6/93";
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 tflag, rval;
58 
59 void err __P((const char *, ...));
60 void run __P((char **));
61 void usage __P((void));
62 
63 main(argc, argv)
64 	int argc;
65 	char **argv;
66 {
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, "n:s:tx")) != EOF)
89 		switch(ch) {
90 		case 'n':
91 			nflag = 1;
92 			if ((nargs = atoi(optarg)) <= 0)
93 				err("illegal argument count");
94 			break;
95 		case 's':
96 			nline = atoi(optarg);
97 			break;
98 		case 't':
99 			tflag = 1;
100 			break;
101 		case 'x':
102 			xflag = 1;
103 			break;
104 		case '?':
105 		default:
106 			usage();
107 	}
108 	argc -= optind;
109 	argv += optind;
110 
111 	if (xflag && !nflag)
112 		usage();
113 
114 	/*
115 	 * Allocate pointers for the utility name, the utility arguments,
116 	 * the maximum arguments to be read from stdin and the trailing
117 	 * NULL.
118 	 */
119 	if (!(av = bxp =
120 	    malloc((u_int)(1 + argc + nargs + 1) * sizeof(char **))))
121 		err("%s", strerror(errno));
122 
123 	/*
124 	 * Use the user's name for the utility as argv[0], just like the
125 	 * shell.  Echo is the default.  Set up pointers for the user's
126 	 * arguments.
127 	 */
128 	if (!*argv)
129 		cnt = strlen(*bxp++ = _PATH_ECHO);
130 	else {
131 		cnt = 0;
132 		do {
133 			cnt += strlen(*bxp++ = *argv) + 1;
134 		} while (*++argv);
135 	}
136 
137 	/*
138 	 * Set up begin/end/traversing pointers into the array.  The -n
139 	 * count doesn't include the trailing NULL pointer, so the malloc
140 	 * added in an extra slot.
141 	 */
142 	exp = (xp = bxp) + nargs;
143 
144 	/*
145 	 * Allocate buffer space for the arguments read from stdin and the
146 	 * trailing NULL.  Buffer space is defined as the default or specified
147 	 * space, minus the length of the utility name and arguments.  Set up
148 	 * begin/end/traversing pointers into the array.  The -s count does
149 	 * include the trailing NULL, so the malloc didn't add in an extra
150 	 * slot.
151 	 */
152 	nline -= cnt;
153 	if (nline <= 0)
154 		err("insufficient space for command");
155 
156 	if (!(bbp = malloc((u_int)nline + 1)))
157 		err("%s", strerror(errno));
158 	ebp = (argp = p = bbp) + nline - 1;
159 
160 	for (insingle = indouble = 0;;)
161 		switch(ch = getchar()) {
162 		case EOF:
163 			/* No arguments since last exec. */
164 			if (p == bbp)
165 				exit(rval);
166 
167 			/* Nothing since end of last argument. */
168 			if (argp == p) {
169 				*xp = NULL;
170 				run(av);
171 				exit(rval);
172 			}
173 			goto arg1;
174 		case ' ':
175 		case '\t':
176 			/* Quotes escape tabs and spaces. */
177 			if (insingle || indouble)
178 				goto addch;
179 			goto arg2;
180 		case '\n':
181 			/* Empty lines are skipped. */
182 			if (argp == p)
183 				continue;
184 
185 			/* Quotes do not escape newlines. */
186 arg1:			if (insingle || indouble)
187 				 err("unterminated quote");
188 
189 arg2:			*p = '\0';
190 			*xp++ = argp;
191 
192 			/*
193 			 * If max'd out on args or buffer, or reached EOF,
194 			 * run the command.  If xflag and max'd out on buffer
195 			 * but not on args, object.
196 			 */
197 			if (xp == exp || p == ebp || ch == EOF) {
198 				if (xflag && xp != exp && p == ebp)
199 					err("insufficient space for arguments");
200 				*xp = NULL;
201 				run(av);
202 				if (ch == EOF)
203 					exit(rval);
204 				p = bbp;
205 				xp = bxp;
206 			} else
207 				++p;
208 			argp = p;
209 			break;
210 		case '\'':
211 			if (indouble)
212 				goto addch;
213 			insingle = !insingle;
214 			break;
215 		case '"':
216 			if (insingle)
217 				goto addch;
218 			indouble = !indouble;
219 			break;
220 		case '\\':
221 			/* Backslash escapes anything, is escaped by quotes. */
222 			if (!insingle && !indouble && (ch = getchar()) == EOF)
223 				err("backslash at EOF");
224 			/* FALLTHROUGH */
225 		default:
226 addch:			if (p < ebp) {
227 				*p++ = ch;
228 				break;
229 			}
230 
231 			/* If only one argument, not enough buffer space. */
232 			if (bxp == xp)
233 				err("insufficient space for argument");
234 			/* Didn't hit argument limit, so if xflag object. */
235 			if (xflag)
236 				err("insufficient space for arguments");
237 
238 			*xp = NULL;
239 			run(av);
240 			xp = bxp;
241 			cnt = ebp - argp;
242 			bcopy(argp, bbp, cnt);
243 			p = (argp = bbp) + cnt;
244 			*p++ = ch;
245 			break;
246 		}
247 	/* NOTREACHED */
248 }
249 
250 void
251 run(argv)
252 	char **argv;
253 {
254 	volatile int noinvoke;
255 	register char **p;
256 	pid_t pid;
257 	int status;
258 
259 	if (tflag) {
260 		(void)fprintf(stderr, "%s", *argv);
261 		for (p = argv + 1; *p; ++p)
262 			(void)fprintf(stderr, " %s", *p);
263 		(void)fprintf(stderr, "\n");
264 		(void)fflush(stderr);
265 	}
266 	noinvoke = 0;
267 	switch(pid = vfork()) {
268 	case -1:
269 		err("vfork: %s", strerror(errno));
270 	case 0:
271 		execvp(argv[0], argv);
272 		(void)fprintf(stderr,
273 		    "xargs: %s: %s\n", argv[0], strerror(errno));
274 		noinvoke = 1;
275 		_exit(1);
276 	}
277 	pid = waitpid(pid, &status, 0);
278 	if (pid == -1)
279 		err("waitpid: %s", strerror(errno));
280 	/* If we couldn't invoke the utility, exit 127. */
281 	if (noinvoke)
282 		exit(127);
283 	/* If utility signaled or exited with a value of 255, exit 1-125. */
284 	if (WIFSIGNALED(status) || WEXITSTATUS(status) == 255)
285 		exit(1);
286 	if (WEXITSTATUS(status))
287 		rval = 1;
288 }
289 
290 void
291 usage()
292 {
293 	(void)fprintf(stderr,
294 "usage: xargs [-t] [-n number [-x]] [-s size] [utility [argument ...]]\n");
295 	exit(1);
296 }
297 
298 #if __STDC__
299 #include <stdarg.h>
300 #else
301 #include <varargs.h>
302 #endif
303 
304 void
305 #if __STDC__
306 err(const char *fmt, ...)
307 #else
308 err(fmt, va_alist)
309 	char *fmt;
310         va_dcl
311 #endif
312 {
313 	va_list ap;
314 #if __STDC__
315 	va_start(ap, fmt);
316 #else
317 	va_start(ap);
318 #endif
319 	(void)fprintf(stderr, "xargs: ");
320 	(void)vfprintf(stderr, fmt, ap);
321 	va_end(ap);
322 	(void)fprintf(stderr, "\n");
323 	exit(1);
324 	/* NOTREACHED */
325 }
326