]> git.saurik.com Git - apple/shell_cmds.git/blame - xargs/xargs.c
shell_cmds-116.tar.gz
[apple/shell_cmds.git] / xargs / xargs.c
CommitLineData
44bd5ea7
A
1/*-
2 * Copyright (c) 1990, 1993
3 * The Regents of the University of California. All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * John B. Roll Jr.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
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.
23 *
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
34 * SUCH DAMAGE.
9bafe280
A
35 *
36 * $xMach: xargs.c,v 1.6 2002/02/23 05:27:47 tim Exp $
44bd5ea7
A
37 */
38
e1a085ba 39#if 0
44bd5ea7 40#ifndef lint
9bafe280
A
41static const char copyright[] =
42"@(#) Copyright (c) 1990, 1993\n\
43 The Regents of the University of California. All rights reserved.\n";
44bd5ea7
A
44#endif /* not lint */
45
9bafe280 46#ifndef lint
44bd5ea7 47static char sccsid[] = "@(#)xargs.c 8.1 (Berkeley) 6/6/93";
44bd5ea7 48#endif /* not lint */
9bafe280 49#endif
9bafe280 50#include <sys/cdefs.h>
e1a085ba 51__FBSDID("$FreeBSD: src/usr.bin/xargs/xargs.c,v 1.57 2005/02/27 02:01:31 gad Exp $");
44bd5ea7 52
e1a085ba 53#include <sys/param.h>
44bd5ea7 54#include <sys/wait.h>
9bafe280
A
55
56#include <err.h>
44bd5ea7 57#include <errno.h>
e1a085ba
A
58#include <fcntl.h>
59#include <langinfo.h>
9bafe280
A
60#include <locale.h>
61#include <paths.h>
62#include <regex.h>
44bd5ea7
A
63#include <stdio.h>
64#include <stdlib.h>
65#include <string.h>
66#include <unistd.h>
9bafe280 67
44bd5ea7
A
68#include "pathnames.h"
69
1a5bac72
A
70#ifdef __APPLE__
71#include <get_compat.h>
72#else
73#define COMPAT_MODE(a,b) (1)
74#endif /* __APPLE__ */
75
9bafe280
A
76static void parse_input(int, char *[]);
77static void prerun(int, char *[]);
78static int prompt(void);
79static void run(char **);
80static void usage(void);
81void strnsubst(char **, const char *, const char *, size_t);
e1a085ba
A
82static void waitchildren(const char *, int);
83
84static int last_was_newline = 1;
85static int last_was_blank = 0;
9bafe280
A
86
87static char echo[] = _PATH_ECHO;
e1a085ba 88static char **av, **bxp, **ep, **endxp, **xp;
9bafe280
A
89static char *argp, *bbp, *ebp, *inpline, *p, *replstr;
90static const char *eofstr;
e1a085ba 91static int count, insingle, indouble, oflag, pflag, tflag, Rflag, rval, zflag;
9bafe280 92static int cnt, Iflag, jfound, Lflag, wasquoted, xflag;
e1a085ba
A
93static int curprocs, maxprocs;
94
95static volatile int childerr;
44bd5ea7 96
9bafe280 97extern char **environ;
44bd5ea7
A
98
99int
9bafe280 100main(int argc, char *argv[])
44bd5ea7 101{
9bafe280
A
102 long arg_max;
103 int ch, Jflag, nargs, nflag, nline;
104 size_t linelen;
e1a085ba 105 char *endptr;
44bd5ea7 106
9bafe280
A
107 inpline = replstr = NULL;
108 ep = environ;
109 eofstr = "";
110 Jflag = nflag = 0;
44bd5ea7 111
e1a085ba
A
112 (void)setlocale(LC_ALL, "");
113
44bd5ea7
A
114 /*
115 * POSIX.2 limits the exec line length to ARG_MAX - 2K. Running that
116 * caused some E2BIG errors, so it was changed to ARG_MAX - 4K. Given
117 * that the smallest argument is 2 bytes in length, this means that
118 * the number of arguments is limited to:
119 *
120 * (ARG_MAX - 4K - LENGTH(utility + arguments)) / 2.
121 *
122 * We arbitrarily limit the number of arguments to 5000. This is
123 * allowed by POSIX.2 as long as the resulting minimum exec line is
124 * at least LINE_MAX. Realloc'ing as necessary is possible, but
125 * probably not worthwhile.
126 */
127 nargs = 5000;
9bafe280
A
128 if ((arg_max = sysconf(_SC_ARG_MAX)) == -1)
129 errx(1, "sysconf(_SC_ARG_MAX) failed");
130 nline = arg_max - 4 * 1024;
131 while (*ep != NULL) {
132 /* 1 byte for each '\0' */
133 nline -= strlen(*ep++) + 1 + sizeof(*ep);
134 }
e1a085ba
A
135 maxprocs = 1;
136 while ((ch = getopt(argc, argv, "0E:I:J:L:n:oP:pR:s:tx")) != -1)
44bd5ea7 137 switch(ch) {
9bafe280
A
138 case 'E':
139 eofstr = optarg;
140 break;
141 case 'I':
142 Jflag = 0;
143 Iflag = 1;
144 Lflag = 1;
145 replstr = optarg;
146 break;
147 case 'J':
148 Iflag = 0;
149 Jflag = 1;
150 replstr = optarg;
151 break;
152 case 'L':
153 Lflag = atoi(optarg);
1a5bac72
A
154 if (COMPAT_MODE("bin/xargs", "Unix2003")) {
155 nflag = 0; /* Override */
156 nargs = 5000;
157 }
44bd5ea7
A
158 break;
159 case 'n':
160 nflag = 1;
e1a085ba
A
161 if ((nargs = atoi(optarg)) <= 0)
162 errx(1, "illegal argument count");
1a5bac72
A
163 if (COMPAT_MODE("bin/xargs", "Unix2003")) {
164 Lflag = 0; /* Override */
165 }
e1a085ba
A
166 break;
167 case 'o':
168 oflag = 1;
169 break;
170 case 'P':
171 if ((maxprocs = atoi(optarg)) <= 0)
172 errx(1, "max. processes must be >0");
44bd5ea7 173 break;
9bafe280
A
174 case 'p':
175 pflag = 1;
176 break;
177 case 'R':
e1a085ba
A
178 Rflag = strtol(optarg, &endptr, 10);
179 if (*endptr != '\0')
180 errx(1, "replacements must be a number");
9bafe280 181 break;
44bd5ea7
A
182 case 's':
183 nline = atoi(optarg);
184 break;
185 case 't':
186 tflag = 1;
187 break;
188 case 'x':
189 xflag = 1;
190 break;
9bafe280
A
191 case '0':
192 zflag = 1;
193 break;
44bd5ea7
A
194 case '?':
195 default:
196 usage();
197 }
198 argc -= optind;
199 argv += optind;
200
9bafe280
A
201 if (!Iflag && Rflag)
202 usage();
203 if (Iflag && !Rflag)
204 Rflag = 5;
44bd5ea7
A
205 if (xflag && !nflag)
206 usage();
9bafe280
A
207 if (Iflag || Lflag)
208 xflag = 1;
209 if (replstr != NULL && *replstr == '\0')
210 errx(1, "replstr may not be empty");
44bd5ea7
A
211
212 /*
213 * Allocate pointers for the utility name, the utility arguments,
214 * the maximum arguments to be read from stdin and the trailing
215 * NULL.
216 */
9bafe280
A
217 linelen = 1 + argc + nargs + 1;
218 if ((av = bxp = malloc(linelen * sizeof(char **))) == NULL)
219 errx(1, "malloc failed");
44bd5ea7
A
220
221 /*
222 * Use the user's name for the utility as argv[0], just like the
223 * shell. Echo is the default. Set up pointers for the user's
224 * arguments.
225 */
9bafe280
A
226 if (*argv == NULL)
227 cnt = strlen(*bxp++ = echo);
44bd5ea7 228 else {
44bd5ea7 229 do {
9bafe280
A
230 if (Jflag && strcmp(*argv, replstr) == 0) {
231 char **avj;
232 jfound = 1;
233 argv++;
234 for (avj = argv; *avj; avj++)
235 cnt += strlen(*avj) + 1;
236 break;
237 }
44bd5ea7 238 cnt += strlen(*bxp++ = *argv) + 1;
9bafe280 239 } while (*++argv != NULL);
44bd5ea7
A
240 }
241
242 /*
243 * Set up begin/end/traversing pointers into the array. The -n
244 * count doesn't include the trailing NULL pointer, so the malloc
245 * added in an extra slot.
246 */
e1a085ba 247 endxp = (xp = bxp) + nargs;
44bd5ea7
A
248
249 /*
250 * Allocate buffer space for the arguments read from stdin and the
251 * trailing NULL. Buffer space is defined as the default or specified
252 * space, minus the length of the utility name and arguments. Set up
253 * begin/end/traversing pointers into the array. The -s count does
254 * include the trailing NULL, so the malloc didn't add in an extra
255 * slot.
256 */
257 nline -= cnt;
258 if (nline <= 0)
259 errx(1, "insufficient space for command");
260
9bafe280
A
261 if ((bbp = malloc((size_t)(nline + 1))) == NULL)
262 errx(1, "malloc failed");
44bd5ea7 263 ebp = (argp = p = bbp) + nline - 1;
9bafe280
A
264 for (;;)
265 parse_input(argc, argv);
266}
44bd5ea7 267
9bafe280
A
268static void
269parse_input(int argc, char *argv[])
270{
271 int ch, foundeof;
272 char **avj;
1a5bac72 273 int last_was_backslashed = 0;
44bd5ea7 274
9bafe280
A
275 foundeof = 0;
276
277 switch(ch = getchar()) {
278 case EOF:
279 /* No arguments since last exec. */
e1a085ba
A
280 if (p == bbp) {
281 waitchildren(*argv, 1);
9bafe280 282 exit(rval);
e1a085ba 283 }
9bafe280
A
284 goto arg1;
285 case ' ':
1a5bac72 286 last_was_blank = 1;
9bafe280
A
287 case '\t':
288 /* Quotes escape tabs and spaces. */
289 if (insingle || indouble || zflag)
290 goto addch;
291 goto arg2;
292 case '\0':
e1a085ba
A
293 if (zflag) {
294 /*
295 * Increment 'count', so that nulls will be treated
296 * as end-of-line, as well as end-of-argument. This
297 * is needed so -0 works properly with -I and -L.
298 */
299 count++;
44bd5ea7 300 goto arg2;
e1a085ba 301 }
9bafe280
A
302 goto addch;
303 case '\n':
e1a085ba
A
304 if (zflag)
305 goto addch;
1a5bac72
A
306 if (COMPAT_MODE("bin/xargs", "Unix2003")) {
307 if (last_was_newline) {
308 /* don't count empty line */
309 break;
310 }
311 if (!last_was_blank ) {
312 /* only count if NOT continuation line */
313 count++;
314 }
315 } else {
316 count++;
317 }
318 last_was_newline = 1;
9bafe280
A
319
320 /* Quotes do not escape newlines. */
321arg1: if (insingle || indouble)
322 errx(1, "unterminated quote");
323arg2:
324 foundeof = *eofstr != '\0' &&
325 strcmp(argp, eofstr) == 0;
326
327 /* Do not make empty args unless they are quoted */
328 if ((argp != p || wasquoted) && !foundeof) {
329 *p++ = '\0';
44bd5ea7 330 *xp++ = argp;
9bafe280
A
331 if (Iflag) {
332 size_t curlen;
44bd5ea7 333
9bafe280
A
334 if (inpline == NULL)
335 curlen = 0;
336 else {
337 /*
338 * If this string is not zero
339 * length, append a space for
e1a085ba 340 * separation before the next
9bafe280
A
341 * argument.
342 */
343 if ((curlen = strlen(inpline)))
344 strcat(inpline, " ");
345 }
346 curlen++;
347 /*
348 * Allocate enough to hold what we will
349 * be holding in a second, and to append
350 * a space next time through, if we have
351 * to.
352 */
353 inpline = realloc(inpline, curlen + 2 +
354 strlen(argp));
355 if (inpline == NULL)
356 errx(1, "realloc failed");
357 if (curlen == 1)
358 strcpy(inpline, argp);
359 else
360 strcat(inpline, argp);
44bd5ea7 361 }
9bafe280 362 }
44bd5ea7 363
9bafe280
A
364 /*
365 * If max'd out on args or buffer, or reached EOF,
366 * run the command. If xflag and max'd out on buffer
367 * but not on args, object. Having reached the limit
368 * of input lines, as specified by -L is the same as
369 * maxing out on arguments.
370 */
e1a085ba 371 if (xp == endxp || p > ebp || ch == EOF ||
9bafe280 372 (Lflag <= count && xflag) || foundeof) {
e1a085ba 373 if (xflag && xp != endxp && p > ebp)
44bd5ea7 374 errx(1, "insufficient space for arguments");
9bafe280
A
375 if (jfound) {
376 for (avj = argv; *avj; avj++)
377 *xp++ = *avj;
378 }
379 prerun(argc, av);
e1a085ba
A
380 if (ch == EOF || foundeof) {
381 waitchildren(*argv, 1);
9bafe280 382 exit(rval);
e1a085ba 383 }
9bafe280 384 p = bbp;
44bd5ea7 385 xp = bxp;
9bafe280
A
386 count = 0;
387 }
388 argp = p;
389 wasquoted = 0;
390 break;
391 case '\'':
392 if (indouble || zflag)
393 goto addch;
394 insingle = !insingle;
395 wasquoted = 1;
396 break;
397 case '"':
398 if (insingle || zflag)
399 goto addch;
400 indouble = !indouble;
401 wasquoted = 1;
402 break;
403 case '\\':
1a5bac72 404 last_was_backslashed = 1;
9bafe280
A
405 if (zflag)
406 goto addch;
407 /* Backslash escapes anything, is escaped by quotes. */
408 if (!insingle && !indouble && (ch = getchar()) == EOF)
409 errx(1, "backslash at EOF");
410 /* FALLTHROUGH */
411 default:
412addch: if (p < ebp) {
44bd5ea7
A
413 *p++ = ch;
414 break;
415 }
9bafe280
A
416
417 /* If only one argument, not enough buffer space. */
418 if (bxp == xp)
419 errx(1, "insufficient space for argument");
420 /* Didn't hit argument limit, so if xflag object. */
421 if (xflag)
422 errx(1, "insufficient space for arguments");
423
424 if (jfound) {
425 for (avj = argv; *avj; avj++)
426 *xp++ = *avj;
427 }
428 prerun(argc, av);
429 xp = bxp;
430 cnt = ebp - argp;
431 memcpy(bbp, argp, (size_t)cnt);
432 p = (argp = bbp) + cnt;
433 *p++ = ch;
434 break;
435 }
1a5bac72
A
436 if (ch != ' ')
437 last_was_blank = 0;
438 if (ch != '\n' || last_was_backslashed)
439 last_was_newline = 0;
44bd5ea7
A
440}
441
9bafe280
A
442/*
443 * Do things necessary before run()'ing, such as -I substitution,
444 * and then call run().
445 */
446static void
447prerun(int argc, char *argv[])
44bd5ea7 448{
9bafe280
A
449 char **tmp, **tmp2, **avj;
450 int repls;
451
452 repls = Rflag;
453
454 if (argc == 0 || repls == 0) {
455 *xp = NULL;
456 run(argv);
457 return;
458 }
459
460 avj = argv;
461
462 /*
463 * Allocate memory to hold the argument list, and
464 * a NULL at the tail.
465 */
466 tmp = malloc((argc + 1) * sizeof(char**));
467 if (tmp == NULL)
468 errx(1, "malloc failed");
469 tmp2 = tmp;
470
471 /*
472 * Save the first argument and iterate over it, we
473 * cannot do strnsubst() to it.
474 */
475 if ((*tmp++ = strdup(*avj++)) == NULL)
476 errx(1, "strdup failed");
477
478 /*
479 * For each argument to utility, if we have not used up
480 * the number of replacements we are allowed to do, and
e1a085ba 481 * if the argument contains at least one occurrence of
9bafe280
A
482 * replstr, call strnsubst(), else just save the string.
483 * Iterations over elements of avj and tmp are done
484 * where appropriate.
485 */
486 while (--argc) {
487 *tmp = *avj++;
488 if (repls && strstr(*tmp, replstr) != NULL) {
489 strnsubst(tmp++, replstr, inpline, (size_t)255);
e1a085ba
A
490 if (repls > 0)
491 repls--;
9bafe280
A
492 } else {
493 if ((*tmp = strdup(*tmp)) == NULL)
494 errx(1, "strdup failed");
495 tmp++;
496 }
497 }
498
499 /*
500 * Run it.
501 */
502 *tmp = NULL;
503 run(tmp2);
504
505 /*
506 * Walk from the tail to the head, free along the way.
507 */
508 for (; tmp2 != tmp; tmp--)
509 free(*tmp);
510 /*
511 * Now free the list itself.
512 */
513 free(tmp2);
514
515 /*
516 * Free the input line buffer, if we have one.
517 */
518 if (inpline != NULL) {
519 free(inpline);
520 inpline = NULL;
521 }
522}
523
524static void
525run(char **argv)
526{
44bd5ea7 527 pid_t pid;
e1a085ba
A
528 int fd;
529 char **avec;
44bd5ea7 530
9bafe280
A
531 /*
532 * If the user wants to be notified of each command before it is
533 * executed, notify them. If they want the notification to be
534 * followed by a prompt, then prompt them.
535 */
536 if (tflag || pflag) {
44bd5ea7 537 (void)fprintf(stderr, "%s", *argv);
9bafe280
A
538 for (avec = argv + 1; *avec != NULL; ++avec)
539 (void)fprintf(stderr, " %s", *avec);
540 /*
541 * If the user has asked to be prompted, do so.
542 */
543 if (pflag)
544 /*
545 * If they asked not to exec, return without execution
546 * but if they asked to, go to the execution. If we
547 * could not open their tty, break the switch and drop
548 * back to -t behaviour.
549 */
550 switch (prompt()) {
551 case 0:
552 return;
553 case 1:
554 goto exec;
555 case 2:
556 break;
557 }
44bd5ea7
A
558 (void)fprintf(stderr, "\n");
559 (void)fflush(stderr);
560 }
9bafe280
A
561exec:
562 childerr = 0;
44bd5ea7
A
563 switch(pid = vfork()) {
564 case -1:
565 err(1, "vfork");
566 case 0:
e1a085ba
A
567 if (oflag) {
568 if ((fd = open(_PATH_TTY, O_RDONLY)) == -1)
569 err(1, "can't open /dev/tty");
570 } else {
571 fd = open(_PATH_DEVNULL, O_RDONLY);
572 }
573 if (fd > STDIN_FILENO) {
574 if (dup2(fd, STDIN_FILENO) != 0)
575 err(1, "can't dup2 to stdin");
576 close(fd);
577 }
44bd5ea7 578 execvp(argv[0], argv);
9bafe280 579 childerr = errno;
44bd5ea7
A
580 _exit(1);
581 }
e1a085ba
A
582 curprocs++;
583 waitchildren(*argv, 0);
584}
585
586static void
587waitchildren(const char *name, int waitall)
588{
589 pid_t pid;
590 int status;
591
592 while ((pid = waitpid(-1, &status, !waitall && curprocs < maxprocs ?
593 WNOHANG : 0)) > 0) {
594 curprocs--;
595 /* If we couldn't invoke the utility, exit. */
596 if (childerr != 0) {
597 errno = childerr;
598 err(errno == ENOENT ? 127 : 126, "%s", name);
599 }
600 /*
601 * If utility signaled or exited with a value of 255,
602 * exit 1-125.
603 */
604 if (WIFSIGNALED(status) || WEXITSTATUS(status) == 255)
605 exit(1);
606 if (WEXITSTATUS(status))
607 rval = 1;
608 }
609 if (pid == -1 && errno != ECHILD)
610 err(1, "wait3");
9bafe280 611}
44bd5ea7 612
9bafe280
A
613/*
614 * Prompt the user about running a command.
615 */
616static int
617prompt(void)
618{
619 regex_t cre;
620 size_t rsize;
621 int match;
622 char *response;
623 FILE *ttyfp;
44bd5ea7 624
9bafe280
A
625 if ((ttyfp = fopen(_PATH_TTY, "r")) == NULL)
626 return (2); /* Indicate that the TTY failed to open. */
627 (void)fprintf(stderr, "?...");
628 (void)fflush(stderr);
629 if ((response = fgetln(ttyfp, &rsize)) == NULL ||
e1a085ba 630 regcomp(&cre, nl_langinfo(YESEXPR), REG_BASIC) != 0) {
9bafe280
A
631 (void)fclose(ttyfp);
632 return (0);
44bd5ea7 633 }
9bafe280
A
634 match = regexec(&cre, response, 0, NULL, 0);
635 (void)fclose(ttyfp);
636 regfree(&cre);
637 return (match == 0);
44bd5ea7
A
638}
639
9bafe280
A
640static void
641usage(void)
44bd5ea7 642{
9bafe280 643 fprintf(stderr,
e1a085ba
A
644"usage: xargs [-0opt] [-E eofstr] [-I replstr [-R replacements]] [-J replstr]\n"
645" [-L number] [-n number [-x]] [-P maxprocs] [-s size]\n"
646" [utility [argument ...]]\n");
44bd5ea7
A
647 exit(1);
648}