~ubuntu-branches/ubuntu/raring/findutils/raring

« back to all changes in this revision

Viewing changes to xargs/xargs.c

  • Committer: Bazaar Package Importer
  • Author(s): Andreas Metzler
  • Date: 2005-07-04 11:37:37 UTC
  • mto: (11.1.1 lenny) (1.1.10 upstream)
  • mto: This revision was merged to the branch mainline in revision 4.
  • Revision ID: james.westby@ubuntu.com-20050704113737-oxfumqxsqgfz5gay
Tags: upstream-4.2.22
ImportĀ upstreamĀ versionĀ 4.2.22

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/* xargs -- build and execute command lines from standard input
2
 
   Copyright (C) 1990, 91, 92, 93, 94, 2000 Free Software Foundation, Inc.
 
2
   Copyright (C) 1990, 91, 92, 93, 94, 2000, 2003, 2005 Free Software Foundation, Inc.
3
3
 
4
4
   This program is free software; you can redistribute it and/or modify
5
5
   it under the terms of the GNU General Public License as published by
13
13
 
14
14
   You should have received a copy of the GNU General Public License
15
15
   along with this program; if not, write to the Free Software
16
 
   Foundation, Inc., 9 Temple Place - Suite 330, Boston, MA 02111-1307,
 
16
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
17
17
   USA.
18
18
*/
19
19
 
20
20
/* Written by Mike Rendell <michael@cs.mun.ca>
21
 
   and David MacKenzie <djm@gnu.ai.mit.edu>.  */
 
21
   and David MacKenzie <djm@gnu.org>.  */
22
22
 
23
 
#include <gnulib/config.h>
24
 
#undef VERSION
25
 
#undef PACKAGE_VERSION
26
 
#undef PACKAGE_TARNAME
27
 
#undef PACKAGE_STRING
28
 
#undef PACKAGE_NAME
29
 
#undef PACKAGE
30
23
#include <config.h>
31
24
 
32
25
# ifndef PARAMS
37
30
#  endif
38
31
# endif
39
32
 
40
 
#ifndef _GNU_SOURCE
41
 
#define _GNU_SOURCE
42
 
#endif
43
33
#include <ctype.h>
44
34
 
45
35
#if !defined (isascii) || defined (STDC_HEADERS)
62
52
#include <stdio.h>
63
53
#include <errno.h>
64
54
#include <getopt.h>
 
55
#include <fcntl.h>
 
56
 
 
57
#if defined(STDC_HEADERS)
 
58
#include <assert.h>
 
59
#endif
65
60
 
66
61
#if defined(HAVE_STRING_H) || defined(STDC_HEADERS)
67
62
#include <string.h>
95
90
#define SIGCHLD SIGCLD
96
91
#endif
97
92
 
98
 
/* COMPAT:  SYSV version defaults size (and has a max value of) to 470.
99
 
   We try to make it as large as possible. */
100
 
#if !defined(ARG_MAX) && defined(_SC_ARG_MAX)
101
 
#define ARG_MAX sysconf (_SC_ARG_MAX)
102
 
#endif
103
 
#ifndef ARG_MAX
104
 
#define ARG_MAX NCARGS
105
 
#endif
106
 
 
107
93
#include "wait.h"
108
94
 
109
95
/* States for read_line. */
132
118
#ifdef gettext_noop
133
119
# define N_(String) gettext_noop (String)
134
120
#else
135
 
# define N_(String) (String)
 
121
/* See locate.c for explanation as to why not use (String) */
 
122
# define N_(String) String
136
123
#endif
137
124
 
 
125
#include "buildcmd.h"
 
126
 
 
127
 
138
128
/* Return nonzero if S is the EOF string.  */
139
129
#define EOF_STR(s) (eof_str && *eof_str == *s && !strcmp (eof_str, s))
140
130
 
141
131
extern char **environ;
142
132
 
 
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)
 
144
 
 
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
 
154
 
143
155
/* Not char because of type promotion; NeXT gcc can't handle it.  */
144
156
typedef int boolean;
145
157
#define         true    1
152
164
#endif
153
165
 
154
166
#include <xalloc.h>
 
167
#include "closeout.h"
 
168
 
155
169
void error PARAMS ((int status, int errnum, char *message,...));
156
170
 
157
171
extern char *version_string;
159
173
/* The name this program was run with.  */
160
174
char *program_name;
161
175
 
162
 
/* Buffer for reading arguments from stdin.  */
 
176
static FILE *input_stream;
 
177
 
 
178
/* Buffer for reading arguments from input.  */
163
179
static char *linebuf;
164
180
 
 
181
static int keep_stdin = 0;
 
182
 
165
183
/* Line number in stdin since the last command was executed.  */
166
184
static int lineno = 0;
167
185
 
 
186
static struct buildcmd_state bc_state;
 
187
static struct buildcmd_control bc_ctl;
 
188
 
 
189
 
 
190
#if 0
168
191
/* If nonzero, then instead of putting the args from stdin at
169
192
   the end of the command argument list, they are each stuck into the
170
193
   initial args, replacing each occurrence of the `replace_pat' in the
171
194
   initial args.  */
172
195
static char *replace_pat = NULL;
173
196
 
 
197
 
