xargs: trivial code shrink
[oweals/busybox.git] / findutils / xargs.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini xargs implementation for busybox
4  * Options are supported: "-prtx -n max_arg -s max_chars -e[ouf_str]"
5  *
6  * (C) 2002,2003 by Vladimir Oleynik <dzo@simtreas.ru>
7  *
8  * Special thanks
9  * - Mark Whitley and Glenn McGrath for stimulus to rewrite :)
10  * - Mike Rendell <michael@cs.mun.ca>
11  * and David MacKenzie <djm@gnu.ai.mit.edu>.
12  *
13  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
14  *
15  * xargs is described in the Single Unix Specification v3 at
16  * http://www.opengroup.org/onlinepubs/007904975/utilities/xargs.html
17  *
18  */
19
20 //kbuild:lib-$(CONFIG_XARGS) += xargs.o
21 //config:
22 //config:config XARGS
23 //config:       bool "xargs"
24 //config:       default y
25 //config:       help
26 //config:         xargs is used to execute a specified command for
27 //config:         every item from standard input.
28 //config:
29 //config:config FEATURE_XARGS_SUPPORT_CONFIRMATION
30 //config:       bool "Enable -p: prompt and confirmation"
31 //config:       default y
32 //config:       depends on XARGS
33 //config:       help
34 //config:         Support -p: prompt the user whether to run each command
35 //config:         line and read a line from the terminal.
36 //config:
37 //config:config FEATURE_XARGS_SUPPORT_QUOTES
38 //config:       bool "Enable single and double quotes and backslash"
39 //config:       default y
40 //config:       depends on XARGS
41 //config:       help
42 //config:         Support quoting in the input.
43 //config:
44 //config:config FEATURE_XARGS_SUPPORT_TERMOPT
45 //config:       bool "Enable -x: exit if -s or -n is exceeded"
46 //config:       default y
47 //config:       depends on XARGS
48 //config:       help
49 //config:         Support -x: exit if the command size (see the -s or -n option)
50 //config:         is exceeded.
51 //config:
52 //config:config FEATURE_XARGS_SUPPORT_ZERO_TERM
53 //config:       bool "Enable -0: NUL-terminated input"
54 //config:       default y
55 //config:       depends on XARGS
56 //config:       help
57 //config:         Support -0: input items are terminated by a NUL character
58 //config:         instead of whitespace, and the quotes and backslash
59 //config:         are not special.
60
61 #include "libbb.h"
62 /* COMPAT:  SYSV version defaults size (and has a max value of) to 470.
63    We try to make it as large as possible. */
64 #if !defined(ARG_MAX) && defined(_SC_ARG_MAX)
65 # define ARG_MAX sysconf(_SC_ARG_MAX)
66 #endif
67 #if !defined(ARG_MAX)
68 # define ARG_MAX 470
69 #endif
70
71 /* This is a NOEXEC applet. Be very careful! */
72
73
74 //#define dbg_msg(...) bb_error_msg(__VA_ARGS__)
75 #define dbg_msg(...) ((void)0)
76
77
78 #ifdef TEST
79 # ifndef ENABLE_FEATURE_XARGS_SUPPORT_CONFIRMATION
80 #  define ENABLE_FEATURE_XARGS_SUPPORT_CONFIRMATION 1
81 # endif
82 # ifndef ENABLE_FEATURE_XARGS_SUPPORT_QUOTES
83 #  define ENABLE_FEATURE_XARGS_SUPPORT_QUOTES 1
84 # endif
85 # ifndef ENABLE_FEATURE_XARGS_SUPPORT_TERMOPT
86 #  define ENABLE_FEATURE_XARGS_SUPPORT_TERMOPT 1
87 # endif
88 # ifndef ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM
89 #  define ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM 1
90 # endif
91 #endif
92
93
94 struct globals {
95         char **args;
96         const char *eof_str;
97         int idx;
98 } FIX_ALIASING;
99 #define G (*(struct globals*)&bb_common_bufsiz1)
100 #define INIT_G() do { } while (0)
101
102
103 /*
104  * This function has special algorithm.
105  * Don't use fork and include to main!
106  */
107 static int xargs_exec(void)
108 {
109         int status;
110
111         status = spawn_and_wait(G.args);
112         if (status < 0) {
113                 bb_simple_perror_msg(G.args[0]);
114                 return errno == ENOENT ? 127 : 126;
115         }
116         if (status == 255) {
117                 bb_error_msg("%s: exited with status 255; aborting", G.args[0]);
118                 return 124;
119         }
120         if (status >= 0x180) {
121                 bb_error_msg("%s: terminated by signal %d",
122                         G.args[0], status - 0x180);
123                 return 125;
124         }
125         if (status)
126                 return 123;
127         return 0;
128 }
129
130 /* In POSIX/C locale isspace is only these chars: "\t\n\v\f\r" and space.
131  * "\t\n\v\f\r" happen to have ASCII codes 9,10,11,12,13.
132  */
133 #define ISSPACE(a) ({ unsigned char xargs__isspace = (a) - 9; xargs__isspace == (' ' - 9) || xargs__isspace <= (13 - 9); })
134
135 static void store_param(char *s)
136 {
137         /* Grow by 256 elements at once */
138         if (!(G.idx & 0xff)) { /* G.idx == N*256 */
139                 /* Enlarge, make G.args[(N+1)*256 - 1] last valid idx */
140                 G.args = xrealloc(G.args, sizeof(G.args[0]) * (G.idx + 0x100));
141         }
142         G.args[G.idx++] = s;
143 }
144
145 /* process[0]_stdin:
146  * Read characters into buf[n_max_chars+1], and when parameter delimiter
147  * is seen, store the address of a new parameter to args[].
148  * If reading discovers that last chars do not form the complete
149  * parameter, the pointer to the first such "tail character" is returned.
150  * (buf has extra byte at the end to accomodate terminating NUL
151  * of "tail characters" string).
152  * Otherwise, the returned pointer points to NUL byte.
153  * On entry, buf[] may contain some "seed chars" which are to become
154  * the beginning of the first parameter.
155  */
156
157 #if ENABLE_FEATURE_XARGS_SUPPORT_QUOTES
158 static char* FAST_FUNC process_stdin(int n_max_chars, int n_max_arg, char *buf)
159 {
160 #define NORM      0
161 #define QUOTE     1
162 #define BACKSLASH 2
163 #define SPACE     4
164         char *s;                /* start of the word */
165         char *p;                /* pointer to end of the word */
166         char q = '\0';          /* quote char */
167         char state = NORM;
168
169         s = buf;
170         p = s + strlen(buf);
171
172         /* "goto ret" is used instead of "break" to make control flow
173          * more obvious: */
174
175         while (1) {
176                 int c = getchar();
177                 if (c == EOF) {
178                         if (p != s)
179                                 goto close_word;
180                         goto ret;
181                 }
182                 if (state == BACKSLASH) {
183                         state = NORM;
184                         goto set;
185                 }
186                 if (state == QUOTE) {
187                         if (c != q)
188                                 goto set;
189                         q = '\0';
190                         state = NORM;
191                 } else { /* if (state == NORM) */
192                         if (ISSPACE(c)) {
193                                 if (p != s) {
194  close_word:
195                                         state = SPACE;
196                                         c = '\0';
197                                         goto set;
198                                 }
199                         } else {
200                                 if (c == '\\') {
201                                         state = BACKSLASH;
202                                 } else if (c == '\'' || c == '"') {
203                                         q = c;
204                                         state = QUOTE;
205                                 } else {
206  set:
207                                         *p++ = c;
208                                 }
209                         }
210                 }
211                 if (state == SPACE) {   /* word's delimiter or EOF detected */
212                         if (q) {
213                                 bb_error_msg_and_die("unmatched %s quote",
214                                         q == '\'' ? "single" : "double");
215                         }
216                         /* A full word is loaded */
217                         if (G.eof_str) {
218                                 if (strcmp(s, G.eof_str) == 0) {
219                                         while (getchar() != EOF)
220                                                 continue;
221                                         p = s;
222                                         goto ret;
223                                 }
224                         }
225                         n_max_chars -= (p - s);
226                         /* if (n_max_chars < 0) impossible */
227                         store_param(s);
228                         dbg_msg("args[]:'%s'", s);
229                         s = p;
230                         n_max_arg--;
231                         if (n_max_arg == 0 || n_max_chars == 0) {
232                                 goto ret;
233                         }
234                         state = NORM;
235                 } else /* state != SPACE */
236                 if (p - s >= n_max_chars) {
237                         dbg_msg("s:'%s' p-s:%d n_max_chars:%d", s, (int)(p-s), n_max_chars);
238                         goto ret;
239                 }
240         }
241  ret:
242         *p = '\0';
243         /* store_param(NULL) - caller will do it */
244         dbg_msg("return:'%s'", s);
245         return s;
246 }
247 #else
248 /* The variant does not support single quotes, double quotes or backslash */
249 static char* FAST_FUNC process_stdin(int n_max_chars, int n_max_arg, char *buf)
250 {
251         char *s;                /* start of the word */
252         char *p;                /* pointer to end of the word */
253
254         s = buf;
255         p = s + strlen(buf);
256
257         while (1) {
258                 int c = getchar();
259                 if (c == EOF) {
260                         if (p == s)
261                                 goto ret;
262                 }
263                 if (c == EOF || ISSPACE(c)) {
264                         if (p == s)
265                                 continue;
266                         c = EOF;
267                 }
268                 *p++ = (c == EOF ? '\0' : c);
269                 if (c == EOF) { /* word's delimiter or EOF detected */
270                         /* A full word is loaded */
271                         if (G.eof_str) {
272                                 if (strcmp(s, G.eof_str) == 0) {
273                                         while (getchar() != EOF)
274                                                 continue;
275                                         p = s;
276                                         goto ret;
277                                 }
278                         }
279                         n_max_chars -= (p - s);
280                         /* if (n_max_chars < 0) impossible */
281                         store_param(s);
282                         dbg_msg("args[]:'%s'", s);
283                         s = p;
284                         n_max_arg--;
285                         if (n_max_arg == 0 || n_max_chars == 0) {
286                                 goto ret;
287                         }
288                 } else /* c != EOF */
289                 if (p - s >= n_max_chars) {
290                         goto ret;
291                 }
292         }
293  ret:
294         *p = '\0';
295         /* store_param(NULL) - caller will do it */
296         dbg_msg("return:'%s'", s);
297         return s;
298 }
299 #endif /* FEATURE_XARGS_SUPPORT_QUOTES */
300
301 #if ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM
302 static char* FAST_FUNC process0_stdin(int n_max_chars, int n_max_arg, char *buf)
303 {
304         char *s;                /* start of the word */
305         char *p;                /* pointer to end of the word */
306
307         s = buf;
308         p = s + strlen(buf);
309
310         while (1) {
311                 int c = getchar();
312                 if (c == EOF) {
313                         if (p == s)
314                                 goto ret;
315                         c = '\0';
316                 }
317                 *p++ = c;
318                 if (c == '\0') {   /* word's delimiter or EOF detected */
319                         /* A full word is loaded */
320                         n_max_chars -= (p - s);
321                         /* if (n_max_chars < 0) impossible */
322                         store_param(s);
323                         dbg_msg("args[]:'%s'", s);
324                         n_max_arg--;
325                         s = p;
326                         if (n_max_arg == 0 || n_max_chars == 0) {
327                                 goto ret;
328                         }
329                 } else /* c != '\0' */
330                 if (p - s >= n_max_chars) {
331                         goto ret;
332                 }
333         }
334  ret:
335         *p = '\0';
336         /* store_param(NULL) - caller will do it */
337         dbg_msg("return:'%s'", s);
338         return s;
339 }
340 #endif /* FEATURE_XARGS_SUPPORT_ZERO_TERM */
341
342 #if ENABLE_FEATURE_XARGS_SUPPORT_CONFIRMATION
343 /* Prompt the user for a response, and
344    if the user responds affirmatively, return true;
345    otherwise, return false. Uses "/dev/tty", not stdin. */
346 static int xargs_ask_confirmation(void)
347 {
348         FILE *tty_stream;
349         int c, savec;
350
351         tty_stream = xfopen_for_read(CURRENT_TTY);
352         fputs(" ?...", stderr);
353         fflush_all();
354         c = savec = getc(tty_stream);
355         while (c != EOF && c != '\n')
356                 c = getc(tty_stream);
357         fclose(tty_stream);
358         return (savec == 'y' || savec == 'Y');
359 }
360 #else
361 # define xargs_ask_confirmation() 1
362 #endif
363
364 /* Correct regardless of combination of CONFIG_xxx */
365 enum {
366         OPTBIT_VERBOSE = 0,
367         OPTBIT_NO_EMPTY,
368         OPTBIT_UPTO_NUMBER,
369         OPTBIT_UPTO_SIZE,
370         OPTBIT_EOF_STRING,
371         OPTBIT_EOF_STRING1,
372         IF_FEATURE_XARGS_SUPPORT_CONFIRMATION(OPTBIT_INTERACTIVE,)
373         IF_FEATURE_XARGS_SUPPORT_TERMOPT(     OPTBIT_TERMINATE  ,)
374         IF_FEATURE_XARGS_SUPPORT_ZERO_TERM(   OPTBIT_ZEROTERM   ,)
375
376         OPT_VERBOSE     = 1 << OPTBIT_VERBOSE    ,
377         OPT_NO_EMPTY    = 1 << OPTBIT_NO_EMPTY   ,
378         OPT_UPTO_NUMBER = 1 << OPTBIT_UPTO_NUMBER,
379         OPT_UPTO_SIZE   = 1 << OPTBIT_UPTO_SIZE  ,
380         OPT_EOF_STRING  = 1 << OPTBIT_EOF_STRING , /* GNU: -e[<param>] */
381         OPT_EOF_STRING1 = 1 << OPTBIT_EOF_STRING1, /* SUS: -E<param> */
382         OPT_INTERACTIVE = IF_FEATURE_XARGS_SUPPORT_CONFIRMATION((1 << OPTBIT_INTERACTIVE)) + 0,
383         OPT_TERMINATE   = IF_FEATURE_XARGS_SUPPORT_TERMOPT(     (1 << OPTBIT_TERMINATE  )) + 0,
384         OPT_ZEROTERM    = IF_FEATURE_XARGS_SUPPORT_ZERO_TERM(   (1 << OPTBIT_ZEROTERM   )) + 0,
385 };
386 #define OPTION_STR "+trn:s:e::E:" \
387         IF_FEATURE_XARGS_SUPPORT_CONFIRMATION("p") \
388         IF_FEATURE_XARGS_SUPPORT_TERMOPT(     "x") \
389         IF_FEATURE_XARGS_SUPPORT_ZERO_TERM(   "0")
390
391 int xargs_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
392 int xargs_main(int argc, char **argv)
393 {
394         int i;
395         int child_error = 0;
396         char *max_args;
397         char *max_chars;
398         char *buf;
399         unsigned opt;
400         int n_max_chars;
401         int n_max_arg;
402 #if ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM
403         char* FAST_FUNC (*read_args)(int, int, char*) = process_stdin;
404 #else
405 #define read_args process_stdin
406 #endif
407
408         INIT_G();
409
410         G.eof_str = NULL;
411         opt = getopt32(argv, OPTION_STR, &max_args, &max_chars, &G.eof_str, &G.eof_str);
412
413         /* -E ""? You may wonder why not just omit -E?
414          * This is used for portability:
415          * old xargs was using "_" as default for -E / -e */
416         if ((opt & OPT_EOF_STRING1) && G.eof_str[0] == '\0')
417                 G.eof_str = NULL;
418
419         if (opt & OPT_ZEROTERM)
420                 IF_FEATURE_XARGS_SUPPORT_ZERO_TERM(read_args = process0_stdin);
421
422         argv += optind;
423         argc -= optind;
424         if (!argv[0]) {
425                 /* default behavior is to echo all the filenames */
426                 *--argv = (char*)"echo";
427                 argc++;
428         }
429
430         /* The Open Group Base Specifications Issue 6:
431          * "The xargs utility shall limit the command line length such that
432          * when the command line is invoked, the combined argument
433          * and environment lists (see the exec family of functions
434          * in the System Interfaces volume of IEEE Std 1003.1-2001)
435          * shall not exceed {ARG_MAX}-2048 bytes".
436          */
437         n_max_chars = ARG_MAX; /* might be calling sysconf(_SC_ARG_MAX) */
438         if (n_max_chars < 4*1024); /* paranoia */
439                 n_max_chars = 4*1024;
440         n_max_chars -= 2048;
441         /* Sanity check for systems with huge ARG_MAX defines (e.g., Suns which
442          * have it at 1 meg).  Things will work fine with a large ARG_MAX
443          * but it will probably hurt the system more than it needs to;
444          * an array of this size is allocated.
445          */
446         if (n_max_chars > 20 * 1024)
447                 n_max_chars = 20 * 1024;
448
449         if (opt & OPT_UPTO_SIZE) {
450                 size_t n_chars = 0;
451                 n_max_chars = xatou_range(max_chars, 1, INT_MAX);
452                 for (i = 0; argv[i]; i++) {
453                         n_chars += strlen(argv[i]) + 1;
454                 }
455                 n_max_chars -= n_chars;
456                 if (n_max_chars <= 0) {
457                         bb_error_msg_and_die("can't fit single argument within argument list size limit");
458                 }
459         }
460
461         buf = xzalloc(n_max_chars + 1);
462
463         n_max_arg = n_max_chars;
464         if (opt & OPT_UPTO_NUMBER) {
465                 n_max_arg = xatou_range(max_args, 1, INT_MAX);
466         }
467
468         /* Allocate pointers for execvp */
469         /* We can statically allocate (argc + n_max_arg + 1) elements
470          * and do not bother with resizing args[], but on 64-bit machines
471          * this results in args[] vector which is ~8 times bigger
472          * than n_max_chars! That is, with n_max_chars == 20k,
473          * args[] will take 160k (!), which will most likely be
474          * almost entirely unused.
475          */
476         /* See store_param() for matching 256-step growth logic */
477         G.args = xmalloc(sizeof(G.args[0]) * ((argc + 0xff) & ~0xff));
478
479         /* Store the command to be executed, part 1 */
480         for (i = 0; argv[i]; i++)
481                 G.args[i] = argv[i];
482
483         while (1) {
484                 char *rem;
485
486                 G.idx = argc;
487                 rem = read_args(n_max_chars, n_max_arg, buf);
488                 store_param(NULL);
489
490                 if (!G.args[argc]) {
491                         if (*rem != '\0')
492                                 bb_error_msg_and_die("argument line too long");
493                         if (opt & OPT_NO_EMPTY)
494                                 break;
495                 }
496                 opt |= OPT_NO_EMPTY;
497
498                 if (opt & (OPT_INTERACTIVE | OPT_VERBOSE)) {
499                         const char *fmt = " %s" + 1;
500                         char **args = G.args;
501                         for (i = 0; args[i]; i++) {
502                                 fprintf(stderr, fmt, args[i]);
503                                 fmt = " %s";
504                         }
505                         if (!(opt & OPT_INTERACTIVE))
506                                 bb_putchar_stderr('\n');
507                 }
508
509                 if (!(opt & OPT_INTERACTIVE) || xargs_ask_confirmation()) {
510                         child_error = xargs_exec();
511                 }
512
513                 if (child_error > 0 && child_error != 123) {
514                         break;
515                 }
516
517                 overlapping_strcpy(buf, rem);
518         } /* while */
519
520         if (ENABLE_FEATURE_CLEAN_UP) {
521                 free(G.args);
522                 free(buf);
523         }
524
525         return child_error;
526 }
527
528
529 #ifdef TEST
530
531 const char *applet_name = "debug stuff usage";
532
533 void bb_show_usage(void)
534 {
535         fprintf(stderr, "Usage: %s [-p] [-r] [-t] -[x] [-n max_arg] [-s max_chars]\n",
536                 applet_name);
537         exit(EXIT_FAILURE);
538 }
539
540 int main(int argc, char **argv)
541 {
542         return xargs_main(argc, argv);
543 }
544 #endif /* TEST */