1 /* vi: set sw=4 ts=4: */
3 * Mini xargs implementation for busybox
5 * (C) 2002,2003 by Vladimir Oleynik <dzo@simtreas.ru>
8 * - Mark Whitley and Glenn McGrath for stimulus to rewrite :)
9 * - Mike Rendell <michael@cs.mun.ca>
10 * and David MacKenzie <djm@gnu.ai.mit.edu>.
12 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
14 * xargs is described in the Single Unix Specification v3 at
15 * http://www.opengroup.org/onlinepubs/007904975/utilities/xargs.html
18 //applet:IF_XARGS(APPLET_NOEXEC(xargs, xargs, _BB_DIR_USR_BIN, _BB_SUID_DROP, xargs))
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 q = '\0'; /* quote char */
166 char *s = buf; /* start of the word */
167 char *p = s + strlen(buf); /* end of the word */
169 buf += n_max_chars; /* past buffer's end */
171 /* "goto ret" is used instead of "break" to make control flow
181 if (state == BACKSLASH) {
185 if (state == QUOTE) {
190 } else { /* if (state == NORM) */
201 } else if (c == '\'' || c == '"') {
210 if (state == SPACE) { /* word's delimiter or EOF detected */
212 bb_error_msg_and_die("unmatched %s quote",
213 q == '\'' ? "single" : "double");
215 /* A full word is loaded */
217 if (strcmp(s, G.eof_str) == 0) {
218 while (getchar() != EOF)
225 dbg_msg("args[]:'%s'", s);
228 if (n_max_arg == 0) {
239 /* store_param(NULL) - caller will do it */
240 dbg_msg("return:'%s'", s);
244 /* The variant does not support single quotes, double quotes or backslash */
245 static char* FAST_FUNC process_stdin(int n_max_chars, int n_max_arg, char *buf)
247 char *s = buf; /* start of the word */
248 char *p = s + strlen(buf); /* end of the word */
250 buf += n_max_chars; /* past buffer's end */
258 if (c == EOF || ISSPACE(c)) {
263 *p++ = (c == EOF ? '\0' : c);
264 if (c == EOF) { /* word's delimiter or EOF detected */
265 /* A full word is loaded */
267 if (strcmp(s, G.eof_str) == 0) {
268 while (getchar() != EOF)
275 dbg_msg("args[]:'%s'", s);
278 if (n_max_arg == 0) {
288 /* store_param(NULL) - caller will do it */
289 dbg_msg("return:'%s'", s);
292 #endif /* FEATURE_XARGS_SUPPORT_QUOTES */
294 #if ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM
295 static char* FAST_FUNC process0_stdin(int n_max_chars, int n_max_arg, char *buf)
297 char *s = buf; /* start of the word */
298 char *p = s + strlen(buf); /* end of the word */
300 buf += n_max_chars; /* past buffer's end */
310 if (c == '\0') { /* word's delimiter or EOF detected */
311 /* A full word is loaded */
313 dbg_msg("args[]:'%s'", s);
316 if (n_max_arg == 0) {
326 /* store_param(NULL) - caller will do it */
327 dbg_msg("return:'%s'", s);
330 #endif /* FEATURE_XARGS_SUPPORT_ZERO_TERM */
332 #if ENABLE_FEATURE_XARGS_SUPPORT_CONFIRMATION
333 /* Prompt the user for a response, and
334 if the user responds affirmatively, return true;
335 otherwise, return false. Uses "/dev/tty", not stdin. */
336 static int xargs_ask_confirmation(void)
341 tty_stream = xfopen_for_read(CURRENT_TTY);
342 fputs(" ?...", stderr);
344 c = savec = getc(tty_stream);
345 while (c != EOF && c != '\n')
346 c = getc(tty_stream);
348 return (savec == 'y' || savec == 'Y');
351 # define xargs_ask_confirmation() 1
354 //usage:#define xargs_trivial_usage
355 //usage: "[OPTIONS] [PROG ARGS]"
356 //usage:#define xargs_full_usage "\n\n"
357 //usage: "Run PROG on every item given by stdin\n"
358 //usage: "\nOptions:"
359 //usage: IF_FEATURE_XARGS_SUPPORT_CONFIRMATION(
360 //usage: "\n -p Ask user whether to run each command"
362 //usage: "\n -r Don't run command if input is empty"
363 //usage: IF_FEATURE_XARGS_SUPPORT_ZERO_TERM(
364 //usage: "\n -0 Input is separated by NUL characters"
366 //usage: "\n -t Print the command on stderr before execution"
367 //usage: "\n -e[STR] STR stops input processing"
368 //usage: "\n -n N Pass no more than N args to PROG"
369 //usage: "\n -s N Pass command line of no more than N bytes"
370 //usage: IF_FEATURE_XARGS_SUPPORT_TERMOPT(
371 //usage: "\n -x Exit if size is exceeded"
373 //usage:#define xargs_example_usage
374 //usage: "$ ls | xargs gzip\n"
375 //usage: "$ find . -name '*.c' -print | xargs rm\n"
377 /* Correct regardless of combination of CONFIG_xxx */
385 IF_FEATURE_XARGS_SUPPORT_CONFIRMATION(OPTBIT_INTERACTIVE,)
386 IF_FEATURE_XARGS_SUPPORT_TERMOPT( OPTBIT_TERMINATE ,)
387 IF_FEATURE_XARGS_SUPPORT_ZERO_TERM( OPTBIT_ZEROTERM ,)
389 OPT_VERBOSE = 1 << OPTBIT_VERBOSE ,
390 OPT_NO_EMPTY = 1 << OPTBIT_NO_EMPTY ,
391 OPT_UPTO_NUMBER = 1 << OPTBIT_UPTO_NUMBER,
392 OPT_UPTO_SIZE = 1 << OPTBIT_UPTO_SIZE ,
393 OPT_EOF_STRING = 1 << OPTBIT_EOF_STRING , /* GNU: -e[<param>] */
394 OPT_EOF_STRING1 = 1 << OPTBIT_EOF_STRING1, /* SUS: -E<param> */
395 OPT_INTERACTIVE = IF_FEATURE_XARGS_SUPPORT_CONFIRMATION((1 << OPTBIT_INTERACTIVE)) + 0,
396 OPT_TERMINATE = IF_FEATURE_XARGS_SUPPORT_TERMOPT( (1 << OPTBIT_TERMINATE )) + 0,
397 OPT_ZEROTERM = IF_FEATURE_XARGS_SUPPORT_ZERO_TERM( (1 << OPTBIT_ZEROTERM )) + 0,
399 #define OPTION_STR "+trn:s:e::E:" \
400 IF_FEATURE_XARGS_SUPPORT_CONFIRMATION("p") \
401 IF_FEATURE_XARGS_SUPPORT_TERMOPT( "x") \
402 IF_FEATURE_XARGS_SUPPORT_ZERO_TERM( "0")
404 int xargs_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
405 int xargs_main(int argc, char **argv)
415 #if ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM
416 char* FAST_FUNC (*read_args)(int, int, char*) = process_stdin;
418 #define read_args process_stdin
424 opt = getopt32(argv, OPTION_STR, &max_args, &max_chars, &G.eof_str, &G.eof_str);
426 /* -E ""? You may wonder why not just omit -E?
427 * This is used for portability:
428 * old xargs was using "_" as default for -E / -e */
429 if ((opt & OPT_EOF_STRING1) && G.eof_str[0] == '\0')
432 if (opt & OPT_ZEROTERM)
433 IF_FEATURE_XARGS_SUPPORT_ZERO_TERM(read_args = process0_stdin);
438 /* default behavior is to echo all the filenames */
439 *--argv = (char*)"echo";
443 /* The Open Group Base Specifications Issue 6:
444 * "The xargs utility shall limit the command line length such that
445 * when the command line is invoked, the combined argument
446 * and environment lists (see the exec family of functions
447 * in the System Interfaces volume of IEEE Std 1003.1-2001)
448 * shall not exceed {ARG_MAX}-2048 bytes".
450 n_max_chars = ARG_MAX; /* might be calling sysconf(_SC_ARG_MAX) */
451 if (n_max_chars < 4*1024); /* paranoia */
452 n_max_chars = 4*1024;
454 /* Sanity check for systems with huge ARG_MAX defines (e.g., Suns which
455 * have it at 1 meg). Things will work fine with a large ARG_MAX
456 * but it will probably hurt the system more than it needs to;
457 * an array of this size is allocated.
459 if (n_max_chars > 20 * 1024)
460 n_max_chars = 20 * 1024;
462 if (opt & OPT_UPTO_SIZE) {
464 n_max_chars = xatou_range(max_chars, 1, INT_MAX);
465 for (i = 0; argv[i]; i++) {
466 n_chars += strlen(argv[i]) + 1;
468 n_max_chars -= n_chars;
469 if (n_max_chars <= 0) {
470 bb_error_msg_and_die("can't fit single argument within argument list size limit");
474 buf = xzalloc(n_max_chars + 1);
476 n_max_arg = n_max_chars;
477 if (opt & OPT_UPTO_NUMBER) {
478 n_max_arg = xatou_range(max_args, 1, INT_MAX);
481 /* Allocate pointers for execvp */
482 /* We can statically allocate (argc + n_max_arg + 1) elements
483 * and do not bother with resizing args[], but on 64-bit machines
484 * this results in args[] vector which is ~8 times bigger
485 * than n_max_chars! That is, with n_max_chars == 20k,
486 * args[] will take 160k (!), which will most likely be
487 * almost entirely unused.
489 /* See store_param() for matching 256-step growth logic */
490 G.args = xmalloc(sizeof(G.args[0]) * ((argc + 0xff) & ~0xff));
492 /* Store the command to be executed, part 1 */
493 for (i = 0; argv[i]; i++)
500 rem = read_args(n_max_chars, n_max_arg, buf);
505 bb_error_msg_and_die("argument line too long");
506 if (opt & OPT_NO_EMPTY)
511 if (opt & (OPT_INTERACTIVE | OPT_VERBOSE)) {
512 const char *fmt = " %s" + 1;
513 char **args = G.args;
514 for (i = 0; args[i]; i++) {
515 fprintf(stderr, fmt, args[i]);
518 if (!(opt & OPT_INTERACTIVE))
519 bb_putchar_stderr('\n');
522 if (!(opt & OPT_INTERACTIVE) || xargs_ask_confirmation()) {
523 child_error = xargs_exec();
526 if (child_error > 0 && child_error != 123) {
530 overlapping_strcpy(buf, rem);
533 if (ENABLE_FEATURE_CLEAN_UP) {
544 const char *applet_name = "debug stuff usage";
546 void bb_show_usage(void)
548 fprintf(stderr, "Usage: %s [-p] [-r] [-t] -[x] [-n max_arg] [-s max_chars]\n",
553 int main(int argc, char **argv)
555 return xargs_main(argc, argv);