174
198
/* The length of `replace_pat'.  */
175
199
static size_t rplen = 0;
 
200
#endif
176
201
 
177
202
/* If nonzero, when this string is read on stdin it is treated as
178
203
   end of file.
179
 
   I don't like this - it should default to NULL.  */
180
 
static char *eof_str = "_";
 
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 "_".
 
206
*/
 
207
static char *eof_str = NULL;
181
208
 
 
209
#if 0
182
210
/* If nonzero, the maximum number of nonblank lines from stdin to use
183
211
   per command line.  */
184
212
static long lines_per_exec = 0;
188
216
 
189
217
/* If true, exit if lines_per_exec or args_per_exec is exceeded.  */
190
218
static boolean exit_if_size_exceeded = false;
191
 
 
192
219
/* The maximum number of characters that can be used per command line.  */
193
220
static long arg_max;
194
 
 
195
221
/* Storage for elements of `cmd_argv'.  */
196
222
static char *argbuf;
 
223
#endif
197
224
 
 
225
#if 0
198
226
/* The list of args being built.  */
199
227
static char **cmd_argv = NULL;
200
228
 
201
229
/* Number of elements allocated for `cmd_argv'.  */
202
230
static int cmd_argv_alloc = 0;
 
231
#endif
203
232
 
 
233
#if 0
204
234
/* Number of valid elements in `cmd_argv'.  */
205
235
static int cmd_argc = 0;
206
 
 
207
236
/* Number of chars being used in `cmd_argv'.  */
208
237
static int cmd_argv_chars = 0;
209
238
 
210
239
/* Number of initial arguments given on the command line.  */
211
240
static int initial_argc = 0;
 
241
#endif
212
242
 
213
243
/* Number of chars in the initial args.  */
214
 
static int initial_argv_chars = 0;
 
244
/* static int initial_argv_chars = 0; */
215
245
 
216
246
/* true when building up initial arguments in `cmd_argv'.  */
217
247
static boolean initial_args = true;
237
267
static int child_error = 0;
238
268
 
239
269
/* If true, print each command on stderr before executing it.  */
240
 
static boolean print_command = false;
 
270
static boolean print_command = false; /* Option -t */
241
271
 
242
272
/* If true, query the user before executing each command, and only
243
273
   execute the command if the user responds affirmatively.  */
246
276
static struct option const longopts[] =
247
277
{
248
278
  {"null", no_argument, NULL, '0'},
 
279
  {"arg-file", required_argument, NULL, 'a'},
249
280
  {"eof", optional_argument, NULL, 'e'},
250
 
  {"replace", optional_argument, NULL, 'i'},
 
281
  {"replace", optional_argument, NULL, 'I'},
251
282
  {"max-lines", optional_argument, NULL, 'l'},
252
283
  {"max-args", required_argument, NULL, 'n'},
253
284
  {"interactive", no_argument, NULL, 'p'},
254
285
  {"no-run-if-empty", no_argument, NULL, 'r'},
255
286
  {"max-chars", required_argument, NULL, 's'},
256
287
  {"verbose", no_argument, NULL, 't'},
 
288
  {"show-limits", no_argument, NULL, 'S'},
257
289
  {"exit", no_argument, NULL, 'x'},
258
290
  {"max-procs", required_argument, NULL, 'P'},
259
291
  {"version", no_argument, NULL, 'v'},
263
295
 
264
296
static int read_line PARAMS ((void));
265
297
static int read_string PARAMS ((void));
 
298
#if 0
 
299
static char *mbstrstr PARAMS ((const char *haystack, const char *needle));
266
300
static void do_insert PARAMS ((char *arg, size_t arglen, size_t lblen));
267
301
static void push_arg PARAMS ((char *arg, size_t len));
 
302
#endif
268
303
static boolean print_args PARAMS ((boolean ask));
269
 
static void do_exec PARAMS ((void));
 
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));
270
307
static void add_proc PARAMS ((pid_t pid));
271
308
static void wait_for_proc PARAMS ((boolean all));
272
 
static long parse_num PARAMS ((char *str, int option, long min, long max));
 
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));
273
311
static long env_size PARAMS ((char **envp));
274
 
static void usage PARAMS ((FILE * stream, int status));
 
312
static void usage PARAMS ((FILE * stream));
 
313
 
 
314
 
 
315
 
 
316
static long
 
317
get_line_max(void)
 
318
{
 
319
  long val;
 
320
#ifdef _SC_LINE_MAX  
 
321
  val = sysconf(_SC_LINE_MAX);
 
322
#else
 
323
  val = -1;
 
324
#endif
 
325
  
 
326
  if (val > 0)
 
327
    return val;
 
328
 
 
329
  /* either _SC_LINE_MAX was not available or 
 
330
   * there is no particular limit.
 
331
   */
 
332
#ifdef LINE_MAX
 
333
  val = LINE_MAX;
 
334
#endif
 
335
 
 
336
  if (val > 0)
 
337
    return val;
 
338
 
 
339
  return 2048L;                 /* a reasonable guess. */
 
340
}
 
341
 
275
342
 
