Indicate that the infinite loop with "-L" has possible security
[findutils.git] / xargs / xargs.c
blob2970768835bca8a778dcb41127a235883fcc50d7
1 /* xargs -- build and execute command lines from standard input
2 Copyright (C) 1990, 91, 92, 93, 94, 2000, 2003, 2005 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
7 any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
17 USA.
20 /* Written by Mike Rendell <michael@cs.mun.ca>
21 and David MacKenzie <djm@gnu.org>. */
23 #include <config.h>
25 # ifndef PARAMS
26 # if defined PROTOTYPES || (defined __STDC__ && __STDC__)
27 # define PARAMS(Args) Args
28 # else
29 # define PARAMS(Args) ()
30 # endif
31 # endif
33 #include <ctype.h>
35 #if !defined (isascii) || defined (STDC_HEADERS)
36 #ifdef isascii
37 #undef isascii
38 #endif
39 #define isascii(c) 1
40 #endif
42 #ifdef isblank
43 #define ISBLANK(c) (isascii (c) && isblank (c))
44 #else
45 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
46 #endif
48 #define ISSPACE(c) (ISBLANK (c) || (c) == '\n' || (c) == '\r' \
49 || (c) == '\f' || (c) == '\v')
51 #include <sys/types.h>
52 #include <stdio.h>
53 #include <errno.h>
54 #include <getopt.h>
55 #include <fcntl.h>
57 #if defined(STDC_HEADERS)
58 #include <assert.h>
59 #endif
61 #if defined(HAVE_STRING_H) || defined(STDC_HEADERS)
62 #include <string.h>
63 #if !defined(STDC_HEADERS)
64 #include <memory.h>
65 #endif
66 #else
67 #include <strings.h>
68 #define memcpy(dest, source, count) (bcopy((source), (dest), (count)))
69 #endif
71 #ifndef _POSIX_SOURCE
72 #include <sys/param.h>
73 #endif
75 #ifdef HAVE_LIMITS_H
76 #include <limits.h>
77 #endif
79 #ifndef LONG_MAX
80 #define LONG_MAX (~(1 << (sizeof (long) * 8 - 1)))
81 #endif
83 #ifdef HAVE_UNISTD_H
84 #include <unistd.h>
85 #endif
87 #include <signal.h>
89 #if !defined(SIGCHLD) && defined(SIGCLD)
90 #define SIGCHLD SIGCLD
91 #endif
93 #include "wait.h"
95 /* States for read_line. */
96 #define NORM 0
97 #define SPACE 1
98 #define QUOTE 2
99 #define BACKSLASH 3
101 #ifdef STDC_HEADERS
102 #include <stdlib.h>
103 #else
104 extern int errno;
105 #endif
107 #ifdef HAVE_LOCALE_H
108 #include <locale.h>
109 #endif
110 #if ENABLE_NLS
111 # include <libintl.h>
112 # define _(Text) gettext (Text)
113 #else
114 # define _(Text) Text
115 #define textdomain(Domain)
116 #define bindtextdomain(Package, Directory)
117 #endif
118 #ifdef gettext_noop
119 # define N_(String) gettext_noop (String)
120 #else
121 /* See locate.c for explanation as to why not use (String) */
122 # define N_(String) String
123 #endif
125 #include "buildcmd.h"
128 /* Return nonzero if S is the EOF string. */
129 #define EOF_STR(s) (eof_str && *eof_str == *s && !strcmp (eof_str, s))
131 extern char **environ;
133 /* Do multibyte processing if multibyte characters are supported,
134 unless multibyte sequences are search safe. Multibyte sequences
135 are search safe if searching for a substring using the byte
136 comparison function 'strstr' gives no false positives. All 8-bit
137 encodings and the UTF-8 multibyte encoding are search safe, but
138 the EUC encodings are not.
139 BeOS uses the UTF-8 encoding exclusively, so it is search safe. */
140 #if defined __BEOS__
141 # define MULTIBYTE_IS_SEARCH_SAFE 1
142 #endif
143 #define DO_MULTIBYTE (HAVE_MBLEN && ! MULTIBYTE_IS_SEARCH_SAFE)
145 #if DO_MULTIBYTE
146 # if HAVE_MBRLEN
147 # include <wchar.h>
148 # else
149 /* Simulate mbrlen with mblen as best we can. */
150 # define mbstate_t int
151 # define mbrlen(s, n, ps) mblen (s, n)
152 # endif
153 #endif
155 /* Not char because of type promotion; NeXT gcc can't handle it. */
156 typedef int boolean;
157 #define true 1
158 #define false 0
160 #if __STDC__
161 #define VOID void
162 #else
163 #define VOID char
164 #endif
166 #include <xalloc.h>
167 #include "closeout.h"
169 void error PARAMS ((int status, int errnum, char *message,...));
171 extern char *version_string;
173 /* The name this program was run with. */
174 char *program_name;
176 static FILE *input_stream;
178 /* Buffer for reading arguments from input. */
179 static char *linebuf;
181 static int keep_stdin = 0;
183 /* Line number in stdin since the last command was executed. */
184 static int lineno = 0;
186 static struct buildcmd_state bc_state;
187 static struct buildcmd_control bc_ctl;
190 #if 0
191 /* If nonzero, then instead of putting the args from stdin at
192 the end of the command argument list, they are each stuck into the
193 initial args, replacing each occurrence of the `replace_pat' in the
194 initial args. */
195 static char *replace_pat = NULL;
198 /* The length of `replace_pat'. */
199 static size_t rplen = 0;
200 #endif
202 /* If nonzero, when this string is read on stdin it is treated as
203 end of file.
204 IEEE Std 1003.1, 2004 Edition allows this to be NULL.
205 In findutils releases up to and including 4.2.8, this was "_".
207 static char *eof_str = NULL;
209 #if 0
210 /* If nonzero, the maximum number of nonblank lines from stdin to use
211 per command line. */
212 static long lines_per_exec = 0;
214 /* The maximum number of arguments to use per command line. */
215 static long args_per_exec = 1024;
217 /* If true, exit if lines_per_exec or args_per_exec is exceeded. */
218 static boolean exit_if_size_exceeded = false;
219 /* The maximum number of characters that can be used per command line. */
220 static long arg_max;
221 /* Storage for elements of `cmd_argv'. */
222 static char *argbuf;
223 #endif
225 #if 0
226 /* The list of args being built. */
227 static char **cmd_argv = NULL;
229 /* Number of elements allocated for `cmd_argv'. */
230 static int cmd_argv_alloc = 0;
231 #endif
233 #if 0
234 /* Number of valid elements in `cmd_argv'. */
235 static int cmd_argc = 0;
236 /* Number of chars being used in `cmd_argv'. */
237 static int cmd_argv_chars = 0;
239 /* Number of initial arguments given on the command line. */
240 static int initial_argc = 0;
241 #endif
243 /* Number of chars in the initial args. */
244 /* static int initial_argv_chars = 0; */
246 /* true when building up initial arguments in `cmd_argv'. */
247 static boolean initial_args = true;
249 /* If nonzero, the maximum number of child processes that can be running
250 at once. */
251 static int proc_max = 1;
253 /* Total number of child processes that have been executed. */
254 static int procs_executed = 0;
256 /* The number of elements in `pids'. */
257 static int procs_executing = 0;
259 /* List of child processes currently executing. */
260 static pid_t *pids = NULL;
262 /* The number of allocated elements in `pids'. */
263 static int pids_alloc = 0;
265 /* Exit status; nonzero if any child process exited with a
266 status of 1-125. */
267 static int child_error = 0;
269 /* If true, print each command on stderr before executing it. */
270 static boolean print_command = false; /* Option -t */
272 /* If true, query the user before executing each command, and only
273 execute the command if the user responds affirmatively. */
274 static boolean query_before_executing = false;
276 static struct option const longopts[] =
278 {"null", no_argument, NULL, '0'},
279 {"arg-file", required_argument, NULL, 'a'},
280 {"eof", optional_argument, NULL, 'e'},
281 {"replace", optional_argument, NULL, 'I'},
282 {"max-lines", optional_argument, NULL, 'l'},
283 {"max-args", required_argument, NULL, 'n'},
284 {"interactive", no_argument, NULL, 'p'},
285 {"no-run-if-empty", no_argument, NULL, 'r'},
286 {"max-chars", required_argument, NULL, 's'},
287 {"verbose", no_argument, NULL, 't'},
288 {"show-limits", no_argument, NULL, 'S'},
289 {"exit", no_argument, NULL, 'x'},
290 {"max-procs", required_argument, NULL, 'P'},
291 {"version", no_argument, NULL, 'v'},
292 {"help", no_argument, NULL, 'h'},
293 {NULL, no_argument, NULL, 0}
296 static int read_line PARAMS ((void));
297 static int read_string PARAMS ((void));
298 #if 0
299 static char *mbstrstr PARAMS ((const char *haystack, const char *needle));
300 static void do_insert PARAMS ((char *arg, size_t arglen, size_t lblen));
301 static void push_arg PARAMS ((char *arg, size_t len));
302 #endif
303 static boolean print_args PARAMS ((boolean ask));
304 /* static void do_exec PARAMS ((void)); */
305 static int xargs_do_exec (const struct buildcmd_control *cl, struct buildcmd_state *state);
306 static void exec_if_possible PARAMS ((void));
307 static void add_proc PARAMS ((pid_t pid));
308 static void wait_for_proc PARAMS ((boolean all));
309 static void wait_for_proc_all PARAMS ((void));
310 static long parse_num PARAMS ((char *str, int option, long min, long max, int fatal));
311 static long env_size PARAMS ((char **envp));
312 static void usage PARAMS ((FILE * stream));
316 static long
317 get_line_max(void)
319 long val;
320 #ifdef _SC_LINE_MAX
321 val = sysconf(_SC_LINE_MAX);
322 #else
323 val = -1;
324 #endif
326 if (val > 0)
327 return val;
329 /* either _SC_LINE_MAX was not available or
330 * there is no particular limit.
332 #ifdef LINE_MAX
333 val = LINE_MAX;
334 #endif
336 if (val > 0)
337 return val;
339 return 2048L; /* a reasonable guess. */
344 main (int argc, char **argv)
346 int optc;
347 int show_limits = 0; /* --show-limits */
348 int always_run_command = 1;
349 char *input_file = "-"; /* "-" is stdin */
350 long posix_arg_size_max;
351 long posix_arg_size_min;
352 long arg_size;
353 long size_of_environment = env_size(environ);
354 char *default_cmd = "/bin/echo";
355 int (*read_args) PARAMS ((void)) = read_line;
357 program_name = argv[0];
359 #ifdef HAVE_SETLOCALE
360 setlocale (LC_ALL, "");
361 #endif
362 bindtextdomain (PACKAGE, LOCALEDIR);
363 textdomain (PACKAGE);
364 atexit (close_stdout);
365 atexit (wait_for_proc_all);
367 /* IEE Std 1003.1, 2003 specifies that the combined argument and
368 * environment list shall not exceed {ARG_MAX}-2048 bytes. It also
369 * specifies that it shall be at least LINE_MAX.
371 posix_arg_size_min = get_line_max();
372 posix_arg_size_max = bc_get_arg_max();
373 posix_arg_size_max -= 2048; /* POSIX.2 requires subtracting 2048. */
375 bc_init_controlinfo(&bc_ctl);
376 assert(bc_ctl.arg_max == posix_arg_size_max);
378 bc_ctl.exec_callback = xargs_do_exec;
381 /* Start with a reasonable default size, though this can be
382 * adjusted via the -s option.
384 arg_size = (128 * 1024) + size_of_environment;
386 /* Take the size of the environment into account. */
387 if (size_of_environment > posix_arg_size_max)
389 error (1, 0, _("environment is too large for exec"));
391 else
393 bc_ctl.arg_max = posix_arg_size_max - size_of_environment;
396 /* Check against the upper and lower limits. */
397 if (arg_size > bc_ctl.arg_max)
398 arg_size = bc_ctl.arg_max;
399 if (arg_size < posix_arg_size_min)
400 arg_size = posix_arg_size_min;
405 while ((optc = getopt_long (argc, argv, "+0a:E:e::i::I:l::L:n:prs:txP:",
406 longopts, (int *) 0)) != -1)
408 switch (optc)
410 case '0':
411 read_args = read_string;
412 break;
414 case 'E': /* POSIX */
415 case 'e': /* deprecated */
416 if (optarg && (strlen(optarg) > 0))
417 eof_str = optarg;
418 else
419 eof_str = 0;
420 break;
422 case 'h':
423 usage (stdout);
424 return 0;
426 case 'I': /* POSIX */
427 case 'i': /* deprecated */
428 if (optarg)
429 bc_ctl.replace_pat = optarg;
430 else
431 bc_ctl.replace_pat = "{}";
432 /* -i excludes -n -l. */
433 bc_ctl.args_per_exec = 0;
434 bc_ctl.lines_per_exec = 0;
435 break;
437 case 'L': /* POSIX */
438 case 'l': /* deprecated */
439 if (optarg)
440 bc_ctl.lines_per_exec = parse_num (optarg, 'l', 1L, -1L, 1);
441 else
442 bc_ctl.lines_per_exec = 1;
443 /* -l excludes -i -n. */
444 bc_ctl.args_per_exec = 0;
445 bc_ctl.replace_pat = NULL;
446 break;
448 case 'n':
449 bc_ctl.args_per_exec = parse_num (optarg, 'n', 1L, -1L, 1);
450 /* -n excludes -i -l. */
451 bc_ctl.lines_per_exec = 0;
452 if (bc_ctl.args_per_exec == 1 && bc_ctl.replace_pat)
453 /* ignore -n1 in '-i -n1' */
454 bc_ctl.args_per_exec = 0;
455 else
456 bc_ctl.replace_pat = NULL;
457 break;
459 /* The POSIX standard specifies that it is not an error
460 * for the -s option to specify a size that the implementation
461 * cannot support - in that case, the relevant limit is used.
463 case 's':
464 arg_size = parse_num (optarg, 's', 1L, posix_arg_size_max, 0);
465 if (arg_size > posix_arg_size_max)
467 error (0, 0, "warning: value %ld for -s option is too large, using %ld instead", arg_size, posix_arg_size_max);
468 arg_size = posix_arg_size_max;
470 break;
472 case 'S':
473 show_limits = true;
474 break;
476 case 't':
477 print_command = true;
478 break;
480 case 'x':
481 bc_ctl.exit_if_size_exceeded = true;
482 break;
484 case 'p':
485 query_before_executing = true;
486 print_command = true;
487 break;
489 case 'r':
490 always_run_command = 0;
491 break;
493 case 'P':
494 proc_max = parse_num (optarg, 'P', 0L, -1L, 1);
495 break;
497 case 'a':
498 input_file = optarg;
499 break;
501 case 'v':
502 printf (_("GNU xargs version %s\n"), version_string);
503 return 0;
505 default:
506 usage (stderr);
507 return 1;
511 if (0 == strcmp (input_file, "-"))
513 input_stream = stdin;
515 else
517 keep_stdin = 1; /* see prep_child_for_exec() */
518 input_stream = fopen (input_file, "r");
519 if (NULL == input_stream)
521 error (1, errno,
522 _("Cannot open input file `%s'"),
523 input_file);
527 if (bc_ctl.replace_pat || bc_ctl.lines_per_exec)
528 bc_ctl.exit_if_size_exceeded = true;
530 if (optind == argc)
532 optind = 0;
533 argc = 1;
534 argv = &default_cmd;
537 /* Taking into account the size of the environment,
538 * figure out how large a buffer we need to
539 * hold all the arguments. We cannot use ARG_MAX
540 * directly since that may be arbitrarily large.
541 * This is from a patch by Bob Prolux, <bob@proulx.com>.
543 if (bc_ctl.arg_max > arg_size)
545 if (show_limits)
547 fprintf(stderr,
548 _("Reducing arg_max (%ld) to arg_size (%ld)\n"),
549 bc_ctl.arg_max, arg_size);
551 bc_ctl.arg_max = arg_size;
554 if (show_limits)
556 fprintf(stderr,
557 _("Your environment variables take up %ld bytes\n"),
558 size_of_environment);
559 fprintf(stderr,
560 _("POSIX lower and upper limits on argument length: %ld, %ld\n"),
561 posix_arg_size_min,
562 posix_arg_size_max);
563 fprintf(stderr,
564 _("Maximum length of command we could actually use: %ld\n"),
565 (posix_arg_size_max - size_of_environment));
566 fprintf(stderr,
567 _("Size of command buffer we are actually using: %ld\n"),
568 arg_size);
571 linebuf = (char *) xmalloc (bc_ctl.arg_max + 1);
572 bc_state.argbuf = (char *) xmalloc (bc_ctl.arg_max + 1);
574 /* Make sure to listen for the kids. */
575 signal (SIGCHLD, SIG_DFL);
577 if (!bc_ctl.replace_pat)
579 for (; optind < argc; optind++)
580 bc_push_arg (&bc_ctl, &bc_state,
581 argv[optind], strlen (argv[optind]) + 1,
582 NULL, 0,
583 initial_args);
584 initial_args = false;
585 bc_ctl.initial_argc = bc_state.cmd_argc;
586 bc_state.cmd_initial_argv_chars = bc_state.cmd_argv_chars;
588 while ((*read_args) () != -1)
589 if (bc_ctl.lines_per_exec && lineno >= bc_ctl.lines_per_exec)
591 xargs_do_exec (&bc_ctl, &bc_state);
592 lineno = 0;
595 /* SYSV xargs seems to do at least one exec, even if the
596 input is empty. */
597 if (bc_state.cmd_argc != bc_ctl.initial_argc
598 || (always_run_command && procs_executed == 0))
599 xargs_do_exec (&bc_ctl, &bc_state);
602 else
604 int i;
605 size_t len;
606 size_t *arglen = (size_t *) xmalloc (sizeof (size_t) * argc);
608 for (i = optind; i < argc; i++)
609 arglen[i] = strlen(argv[i]);
610 bc_ctl.rplen = strlen (bc_ctl.replace_pat);
611 while ((len = (*read_args) ()) != -1)
613 /* Don't do insert on the command name. */
614 bc_clear_args(&bc_ctl, &bc_state);
615 bc_state.cmd_argv_chars = 0; /* begin at start of buffer */
617 bc_push_arg (&bc_ctl, &bc_state,
618 argv[optind], arglen[optind] + 1,
619 NULL, 0,
620 initial_args);
621 len--;
622 initial_args = false;
624 for (i = optind + 1; i < argc; i++)
625 bc_do_insert (&bc_ctl, &bc_state,
626 argv[i], arglen[i],
627 NULL, 0,
628 linebuf, len,
629 initial_args);
630 xargs_do_exec (&bc_ctl, &bc_state);
634 return child_error;
637 #if 0
638 static int
639 append_char_to_buf(char **pbuf, char **pend, char **pp, int c)
641 char *end_of_buffer = *pend;
642 char *start_of_buffer = *pbuf;
643 char *p = *pp;
644 if (p >= end_of_buffer)
646 if (bc_ctl.replace_pat)
648 size_t len = end_of_buffer - start_of_buffer;
649 size_t offset = p - start_of_buffer;
650 len *= 2;
651 start_of_buffer = xrealloc(start_of_buffer, len*2);
652 if (NULL != start_of_buffer)
654 end_of_buffer = start_of_buffer + len;
655 p = start_of_buffer + offset;
656 *p++ = c;
658 /* Update the caller's idea of where the buffer is. */
659 *pbuf = start_of_buffer;
660 *pend = end_of_buffer;
661 *pp = p;
663 return 0;
665 else
667 /* Failed to reallocate. */
668 return -1;
671 else
673 /* I suspect that this can never happen now, because append_char_to_buf()
674 * should only be called when replace_pat is true.
676 error (1, 0, _("argument line too long"));
677 /*NOTREACHED*/
678 return -1;
681 else
683 /* Enough space remains. */
684 *p++ = c;
685 *pp = p;
686 return 0;
689 #endif
692 /* Read a line of arguments from the input and add them to the list of
693 arguments to pass to the command. Ignore blank lines and initial blanks.
694 Single and double quotes and backslashes quote metacharacters and blanks
695 as they do in the shell.
696 Return -1 if eof (either physical or logical) is reached,
697 otherwise the length of the last string read (including the null). */
699 static int
700 read_line (void)
702 static boolean eof = false;
703 /* Start out in mode SPACE to always strip leading spaces (even with -i). */
704 int state = SPACE; /* The type of character we last read. */
705 int prevc; /* The previous value of c. */
706 int quotc = 0; /* The last quote character read. */
707 int c = EOF;
708 boolean first = true; /* true if reading first arg on line. */
709 int len;
710 char *p = linebuf;
711 /* Including the NUL, the args must not grow past this point. */
712 char *endbuf = linebuf + bc_ctl.arg_max - bc_state.cmd_initial_argv_chars - 1;
714 if (eof)
715 return -1;
716 while (1)
718 prevc = c;
719 c = getc (input_stream);
720 if (c == EOF)
722 /* COMPAT: SYSV seems to ignore stuff on a line that
723 ends without a \n; we don't. */
724 eof = true;
725 if (p == linebuf)
726 return -1;
727 *p++ = '\0';
728 len = p - linebuf;
729 if (state == QUOTE)
731 exec_if_possible ();
732 error (1, 0, _("unmatched %s quote; by default quotes are special to xargs unless you use the -0 option"),
733 quotc == '"' ? _("double") : _("single"));
735 if (first && EOF_STR (linebuf))
736 return -1;
737 if (!bc_ctl.replace_pat)
738 bc_push_arg (&bc_ctl, &bc_state,
739 linebuf, len,
740 NULL, 0,
741 initial_args);
742 return len;
744 switch (state)
746 case SPACE:
747 if (ISSPACE (c))
748 continue;
749 state = NORM;
750 /* aaahhhh.... */
752 case NORM:
753 if (c == '\n')
755 if (!ISBLANK (prevc))
756 lineno++; /* For -l. */
757 if (p == linebuf)
759 /* Blank line. */
760 state = SPACE;
761 continue;
763 *p++ = '\0';
764 len = p - linebuf;
765 if (EOF_STR (linebuf))
767 eof = true;
768 return first ? -1 : len;
770 if (!bc_ctl.replace_pat)
771 bc_push_arg (&bc_ctl, &bc_state,
772 linebuf, len,
773 NULL, 0,
774 initial_args);
775 return len;
777 if (!bc_ctl.replace_pat && ISSPACE (c))
779 *p++ = '\0';
780 len = p - linebuf;
781 if (EOF_STR (linebuf))
783 eof = true;
784 return first ? -1 : len;
786 bc_push_arg (&bc_ctl, &bc_state,
787 linebuf, len,
788 NULL, 0,
789 initial_args);
790 p = linebuf;
791 state = SPACE;
792 first = false;
793 continue;
795 switch (c)
797 case '\\':
798 state = BACKSLASH;
799 continue;
801 case '\'':
802 case '"':
803 state = QUOTE;
804 quotc = c;
805 continue;
807 break;
809 case QUOTE:
810 if (c == '\n')
812 exec_if_possible ();
813 error (1, 0, _("unmatched %s quote; by default quotes are special to xargs unless you use the -0 option"),
814 quotc == '"' ? _("double") : _("single"));
816 if (c == quotc)
818 state = NORM;
819 continue;
821 break;
823 case BACKSLASH:
824 state = NORM;
825 break;
827 #if 1
828 if (p >= endbuf)
830 exec_if_possible ();
831 error (1, 0, _("argument line too long"));
833 *p++ = c;
834 #else
835 append_char_to_buf(&linebuf, &endbuf, &p, c);
836 #endif
840 /* Read a null-terminated string from the input and add it to the list of
841 arguments to pass to the command.
842 Return -1 if eof (either physical or logical) is reached,
843 otherwise the length of the string read (including the null). */
845 static int
846 read_string (void)
848 static boolean eof = false;
849 int len;
850 char *p = linebuf;
851 /* Including the NUL, the args must not grow past this point. */
852 char *endbuf = linebuf + bc_ctl.arg_max - bc_state.cmd_initial_argv_chars - 1;
854 if (eof)
855 return -1;
856 while (1)
858 int c = getc (input_stream);
859 if (c == EOF)
861 eof = true;
862 if (p == linebuf)
863 return -1;
864 *p++ = '\0';
865 len = p - linebuf;
866 if (!bc_ctl.replace_pat)
867 bc_push_arg (&bc_ctl, &bc_state,
868 linebuf, len,
869 NULL, 0,
870 initial_args);
871 return len;
873 if (c == '\0')
875 lineno++; /* For -l. */
876 *p++ = '\0';
877 len = p - linebuf;
878 if (!bc_ctl.replace_pat)
879 bc_push_arg (&bc_ctl, &bc_state,
880 linebuf, len,
881 NULL, 0,
882 initial_args);
883 return len;
885 if (p >= endbuf)
887 exec_if_possible ();
888 error (1, 0, _("argument line too long"));
890 *p++ = c;
894 /* Print the arguments of the command to execute.
895 If ASK is nonzero, prompt the user for a response, and
896 if the user responds affirmatively, return true;
897 otherwise, return false. */
899 static boolean
900 print_args (boolean ask)
902 int i;
904 for (i = 0; i < bc_state.cmd_argc - 1; i++)
905 fprintf (stderr, "%s ", bc_state.cmd_argv[i]);
906 if (ask)
908 static FILE *tty_stream;
909 int c, savec;
911 if (!tty_stream)
913 tty_stream = fopen ("/dev/tty", "r");
914 if (!tty_stream)
915 error (1, errno, "/dev/tty");
917 fputs ("?...", stderr);
918 fflush (stderr);
919 c = savec = getc (tty_stream);
920 while (c != EOF && c != '\n')
921 c = getc (tty_stream);
922 if (savec == 'y' || savec == 'Y')
923 return true;
925 else
926 putc ('\n', stderr);
928 return false;
932 /* Close stdin and attach /dev/null to it.
933 * This resolves Savannah bug #3992.
935 static void
936 prep_child_for_exec (void)
938 if (!keep_stdin)
940 const char inputfile[] = "/dev/null";
941 /* fprintf(stderr, "attaching stdin to /dev/null\n"); */
943 close(0);
944 if (open(inputfile, O_RDONLY) < 0)
946 /* This is not entirely fatal, since
947 * executing the child with a closed
948 * stdin is almost as good as executing it
949 * with its stdin attached to /dev/null.
951 error (0, errno, "%s", inputfile);
957 /* Execute the command that has been built in `cmd_argv'. This may involve
958 waiting for processes that were previously executed. */
960 static int
961 xargs_do_exec (const struct buildcmd_control *ctl, struct buildcmd_state *state)
963 pid_t child;
965 bc_push_arg (&bc_ctl, &bc_state,
966 (char *) NULL, 0,
967 NULL, 0,
968 false); /* Null terminate the arg list. */
970 if (!query_before_executing || print_args (true))
972 if (proc_max && procs_executing >= proc_max)
973 wait_for_proc (false);
974 if (!query_before_executing && print_command)
975 print_args (false);
976 /* If we run out of processes, wait for a child to return and
977 try again. */
978 while ((child = fork ()) < 0 && errno == EAGAIN && procs_executing)
979 wait_for_proc (false);
980 switch (child)
982 case -1:
983 error (1, errno, _("cannot fork"));
985 case 0: /* Child. */
986 prep_child_for_exec();
987 execvp (bc_state.cmd_argv[0], bc_state.cmd_argv);
988 error (0, errno, "%s", bc_state.cmd_argv[0]);
989 _exit (errno == ENOENT ? 127 : 126);
990 /*NOTREACHED*/
992 add_proc (child);
995 bc_clear_args(&bc_ctl, &bc_state);
996 return 1; /* Success */
999 /* Execute the command if possible. */
1001 static void
1002 exec_if_possible (void)
1004 if (bc_ctl.replace_pat || initial_args ||
1005 bc_state.cmd_argc == bc_ctl.initial_argc || bc_ctl.exit_if_size_exceeded)
1006 return;
1007 xargs_do_exec (&bc_ctl, &bc_state);
1010 /* Add the process with id PID to the list of processes that have
1011 been executed. */
1013 static void
1014 add_proc (pid_t pid)
1016 int i;
1018 /* Find an empty slot. */
1019 for (i = 0; i < pids_alloc && pids[i]; i++)
1021 if (i == pids_alloc)
1023 if (pids_alloc == 0)
1025 pids_alloc = proc_max ? proc_max : 64;
1026 pids = (pid_t *) xmalloc (sizeof (pid_t) * pids_alloc);
1028 else
1030 pids_alloc *= 2;
1031 pids = (pid_t *) xrealloc (pids,
1032 sizeof (pid_t) * pids_alloc);
1034 memset (&pids[i], '\0', sizeof (pid_t) * (pids_alloc - i));
1036 pids[i] = pid;
1037 procs_executing++;
1038 procs_executed++;
1041 /* If ALL is true, wait for all child processes to finish;
1042 otherwise, wait for one child process to finish.
1043 Remove the processes that finish from the list of executing processes. */
1045 static void
1046 wait_for_proc (boolean all)
1048 while (procs_executing)
1050 int i, status;
1054 pid_t pid;
1056 while ((pid = wait (&status)) == (pid_t) -1)
1057 if (errno != EINTR)
1058 error (1, errno, _("error waiting for child process"));
1060 /* Find the entry in `pids' for the child process
1061 that exited. */
1062 for (i = 0; i < pids_alloc && pid != pids[i]; i++)
1065 while (i == pids_alloc); /* A child died that we didn't start? */
1067 /* Remove the child from the list. */
1068 pids[i] = 0;
1069 procs_executing--;
1071 if (WEXITSTATUS (status) == 126 || WEXITSTATUS (status) == 127)
1072 exit (WEXITSTATUS (status)); /* Can't find or run the command. */
1073 if (WEXITSTATUS (status) == 255)
1074 error (124, 0, _("%s: exited with status 255; aborting"), bc_state.cmd_argv[0]);
1075 if (WIFSTOPPED (status))
1076 error (125, 0, _("%s: stopped by signal %d"), bc_state.cmd_argv[0], WSTOPSIG (status));
1077 if (WIFSIGNALED (status))
1078 error (125, 0, _("%s: terminated by signal %d"), bc_state.cmd_argv[0], WTERMSIG (status));
1079 if (WEXITSTATUS (status) != 0)
1080 child_error = 123;
1082 if (!all)
1083 break;
1087 /* Wait for all child processes to finish. */
1089 static void
1090 wait_for_proc_all (void)
1092 static boolean waiting = false;
1094 if (waiting)
1095 return;
1097 waiting = true;
1098 wait_for_proc (true);
1099 waiting = false;
1102 /* Return the value of the number represented in STR.
1103 OPTION is the command line option to which STR is the argument.
1104 If the value does not fall within the boundaries MIN and MAX,
1105 Print an error message mentioning OPTION. If FATAL is true,
1106 we also exit. */
1108 static long
1109 parse_num (char *str, int option, long int min, long int max, int fatal)
1111 char *eptr;
1112 long val;
1114 val = strtol (str, &eptr, 10);
1115 if (eptr == str || *eptr)
1117 fprintf (stderr, _("%s: invalid number for -%c option\n"),
1118 program_name, option);
1119 usage (stderr);
1120 exit(1);
1122 else if (val < min)
1124 fprintf (stderr, _("%s: value for -%c option should be >= %ld\n"),
1125 program_name, option, min);
1126 if (fatal)
1128 usage (stderr);
1129 exit(1);
1131 else
1133 val = min;
1136 else if (max >= 0 && val > max)
1138 fprintf (stderr, _("%s: value for -%c option should be < %ld\n"),
1139 program_name, option, max);
1140 if (fatal)
1142 usage (stderr);
1143 exit(1);
1145 else
1147 val = max;
1150 return val;
1153 /* Return how much of ARG_MAX is used by the environment. */
1155 static long
1156 env_size (char **envp)
1158 long len = 0;
1160 while (*envp)
1161 len += strlen (*envp++) + 1;
1163 return len;
1166 static void
1167 usage (FILE *stream)
1169 fprintf (stream, _("\
1170 Usage: %s [-0prtx] [-e[eof-str]] [-i[replace-str]] [-l[max-lines]]\n\
1171 [-n max-args] [-s max-chars] [-P max-procs] [--null] [--eof[=eof-str]]\n\
1172 [--replace[=replace-str]] [--max-lines[=max-lines]] [--interactive]\n\
1173 [--max-chars=max-chars] [--verbose] [--exit] [--max-procs=max-procs]\n\
1174 [--max-args=max-args] [--no-run-if-empty] [--arg-file=file]\n\
1175 [--version] [--help] [command [initial-arguments]]\n"),
1176 program_name);
1177 fputs (_("\nReport bugs to <bug-findutils@gnu.org>.\n"), stream);