1 /* vi: set sw=4 ts=4: */
3 * Mini xargs implementation for busybox
4 * Options are supported: "-prtx -n max_arg -s max_chars -e[ouf_str]"
6 * (C) 2002,2003 by Vladimir Oleynik <dzo@simtreas.ru>
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>.
13 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
15 * xargs is described in the Single Unix Specification v3 at
16 * http://www.opengroup.org/onlinepubs/007904975/utilities/xargs.html
20 //kbuild:lib-$(CONFIG_XARGS) += xargs.o
23 //config: bool "xargs"
26 //config: xargs is used to execute a specified command for
27 //config: every item from standard input.
29 //config:config FEATURE_XARGS_SUPPORT_CONFIRMATION
30 //config: bool "Enable -p: prompt and confirmation"
32 //config: depends on XARGS
34 //config: Support -p: prompt the user whether to run each command
35 //config: line and read a line from the terminal.
37 //config:config FEATURE_XARGS_SUPPORT_QUOTES
38 //config: bool "Enable single and double quotes and backslash"
40 //config: depends on XARGS
42 //config: Support quoting in the input.
44 //config:config FEATURE_XARGS_SUPPORT_TERMOPT
45 //config: bool "Enable -x: exit if -s or -n is exceeded"
47 //config: depends on XARGS
49 //config: Support -x: exit if the command size (see the -s or -n option)
50 //config: is exceeded.
52 //config:config FEATURE_XARGS_SUPPORT_ZERO_TERM
53 //config: bool "Enable -0: NUL-terminated input"
55 //config: depends on XARGS
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.
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)
71 /* This is a NOEXEC applet. Be very careful! */
74 //#define dbg_msg(...) bb_error_msg(__VA_ARGS__)
75 #define dbg_msg(...) ((void)0)
79 # ifndef ENABLE_FEATURE_XARGS_SUPPORT_CONFIRMATION
80 # define ENABLE_FEATURE_XARGS_SUPPORT_CONFIRMATION 1
82 # ifndef ENABLE_FEATURE_XARGS_SUPPORT_QUOTES
83 # define ENABLE_FEATURE_XARGS_SUPPORT_QUOTES 1
85 # ifndef ENABLE_FEATURE_XARGS_SUPPORT_TERMOPT
86 # define ENABLE_FEATURE_XARGS_SUPPORT_TERMOPT 1
88 # ifndef ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM
89 # define ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM 1
99 #define G (*(struct globals*)&bb_common_bufsiz1)
100 #define INIT_G() do { } while (0)
104 * This function has special algorithm.
105 * Don't use fork and include to main!
107 static int xargs_exec(void)
111 status = spawn_and_wait(G.args);
113 bb_simple_perror_msg(G.args[0]);
114 return errno == ENOENT ? 127 : 126;
117 bb_error_msg("%s: exited with status 255; aborting", G.args[0]);
120 if (status >= 0x180) {
121 bb_error_msg("%s: terminated by signal %d",
122 G.args[0], status - 0x180);
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.
133 #define ISSPACE(a) ({ unsigned char xargs__isspace = (a) - 9; xargs__isspace == (' ' - 9) || xargs__isspace <= (13 - 9); })
135 static void store_param(char *s)
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));
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.
157 #if ENABLE_FEATURE_XARGS_SUPPORT_QUOTES
158 static char* FAST_FUNC process_stdin(int n_max_chars, int n_max_arg, char *buf)
164 char *s; /* start of the word */
165 char *p; /* pointer to end of the word */
166 char q = '\0'; /* quote char */
172 /* "goto ret" is used instead of "break" to make control flow
182 if (state == BACKSLASH) {
186 if (state == QUOTE) {
191 } else { /* if (state == NORM) */
202 } else if (c == '\'' || c == '"') {
211 if (state == SPACE) { /* word's delimiter or EOF detected */
213 bb_error_msg_and_die("unmatched %s quote",
214 q == '\'' ? "single" : "double");
216 /* A full word is loaded */
218 if (strcmp(s, G.eof_str) == 0) {
219 while (getchar() != EOF)
225 n_max_chars -= (p - s);
226 /* if (n_max_chars < 0) impossible */
228 dbg_msg("args[]:'%s'", s);
231 if (n_max_arg == 0 || n_max_chars == 0) {
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);
243 /* store_param(NULL) - caller will do it */
244 dbg_msg("return:'%s'", s);
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)
251 char *s; /* start of the word */
252 char *p; /* pointer to end of the word */
263 if (c == EOF || ISSPACE(c)) {
268 *p++ = (c == EOF ? '\0' : c);
269 if (c == EOF) { /* word's delimiter or EOF detected */
270 /* A full word is loaded */
272 if (strcmp(s, G.eof_str) == 0) {
273 while (getchar() != EOF)
279 n_max_chars -= (p - s);
280 /* if (n_max_chars < 0) impossible */
282 dbg_msg("args[]:'%s'", s);
285 if (n_max_arg == 0 || n_max_chars == 0) {
288 } else /* c != EOF */
289 if (p - s >= n_max_chars) {
295 /* store_param(NULL) - caller will do it */
296 dbg_msg("return:'%s'", s);
299 #endif /* FEATURE_XARGS_SUPPORT_QUOTES */
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)
304 char *s; /* start of the word */
305 char *p; /* pointer to end of the word */
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 */
323 dbg_msg("args[]:'%s'", s);
326 if (n_max_arg == 0 || n_max_chars == 0) {
329 } else /* c != '\0' */
330 if (p - s >= n_max_chars) {
336 /* store_param(NULL) - caller will do it */
337 dbg_msg("return:'%s'", s);
340 #endif /* FEATURE_XARGS_SUPPORT_ZERO_TERM */
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)
351 tty_stream = xfopen_for_read(CURRENT_TTY);
352 fputs(" ?...", stderr);
354 c = savec = getc(tty_stream);
355 while (c != EOF && c != '\n')
356 c = getc(tty_stream);
358 return (savec == 'y' || savec == 'Y');
361 # define xargs_ask_confirmation() 1
364 /* Correct regardless of combination of CONFIG_xxx */
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 ,)
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,
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")
391 int xargs_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
392 int xargs_main(int argc, char **argv)
402 #if ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM
403 char* FAST_FUNC (*read_args)(int, int, char*) = process_stdin;
405 #define read_args process_stdin
411 opt = getopt32(argv, OPTION_STR, &max_args, &max_chars, &G.eof_str, &G.eof_str);
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')
419 if (opt & OPT_ZEROTERM)
420 IF_FEATURE_XARGS_SUPPORT_ZERO_TERM(read_args = process0_stdin);
425 /* default behavior is to echo all the filenames */
426 *--argv = (char*)"echo";
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".
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;
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.
446 if (n_max_chars > 20 * 1024)
447 n_max_chars = 20 * 1024;
449 if (opt & OPT_UPTO_SIZE) {
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;
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");
461 buf = xzalloc(n_max_chars + 1);
463 n_max_arg = n_max_chars;
464 if (opt & OPT_UPTO_NUMBER) {
465 n_max_arg = xatou_range(max_args, 1, INT_MAX);
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.
476 /* See store_param() for matching 256-step growth logic */
477 G.args = xmalloc(sizeof(G.args[0]) * ((argc + 0xff) & ~0xff));
479 /* Store the command to be executed, part 1 */
480 for (i = 0; argv[i]; i++)
487 rem = read_args(n_max_chars, n_max_arg, buf);
492 bb_error_msg_and_die("argument line too long");
493 if (opt & OPT_NO_EMPTY)
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]);
505 if (!(opt & OPT_INTERACTIVE))
506 bb_putchar_stderr('\n');
509 if (!(opt & OPT_INTERACTIVE) || xargs_ask_confirmation()) {
510 child_error = xargs_exec();
513 if (child_error > 0 && child_error != 123) {
517 overlapping_strcpy(buf, rem);
520 if (ENABLE_FEATURE_CLEAN_UP) {
531 const char *applet_name = "debug stuff usage";
533 void bb_show_usage(void)
535 fprintf(stderr, "Usage: %s [-p] [-r] [-t] -[x] [-n max_arg] [-s max_chars]\n",
540 int main(int argc, char **argv)
542 return xargs_main(argc, argv);