276
343
int
277
344
main (int argc, char **argv)
278
345
{
279
346
  int optc;
 
347
  int show_limits = 0;                  /* --show-limits */
280
348
  int always_run_command = 1;
281
 
  long orig_arg_max;
 
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);
282
354
  char *default_cmd = "/bin/echo";
283
355
  int (*read_args) PARAMS ((void)) = read_line;
284
356
 
289
361
#endif
290
362
  bindtextdomain (PACKAGE, LOCALEDIR);
291
363
  textdomain (PACKAGE);
292
 
 
293
 
  orig_arg_max = ARG_MAX;
294
 
  if (orig_arg_max == -1)
295
 
    orig_arg_max = LONG_MAX;
296
 
  orig_arg_max -= 2048; /* POSIX.2 requires subtracting 2048.  */
297
 
  arg_max = orig_arg_max;
298
 
 
299
 
  /* Sanity check for systems with huge ARG_MAX defines (e.g., Suns which
300
 
     have it at 1 meg).  Things will work fine with a large ARG_MAX but it
301
 
     will probably hurt the system more than it needs to; an array of this
302
 
     size is allocated.  */
303
 
  if (arg_max > 20 * 1024)
304
 
    arg_max = 20 * 1024;
 
364
  atexit (close_stdout);
 
365
  atexit (wait_for_proc_all);
 
366
 
 
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.
 
370
   */
 
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.  */
 
374
 
 
375
  bc_init_controlinfo(&bc_ctl);
 
376
  assert(bc_ctl.arg_max == posix_arg_size_max);
 
377
 
 
378
  bc_ctl.exec_callback = xargs_do_exec;
 
379
 
 
380
  
 
381
  /* Start with a reasonable default size, though this can be
 
382
   * adjusted via the -s option.
 
383
   */
 
384
  arg_size = (128 * 1024) + size_of_environment;
305
385
 
306
386
  /* Take the size of the environment into account.  */
307
 
  arg_max -= env_size (environ);
308
 
  if (arg_max <= 0)
309
 
    error (1, 0, _("environment is too large for exec"));
310
 
 
311
 
  while ((optc = getopt_long (argc, argv, "+0e::i::l::n:prs:txP:",
 
387
  if (size_of_environment > posix_arg_size_max)
 
388
    {
 
389
      error (1, 0, _("environment is too large for exec"));
 
390
    }
 
391
  else
 
392
    {
 
393
      bc_ctl.arg_max = posix_arg_size_max - size_of_environment;
 
394
    }
 
395
 
 
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;
 
401
  
 
402
  
 
403
 
 
404
  
 
405
  while ((optc = getopt_long (argc, argv, "+0a:E:e::i::I:l::L:n:prs:txP:",
312
406
                              longopts, (int *) 0)) != -1)
313
407
    {
314
408
      switch (optc)
317
411
          read_args = read_string;
318
412
          break;
319
413
 
320
 
        case 'e':
321
 
          if (optarg)
 
414
        case 'E':               /* POSIX */
 
415
        case 'e':               /* deprecated */
 
416
          if (optarg && (strlen(optarg) > 0))
322
417
            eof_str = optarg;
323
418
          else
324
419
            eof_str = 0;
325
420
          break;
326
421
 
327
422
        case 'h':
328
 
          usage (stdout, 0);
 
423
          usage (stdout);
 
424
          return 0;
329
425
 
330
 
        case 'i':
 
426
        case 'I':               /* POSIX */
 
427
        case 'i':               /* deprecated */
331
428
          if (optarg)
332
 
            replace_pat = optarg;
 
429
            bc_ctl.replace_pat = optarg;
333
430
          else
334
 
            replace_pat = "{}";
 
431
            bc_ctl.replace_pat = "{}";
335
432
          /* -i excludes -n -l.  */
336
 
          args_per_exec = 0;
337
 
          lines_per_exec = 0;
 
433
          bc_ctl.args_per_exec = 0;
 
434
          bc_ctl.lines_per_exec = 0;
338
435
          break;
339
436
 
340
 
        case 'l':
 
437
        case 'L':               /* POSIX */
 
438
        case 'l':               /* deprecated */
341
439
          if (optarg)
342
 
            lines_per_exec = parse_num (optarg, 'l', 1L, -1L);
 
440
            bc_ctl.lines_per_exec = parse_num (optarg, 'l', 1L, -1L, 1);
343
441
          else
344
 
            lines_per_exec = 1;
 
442
            bc_ctl.lines_per_exec = 1;
345
443
          /* -l excludes -i -n.  */
346
 
          args_per_exec = 0;
347
 
          replace_pat = NULL;
 
444
          bc_ctl.args_per_exec = 0;
 
445
          bc_ctl.replace_pat = NULL;
348
446
          break;
349
447
 
350
448
        case 'n':
351
 
          args_per_exec = parse_num (optarg, 'n', 1L, -1L);
 
449
          bc_ctl.args_per_exec = parse_num (optarg, 'n', 1L, -1L, 1);
352
450
          /* -n excludes -i -l.  */
353
 
          lines_per_exec = 0;
354
 
          replace_pat = NULL;
 
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;
355
457
          break;
356
458
 
 
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.
 
462
           */
357
463
        case 's':
358
 
          arg_max = parse_num (optarg, 's', 1L, orig_arg_max);
 
464
          arg_size = parse_num (optarg, 's', 1L, posix_arg_size_max, 0);
 
465
          if (arg_size > posix_arg_size_max)
 
466
            {
 
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;
 
469
            }
 
470
          break;
 
471
 
 
472
        case 'S':
 
473
          show_limits = true;
359
474
          break;
360
475
 
361
476
        case 't':
363
478
          break;
364
479
 
365
480
        case 'x':
366
 
          exit_if_size_exceeded = true;
 
481
          bc_ctl.exit_if_size_exceeded = true;
367
482
          break;
368
483
 
369
484
        case 'p':
376
491
          break;
377
492
 
378
493
        case 'P':
379
 
          proc_max = parse_num (optarg, 'P', 0L, -1L);
 
494
          proc_max = parse_num (optarg, 'P', 0L, -1L, 1);
380
495
          break;
381
496
 
 
497
        case 'a':
 
498
          input_file = optarg;
 
499
          break;
 
500
 
382
501
        case 'v':
383
502
          printf (_("GNU xargs version %s\n"), version_string);
384
 
          exit (0);
 
503
          return 0;
385
504
 
386
505
        default:
387
 
          usage (stderr, 1);
388
 
        }
389
 
    }
390
 
 
391
 
  if (replace_pat || lines_per_exec)
392
 
    exit_if_size_exceeded = true;
 
506
          usage (stderr);
 
507
          return 1;
 
508
        }
 
509
    }
 
