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 $
41 * $DragonFly: src/usr.bin/xargs/xargs.c,v 1.3 2004/07/27 21:42:48 dillon Exp $
44 #include <sys/types.h>
61 #include "pathnames.h"
63 static void parse_input(int, char *[]);
64 static void prerun(int, char *[]);
65 static int prompt(void);
66 static void run(char **);
67 static void usage(void);
68 void strnsubst(char **, const char *, const char *, size_t);
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;
77 extern char **environ;
80 main(int argc, char *argv[])
83 int ch, Jflag, nargs, nflag, nline;
86 inpline = replstr = NULL;
91 (void)setlocale(LC_MESSAGES, "");
94 * POSIX.2 limits the exec line length to ARG_MAX - 2K. Running that
95 * caused some E2BIG errors, so it was changed to ARG_MAX - 4K. Given
96 * that the smallest argument is 2 bytes in length, this means that
97 * the number of arguments is limited to:
99 * (ARG_MAX - 4K - LENGTH(utility + arguments)) / 2.
101 * We arbitrarily limit the number of arguments to 5000. This is
102 * allowed by POSIX.2 as long as the resulting minimum exec line is
103 * at least LINE_MAX. Realloc'ing as necessary is possible, but
104 * probably not worthwhile.
107 if ((arg_max = sysconf(_SC_ARG_MAX)) == -1)
108 errx(1, "sysconf(_SC_ARG_MAX) failed");
109 nline = arg_max - 4 * 1024;
110 while (*ep != NULL) {
111 /* 1 byte for each '\0' */
112 nline -= strlen(*ep++) + 1 + sizeof(*ep);
114 while ((ch = getopt(argc, argv, "0E:I:J:L:n:opR:s:tx")) != -1)
131 Lflag = atoi(optarg);
135 if ((nargs = atoi(optarg)) <= 0)
136 errx(1, "illegal argument count");
145 if ((Rflag = atoi(optarg)) <= 0)
146 errx(1, "illegal number of replacements");
149 nline = atoi(optarg);
175 if (replstr != NULL && *replstr == '\0')
176 errx(1, "replstr may not be empty");
179 * Allocate pointers for the utility name, the utility arguments,
180 * the maximum arguments to be read from stdin and the trailing
183 linelen = 1 + argc + nargs + 1;
184 if ((av = bxp = malloc(linelen * sizeof(char **))) == NULL)
185 errx(1, "malloc failed");
188 * Use the user's name for the utility as argv[0], just like the
189 * shell. Echo is the default. Set up pointers for the user's
193 cnt = strlen(*bxp++ = echo);
196 if (Jflag && strcmp(*argv, replstr) == 0) {
200 for (avj = argv; *avj; avj++)
201 cnt += strlen(*avj) + 1;
204 cnt += strlen(*bxp++ = *argv) + 1;
205 } while (*++argv != NULL);
209 * Set up begin/end/traversing pointers into the array. The -n
210 * count doesn't include the trailing NULL pointer, so the malloc
211 * added in an extra slot.
213 expx = (xp = bxp) + nargs;
216 * Allocate buffer space for the arguments read from stdin and the
217 * trailing NULL. Buffer space is defined as the default or specified
218 * space, minus the length of the utility name and arguments. Set up
219 * begin/end/traversing pointers into the array. The -s count does
220 * include the trailing NULL, so the malloc didn't add in an extra
225 errx(1, "insufficient space for command");
227 if ((bbp = malloc((size_t)(nline + 1))) == NULL)
228 errx(1, "malloc failed");
229 ebp = (argp = p = bbp) + nline - 1;
231 parse_input(argc, argv);
235 parse_input(int argc, char *argv[])
242 switch(ch = getchar()) {
244 /* No arguments since last exec. */
250 /* Quotes escape tabs and spaces. */
251 if (insingle || indouble || zflag)
263 /* Quotes do not escape newlines. */
264 arg1: if (insingle || indouble)
265 errx(1, "unterminated quote");
267 foundeof = *eofstr != '\0' &&
268 strcmp(argp, eofstr) == 0;
270 /* Do not make empty args unless they are quoted */
271 if ((argp != p || wasquoted) && !foundeof) {
281 * If this string is not zero
282 * length, append a space for
283 * separation before the next
286 if ((curlen = strlen(inpline)))
287 strcat(inpline, " ");
291 * Allocate enough to hold what we will
292 * be holding in a second, and to append
293 * a space next time through, if we have
296 inpline = realloc(inpline, curlen + 2 +
299 errx(1, "realloc failed");
301 strcpy(inpline, argp);
303 strcat(inpline, argp);
308 * If max'd out on args or buffer, or reached EOF,
309 * run the command. If xflag and max'd out on buffer
310 * but not on args, object. Having reached the limit
311 * of input lines, as specified by -L is the same as
312 * maxing out on arguments.
314 if (xp == expx || p > ebp || ch == EOF ||
315 (Lflag <= count && xflag) || foundeof) {
316 if (xflag && xp != expx && p > ebp)
317 errx(1, "insufficient space for arguments");
319 for (avj = argv; *avj; avj++)
323 if (ch == EOF || foundeof)
333 if (indouble || zflag)
335 insingle = !insingle;
339 if (insingle || zflag)
341 indouble = !indouble;
347 /* Backslash escapes anything, is escaped by quotes. */
348 if (!insingle && !indouble && (ch = getchar()) == EOF)
349 errx(1, "backslash at EOF");
352 addch: if (p < ebp) {
357 /* If only one argument, not enough buffer space. */
359 errx(1, "insufficient space for argument");
360 /* Didn't hit argument limit, so if xflag object. */
362 errx(1, "insufficient space for arguments");
365 for (avj = argv; *avj; avj++)
371 memcpy(bbp, argp, (size_t)cnt);
372 p = (argp = bbp) + cnt;
380 * Do things necessary before run()'ing, such as -I substitution,
381 * and then call run().
384 prerun(int argc, char *argv[])
386 char **tmp, **tmp2, **avj;
391 if (argc == 0 || repls == 0) {
400 * Allocate memory to hold the argument list, and
401 * a NULL at the tail.
403 tmp = malloc((argc + 1) * sizeof(char**));
405 errx(1, "malloc failed");
409 * Save the first argument and iterate over it, we
410 * cannot do strnsubst() to it.
412 if ((*tmp++ = strdup(*avj++)) == NULL)
413 errx(1, "strdup failed");
416 * For each argument to utility, if we have not used up
417 * the number of replacements we are allowed to do, and
418 * if the argument contains at least one occurrence of
419 * replstr, call strnsubst(), else just save the string.
420 * Iterations over elements of avj and tmp are done
425 if (repls && strstr(*tmp, replstr) != NULL) {
426 strnsubst(tmp++, replstr, inpline, (size_t)255);
429 if ((*tmp = strdup(*tmp)) == NULL)
430 errx(1, "strdup failed");
442 * Walk from the tail to the head, free along the way.
444 for (; tmp2 != tmp; tmp--)
447 * Now free the list itself.
452 * Free the input line buffer, if we have one.
454 if (inpline != NULL) {
463 volatile int childerr;
469 * If the user wants to be notified of each command before it is
470 * executed, notify them. If they want the notification to be
471 * followed by a prompt, then prompt them.
473 if (tflag || pflag) {
474 (void)fprintf(stderr, "%s", *argv);
475 for (avec = argv + 1; *avec != NULL; ++avec)
476 (void)fprintf(stderr, " %s", *avec);
478 * If the user has asked to be prompted, do so.
482 * If they asked not to exec, return without execution
483 * but if they asked to, go to the execution. If we
484 * could not open their tty, break the switch and drop
485 * back to -t behaviour.
495 (void)fprintf(stderr, "\n");
496 (void)fflush(stderr);
500 switch(pid = vfork()) {
506 if (open("/dev/tty", O_RDONLY) == -1)
507 err(1, "open /dev/tty");
509 if (open("/dev/null", O_RDONLY) == -1)
510 err(1, "open /dev/null");
512 execvp(argv[0], argv);
516 pid = waitpid(pid, &status, 0);
519 /* If we couldn't invoke the utility, exit. */
521 err(childerr == ENOENT ? 127 : 126, "%s", *argv);
522 /* If utility signaled or exited with a value of 255, exit 1-125. */
523 if (WIFSIGNALED(status) || WEXITSTATUS(status) == 255)
525 if (WEXITSTATUS(status))
530 * Prompt the user about running a command.
541 if ((ttyfp = fopen(_PATH_TTY, "r")) == NULL)
542 return (2); /* Indicate that the TTY failed to open. */
543 (void)fprintf(stderr, "?...");
544 (void)fflush(stderr);
545 if ((response = fgetln(ttyfp, &rsize)) == NULL ||
550 nl_langinfo(YESEXPR),
556 match = regexec(&cre, response, 0, NULL, 0);
566 "usage: xargs [-0opt] [-E eofstr] [-I replstr [-R replacements]] [-J replstr]\n"
567 " [-L number] [-n number [-x] [-s size] [utility [argument ...]]\n");