]>
git.saurik.com Git - apple/shell_cmds.git/blob - xargs/xargs.c
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 $
41 static const char copyright
[] =
42 "@(#) Copyright (c) 1990, 1993\n\
43 The Regents of the University of California. All rights reserved.\n";
47 static char sccsid
[] = "@(#)xargs.c 8.1 (Berkeley) 6/6/93";
50 #include <sys/cdefs.h>
51 __FBSDID("$FreeBSD: src/usr.bin/xargs/xargs.c,v 1.57 2005/02/27 02:01:31 gad Exp $");
53 #include <sys/param.h>
68 #include "pathnames.h"
71 #include <get_compat.h>
73 #define COMPAT_MODE(a,b) (1)
74 #endif /* __APPLE__ */
76 static void parse_input(int, char *[]);
77 static void prerun(int, char *[]);
78 static int prompt(void);
79 static void run(char **);
80 static void usage(void);
81 void strnsubst(char **, const char *, const char *, size_t);
82 static void waitchildren(const char *, int);
84 static int last_was_newline
= 1;
85 static int last_was_blank
= 0;
87 static char echo
[] = _PATH_ECHO
;
88 static char **av
, **bxp
, **ep
, **endxp
, **xp
;
89 static char *argp
, *bbp
, *ebp
, *inpline
, *p
, *replstr
;
90 static const char *eofstr
;
91 static int count
, insingle
, indouble
, oflag
, pflag
, tflag
, Rflag
, rval
, zflag
;
92 static int cnt
, Iflag
, jfound
, Lflag
, wasquoted
, xflag
;
93 static int curprocs
, maxprocs
;
94 static size_t pad9314053
;
96 static volatile int childerr
;
98 extern char **environ
;
101 main(int argc
, char *argv
[])
104 int ch
, Jflag
, nflag
, nline
;
109 inpline
= replstr
= NULL
;
114 (void)setlocale(LC_ALL
, "");
117 * POSIX.2 limits the exec line length to ARG_MAX - 2K. Running that
118 * caused some E2BIG errors, so it was changed to ARG_MAX - 4K. Given
119 * that the smallest argument is 2 bytes in length, this means that
120 * the number of arguments is limited to:
122 * (ARG_MAX - 4K - LENGTH(utility + arguments)) / 2.
124 * We arbitrarily limit the number of arguments to 5000. This is
125 * allowed by POSIX.2 as long as the resulting minimum exec line is
126 * at least LINE_MAX. Realloc'ing as necessary is possible, but
127 * probably not worthwhile.
130 if ((arg_max
= sysconf(_SC_ARG_MAX
)) == -1)
131 errx(1, "sysconf(_SC_ARG_MAX) failed");
132 nline
= arg_max
- MAXPATHLEN
; /* for argv[0] from execvp() */
133 pad9314053
= sizeof(char *); /* reserve for string area rounding */
134 while (*ep
!= NULL
) {
135 /* 1 byte for each '\0' */
136 nline
-= strlen(*ep
++) + 1 + sizeof(*ep
);
140 while ((ch
= getopt(argc
, argv
, "0E:I:J:L:n:oP:pR:s:tx")) != -1)
157 Lflag
= atoi(optarg
);
158 if (COMPAT_MODE("bin/xargs", "Unix2003")) {
159 nflag
= 0; /* Override */
165 if ((nargs
= strtol(optarg
, NULL
, 10)) <= 0)
166 errx(1, "illegal argument count");
167 if (COMPAT_MODE("bin/xargs", "Unix2003")) {
168 Lflag
= 0; /* Override */
175 if ((maxprocs
= atoi(optarg
)) <= 0)
176 errx(1, "max. processes must be >0");
182 Rflag
= strtol(optarg
, &endptr
, 10);
184 errx(1, "replacements must be a number");
187 nline
= atoi(optarg
);
188 pad9314053
= 0; /* assume the -s value is valid */
214 if (replstr
!= NULL
&& *replstr
== '\0')
215 errx(1, "replstr may not be empty");
218 * Allocate pointers for the utility name, the utility arguments,
219 * the maximum arguments to be read from stdin and the trailing
222 linelen
= 1 + argc
+ nargs
+ 1;
223 if ((av
= bxp
= malloc(linelen
* sizeof(char **))) == NULL
)
224 errx(1, "malloc failed");
227 * Use the user's name for the utility as argv[0], just like the
228 * shell. Echo is the default. Set up pointers for the user's
232 cnt
= strlen(*bxp
++ = echo
) + pad9314053
;
235 if (Jflag
&& strcmp(*argv
, replstr
) == 0) {
239 for (avj
= argv
; *avj
; avj
++)
240 cnt
+= strlen(*avj
) + 1 + pad9314053
;
243 cnt
+= strlen(*bxp
++ = *argv
) + 1 + pad9314053
;
244 } while (*++argv
!= NULL
);
248 * Set up begin/end/traversing pointers into the array. The -n
249 * count doesn't include the trailing NULL pointer, so the malloc
250 * added in an extra slot.
252 endxp
= (xp
= bxp
) + nargs
;
255 * Allocate buffer space for the arguments read from stdin and the
256 * trailing NULL. Buffer space is defined as the default or specified
257 * space, minus the length of the utility name and arguments. Set up
258 * begin/end/traversing pointers into the array. The -s count does
259 * include the trailing NULL, so the malloc didn't add in an extra
264 errx(1, "insufficient space for command");
266 if ((bbp
= malloc((size_t)(nline
+ 1))) == NULL
)
267 errx(1, "malloc failed");
268 ebp
= (argp
= p
= bbp
) + nline
- 1;
270 parse_input(argc
, argv
);
274 parse_input(int argc
, char *argv
[])
278 int last_was_backslashed
= 0;
282 switch(ch
= getchar()) {
284 /* No arguments since last exec. */
286 waitchildren(*argv
, 1);
293 /* Quotes escape tabs and spaces. */
294 if (insingle
|| indouble
|| zflag
)
300 * Increment 'count', so that nulls will be treated
301 * as end-of-line, as well as end-of-argument. This
302 * is needed so -0 works properly with -I and -L.
311 if (COMPAT_MODE("bin/xargs", "Unix2003")) {
312 if (last_was_newline
) {
313 /* don't count empty line */
316 if (!last_was_blank
) {
317 /* only count if NOT continuation line */
323 last_was_newline
= 1;
325 /* Quotes do not escape newlines. */
326 arg1
: if (insingle
|| indouble
)
327 errx(1, "unterminated quote");
329 foundeof
= *eofstr
!= '\0' &&
330 strcmp(argp
, eofstr
) == 0;
333 /* 6591323: -I specifies that it processes the entire line,
334 * so only recognize eofstr at the end of a line. */
335 if (Iflag
&& !last_was_newline
)
338 /* 6591323: Essentially the same as the EOF handling above. */
339 if (foundeof
&& (p
- strlen(eofstr
) == bbp
)) {
340 waitchildren(*argv
, 1);
345 /* Do not make empty args unless they are quoted */
346 if ((argp
!= p
|| wasquoted
) && !foundeof
) {
356 * If this string is not zero
357 * length, append a space for
358 * separation before the next
361 if ((curlen
= strlen(inpline
)))
362 strcat(inpline
, " ");
366 * Allocate enough to hold what we will
367 * be holding in a second, and to append
368 * a space next time through, if we have
371 inpline
= realloc(inpline
, curlen
+ 2 +
374 errx(1, "realloc failed");
376 strcpy(inpline
, argp
);
378 strcat(inpline
, argp
);
383 * If max'd out on args or buffer, or reached EOF,
384 * run the command. If xflag and max'd out on buffer
385 * but not on args, object. Having reached the limit
386 * of input lines, as specified by -L is the same as
387 * maxing out on arguments.
389 if (xp
== endxp
|| p
+ (count
* pad9314053
) > ebp
|| ch
== EOF
||
390 (Lflag
<= count
&& xflag
) || foundeof
) {
391 if (xflag
&& xp
!= endxp
&& p
+ (count
* pad9314053
) > ebp
)
392 errx(1, "insufficient space for arguments");
394 for (avj
= argv
; *avj
; avj
++)
398 if (ch
== EOF
|| foundeof
) {
399 waitchildren(*argv
, 1);
410 if (indouble
|| zflag
)
412 insingle
= !insingle
;
416 if (insingle
|| zflag
)
418 indouble
= !indouble
;
422 last_was_backslashed
= 1;
425 /* Backslash escapes anything, is escaped by quotes. */
426 if (!insingle
&& !indouble
&& (ch
= getchar()) == EOF
)
427 errx(1, "backslash at EOF");
430 addch
: if (p
< ebp
) {
435 /* If only one argument, not enough buffer space. */
437 errx(1, "insufficient space for argument");
438 /* Didn't hit argument limit, so if xflag object. */
440 errx(1, "insufficient space for arguments");
443 for (avj
= argv
; *avj
; avj
++)
449 memcpy(bbp
, argp
, (size_t)cnt
);
450 p
= (argp
= bbp
) + cnt
;
456 if (ch
!= '\n' || last_was_backslashed
)
457 last_was_newline
= 0;
461 * Do things necessary before run()'ing, such as -I substitution,
462 * and then call run().
465 prerun(int argc
, char *argv
[])
467 char **tmp
, **tmp2
, **avj
;
472 if (argc
== 0 || repls
== 0) {
481 * Allocate memory to hold the argument list, and
482 * a NULL at the tail.
484 tmp
= malloc((argc
+ 1) * sizeof(char**));
486 errx(1, "malloc failed");
490 * Save the first argument and iterate over it, we
491 * cannot do strnsubst() to it.
493 if ((*tmp
++ = strdup(*avj
++)) == NULL
)
494 errx(1, "strdup failed");
497 * For each argument to utility, if we have not used up
498 * the number of replacements we are allowed to do, and
499 * if the argument contains at least one occurrence of
500 * replstr, call strnsubst(), else just save the string.
501 * Iterations over elements of avj and tmp are done
506 if (repls
&& strstr(*tmp
, replstr
) != NULL
) {
507 strnsubst(tmp
++, replstr
, inpline
, (size_t)255);
511 if ((*tmp
= strdup(*tmp
)) == NULL
)
512 errx(1, "strdup failed");
524 * Walk from the tail to the head, free along the way.
526 for (; tmp2
!= tmp
; tmp
--)
529 * Now free the list itself.
534 * Free the input line buffer, if we have one.
536 if (inpline
!= NULL
) {
550 * If the user wants to be notified of each command before it is
551 * executed, notify them. If they want the notification to be
552 * followed by a prompt, then prompt them.
554 if (tflag
|| pflag
) {
555 (void)fprintf(stderr
, "%s", *argv
);
556 for (avec
= argv
+ 1; *avec
!= NULL
; ++avec
)
557 (void)fprintf(stderr
, " %s", *avec
);
559 * If the user has asked to be prompted, do so.
563 * If they asked not to exec, return without execution
564 * but if they asked to, go to the execution. If we
565 * could not open their tty, break the switch and drop
566 * back to -t behaviour.
576 (void)fprintf(stderr
, "\n");
577 (void)fflush(stderr
);
581 switch(pid
= vfork()) {
586 if ((fd
= open(_PATH_TTY
, O_RDONLY
)) == -1)
587 err(1, "can't open /dev/tty");
589 fd
= open(_PATH_DEVNULL
, O_RDONLY
);
591 if (fd
> STDIN_FILENO
) {
592 if (dup2(fd
, STDIN_FILENO
) != 0)
593 err(1, "can't dup2 to stdin");
596 execvp(argv
[0], argv
);
601 waitchildren(*argv
, 0);
605 waitchildren(const char *name
, int waitall
)
610 while ((pid
= waitpid(-1, &status
, !waitall
&& curprocs
< maxprocs
?
613 /* If we couldn't invoke the utility, exit. */
616 err(errno
== ENOENT
? 127 : 126, "%s", name
);
619 * If utility signaled or exited with a value of 255,
622 if (WIFSIGNALED(status
) || WEXITSTATUS(status
) == 255)
624 if (WEXITSTATUS(status
))
627 if (pid
== -1 && errno
!= ECHILD
)
632 * Prompt the user about running a command.
643 if ((ttyfp
= fopen(_PATH_TTY
, "r")) == NULL
)
644 return (2); /* Indicate that the TTY failed to open. */
645 (void)fprintf(stderr
, "?...");
646 (void)fflush(stderr
);
647 if ((response
= fgetln(ttyfp
, &rsize
)) == NULL
||
648 regcomp(&cre
, nl_langinfo(YESEXPR
), REG_BASIC
) != 0) {
652 match
= regexec(&cre
, response
, 0, NULL
, 0);
662 "usage: xargs [-0opt] [-E eofstr] [-I replstr [-R replacements]] [-J replstr]\n"
663 " [-L number] [-n number [-x]] [-P maxprocs] [-s size]\n"
664 " [utility [argument ...]]\n");