510
 
 
511
  if (0 == strcmp (input_file, "-"))
 
512
    {
 
513
      input_stream = stdin;
 
514
    }
 
515
  else
 
516
    {
 
517
      keep_stdin = 1;           /* see prep_child_for_exec() */
 
518
      input_stream = fopen (input_file, "r");
 
519
      if (NULL == input_stream)
 
520
        {
 
521
          error (1, errno,
 
522
                 _("Cannot open input file `%s'"),
 
523
                 input_file);
 
524
        }
 
525
    }
 
526
 
 
527
  if (bc_ctl.replace_pat || bc_ctl.lines_per_exec)
 
528
    bc_ctl.exit_if_size_exceeded = true;
393
529
 
394
530
  if (optind == argc)
395
531
    {
398
534
      argv = &default_cmd;
399
535
    }
400
536
 
401
 
  linebuf = (char *) xmalloc (arg_max + 1);
402
 
  argbuf = (char *) xmalloc (arg_max + 1);
 
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>.
 
542
   */
 
543
  if (bc_ctl.arg_max > arg_size)
 
544
    {
 
545
      if (show_limits)
 
546
        {
 
547
          fprintf(stderr,
 
548
                  _("Reducing arg_max (%ld) to arg_size (%ld)\n"),
 
549
                  bc_ctl.arg_max, arg_size);
 
550
        }
 
551
      bc_ctl.arg_max = arg_size;
 
552
    }
 
553
 
 
554
  if (show_limits)
 
555
    {
 
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);
 
569
    }
 
570
  
 
571
  linebuf = (char *) xmalloc (bc_ctl.arg_max + 1);
 
572
  bc_state.argbuf = (char *) xmalloc (bc_ctl.arg_max + 1);
403
573
 
404
574
  /* Make sure to listen for the kids.  */
405
575
  signal (SIGCHLD, SIG_DFL);
406
576
 
407
 
  if (!replace_pat)
 
577
  if (!bc_ctl.replace_pat)
408
578
    {
409
579
      for (; optind < argc; optind++)
410
 
        push_arg (argv[optind], strlen (argv[optind]) + 1);
 
580
        bc_push_arg (&bc_ctl, &bc_state,
 
581
                     argv[optind], strlen (argv[optind]) + 1,
 
582
                     NULL, 0,
 
583
                     initial_args);
411
584
      initial_args = false;
412
 
      initial_argc = cmd_argc;
413
 
      initial_argv_chars = cmd_argv_chars;
 
585
      bc_ctl.initial_argc = bc_state.cmd_argc;
 
586
      bc_state.cmd_initial_argv_chars = bc_state.cmd_argv_chars;
414
587
 
415
588
      while ((*read_args) () != -1)
416
 
        if (lines_per_exec && lineno >= lines_per_exec)
 
589
        if (bc_ctl.lines_per_exec && lineno >= bc_ctl.lines_per_exec)
417
590
          {
418
 
            do_exec ();
 
591
            xargs_do_exec (&bc_ctl, &bc_state);
419
592
            lineno = 0;
420
593
          }
421
594
 
422
595
      /* SYSV xargs seems to do at least one exec, even if the
423
596
         input is empty.  */
424
 
      if (cmd_argc != initial_argc
 
597
      if (bc_state.cmd_argc != bc_ctl.initial_argc
425
598
          || (always_run_command && procs_executed == 0))
426
 
        do_exec ();
 
599
        xargs_do_exec (&bc_ctl, &bc_state);
 
600
 
427
601
    }
428
602
  else
429
603
    {
433
607
 
434
608
      for (i = optind; i < argc; i++)
435
609
        arglen[i] = strlen(argv[i]);
436
 
      rplen = strlen (replace_pat);
 
610
      bc_ctl.rplen = strlen (bc_ctl.replace_pat);
437
611
      while ((len = (*read_args) ()) != -1)
438
612
        {
439
613
          /* Don't do insert on the command name.  */
440
 
          push_arg (argv[optind], arglen[optind] + 1);
 
614
          bc_clear_args(&bc_ctl, &bc_state);
 
615
          bc_state.cmd_argv_chars = 0; /* begin at start of buffer */
 
616
          
 
617
          bc_push_arg (&bc_ctl, &bc_state,
 
618
                       argv[optind], arglen[optind] + 1,
 
619
                       NULL, 0,
 
620
                       initial_args);
441
621
          len--;
 
622
          initial_args = false;
 
623
          
442
624
          for (i = optind + 1; i < argc; i++)
443
 
            do_insert (argv[i], arglen[i], len);
444
 
          do_exec ();
445
 
        }
446
 
    }
447
 
 
448
 
  wait_for_proc (true);
449
 
  exit (child_error);
450
 
}
451
 
 
452
 
