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. 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 $
34 * @(#) Copyright (c) 1990, 1993 The Regents of the University of California. All rights reserved.
35 * @(#)xargs.c 8.1 (Berkeley) 6/6/93
36 * $FreeBSD: src/usr.bin/xargs/xargs.c,v 1.9.2.6 2003/06/01 21:40:35 mux Exp $
39 #include <sys/types.h>
56 #include "pathnames.h"
58 static void parse_input(int, char *[]);
59 static void prerun(int, char *[]);
60 static int prompt(void);
61 static void run(char **);
62 static void usage(void);
63 void strnsubst(char **, const char *, const char *, size_t);
64 static void waitchildren(const char *, int);
66 static char echo[] = _PATH_ECHO;
67 static char **av, **bxp, **ep, **expx, **xp;
68 static char *argp, *bbp, *ebp, *inpline, *p, *replstr;
69 static const char *eofstr;
70 static int count, insingle, indouble, oflag, pflag, tflag, Rflag, rval, zflag;
71 static int cnt, Iflag, jfound, Lflag, wasquoted, xflag;
72 static int curprocs, maxprocs;
73 static volatile int childerr;
75 extern char **environ;
78 main(int argc, char *argv[])
82 int ch, Jflag, nargs, nflag, nline;
85 inpline = replstr = NULL;
90 (void)setlocale(LC_MESSAGES, "");
93 * POSIX.2 limits the exec line length to ARG_MAX - 2K. Running that
94 * caused some E2BIG errors, so it was changed to ARG_MAX - 4K. Given
95 * that the smallest argument is 2 bytes in length, this means that
96 * the number of arguments is limited to:
98 * (ARG_MAX - 4K - LENGTH(utility + arguments)) / 2.
100 * We arbitrarily limit the number of arguments to 5000. This is
101 * allowed by POSIX.2 as long as the resulting minimum exec line is
102 * at least LINE_MAX. Realloc'ing as necessary is possible, but
103 * probably not worthwhile.
106 if ((arg_max = sysconf(_SC_ARG_MAX)) == -1)
107 errx(1, "sysconf(_SC_ARG_MAX) failed");
108 nline = arg_max - 4 * 1024;
109 while (*ep != NULL) {
110 /* 1 byte for each '\0' */
111 nline -= strlen(*ep++) + 1 + sizeof(*ep);
115 while ((ch = getopt(argc, argv, "0E:I:J:L:n:opP:R:s:tx")) != -1)
132 Lflag = strtol(optarg, &tmp, 10);
133 if (*tmp != 0 || *optarg == 0)
134 errx(1, "illegal argument count");
138 if ((nargs = atoi(optarg)) <= 0)
139 errx(1, "illegal argument count");
148 if ((maxprocs = atoi(optarg)) <= 0)
149 errx(1, "max.processes must be >0");
152 if ((Rflag = atoi(optarg)) <= 0)
153 errx(1, "illegal number of replacements");
156 nline = atoi(optarg);
182 if (replstr != NULL && *replstr == '\0')
183 errx(1, "replstr may not be empty");
186 * Allocate pointers for the utility name, the utility arguments,
187 * the maximum arguments to be read from stdin and the trailing
190 linelen = 1 + argc + nargs + 1;
191 if ((av = bxp = malloc(linelen * sizeof(char **))) == NULL)
192 errx(1, "malloc failed");
195 * Use the user's name for the utility as argv[0], just like the
196 * shell. Echo is the default. Set up pointers for the user's
200 cnt = strlen(*bxp++ = echo);
203 if (Jflag && strcmp(*argv, replstr) == 0) {
207 for (avj = argv; *avj; avj++)
208 cnt += strlen(*avj) + 1;
211 cnt += strlen(*bxp++ = *argv) + 1;
212 } while (*++argv != NULL);
216 * Set up begin/end/traversing pointers into the array. The -n
217 * count doesn't include the trailing NULL pointer, so the malloc
218 * added in an extra slot.
220 expx = (xp = bxp) + nargs;
223 * Allocate buffer space for the arguments read from stdin and the
224 * trailing NULL. Buffer space is defined as the default or specified
225 * space, minus the length of the utility name and arguments. Set up
226 * begin/end/traversing pointers into the array. The -s count does
227 * include the trailing NULL, so the malloc didn't add in an extra
232 errx(1, "insufficient space for command");
234 if ((bbp = malloc((size_t)(nline + 1))) == NULL)
235 errx(1, "malloc failed");
236 ebp = (argp = p = bbp) + nline - 1;
238 parse_input(argc, argv);
242 parse_input(int argc, char *argv[])
249 switch(ch = getchar()) {
251 /* No arguments since last exec. */
253 waitchildren(*argv, 1);
259 /* Quotes escape tabs and spaces. */
260 if (insingle || indouble || zflag)
272 /* Quotes do not escape newlines. */
273 arg1: if (insingle || indouble)
274 errx(1, "unterminated quote");
276 foundeof = *eofstr != '\0' &&
277 strcmp(argp, eofstr) == 0;
279 /* Do not make empty args unless they are quoted */
280 if ((argp != p || wasquoted) && !foundeof) {
290 * If this string is not zero
291 * length, append a space for
292 * separation before the next
295 if ((curlen = strlen(inpline)))
296 strcat(inpline, " ");
300 * Allocate enough to hold what we will
301 * be holding in a second, and to append
302 * a space next time through, if we have
305 inpline = realloc(inpline, curlen + 2 +
308 errx(1, "realloc failed");
310 strcpy(inpline, argp);
312 strcat(inpline, argp);
317 * If max'd out on args or buffer, or reached EOF,
318 * run the command. If xflag and max'd out on buffer
319 * but not on args, object. Having reached the limit
320 * of input lines, as specified by -L is the same as
321 * maxing out on arguments.
323 if (xp == expx || p > ebp || ch == EOF ||
324 (Lflag <= count && xflag) || foundeof) {
325 if (xflag && xp != expx && p > ebp)
326 errx(1, "insufficient space for arguments");
328 for (avj = argv; *avj; avj++)
332 if (ch == EOF || foundeof) {
333 waitchildren(*argv, 1);
344 if (indouble || zflag)
346 insingle = !insingle;
350 if (insingle || zflag)
352 indouble = !indouble;
358 /* Backslash escapes anything, is escaped by quotes. */
359 if (!insingle && !indouble && (ch = getchar()) == EOF)
360 errx(1, "backslash at EOF");
363 addch: if (p < ebp) {
368 /* If only one argument, not enough buffer space. */
370 errx(1, "insufficient space for argument");
371 /* Didn't hit argument limit, so if xflag object. */
373 errx(1, "insufficient space for arguments");
376 for (avj = argv; *avj; avj++)
382 memcpy(bbp, argp, (size_t)cnt);
383 p = (argp = bbp) + cnt;
391 * Do things necessary before run()'ing, such as -I substitution,
392 * and then call run().
395 prerun(int argc, char *argv[])
397 char **tmp, **tmp2, **avj;
402 if (argc == 0 || repls == 0) {
411 * Allocate memory to hold the argument list, and
412 * a NULL at the tail.
414 tmp = malloc((argc + 1) * sizeof(char**));
416 errx(1, "malloc failed");
420 * Save the first argument and iterate over it, we
421 * cannot do strnsubst() to it.
423 if ((*tmp++ = strdup(*avj++)) == NULL)
424 errx(1, "strdup failed");
427 * For each argument to utility, if we have not used up
428 * the number of replacements we are allowed to do, and
429 * if the argument contains at least one occurrence of
430 * replstr, call strnsubst(), else just save the string.
431 * Iterations over elements of avj and tmp are done
436 if (repls && strstr(*tmp, replstr) != NULL) {
437 strnsubst(tmp++, replstr, inpline, (size_t)255);
440 if ((*tmp = strdup(*tmp)) == NULL)
441 errx(1, "strdup failed");
453 * Walk from the tail to the head, free along the way.
455 for (; tmp2 != tmp; tmp--)
458 * Now free the list itself.
463 * Free the input line buffer, if we have one.
465 if (inpline != NULL) {
478 * If the user wants to be notified of each command before it is
479 * executed, notify them. If they want the notification to be
480 * followed by a prompt, then prompt them.
482 if (tflag || pflag) {
483 (void)fprintf(stderr, "%s", *argv);
484 for (avec = argv + 1; *avec != NULL; ++avec)
485 (void)fprintf(stderr, " %s", *avec);
487 * If the user has asked to be prompted, do so.
491 * If they asked not to exec, return without execution
492 * but if they asked to, go to the execution. If we
493 * could not open their tty, break the switch and drop
494 * back to -t behaviour.
504 (void)fprintf(stderr, "\n");
505 (void)fflush(stderr);
509 switch(pid = vfork()) {
515 if (open("/dev/tty", O_RDONLY) == -1)
516 err(1, "open /dev/tty");
518 if (open("/dev/null", O_RDONLY) == -1)
519 err(1, "open /dev/null");
521 execvp(argv[0], argv);
526 waitchildren(*argv, 0);
530 * Handle child processes.
533 waitchildren(const char *name, int waitall)
538 while ((pid = wait3(&status, !waitall && curprocs < maxprocs ?
539 WNOHANG : 0, NULL)) > 0) {
542 /* If we couldn't invoke the utility, exit. */
545 err(errno == ENOENT ? 127 : 126, "%s", name);
549 * If utility signaled or exited with a value of 255,
552 if (WIFSIGNALED(status) || WEXITSTATUS(status) == 255)
554 if (WEXITSTATUS(status))
557 if (pid == -1 && errno != ECHILD)
562 * Prompt the user about running a command.
573 if ((ttyfp = fopen(_PATH_TTY, "r")) == NULL)
574 return (2); /* Indicate that the TTY failed to open. */
575 (void)fprintf(stderr, "?...");
576 (void)fflush(stderr);
577 if ((response = fgetln(ttyfp, &rsize)) == NULL ||
582 nl_langinfo(YESEXPR),
588 match = regexec(&cre, response, 0, NULL, 0);
598 "usage: xargs [-0opt] [-E eofstr] [-I replstr [-R replacements]] [-J replstr]\n"
599 " [-L number] [-n number [-x] [-P maxprocs] [-s size]\n"
600 " [utility [argument ...]]\n");