Imported Upstream version 4.5.10
[platform/upstream/findutils.git] / xargs / xargs.c
1 /* xargs -- build and execute command lines from standard input
2    Copyright (C) 1990, 91, 92, 93, 94, 2000, 2003, 2004, 2005, 2006,
3    2007, 2008, 2009, 2010 Free Software Foundation, Inc.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation, either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 /* Written by Mike Rendell <michael@cs.mun.ca>
20    and David MacKenzie <djm@gnu.org>.
21    Modifications by
22         James Youngman
23         Dmitry V. Levin
24 */
25
26 #include <config.h>
27
28 #include <ctype.h>
29 #include <stdio.h>
30 #include <errno.h>
31 #include <limits.h>
32 #include <stdint.h>
33 #include <inttypes.h>
34
35 #include <sys/types.h>
36 #include <getopt.h>
37 #include <fcntl.h>
38 #include <assert.h>
39 #include <string.h>
40 #include <sys/param.h>
41
42 #ifndef LONG_MAX
43 #define LONG_MAX (~(1 << (sizeof (long) * 8 - 1)))
44 #endif
45
46 #define ISBLANK(c) (isascii (c) && isblank (c))
47 #define ISSPACE(c) (ISBLANK (c) || (c) == '\n' || (c) == '\r' \
48                     || (c) == '\f' || (c) == '\v')
49
50 /* The presence of unistd.h is assumed by gnulib these days, so we
51  * might as well assume it too.
52  */
53 #include <unistd.h>
54 #include <signal.h>
55 #include <sys/wait.h>
56 #include <stdlib.h>
57 #include <locale.h>
58 #include <wchar.h>
59 #include <stdint.h>
60
61 #if !defined(SIGCHLD) && defined(SIGCLD)
62 #define SIGCHLD SIGCLD
63 #endif
64
65 #include "verify.h"
66
67 #include "progname.h"
68 #include "quotearg.h"
69 #include "findutils-version.h"
70
71
72 #if ENABLE_NLS
73 # include <libintl.h>
74 # define _(Text) gettext (Text)
75 #else
76 # define _(Text) Text
77 #define textdomain(Domain)
78 #define bindtextdomain(Package, Directory)
79 #endif
80 #ifdef gettext_noop
81 # define N_(String) gettext_noop(String)
82 #else
83 /* See locate.c for explanation as to why not use (String) */
84 # define N_(String) String
85 #endif
86
87 #include "buildcmd.h"
88 #include "arg-max.h"            /* must include after unistd.h. */
89
90
91 /* Return nonzero if S is the EOF string.  */
92 #define EOF_STR(s) (eof_str && *eof_str == *s && !strcmp (eof_str, s))
93
94 #if __STDC__
95 #define VOID void
96 #else
97 #define VOID char
98 #endif
99
100 #include <xalloc.h>
101 #include "closein.h"
102 #include "gnulib-version.h"
103
104 void error (int status, int errnum, char *message,...);
105
106 extern char *version_string;
107
108 static FILE *input_stream;
109
110 /* Buffer for reading arguments from input.  */
111 static char *linebuf;
112
113 static int keep_stdin = 0;
114
115 /* Line number in stdin since the last command was executed.  */
116 static int lineno = 0;
117
118 static struct buildcmd_state bc_state;
119 static struct buildcmd_control bc_ctl;
120
121 /* Did we already complain about NUL characters in the input? */
122 static int nullwarning_given = 0;
123
124
125 /* If nonzero, when this string is read on stdin it is treated as
126    end of file.
127    IEEE Std 1003.1, 2004 Edition allows this to be NULL.
128    In findutils releases up to and including 4.2.8, this was "_".
129 */
130 static char *eof_str = NULL;
131
132 /* Number of chars in the initial args.  */
133 /* static int initial_argv_chars = 0; */
134
135 /* true when building up initial arguments in `cmd_argv'.  */
136 static bool initial_args = true;
137
138 /* If nonzero, the maximum number of child processes that can be running
139    at once.  */
140 /* TODO: check conversion safety (i.e. range) for -P option. */
141 static volatile sig_atomic_t proc_max = 1;
142
143 /* Did we fork a child yet? */
144 static bool procs_executed = false;
145
146 /* The number of elements in `pids'.  */
147 static unsigned long int procs_executing = 0uL;
148
149 /* List of child processes currently executing.  */
150 static pid_t *pids = NULL;
151
152 /* The number of allocated elements in `pids'. */
153 static size_t pids_alloc = 0u;
154
155 /* Process ID of the parent xargs process. */
156 static pid_t parent;
157
158 /* If nonzero, we've been signaled that we can start more child processes. */
159 static volatile sig_atomic_t stop_waiting = 0;
160
161 /* Exit status; nonzero if any child process exited with a
162    status of 1-125.  */
163 static volatile int child_error = EXIT_SUCCESS;
164
165 static volatile int original_exit_value;
166
167 /* If true, print each command on stderr before executing it.  */
168 static bool print_command = false; /* Option -t */
169
170 /* If true, query the user before executing each command, and only
171    execute the command if the user responds affirmatively.  */
172 static bool query_before_executing = false;
173
174 /* The delimiter for input arguments.   This is only consulted if the
175  * -0 or -d option had been given.
176  */
177 static char input_delimiter = '\0';
178
179
180 static struct option const longopts[] =
181 {
182   {"null", no_argument, NULL, '0'},
183   {"arg-file", required_argument, NULL, 'a'},
184   {"delimiter", required_argument, NULL, 'd'},
185   {"eof", optional_argument, NULL, 'e'},
186   {"replace", optional_argument, NULL, 'I'},
187   {"max-lines", optional_argument, NULL, 'l'},
188   {"max-args", required_argument, NULL, 'n'},
189   {"interactive", no_argument, NULL, 'p'},
190   {"no-run-if-empty", no_argument, NULL, 'r'},
191   {"max-chars", required_argument, NULL, 's'},
192   {"verbose", no_argument, NULL, 't'},
193   {"show-limits", no_argument, NULL, 'S'},
194   {"exit", no_argument, NULL, 'x'},
195   {"max-procs", required_argument, NULL, 'P'},
196   {"version", no_argument, NULL, 'v'},
197   {"help", no_argument, NULL, 'h'},
198   {NULL, no_argument, NULL, 0}
199 };
200
201 /* xargs exits with status values with specific meanings (this is a POSIX requirement).
202    These are the values.
203 */
204 enum XargsStatusValues {
205   XARGS_EXIT_CLIENT_EXIT_NONZERO = 123, /* utility exited with nonzero status */
206   XARGS_EXIT_CLIENT_EXIT_255 = 124,     /* utility exites with status 255 */
207   XARGS_EXIT_CLIENT_FATAL_SIG = 125,    /* utility died from a fatal signal */
208   XARGS_EXIT_COMMAND_CANNOT_BE_RUN = 126, /* canot run the command */
209   XARGS_EXIT_COMMAND_NOT_FOUND = 127,     /* cannot find the command */
210 };
211 /* Exit status values the child might use. */
212 enum  ClientStatusValues {
213   CHILD_EXIT_PLEASE_STOP_IMMEDIATELY = 255
214 };
215
216 static int read_line (void);
217 static int read_string (void);
218 static bool print_args (bool ask);
219 /* static void do_exec (void); */
220 static int xargs_do_exec (struct buildcmd_control *ctl, void *usercontext, int argc, char **argv);
221 static void exec_if_possible (void);
222 static void add_proc (pid_t pid);
223 static void wait_for_proc (bool all, unsigned int minreap);
224 static void wait_for_proc_all (void);
225 static void increment_proc_max (int);
226 static void decrement_proc_max (int);
227 static long parse_num (char *str, int option, long min, long max, int fatal);
228 static void usage (FILE * stream);
229
230
231
232 static char
233 get_char_oct_or_hex_escape (const char *s)
234 {
235   const char * p;
236   int base = 8;
237   unsigned long val;
238   char *endp;
239
240   assert ('\\' == s[0]);
241
242   if ('x' == s[1])
243     {
244       /* hex */
245       p = s+2;
246       base = 16;
247     }
248   else if (isdigit ((unsigned char) s[1]))
249     {
250       /* octal */
251       p = s+1;
252       base = 8;
253     }
254   else
255     {
256       p = NULL;                 /* Silence compiler warning. */
257       error (EXIT_FAILURE, 0,
258              _("Invalid escape sequence %s in input delimiter specification."),
259              s);
260     }
261   errno = 0;
262   endp = (char*)p;
263   val = strtoul (p, &endp, base);
264
265   /* This if condition is carefully constructed to do
266    * the right thing if UCHAR_MAX has the same
267    * value as ULONG_MAX.   IF UCHAR_MAX==ULONG_MAX,
268    * then val can never be greater than UCHAR_MAX.
269    */
270   if ((ULONG_MAX == val && ERANGE == errno)
271       || (val > UCHAR_MAX))
272     {
273       if (16 == base)
274         {
275           error (EXIT_FAILURE, 0,
276                  _("Invalid escape sequence %s in input delimiter specification; character values must not exceed %lx."),
277                  s, (unsigned long)UCHAR_MAX);
278         }
279       else
280         {
281           error (EXIT_FAILURE, 0,
282                  _("Invalid escape sequence %s in input delimiter specification; character values must not exceed %lo."),
283                  s, (unsigned long)UCHAR_MAX);
284         }
285     }
286
287   /* check for trailing garbage */
288   if (0 != *endp)
289     {
290       error (EXIT_FAILURE, 0,
291              _("Invalid escape sequence %s in input delimiter specification; trailing characters %s not recognised."),
292              s, endp);
293     }
294
295   return (char) val;
296 }
297
298
299 static char
300 get_input_delimiter (const char *s)
301 {
302   if (1 == strlen (s))
303     {
304       return s[0];
305     }
306   else
307     {
308       if ('\\' == s[0])
309         {
310           /* an escape code */
311           switch (s[1])
312             {
313             case 'a':
314               return '\a';
315             case 'b':
316               return '\b';
317             case 'f':
318               return '\f';
319             case 'n':
320               return '\n';
321             case 'r':
322               return '\r';
323             case 't':
324               return'\t';
325             case 'v':
326               return '\v';
327             case '\\':
328               return '\\';
329             default:
330               return get_char_oct_or_hex_escape (s);
331             }
332         }
333       else
334         {
335           error (EXIT_FAILURE, 0,
336                  _("Invalid input delimiter specification %s: the delimiter must be either a single character or an escape sequence starting with \\."),
337                  s);
338           /*NOTREACHED*/
339           return 0;
340         }
341     }
342 }
343
344 static void
345 noop (void)
346 {
347   /* does nothing. */
348 }
349
350 static void
351 fail_due_to_env_size (void)
352 {
353   error (EXIT_FAILURE, 0, _("environment is too large for exec"));
354 }
355
356 static size_t
357 smaller_of (size_t a, size_t b)
358 {
359   if (a < b)
360     return a;
361   else
362     return b;
363 }
364
365
366
367 int
368 main (int argc, char **argv)
369 {
370   int optc;
371   int show_limits = 0;                  /* --show-limits */
372   int always_run_command = 1;
373   char *input_file = "-"; /* "-" is stdin */
374   char *default_cmd = "/bin/echo";
375   int (*read_args) (void) = read_line;
376   void (*act_on_init_result)(void) = noop;
377   enum BC_INIT_STATUS bcstatus;
378   enum { XARGS_POSIX_HEADROOM = 2048u };
379   struct sigaction sigact;
380
381   if (argv[0])
382     set_program_name (argv[0]);
383   else
384     set_program_name ("xargs");
385
386   parent = getpid ();
387   original_exit_value = EXIT_SUCCESS;
388
389 #ifdef HAVE_SETLOCALE
390   setlocale (LC_ALL, "");
391 #endif
392   bindtextdomain (PACKAGE, LOCALEDIR);
393   textdomain (PACKAGE);
394   atexit (close_stdin);
395   atexit (wait_for_proc_all);
396
397   /* xargs is required by POSIX to allow 2048 bytes of headroom
398    * for extra environment variables (that perhaps the utliity might
399    * want to set before execing something else).
400    */
401   bcstatus = bc_init_controlinfo (&bc_ctl, XARGS_POSIX_HEADROOM);
402
403   /* The bc_init_controlinfo call may have determined that the
404    * environment is too big.  In that case, we will fail with
405    * an error message after processing the command-line options,
406    * as "xargs --help" should still work even if the environment is
407    * too big.
408    *
409    * Some of the argument processing depends on the contents of
410    * bc_ctl, which will be in an undefined state if bc_init_controlinfo ()
411    * failed.
412    */
413   if (BC_INIT_ENV_TOO_BIG == bcstatus)
414     {
415       act_on_init_result = fail_due_to_env_size;
416     }
417   else if (BC_INIT_CANNOT_ACCOMODATE_HEADROOM == bcstatus)
418     {
419       /* All POSIX systems are required to support ARG_MAX of at least
420        * 4096.  For everything to work the total of (command line +
421        * headroom + environment) must fit into this.  POSIX requires
422        * that we use a headroom of 2048 bytes.  The user is in control
423        * of the size of the environment.
424        *
425        * In general if bc_init_controlinfo () returns
426        * BC_INIT_CANNOT_ACCOMODATE_HEADROOM, its caller can try again
427        * with a smaller headroom.  However, in the case of xargs, this
428        * would not be POSIX-compliant.
429        */
430       act_on_init_result = fail_due_to_env_size;
431     }
432   else
433     {
434       /* IEEE Std 1003.1, 2003 specifies that the combined argument and
435        * environment list shall not exceed {ARG_MAX}-2048 bytes.  It also
436        * specifies that it shall be at least LINE_MAX.
437        */
438       long val;
439 #ifdef _SC_ARG_MAX
440       val = sysconf (_SC_ARG_MAX);
441       if (val > 0)
442         {
443           assert (val > XARGS_POSIX_HEADROOM);
444           /* Note that val can in fact be greater than ARG_MAX
445            * and bc_ctl.arg_max can also be greater than ARG_MAX.
446            */
447           bc_ctl.arg_max = smaller_of (bc_ctl.arg_max,
448                                        (size_t)val-XARGS_POSIX_HEADROOM);
449         }
450       else
451         {
452 # if defined ARG_MAX
453           assert (ARG_MAX > XARGS_POSIX_HEADROOM);
454           bc_ctl.arg_max = smaller_of (bc_ctl.arg_max,
455                                        (ARG_MAX - XARGS_POSIX_HEADROOM));
456 # endif
457         }
458 #else
459       /* No _SC_ARG_MAX */
460       assert (ARG_MAX > XARGS_POSIX_HEADROOM);
461       bc_ctl.arg_max = smaller_of (bc_ctl.arg_max,
462                                    (ARG_MAX - XARGS_POSIX_HEADROOM));
463 #endif
464
465
466 #ifdef LINE_MAX
467       /* This assertion ensures that this xargs implementation
468        * conforms to the POSIX requirement that the default command
469        * line length shall be at least LINE_MAX.
470        */
471       assert (bc_ctl.arg_max >= LINE_MAX);
472 #endif
473
474       bc_ctl.exec_callback = xargs_do_exec;
475
476       /* Start with a reasonable default size, though this can be
477        * adjusted via the -s option.
478        */
479       bc_use_sensible_arg_max (&bc_ctl);
480     }
481
482   while ((optc = getopt_long (argc, argv, "+0a:E:e::i::I:l::L:n:prs:txP:d:",
483                               longopts, (int *) 0)) != -1)
484     {
485       switch (optc)
486         {
487         case '0':
488           read_args = read_string;
489           input_delimiter = '\0';
490           break;
491
492         case 'd':
493           read_args = read_string;
494           input_delimiter = get_input_delimiter (optarg);
495           break;
496
497         case 'E':               /* POSIX */
498         case 'e':               /* deprecated */
499           if (optarg && (strlen (optarg) > 0))
500             eof_str = optarg;
501           else
502             eof_str = 0;
503           break;
504
505         case 'h':
506           usage (stdout);
507           return 0;
508
509         case 'I':               /* POSIX */
510         case 'i':               /* deprecated */
511           if (optarg)
512             bc_ctl.replace_pat = optarg;
513           else
514             bc_ctl.replace_pat = "{}";
515           /* -i excludes -n -l.  */
516           bc_ctl.args_per_exec = 0;
517           bc_ctl.lines_per_exec = 0;
518           break;
519
520         case 'L':               /* POSIX */
521           bc_ctl.lines_per_exec = parse_num (optarg, 'L', 1L, -1L, 1);
522           /* -L excludes -i -n.  */
523           bc_ctl.args_per_exec = 0;
524           bc_ctl.replace_pat = NULL;
525           break;
526
527         case 'l':               /* deprecated */
528           if (optarg)
529             bc_ctl.lines_per_exec = parse_num (optarg, 'l', 1L, -1L, 1);
530           else
531             bc_ctl.lines_per_exec = 1;
532           /* -l excludes -i -n.  */
533           bc_ctl.args_per_exec = 0;
534           bc_ctl.replace_pat = NULL;
535           break;
536
537         case 'n':
538           bc_ctl.args_per_exec = parse_num (optarg, 'n', 1L, -1L, 1);
539           /* -n excludes -i -l.  */
540           bc_ctl.lines_per_exec = 0;
541           if (bc_ctl.args_per_exec == 1 && bc_ctl.replace_pat)
542             /* ignore -n1 in '-i -n1' */
543             bc_ctl.args_per_exec = 0;
544           else
545             bc_ctl.replace_pat = NULL;
546           break;
547
548           /* The POSIX standard specifies that it is not an error
549            * for the -s option to specify a size that the implementation
550            * cannot support - in that case, the relevant limit is used.
551            */
552         case 's':
553           {
554             size_t arg_size;
555             act_on_init_result ();
556             arg_size = parse_num (optarg, 's', 1L,
557                                   bc_ctl.posix_arg_size_max, 0);
558             if (arg_size > bc_ctl.posix_arg_size_max)
559               {
560                 error (0, 0,
561                        _("warning: value %ld for -s option is too large, "
562                          "using %ld instead"),
563                        arg_size, bc_ctl.posix_arg_size_max);
564                 arg_size = bc_ctl.posix_arg_size_max;
565               }
566             bc_ctl.arg_max = arg_size;
567           }
568           break;
569
570         case 'S':
571           show_limits = true;
572           break;
573
574         case 't':
575           print_command = true;
576           break;
577
578         case 'x':
579           bc_ctl.exit_if_size_exceeded = true;
580           break;
581
582         case 'p':
583           query_before_executing = true;
584           print_command = true;
585           break;
586
587         case 'r':
588           always_run_command = 0;
589           break;
590
591         case 'P':
592           /* Allow only up to LONG_MAX child processes. */
593           proc_max = parse_num (optarg, 'P', 0L, LONG_MAX, 1);
594           break;
595
596         case 'a':
597           input_file = optarg;
598           break;
599
600         case 'v':
601           display_findutils_version ("xargs");
602           return 0;
603
604         default:
605           usage (stderr);
606           return 1;
607         }
608     }
609
610   /* If we had deferred failing due to problems in bc_init_controlinfo (),
611    * do it now.
612    *
613    * We issue this error message after processing command line
614    * arguments so that it is possible to use "xargs --help" even if
615    * the environment is too large.
616    */
617   act_on_init_result ();
618   assert (BC_INIT_OK == bcstatus);
619
620 #ifdef SIGUSR1
621 #ifdef SIGUSR2
622   /* Accept signals to increase or decrease the number of running
623      child processes.  Do this as early as possible after setting
624      proc_max.  */
625   sigact.sa_handler = increment_proc_max;
626   sigemptyset(&sigact.sa_mask);
627   sigact.sa_flags = 0;
628   if (0 != sigaction (SIGUSR1, &sigact, (struct sigaction *)NULL))
629           error (0, errno, _("Cannot set SIGUSR1 signal handler"));
630
631   sigact.sa_handler = decrement_proc_max;
632   sigemptyset(&sigact.sa_mask);
633   sigact.sa_flags = 0;
634   if (0 != sigaction (SIGUSR2, &sigact, (struct sigaction *)NULL))
635           error (0, errno, _("Cannot set SIGUSR2 signal handler"));
636 #endif /* SIGUSR2 */
637 #endif /* SIGUSR1 */
638
639
640   if (0 == strcmp (input_file, "-"))
641     {
642       input_stream = stdin;
643     }
644   else
645     {
646       keep_stdin = 1;           /* see prep_child_for_exec () */
647       input_stream = fopen (input_file, "r");
648       if (NULL == input_stream)
649         {
650           error (EXIT_FAILURE, errno,
651                  _("Cannot open input file %s"),
652                  quotearg_n_style (0, locale_quoting_style, input_file));
653         }
654     }
655
656   if (bc_ctl.replace_pat || bc_ctl.lines_per_exec)
657     bc_ctl.exit_if_size_exceeded = true;
658
659   if (optind == argc)
660     {
661       optind = 0;
662       argc = 1;
663       argv = &default_cmd;
664     }
665
666   if (show_limits)
667     {
668       fprintf (stderr,
669               _("Your environment variables take up %" PRIuMAX " bytes\n"),
670               (uintmax_t)bc_size_of_environment ());
671       fprintf (stderr,
672               _("POSIX upper limit on argument length (this system): %" PRIuMAX "\n"),
673               (uintmax_t)bc_ctl.posix_arg_size_max);
674       fprintf (stderr,
675               _("POSIX smallest allowable upper limit on argument length (all systems): %" PRIuMAX "\n"),
676               (uintmax_t)bc_ctl.posix_arg_size_min);
677       fprintf (stderr,
678               _("Maximum length of command we could actually use: %" PRIuMAX "\n"),
679               (uintmax_t)(bc_ctl.posix_arg_size_max - bc_size_of_environment ()));
680       fprintf (stderr,
681               _("Size of command buffer we are actually using: %" PRIuMAX "\n"),
682               (uintmax_t)bc_ctl.arg_max);
683
684       if (isatty (STDIN_FILENO))
685         {
686           fprintf (stderr,
687                   _("\n"
688                     "Execution of xargs will continue now, and it will "
689                     "try to read its input and run commands; if this is "
690                     "not what you wanted to happen, please type the "
691                     "end-of-file keystroke.\n"));
692           if (always_run_command)
693             {
694               fprintf (stderr,
695                       _("Warning: %s will be run at least once.  "
696                         "If you do not want that to happen, then press "
697                         "the interrupt keystroke.\n"),
698                       argv[optind]);
699             }
700         }
701     }
702
703   linebuf = xmalloc (bc_ctl.arg_max + 1);
704   bc_state.argbuf = xmalloc (bc_ctl.arg_max + 1);
705
706   /* Make sure to listen for the kids.  */
707   signal (SIGCHLD, SIG_DFL);
708
709   if (!bc_ctl.replace_pat)
710     {
711       for (; optind < argc; optind++)
712         bc_push_arg (&bc_ctl, &bc_state,
713                      argv[optind], strlen (argv[optind]) + 1,
714                      NULL, 0,
715                      initial_args);
716       initial_args = false;
717       bc_ctl.initial_argc = bc_state.cmd_argc;
718       bc_state.cmd_initial_argv_chars = bc_state.cmd_argv_chars;
719       bc_ctl.initial_argc = bc_state.cmd_argc;
720       /*fprintf (stderr, "setting initial_argc=%d\n", bc_state.cmd_initial_argc);*/
721
722       while ((*read_args) () != -1)
723         if (bc_ctl.lines_per_exec && lineno >= bc_ctl.lines_per_exec)
724           {
725             bc_do_exec (&bc_ctl, &bc_state);
726             lineno = 0;
727           }
728
729       /* SYSV xargs seems to do at least one exec, even if the
730          input is empty.  */
731       if (bc_state.cmd_argc != bc_ctl.initial_argc
732           || (always_run_command && procs_executed==0))
733         bc_do_exec (&bc_ctl, &bc_state);
734
735     }
736   else
737     {
738       int i;
739       size_t len;
740       size_t *arglen = xmalloc (sizeof (size_t) * argc);
741
742       for (i = optind; i < argc; i++)
743         arglen[i] = strlen (argv[i]);
744       bc_ctl.rplen = strlen (bc_ctl.replace_pat);
745       while ((len = (*read_args) ()) != -1)
746         {
747           /* Don't do insert on the command name.  */
748           bc_clear_args (&bc_ctl, &bc_state);
749           bc_state.cmd_argv_chars = 0; /* begin at start of buffer */
750
751           bc_push_arg (&bc_ctl, &bc_state,
752                        argv[optind], arglen[optind] + 1,
753                        NULL, 0,
754                        initial_args);
755           len--;
756           initial_args = false;
757
758           for (i = optind + 1; i < argc; i++)
759             bc_do_insert (&bc_ctl, &bc_state,
760                           argv[i], arglen[i],
761                           NULL, 0,
762                           linebuf, len,
763                           initial_args);
764           bc_do_exec (&bc_ctl, &bc_state);
765         }
766     }
767
768   original_exit_value = child_error;
769   return child_error;
770 }
771
772
773 /* Read a line of arguments from the input and add them to the list of
774    arguments to pass to the command.  Ignore blank lines and initial blanks.
775    Single and double quotes and backslashes quote metacharacters and blanks
776    as they do in the shell.
777    Return -1 if eof (either physical or logical) is reached,
778    otherwise the length of the last string read (including the null).  */
779
780 static int
781 read_line (void)
782 {
783 /* States for read_line. */
784   enum read_line_state
785     {
786       NORM = 0,
787       SPACE = 1,
788       QUOTE = 2,
789       BACKSLASH = 3
790     };
791   static bool eof = false;
792   /* Start out in mode SPACE to always strip leading spaces (even with -i).  */
793   enum read_line_state state = SPACE; /* The type of character we last read.  */
794   int prevc;                    /* The previous value of c.  */
795   int quotc = 0;                /* The last quote character read.  */
796   int c = EOF;
797   bool first = true;            /* true if reading first arg on line.  */
798   bool seen_arg = false;      /* true if we have seen any arg (or part of one) yet */
799   int len;
800   char *p = linebuf;
801   /* Including the NUL, the args must not grow past this point.  */
802   char *endbuf = linebuf + bc_ctl.arg_max - bc_state.cmd_initial_argv_chars - 1;
803
804   if (eof)
805     return -1;
806   while (1)
807     {
808       prevc = c;
809       c = getc (input_stream);
810
811       if (c == EOF)
812         {
813           /* COMPAT: SYSV seems to ignore stuff on a line that
814              ends without a \n; we don't.  */
815           eof = true;
816           if (p == linebuf)
817             return -1;
818           *p++ = '\0';
819           len = p - linebuf;
820           if (state == QUOTE)
821             {
822               exec_if_possible ();
823               error (EXIT_FAILURE, 0, _("unmatched %s quote; by default quotes are special to xargs unless you use the -0 option"),
824                      quotc == '"' ? _("double") : _("single"));
825             }
826           if (first && EOF_STR (linebuf))
827             return -1;
828           if (!bc_ctl.replace_pat)
829             bc_push_arg (&bc_ctl, &bc_state,
830                          linebuf, len,
831                          NULL, 0,
832                          initial_args);
833           return len;
834         }
835       switch (state)
836         {
837         case SPACE:
838           if (ISSPACE (c))
839             continue;
840           state = NORM;
841           /* aaahhhh....  */
842
843         case NORM:
844           if (c == '\n')
845             {
846               if (!ISBLANK (prevc))
847                 lineno++;       /* For -l.  */
848               if (p == linebuf)
849                 {
850                   if (seen_arg)
851                     {
852                       /* An empty argument, add it to the list as normal. */
853                     }
854                   else
855                     {
856                       /* Blank line.  */
857                       state = SPACE;
858                       continue;
859                     }
860                 }
861               *p++ = '\0';
862               len = p - linebuf;
863               if (EOF_STR (linebuf))
864                 {
865                   eof = true;
866                   return first ? -1 : len;
867                 }
868               if (!bc_ctl.replace_pat)
869                 bc_push_arg (&bc_ctl, &bc_state,
870                              linebuf, len,
871                              NULL, 0,
872                              initial_args);
873               return len;
874             }
875           seen_arg = true;
876
877           /* POSIX: In the POSIX locale, the separators are <SPC> and
878            * <TAB>, but not <FF> or <VT>.
879            */
880           if (!bc_ctl.replace_pat && ISBLANK (c))
881             {
882               *p++ = '\0';
883               len = p - linebuf;
884               if (EOF_STR (linebuf))
885                 {
886                   eof = true;
887                   return first ? -1 : len;
888                 }
889               bc_push_arg (&bc_ctl, &bc_state,
890                            linebuf, len,
891                            NULL, 0,
892                            initial_args);
893               p = linebuf;
894               state = SPACE;
895               first = false;
896               continue;
897             }
898           switch (c)
899             {
900             case '\\':
901               state = BACKSLASH;
902               continue;
903
904             case '\'':
905             case '"':
906               state = QUOTE;
907               quotc = c;
908               continue;
909             }
910           break;
911
912         case QUOTE:
913           if (c == '\n')
914             {
915               exec_if_possible ();
916               error (EXIT_FAILURE, 0, _("unmatched %s quote; by default quotes are special to xargs unless you use the -0 option"),
917                      quotc == '"' ? _("double") : _("single"));
918             }
919           if (c == quotc)
920             {
921               state = NORM;
922               seen_arg = true; /* Makes a difference for e.g. just '' or "" as the first arg on a line */
923               continue;
924             }
925           break;
926
927         case BACKSLASH:
928           state = NORM;
929           break;
930         }
931
932       if ( (0 == c) && !nullwarning_given )
933         {
934           /* This is just a warning message.  We only issue it once. */
935           error (0, 0,
936                  _("WARNING: a NUL character occurred in the input.  "
937                    "It cannot be passed through in the argument list.  "
938                    "Did you mean to use the --null option?"));
939           nullwarning_given = 1;
940         }
941
942 #if 1
943       if (p >= endbuf)
944         {
945           exec_if_possible ();
946           error (EXIT_FAILURE, 0, _("argument line too long"));
947         }
948       *p++ = c;
949 #else
950       append_char_to_buf (&linebuf, &endbuf, &p, c);
951 #endif
952     }
953 }
954
955 /* Read a null-terminated string from the input and add it to the list of
956    arguments to pass to the command.
957    Return -1 if eof (either physical or logical) is reached,
958    otherwise the length of the string read (including the null).  */
959
960 static int
961 read_string (void)
962 {
963   static bool eof = false;
964   int len;
965   char *p = linebuf;
966   /* Including the NUL, the args must not grow past this point.  */
967   char *endbuf = linebuf + bc_ctl.arg_max - bc_state.cmd_initial_argv_chars - 1;
968
969   if (eof)
970     return -1;
971   while (1)
972     {
973       int c = getc (input_stream);
974       if (c == EOF)
975         {
976           eof = true;
977           if (p == linebuf)
978             return -1;
979           *p++ = '\0';
980           len = p - linebuf;
981           if (!bc_ctl.replace_pat)
982             bc_push_arg (&bc_ctl, &bc_state,
983                          linebuf, len,
984                          NULL, 0,
985                          initial_args);
986           return len;
987         }
988       if (c == input_delimiter)
989         {
990           lineno++;             /* For -l.  */
991           *p++ = '\0';
992           len = p - linebuf;
993           if (!bc_ctl.replace_pat)
994             bc_push_arg (&bc_ctl, &bc_state,
995                          linebuf, len,
996                          NULL, 0,
997                          initial_args);
998           return len;
999         }
1000       if (p >= endbuf)
1001         {
1002           exec_if_possible ();
1003           error (EXIT_FAILURE, 0, _("argument line too long"));
1004         }
1005       *p++ = c;
1006     }
1007 }
1008
1009 /* Print the arguments of the command to execute.
1010    If ASK is nonzero, prompt the user for a response, and
1011    if the user responds affirmatively, return true;
1012    otherwise, return false.  */
1013
1014 static bool
1015 print_args (bool ask)
1016 {
1017   int i;
1018
1019   for (i = 0; i < bc_state.cmd_argc - 1; i++)
1020     fprintf (stderr, "%s ", bc_state.cmd_argv[i]);
1021   if (ask)
1022     {
1023       static FILE *tty_stream;
1024       int c, savec;
1025
1026       if (!tty_stream)
1027         {
1028           tty_stream = fopen ("/dev/tty", "r");
1029           if (!tty_stream)
1030             error (EXIT_FAILURE, errno,
1031                    _("failed to open /dev/tty for reading"));
1032         }
1033       fputs ("?...", stderr);
1034       fflush (stderr);
1035       c = savec = getc (tty_stream);
1036       while (c != EOF && c != '\n')
1037         c = getc (tty_stream);
1038       if (savec == 'y' || savec == 'Y')
1039         return true;
1040     }
1041   else
1042     putc ('\n', stderr);
1043
1044   return false;
1045 }
1046
1047
1048 /* Close stdin and attach /dev/null to it.
1049  * This resolves Savannah bug #3992.
1050  */
1051 static void
1052 prep_child_for_exec (void)
1053 {
1054   if (!keep_stdin)
1055     {
1056       const char inputfile[] = "/dev/null";
1057       /* fprintf (stderr, "attaching stdin to /dev/null\n"); */
1058
1059       close (0);
1060       if (open (inputfile, O_RDONLY) < 0)
1061         {
1062           /* This is not entirely fatal, since
1063            * executing the child with a closed
1064            * stdin is almost as good as executing it
1065            * with its stdin attached to /dev/null.
1066            */
1067           error (0, errno, "%s", quotearg_n_style (0, locale_quoting_style, inputfile));
1068         }
1069     }
1070 }
1071
1072
1073 /* Execute the command that has been built in `cmd_argv'.  This may involve
1074    waiting for processes that were previously executed.
1075
1076    There are a number of cases where we want to terminate the current (child)
1077    process.  We do this by calling _exit () rather than exit () in order to
1078    avoid the invocation of wait_for_proc_all (), which was registered by the parent
1079    as an atexit () function.
1080 */
1081 static int
1082 xargs_do_exec (struct buildcmd_control *ctl, void *usercontext, int argc, char **argv)
1083 {
1084   pid_t child;
1085   int fd[2];
1086   int buf;
1087   int r;
1088
1089   (void) ctl;
1090
1091   if (!query_before_executing || print_args (true))
1092     {
1093       if (proc_max)
1094         {
1095           while (procs_executing >= proc_max)
1096             {
1097               wait_for_proc (false, 1u);
1098             }
1099         }
1100       if (!query_before_executing && print_command)
1101         print_args (false);
1102
1103       /* Before forking, reap any already-exited child. We do this so
1104          that we don't leave unreaped children around while we build a
1105          new command line.  For example this command will spend most
1106          of its time waiting for sufficient arguments to launch
1107          another command line:
1108
1109          seq 1 1000 | fmt | while read x ; do echo $x; sleep 1 ; done |
1110          ./xargs -P 200 -n 20  sh -c 'echo "$@"; sleep $((1 + $RANDOM % 5))' sleeper
1111       */
1112       wait_for_proc (false, 0u);
1113
1114       if (pipe (fd))
1115         error (EXIT_FAILURE, errno, _("could not create pipe before fork"));
1116       fcntl (fd[1], F_SETFD, FD_CLOEXEC);
1117
1118       /* If we run out of processes, wait for a child to return and
1119          try again.  */
1120       while ((child = fork ()) < 0 && errno == EAGAIN && procs_executing)
1121         wait_for_proc (false, 1u);
1122
1123       switch (child)
1124         {
1125         case -1:
1126           error (EXIT_FAILURE, errno, _("cannot fork"));
1127
1128         case 0:         /* Child.  */
1129           {
1130             close (fd[0]);
1131             child_error = EXIT_SUCCESS;
1132
1133             prep_child_for_exec ();
1134
1135             if (bc_args_exceed_testing_limit (argv))
1136               errno = E2BIG;
1137             else
1138               execvp (argv[0], argv);
1139             if (errno)
1140               {
1141                 /* Write errno value to parent.  We do this even if
1142                  * the error was not E2BIG, because we need to
1143                  * distinguish successful execs from unsuccessful
1144                  * ones.  The reason we need to do this is to know
1145                  * whether to reap the child here (preventing the
1146                  * exit status processing in wait_for_proc () from
1147                  * changing the value of child_error) or leave it
1148                  * for wait_for_proc () to handle.  We need to have
1149                  * wait_for_proc () handle the exit values from the
1150                  * utility if we run it, for POSIX compliance on the
1151                  * handling of exit values.
1152                  */
1153                 write (fd[1], &errno, sizeof (int));
1154               }
1155
1156             close (fd[1]);
1157             if (E2BIG != errno)
1158               {
1159                 error (0, errno, "%s", argv[0]);
1160               }
1161             /* The actual value returned here should be irrelevant,
1162              * because the parent will test our value of errno.
1163              */
1164             _exit (errno == ENOENT ? XARGS_EXIT_COMMAND_NOT_FOUND : XARGS_EXIT_COMMAND_CANNOT_BE_RUN);
1165
1166           /*NOTREACHED*/
1167           } /* child */
1168
1169         default:
1170           {
1171             /* Parent */
1172             close (fd[1]);
1173           }
1174
1175         } /* switch (child) */
1176       /*fprintf (stderr, "forked child (bc_state.cmd_argc=%d) -> ", bc_state.cmd_argc);*/
1177
1178       switch (r = read (fd[0], &buf, sizeof (int)))
1179         {
1180         case -1:
1181           {
1182             close (fd[0]);
1183             error (0, errno,
1184                    _("errno-buffer read failed in xargs_do_exec "
1185                      "(this is probably a bug, please report it)"));
1186             break;
1187           }
1188
1189         case sizeof (int):
1190           {
1191             /* Failure */
1192             int childstatus;
1193
1194             close (fd[0]);
1195
1196             /* we know the child is about to exit, so wait for that.
1197              * We have to do this so that wait_for_proc () does not
1198              * change the value of child_error on the basis of the
1199              * return value -- since in this case we did not launch
1200              * the utility.
1201              *
1202              * We do the wait before deciding if we failed in order to
1203              * avoid creating a zombie, even briefly.
1204              */
1205             waitpid (child, &childstatus, 0);
1206
1207
1208             if (E2BIG == buf)
1209               {
1210                 return 0; /* Failure; caller should pass fewer args */
1211               }
1212             else if (ENOENT == buf)
1213               {
1214                 exit (XARGS_EXIT_COMMAND_NOT_FOUND); /* command cannot be found */
1215               }
1216             else
1217               {
1218                 exit (XARGS_EXIT_COMMAND_CANNOT_BE_RUN); /* command cannot be run */
1219               }
1220             break;
1221           }
1222
1223         case 0:
1224           {
1225             /* Failed to read data from pipe; the exec must have
1226              * succeeded.  We call add_proc only in this case,
1227              * because it increments procs_executing, and we only
1228              * want to do that if we didn't already wait for the
1229              * child.
1230              */
1231             add_proc (child);
1232             break;
1233           }
1234         default:
1235           {
1236             error (EXIT_FAILURE, errno,
1237                    _("read returned unexpected value %d; "
1238                      "this is probably a bug, please report it"), r);
1239           }
1240         } /* switch on bytes read */
1241       close (fd[0]);
1242     }
1243   return 1;                     /* Success */
1244 }
1245
1246 /* Execute the command if possible.  */
1247
1248 static void
1249 exec_if_possible (void)
1250 {
1251   if (bc_ctl.replace_pat || initial_args ||
1252       bc_state.cmd_argc == bc_ctl.initial_argc || bc_ctl.exit_if_size_exceeded)
1253     return;
1254   bc_do_exec (&bc_ctl, &bc_state);
1255 }
1256
1257 /* Add the process with id PID to the list of processes that have
1258    been executed.  */
1259
1260 static void
1261 add_proc (pid_t pid)
1262 {
1263   unsigned int i, j;
1264
1265   /* Find an empty slot.  */
1266   for (i = 0; i < pids_alloc && pids[i]; i++)
1267     ;
1268
1269   /* Extend the array if we failed. */
1270   if (i == pids_alloc)
1271     {
1272       pids = x2nrealloc (pids, &pids_alloc, sizeof *pids);
1273
1274       /* Zero out the new slots. */
1275       for (j=i; j<pids_alloc; ++j)
1276         pids[j] = (pid_t)0;
1277     }
1278   /* Verify that we are not destroying the record of some existing child. */
1279   assert (0 == pids[i]);
1280
1281   /* Remember the child. */
1282   pids[i] = pid;
1283   procs_executing++;
1284   procs_executed = true;
1285 }
1286
1287
1288 /* If ALL is true, wait for all child processes to finish;
1289    otherwise, wait for one child process to finish, or for another signal
1290    that tells us that we can run more child processes.
1291    Remove the processes that finish from the list of executing processes.  */
1292
1293 static void
1294 wait_for_proc (bool all, unsigned int minreap)
1295 {
1296   unsigned int reaped = 0;
1297
1298   while (procs_executing)
1299     {
1300       unsigned int i;
1301       int status;
1302       pid_t pid;
1303       int wflags = 0;
1304
1305       if (!all)
1306         {
1307           if (reaped >= minreap)
1308             {
1309               /* We already reaped enough children.  To save system
1310                * resources, reap any dead children anyway, but do not
1311                * wait for any currently executing children to exit.
1312
1313                */
1314               wflags = WNOHANG;
1315             }
1316         }
1317
1318       stop_waiting = 0;
1319       do
1320         {
1321           /* Wait for any child.   We used to use wait () here, but it's
1322            * unlikely that that offers any portability advantage over
1323            * wait these days.
1324            */
1325           while ((pid = waitpid (-1, &status, wflags)) == (pid_t) -1)
1326             {
1327               if (errno != EINTR)
1328                 error (EXIT_FAILURE, errno,
1329                        _("error waiting for child process"));
1330
1331               if (stop_waiting && !all)
1332                 {
1333                   /* Receipt of SIGUSR1 gave us an extra slot and we
1334                    * don't need to wait for all processes to finish.
1335                    * We can stop reaping now, but in any case check for 
1336                    * further dead children without waiting for another 
1337                    * to exit.
1338                    */
1339                   wflags = WNOHANG;
1340                 }
1341             }
1342
1343           /* Find the entry in `pids' for the child process
1344              that exited.  */
1345           if (pid)
1346             {
1347               for (i = 0; i < pids_alloc && pid != pids[i]; i++)
1348                 ;
1349             }
1350         }
1351       while (pid && i == pids_alloc);   /* A child died that we didn't start? */
1352
1353       if (!pid)
1354         {
1355           if (!(wflags & WNOHANG))
1356             {
1357               /* Nothing remained to be reaped.  This should not
1358                * happen, because procs_executing should contain the
1359                * number of child processes still executing, so the
1360                * loop should have terminated.
1361                */
1362               error (0, 0, _("WARNING: Lost track of %d child processes"),
1363                      procs_executing);
1364             }
1365           else
1366             {
1367               /* Children are (probably) executing but are not ready
1368                * to be reaped at the moment.
1369                */
1370             }
1371           break;
1372         }
1373
1374       /* Remove the child from the list.  */
1375       pids[i] = 0;
1376       procs_executing--;
1377       reaped++;
1378
1379       if (WEXITSTATUS (status) == CHILD_EXIT_PLEASE_STOP_IMMEDIATELY)
1380         error (XARGS_EXIT_CLIENT_EXIT_255, 0,
1381                _("%s: exited with status 255; aborting"), bc_state.cmd_argv[0]);
1382       if (WIFSTOPPED (status))
1383         error (XARGS_EXIT_CLIENT_FATAL_SIG, 0,
1384                _("%s: stopped by signal %d"), bc_state.cmd_argv[0], WSTOPSIG (status));
1385       if (WIFSIGNALED (status))
1386         error (XARGS_EXIT_CLIENT_FATAL_SIG, 0,
1387                _("%s: terminated by signal %d"), bc_state.cmd_argv[0], WTERMSIG (status));
1388       if (WEXITSTATUS (status) != 0)
1389         child_error = XARGS_EXIT_CLIENT_EXIT_NONZERO;
1390     }
1391 }
1392
1393 /* Wait for all child processes to finish.  */
1394
1395 static void
1396 wait_for_proc_all (void)
1397 {
1398   static bool waiting = false;
1399
1400   /* This function was registered by the original, parent, process.
1401    * The child processes must not call exit () to terminate, since this
1402    * will mean that their exit status will be inappropriately changed.
1403    * Instead the child processes should call _exit ().  If someone
1404    * forgets this rule, you may see the following assert () fail.
1405    */
1406   assert (getpid () == parent);
1407
1408   if (waiting)
1409     return;
1410
1411   waiting = true;
1412   wait_for_proc (true, 0u);
1413   waiting = false;
1414
1415   if (original_exit_value != child_error)
1416     {
1417       /* wait_for_proc () changed the value of child_error ().  This
1418        * function is registered via atexit (), and so may have been
1419        * called from exit ().  We now know that the original value
1420        * passed to exit () is no longer the exit status we require.
1421        * The POSIX standard states that the behaviour if exit () is
1422        * called more than once is undefined.  Therefore we now have to
1423        * exit with _exit () instead of exit ().
1424        */
1425       _exit (child_error);
1426     }
1427
1428 }
1429
1430
1431 /* Increment or decrement the number of processes we can start simultaneously,
1432    when we receive a signal from the outside world.
1433    
1434    We must take special care around proc_max == 0 (unlimited children),
1435    proc_max == 1 (don't decrement to zero).  */
1436 static void
1437 increment_proc_max (int ignore)
1438 {
1439         /* If user increments from 0 to 1, we'll take it and serialize. */
1440         proc_max++;
1441         /* If we're waiting for a process to die before doing something,
1442            no need to wait any more. */
1443         stop_waiting = 1;
1444 }
1445
1446 static void
1447 decrement_proc_max (int ignore)
1448 {
1449         if (proc_max > 1)
1450                 proc_max--;
1451 }
1452
1453
1454 /* Return the value of the number represented in STR.
1455    OPTION is the command line option to which STR is the argument.
1456    If the value does not fall within the boundaries MIN and MAX,
1457    Print an error message mentioning OPTION.  If FATAL is true,
1458    we also exit. */
1459
1460 static long
1461 parse_num (char *str, int option, long int min, long int max, int fatal)
1462 {
1463   char *eptr;
1464   long val;
1465
1466   val = strtol (str, &eptr, 10);
1467   if (eptr == str || *eptr)
1468     {
1469       fprintf (stderr, _("%s: invalid number for -%c option\n"),
1470                program_name, option);
1471       usage (stderr);
1472       exit (EXIT_FAILURE);
1473     }
1474   else if (val < min)
1475     {
1476       fprintf (stderr, _("%s: value for -%c option should be >= %ld\n"),
1477                program_name, option, min);
1478       if (fatal)
1479         {
1480           usage (stderr);
1481           exit (EXIT_FAILURE);
1482         }
1483       else
1484         {
1485           val = min;
1486         }
1487     }
1488   else if (max >= 0 && val > max)
1489     {
1490       fprintf (stderr, _("%s: value for -%c option should be < %ld\n"),
1491                program_name, option, max);
1492       if (fatal)
1493         {
1494           usage (stderr);
1495           exit (EXIT_FAILURE);
1496         }
1497       else
1498         {
1499           val = max;
1500         }
1501     }
1502   return val;
1503 }
1504
1505 static void
1506 usage (FILE *stream)
1507 {
1508   fprintf (stream, _("\
1509 Usage: %s [-0prtx] [--interactive] [--null] [-d|--delimiter=delim]\n\
1510        [-E eof-str] [-e[eof-str]]  [--eof[=eof-str]]\n\
1511        [-L max-lines] [-l[max-lines]] [--max-lines[=max-lines]]\n\
1512        [-I replace-str] [-i[replace-str]] [--replace[=replace-str]]\n\
1513        [-n max-args] [--max-args=max-args]\n\
1514        [-s max-chars] [--max-chars=max-chars]\n\
1515        [-P max-procs]  [--max-procs=max-procs] [--show-limits]\n\
1516        [--verbose] [--exit] [--no-run-if-empty] [--arg-file=file]\n\
1517        [--version] [--help] [command [initial-arguments]]\n"),
1518            program_name);
1519   fputs (_("\nReport bugs to <bug-findutils@gnu.org>.\n"), stream);
1520 }