/* Read a line of arguments from stdin and add them to the list of
 
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);
 
631
        }
 
632
    }
 
633
 
 
634
  return child_error;
 
635
}
 
636
 
 
637
#if 0
 
638
static int
 
639
append_char_to_buf(char **pbuf, char **pend, char **pp, int c)
 
640
{
 
641
  char *end_of_buffer = *pend;
 
642
  char *start_of_buffer = *pbuf;
 
643
  char *p = *pp;
 
644
  if (p >= end_of_buffer)
 
645
    {
 
646
      if (bc_ctl.replace_pat)
 
647
        {
 
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)
 
653
            {
 
654
              end_of_buffer = start_of_buffer + len;
 
655
              p = start_of_buffer + offset;
 
656
              *p++ = c;
 
657
 
 
658
              /* Update the caller's idea of where the buffer is. */
 
659
              *pbuf = start_of_buffer;
 
660
              *pend = end_of_buffer;
 
661
              *pp = p;
 
662
              
 
663
              return 0;
 
664
            }
 
665
          else
 
666
            {
 
667
              /* Failed to reallocate. */
 
668
              return -1;
 
669
            }
 
670
        }
 
671
      else
 
672
        {
 
673
          /* I suspect that this can never happen now, because append_char_to_buf()
 
674
           * should only be called when replace_pat is true.
 
675
           */
 
676
          error (1, 0, _("argument line too long"));
 
677
          /*NOTREACHED*/
 
678
          return -1;
 
679
        }
 
680
    }
 
681
  else
 
682
    {
 
683
      /* Enough space remains. */
 
684
      *p++ = c;
 
685
      *pp = p;
 
686
      return 0;
 
687
    }
 
688
}
 
689
#endif
 
690
 
 
691
 
 
692
/* Read a line of arguments from the input and add them to the list of
453
693
   arguments to pass to the command.  Ignore blank lines and initial blanks.
454
694
   Single and double quotes and backslashes quote metacharacters and blanks
455
695
   as they do in the shell.
469
709
  int len;
470
710
  char *p = linebuf;
471
711
  /* Including the NUL, the args must not grow past this point.  */
472
 
  char *endbuf = linebuf + arg_max - initial_argv_chars - 1;
 
712
  char *endbuf = linebuf + bc_ctl.arg_max - bc_state.cmd_initial_argv_chars - 1;
473
713
 
474
714
  if (eof)
475
715
    return -1;
476
716
  while (1)
477
717
    {
478
718
      prevc = c;
479
 
      c = getc (stdin);
 
719
      c = getc (input_stream);
480
720
      if (c == EOF)
481
721
        {
482
722
          /* COMPAT: SYSV seems to ignore stuff on a line that
486
726
            return -1;
487
727
          *p++ = '\0';
488
728
          len = p - linebuf;
489
 
          /* FIXME we don't check for unterminated quotes here.  */
 
729
          if (state == QUOTE)
 
730
            {
 
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"));
 
734
            }
490
735
          if (first && EOF_STR (linebuf))
491
736
            return -1;
492
 
          if (!replace_pat)
493
 
            push_arg (linebuf, len);
 
737
          if (!bc_ctl.replace_pat)
 
738
            bc_push_arg (&bc_ctl, &bc_state,
 
739
                         linebuf, len,
 
740
                         NULL, 0,
 
741
                         initial_args);
494
742
          return len;
495
743
        }
496
744
      switch (state)
519
767
                  eof = true;
520
768
                  return first ? -1 : len;
521
769
                }
522
 
              if (!replace_pat)
523
 
                push_arg (linebuf, len);
 
770
              if (!bc_ctl.replace_pat)
 
771
                bc_push_arg (&bc_ctl, &bc_state,
 
772
                             linebuf, len,
 
773
                             NULL, 0,
 
774
                             initial_args);
524
775
              return len;
525
776
            }
526
 
          if (!replace_pat && ISSPACE (c))
 
777
          if (!bc_ctl.replace_pat && ISSPACE (c))
527
778
            {
528
779
              *p++ = '\0';
529
780
              len = p - linebuf;
532
783
                  eof = true;
533
784
                  return first ? -1 : len;
534
785
                }
535
 
              push_arg (linebuf, len);
 
