2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1990, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * $xMach: xargs.c,v 1.6 2002/02/23 05:27:47 tim Exp $
39 static const char copyright[] =
40 "@(#) Copyright (c) 1990, 1993\n\
41 The Regents of the University of California. All rights reserved.\n";
45 static char sccsid[] = "@(#)xargs.c 8.1 (Berkeley) 6/6/93";
48 #include <sys/cdefs.h>
49 __FBSDID("$FreeBSD$");
51 #include <sys/types.h>
54 #include <sys/limits.h>
55 #include <sys/resource.h>
68 #include "pathnames.h"
70 static void parse_input(int, char *[]);
71 static void prerun(int, char *[]);
72 static int prompt(void);
73 static void run(char **);
74 static void usage(void);
75 void strnsubst(char **, const char *, const char *, size_t);
76 static pid_t xwait(int block, int *status);
77 static void xexit(const char *, const int);
78 static void waitchildren(const char *, int);
79 static void pids_init(void);
80 static int pids_empty(void);
81 static int pids_full(void);
82 static void pids_add(pid_t pid);
83 static int pids_remove(pid_t pid);
84 static int findslot(pid_t pid);
85 static int findfreeslot(void);
86 static void clearslot(int slot);
88 static char echo[] = _PATH_ECHO;
89 static char **av, **bxp, **ep, **endxp, **xp;
90 static char *argp, *bbp, *ebp, *inpline, *p, *replstr;
91 static const char *eofstr;
92 static int count, insingle, indouble, oflag, pflag, tflag, Rflag, rval, zflag;
93 static int cnt, Iflag, jfound, Lflag, Sflag, wasquoted, xflag;
94 static int curprocs, maxprocs;
95 static pid_t *childpids;
97 static volatile int childerr;
99 extern char **environ;
102 main(int argc, char *argv[])
105 int ch, Jflag, nargs, nflag, nline;
111 inpline = replstr = NULL;
116 (void)setlocale(LC_ALL, "");
119 * POSIX.2 limits the exec line length to ARG_MAX - 2K. Running that
120 * caused some E2BIG errors, so it was changed to ARG_MAX - 4K. Given
121 * that the smallest argument is 2 bytes in length, this means that
122 * the number of arguments is limited to:
124 * (ARG_MAX - 4K - LENGTH(utility + arguments)) / 2.
126 * We arbitrarily limit the number of arguments to 5000. This is
127 * allowed by POSIX.2 as long as the resulting minimum exec line is
128 * at least LINE_MAX. Realloc'ing as necessary is possible, but
129 * probably not worthwhile.
132 if ((arg_max = sysconf(_SC_ARG_MAX)) == -1)
133 errx(1, "sysconf(_SC_ARG_MAX) failed");
134 nline = arg_max - 4 * 1024;
135 while (*ep != NULL) {
136 /* 1 byte for each '\0' */
137 nline -= strlen(*ep++) + 1 + sizeof(*ep);
140 while ((ch = getopt(argc, argv, "0E:I:J:L:n:oP:pR:S:s:rtx")) != -1)
157 Lflag = strtonum(optarg, 0, INT_MAX, &errstr);
159 errx(1, "-L %s: %s", optarg, errstr);
163 nargs = strtonum(optarg, 1, INT_MAX, &errstr);
165 errx(1, "-n %s: %s", optarg, errstr);
171 maxprocs = strtonum(optarg, 0, INT_MAX, &errstr);
173 errx(1, "-P %s: %s", optarg, errstr);
174 if (getrlimit(RLIMIT_NPROC, &rl) != 0)
175 errx(1, "getrlimit failed");
176 if (maxprocs == 0 || maxprocs > rl.rlim_cur)
177 maxprocs = rl.rlim_cur;
183 Rflag = strtol(optarg, &endptr, 10);
185 errx(1, "replacements must be a number");
188 /* GNU compatibility */
191 Sflag = strtoul(optarg, &endptr, 10);
193 errx(1, "replsize must be a number");
196 nline = strtonum(optarg, 0, INT_MAX, &errstr);
198 errx(1, "-s %s: %s", optarg, errstr);
228 if (replstr != NULL && *replstr == '\0')
229 errx(1, "replstr may not be empty");
234 * Allocate pointers for the utility name, the utility arguments,
235 * the maximum arguments to be read from stdin and the trailing
238 linelen = 1 + argc + nargs + 1;
239 if ((av = bxp = malloc(linelen * sizeof(char *))) == NULL)
240 errx(1, "malloc failed");
243 * Use the user's name for the utility as argv[0], just like the
244 * shell. Echo is the default. Set up pointers for the user's
248 cnt = strlen(*bxp++ = echo);
251 if (Jflag && strcmp(*argv, replstr) == 0) {
255 for (avj = argv; *avj; avj++)
256 cnt += strlen(*avj) + 1;
259 cnt += strlen(*bxp++ = *argv) + 1;
260 } while (*++argv != NULL);
264 * Set up begin/end/traversing pointers into the array. The -n
265 * count doesn't include the trailing NULL pointer, so the malloc
266 * added in an extra slot.
268 endxp = (xp = bxp) + nargs;
271 * Allocate buffer space for the arguments read from stdin and the
272 * trailing NULL. Buffer space is defined as the default or specified
273 * space, minus the length of the utility name and arguments. Set up
274 * begin/end/traversing pointers into the array. The -s count does
275 * include the trailing NULL, so the malloc didn't add in an extra
280 errx(1, "insufficient space for command");
282 if ((bbp = malloc((size_t)(nline + 1))) == NULL)
283 errx(1, "malloc failed");
284 ebp = (argp = p = bbp) + nline - 1;
286 parse_input(argc, argv);
290 parse_input(int argc, char *argv[])
297 switch (ch = getchar()) {
299 /* No arguments since last exec. */
305 /* Quotes escape tabs and spaces. */
306 if (insingle || indouble || zflag)
312 * Increment 'count', so that nulls will be treated
313 * as end-of-line, as well as end-of-argument. This
314 * is needed so -0 works properly with -I and -L.
323 count++; /* Indicate end-of-line (used by -L) */
325 /* Quotes do not escape newlines. */
326 arg1: if (insingle || indouble) {
327 warnx("unterminated quote");
331 foundeof = *eofstr != '\0' &&
332 strncmp(argp, eofstr, p - argp) == 0;
334 /* Do not make empty args unless they are quoted */
335 if ((argp != p || wasquoted) && !foundeof) {
345 * If this string is not zero
346 * length, append a space for
347 * separation before the next
350 if ((curlen = strlen(inpline)))
351 strcat(inpline, " ");
355 * Allocate enough to hold what we will
356 * be holding in a second, and to append
357 * a space next time through, if we have
360 inpline = realloc(inpline, curlen + 2 +
362 if (inpline == NULL) {
363 warnx("realloc failed");
367 strcpy(inpline, argp);
369 strcat(inpline, argp);
374 * If max'd out on args or buffer, or reached EOF,
375 * run the command. If xflag and max'd out on buffer
376 * but not on args, object. Having reached the limit
377 * of input lines, as specified by -L is the same as
378 * maxing out on arguments.
380 if (xp == endxp || p > ebp || ch == EOF ||
381 (Lflag <= count && xflag) || foundeof) {
382 if (xflag && xp != endxp && p > ebp) {
383 warnx("insufficient space for arguments");
387 for (avj = argv; *avj; avj++)
391 if (ch == EOF || foundeof)
401 if (indouble || zflag)
403 insingle = !insingle;
407 if (insingle || zflag)
409 indouble = !indouble;
415 /* Backslash escapes anything, is escaped by quotes. */
416 if (!insingle && !indouble && (ch = getchar()) == EOF) {
417 warnx("backslash at EOF");
422 addch: if (p < ebp) {
427 /* If only one argument, not enough buffer space. */
429 warnx("insufficient space for argument");
432 /* Didn't hit argument limit, so if xflag object. */
434 warnx("insufficient space for arguments");
439 for (avj = argv; *avj; avj++)
445 memcpy(bbp, argp, (size_t)cnt);
446 p = (argp = bbp) + cnt;
453 * Do things necessary before run()'ing, such as -I substitution,
454 * and then call run().
457 prerun(int argc, char *argv[])
459 char **tmp, **tmp2, **avj;
464 if (argc == 0 || repls == 0) {
473 * Allocate memory to hold the argument list, and
474 * a NULL at the tail.
476 tmp = malloc((argc + 1) * sizeof(char *));
478 warnx("malloc failed");
484 * Save the first argument and iterate over it, we
485 * cannot do strnsubst() to it.
487 if ((*tmp++ = strdup(*avj++)) == NULL) {
488 warnx("strdup failed");
493 * For each argument to utility, if we have not used up
494 * the number of replacements we are allowed to do, and
495 * if the argument contains at least one occurrence of
496 * replstr, call strnsubst(), else just save the string.
497 * Iterations over elements of avj and tmp are done
502 if (repls && strstr(*tmp, replstr) != NULL) {
503 strnsubst(tmp++, replstr, inpline, (size_t)Sflag);
507 if ((*tmp = strdup(*tmp)) == NULL) {
508 warnx("strdup failed");
522 * Walk from the tail to the head, free along the way.
524 for (; tmp2 != tmp; tmp--)
527 * Now free the list itself.
532 * Free the input line buffer, if we have one.
534 if (inpline != NULL) {
548 * If the user wants to be notified of each command before it is
549 * executed, notify them. If they want the notification to be
550 * followed by a prompt, then prompt them.
552 if (tflag || pflag) {
553 (void)fprintf(stderr, "%s", *argv);
554 for (avec = argv + 1; *avec != NULL; ++avec)
555 (void)fprintf(stderr, " %s", *avec);
557 * If the user has asked to be prompted, do so.
561 * If they asked not to exec, return without execution
562 * but if they asked to, go to the execution. If we
563 * could not open their tty, break the switch and drop
564 * back to -t behaviour.
574 (void)fprintf(stderr, "\n");
575 (void)fflush(stderr);
579 switch (pid = vfork()) {
585 if ((fd = open(_PATH_TTY, O_RDONLY)) == -1)
586 err(1, "can't open /dev/tty");
588 fd = open(_PATH_DEVNULL, O_RDONLY);
590 if (fd > STDIN_FILENO) {
591 if (dup2(fd, STDIN_FILENO) != 0)
592 err(1, "can't dup2 to stdin");
595 execvp(argv[0], argv);
600 waitchildren(*argv, 0);
604 * Wait for a tracked child to exit and return its pid and exit status.
606 * Ignores (discards) all untracked child processes.
607 * Returns -1 and sets errno to ECHILD if no tracked children exist.
608 * If block is set, waits indefinitely for a child process to exit.
609 * If block is not set and no children have exited, returns 0 immediately.
612 xwait(int block, int *status) {
620 while ((pid = waitpid(-1, status, block ? 0 : WNOHANG)) > 0)
621 if (pids_remove(pid))
628 xexit(const char *name, const int exit_code) {
629 waitchildren(name, 1);
634 waitchildren(const char *name, int waitall)
640 while ((pid = xwait(waitall || pids_full(), &status)) > 0) {
642 * If we couldn't invoke the utility or if utility exited
643 * because of a signal or with a value of 255, warn (per
644 * POSIX), and then wait until all other children have
645 * exited before exiting 1-125. POSIX requires us to stop
646 * reading if child exits because of a signal or with 255,
647 * but it does not require us to exit immediately; waiting
648 * is preferable to orphaning.
650 if (childerr != 0 && cause_exit == 0) {
653 cause_exit = ENOENT ? 127 : 126;
655 } else if (WIFSIGNALED(status)) {
656 waitall = cause_exit = 1;
657 warnx("%s: terminated with signal %d; aborting",
658 name, WTERMSIG(status));
659 } else if (WEXITSTATUS(status) == 255) {
660 waitall = cause_exit = 1;
661 warnx("%s: exited with status 255; aborting", name);
662 } else if (WEXITSTATUS(status))
668 if (pid == -1 && errno != ECHILD)
679 if ((childpids = malloc(maxprocs * sizeof(*childpids))) == NULL)
680 errx(1, "malloc failed");
682 for (i = 0; i < maxprocs; i++)
690 return (curprocs == 0);
697 return (curprocs >= maxprocs);
705 slot = findfreeslot();
706 childpids[slot] = pid;
711 pids_remove(pid_t pid)
715 if ((slot = findslot(pid)) < 0)
728 if ((slot = findslot(NOPID)) < 0)
729 errx(1, "internal error: no free pid slot");
738 for (slot = 0; slot < maxprocs; slot++)
739 if (childpids[slot] == pid)
748 childpids[slot] = NOPID;
752 * Prompt the user about running a command.
763 if ((ttyfp = fopen(_PATH_TTY, "r")) == NULL)
764 return (2); /* Indicate that the TTY failed to open. */
765 (void)fprintf(stderr, "?...");
766 (void)fflush(stderr);
767 if ((response = fgetln(ttyfp, &rsize)) == NULL ||
768 regcomp(&cre, nl_langinfo(YESEXPR), REG_BASIC) != 0) {
772 response[rsize - 1] = '\0';
773 match = regexec(&cre, response, 0, NULL, 0);
784 "usage: xargs [-0opt] [-E eofstr] [-I replstr [-R replacements] [-S replsize]]\n"
785 " [-J replstr] [-L number] [-n number [-x]] [-P maxprocs]\n"
786 " [-s size] [utility [argument ...]]\n");