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 $
40 static const char copyright[] =
41 "@(#) Copyright (c) 1990, 1993\n\
42 The Regents of the University of California. All rights reserved.\n";
47 static char sccsid[] = "@(#)xargs.c 8.1 (Berkeley) 6/6/93";
51 #include <sys/cdefs.h>
52 __FBSDID("$FreeBSD: src/usr.bin/xargs/xargs.c,v 1.9.2.6 2003/06/01 21:40:35 mux Exp $");
54 #include <sys/types.h>
71 #include "pathnames.h"
73 static void parse_input(int, char *[]);
74 static void prerun(int, char *[]);
75 static int prompt(void);
76 static void run(char **);
77 static void usage(void);
78 void strnsubst(char **, const char *, const char *, size_t);
80 static char echo[] = _PATH_ECHO;
81 static char **av, **bxp, **ep, **exp, **xp;
82 static char *argp, *bbp, *ebp, *inpline, *p, *replstr;
83 static const char *eofstr;
84 static int count, insingle, indouble, oflag, pflag, tflag, Rflag, rval, zflag;
85 static int cnt, Iflag, jfound, Lflag, wasquoted, xflag;
87 extern char **environ;
90 main(int argc, char *argv[])
93 int ch, Jflag, nargs, nflag, nline;
96 inpline = replstr = NULL;
101 (void)setlocale(LC_MESSAGES, "");
104 * POSIX.2 limits the exec line length to ARG_MAX - 2K. Running that
105 * caused some E2BIG errors, so it was changed to ARG_MAX - 4K. Given
106 * that the smallest argument is 2 bytes in length, this means that
107 * the number of arguments is limited to:
109 * (ARG_MAX - 4K - LENGTH(utility + arguments)) / 2.
111 * We arbitrarily limit the number of arguments to 5000. This is
112 * allowed by POSIX.2 as long as the resulting minimum exec line is
113 * at least LINE_MAX. Realloc'ing as necessary is possible, but
114 * probably not worthwhile.
117 if ((arg_max = sysconf(_SC_ARG_MAX)) == -1)
118 errx(1, "sysconf(_SC_ARG_MAX) failed");
119 nline = arg_max - 4 * 1024;
120 while (*ep != NULL) {
121 /* 1 byte for each '\0' */
122 nline -= strlen(*ep++) + 1 + sizeof(*ep);
124 while ((ch = getopt(argc, argv, "0E:I:J:L:n:opR:s:tx")) != -1)
141 Lflag = atoi(optarg);
145 if ((nargs = atoi(optarg)) <= 0)
146 errx(1, "illegal argument count");
155 if ((Rflag = atoi(optarg)) <= 0)
156 errx(1, "illegal number of replacements");
159 nline = atoi(optarg);
185 if (replstr != NULL && *replstr == '\0')
186 errx(1, "replstr may not be empty");
189 * Allocate pointers for the utility name, the utility arguments,
190 * the maximum arguments to be read from stdin and the trailing
193 linelen = 1 + argc + nargs + 1;
194 if ((av = bxp = malloc(linelen * sizeof(char **))) == NULL)
195 errx(1, "malloc failed");
198 * Use the user's name for the utility as argv[0], just like the
199 * shell. Echo is the default. Set up pointers for the user's
203 cnt = strlen(*bxp++ = echo);
206 if (Jflag && strcmp(*argv, replstr) == 0) {
210 for (avj = argv; *avj; avj++)
211 cnt += strlen(*avj) + 1;
214 cnt += strlen(*bxp++ = *argv) + 1;
215 } while (*++argv != NULL);
219 * Set up begin/end/traversing pointers into the array. The -n
220 * count doesn't include the trailing NULL pointer, so the malloc
221 * added in an extra slot.
223 exp = (xp = bxp) + nargs;
226 * Allocate buffer space for the arguments read from stdin and the
227 * trailing NULL. Buffer space is defined as the default or specified
228 * space, minus the length of the utility name and arguments. Set up
229 * begin/end/traversing pointers into the array. The -s count does
230 * include the trailing NULL, so the malloc didn't add in an extra
235 errx(1, "insufficient space for command");
237 if ((bbp = malloc((size_t)(nline + 1))) == NULL)
238 errx(1, "malloc failed");
239 ebp = (argp = p = bbp) + nline - 1;
241 parse_input(argc, argv);
245 parse_input(int argc, char *argv[])
252 switch(ch = getchar()) {
254 /* No arguments since last exec. */
260 /* Quotes escape tabs and spaces. */
261 if (insingle || indouble || zflag)
273 /* Quotes do not escape newlines. */
274 arg1: if (insingle || indouble)
275 errx(1, "unterminated quote");
277 foundeof = *eofstr != '\0' &&
278 strcmp(argp, eofstr) == 0;
280 /* Do not make empty args unless they are quoted */
281 if ((argp != p || wasquoted) && !foundeof) {
291 * If this string is not zero
292 * length, append a space for
293 * separation before the next
296 if ((curlen = strlen(inpline)))
297 strcat(inpline, " ");
301 * Allocate enough to hold what we will
302 * be holding in a second, and to append
303 * a space next time through, if we have
306 inpline = realloc(inpline, curlen + 2 +
309 errx(1, "realloc failed");
311 strcpy(inpline, argp);
313 strcat(inpline, argp);
318 * If max'd out on args or buffer, or reached EOF,
319 * run the command. If xflag and max'd out on buffer
320 * but not on args, object. Having reached the limit
321 * of input lines, as specified by -L is the same as
322 * maxing out on arguments.
324 if (xp == exp || p > ebp || ch == EOF ||
325 (Lflag <= count && xflag) || foundeof) {
326 if (xflag && xp != exp && p > ebp)
327 errx(1, "insufficient space for arguments");
329 for (avj = argv; *avj; avj++)
333 if (ch == EOF || foundeof)
343 if (indouble || zflag)
345 insingle = !insingle;
349 if (insingle || zflag)
351 indouble = !indouble;
357 /* Backslash escapes anything, is escaped by quotes. */
358 if (!insingle && !indouble && (ch = getchar()) == EOF)
359 errx(1, "backslash at EOF");
362 addch: if (p < ebp) {
367 /* If only one argument, not enough buffer space. */
369 errx(1, "insufficient space for argument");
370 /* Didn't hit argument limit, so if xflag object. */
372 errx(1, "insufficient space for arguments");
375 for (avj = argv; *avj; avj++)
381 memcpy(bbp, argp, (size_t)cnt);
382 p = (argp = bbp) + cnt;
390 * Do things necessary before run()'ing, such as -I substitution,
391 * and then call run().
394 prerun(int argc, char *argv[])
396 char **tmp, **tmp2, **avj;
401 if (argc == 0 || repls == 0) {
410 * Allocate memory to hold the argument list, and
411 * a NULL at the tail.
413 tmp = malloc((argc + 1) * sizeof(char**));
415 errx(1, "malloc failed");
419 * Save the first argument and iterate over it, we
420 * cannot do strnsubst() to it.
422 if ((*tmp++ = strdup(*avj++)) == NULL)
423 errx(1, "strdup failed");
426 * For each argument to utility, if we have not used up
427 * the number of replacements we are allowed to do, and
428 * if the argument contains at least one occurrence of
429 * replstr, call strnsubst(), else just save the string.
430 * Iterations over elements of avj and tmp are done
435 if (repls && strstr(*tmp, replstr) != NULL) {
436 strnsubst(tmp++, replstr, inpline, (size_t)255);
439 if ((*tmp = strdup(*tmp)) == NULL)
440 errx(1, "strdup failed");
452 * Walk from the tail to the head, free along the way.
454 for (; tmp2 != tmp; tmp--)
457 * Now free the list itself.
462 * Free the input line buffer, if we have one.
464 if (inpline != NULL) {
473 volatile int childerr;
479 * If the user wants to be notified of each command before it is
480 * executed, notify them. If they want the notification to be
481 * followed by a prompt, then prompt them.
483 if (tflag || pflag) {
484 (void)fprintf(stderr, "%s", *argv);
485 for (avec = argv + 1; *avec != NULL; ++avec)
486 (void)fprintf(stderr, " %s", *avec);
488 * If the user has asked to be prompted, do so.
492 * If they asked not to exec, return without execution
493 * but if they asked to, go to the execution. If we
494 * could not open their tty, break the switch and drop
495 * back to -t behaviour.
505 (void)fprintf(stderr, "\n");
506 (void)fflush(stderr);
510 switch(pid = vfork()) {
516 if (open("/dev/tty", O_RDONLY) == -1)
517 err(1, "open /dev/tty");
519 if (open("/dev/null", O_RDONLY) == -1)
520 err(1, "open /dev/null");
522 execvp(argv[0], argv);
526 pid = waitpid(pid, &status, 0);
529 /* If we couldn't invoke the utility, exit. */
531 err(childerr == ENOENT ? 127 : 126, "%s", *argv);
532 /* If utility signaled or exited with a value of 255, exit 1-125. */
533 if (WIFSIGNALED(status) || WEXITSTATUS(status) == 255)
535 if (WEXITSTATUS(status))
540 * Prompt the user about running a command.
551 if ((ttyfp = fopen(_PATH_TTY, "r")) == NULL)
552 return (2); /* Indicate that the TTY failed to open. */
553 (void)fprintf(stderr, "?...");
554 (void)fflush(stderr);
555 if ((response = fgetln(ttyfp, &rsize)) == NULL ||
560 nl_langinfo(YESEXPR),
566 match = regexec(&cre, response, 0, NULL, 0);
576 "usage: xargs [-0opt] [-E eofstr] [-I replstr [-R replacements]] [-J replstr]\n"
577 " [-L number] [-n number [-x] [-s size] [utility [argument ...]]\n");