786
              bc_push_arg (&bc_ctl, &bc_state,
 
787
                           linebuf, len,
 
788
                           NULL, 0,
 
789
                           initial_args);
536
790
              p = linebuf;
537
791
              state = SPACE;
538
792
              first = false;
554
808
 
555
809
        case QUOTE:
556
810
          if (c == '\n')
557
 
            error (1, 0, _("unmatched %s quote"),
558
 
                   quotc == '"' ? _("double") : _("single"));
 
811
            {
 
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"));
 
815
            }
559
816
          if (c == quotc)
560
817
            {
561
818
              state = NORM;
567
824
          state = NORM;
568
825
          break;
569
826
        }
 
827
#if 1
570
828
      if (p >= endbuf)
571
 
        error (1, 0, _("argument line too long"));
 
829
        {
 
830
          exec_if_possible ();
 
831
          error (1, 0, _("argument line too long"));
 
832
        }
572
833
      *p++ = c;
 
834
#else
 
835
      append_char_to_buf(&linebuf, &endbuf, &p, c);
 
836
#endif
573
837
    }
574
838
}
575
839
 
576
 
/* Read a null-terminated string from stdin and add it to the list of
 
840
/* Read a null-terminated string from the input and add it to the list of
577
841
   arguments to pass to the command.
578
842
   Return -1 if eof (either physical or logical) is reached,
579
843
   otherwise the length of the string read (including the null).  */
585
849
  int len;
586
850
  char *p = linebuf;
587
851
  /* Including the NUL, the args must not grow past this point.  */
588
 
  char *endbuf = linebuf + arg_max - initial_argv_chars - 1;
 
852
  char *endbuf = linebuf + bc_ctl.arg_max - bc_state.cmd_initial_argv_chars - 1;
589
853
 
590
854
  if (eof)
591
855
    return -1;
592
856
  while (1)
593
857
    {
594
 
      int c = getc (stdin);
 
858
      int c = getc (input_stream);
595
859
      if (c == EOF)
596
860
        {
597
861
          eof = true;
599
863
            return -1;
600
864
          *p++ = '\0';
601
865
          len = p - linebuf;
602
 
          if (!replace_pat)
603
 
            push_arg (linebuf, len);
 
866
          if (!bc_ctl.replace_pat)
 
867
            bc_push_arg (&bc_ctl, &bc_state,
 
868
                         linebuf, len,
 
869
                         NULL, 0,
 
870
                         initial_args);
604
871
          return len;
605
872
        }
606
873
      if (c == '\0')
608
875
          lineno++;             /* For -l.  */
609
876
          *p++ = '\0';
610
877
          len = p - linebuf;
611
 
          if (!replace_pat)
612
 
            push_arg (linebuf, len);
 
878
          if (!bc_ctl.replace_pat)
 
879
            bc_push_arg (&bc_ctl, &bc_state,
 
880
                         linebuf, len,
 
881
                         NULL, 0,
 
882
                         initial_args);
613
883
          return len;
614
884
        }
615
885
      if (p >= endbuf)
616
 
        error (1, 0, _("argument line too long"));
 
886
        {
 
887
          exec_if_possible ();
 
888
          error (1, 0, _("argument line too long"));
 
889
        }
617
890
      *p++ = c;
618
891
    }
619
892
}
620
893
 
621
 
/* Replace all instances of `replace_pat' in ARG with `linebuf',
622
 
   and add the resulting string to the list of arguments for the command
623
 
   to execute.
624
 
   ARGLEN is the length of ARG, not including the null.
625
 
   LBLEN is the length of `linebuf', not including the null.
626
 
 
627
 
   COMPAT: insertions on the SYSV version are limited to 255 chars per line,
628
 
   and a max of 5 occurrences of replace_pat in the initial-arguments.
629
 
   Those restrictions do not exist here.  */
630
 
 
631
 
static void
632
 
do_insert (char *arg, size_t arglen, size_t lblen)
633
 
{
634
 
  /* Temporary copy of each arg with the replace pattern replaced by the
635
 
     real arg.  */
636
 
  static char *insertbuf;
637
 
  char *p;
638
 
  int bytes_left = arg_max - 1; /* Bytes left on the command line.  */
639
 
 
640
 
  if (!insertbuf)
641
 
    insertbuf = (char *) xmalloc (arg_max + 1);
642
 
  p = insertbuf;
643
 
 
644
 
  do
645
 
    {
646
 
      size_t len;               /* Length in ARG before `replace_pat'.  */
647
 
      char *s = strstr (arg, replace_pat);
648
 
      if (s)
649
 
        len = s - arg;
650
 
      else
651
 
        len = arglen;
652
 
      bytes_left -= len;
653
 
      if (bytes_left <= 0)
654
 
        break;
655
 
 
656
 
      strncpy (p, arg, len);
657
 
      p += len;
658
 
      arg += len;
659
 
      arglen -= len;
660
 
 
661
 
      if (s)
662
 
        {
663
 
          bytes_left -= lblen;
664
 
          if (bytes_left <= 0)
665
 
            break;
666
 
          strcpy (p, linebuf);
667
 
          arg += rplen;
668
 
          arglen -= rplen;
669
 
          p += lblen;
670
 
        }
671
 
    }
672
 
  while (*arg);
673
 
  if (*arg)
674
 
    error (1, 0, _("command too long"));
675
 
  *p++ = '\0';
676
 
  push_arg (insertbuf, p - insertbuf);
677
 
}
678
 
 
679
 
