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 * 4. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * $xMach: xargs.c,v 1.6 2002/02/23 05:27:47 tim Exp $
37 static const char copyright[] =
38 "@(#) Copyright (c) 1990, 1993\n\
39 The Regents of the University of California. All rights reserved.\n";
43 static char sccsid[] = "@(#)xargs.c 8.1 (Berkeley) 6/6/93";
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
49 #include <sys/types.h>
52 #include <sys/limits.h>
53 #include <sys/resource.h>
66 #include "pathnames.h"
68 static void parse_input(int, char *[]);
69 static void prerun(int, char *[]);
70 static int prompt(void);
71 static void run(char **);
72 static void usage(void);
73 void strnsubst(char **, const char *, const char *, size_t);
74 static pid_t xwait(int block, int *status);
75 static void xexit(const char *, const int);
76 static void waitchildren(const char *, int);
77 static void pids_init(void);
78 static int pids_empty(void);
79 static int pids_full(void);
80 static void pids_add(pid_t pid);
81 static int pids_remove(pid_t pid);
82 static int findslot(pid_t pid);
83 static int findfreeslot(void);
84 static void clearslot(int slot);
86 static char echo[] = _PATH_ECHO;
87 static char **av, **bxp, **ep, **endxp, **xp;
88 static char *argp, *bbp, *ebp, *inpline, *p, *replstr;
89 static const char *eofstr;
90 static int count, insingle, indouble, oflag, pflag, tflag, Rflag, rval, zflag;
91 static int cnt, Iflag, jfound, Lflag, Sflag, wasquoted, xflag;
92 static int curprocs, maxprocs;
93 static pid_t *childpids;
95 static volatile int childerr;
97 extern char **environ;
100 main(int argc, char *argv[])
103 int ch, Jflag, nargs, nflag, nline;
109 inpline = replstr = NULL;
114 (void)setlocale(LC_ALL, "");
117 * POSIX.2 limits the exec line length to ARG_MAX - 2K. Running that
118 * caused some E2BIG errors, so it was changed to ARG_MAX - 4K. Given
119 * that the smallest argument is 2 bytes in length, this means that
120 * the number of arguments is limited to:
122 * (ARG_MAX - 4K - LENGTH(utility + arguments)) / 2.
124 * We arbitrarily limit the number of arguments to 5000. This is
125 * allowed by POSIX.2 as long as the resulting minimum exec line is
126 * at least LINE_MAX. Realloc'ing as necessary is possible, but
127 * probably not worthwhile.
130 if ((arg_max = sysconf(_SC_ARG_MAX)) == -1)
131 errx(1, "sysconf(_SC_ARG_MAX) failed");
132 nline = arg_max - 4 * 1024;
133 while (*ep != NULL) {
134 /* 1 byte for each '\0' */
135 nline -= strlen(*ep++) + 1 + sizeof(*ep);
138 while ((ch = getopt(argc, argv, "0E:I:J:L:n:oP:pR:S:s:rtx")) != -1)
155 Lflag = strtonum(optarg, 0, INT_MAX, &errstr);
157 errx(1, "-L %s: %s", optarg, errstr);
161 nargs = strtonum(optarg, 1, INT_MAX, &errstr);
163 errx(1, "-n %s: %s", optarg, errstr);
169 maxprocs = strtonum(optarg, 0, INT_MAX, &errstr);
171 errx(1, "-P %s: %s", optarg, errstr);
172 if (getrlimit(RLIMIT_NPROC, &rl) != 0)
173 errx(1, "getrlimit failed");
174 if (maxprocs == 0 || maxprocs > rl.rlim_cur)
175 maxprocs = rl.rlim_cur;
181 Rflag = strtol(optarg, &endptr, 10);
183 errx(1, "replacements must be a number");
186 /* GNU compatibility */
189 Sflag = strtoul(optarg, &endptr, 10);
191 errx(1, "replsize must be a number");
194 nline = strtonum(optarg, 0, INT_MAX, &errstr);
196 errx(1, "-s %s: %s", optarg, errstr);
226 if (replstr != NULL && *replstr == '\0')
227 errx(1, "replstr may not be empty");
232 * Allocate pointers for the utility name, the utility arguments,
233 * the maximum arguments to be read from stdin and the trailing
236 linelen = 1 + argc + nargs + 1;
237 if ((av = bxp = malloc(linelen * sizeof(char **))) == NULL)
238 errx(1, "malloc failed");
241 * Use the user's name for the utility as argv[0], just like the
242 * shell. Echo is the default. Set up pointers for the user's
246 cnt = strlen(*bxp++ = echo);
249 if (Jflag && strcmp(*argv, replstr) == 0) {
253 for (avj = argv; *avj; avj++)
254 cnt += strlen(*avj) + 1;
257 cnt += strlen(*bxp++ = *argv) + 1;
258 } while (*++argv != NULL);
262 * Set up begin/end/traversing pointers into the array. The -n
263 * count doesn't include the trailing NULL pointer, so the malloc
264 * added in an extra slot.
266 endxp = (xp = bxp) + nargs;
269 * Allocate buffer space for the arguments read from stdin and the
270 * trailing NULL. Buffer space is defined as the default or specified
271 * space, minus the length of the utility name and arguments. Set up
272 * begin/end/traversing pointers into the array. The -s count does
273 * include the trailing NULL, so the malloc didn't add in an extra
278 errx(1, "insufficient space for command");
280 if ((bbp = malloc((size_t)(nline + 1))) == NULL)
281 errx(1, "malloc failed");
282 ebp = (argp = p = bbp) + nline - 1;
284 parse_input(argc, argv);
288 parse_input(int argc, char *argv[])
295 switch (ch = getchar()) {
297 /* No arguments since last exec. */
303 /* Quotes escape tabs and spaces. */
304 if (insingle || indouble || zflag)
310 * Increment 'count', so that nulls will be treated
311 * as end-of-line, as well as end-of-argument. This
312 * is needed so -0 works properly with -I and -L.
321 count++; /* Indicate end-of-line (used by -L) */
323 /* Quotes do not escape newlines. */
324 arg1: if (insingle || indouble) {
325 warnx("unterminated quote");
329 foundeof = *eofstr != '\0' &&
330 strncmp(argp, eofstr, p - argp) == 0;
332 /* Do not make empty args unless they are quoted */
333 if ((argp != p || wasquoted) && !foundeof) {
343 * If this string is not zero
344 * length, append a space for
345 * separation before the next
348 if ((curlen = strlen(inpline)))
349 strcat(inpline, " ");
353 * Allocate enough to hold what we will
354 * be holding in a second, and to append
355 * a space next time through, if we have
358 inpline = realloc(inpline, curlen + 2 +
360 if (inpline == NULL) {
361 warnx("realloc failed");
365 strcpy(inpline, argp);
367 strcat(inpline, argp);
372 * If max'd out on args or buffer, or reached EOF,
373 * run the command. If xflag and max'd out on buffer
374 * but not on args, object. Having reached the limit
375 * of input lines, as specified by -L is the same as
376 * maxing out on arguments.
378 if (xp == endxp || p > ebp || ch == EOF ||
379 (Lflag <= count && xflag) || foundeof) {
380 if (xflag && xp != endxp && p > ebp) {
381 warnx("insufficient space for arguments");
385 for (avj = argv; *avj; avj++)
389 if (ch == EOF || foundeof)
399 if (indouble || zflag)
401 insingle = !insingle;
405 if (insingle || zflag)
407 indouble = !indouble;
413 /* Backslash escapes anything, is escaped by quotes. */
414 if (!insingle && !indouble && (ch = getchar()) == EOF) {
415 warnx("backslash at EOF");
420 addch: if (p < ebp) {
425 /* If only one argument, not enough buffer space. */
427 warnx("insufficient space for argument");
430 /* Didn't hit argument limit, so if xflag object. */
432 warnx("insufficient space for arguments");
437 for (avj = argv; *avj; avj++)
443 memcpy(bbp, argp, (size_t)cnt);
444 p = (argp = bbp) + cnt;
451 * Do things necessary before run()'ing, such as -I substitution,
452 * and then call run().
455 prerun(int argc, char *argv[])
457 char **tmp, **tmp2, **avj;
462 if (argc == 0 || repls == 0) {
471 * Allocate memory to hold the argument list, and
472 * a NULL at the tail.
474 tmp = malloc((argc + 1) * sizeof(char**));
476 warnx("malloc failed");
482 * Save the first argument and iterate over it, we
483 * cannot do strnsubst() to it.
485 if ((*tmp++ = strdup(*avj++)) == NULL) {
486 warnx("strdup failed");
491 * For each argument to utility, if we have not used up
492 * the number of replacements we are allowed to do, and
493 * if the argument contains at least one occurrence of
494 * replstr, call strnsubst(), else just save the string.
495 * Iterations over elements of avj and tmp are done
500 if (repls && strstr(*tmp, replstr) != NULL) {
501 strnsubst(tmp++, replstr, inpline, (size_t)Sflag);
505 if ((*tmp = strdup(*tmp)) == NULL) {
506 warnx("strdup failed");
520 * Walk from the tail to the head, free along the way.
522 for (; tmp2 != tmp; tmp--)
525 * Now free the list itself.
530 * Free the input line buffer, if we have one.
532 if (inpline != NULL) {
546 * If the user wants to be notified of each command before it is
547 * executed, notify them. If they want the notification to be
548 * followed by a prompt, then prompt them.
550 if (tflag || pflag) {
551 (void)fprintf(stderr, "%s", *argv);
552 for (avec = argv + 1; *avec != NULL; ++avec)
553 (void)fprintf(stderr, " %s", *avec);
555 * If the user has asked to be prompted, do so.
559 * If they asked not to exec, return without execution
560 * but if they asked to, go to the execution. If we
561 * could not open their tty, break the switch and drop
562 * back to -t behaviour.
572 (void)fprintf(stderr, "\n");
573 (void)fflush(stderr);
577 switch (pid = vfork()) {
583 if ((fd = open(_PATH_TTY, O_RDONLY)) == -1)
584 err(1, "can't open /dev/tty");
586 fd = open(_PATH_DEVNULL, O_RDONLY);
588 if (fd > STDIN_FILENO) {
589 if (dup2(fd, STDIN_FILENO) != 0)
590 err(1, "can't dup2 to stdin");
593 execvp(argv[0], argv);
598 waitchildren(*argv, 0);
602 * Wait for a tracked child to exit and return its pid and exit status.
604 * Ignores (discards) all untracked child processes.
605 * Returns -1 and sets errno to ECHILD if no tracked children exist.
606 * If block is set, waits indefinitely for a child process to exit.
607 * If block is not set and no children have exited, returns 0 immediately.
610 xwait(int block, int *status) {
618 while ((pid = waitpid(-1, status, block ? 0 : WNOHANG)) > 0)
619 if (pids_remove(pid))
626 xexit(const char *name, const int exit_code) {
627 waitchildren(name, 1);
632 waitchildren(const char *name, int waitall)
638 while ((pid = xwait(waitall || pids_full(), &status)) > 0) {
640 * If we couldn't invoke the utility or if utility exited
641 * because of a signal or with a value of 255, warn (per
642 * POSIX), and then wait until all other children have
643 * exited before exiting 1-125. POSIX requires us to stop
644 * reading if child exits because of a signal or with 255,
645 * but it does not require us to exit immediately; waiting
646 * is preferable to orphaning.
648 if (childerr != 0 && cause_exit == 0) {
651 cause_exit = ENOENT ? 127 : 126;
653 } else if (WIFSIGNALED(status)) {
654 waitall = cause_exit = 1;
655 warnx("%s: terminated with signal %d; aborting",
656 name, WTERMSIG(status));
657 } else if (WEXITSTATUS(status) == 255) {
658 waitall = cause_exit = 1;
659 warnx("%s: exited with status 255; aborting", name);
660 } else if (WEXITSTATUS(status))
666 if (pid == -1 && errno != ECHILD)
677 if ((childpids = malloc(maxprocs * sizeof(*childpids))) == NULL)
678 errx(1, "malloc failed");
680 for (i = 0; i < maxprocs; i++)
688 return (curprocs == 0);
695 return (curprocs >= maxprocs);
703 slot = findfreeslot();
704 childpids[slot] = pid;
709 pids_remove(pid_t pid)
713 if ((slot = findslot(pid)) < 0)
726 if ((slot = findslot(NOPID)) < 0)
727 errx(1, "internal error: no free pid slot");
736 for (slot = 0; slot < maxprocs; slot++)
737 if (childpids[slot] == pid)
746 childpids[slot] = NOPID;
750 * Prompt the user about running a command.
761 if ((ttyfp = fopen(_PATH_TTY, "r")) == NULL)
762 return (2); /* Indicate that the TTY failed to open. */
763 (void)fprintf(stderr, "?...");
764 (void)fflush(stderr);
765 if ((response = fgetln(ttyfp, &rsize)) == NULL ||
766 regcomp(&cre, nl_langinfo(YESEXPR), REG_BASIC) != 0) {
770 response[rsize - 1] = '\0';
771 match = regexec(&cre, response, 0, NULL, 0);
782 "usage: xargs [-0opt] [-E eofstr] [-I replstr [-R replacements] [-S replsize]]\n"
783 " [-J replstr] [-L number] [-n number [-x]] [-P maxprocs]\n"
784 " [-s size] [utility [argument ...]]\n");