[T106][ZXW-22]7520V3SCV2.01.01.02P42U09_VEC_V0.8_AP_VEC origin source commit
Change-Id: Ic6e05d89ecd62fc34f82b23dcf306c93764aec4b
diff --git a/ap/app/busybox/src/findutils/Config.src b/ap/app/busybox/src/findutils/Config.src
new file mode 100644
index 0000000..9ee71a8
--- /dev/null
+++ b/ap/app/busybox/src/findutils/Config.src
@@ -0,0 +1,10 @@
+#
+# For a description of the syntax of this configuration file,
+# see scripts/kbuild/config-language.txt.
+#
+
+menu "Finding Utilities"
+
+INSERT
+
+endmenu
diff --git a/ap/app/busybox/src/findutils/Kbuild.src b/ap/app/busybox/src/findutils/Kbuild.src
new file mode 100644
index 0000000..6b4fb74
--- /dev/null
+++ b/ap/app/busybox/src/findutils/Kbuild.src
@@ -0,0 +1,9 @@
+# Makefile for busybox
+#
+# Copyright (C) 1999-2005 by Erik Andersen <andersen@codepoet.org>
+#
+# Licensed under GPLv2, see file LICENSE in this source tree.
+
+lib-y:=
+
+INSERT
diff --git a/ap/app/busybox/src/findutils/find.c b/ap/app/busybox/src/findutils/find.c
new file mode 100644
index 0000000..2235b50
--- /dev/null
+++ b/ap/app/busybox/src/findutils/find.c
@@ -0,0 +1,1305 @@
+/* vi: set sw=4 ts=4: */
+/*
+ * Mini find implementation for busybox
+ *
+ * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
+ *
+ * Reworked by David Douthitt <n9ubh@callsign.net> and
+ * Matt Kraai <kraai@alumni.carnegiemellon.edu>.
+ *
+ * Licensed under GPLv2, see file LICENSE in this source tree.
+ */
+
+/* findutils-4.1.20:
+ *
+ * # find file.txt -exec 'echo {}' '{} {}' ';'
+ * find: echo file.txt: No such file or directory
+ * # find file.txt -exec 'echo' '{} {}' '; '
+ * find: missing argument to `-exec'
+ * # find file.txt -exec 'echo {}' '{} {}' ';' junk
+ * find: paths must precede expression
+ * # find file.txt -exec 'echo {}' '{} {}' ';' junk ';'
+ * find: paths must precede expression
+ * # find file.txt -exec 'echo' '{} {}' ';'
+ * file.txt file.txt
+ * (strace: execve("/bin/echo", ["echo", "file.txt file.txt"], [ 30 vars ]))
+ * # find file.txt -exec 'echo' '{} {}' ';' -print -exec pwd ';'
+ * file.txt file.txt
+ * file.txt
+ * /tmp
+ * # find -name '*.c' -o -name '*.h'
+ * [shows files, *.c and *.h intermixed]
+ * # find file.txt -name '*f*' -o -name '*t*'
+ * file.txt
+ * # find file.txt -name '*z*' -o -name '*t*'
+ * file.txt
+ * # find file.txt -name '*f*' -o -name '*z*'
+ * file.txt
+ *
+ * # find t z -name '*t*' -print -o -name '*z*'
+ * t
+ * # find t z t z -name '*t*' -o -name '*z*' -print
+ * z
+ * z
+ * # find t z t z '(' -name '*t*' -o -name '*z*' ')' -o -print
+ * (no output)
+ */
+
+/* Testing script
+ * ./busybox find "$@" | tee /tmp/bb_find
+ * echo ==================
+ * /path/to/gnu/find "$@" | tee /tmp/std_find
+ * echo ==================
+ * diff -u /tmp/std_find /tmp/bb_find && echo Identical
+ */
+
+//config:config FIND
+//config: bool "find"
+//config: default y
+//config: help
+//config: find is used to search your system to find specified files.
+//config:
+//config:config FEATURE_FIND_PRINT0
+//config: bool "Enable -print0: NUL-terminated output"
+//config: default y
+//config: depends on FIND
+//config: help
+//config: Causes output names to be separated by a NUL character
+//config: rather than a newline. This allows names that contain
+//config: newlines and other whitespace to be more easily
+//config: interpreted by other programs.
+//config:
+//config:config FEATURE_FIND_MTIME
+//config: bool "Enable -mtime: modified time matching"
+//config: default y
+//config: depends on FIND
+//config: help
+//config: Allow searching based on the modification time of
+//config: files, in days.
+//config:
+//config:config FEATURE_FIND_MMIN
+//config: bool "Enable -mmin: modified time matching by minutes"
+//config: default y
+//config: depends on FIND
+//config: help
+//config: Allow searching based on the modification time of
+//config: files, in minutes.
+//config:
+//config:config FEATURE_FIND_PERM
+//config: bool "Enable -perm: permissions matching"
+//config: default y
+//config: depends on FIND
+//config: help
+//config: Enable searching based on file permissions.
+//config:
+//config:config FEATURE_FIND_TYPE
+//config: bool "Enable -type: file type matching (file/dir/link/...)"
+//config: default y
+//config: depends on FIND
+//config: help
+//config: Enable searching based on file type (file,
+//config: directory, socket, device, etc.).
+//config:
+//config:config FEATURE_FIND_XDEV
+//config: bool "Enable -xdev: 'stay in filesystem'"
+//config: default y
+//config: depends on FIND
+//config: help
+//config: This option allows find to restrict searches to a single filesystem.
+//config:
+//config:config FEATURE_FIND_MAXDEPTH
+//config: bool "Enable -mindepth N and -maxdepth N"
+//config: default y
+//config: depends on FIND
+//config: help
+//config: This option enables -mindepth N and -maxdepth N option.
+//config:
+//config:config FEATURE_FIND_NEWER
+//config: bool "Enable -newer: compare file modification times"
+//config: default y
+//config: depends on FIND
+//config: help
+//config: Support the 'find -newer' option for finding any files which have
+//config: modification time that is more recent than the specified FILE.
+//config:
+//config:config FEATURE_FIND_INUM
+//config: bool "Enable -inum: inode number matching"
+//config: default y
+//config: depends on FIND
+//config: help
+//config: Support the 'find -inum' option for searching by inode number.
+//config:
+//config:config FEATURE_FIND_EXEC
+//config: bool "Enable -exec: execute commands"
+//config: default y
+//config: depends on FIND
+//config: help
+//config: Support the 'find -exec' option for executing commands based upon
+//config: the files matched.
+//config:
+//config:config FEATURE_FIND_USER
+//config: bool "Enable -user: username/uid matching"
+//config: default y
+//config: depends on FIND
+//config: help
+//config: Support the 'find -user' option for searching by username or uid.
+//config:
+//config:config FEATURE_FIND_GROUP
+//config: bool "Enable -group: group/gid matching"
+//config: default y
+//config: depends on FIND
+//config: help
+//config: Support the 'find -group' option for searching by group name or gid.
+//config:
+//config:config FEATURE_FIND_NOT
+//config: bool "Enable the 'not' (!) operator"
+//config: default y
+//config: depends on FIND
+//config: help
+//config: Support the '!' operator to invert the test results.
+//config: If 'Enable full-blown desktop' is enabled, then will also support
+//config: the non-POSIX notation '-not'.
+//config:
+//config:config FEATURE_FIND_DEPTH
+//config: bool "Enable -depth"
+//config: default y
+//config: depends on FIND
+//config: help
+//config: Process each directory's contents before the directory itself.
+//config:
+//config:config FEATURE_FIND_PAREN
+//config: bool "Enable parens in options"
+//config: default y
+//config: depends on FIND
+//config: help
+//config: Enable usage of parens '(' to specify logical order of arguments.
+//config:
+//config:config FEATURE_FIND_SIZE
+//config: bool "Enable -size: file size matching"
+//config: default y
+//config: depends on FIND
+//config: help
+//config: Support the 'find -size' option for searching by file size.
+//config:
+//config:config FEATURE_FIND_PRUNE
+//config: bool "Enable -prune: exclude subdirectories"
+//config: default y
+//config: depends on FIND
+//config: help
+//config: If the file is a directory, dont descend into it. Useful for
+//config: exclusion .svn and CVS directories.
+//config:
+//config:config FEATURE_FIND_DELETE
+//config: bool "Enable -delete: delete files/dirs"
+//config: default y
+//config: depends on FIND && FEATURE_FIND_DEPTH
+//config: help
+//config: Support the 'find -delete' option for deleting files and directories.
+//config: WARNING: This option can do much harm if used wrong. Busybox will not
+//config: try to protect the user from doing stupid things. Use with care.
+//config:
+//config:config FEATURE_FIND_PATH
+//config: bool "Enable -path: match pathname with shell pattern"
+//config: default y
+//config: depends on FIND
+//config: help
+//config: The -path option matches whole pathname instead of just filename.
+//config:
+//config:config FEATURE_FIND_REGEX
+//config: bool "Enable -regex: match pathname with regex"
+//config: default y
+//config: depends on FIND
+//config: help
+//config: The -regex option matches whole pathname against regular expression.
+//config:
+//config:config FEATURE_FIND_CONTEXT
+//config: bool "Enable -context: security context matching"
+//config: default n
+//config: depends on FIND && SELINUX
+//config: help
+//config: Support the 'find -context' option for matching security context.
+//config:
+//config:config FEATURE_FIND_LINKS
+//config: bool "Enable -links: link count matching"
+//config: default y
+//config: depends on FIND
+//config: help
+//config: Support the 'find -links' option for matching number of links.
+
+//applet:IF_FIND(APPLET_NOEXEC(find, find, BB_DIR_USR_BIN, BB_SUID_DROP, find))
+
+//kbuild:lib-$(CONFIG_FIND) += find.o
+
+//usage:#define find_trivial_usage
+//usage: "[PATH]... [OPTIONS] [ACTIONS]"
+//usage:#define find_full_usage "\n\n"
+//usage: "Search for files and perform actions on them.\n"
+//usage: "First failed action stops processing of current file.\n"
+//usage: "Defaults: PATH is current directory, action is '-print'\n"
+//usage: "\n -follow Follow symlinks"
+//usage: IF_FEATURE_FIND_XDEV(
+//usage: "\n -xdev Don't descend directories on other filesystems"
+//usage: )
+//usage: IF_FEATURE_FIND_MAXDEPTH(
+//usage: "\n -maxdepth N Descend at most N levels. -maxdepth 0 applies"
+//usage: "\n actions to command line arguments only"
+//usage: "\n -mindepth N Don't act on first N levels"
+//usage: )
+//usage: IF_FEATURE_FIND_DEPTH(
+//usage: "\n -depth Act on directory *after* traversing it"
+//usage: )
+//usage: "\n"
+//usage: "\nActions:"
+//usage: IF_FEATURE_FIND_PAREN(
+//usage: "\n ( ACTIONS ) Group actions for -o / -a"
+//usage: )
+//usage: IF_FEATURE_FIND_NOT(
+//usage: "\n ! ACT Invert ACT's success/failure"
+//usage: )
+//usage: "\n ACT1 [-a] ACT2 If ACT1 fails, stop, else do ACT2"
+//usage: "\n ACT1 -o ACT2 If ACT1 succeeds, stop, else do ACT2"
+//usage: "\n Note: -a has higher priority than -o"
+//usage: "\n -name PATTERN Match file name (w/o directory name) to PATTERN"
+//usage: "\n -iname PATTERN Case insensitive -name"
+//usage: IF_FEATURE_FIND_PATH(
+//usage: "\n -path PATTERN Match path to PATTERN"
+//usage: "\n -ipath PATTERN Case insensitive -path"
+//usage: )
+//usage: IF_FEATURE_FIND_REGEX(
+//usage: "\n -regex PATTERN Match path to regex PATTERN"
+//usage: )
+//usage: IF_FEATURE_FIND_TYPE(
+//usage: "\n -type X File type is X (one of: f,d,l,b,c,...)"
+//usage: )
+//usage: IF_FEATURE_FIND_PERM(
+//usage: "\n -perm MASK At least one mask bit (+MASK), all bits (-MASK),"
+//usage: "\n or exactly MASK bits are set in file's mode"
+//usage: )
+//usage: IF_FEATURE_FIND_MTIME(
+//usage: "\n -mtime DAYS mtime is greater than (+N), less than (-N),"
+//usage: "\n or exactly N days in the past"
+//usage: )
+//usage: IF_FEATURE_FIND_MMIN(
+//usage: "\n -mmin MINS mtime is greater than (+N), less than (-N),"
+//usage: "\n or exactly N minutes in the past"
+//usage: )
+//usage: IF_FEATURE_FIND_NEWER(
+//usage: "\n -newer FILE mtime is more recent than FILE's"
+//usage: )
+//usage: IF_FEATURE_FIND_INUM(
+//usage: "\n -inum N File has inode number N"
+//usage: )
+//usage: IF_FEATURE_FIND_USER(
+//usage: "\n -user NAME/ID File is owned by given user"
+//usage: )
+//usage: IF_FEATURE_FIND_GROUP(
+//usage: "\n -group NAME/ID File is owned by given group"
+//usage: )
+//usage: IF_FEATURE_FIND_SIZE(
+//usage: "\n -size N[bck] File size is N (c:bytes,k:kbytes,b:512 bytes(def.))"
+//usage: "\n +/-N: file size is bigger/smaller than N"
+//usage: )
+//usage: IF_FEATURE_FIND_LINKS(
+//usage: "\n -links N Number of links is greater than (+N), less than (-N),"
+//usage: "\n or exactly N"
+//usage: )
+//usage: IF_FEATURE_FIND_CONTEXT(
+//usage: "\n -context CTX File has specified security context"
+//usage: )
+//usage: IF_FEATURE_FIND_PRUNE(
+//usage: "\n -prune If current file is directory, don't descend into it"
+//usage: )
+//usage: "\nIf none of the following actions is specified, -print is assumed"
+//usage: "\n -print Print file name"
+//usage: IF_FEATURE_FIND_PRINT0(
+//usage: "\n -print0 Print file name, NUL terminated"
+//usage: )
+//usage: IF_FEATURE_FIND_EXEC(
+//usage: "\n -exec CMD ARG ; Run CMD with all instances of {} replaced by"
+//usage: "\n file name. Fails if CMD exits with nonzero"
+//usage: )
+//usage: IF_FEATURE_FIND_DELETE(
+//usage: "\n -delete Delete current file/directory. Turns on -depth option"
+//usage: )
+//usage:
+//usage:#define find_example_usage
+//usage: "$ find / -name passwd\n"
+//usage: "/etc/passwd\n"
+
+#include <fnmatch.h>
+#include "libbb.h"
+#if ENABLE_FEATURE_FIND_REGEX
+# include "xregex.h"
+#endif
+/* GNUism: */
+#ifndef FNM_CASEFOLD
+# define FNM_CASEFOLD 0
+#endif
+
+#define dbg(...) ((void)0)
+/* #define dbg(...) bb_error_msg(__VA_ARGS__) */
+
+/* This is a NOEXEC applet. Be very careful! */
+
+
+typedef int (*action_fp)(const char *fileName, const struct stat *statbuf, void *) FAST_FUNC;
+
+typedef struct {
+ action_fp f;
+#if ENABLE_FEATURE_FIND_NOT
+ bool invert;
+#endif
+} action;
+
+#define ACTS(name, ...) typedef struct { action a; __VA_ARGS__ } action_##name;
+#define ACTF(name) \
+ static int FAST_FUNC func_##name(const char *fileName UNUSED_PARAM, \
+ const struct stat *statbuf UNUSED_PARAM, \
+ action_##name* ap UNUSED_PARAM)
+
+ ACTS(print)
+ ACTS(name, const char *pattern; bool iname;)
+IF_FEATURE_FIND_PATH( ACTS(path, const char *pattern; bool ipath;))
+IF_FEATURE_FIND_REGEX( ACTS(regex, regex_t compiled_pattern;))
+IF_FEATURE_FIND_PRINT0( ACTS(print0))
+IF_FEATURE_FIND_TYPE( ACTS(type, int type_mask;))
+IF_FEATURE_FIND_PERM( ACTS(perm, char perm_char; mode_t perm_mask;))
+IF_FEATURE_FIND_MTIME( ACTS(mtime, char mtime_char; unsigned mtime_days;))
+IF_FEATURE_FIND_MMIN( ACTS(mmin, char mmin_char; unsigned mmin_mins;))
+IF_FEATURE_FIND_NEWER( ACTS(newer, time_t newer_mtime;))
+IF_FEATURE_FIND_INUM( ACTS(inum, ino_t inode_num;))
+IF_FEATURE_FIND_USER( ACTS(user, uid_t uid;))
+IF_FEATURE_FIND_SIZE( ACTS(size, char size_char; off_t size;))
+IF_FEATURE_FIND_CONTEXT(ACTS(context, security_context_t context;))
+IF_FEATURE_FIND_PAREN( ACTS(paren, action ***subexpr;))
+IF_FEATURE_FIND_PRUNE( ACTS(prune))
+IF_FEATURE_FIND_DELETE( ACTS(delete))
+IF_FEATURE_FIND_EXEC( ACTS(exec, char **exec_argv; unsigned *subst_count; int exec_argc;))
+IF_FEATURE_FIND_GROUP( ACTS(group, gid_t gid;))
+IF_FEATURE_FIND_LINKS( ACTS(links, char links_char; int links_count;))
+
+struct globals {
+ IF_FEATURE_FIND_XDEV(dev_t *xdev_dev;)
+ IF_FEATURE_FIND_XDEV(int xdev_count;)
+#if ENABLE_FEATURE_FIND_MAXDEPTH
+ int minmaxdepth[2];
+#endif
+ action ***actions;
+ smallint need_print;
+ smallint xdev_on;
+ recurse_flags_t recurse_flags;
+} FIX_ALIASING;
+#define G (*(struct globals*)&bb_common_bufsiz1)
+#define INIT_G() do { \
+ struct G_sizecheck { \
+ char G_sizecheck[sizeof(G) > COMMON_BUFSIZE ? -1 : 1]; \
+ }; \
+ /* we have to zero it out because of NOEXEC */ \
+ memset(&G, 0, sizeof(G)); \
+ IF_FEATURE_FIND_MAXDEPTH(G.minmaxdepth[1] = INT_MAX;) \
+ G.need_print = 1; \
+ G.recurse_flags = ACTION_RECURSE; \
+} while (0)
+
+#if ENABLE_FEATURE_FIND_EXEC
+static unsigned count_subst(const char *str)
+{
+ unsigned count = 0;
+ while ((str = strstr(str, "{}")) != NULL) {
+ count++;
+ str++;
+ }
+ return count;
+}
+
+
+static char* subst(const char *src, unsigned count, const char* filename)
+{
+ char *buf, *dst, *end;
+ size_t flen = strlen(filename);
+ /* we replace each '{}' with filename: growth by strlen-2 */
+ buf = dst = xmalloc(strlen(src) + count*(flen-2) + 1);
+ while ((end = strstr(src, "{}"))) {
+ memcpy(dst, src, end - src);
+ dst += end - src;
+ src = end + 2;
+ memcpy(dst, filename, flen);
+ dst += flen;
+ }
+ strcpy(dst, src);
+ return buf;
+}
+#endif
+
+/* Return values of ACTFs ('action functions') are a bit mask:
+ * bit 1=1: prune (use SKIP constant for setting it)
+ * bit 0=1: matched successfully (TRUE)
+ */
+
+static int exec_actions(action ***appp, const char *fileName, const struct stat *statbuf)
+{
+ int cur_group;
+ int cur_action;
+ int rc = 0;
+ action **app, *ap;
+
+ /* "action group" is a set of actions ANDed together.
+ * groups are ORed together.
+ * We simply evaluate each group until we find one in which all actions
+ * succeed. */
+
+ /* -prune is special: if it is encountered, then we won't
+ * descend into current directory. It doesn't matter whether
+ * action group (in which -prune sits) will succeed or not:
+ * find * -prune -name 'f*' -o -name 'm*' -- prunes every dir
+ * find * -name 'f*' -o -prune -name 'm*' -- prunes all dirs
+ * not starting with 'f' */
+
+ /* We invert TRUE bit (bit 0). Now 1 there means 'failure'.
+ * and bitwise OR in "rc |= TRUE ^ ap->f()" will:
+ * (1) make SKIP (-prune) bit stick; and (2) detect 'failure'.
+ * On return, bit is restored. */
+
+ cur_group = -1;
+ while ((app = appp[++cur_group]) != NULL) {
+ rc &= ~TRUE; /* 'success' so far, clear TRUE bit */
+ cur_action = -1;
+ while (1) {
+ ap = app[++cur_action];
+ if (!ap) /* all actions in group were successful */
+ return rc ^ TRUE; /* restore TRUE bit */
+ rc |= TRUE ^ ap->f(fileName, statbuf, ap);
+#if ENABLE_FEATURE_FIND_NOT
+ if (ap->invert) rc ^= TRUE;
+#endif
+ dbg("grp %d action %d rc:0x%x", cur_group, cur_action, rc);
+ if (rc & TRUE) /* current group failed, try next */
+ break;
+ }
+ }
+ dbg("returning:0x%x", rc ^ TRUE);
+ return rc ^ TRUE; /* restore TRUE bit */
+}
+
+
+#if !FNM_CASEFOLD
+static char *strcpy_upcase(char *dst, const char *src)
+{
+ char *d = dst;
+ while (1) {
+ unsigned char ch = *src++;
+ if (ch >= 'a' && ch <= 'z')
+ ch -= ('a' - 'A');
+ *d++ = ch;
+ if (ch == '\0')
+ break;
+ }
+ return dst;
+}
+#endif
+
+ACTF(name)
+{
+ const char *tmp = bb_basename(fileName);
+ if (tmp != fileName && *tmp == '\0') {
+ /* "foo/bar/". Oh no... go back to 'b' */
+ tmp--;
+ while (tmp != fileName && *--tmp != '/')
+ continue;
+ if (*tmp == '/')
+ tmp++;
+ }
+ /* Was using FNM_PERIOD flag too,
+ * but somewhere between 4.1.20 and 4.4.0 GNU find stopped using it.
+ * find -name '*foo' should match .foo too:
+ */
+#if FNM_CASEFOLD
+ return fnmatch(ap->pattern, tmp, (ap->iname ? FNM_CASEFOLD : 0)) == 0;
+#else
+ if (ap->iname)
+ tmp = strcpy_upcase(alloca(strlen(tmp) + 1), tmp);
+ return fnmatch(ap->pattern, tmp, 0) == 0;
+#endif
+}
+
+#if ENABLE_FEATURE_FIND_PATH
+ACTF(path)
+{
+# if FNM_CASEFOLD
+ return fnmatch(ap->pattern, fileName, (ap->ipath ? FNM_CASEFOLD : 0)) == 0;
+# else
+ if (ap->ipath)
+ fileName = strcpy_upcase(alloca(strlen(fileName) + 1), fileName);
+ return fnmatch(ap->pattern, fileName, 0) == 0;
+# endif
+}
+#endif
+#if ENABLE_FEATURE_FIND_REGEX
+ACTF(regex)
+{
+ regmatch_t match;
+ if (regexec(&ap->compiled_pattern, fileName, 1, &match, 0 /*eflags*/))
+ return 0; /* no match */
+ if (match.rm_so)
+ return 0; /* match doesn't start at pos 0 */
+ if (fileName[match.rm_eo])
+ return 0; /* match doesn't end exactly at end of pathname */
+ return 1;
+}
+#endif
+#if ENABLE_FEATURE_FIND_TYPE
+ACTF(type)
+{
+ return ((statbuf->st_mode & S_IFMT) == ap->type_mask);
+}
+#endif
+#if ENABLE_FEATURE_FIND_PERM
+ACTF(perm)
+{
+ /* -perm +mode: at least one of perm_mask bits are set */
+ if (ap->perm_char == '+')
+ return (statbuf->st_mode & ap->perm_mask) != 0;
+ /* -perm -mode: all of perm_mask are set */
+ if (ap->perm_char == '-')
+ return (statbuf->st_mode & ap->perm_mask) == ap->perm_mask;
+ /* -perm mode: file mode must match perm_mask */
+ return (statbuf->st_mode & 07777) == ap->perm_mask;
+}
+#endif
+#if ENABLE_FEATURE_FIND_MTIME
+ACTF(mtime)
+{
+ time_t file_age = time(NULL) - statbuf->st_mtime;
+ time_t mtime_secs = ap->mtime_days * 24*60*60;
+ if (ap->mtime_char == '+')
+ return file_age >= mtime_secs + 24*60*60;
+ if (ap->mtime_char == '-')
+ return file_age < mtime_secs;
+ /* just numeric mtime */
+ return file_age >= mtime_secs && file_age < (mtime_secs + 24*60*60);
+}
+#endif
+#if ENABLE_FEATURE_FIND_MMIN
+ACTF(mmin)
+{
+ time_t file_age = time(NULL) - statbuf->st_mtime;
+ time_t mmin_secs = ap->mmin_mins * 60;
+ if (ap->mmin_char == '+')
+ return file_age >= mmin_secs + 60;
+ if (ap->mmin_char == '-')
+ return file_age < mmin_secs;
+ /* just numeric mmin */
+ return file_age >= mmin_secs && file_age < (mmin_secs + 60);
+}
+#endif
+#if ENABLE_FEATURE_FIND_NEWER
+ACTF(newer)
+{
+ return (ap->newer_mtime < statbuf->st_mtime);
+}
+#endif
+#if ENABLE_FEATURE_FIND_INUM
+ACTF(inum)
+{
+ return (statbuf->st_ino == ap->inode_num);
+}
+#endif
+#if ENABLE_FEATURE_FIND_EXEC
+ACTF(exec)
+{
+ int i, rc;
+#if ENABLE_USE_PORTABLE_CODE
+ char **argv = alloca(sizeof(char*) * (ap->exec_argc + 1));
+#else /* gcc 4.3.1 generates smaller code: */
+ char *argv[ap->exec_argc + 1];
+#endif
+ for (i = 0; i < ap->exec_argc; i++)
+ argv[i] = subst(ap->exec_argv[i], ap->subst_count[i], fileName);
+ argv[i] = NULL; /* terminate the list */
+
+ rc = spawn_and_wait(argv);
+ if (rc < 0)
+ bb_simple_perror_msg(argv[0]);
+
+ i = 0;
+ while (argv[i])
+ free(argv[i++]);
+ return rc == 0; /* return 1 if exitcode 0 */
+}
+#endif
+#if ENABLE_FEATURE_FIND_USER
+ACTF(user)
+{
+ return (statbuf->st_uid == ap->uid);
+}
+#endif
+#if ENABLE_FEATURE_FIND_GROUP
+ACTF(group)
+{
+ return (statbuf->st_gid == ap->gid);
+}
+#endif
+#if ENABLE_FEATURE_FIND_PRINT0
+ACTF(print0)
+{
+ printf("%s%c", fileName, '\0');
+ return TRUE;
+}
+#endif
+ACTF(print)
+{
+ puts(fileName);
+ return TRUE;
+}
+#if ENABLE_FEATURE_FIND_PAREN
+ACTF(paren)
+{
+ return exec_actions(ap->subexpr, fileName, statbuf);
+}
+#endif
+#if ENABLE_FEATURE_FIND_SIZE
+ACTF(size)
+{
+ if (ap->size_char == '+')
+ return statbuf->st_size > ap->size;
+ if (ap->size_char == '-')
+ return statbuf->st_size < ap->size;
+ return statbuf->st_size == ap->size;
+}
+#endif
+#if ENABLE_FEATURE_FIND_PRUNE
+/*
+ * -prune: if -depth is not given, return true and do not descend
+ * current dir; if -depth is given, return false with no effect.
+ * Example:
+ * find dir -name 'asm-*' -prune -o -name '*.[chS]' -print
+ */
+ACTF(prune)
+{
+ return SKIP + TRUE;
+}
+#endif
+#if ENABLE_FEATURE_FIND_DELETE
+ACTF(delete)
+{
+ int rc;
+ if (S_ISDIR(statbuf->st_mode)) {
+ rc = rmdir(fileName);
+ } else {
+ rc = unlink(fileName);
+ }
+ if (rc < 0)
+ bb_simple_perror_msg(fileName);
+ return TRUE;
+}
+#endif
+#if ENABLE_FEATURE_FIND_CONTEXT
+ACTF(context)
+{
+ security_context_t con;
+ int rc;
+
+ if (G.recurse_flags & ACTION_FOLLOWLINKS) {
+ rc = getfilecon(fileName, &con);
+ } else {
+ rc = lgetfilecon(fileName, &con);
+ }
+ if (rc < 0)
+ return FALSE;
+ rc = strcmp(ap->context, con);
+ freecon(con);
+ return rc == 0;
+}
+#endif
+#if ENABLE_FEATURE_FIND_LINKS
+ACTF(links)
+{
+ switch(ap->links_char) {
+ case '-' : return (statbuf->st_nlink < ap->links_count);
+ case '+' : return (statbuf->st_nlink > ap->links_count);
+ default: return (statbuf->st_nlink == ap->links_count);
+ }
+}
+#endif
+
+static int FAST_FUNC fileAction(const char *fileName,
+ struct stat *statbuf,
+ void *userData UNUSED_PARAM,
+ int depth IF_NOT_FEATURE_FIND_MAXDEPTH(UNUSED_PARAM))
+{
+ int r;
+ int same_fs = 1;
+
+#if ENABLE_FEATURE_FIND_XDEV
+ if (S_ISDIR(statbuf->st_mode) && G.xdev_count) {
+ int i;
+ for (i = 0; i < G.xdev_count; i++) {
+ if (G.xdev_dev[i] == statbuf->st_dev)
+ goto found;
+ }
+ //bb_error_msg("'%s': not same fs", fileName);
+ same_fs = 0;
+ found: ;
+ }
+#endif
+
+#if ENABLE_FEATURE_FIND_MAXDEPTH
+ if (depth < G.minmaxdepth[0]) {
+ if (same_fs)
+ return TRUE; /* skip this, continue recursing */
+ return SKIP; /* stop recursing */
+ }
+ if (depth > G.minmaxdepth[1])
+ return SKIP; /* stop recursing */
+#endif
+
+ r = exec_actions(G.actions, fileName, statbuf);
+ /* Had no explicit -print[0] or -exec? then print */
+ if ((r & TRUE) && G.need_print)
+ puts(fileName);
+
+#if ENABLE_FEATURE_FIND_MAXDEPTH
+ if (S_ISDIR(statbuf->st_mode)) {
+ if (depth == G.minmaxdepth[1])
+ return SKIP;
+ }
+#endif
+ /* -xdev stops on mountpoints, but AFTER mountpoit itself
+ * is processed as usual */
+ if (!same_fs) {
+ return SKIP;
+ }
+
+ /* Cannot return 0: our caller, recursive_action(),
+ * will perror() and skip dirs (if called on dir) */
+ return (r & SKIP) ? SKIP : TRUE;
+}
+
+
+#if ENABLE_FEATURE_FIND_TYPE
+static int find_type(const char *type)
+{
+ int mask = 0;
+
+ if (*type == 'b')
+ mask = S_IFBLK;
+ else if (*type == 'c')
+ mask = S_IFCHR;
+ else if (*type == 'd')
+ mask = S_IFDIR;
+ else if (*type == 'p')
+ mask = S_IFIFO;
+ else if (*type == 'f')
+ mask = S_IFREG;
+ else if (*type == 'l')
+ mask = S_IFLNK;
+ else if (*type == 's')
+ mask = S_IFSOCK;
+
+ if (mask == 0 || type[1] != '\0')
+ bb_error_msg_and_die(bb_msg_invalid_arg, type, "-type");
+
+ return mask;
+}
+#endif
+
+#if ENABLE_FEATURE_FIND_PERM \
+ || ENABLE_FEATURE_FIND_MTIME || ENABLE_FEATURE_FIND_MMIN \
+ || ENABLE_FEATURE_FIND_SIZE || ENABLE_FEATURE_FIND_LINKS
+static const char* plus_minus_num(const char* str)
+{
+ if (*str == '-' || *str == '+')
+ str++;
+ return str;
+}
+#endif
+
+static action*** parse_params(char **argv)
+{
+ enum {
+ OPT_FOLLOW ,
+ IF_FEATURE_FIND_XDEV( OPT_XDEV ,)
+ IF_FEATURE_FIND_DEPTH( OPT_DEPTH ,)
+ PARM_a ,
+ PARM_o ,
+ IF_FEATURE_FIND_NOT( PARM_char_not ,)
+#if ENABLE_DESKTOP
+ PARM_and ,
+ PARM_or ,
+ IF_FEATURE_FIND_NOT( PARM_not ,)
+#endif
+ PARM_print ,
+ IF_FEATURE_FIND_PRINT0( PARM_print0 ,)
+ IF_FEATURE_FIND_PRUNE( PARM_prune ,)
+ IF_FEATURE_FIND_DELETE( PARM_delete ,)
+ IF_FEATURE_FIND_EXEC( PARM_exec ,)
+ IF_FEATURE_FIND_PAREN( PARM_char_brace,)
+ /* All options/actions starting from here require argument */
+ PARM_name ,
+ PARM_iname ,
+ IF_FEATURE_FIND_PATH( PARM_path ,)
+#if ENABLE_DESKTOP
+ /* -wholename is a synonym for -path */
+ /* We support it because Linux kernel's "make tags" uses it */
+ IF_FEATURE_FIND_PATH( PARM_wholename ,)
+#endif
+ IF_FEATURE_FIND_PATH( PARM_ipath ,)
+ IF_FEATURE_FIND_REGEX( PARM_regex ,)
+ IF_FEATURE_FIND_TYPE( PARM_type ,)
+ IF_FEATURE_FIND_PERM( PARM_perm ,)
+ IF_FEATURE_FIND_MTIME( PARM_mtime ,)
+ IF_FEATURE_FIND_MMIN( PARM_mmin ,)
+ IF_FEATURE_FIND_NEWER( PARM_newer ,)
+ IF_FEATURE_FIND_INUM( PARM_inum ,)
+ IF_FEATURE_FIND_USER( PARM_user ,)
+ IF_FEATURE_FIND_GROUP( PARM_group ,)
+ IF_FEATURE_FIND_SIZE( PARM_size ,)
+ IF_FEATURE_FIND_CONTEXT(PARM_context ,)
+ IF_FEATURE_FIND_LINKS( PARM_links ,)
+ IF_FEATURE_FIND_MAXDEPTH(OPT_MINDEPTH,OPT_MAXDEPTH,)
+ };
+
+ static const char params[] ALIGN1 =
+ "-follow\0"
+ IF_FEATURE_FIND_XDEV( "-xdev\0" )
+ IF_FEATURE_FIND_DEPTH( "-depth\0" )
+ "-a\0"
+ "-o\0"
+ IF_FEATURE_FIND_NOT( "!\0" )
+#if ENABLE_DESKTOP
+ "-and\0"
+ "-or\0"
+ IF_FEATURE_FIND_NOT( "-not\0" )
+#endif
+ "-print\0"
+ IF_FEATURE_FIND_PRINT0( "-print0\0" )
+ IF_FEATURE_FIND_PRUNE( "-prune\0" )
+ IF_FEATURE_FIND_DELETE( "-delete\0" )
+ IF_FEATURE_FIND_EXEC( "-exec\0" )
+ IF_FEATURE_FIND_PAREN( "(\0" )
+ /* All options/actions starting from here require argument */
+ "-name\0"
+ "-iname\0"
+ IF_FEATURE_FIND_PATH( "-path\0" )
+#if ENABLE_DESKTOP
+ IF_FEATURE_FIND_PATH( "-wholename\0")
+#endif
+ IF_FEATURE_FIND_PATH( "-ipath\0" )
+ IF_FEATURE_FIND_REGEX( "-regex\0" )
+ IF_FEATURE_FIND_TYPE( "-type\0" )
+ IF_FEATURE_FIND_PERM( "-perm\0" )
+ IF_FEATURE_FIND_MTIME( "-mtime\0" )
+ IF_FEATURE_FIND_MMIN( "-mmin\0" )
+ IF_FEATURE_FIND_NEWER( "-newer\0" )
+ IF_FEATURE_FIND_INUM( "-inum\0" )
+ IF_FEATURE_FIND_USER( "-user\0" )
+ IF_FEATURE_FIND_GROUP( "-group\0" )
+ IF_FEATURE_FIND_SIZE( "-size\0" )
+ IF_FEATURE_FIND_CONTEXT("-context\0")
+ IF_FEATURE_FIND_LINKS( "-links\0" )
+ IF_FEATURE_FIND_MAXDEPTH("-mindepth\0""-maxdepth\0")
+ ;
+
+ action*** appp;
+ unsigned cur_group = 0;
+ unsigned cur_action = 0;
+ IF_FEATURE_FIND_NOT( bool invert_flag = 0; )
+
+ /* This is the only place in busybox where we use nested function.
+ * So far more standard alternatives were bigger. */
+ /* Auto decl suppresses "func without a prototype" warning: */
+ auto action* alloc_action(int sizeof_struct, action_fp f);
+ action* alloc_action(int sizeof_struct, action_fp f)
+ {
+ action *ap;
+ appp[cur_group] = xrealloc(appp[cur_group], (cur_action+2) * sizeof(*appp));
+ appp[cur_group][cur_action++] = ap = xzalloc(sizeof_struct);
+ appp[cur_group][cur_action] = NULL;
+ ap->f = f;
+ IF_FEATURE_FIND_NOT( ap->invert = invert_flag; )
+ IF_FEATURE_FIND_NOT( invert_flag = 0; )
+ return ap;
+ }
+
+#define ALLOC_ACTION(name) (action_##name*)alloc_action(sizeof(action_##name), (action_fp) func_##name)
+
+ appp = xzalloc(2 * sizeof(appp[0])); /* appp[0],[1] == NULL */
+
+ while (*argv) {
+ const char *arg = argv[0];
+ int parm = index_in_strings(params, arg);
+ const char *arg1 = argv[1];
+
+ dbg("arg:'%s' arg1:'%s' parm:%d PARM_type:%d", arg, arg1, parm, PARM_type);
+
+ if (parm >= PARM_name) {
+ /* All options/actions starting from -name require argument */
+ if (!arg1)
+ bb_error_msg_and_die(bb_msg_requires_arg, arg);
+ argv++;
+ }
+
+ /* We can use big switch() here, but on i386
+ * it doesn't give smaller code. Other arches? */
+
+/* Options always return true. They always take effect
+ * rather than being processed only when their place in the
+ * expression is reached.
+ */
+ /* Options */
+ if (parm == OPT_FOLLOW) {
+ dbg("follow enabled: %d", __LINE__);
+ G.recurse_flags |= ACTION_FOLLOWLINKS | ACTION_DANGLING_OK;
+ }
+#if ENABLE_FEATURE_FIND_XDEV
+ else if (parm == OPT_XDEV) {
+ dbg("%d", __LINE__);
+ G.xdev_on = 1;
+ }
+#endif
+#if ENABLE_FEATURE_FIND_MAXDEPTH
+ else if (parm == OPT_MINDEPTH || parm == OPT_MINDEPTH + 1) {
+ dbg("%d", __LINE__);
+ G.minmaxdepth[parm - OPT_MINDEPTH] = xatoi_positive(arg1);
+ }
+#endif
+#if ENABLE_FEATURE_FIND_DEPTH
+ else if (parm == OPT_DEPTH) {
+ dbg("%d", __LINE__);
+ G.recurse_flags |= ACTION_DEPTHFIRST;
+ }
+#endif
+/* Actions are grouped by operators
+ * ( expr ) Force precedence
+ * ! expr True if expr is false
+ * -not expr Same as ! expr
+ * expr1 [-a[nd]] expr2 And; expr2 is not evaluated if expr1 is false
+ * expr1 -o[r] expr2 Or; expr2 is not evaluated if expr1 is true
+ * expr1 , expr2 List; both expr1 and expr2 are always evaluated
+ * We implement: (), -a, -o
+ */
+ /* Operators */
+ else if (parm == PARM_a IF_DESKTOP(|| parm == PARM_and)) {
+ dbg("%d", __LINE__);
+ /* no further special handling required */
+ }
+ else if (parm == PARM_o IF_DESKTOP(|| parm == PARM_or)) {
+ dbg("%d", __LINE__);
+ /* start new OR group */
+ cur_group++;
+ appp = xrealloc(appp, (cur_group+2) * sizeof(*appp));
+ /*appp[cur_group] = NULL; - already NULL */
+ appp[cur_group+1] = NULL;
+ cur_action = 0;
+ }
+#if ENABLE_FEATURE_FIND_NOT
+ else if (parm == PARM_char_not IF_DESKTOP(|| parm == PARM_not)) {
+ /* also handles "find ! ! -name 'foo*'" */
+ invert_flag ^= 1;
+ dbg("invert_flag:%d", invert_flag);
+ }
+#endif
+ /* Actions */
+ else if (parm == PARM_print) {
+ dbg("%d", __LINE__);
+ G.need_print = 0;
+ (void) ALLOC_ACTION(print);
+ }
+#if ENABLE_FEATURE_FIND_PRINT0
+ else if (parm == PARM_print0) {
+ dbg("%d", __LINE__);
+ G.need_print = 0;
+ (void) ALLOC_ACTION(print0);
+ }
+#endif
+#if ENABLE_FEATURE_FIND_PRUNE
+ else if (parm == PARM_prune) {
+ dbg("%d", __LINE__);
+ (void) ALLOC_ACTION(prune);
+ }
+#endif
+#if ENABLE_FEATURE_FIND_DELETE
+ else if (parm == PARM_delete) {
+ dbg("%d", __LINE__);
+ G.need_print = 0;
+ G.recurse_flags |= ACTION_DEPTHFIRST;
+ (void) ALLOC_ACTION(delete);
+ }
+#endif
+#if ENABLE_FEATURE_FIND_EXEC
+ else if (parm == PARM_exec) {
+ int i;
+ action_exec *ap;
+ dbg("%d", __LINE__);
+ G.need_print = 0;
+ ap = ALLOC_ACTION(exec);
+ ap->exec_argv = ++argv; /* first arg after -exec */
+ /*ap->exec_argc = 0; - ALLOC_ACTION did it */
+ while (1) {
+ if (!*argv) /* did not see ';' or '+' until end */
+ bb_error_msg_and_die(bb_msg_requires_arg, "-exec");
+ // find -exec echo Foo ">{}<" ";"
+ // executes "echo Foo >FILENAME<",
+ // find -exec echo Foo ">{}<" "+"
+ // executes "echo Foo FILENAME1 FILENAME2 FILENAME3...".
+ // TODO (so far we treat "+" just like ";")
+ if ((argv[0][0] == ';' || argv[0][0] == '+')
+ && argv[0][1] == '\0'
+ ) {
+ break;
+ }
+ argv++;
+ ap->exec_argc++;
+ }
+ if (ap->exec_argc == 0)
+ bb_error_msg_and_die(bb_msg_requires_arg, arg);
+ ap->subst_count = xmalloc(ap->exec_argc * sizeof(int));
+ i = ap->exec_argc;
+ while (i--)
+ ap->subst_count[i] = count_subst(ap->exec_argv[i]);
+ }
+#endif
+#if ENABLE_FEATURE_FIND_PAREN
+ else if (parm == PARM_char_brace) {
+ action_paren *ap;
+ char **endarg;
+ unsigned nested = 1;
+
+ dbg("%d", __LINE__);
+ endarg = argv;
+ while (1) {
+ if (!*++endarg)
+ bb_error_msg_and_die("unpaired '('");
+ if (LONE_CHAR(*endarg, '('))
+ nested++;
+ else if (LONE_CHAR(*endarg, ')') && !--nested) {
+ *endarg = NULL;
+ break;
+ }
+ }
+ ap = ALLOC_ACTION(paren);
+ ap->subexpr = parse_params(argv + 1);
+ *endarg = (char*) ")"; /* restore NULLed parameter */
+ argv = endarg;
+ }
+#endif
+ else if (parm == PARM_name || parm == PARM_iname) {
+ action_name *ap;
+ dbg("%d", __LINE__);
+ ap = ALLOC_ACTION(name);
+ ap->pattern = arg1;
+ ap->iname = (parm == PARM_iname);
+ }
+#if ENABLE_FEATURE_FIND_PATH
+ else if (parm == PARM_path IF_DESKTOP(|| parm == PARM_wholename) || parm == PARM_ipath) {
+ action_path *ap;
+ dbg("%d", __LINE__);
+ ap = ALLOC_ACTION(path);
+ ap->pattern = arg1;
+ ap->ipath = (parm == PARM_ipath);
+ }
+#endif
+#if ENABLE_FEATURE_FIND_REGEX
+ else if (parm == PARM_regex) {
+ action_regex *ap;
+ dbg("%d", __LINE__);
+ ap = ALLOC_ACTION(regex);
+ xregcomp(&ap->compiled_pattern, arg1, 0 /*cflags*/);
+ }
+#endif
+#if ENABLE_FEATURE_FIND_TYPE
+ else if (parm == PARM_type) {
+ action_type *ap;
+ ap = ALLOC_ACTION(type);
+ ap->type_mask = find_type(arg1);
+ dbg("created:type mask:%x", ap->type_mask);
+ }
+#endif
+#if ENABLE_FEATURE_FIND_PERM
+/* -perm BITS File's mode bits are exactly BITS (octal or symbolic).
+ * Symbolic modes use mode 0 as a point of departure.
+ * -perm -BITS All of the BITS are set in file's mode.
+ * -perm +BITS At least one of the BITS is set in file's mode.
+ */
+ else if (parm == PARM_perm) {
+ action_perm *ap;
+ dbg("%d", __LINE__);
+ ap = ALLOC_ACTION(perm);
+ ap->perm_char = arg1[0];
+ arg1 = plus_minus_num(arg1);
+ /*ap->perm_mask = 0; - ALLOC_ACTION did it */
+ if (!bb_parse_mode(arg1, &ap->perm_mask))
+ bb_error_msg_and_die("invalid mode '%s'", arg1);
+ }
+#endif
+#if ENABLE_FEATURE_FIND_MTIME
+ else if (parm == PARM_mtime) {
+ action_mtime *ap;
+ dbg("%d", __LINE__);
+ ap = ALLOC_ACTION(mtime);
+ ap->mtime_char = arg1[0];
+ ap->mtime_days = xatoul(plus_minus_num(arg1));
+ }
+#endif
+#if ENABLE_FEATURE_FIND_MMIN
+ else if (parm == PARM_mmin) {
+ action_mmin *ap;
+ dbg("%d", __LINE__);
+ ap = ALLOC_ACTION(mmin);
+ ap->mmin_char = arg1[0];
+ ap->mmin_mins = xatoul(plus_minus_num(arg1));
+ }
+#endif
+#if ENABLE_FEATURE_FIND_NEWER
+ else if (parm == PARM_newer) {
+ struct stat stat_newer;
+ action_newer *ap;
+ dbg("%d", __LINE__);
+ ap = ALLOC_ACTION(newer);
+ xstat(arg1, &stat_newer);
+ ap->newer_mtime = stat_newer.st_mtime;
+ }
+#endif
+#if ENABLE_FEATURE_FIND_INUM
+ else if (parm == PARM_inum) {
+ action_inum *ap;
+ dbg("%d", __LINE__);
+ ap = ALLOC_ACTION(inum);
+ ap->inode_num = xatoul(arg1);
+ }
+#endif
+#if ENABLE_FEATURE_FIND_USER
+ else if (parm == PARM_user) {
+ action_user *ap;
+ dbg("%d", __LINE__);
+ ap = ALLOC_ACTION(user);
+ ap->uid = bb_strtou(arg1, NULL, 10);
+ if (errno)
+ ap->uid = xuname2uid(arg1);
+ }
+#endif
+#if ENABLE_FEATURE_FIND_GROUP
+ else if (parm == PARM_group) {
+ action_group *ap;
+ dbg("%d", __LINE__);
+ ap = ALLOC_ACTION(group);
+ ap->gid = bb_strtou(arg1, NULL, 10);
+ if (errno)
+ ap->gid = xgroup2gid(arg1);
+ }
+#endif
+#if ENABLE_FEATURE_FIND_SIZE
+ else if (parm == PARM_size) {
+/* -size n[bckw]: file uses n units of space
+ * b (default): units are 512-byte blocks
+ * c: 1 byte
+ * k: kilobytes
+ * w: 2-byte words
+ */
+#if ENABLE_LFS
+#define XATOU_SFX xatoull_sfx
+#else
+#define XATOU_SFX xatoul_sfx
+#endif
+ static const struct suffix_mult find_suffixes[] = {
+ { "c", 1 },
+ { "w", 2 },
+ { "", 512 },
+ { "b", 512 },
+ { "k", 1024 },
+ { "", 0 }
+ };
+ action_size *ap;
+ dbg("%d", __LINE__);
+ ap = ALLOC_ACTION(size);
+ ap->size_char = arg1[0];
+ ap->size = XATOU_SFX(plus_minus_num(arg1), find_suffixes);
+ }
+#endif
+#if ENABLE_FEATURE_FIND_CONTEXT
+ else if (parm == PARM_context) {
+ action_context *ap;
+ dbg("%d", __LINE__);
+ ap = ALLOC_ACTION(context);
+ /*ap->context = NULL; - ALLOC_ACTION did it */
+ /* SELinux headers erroneously declare non-const parameter */
+ if (selinux_raw_to_trans_context((char*)arg1, &ap->context))
+ bb_simple_perror_msg(arg1);
+ }
+#endif
+#if ENABLE_FEATURE_FIND_LINKS
+ else if (parm == PARM_links) {
+ action_links *ap;
+ dbg("%d", __LINE__);
+ ap = ALLOC_ACTION(links);
+ ap->links_char = arg1[0];
+ ap->links_count = xatoul(plus_minus_num(arg1));
+ }
+#endif
+ else {
+ bb_error_msg("unrecognized: %s", arg);
+ bb_show_usage();
+ }
+ argv++;
+ }
+ dbg("exiting %s", __func__);
+ return appp;
+#undef ALLOC_ACTION
+}
+
+int find_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
+int find_main(int argc UNUSED_PARAM, char **argv)
+{
+ int i, firstopt, status = EXIT_SUCCESS;
+
+ INIT_G();
+
+ argv++;
+ for (firstopt = 0; argv[firstopt]; firstopt++) {
+ if (argv[firstopt][0] == '-')
+ break;
+ if (ENABLE_FEATURE_FIND_NOT && LONE_CHAR(argv[firstopt], '!'))
+ break;
+ if (ENABLE_FEATURE_FIND_PAREN && LONE_CHAR(argv[firstopt], '('))
+ break;
+ }
+ if (firstopt == 0) {
+ *--argv = (char*)".";
+ firstopt++;
+ }
+
+ G.actions = parse_params(&argv[firstopt]);
+ argv[firstopt] = NULL;
+
+#if ENABLE_FEATURE_FIND_XDEV
+ if (G.xdev_on) {
+ struct stat stbuf;
+
+ G.xdev_count = firstopt;
+ G.xdev_dev = xzalloc(G.xdev_count * sizeof(G.xdev_dev[0]));
+ for (i = 0; argv[i]; i++) {
+ /* not xstat(): shouldn't bomb out on
+ * "find not_exist exist -xdev" */
+ if (stat(argv[i], &stbuf) == 0)
+ G.xdev_dev[i] = stbuf.st_dev;
+ /* else G.xdev_dev[i] stays 0 and
+ * won't match any real device dev_t
+ */
+ }
+ }
+#endif
+
+ for (i = 0; argv[i]; i++) {
+ if (!recursive_action(argv[i],
+ G.recurse_flags,/* flags */
+ fileAction, /* file action */
+ fileAction, /* dir action */
+ NULL, /* user data */
+ 0) /* depth */
+ ) {
+ status = EXIT_FAILURE;
+ }
+ }
+
+ return status;
+}
diff --git a/ap/app/busybox/src/findutils/grep.c b/ap/app/busybox/src/findutils/grep.c
new file mode 100644
index 0000000..863940d
--- /dev/null
+++ b/ap/app/busybox/src/findutils/grep.c
@@ -0,0 +1,823 @@
+/* vi: set sw=4 ts=4: */
+/*
+ * Mini grep implementation for busybox using libc regex.
+ *
+ * Copyright (C) 1999,2000,2001 by Lineo, inc. and Mark Whitley
+ * Copyright (C) 1999,2000,2001 by Mark Whitley <markw@codepoet.org>
+ *
+ * Licensed under GPLv2 or later, see file LICENSE in this source tree.
+ */
+/* BB_AUDIT SUSv3 defects - unsupported option -x "match whole line only". */
+/* BB_AUDIT GNU defects - always acts as -a. */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/grep.html */
+/*
+ * 2004,2006 (C) Vladimir Oleynik <dzo@simtreas.ru> -
+ * correction "-e pattern1 -e pattern2" logic and more optimizations.
+ * precompiled regex
+ *
+ * (C) 2006 Jac Goudsmit added -o option
+ */
+
+//applet:IF_GREP(APPLET(grep, BB_DIR_BIN, BB_SUID_DROP))
+//applet:IF_FEATURE_GREP_EGREP_ALIAS(APPLET_ODDNAME(egrep, grep, BB_DIR_BIN, BB_SUID_DROP, egrep))
+//applet:IF_FEATURE_GREP_FGREP_ALIAS(APPLET_ODDNAME(fgrep, grep, BB_DIR_BIN, BB_SUID_DROP, fgrep))
+
+//kbuild:lib-$(CONFIG_GREP) += grep.o
+
+//config:config GREP
+//config: bool "grep"
+//config: default y
+//config: help
+//config: grep is used to search files for a specified pattern.
+//config:
+//config:config FEATURE_GREP_EGREP_ALIAS
+//config: bool "Enable extended regular expressions (egrep & grep -E)"
+//config: default y
+//config: depends on GREP
+//config: help
+//config: Enabled support for extended regular expressions. Extended
+//config: regular expressions allow for alternation (foo|bar), grouping,
+//config: and various repetition operators.
+//config:
+//config:config FEATURE_GREP_FGREP_ALIAS
+//config: bool "Alias fgrep to grep -F"
+//config: default y
+//config: depends on GREP
+//config: help
+//config: fgrep sees the search pattern as a normal string rather than
+//config: regular expressions.
+//config: grep -F always works, this just creates the fgrep alias.
+//config:
+//config:config FEATURE_GREP_CONTEXT
+//config: bool "Enable before and after context flags (-A, -B and -C)"
+//config: default y
+//config: depends on GREP
+//config: help
+//config: Print the specified number of leading (-B) and/or trailing (-A)
+//config: context surrounding our matching lines.
+//config: Print the specified number of context lines (-C).
+
+#include "libbb.h"
+#include "xregex.h"
+
+
+/* options */
+//usage:#define grep_trivial_usage
+//usage: "[-HhnlLoqvsriw"
+//usage: "F"
+//usage: IF_FEATURE_GREP_EGREP_ALIAS("E")
+//usage: IF_EXTRA_COMPAT("z")
+//usage: "] [-m N] "
+//usage: IF_FEATURE_GREP_CONTEXT("[-A/B/C N] ")
+//usage: "PATTERN/-e PATTERN.../-f FILE [FILE]..."
+//usage:#define grep_full_usage "\n\n"
+//usage: "Search for PATTERN in FILEs (or stdin)\n"
+//usage: "\n -H Add 'filename:' prefix"
+//usage: "\n -h Do not add 'filename:' prefix"
+//usage: "\n -n Add 'line_no:' prefix"
+//usage: "\n -l Show only names of files that match"
+//usage: "\n -L Show only names of files that don't match"
+//usage: "\n -c Show only count of matching lines"
+//usage: "\n -o Show only the matching part of line"
+//usage: "\n -q Quiet. Return 0 if PATTERN is found, 1 otherwise"
+//usage: "\n -v Select non-matching lines"
+//usage: "\n -s Suppress open and read errors"
+//usage: "\n -r Recurse"
+//usage: "\n -i Ignore case"
+//usage: "\n -w Match whole words only"
+//usage: "\n -x Match whole lines only"
+//usage: "\n -F PATTERN is a literal (not regexp)"
+//usage: IF_FEATURE_GREP_EGREP_ALIAS(
+//usage: "\n -E PATTERN is an extended regexp"
+//usage: )
+//usage: IF_EXTRA_COMPAT(
+//usage: "\n -z Input is NUL terminated"
+//usage: )
+//usage: "\n -m N Match up to N times per file"
+//usage: IF_FEATURE_GREP_CONTEXT(
+//usage: "\n -A N Print N lines of trailing context"
+//usage: "\n -B N Print N lines of leading context"
+//usage: "\n -C N Same as '-A N -B N'"
+//usage: )
+//usage: "\n -e PTRN Pattern to match"
+//usage: "\n -f FILE Read pattern from file"
+//usage:
+//usage:#define grep_example_usage
+//usage: "$ grep root /etc/passwd\n"
+//usage: "root:x:0:0:root:/root:/bin/bash\n"
+//usage: "$ grep ^[rR]oo. /etc/passwd\n"
+//usage: "root:x:0:0:root:/root:/bin/bash\n"
+//usage:
+//usage:#define egrep_trivial_usage NOUSAGE_STR
+//usage:#define egrep_full_usage ""
+//usage:#define fgrep_trivial_usage NOUSAGE_STR
+//usage:#define fgrep_full_usage ""
+
+#define OPTSTR_GREP \
+ "lnqvscFiHhe:f:Lorm:wx" \
+ IF_FEATURE_GREP_CONTEXT("A:B:C:") \
+ IF_FEATURE_GREP_EGREP_ALIAS("E") \
+ IF_EXTRA_COMPAT("z") \
+ "aI"
+/* ignored: -a "assume all files to be text" */
+/* ignored: -I "assume binary files have no matches" */
+enum {
+ OPTBIT_l, /* list matched file names only */
+ OPTBIT_n, /* print line# */
+ OPTBIT_q, /* quiet - exit(EXIT_SUCCESS) of first match */
+ OPTBIT_v, /* invert the match, to select non-matching lines */
+ OPTBIT_s, /* suppress errors about file open errors */
+ OPTBIT_c, /* count matches per file (suppresses normal output) */
+ OPTBIT_F, /* literal match */
+ OPTBIT_i, /* case-insensitive */
+ OPTBIT_H, /* force filename display */
+ OPTBIT_h, /* inhibit filename display */
+ OPTBIT_e, /* -e PATTERN */
+ OPTBIT_f, /* -f FILE_WITH_PATTERNS */
+ OPTBIT_L, /* list unmatched file names only */
+ OPTBIT_o, /* show only matching parts of lines */
+ OPTBIT_r, /* recurse dirs */
+ OPTBIT_m, /* -m MAX_MATCHES */
+ OPTBIT_w, /* -w whole word match */
+ OPTBIT_x, /* -x whole line match */
+ IF_FEATURE_GREP_CONTEXT( OPTBIT_A ,) /* -A NUM: after-match context */
+ IF_FEATURE_GREP_CONTEXT( OPTBIT_B ,) /* -B NUM: before-match context */
+ IF_FEATURE_GREP_CONTEXT( OPTBIT_C ,) /* -C NUM: -A and -B combined */
+ IF_FEATURE_GREP_EGREP_ALIAS(OPTBIT_E ,) /* extended regexp */
+ IF_EXTRA_COMPAT( OPTBIT_z ,) /* input is NUL terminated */
+ OPT_l = 1 << OPTBIT_l,
+ OPT_n = 1 << OPTBIT_n,
+ OPT_q = 1 << OPTBIT_q,
+ OPT_v = 1 << OPTBIT_v,
+ OPT_s = 1 << OPTBIT_s,
+ OPT_c = 1 << OPTBIT_c,
+ OPT_F = 1 << OPTBIT_F,
+ OPT_i = 1 << OPTBIT_i,
+ OPT_H = 1 << OPTBIT_H,
+ OPT_h = 1 << OPTBIT_h,
+ OPT_e = 1 << OPTBIT_e,
+ OPT_f = 1 << OPTBIT_f,
+ OPT_L = 1 << OPTBIT_L,
+ OPT_o = 1 << OPTBIT_o,
+ OPT_r = 1 << OPTBIT_r,
+ OPT_m = 1 << OPTBIT_m,
+ OPT_w = 1 << OPTBIT_w,
+ OPT_x = 1 << OPTBIT_x,
+ OPT_A = IF_FEATURE_GREP_CONTEXT( (1 << OPTBIT_A)) + 0,
+ OPT_B = IF_FEATURE_GREP_CONTEXT( (1 << OPTBIT_B)) + 0,
+ OPT_C = IF_FEATURE_GREP_CONTEXT( (1 << OPTBIT_C)) + 0,
+ OPT_E = IF_FEATURE_GREP_EGREP_ALIAS((1 << OPTBIT_E)) + 0,
+ OPT_z = IF_EXTRA_COMPAT( (1 << OPTBIT_z)) + 0,
+};
+
+#define PRINT_FILES_WITH_MATCHES (option_mask32 & OPT_l)
+#define PRINT_LINE_NUM (option_mask32 & OPT_n)
+#define BE_QUIET (option_mask32 & OPT_q)
+#define SUPPRESS_ERR_MSGS (option_mask32 & OPT_s)
+#define PRINT_MATCH_COUNTS (option_mask32 & OPT_c)
+#define FGREP_FLAG (option_mask32 & OPT_F)
+#define PRINT_FILES_WITHOUT_MATCHES (option_mask32 & OPT_L)
+#define NUL_DELIMITED (option_mask32 & OPT_z)
+
+struct globals {
+ int max_matches;
+#if !ENABLE_EXTRA_COMPAT
+ int reflags;
+#else
+ RE_TRANSLATE_TYPE case_fold; /* RE_TRANSLATE_TYPE is [[un]signed] char* */
+#endif
+ smalluint invert_search;
+ smalluint print_filename;
+ smalluint open_errors;
+#if ENABLE_FEATURE_GREP_CONTEXT
+ smalluint did_print_line;
+ int lines_before;
+ int lines_after;
+ char **before_buf;
+ IF_EXTRA_COMPAT(size_t *before_buf_size;)
+ int last_line_printed;
+#endif
+ /* globals used internally */
+ llist_t *pattern_head; /* growable list of patterns to match */
+ const char *cur_file; /* the current file we are reading */
+} FIX_ALIASING;
+#define G (*(struct globals*)&bb_common_bufsiz1)
+#define INIT_G() do { \
+ struct G_sizecheck { \
+ char G_sizecheck[sizeof(G) > COMMON_BUFSIZE ? -1 : 1]; \
+ }; \
+} while (0)
+#define max_matches (G.max_matches )
+#if !ENABLE_EXTRA_COMPAT
+# define reflags (G.reflags )
+#else
+# define case_fold (G.case_fold )
+/* http://www.delorie.com/gnu/docs/regex/regex_46.html */
+# define reflags re_syntax_options
+# undef REG_NOSUB
+# undef REG_EXTENDED
+# undef REG_ICASE
+# define REG_NOSUB bug:is:here /* should not be used */
+/* Just RE_SYNTAX_EGREP is not enough, need to enable {n[,[m]]} too */
+# define REG_EXTENDED (RE_SYNTAX_EGREP | RE_INTERVALS | RE_NO_BK_BRACES)
+# define REG_ICASE bug:is:here /* should not be used */
+#endif
+#define invert_search (G.invert_search )
+#define print_filename (G.print_filename )
+#define open_errors (G.open_errors )
+#define did_print_line (G.did_print_line )
+#define lines_before (G.lines_before )
+#define lines_after (G.lines_after )
+#define before_buf (G.before_buf )
+#define before_buf_size (G.before_buf_size )
+#define last_line_printed (G.last_line_printed )
+#define pattern_head (G.pattern_head )
+#define cur_file (G.cur_file )
+
+
+typedef struct grep_list_data_t {
+ char *pattern;
+/* for GNU regex, matched_range must be persistent across grep_file() calls */
+#if !ENABLE_EXTRA_COMPAT
+ regex_t compiled_regex;
+ regmatch_t matched_range;
+#else
+ struct re_pattern_buffer compiled_regex;
+ struct re_registers matched_range;
+#endif
+#define ALLOCATED 1
+#define COMPILED 2
+ int flg_mem_alocated_compiled;
+} grep_list_data_t;
+
+#if !ENABLE_EXTRA_COMPAT
+#define print_line(line, line_len, linenum, decoration) \
+ print_line(line, linenum, decoration)
+#endif
+static void print_line(const char *line, size_t line_len, int linenum, char decoration)
+{
+#if ENABLE_FEATURE_GREP_CONTEXT
+ /* Happens when we go to next file, immediately hit match
+ * and try to print prev context... from prev file! Don't do it */
+ if (linenum < 1)
+ return;
+ /* possibly print the little '--' separator */
+ if ((lines_before || lines_after) && did_print_line
+ && last_line_printed != linenum - 1
+ ) {
+ puts("--");
+ }
+ /* guard against printing "--" before first line of first file */
+ did_print_line = 1;
+ last_line_printed = linenum;
+#endif
+ if (print_filename)
+ printf("%s%c", cur_file, decoration);
+ if (PRINT_LINE_NUM)
+ printf("%i%c", linenum, decoration);
+ /* Emulate weird GNU grep behavior with -ov */
+ if ((option_mask32 & (OPT_v|OPT_o)) != (OPT_v|OPT_o)) {
+#if !ENABLE_EXTRA_COMPAT
+ puts(line);
+#else
+ fwrite(line, 1, line_len, stdout);
+ putchar(NUL_DELIMITED ? '\0' : '\n');
+#endif
+ }
+}
+
+#if ENABLE_EXTRA_COMPAT
+/* Unlike getline, this one removes trailing '\n' */
+static ssize_t FAST_FUNC bb_getline(char **line_ptr, size_t *line_alloc_len, FILE *file)
+{
+ ssize_t res_sz;
+ char *line;
+ int delim = (NUL_DELIMITED ? '\0' : '\n');
+
+ res_sz = getdelim(line_ptr, line_alloc_len, delim, file);
+ line = *line_ptr;
+
+ if (res_sz > 0) {
+ if (line[res_sz - 1] == delim)
+ line[--res_sz] = '\0';
+ } else {
+ free(line); /* uclibc allocates a buffer even on EOF. WTF? */
+ }
+ return res_sz;
+}
+#endif
+
+static int grep_file(FILE *file)
+{
+ smalluint found;
+ int linenum = 0;
+ int nmatches = 0;
+#if !ENABLE_EXTRA_COMPAT
+ char *line;
+#else
+ char *line = NULL;
+ ssize_t line_len;
+ size_t line_alloc_len;
+# define rm_so start[0]
+# define rm_eo end[0]
+#endif
+#if ENABLE_FEATURE_GREP_CONTEXT
+ int print_n_lines_after = 0;
+ int curpos = 0; /* track where we are in the circular 'before' buffer */
+ int idx = 0; /* used for iteration through the circular buffer */
+#else
+ enum { print_n_lines_after = 0 };
+#endif
+
+ while (
+#if !ENABLE_EXTRA_COMPAT
+ (line = xmalloc_fgetline(file)) != NULL
+#else
+ (line_len = bb_getline(&line, &line_alloc_len, file)) >= 0
+#endif
+ ) {
+ llist_t *pattern_ptr = pattern_head;
+ grep_list_data_t *gl = gl; /* for gcc */
+
+ linenum++;
+ found = 0;
+ while (pattern_ptr) {
+ gl = (grep_list_data_t *)pattern_ptr->data;
+ if (FGREP_FLAG) {
+ char *match;
+ char *str = line;
+ opt_f_again:
+ match = ((option_mask32 & OPT_i)
+ ? strcasestr(str, gl->pattern)
+ : strstr(str, gl->pattern)
+ );
+ if (match) {
+ if (option_mask32 & OPT_x) {
+ if (match != str)
+ goto opt_f_not_found;
+ if (str[strlen(gl->pattern)] != '\0')
+ goto opt_f_not_found;
+ } else
+ if (option_mask32 & OPT_w) {
+ char c = (match != str) ? match[-1] : ' ';
+ if (!isalnum(c) && c != '_') {
+ c = match[strlen(gl->pattern)];
+ if (!c || (!isalnum(c) && c != '_'))
+ goto opt_f_found;
+ }
+ str = match + 1;
+ goto opt_f_again;
+ }
+ opt_f_found:
+ found = 1;
+ opt_f_not_found: ;
+ }
+ } else {
+#if defined(__UC_LIBC__)
+ regexp *regexes = NULL;
+ xregcomp(®exes, gl->pattern, reflags);
+ ret = !regexec(regexes, line);
+ free(regexes);
+#else
+ if (!(gl->flg_mem_alocated_compiled & COMPILED)) {
+ gl->flg_mem_alocated_compiled |= COMPILED;
+#if !ENABLE_EXTRA_COMPAT
+ xregcomp(&gl->compiled_regex, gl->pattern, reflags);
+#else
+ memset(&gl->compiled_regex, 0, sizeof(gl->compiled_regex));
+ gl->compiled_regex.translate = case_fold; /* for -i */
+ if (re_compile_pattern(gl->pattern, strlen(gl->pattern), &gl->compiled_regex))
+ bb_error_msg_and_die("bad regex '%s'", gl->pattern);
+#endif
+ }
+#if !ENABLE_EXTRA_COMPAT
+ gl->matched_range.rm_so = 0;
+ gl->matched_range.rm_eo = 0;
+#endif
+ if (
+#if !ENABLE_EXTRA_COMPAT
+ regexec(&gl->compiled_regex, line, 1, &gl->matched_range, 0) == 0
+#else
+ re_search(&gl->compiled_regex, line, line_len,
+ /*start:*/ 0, /*range:*/ line_len,
+ &gl->matched_range) >= 0
+#endif
+ ) {
+ if (option_mask32 & OPT_x) {
+ found = (gl->matched_range.rm_so == 0
+ && line[gl->matched_range.rm_eo] == '\0');
+ } else
+ if (!(option_mask32 & OPT_w)) {
+ found = 1;
+ } else {
+ char c = ' ';
+ if (gl->matched_range.rm_so)
+ c = line[gl->matched_range.rm_so - 1];
+ if (!isalnum(c) && c != '_') {
+ c = line[gl->matched_range.rm_eo];
+ if (!c || (!isalnum(c) && c != '_'))
+ found = 1;
+ }
+//BUG: "echo foop foo | grep -w foo" should match, but doesn't:
+//we bail out on first "mismatch" because it's not a word.
+ }
+ }
+#endif
+ }
+ /* If it's non-inverted search, we can stop
+ * at first match */
+ if (found && !invert_search)
+ goto do_found;
+ pattern_ptr = pattern_ptr->link;
+ } /* while (pattern_ptr) */
+
+ if (found ^ invert_search) {
+ do_found:
+ /* keep track of matches */
+ nmatches++;
+
+ /* quiet/print (non)matching file names only? */
+ if (option_mask32 & (OPT_q|OPT_l|OPT_L)) {
+ free(line); /* we don't need line anymore */
+ if (BE_QUIET) {
+ /* manpage says about -q:
+ * "exit immediately with zero status
+ * if any match is found,
+ * even if errors were detected" */
+ exit(EXIT_SUCCESS);
+ }
+ /* if we're just printing filenames, we stop after the first match */
+ if (PRINT_FILES_WITH_MATCHES) {
+ puts(cur_file);
+ /* fall through to "return 1" */
+ }
+ /* OPT_L aka PRINT_FILES_WITHOUT_MATCHES: return early */
+ return 1; /* one match */
+ }
+
+#if ENABLE_FEATURE_GREP_CONTEXT
+ /* Were we printing context and saw next (unwanted) match? */
+ if ((option_mask32 & OPT_m) && nmatches > max_matches)
+ break;
+#endif
+
+ /* print the matched line */
+ if (PRINT_MATCH_COUNTS == 0) {
+#if ENABLE_FEATURE_GREP_CONTEXT
+ int prevpos = (curpos == 0) ? lines_before - 1 : curpos - 1;
+
+ /* if we were told to print 'before' lines and there is at least
+ * one line in the circular buffer, print them */
+ if (lines_before && before_buf[prevpos] != NULL) {
+ int first_buf_entry_line_num = linenum - lines_before;
+
+ /* advance to the first entry in the circular buffer, and
+ * figure out the line number is of the first line in the
+ * buffer */
+ idx = curpos;
+ while (before_buf[idx] == NULL) {
+ idx = (idx + 1) % lines_before;
+ first_buf_entry_line_num++;
+ }
+
+ /* now print each line in the buffer, clearing them as we go */
+ while (before_buf[idx] != NULL) {
+ print_line(before_buf[idx], before_buf_size[idx], first_buf_entry_line_num, '-');
+ free(before_buf[idx]);
+ before_buf[idx] = NULL;
+ idx = (idx + 1) % lines_before;
+ first_buf_entry_line_num++;
+ }
+ }
+
+ /* make a note that we need to print 'after' lines */
+ print_n_lines_after = lines_after;
+#endif
+ if (option_mask32 & OPT_o) {
+ if (FGREP_FLAG) {
+ /* -Fo just prints the pattern
+ * (unless -v: -Fov doesnt print anything at all) */
+ if (found)
+ print_line(gl->pattern, strlen(gl->pattern), linenum, ':');
+ } else while (1) {
+ unsigned start = gl->matched_range.rm_so;
+ unsigned end = gl->matched_range.rm_eo;
+ unsigned len = end - start;
+ char old = line[end];
+ line[end] = '\0';
+ /* Empty match is not printed: try "echo test | grep -o ''" */
+ if (len != 0)
+ print_line(line + start, len, linenum, ':');
+ if (old == '\0')
+ break;
+ line[end] = old;
+ if (len == 0)
+ end++;
+#if !ENABLE_EXTRA_COMPAT
+ if (regexec(&gl->compiled_regex, line + end,
+ 1, &gl->matched_range, REG_NOTBOL) != 0)
+ break;
+ gl->matched_range.rm_so += end;
+ gl->matched_range.rm_eo += end;
+#else
+ if (re_search(&gl->compiled_regex, line, line_len,
+ end, line_len - end,
+ &gl->matched_range) < 0)
+ break;
+#endif
+ }
+ } else {
+ print_line(line, line_len, linenum, ':');
+ }
+ }
+ }
+#if ENABLE_FEATURE_GREP_CONTEXT
+ else { /* no match */
+ /* if we need to print some context lines after the last match, do so */
+ if (print_n_lines_after) {
+ print_line(line, strlen(line), linenum, '-');
+ print_n_lines_after--;
+ } else if (lines_before) {
+ /* Add the line to the circular 'before' buffer */
+ free(before_buf[curpos]);
+ before_buf[curpos] = line;
+ IF_EXTRA_COMPAT(before_buf_size[curpos] = line_len;)
+ curpos = (curpos + 1) % lines_before;
+ /* avoid free(line) - we took the line */
+ line = NULL;
+ }
+ }
+
+#endif /* ENABLE_FEATURE_GREP_CONTEXT */
+#if !ENABLE_EXTRA_COMPAT
+ free(line);
+#endif
+ /* Did we print all context after last requested match? */
+ if ((option_mask32 & OPT_m)
+ && !print_n_lines_after
+ && nmatches == max_matches
+ ) {
+ break;
+ }
+ } /* while (read line) */
+
+ /* special-case file post-processing for options where we don't print line
+ * matches, just filenames and possibly match counts */
+
+ /* grep -c: print [filename:]count, even if count is zero */
+ if (PRINT_MATCH_COUNTS) {
+ if (print_filename)
+ printf("%s:", cur_file);
+ printf("%d\n", nmatches);
+ }
+
+ /* grep -L: print just the filename */
+ if (PRINT_FILES_WITHOUT_MATCHES) {
+ /* nmatches is zero, no need to check it:
+ * we return 1 early if we detected a match
+ * and PRINT_FILES_WITHOUT_MATCHES is set */
+ puts(cur_file);
+ }
+
+ return nmatches;
+}
+
+#if ENABLE_FEATURE_CLEAN_UP
+#define new_grep_list_data(p, m) add_grep_list_data(p, m)
+static char *add_grep_list_data(char *pattern, int flg_used_mem)
+#else
+#define new_grep_list_data(p, m) add_grep_list_data(p)
+static char *add_grep_list_data(char *pattern)
+#endif
+{
+ grep_list_data_t *gl = xzalloc(sizeof(*gl));
+ gl->pattern = pattern;
+#if ENABLE_FEATURE_CLEAN_UP
+ gl->flg_mem_alocated_compiled = flg_used_mem;
+#else
+ /*gl->flg_mem_alocated_compiled = 0;*/
+#endif
+ return (char *)gl;
+}
+
+static void load_regexes_from_file(llist_t *fopt)
+{
+ while (fopt) {
+ char *line;
+ FILE *fp;
+ llist_t *cur = fopt;
+ char *ffile = cur->data;
+
+ fopt = cur->link;
+ free(cur);
+ fp = xfopen_stdin(ffile);
+ while ((line = xmalloc_fgetline(fp)) != NULL) {
+ llist_add_to(&pattern_head,
+ new_grep_list_data(line, ALLOCATED));
+ }
+ fclose_if_not_stdin(fp);
+ }
+}
+
+static int FAST_FUNC file_action_grep(const char *filename,
+ struct stat *statbuf UNUSED_PARAM,
+ void* matched,
+ int depth UNUSED_PARAM)
+{
+ FILE *file = fopen_for_read(filename);
+ if (file == NULL) {
+ if (!SUPPRESS_ERR_MSGS)
+ bb_simple_perror_msg(filename);
+ open_errors = 1;
+ return 0;
+ }
+ cur_file = filename;
+ *(int*)matched += grep_file(file);
+ fclose(file);
+ return 1;
+}
+
+static int grep_dir(const char *dir)
+{
+ int matched = 0;
+ recursive_action(dir,
+ /* recurse=yes */ ACTION_RECURSE |
+ /* followLinks=no */
+ /* depthFirst=yes */ ACTION_DEPTHFIRST,
+ /* fileAction= */ file_action_grep,
+ /* dirAction= */ NULL,
+ /* userData= */ &matched,
+ /* depth= */ 0);
+ return matched;
+}
+
+int grep_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
+int grep_main(int argc UNUSED_PARAM, char **argv)
+{
+ FILE *file;
+ int matched;
+ llist_t *fopt = NULL;
+
+ /* do normal option parsing */
+#if ENABLE_FEATURE_GREP_CONTEXT
+ int Copt, opts;
+
+ /* -H unsets -h; -C unsets -A,-B; -e,-f are lists;
+ * -m,-A,-B,-C have numeric param */
+ opt_complementary = "H-h:C-AB:e::f::m+:A+:B+:C+";
+ opts = getopt32(argv,
+ OPTSTR_GREP,
+ &pattern_head, &fopt, &max_matches,
+ &lines_after, &lines_before, &Copt);
+
+ if (opts & OPT_C) {
+ /* -C unsets prev -A and -B, but following -A or -B
+ * may override it */
+ if (!(opts & OPT_A)) /* not overridden */
+ lines_after = Copt;
+ if (!(opts & OPT_B)) /* not overridden */
+ lines_before = Copt;
+ }
+ /* sanity checks */
+ if (opts & (OPT_c|OPT_q|OPT_l|OPT_L)) {
+ option_mask32 &= ~OPT_n;
+ lines_before = 0;
+ lines_after = 0;
+ } else if (lines_before > 0) {
+ if (lines_before > INT_MAX / sizeof(long long))
+ lines_before = INT_MAX / sizeof(long long);
+ /* overflow in (lines_before * sizeof(x)) is prevented (above) */
+ before_buf = xzalloc(lines_before * sizeof(before_buf[0]));
+ IF_EXTRA_COMPAT(before_buf_size = xzalloc(lines_before * sizeof(before_buf_size[0]));)
+ }
+#else
+ /* with auto sanity checks */
+ /* -H unsets -h; -c,-q or -l unset -n; -e,-f are lists; -m N */
+ opt_complementary = "H-h:c-n:q-n:l-n:e::f::m+";
+ getopt32(argv, OPTSTR_GREP,
+ &pattern_head, &fopt, &max_matches);
+#endif
+ invert_search = ((option_mask32 & OPT_v) != 0); /* 0 | 1 */
+
+ { /* convert char **argv to grep_list_data_t */
+ llist_t *cur;
+ for (cur = pattern_head; cur; cur = cur->link)
+ cur->data = new_grep_list_data(cur->data, 0);
+ }
+ if (option_mask32 & OPT_f) {
+ load_regexes_from_file(fopt);
+ if (!pattern_head) { /* -f EMPTY_FILE? */
+ /* GNU grep treats it as "nothing matches" */
+ llist_add_to(&pattern_head, new_grep_list_data((char*) "", 0));
+ invert_search ^= 1;
+ }
+ }
+
+ if (ENABLE_FEATURE_GREP_FGREP_ALIAS && applet_name[0] == 'f')
+ option_mask32 |= OPT_F;
+
+#ifndef __UC_LIBC__
+#if !ENABLE_EXTRA_COMPAT
+ if (!(option_mask32 & (OPT_o | OPT_w)))
+ reflags = REG_NOSUB;
+#endif
+
+ if (ENABLE_FEATURE_GREP_EGREP_ALIAS
+ && (applet_name[0] == 'e' || (option_mask32 & OPT_E))
+ ) {
+ reflags |= REG_EXTENDED;
+ }
+#if ENABLE_EXTRA_COMPAT
+ else {
+ reflags = RE_SYNTAX_GREP;
+ }
+#endif
+
+ if (option_mask32 & OPT_i) {
+#if !ENABLE_EXTRA_COMPAT
+ reflags |= REG_ICASE;
+#else
+ int i;
+ case_fold = xmalloc(256);
+ for (i = 0; i < 256; i++)
+ case_fold[i] = (unsigned char)i;
+ for (i = 'a'; i <= 'z'; i++)
+ case_fold[i] = (unsigned char)(i - ('a' - 'A'));
+#endif
+ }
+#endif /* __UC_LIBC__ */
+
+ argv += optind;
+
+ /* if we didn't get a pattern from -e and no command file was specified,
+ * first parameter should be the pattern. no pattern, no worky */
+ if (pattern_head == NULL) {
+ char *pattern;
+ if (*argv == NULL)
+ bb_show_usage();
+ pattern = new_grep_list_data(*argv++, 0);
+ llist_add_to(&pattern_head, pattern);
+ }
+
+ /* argv[0..(argc-1)] should be names of file to grep through. If
+ * there is more than one file to grep, we will print the filenames. */
+ if (argv[0] && argv[1])
+ print_filename = 1;
+ /* -H / -h of course override */
+ if (option_mask32 & OPT_H)
+ print_filename = 1;
+ if (option_mask32 & OPT_h)
+ print_filename = 0;
+
+ /* If no files were specified, or '-' was specified, take input from
+ * stdin. Otherwise, we grep through all the files specified. */
+ matched = 0;
+ do {
+ cur_file = *argv;
+ file = stdin;
+ if (!cur_file || LONE_DASH(cur_file)) {
+ cur_file = "(standard input)";
+ } else {
+ if (option_mask32 & OPT_r) {
+ struct stat st;
+ if (stat(cur_file, &st) == 0 && S_ISDIR(st.st_mode)) {
+ if (!(option_mask32 & OPT_h))
+ print_filename = 1;
+ matched += grep_dir(cur_file);
+ goto grep_done;
+ }
+ }
+ /* else: fopen(dir) will succeed, but reading won't */
+ file = fopen_for_read(cur_file);
+ if (file == NULL) {
+ if (!SUPPRESS_ERR_MSGS)
+ bb_simple_perror_msg(cur_file);
+ open_errors = 1;
+ continue;
+ }
+ }
+ matched += grep_file(file);
+ fclose_if_not_stdin(file);
+ grep_done: ;
+ } while (*argv && *++argv);
+
+ /* destroy all the elments in the pattern list */
+ if (ENABLE_FEATURE_CLEAN_UP) {
+ while (pattern_head) {
+ llist_t *pattern_head_ptr = pattern_head;
+ grep_list_data_t *gl = (grep_list_data_t *)pattern_head_ptr->data;
+
+ pattern_head = pattern_head->link;
+ if (gl->flg_mem_alocated_compiled & ALLOCATED)
+ free(gl->pattern);
+ if (gl->flg_mem_alocated_compiled & COMPILED)
+ regfree(&gl->compiled_regex);
+ free(gl);
+ free(pattern_head_ptr);
+ }
+ }
+ /* 0 = success, 1 = failed, 2 = error */
+ if (open_errors)
+ return 2;
+ return !matched; /* invert return value: 0 = success, 1 = failed */
+}
diff --git a/ap/app/busybox/src/findutils/xargs.c b/ap/app/busybox/src/findutils/xargs.c
new file mode 100644
index 0000000..0d1bb43
--- /dev/null
+++ b/ap/app/busybox/src/findutils/xargs.c
@@ -0,0 +1,565 @@
+/* vi: set sw=4 ts=4: */
+/*
+ * Mini xargs implementation for busybox
+ *
+ * (C) 2002,2003 by Vladimir Oleynik <dzo@simtreas.ru>
+ *
+ * Special thanks
+ * - Mark Whitley and Glenn McGrath for stimulus to rewrite :)
+ * - Mike Rendell <michael@cs.mun.ca>
+ * and David MacKenzie <djm@gnu.ai.mit.edu>.
+ *
+ * Licensed under GPLv2 or later, see file LICENSE in this source tree.
+ *
+ * xargs is described in the Single Unix Specification v3 at
+ * http://www.opengroup.org/onlinepubs/007904975/utilities/xargs.html
+ */
+
+//config:config XARGS
+//config: bool "xargs"
+//config: default y
+//config: help
+//config: xargs is used to execute a specified command for
+//config: every item from standard input.
+//config:
+//config:config FEATURE_XARGS_SUPPORT_CONFIRMATION
+//config: bool "Enable -p: prompt and confirmation"
+//config: default y
+//config: depends on XARGS
+//config: help
+//config: Support -p: prompt the user whether to run each command
+//config: line and read a line from the terminal.
+//config:
+//config:config FEATURE_XARGS_SUPPORT_QUOTES
+//config: bool "Enable single and double quotes and backslash"
+//config: default y
+//config: depends on XARGS
+//config: help
+//config: Support quoting in the input.
+//config:
+//config:config FEATURE_XARGS_SUPPORT_TERMOPT
+//config: bool "Enable -x: exit if -s or -n is exceeded"
+//config: default y
+//config: depends on XARGS
+//config: help
+//config: Support -x: exit if the command size (see the -s or -n option)
+//config: is exceeded.
+//config:
+//config:config FEATURE_XARGS_SUPPORT_ZERO_TERM
+//config: bool "Enable -0: NUL-terminated input"
+//config: default y
+//config: depends on XARGS
+//config: help
+//config: Support -0: input items are terminated by a NUL character
+//config: instead of whitespace, and the quotes and backslash
+//config: are not special.
+
+//applet:IF_XARGS(APPLET_NOEXEC(xargs, xargs, BB_DIR_USR_BIN, BB_SUID_DROP, xargs))
+
+//kbuild:lib-$(CONFIG_XARGS) += xargs.o
+
+#include "libbb.h"
+
+/* This is a NOEXEC applet. Be very careful! */
+
+
+//#define dbg_msg(...) bb_error_msg(__VA_ARGS__)
+#define dbg_msg(...) ((void)0)
+
+
+#ifdef TEST
+# ifndef ENABLE_FEATURE_XARGS_SUPPORT_CONFIRMATION
+# define ENABLE_FEATURE_XARGS_SUPPORT_CONFIRMATION 1
+# endif
+# ifndef ENABLE_FEATURE_XARGS_SUPPORT_QUOTES
+# define ENABLE_FEATURE_XARGS_SUPPORT_QUOTES 1
+# endif
+# ifndef ENABLE_FEATURE_XARGS_SUPPORT_TERMOPT
+# define ENABLE_FEATURE_XARGS_SUPPORT_TERMOPT 1
+# endif
+# ifndef ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM
+# define ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM 1
+# endif
+#endif
+
+
+struct globals {
+ char **args;
+ const char *eof_str;
+ int idx;
+} FIX_ALIASING;
+#define G (*(struct globals*)&bb_common_bufsiz1)
+#define INIT_G() do { \
+ G.eof_str = NULL; /* need to clear by hand because we are NOEXEC applet */ \
+} while (0)
+
+
+/*
+ * This function has special algorithm.
+ * Don't use fork and include to main!
+ */
+static int xargs_exec(void)
+{
+ int status;
+
+ status = spawn_and_wait(G.args);
+ if (status < 0) {
+ bb_simple_perror_msg(G.args[0]);
+ return errno == ENOENT ? 127 : 126;
+ }
+ if (status == 255) {
+ bb_error_msg("%s: exited with status 255; aborting", G.args[0]);
+ return 124;
+ }
+ if (status >= 0x180) {
+ bb_error_msg("%s: terminated by signal %d",
+ G.args[0], status - 0x180);
+ return 125;
+ }
+ if (status)
+ return 123;
+ return 0;
+}
+
+/* In POSIX/C locale isspace is only these chars: "\t\n\v\f\r" and space.
+ * "\t\n\v\f\r" happen to have ASCII codes 9,10,11,12,13.
+ */
+#define ISSPACE(a) ({ unsigned char xargs__isspace = (a) - 9; xargs__isspace == (' ' - 9) || xargs__isspace <= (13 - 9); })
+
+static void store_param(char *s)
+{
+ /* Grow by 256 elements at once */
+ if (!(G.idx & 0xff)) { /* G.idx == N*256 */
+ /* Enlarge, make G.args[(N+1)*256 - 1] last valid idx */
+ G.args = xrealloc(G.args, sizeof(G.args[0]) * (G.idx + 0x100));
+ }
+ G.args[G.idx++] = s;
+}
+
+/* process[0]_stdin:
+ * Read characters into buf[n_max_chars+1], and when parameter delimiter
+ * is seen, store the address of a new parameter to args[].
+ * If reading discovers that last chars do not form the complete
+ * parameter, the pointer to the first such "tail character" is returned.
+ * (buf has extra byte at the end to accomodate terminating NUL
+ * of "tail characters" string).
+ * Otherwise, the returned pointer points to NUL byte.
+ * On entry, buf[] may contain some "seed chars" which are to become
+ * the beginning of the first parameter.
+ */
+
+#if ENABLE_FEATURE_XARGS_SUPPORT_QUOTES
+static char* FAST_FUNC process_stdin(int n_max_chars, int n_max_arg, char *buf)
+{
+#define NORM 0
+#define QUOTE 1
+#define BACKSLASH 2
+#define SPACE 4
+ char q = '\0'; /* quote char */
+ char state = NORM;
+ char *s = buf; /* start of the word */
+ char *p = s + strlen(buf); /* end of the word */
+
+ buf += n_max_chars; /* past buffer's end */
+
+ /* "goto ret" is used instead of "break" to make control flow
+ * more obvious: */
+
+ while (1) {
+ int c = getchar();
+ if (c == EOF) {
+ if (p != s)
+ goto close_word;
+ goto ret;
+ }
+ if (state == BACKSLASH) {
+ state = NORM;
+ goto set;
+ }
+ if (state == QUOTE) {
+ if (c != q)
+ goto set;
+ q = '\0';
+ state = NORM;
+ } else { /* if (state == NORM) */
+ if (ISSPACE(c)) {
+ if (p != s) {
+ close_word:
+ state = SPACE;
+ c = '\0';
+ goto set;
+ }
+ } else {
+ if (c == '\\') {
+ state = BACKSLASH;
+ } else if (c == '\'' || c == '"') {
+ q = c;
+ state = QUOTE;
+ } else {
+ set:
+ *p++ = c;
+ }
+ }
+ }
+ if (state == SPACE) { /* word's delimiter or EOF detected */
+ if (q) {
+ bb_error_msg_and_die("unmatched %s quote",
+ q == '\'' ? "single" : "double");
+ }
+ /* A full word is loaded */
+ if (G.eof_str) {
+ if (strcmp(s, G.eof_str) == 0) {
+ while (getchar() != EOF)
+ continue;
+ p = s;
+ goto ret;
+ }
+ }
+ store_param(s);
+ dbg_msg("args[]:'%s'", s);
+ s = p;
+ n_max_arg--;
+ if (n_max_arg == 0) {
+ goto ret;
+ }
+ state = NORM;
+ }
+ if (p == buf) {
+ goto ret;
+ }
+ }
+ ret:
+ *p = '\0';
+ /* store_param(NULL) - caller will do it */
+ dbg_msg("return:'%s'", s);
+ return s;
+}
+#else
+/* The variant does not support single quotes, double quotes or backslash */
+static char* FAST_FUNC process_stdin(int n_max_chars, int n_max_arg, char *buf)
+{
+ char *s = buf; /* start of the word */
+ char *p = s + strlen(buf); /* end of the word */
+
+ buf += n_max_chars; /* past buffer's end */
+
+ while (1) {
+ int c = getchar();
+ if (c == EOF) {
+ if (p == s)
+ goto ret;
+ }
+ if (c == EOF || ISSPACE(c)) {
+ if (p == s)
+ continue;
+ c = EOF;
+ }
+ *p++ = (c == EOF ? '\0' : c);
+ if (c == EOF) { /* word's delimiter or EOF detected */
+ /* A full word is loaded */
+ if (G.eof_str) {
+ if (strcmp(s, G.eof_str) == 0) {
+ while (getchar() != EOF)
+ continue;
+ p = s;
+ goto ret;
+ }
+ }
+ store_param(s);
+ dbg_msg("args[]:'%s'", s);
+ s = p;
+ n_max_arg--;
+ if (n_max_arg == 0) {
+ goto ret;
+ }
+ }
+ if (p == buf) {
+ goto ret;
+ }
+ }
+ ret:
+ *p = '\0';
+ /* store_param(NULL) - caller will do it */
+ dbg_msg("return:'%s'", s);
+ return s;
+}
+#endif /* FEATURE_XARGS_SUPPORT_QUOTES */
+
+#if ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM
+static char* FAST_FUNC process0_stdin(int n_max_chars, int n_max_arg, char *buf)
+{
+ char *s = buf; /* start of the word */
+ char *p = s + strlen(buf); /* end of the word */
+
+ buf += n_max_chars; /* past buffer's end */
+
+ while (1) {
+ int c = getchar();
+ if (c == EOF) {
+ if (p == s)
+ goto ret;
+ c = '\0';
+ }
+ *p++ = c;
+ if (c == '\0') { /* word's delimiter or EOF detected */
+ /* A full word is loaded */
+ store_param(s);
+ dbg_msg("args[]:'%s'", s);
+ s = p;
+ n_max_arg--;
+ if (n_max_arg == 0) {
+ goto ret;
+ }
+ }
+ if (p == buf) {
+ goto ret;
+ }
+ }
+ ret:
+ *p = '\0';
+ /* store_param(NULL) - caller will do it */
+ dbg_msg("return:'%s'", s);
+ return s;
+}
+#endif /* FEATURE_XARGS_SUPPORT_ZERO_TERM */
+
+#if ENABLE_FEATURE_XARGS_SUPPORT_CONFIRMATION
+/* Prompt the user for a response, and
+ if the user responds affirmatively, return true;
+ otherwise, return false. Uses "/dev/tty", not stdin. */
+static int xargs_ask_confirmation(void)
+{
+ FILE *tty_stream;
+ int c, savec;
+
+ tty_stream = xfopen_for_read(CURRENT_TTY);
+ fputs(" ?...", stderr);
+ fflush_all();
+ c = savec = getc(tty_stream);
+ while (c != EOF && c != '\n')
+ c = getc(tty_stream);
+ fclose(tty_stream);
+ return (savec == 'y' || savec == 'Y');
+}
+#else
+# define xargs_ask_confirmation() 1
+#endif
+
+//usage:#define xargs_trivial_usage
+//usage: "[OPTIONS] [PROG ARGS]"
+//usage:#define xargs_full_usage "\n\n"
+//usage: "Run PROG on every item given by stdin\n"
+//usage: IF_FEATURE_XARGS_SUPPORT_CONFIRMATION(
+//usage: "\n -p Ask user whether to run each command"
+//usage: )
+//usage: "\n -r Don't run command if input is empty"
+//usage: IF_FEATURE_XARGS_SUPPORT_ZERO_TERM(
+//usage: "\n -0 Input is separated by NUL characters"
+//usage: )
+//usage: "\n -t Print the command on stderr before execution"
+//usage: "\n -e[STR] STR stops input processing"
+//usage: "\n -n N Pass no more than N args to PROG"
+//usage: "\n -s N Pass command line of no more than N bytes"
+//usage: IF_FEATURE_XARGS_SUPPORT_TERMOPT(
+//usage: "\n -x Exit if size is exceeded"
+//usage: )
+//usage:#define xargs_example_usage
+//usage: "$ ls | xargs gzip\n"
+//usage: "$ find . -name '*.c' -print | xargs rm\n"
+
+/* Correct regardless of combination of CONFIG_xxx */
+enum {
+ OPTBIT_VERBOSE = 0,
+ OPTBIT_NO_EMPTY,
+ OPTBIT_UPTO_NUMBER,
+ OPTBIT_UPTO_SIZE,
+ OPTBIT_EOF_STRING,
+ OPTBIT_EOF_STRING1,
+ IF_FEATURE_XARGS_SUPPORT_CONFIRMATION(OPTBIT_INTERACTIVE,)
+ IF_FEATURE_XARGS_SUPPORT_TERMOPT( OPTBIT_TERMINATE ,)
+ IF_FEATURE_XARGS_SUPPORT_ZERO_TERM( OPTBIT_ZEROTERM ,)
+
+ OPT_VERBOSE = 1 << OPTBIT_VERBOSE ,
+ OPT_NO_EMPTY = 1 << OPTBIT_NO_EMPTY ,
+ OPT_UPTO_NUMBER = 1 << OPTBIT_UPTO_NUMBER,
+ OPT_UPTO_SIZE = 1 << OPTBIT_UPTO_SIZE ,
+ OPT_EOF_STRING = 1 << OPTBIT_EOF_STRING , /* GNU: -e[<param>] */
+ OPT_EOF_STRING1 = 1 << OPTBIT_EOF_STRING1, /* SUS: -E<param> */
+ OPT_INTERACTIVE = IF_FEATURE_XARGS_SUPPORT_CONFIRMATION((1 << OPTBIT_INTERACTIVE)) + 0,
+ OPT_TERMINATE = IF_FEATURE_XARGS_SUPPORT_TERMOPT( (1 << OPTBIT_TERMINATE )) + 0,
+ OPT_ZEROTERM = IF_FEATURE_XARGS_SUPPORT_ZERO_TERM( (1 << OPTBIT_ZEROTERM )) + 0,
+};
+#define OPTION_STR "+trn:s:e::E:" \
+ IF_FEATURE_XARGS_SUPPORT_CONFIRMATION("p") \
+ IF_FEATURE_XARGS_SUPPORT_TERMOPT( "x") \
+ IF_FEATURE_XARGS_SUPPORT_ZERO_TERM( "0")
+
+int xargs_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
+int xargs_main(int argc, char **argv)
+{
+ int i;
+ int child_error = 0;
+ char *max_args;
+ char *max_chars;
+ char *buf;
+ unsigned opt;
+ int n_max_chars;
+ int n_max_arg;
+#if ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM
+ char* FAST_FUNC (*read_args)(int, int, char*) = process_stdin;
+#else
+#define read_args process_stdin
+#endif
+
+ INIT_G();
+
+#if ENABLE_DESKTOP && ENABLE_LONG_OPTS
+ /* For example, Fedora's build system uses --no-run-if-empty */
+ applet_long_options =
+ "no-run-if-empty\0" No_argument "r"
+ ;
+#endif
+ opt = getopt32(argv, OPTION_STR, &max_args, &max_chars, &G.eof_str, &G.eof_str);
+
+ /* -E ""? You may wonder why not just omit -E?
+ * This is used for portability:
+ * old xargs was using "_" as default for -E / -e */
+ if ((opt & OPT_EOF_STRING1) && G.eof_str[0] == '\0')
+ G.eof_str = NULL;
+
+ if (opt & OPT_ZEROTERM)
+ IF_FEATURE_XARGS_SUPPORT_ZERO_TERM(read_args = process0_stdin);
+
+ argv += optind;
+ argc -= optind;
+ if (!argv[0]) {
+ /* default behavior is to echo all the filenames */
+ *--argv = (char*)"echo";
+ argc++;
+ }
+
+ /* -s NUM default. fileutils-4.4.2 uses 128k, but I heasitate
+ * to use such a big value - first need to change code to use
+ * growable buffer instead of fixed one.
+ */
+ n_max_chars = 32 * 1024;
+ /* Make smaller if system does not allow our default value.
+ * The Open Group Base Specifications Issue 6:
+ * "The xargs utility shall limit the command line length such that
+ * when the command line is invoked, the combined argument
+ * and environment lists (see the exec family of functions
+ * in the System Interfaces volume of IEEE Std 1003.1-2001)
+ * shall not exceed {ARG_MAX}-2048 bytes".
+ */
+ {
+ long arg_max = 0;
+#if defined _SC_ARG_MAX
+ arg_max = sysconf(_SC_ARG_MAX) - 2048;
+#elif defined ARG_MAX
+ arg_max = ARG_MAX - 2048;
+#endif
+ if (arg_max > 0 && n_max_chars > arg_max)
+ n_max_chars = arg_max;
+ }
+ if (opt & OPT_UPTO_SIZE) {
+ n_max_chars = xatou_range(max_chars, 1, INT_MAX);
+ }
+ /* Account for prepended fixed arguments */
+ {
+ size_t n_chars = 0;
+ for (i = 0; argv[i]; i++) {
+ n_chars += strlen(argv[i]) + 1;
+ }
+ n_max_chars -= n_chars;
+ }
+ /* Sanity check */
+ if (n_max_chars <= 0) {
+ bb_error_msg_and_die("can't fit single argument within argument list size limit");
+ }
+
+ buf = xzalloc(n_max_chars + 1);
+
+ n_max_arg = n_max_chars;
+ if (opt & OPT_UPTO_NUMBER) {
+ n_max_arg = xatou_range(max_args, 1, INT_MAX);
+ /* Not necessary, we use growable args[]: */
+ /* if (n_max_arg > n_max_chars) n_max_arg = n_max_chars */
+ }
+
+ /* Allocate pointers for execvp */
+ /* We can statically allocate (argc + n_max_arg + 1) elements
+ * and do not bother with resizing args[], but on 64-bit machines
+ * this results in args[] vector which is ~8 times bigger
+ * than n_max_chars! That is, with n_max_chars == 20k,
+ * args[] will take 160k (!), which will most likely be
+ * almost entirely unused.
+ */
+ /* See store_param() for matching 256-step growth logic */
+ G.args = xmalloc(sizeof(G.args[0]) * ((argc + 0xff) & ~0xff));
+
+ /* Store the command to be executed, part 1 */
+ for (i = 0; argv[i]; i++)
+ G.args[i] = argv[i];
+
+ while (1) {
+ char *rem;
+
+ G.idx = argc;
+ rem = read_args(n_max_chars, n_max_arg, buf);
+ store_param(NULL);
+
+ if (!G.args[argc]) {
+ if (*rem != '\0')
+ bb_error_msg_and_die("argument line too long");
+ if (opt & OPT_NO_EMPTY)
+ break;
+ }
+ opt |= OPT_NO_EMPTY;
+
+ if (opt & (OPT_INTERACTIVE | OPT_VERBOSE)) {
+ const char *fmt = " %s" + 1;
+ char **args = G.args;
+ for (i = 0; args[i]; i++) {
+ fprintf(stderr, fmt, args[i]);
+ fmt = " %s";
+ }
+ if (!(opt & OPT_INTERACTIVE))
+ bb_putchar_stderr('\n');
+ }
+
+ if (!(opt & OPT_INTERACTIVE) || xargs_ask_confirmation()) {
+ child_error = xargs_exec();
+ }
+
+ if (child_error > 0 && child_error != 123) {
+ break;
+ }
+
+ overlapping_strcpy(buf, rem);
+ } /* while */
+
+ if (ENABLE_FEATURE_CLEAN_UP) {
+ free(G.args);
+ free(buf);
+ }
+
+ return child_error;
+}
+
+
+#ifdef TEST
+
+const char *applet_name = "debug stuff usage";
+
+void bb_show_usage(void)
+{
+ fprintf(stderr, "Usage: %s [-p] [-r] [-t] -[x] [-n max_arg] [-s max_chars]\n",
+ applet_name);
+ exit(EXIT_FAILURE);
+}
+
+int main(int argc, char **argv)
+{
+ return xargs_main(argc, argv);
+}
+#endif /* TEST */