/* Add ARG to the end of the list of arguments `cmd_argv' to pass
680
 
   to the command.
681
 
   LEN is the length of ARG, including the terminating null.
682
 
   If this brings the list up to its maximum size, execute the command.  */
683
 
 
684
 
static void
685
 
push_arg (char *arg, size_t len)
686
 
{
687
 
  if (arg)
688
 
    {
689
 
      if (cmd_argv_chars + len > arg_max)
690
 
        {
691
 
          if (initial_args || cmd_argc == initial_argc)
692
 
            error (1, 0, _("can not fit single argument within argument list size limit"));
693
 
          if (replace_pat
694
 
              || (exit_if_size_exceeded &&
695
 
                  (lines_per_exec || args_per_exec)))
696
 
            error (1, 0, _("argument list too long"));
697
 
          do_exec ();
698
 
        }
699
 
      if (!initial_args && args_per_exec &&
700
 
          cmd_argc - initial_argc == args_per_exec)
701
 
        do_exec ();
702
 
    }
703
 
 
704
 
  if (cmd_argc >= cmd_argv_alloc)
705
 
    {
706
 
      if (!cmd_argv)
707
 
        {
708
 
          cmd_argv_alloc = 64;
709
 
          cmd_argv = (char **) xmalloc (sizeof (char *) * cmd_argv_alloc);
710
 
        }
711
 
      else
712
 
        {
713
 
          cmd_argv_alloc *= 2;
714
 
          cmd_argv = (char **) xrealloc (cmd_argv,
715
 
                                         sizeof (char *) * cmd_argv_alloc);
716
 
        }
717
 
    }
718
 
 
719
 
  if (!arg)
720
 
    cmd_argv[cmd_argc++] = NULL;
721
 
  else
722
 
    {
723
 
      cmd_argv[cmd_argc++] = argbuf + cmd_argv_chars;
724
 
      strcpy (argbuf + cmd_argv_chars, arg);
725
 
      cmd_argv_chars += len;
726
 
    }
727
 
}
728
 
 
729
894
/* Print the arguments of the command to execute.
730
895
   If ASK is nonzero, prompt the user for a response, and
731
896
   if the user responds affirmatively, return true;
736
901
{
737
902
  int i;
738
903
 
739
 
  for (i = 0; i < cmd_argc - 1; i++)
740
 
    fprintf (stderr, "%s ", cmd_argv[i]);
 
904
  for (i = 0; i < bc_state.cmd_argc - 1; i++)
 
905
    fprintf (stderr, "%s ", bc_state.cmd_argv[i]);
741
906
  if (ask)
742
907
    {
743
908
      static FILE *tty_stream;
763
928
  return false;
764
929
}
765
930
 
 
931
 
 
932
/* Close stdin and attach /dev/null to it.
 
933
 * This resolves Savannah bug #3992.
 
934
 */
 
935
static void
 
936
prep_child_for_exec (void)
 
937
{
 
938
  if (!keep_stdin)
 
939
    {
 
940
      const char inputfile[] = "/dev/null";
 
941
      /* fprintf(stderr, "attaching stdin to /dev/null\n"); */
 
942
      
 
943
      close(0);
 
944
      if (open(inputfile, O_RDONLY) < 0)
 
945
        {
 
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.
 
950
           */
 
951
          error (0, errno, "%s", inputfile);
 
952
        }
 
953
    }
 
954
}
 
955
 
 
956
 
766
957
/* Execute the command that has been built in `cmd_argv'.  This may involve
767
958
   waiting for processes that were previously executed.  */
768
959
 
769
 
static void
770
 
do_exec (void)
 
960
static int
 
961
xargs_do_exec (const struct buildcmd_control *ctl, struct buildcmd_state *state)
771
962
{
772
963
  pid_t child;
773
964
 
774
 
  push_arg ((char *) NULL, 0);  /* Null terminate the arg list.  */
 
965
  bc_push_arg (&bc_ctl, &bc_state,
 
966
               (char *) NULL, 0,
 
967
               NULL, 0,
 
968
               false); /* Null terminate the arg list.  */
 
969
  
775
970
  if (!query_before_executing || print_args (true))
776
971
    {
777
972
      if (proc_max && procs_executing >= proc_max)
788
983
          error (1, errno, _("cannot fork"));
789
984
 
790
985
        case 0:         /* Child.  */
791
 
          execvp (cmd_argv[0], cmd_argv);
792
 
          error (0, errno, "%s", cmd_argv[0]);
 
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]);
793
989
          _exit (errno == ENOENT ? 127 : 126);
 
990
          /*NOTREACHED*/
794
991
        }
795
992
      add_proc (child);
796
993
    }
797
994
 
798
 
  cmd_argc = initial_argc;
799
 
  cmd_argv_chars = initial_argv_chars;
 
995
  bc_clear_args(&bc_ctl, &bc_state);
 
996
  return 1;                     /* Success */
 
997
}
 
998
 
 
999
/* Execute the command if possible.  */
 
