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