1 /* $NetBSD: xargs.c,v 1.20 2010/12/17 11:32:57 plunky Exp $ */
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 $
37 #include <sys/cdefs.h>
39 __COPYRIGHT("@(#) Copyright (c) 1990, 1993\
40 The Regents of the University of California. All rights reserved.");
42 static char sccsid
[] = "@(#)xargs.c 8.1 (Berkeley) 6/6/93";
43 __FBSDID("$FreeBSD: src/usr.bin/xargs/xargs.c,v 1.62 2006/01/01 22:59:54 jmallett Exp $");
45 __RCSID("$NetBSD: xargs.c,v 1.20 2010/12/17 11:32:57 plunky Exp $");
48 #include <sys/param.h>
64 #include "pathnames.h"
66 static void parse_input(int, char *[]);
67 static void prerun(int, char *[]);
68 static int prompt(void);
69 static void run(char **);
70 static void usage(void) __dead
;
71 void strnsubst(char **, const char *, const char *, size_t);
72 static void waitchildren(const char *, int);
74 static char echo
[] = _PATH_ECHO
;
75 static char **av
, **bxp
, **ep
, **endxp
, **xp
;
76 static char *argp
, *bbp
, *ebp
, *inpline
, *p
, *replstr
;
77 static const char *eofstr
;
78 static int count
, insingle
, indouble
, oflag
, pflag
, tflag
, Rflag
, rval
, zflag
;
79 static int cnt
, Iflag
, jfound
, Lflag
, Sflag
, wasquoted
, xflag
;
80 static int curprocs
, maxprocs
;
82 static volatile int childerr
;
84 extern char **environ
;
87 main(int argc
, char *argv
[])
90 int ch
, Jflag
, nargs
, nflag
, nline
;
96 inpline
= replstr
= NULL
;
101 (void)setlocale(LC_ALL
, "");
104 * SUSv3 says of the exec family of functions:
105 * The number of bytes available for the new process'
106 * combined argument and environment lists is {ARG_MAX}. It
107 * is implementation-defined whether null terminators,
108 * pointers, and/or any alignment bytes are included in this
111 * SUSv3 says of xargs:
112 * ... the combined argument and environment lists ...
113 * shall not exceed {ARG_MAX}-2048.
115 * To be conservative, we use ARG_MAX - 4K, and we do include
116 * nul terminators and pointers in the calculation.
118 * Given that the smallest argument is 2 bytes in length, this
119 * means that the number of arguments is limited to:
121 * (ARG_MAX - 4K - LENGTH(env + utility + arguments)) / 2.
123 * We arbitrarily limit the number of arguments to 5000. This is
124 * allowed by POSIX.2 as long as the resulting minimum exec line is
125 * at least LINE_MAX. Realloc'ing as necessary is possible, but
126 * probably not worthwhile.
129 if ((arg_max
= sysconf(_SC_ARG_MAX
)) == -1)
130 errx(1, "sysconf(_SC_ARG_MAX) failed");
131 nline
= arg_max
- 4 * 1024;
132 while (*ep
!= NULL
) {
133 /* 1 byte for each '\0' */
134 nline
-= strlen(*ep
++) + 1 + sizeof(*ep
);
137 while ((ch
= getopt(argc
, argv
, "0E:I:J:L:n:oP:pR:S:s:rtx")) != -1)
154 Lflag
= atoi(optarg
);
158 if ((nargs
= atoi(optarg
)) <= 0)
159 errx(1, "illegal argument count");
165 if ((maxprocs
= atoi(optarg
)) <= 0)
166 errx(1, "max. processes must be >0");
172 Rflag
= strtol(optarg
, &endptr
, 10);
174 errx(1, "replacements must be a number");
177 /* GNU compatibility */
180 Sflag
= strtoul(optarg
, &endptr
, 10);
182 errx(1, "replsize must be a number");
185 nline
= atoi(optarg
);
215 if (replstr
!= NULL
&& *replstr
== '\0')
216 errx(1, "replstr may not be empty");
219 * Allocate pointers for the utility name, the utility arguments,
220 * the maximum arguments to be read from stdin and the trailing
223 linelen
= 1 + argc
+ nargs
+ 1;
224 if ((av
= bxp
= malloc(linelen
* sizeof(char **))) == NULL
)
225 errx(1, "malloc failed");
228 * Use the user's name for the utility as argv[0], just like the
229 * shell. Echo is the default. Set up pointers for the user's
233 cnt
= strlen(*bxp
++ = echo
);
236 if (Jflag
&& strcmp(*argv
, replstr
) == 0) {
240 for (avj
= argv
; *avj
; avj
++)
241 cnt
+= strlen(*avj
) + 1;
244 cnt
+= strlen(*bxp
++ = *argv
) + 1;
245 } while (*++argv
!= NULL
);
249 * Set up begin/end/traversing pointers into the array. The -n
250 * count doesn't include the trailing NULL pointer, so the malloc
251 * added in an extra slot.
253 endxp
= (xp
= bxp
) + nargs
;
256 * Allocate buffer space for the arguments read from stdin and the
257 * trailing NULL. Buffer space is defined as the default or specified
258 * space, minus the length of the utility name and arguments. Set up
259 * begin/end/traversing pointers into the array. The -s count does
260 * include the trailing NULL, so the malloc didn't add in an extra
265 errx(1, "insufficient space for command");
267 if ((bbp
= malloc((size_t)(nline
+ 1))) == NULL
)
268 errx(1, "malloc failed");
269 ebp
= (argp
= p
= bbp
) + nline
- 1;
271 parse_input(argc
, argv
);
275 parse_input(int argc
, char *argv
[])
282 switch (ch
= getchar()) {
284 /* No arguments since last exec. */
286 waitchildren(*argv
, 1);
292 /* Quotes escape tabs and spaces. */
293 if (insingle
|| indouble
|| zflag
)
299 * Increment 'count', so that nulls will be treated
300 * as end-of-line, as well as end-of-argument. This
301 * is needed so -0 works properly with -I and -L.
310 count
++; /* Indicate end-of-line (used by -L) */
312 /* Quotes do not escape newlines. */
313 arg1
: if (insingle
|| indouble
)
314 errx(1, "unterminated quote");
316 foundeof
= *eofstr
!= '\0' &&
317 strncmp(argp
, eofstr
, (size_t)(p
- argp
)) == 0;
319 /* Do not make empty args unless they are quoted */
320 if ((argp
!= p
|| wasquoted
) && !foundeof
) {
330 * If this string is not zero
331 * length, append a space for
332 * separation before the next
335 if ((curlen
= strlen(inpline
)) != 0)
336 (void)strcat(inpline
, " ");
340 * Allocate enough to hold what we will
341 * be holding in a second, and to append
342 * a space next time through, if we have
345 inpline
= realloc(inpline
, curlen
+ 2 +
348 errx(1, "realloc failed");
350 (void)strcpy(inpline
, argp
);
352 (void)strcat(inpline
, argp
);
357 * If max'd out on args or buffer, or reached EOF,
358 * run the command. If xflag and max'd out on buffer
359 * but not on args, object. Having reached the limit
360 * of input lines, as specified by -L is the same as
361 * maxing out on arguments.
363 if (xp
== endxp
|| p
> ebp
|| ch
== EOF
||
364 (Lflag
<= count
&& xflag
) || foundeof
) {
365 if (xflag
&& xp
!= endxp
&& p
> ebp
)
366 errx(1, "insufficient space for arguments");
368 for (avj
= argv
; *avj
; avj
++)
372 if (ch
== EOF
|| foundeof
) {
373 waitchildren(*argv
, 1);
384 if (indouble
|| zflag
)
386 insingle
= !insingle
;
390 if (insingle
|| zflag
)
392 indouble
= !indouble
;
398 /* Backslash escapes anything, is escaped by quotes. */
399 if (!insingle
&& !indouble
&& (ch
= getchar()) == EOF
)
400 errx(1, "backslash at EOF");
403 addch
: if (p
< ebp
) {
408 /* If only one argument, not enough buffer space. */
410 errx(1, "insufficient space for argument");
411 /* Didn't hit argument limit, so if xflag object. */
413 errx(1, "insufficient space for arguments");
416 for (avj
= argv
; *avj
; avj
++)
422 (void)memcpy(bbp
, argp
, (size_t)cnt
);
423 p
= (argp
= bbp
) + cnt
;
430 * Do things necessary before run()'ing, such as -I substitution,
431 * and then call run().
434 prerun(int argc
, char *argv
[])
436 char **tmp
, **tmp2
, **avj
;
441 if (argc
== 0 || repls
== 0) {
450 * Allocate memory to hold the argument list, and
451 * a NULL at the tail.
453 tmp
= malloc((argc
+ 1) * sizeof(char**));
455 errx(1, "malloc failed");
459 * Save the first argument and iterate over it, we
460 * cannot do strnsubst() to it.
462 if ((*tmp
++ = strdup(*avj
++)) == NULL
)
463 errx(1, "strdup failed");
466 * For each argument to utility, if we have not used up
467 * the number of replacements we are allowed to do, and
468 * if the argument contains at least one occurrence of
469 * replstr, call strnsubst(), else just save the string.
470 * Iterations over elements of avj and tmp are done
475 if (repls
&& strstr(*tmp
, replstr
) != NULL
) {
476 strnsubst(tmp
++, replstr
, inpline
, (size_t)Sflag
);
480 if ((*tmp
= strdup(*tmp
)) == NULL
)
481 errx(1, "strdup failed");
493 * Walk from the tail to the head, free along the way.
495 for (; tmp2
!= tmp
; tmp
--)
498 * Now free the list itself.
503 * Free the input line buffer, if we have one.
505 if (inpline
!= NULL
) {
518 * If the user wants to be notified of each command before it is
519 * executed, notify them. If they want the notification to be
520 * followed by a prompt, then prompt them.
522 if (tflag
|| pflag
) {
523 (void)fprintf(stderr
, "%s", *argv
);
524 for (avec
= argv
+ 1; *avec
!= NULL
; ++avec
)
525 (void)fprintf(stderr
, " %s", *avec
);
527 * If the user has asked to be prompted, do so.
531 * If they asked not to exec, return without execution
532 * but if they asked to, go to the execution. If we
533 * could not open their tty, break the switch and drop
534 * back to -t behaviour.
544 (void)fprintf(stderr
, "\n");
545 (void)fflush(stderr
);
555 if ((fd
= open(_PATH_TTY
, O_RDONLY
)) == -1)
556 err(1, "can't open /dev/tty");
558 fd
= open(_PATH_DEVNULL
, O_RDONLY
);
560 if (fd
> STDIN_FILENO
) {
561 if (dup2(fd
, STDIN_FILENO
) != 0)
562 err(1, "can't dup2 to stdin");
565 (void)execvp(argv
[0], argv
);
570 waitchildren(*argv
, 0);
574 waitchildren(const char *name
, int waitall
)
579 while ((pid
= waitpid(-1, &status
, !waitall
&& curprocs
< maxprocs
?
582 /* If we couldn't invoke the utility, exit. */
585 err(errno
== ENOENT
? 127 : 126, "%s", name
);
588 * According to POSIX, we have to exit if the utility exits
589 * with a 255 status, or is interrupted by a signal. xargs
590 * is allowed to return any exit status between 1 and 125
591 * in these cases, but we'll use 124 and 125, the same
592 * values used by GNU xargs.
594 if (WIFEXITED(status
)) {
595 if (WEXITSTATUS (status
) == 255) {
596 warnx ("%s exited with status 255", name
);
598 } else if (WEXITSTATUS (status
) != 0) {
601 } else if (WIFSIGNALED (status
)) {
602 if (WTERMSIG(status
) < NSIG
) {
603 warnx("%s terminated by SIG%s", name
,
604 sys_signame
[WTERMSIG(status
)]);
606 warnx("%s terminated by signal %d", name
,
612 if (pid
== -1 && errno
!= ECHILD
)
617 * Prompt the user about running a command.
628 if ((ttyfp
= fopen(_PATH_TTY
, "r")) == NULL
)
629 return (2); /* Indicate that the TTY failed to open. */
630 (void)fprintf(stderr
, "?...");
631 (void)fflush(stderr
);
632 if ((response
= fgetln(ttyfp
, &rsize
)) == NULL
||
633 regcomp(&cre
, nl_langinfo(YESEXPR
), REG_BASIC
) != 0) {
637 response
[rsize
- 1] = '\0';
638 match
= regexec(&cre
, response
, 0, NULL
, 0);
647 (void)fprintf(stderr
,
648 "Usage: %s [-0opt] [-E eofstr] [-I replstr [-R replacements] [-S replsize]]\n"
649 " [-J replstr] [-L number] [-n number [-x]] [-P maxprocs]\n"
650 " [-s size] [utility [argument ...]]\n", getprogname());