1000
 
 
1001
static void
 
1002
exec_if_possible (void)
 
1003
{
 
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);
800
1008
}
801
1009
 
802
1010
/* Add the process with id PID to the list of processes that have
863
1071
      if (WEXITSTATUS (status) == 126 || WEXITSTATUS (status) == 127)
864
1072
        exit (WEXITSTATUS (status));    /* Can't find or run the command.  */
865
1073
      if (WEXITSTATUS (status) == 255)
866
 
        error (124, 0, _("%s: exited with status 255; aborting"), cmd_argv[0]);
 
1074
        error (124, 0, _("%s: exited with status 255; aborting"), bc_state.cmd_argv[0]);
867
1075
      if (WIFSTOPPED (status))
868
 
        error (125, 0, _("%s: stopped by signal %d"), cmd_argv[0], WSTOPSIG (status));
 
1076
        error (125, 0, _("%s: stopped by signal %d"), bc_state.cmd_argv[0], WSTOPSIG (status));
869
1077
      if (WIFSIGNALED (status))
870
 
        error (125, 0, _("%s: terminated by signal %d"), cmd_argv[0], WTERMSIG (status));
 
1078
        error (125, 0, _("%s: terminated by signal %d"), bc_state.cmd_argv[0], WTERMSIG (status));
871
1079
      if (WEXITSTATUS (status) != 0)
872
1080
        child_error = 123;
873
1081
 
876
1084
    }
877
1085
}
878
1086
 
 
1087
/* Wait for all child processes to finish.  */
 
1088
 
 
1089
static void
 
1090
wait_for_proc_all (void)
 
1091
{
 
1092
  static boolean waiting = false;
 
1093
 
 
1094
  if (waiting)
 
1095
    return;
 
1096
 
 
1097
  waiting = true;
 
1098
  wait_for_proc (true);
 
1099
  waiting = false;
 
1100
}
 
1101
 
879
1102
/* Return the value of the number represented in STR.
880
1103
   OPTION is the command line option to which STR is the argument.
881
1104
   If the value does not fall within the boundaries MIN and MAX,
882
 
   Print an error message mentioning OPTION and exit.  */
 
1105
   Print an error message mentioning OPTION.  If FATAL is true, 
 
1106
   we also exit. */
883
1107
 
884
1108
static long
885
 
parse_num (char *str, int option, long int min, long int max)
 
1109
parse_num (char *str, int option, long int min, long int max, int fatal)
886
1110
{
887
1111
  char *eptr;
888
1112
  long val;
892
1116
    {
893
1117
      fprintf (stderr, _("%s: invalid number for -%c option\n"),
894
1118
               program_name, option);
895
 
      usage (stderr, 1);
 
1119
      usage (stderr);
 
1120
      exit(1);
896
1121
    }
897
1122
  else if (val < min)
898
1123
    {
899
 
      fprintf (stderr, _("%s: value for -%c option must be >= %ld\n"),
 
1124
      fprintf (stderr, _("%s: value for -%c option should be >= %ld\n"),
900
1125
               program_name, option, min);
901
 
      usage (stderr, 1);
 
1126
      if (fatal)
 
1127
        {
 
1128
          usage (stderr);
 
1129
          exit(1);
 
1130
        }
 
1131
      else
 
1132
        {
 
1133
          val = min;
 
1134
        }
902
1135
    }
903
1136
  else if (max >= 0 && val > max)
904
1137
    {
905
 
      fprintf (stderr, _("%s: value for -%c option must be < %ld\n"),
 
1138
      fprintf (stderr, _("%s: value for -%c option should be < %ld\n"),
906
1139
               program_name, option, max);
907
 
      usage (stderr, 1);
 
1140
      if (fatal)
 
1141
        {
 
1142
          usage (stderr);
 
1143
          exit(1);
 
1144
        }
 
1145
      else
 
1146
        {
 
1147
          val = max;
 
1148
        }
908
1149
    }
909
1150
  return val;
910
1151
}
923
1164
}
924
1165
 
925
1166
static void
926
 
usage (FILE *stream, int status)
 
1167
usage (FILE *stream)
927
1168
{
928
1169
  fprintf (stream, _("\
929
1170
Usage: %s [-0prtx] [-e[eof-str]] [-i[replace-str]] [-l[max-lines]]\n\
930
1171
       [-n max-args] [-s max-chars] [-P max-procs] [--null] [--eof[=eof-str]]\n\
931
1172
       [--replace[=replace-str]] [--max-lines[=max-lines]] [--interactive]\n\
932
1173
       [--max-chars=max-chars] [--verbose] [--exit] [--max-procs=max-procs]\n\
933
 
       [--max-args=max-args] [--no-run-if-empty] [--version] [--help]\n\
934
 
       [command [initial-arguments]]\n"),
 
1174
       [--max-args=max-args] [--no-run-if-empty] [--arg-file=file]\n\
 
1175
       [--version] [--help] [command [initial-arguments]]\n"),
935
1176
           program_name);
936
 
  fputs (_("\nReport bugs to <bug-findutils@gnu.org>."), stream);
937
 
  exit (status);
 
1177
  fputs (_("\nReport bugs to <bug-findutils@gnu.org>.\n"), stream);
938
1178
}