2 * Copyright (c) 1990, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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.
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
36 * $xMach: xargs.c,v 1.6 2002/02/23 05:27:47 tim Exp $
38 * @(#) Copyright (c) 1990, 1993 The Regents of the University of California. All rights reserved.
39 * @(#)xargs.c 8.1 (Berkeley) 6/6/93
40 * $FreeBSD: src/usr.bin/xargs/xargs.c,v 1.9.2.6 2003/06/01 21:40:35 mux Exp $
43 #include <sys/types.h>
60 #include "pathnames.h"
62 static void parse_input(int, char *[]);
63 static void prerun(int, char *[]);
64 static int prompt(void);
65 static void run(char **);
66 static void usage(void);
67 void strnsubst(char **, const char *, const char *, size_t);
68 static void waitchildren(const char *, int);
70 static char echo[] = _PATH_ECHO;
71 static char **av, **bxp, **ep, **expx, **xp;
72 static char *argp, *bbp, *ebp, *inpline, *p, *replstr;
73 static const char *eofstr;
74 static int count, insingle, indouble, oflag, pflag, tflag, Rflag, rval, zflag;
75 static int cnt, Iflag, jfound, Lflag, wasquoted, xflag;
76 static int curprocs, maxprocs;
77 static volatile int childerr;
79 extern char **environ;
82 main(int argc, char *argv[])
86 int ch, Jflag, nargs, nflag, nline;
89 inpline = replstr = NULL;
94 (void)setlocale(LC_MESSAGES, "");
97 * POSIX.2 limits the exec line length to ARG_MAX - 2K. Running that
98 * caused some E2BIG errors, so it was changed to ARG_MAX - 4K. Given
99 * that the smallest argument is 2 bytes in length, this means that
100 * the number of arguments is limited to:
102 * (ARG_MAX - 4K - LENGTH(utility + arguments)) / 2.
104 * We arbitrarily limit the number of arguments to 5000. This is
105 * allowed by POSIX.2 as long as the resulting minimum exec line is
106 * at least LINE_MAX. Realloc'ing as necessary is possible, but
107 * probably not worthwhile.
110 if ((arg_max = sysconf(_SC_ARG_MAX)) == -1)
111 errx(1, "sysconf(_SC_ARG_MAX) failed");
112 nline = arg_max - 4 * 1024;
113 while (*ep != NULL) {
114 /* 1 byte for each '\0' */
115 nline -= strlen(*ep++) + 1 + sizeof(*ep);
119 while ((ch = getopt(argc, argv, "0E:I:J:L:n:opP:R:s:tx")) != -1)
136 Lflag = strtol(optarg, &tmp, 10);
137 if (*tmp != 0 || *optarg == 0)
138 errx(1, "illegal argument count");
142 if ((nargs = atoi(optarg)) <= 0)
143 errx(1, "illegal argument count");
152 if ((maxprocs = atoi(optarg)) <= 0)
153 errx(1, "max.processes must be >0");
156 if ((Rflag = atoi(optarg)) <= 0)
157 errx(1, "illegal number of replacements");
160 nline = atoi(optarg);
186 if (replstr != NULL && *replstr == '\0')
187 errx(1, "replstr may not be empty");
190 * Allocate pointers for the utility name, the utility arguments,
191 * the maximum arguments to be read from stdin and the trailing
194 linelen = 1 + argc + nargs + 1;
195 if ((av = bxp = malloc(linelen * sizeof(char **))) == NULL)
196 errx(1, "malloc failed");
199 * Use the user's name for the utility as argv[0], just like the
200 * shell. Echo is the default. Set up pointers for the user's
204 cnt = strlen(*bxp++ = echo);
207 if (Jflag && strcmp(*argv, replstr) == 0) {
211 for (avj = argv; *avj; avj++)
212 cnt += strlen(*avj) + 1;
215 cnt += strlen(*bxp++ = *argv) + 1;
216 } while (*++argv != NULL);
220 * Set up begin/end/traversing pointers into the array. The -n
221 * count doesn't include the trailing NULL pointer, so the malloc
222 * added in an extra slot.
224 expx = (xp = bxp) + nargs;
227 * Allocate buffer space for the arguments read from stdin and the
228 * trailing NULL. Buffer space is defined as the default or specified
229 * space, minus the length of the utility name and arguments. Set up
230 * begin/end/traversing pointers into the array. The -s count does
231 * include the trailing NULL, so the malloc didn't add in an extra
236 errx(1, "insufficient space for command");
238 if ((bbp = malloc((size_t)(nline + 1))) == NULL)
239 errx(1, "malloc failed");
240 ebp = (argp = p = bbp) + nline - 1;
242 parse_input(argc, argv);
246 parse_input(int argc, char *argv[])
253 switch(ch = getchar()) {
255 /* No arguments since last exec. */
257 waitchildren(*argv, 1);
263 /* Quotes escape tabs and spaces. */
264 if (insingle || indouble || zflag)
276 /* Quotes do not escape newlines. */
277 arg1: if (insingle || indouble)
278 errx(1, "unterminated quote");
280 foundeof = *eofstr != '\0' &&
281 strcmp(argp, eofstr) == 0;
283 /* Do not make empty args unless they are quoted */
284 if ((argp != p || wasquoted) && !foundeof) {
294 * If this string is not zero
295 * length, append a space for
296 * separation before the next
299 if ((curlen = strlen(inpline)))
300 strcat(inpline, " ");
304 * Allocate enough to hold what we will
305 * be holding in a second, and to append
306 * a space next time through, if we have
309 inpline = realloc(inpline, curlen + 2 +
312 errx(1, "realloc failed");
314 strcpy(inpline, argp);
316 strcat(inpline, argp);
321 * If max'd out on args or buffer, or reached EOF,
322 * run the command. If xflag and max'd out on buffer
323 * but not on args, object. Having reached the limit
324 * of input lines, as specified by -L is the same as
325 * maxing out on arguments.
327 if (xp == expx || p > ebp || ch == EOF ||
328 (Lflag <= count && xflag) || foundeof) {
329 if (xflag && xp != expx && p > ebp)
330 errx(1, "insufficient space for arguments");
332 for (avj = argv; *avj; avj++)
336 if (ch == EOF || foundeof) {
337 waitchildren(*argv, 1);
348 if (indouble || zflag)
350 insingle = !insingle;
354 if (insingle || zflag)
356 indouble = !indouble;
362 /* Backslash escapes anything, is escaped by quotes. */
363 if (!insingle && !indouble && (ch = getchar()) == EOF)
364 errx(1, "backslash at EOF");
367 addch: if (p < ebp) {
372 /* If only one argument, not enough buffer space. */
374 errx(1, "insufficient space for argument");
375 /* Didn't hit argument limit, so if xflag object. */
377 errx(1, "insufficient space for arguments");
380 for (avj = argv; *avj; avj++)
386 memcpy(bbp, argp, (size_t)cnt);
387 p = (argp = bbp) + cnt;
395 * Do things necessary before run()'ing, such as -I substitution,
396 * and then call run().
399 prerun(int argc, char *argv[])
401 char **tmp, **tmp2, **avj;
406 if (argc == 0 || repls == 0) {
415 * Allocate memory to hold the argument list, and
416 * a NULL at the tail.
418 tmp = malloc((argc + 1) * sizeof(char**));
420 errx(1, "malloc failed");
424 * Save the first argument and iterate over it, we
425 * cannot do strnsubst() to it.
427 if ((*tmp++ = strdup(*avj++)) == NULL)
428 errx(1, "strdup failed");
431 * For each argument to utility, if we have not used up
432 * the number of replacements we are allowed to do, and
433 * if the argument contains at least one occurrence of
434 * replstr, call strnsubst(), else just save the string.
435 * Iterations over elements of avj and tmp are done
440 if (repls && strstr(*tmp, replstr) != NULL) {
441 strnsubst(tmp++, replstr, inpline, (size_t)255);
444 if ((*tmp = strdup(*tmp)) == NULL)
445 errx(1, "strdup failed");
457 * Walk from the tail to the head, free along the way.
459 for (; tmp2 != tmp; tmp--)
462 * Now free the list itself.
467 * Free the input line buffer, if we have one.
469 if (inpline != NULL) {
482 * If the user wants to be notified of each command before it is
483 * executed, notify them. If they want the notification to be
484 * followed by a prompt, then prompt them.
486 if (tflag || pflag) {
487 (void)fprintf(stderr, "%s", *argv);
488 for (avec = argv + 1; *avec != NULL; ++avec)
489 (void)fprintf(stderr, " %s", *avec);
491 * If the user has asked to be prompted, do so.
495 * If they asked not to exec, return without execution
496 * but if they asked to, go to the execution. If we
497 * could not open their tty, break the switch and drop
498 * back to -t behaviour.
508 (void)fprintf(stderr, "\n");
509 (void)fflush(stderr);
513 switch(pid = vfork()) {
519 if (open("/dev/tty", O_RDONLY) == -1)
520 err(1, "open /dev/tty");
522 if (open("/dev/null", O_RDONLY) == -1)
523 err(1, "open /dev/null");
525 execvp(argv[0], argv);
530 waitchildren(*argv, 0);
534 * Handle child processes.
537 waitchildren(const char *name, int waitall)
542 while ((pid = wait3(&status, !waitall && curprocs < maxprocs ?
543 WNOHANG : 0, NULL)) > 0) {
546 /* If we couldn't invoke the utility, exit. */
549 err(errno == ENOENT ? 127 : 126, "%s", name);
553 * If utility signaled or exited with a value of 255,
556 if (WIFSIGNALED(status) || WEXITSTATUS(status) == 255)
558 if (WEXITSTATUS(status))
561 if (pid == -1 && errno != ECHILD)
566 * Prompt the user about running a command.
577 if ((ttyfp = fopen(_PATH_TTY, "r")) == NULL)
578 return (2); /* Indicate that the TTY failed to open. */
579 (void)fprintf(stderr, "?...");
580 (void)fflush(stderr);
581 if ((response = fgetln(ttyfp, &rsize)) == NULL ||
586 nl_langinfo(YESEXPR),
592 match = regexec(&cre, response, 0, NULL, 0);
602 "usage: xargs [-0opt] [-E eofstr] [-I replstr [-R replacements]] [-J replstr]\n"
603 " [-L number] [-n number [-x] [-P maxprocs] [-s size]\n"
604 " [utility [argument ...]]\n");