toybox/toys/posix/find.c
<<
>>
Prefs
   1/* find.c - Search directories for matching files.
   2 *
   3 * Copyright 2014 Rob Landley <rob@landley.net>
   4 *
   5 * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/find.c
   6 *
   7 * Our "unspecified" behavior for no paths is to use "."
   8 * Parentheses can only stack 4096 deep
   9 * Not treating two {} as an error, but only using last
  10
  11USE_FIND(NEWTOY(find, "?^HL[-HL]", TOYFLAG_USR|TOYFLAG_BIN))
  12
  13config FIND
  14  bool "find"
  15  default y
  16  help
  17    usage: find [-HL] [DIR...] [<options>]
  18
  19    Search directories for matching files.
  20    Default: search "." match all -print all matches.
  21
  22    -H  Follow command line symlinks         -L  Follow all symlinks
  23
  24    Match filters:
  25    -name  PATTERN  filename with wildcards   -iname      case insensitive -name
  26    -path  PATTERN  path name with wildcards  -ipath      case insensitive -path
  27    -user  UNAME    belongs to user UNAME     -nouser     user ID not known
  28    -group GROUP    belongs to group GROUP    -nogroup    group ID not known
  29    -perm  [-/]MODE permissions (-=min /=any) -prune      ignore contents of dir
  30    -size  N[c]     512 byte blocks (c=bytes) -xdev       only this filesystem
  31    -links N        hardlink count            -atime N[u] accessed N units ago
  32    -ctime N[u]     created N units ago       -mtime N[u] modified N units ago
  33    -newer FILE     newer mtime than FILE     -mindepth # at least # dirs down
  34    -depth          ignore contents of dir    -maxdepth # at most # dirs down
  35    -inum  N        inode number N            -empty      empty files and dirs
  36    -type [bcdflps]   (block, char, dir, file, symlink, pipe, socket)
  37    -context PATTERN  security context
  38
  39    Numbers N may be prefixed by a - (less than) or + (greater than). Units for
  40    -Xtime are d (days, default), h (hours), m (minutes), or s (seconds).
  41
  42    Combine matches with:
  43    !, -a, -o, ( )    not, and, or, group expressions
  44
  45    Actions:
  46    -print   Print match with newline  -print0    Print match with null
  47    -exec    Run command with path     -execdir   Run command in file's dir
  48    -ok      Ask before exec           -okdir     Ask before execdir
  49    -delete         Remove matching file/dir
  50    -printf FORMAT  Print using format string
  51
  52    Commands substitute "{}" with matched file. End with ";" to run each file,
  53    or "+" (next argument after "{}") to collect and run with multiple files.
  54
  55    -printf FORMAT characters are \ escapes and:
  56    %b 512 byte blocks used
  57    %f  basename            %g  textual gid          %G  numeric gid
  58    %i  decimal inode       %l  target of symlink    %m  octal mode
  59    %M  ls format type/mode %p  path to file         %P  path to file minus DIR
  60    %s  size in bytes       %T@ mod time as unixtime
  61    %u  username            %U  numeric uid          %Z  security context
  62*/
  63
  64#define FOR_find
  65#include "toys.h"
  66
  67GLOBALS(
  68  char **filter;
  69  struct double_list *argdata;
  70  int topdir, xdev, depth;
  71  time_t now;
  72  long max_bytes;
  73  char *start;
  74)
  75
  76struct execdir_data {
  77  struct execdir_data *next;
  78
  79  int namecount;
  80  struct double_list *names;
  81};
  82
  83// None of this can go in TT because you can have more than one -exec
  84struct exec_range {
  85  char *next, *prev;  // layout compatible with struct double_list
  86
  87  int dir, plus, arglen, argsize, curly;
  88  char **argstart;
  89  struct execdir_data exec, *execdir;
  90};
  91
  92// Perform pending -exec (if any)
  93static int flush_exec(struct dirtree *new, struct exec_range *aa)
  94{
  95  struct execdir_data *bb = aa->execdir ? aa->execdir : &aa->exec;
  96  char **newargs;
  97  int rc, revert = 0;
  98
  99  if (!bb->namecount) return 0;
 100
 101  dlist_terminate(bb->names);
 102
 103  // switch to directory for -execdir, or back to top if we have an -execdir
 104  // _and_ a normal -exec, or are at top of tree in -execdir
 105  if (TT.topdir != -1) {
 106    if (aa->dir && new && new->parent) {
 107      revert++;
 108      rc = fchdir(new->parent->dirfd);
 109    } else rc = fchdir(TT.topdir);
 110    if (rc) {
 111      perror_msg_raw(revert ? new->name : ".");
 112
 113      return rc;
 114    }
 115  }
 116
 117  // execdir: accumulated execs in this directory's children.
 118  newargs = xmalloc(sizeof(char *)*(aa->arglen+bb->namecount+1));
 119  if (aa->curly < 0) {
 120    memcpy(newargs, aa->argstart, sizeof(char *)*aa->arglen);
 121    newargs[aa->arglen] = 0;
 122  } else {
 123    int pos = aa->curly, rest = aa->arglen - aa->curly;
 124    struct double_list *dl;
 125
 126    // Collate argument list
 127    memcpy(newargs, aa->argstart, sizeof(char *)*pos);
 128    for (dl = bb->names; dl; dl = dl->next) newargs[pos++] = dl->data;
 129    rest = aa->arglen - aa->curly - 1;
 130    memcpy(newargs+pos, aa->argstart+aa->curly+1, sizeof(char *)*rest);
 131    newargs[pos+rest] = 0;
 132  }
 133
 134  rc = xrun(newargs);
 135
 136  llist_traverse(bb->names, llist_free_double);
 137  bb->names = 0;
 138  bb->namecount = 0;
 139
 140  if (revert) revert = fchdir(TT.topdir);
 141
 142  return rc;
 143}
 144
 145// Return numeric value with explicit sign
 146static int compare_numsign(long val, long units, char *str)
 147{
 148  char sign = 0;
 149  long myval;
 150
 151  if (*str == '+' || *str == '-') sign = *(str++);
 152  else if (!isdigit(*str)) error_exit("%s not [+-]N", str);
 153  myval = atolx(str);
 154  if (units && isdigit(str[strlen(str)-1])) myval *= units;
 155
 156  if (sign == '+') return val > myval;
 157  if (sign == '-') return val < myval;
 158  return val == myval;
 159}
 160
 161static void do_print(struct dirtree *new, char c)
 162{
 163  char *s=dirtree_path(new, 0);
 164
 165  xprintf("%s%c", s, c);
 166  free(s);
 167}
 168
 169// Descend or ascend -execdir + directory level
 170static void execdir(struct dirtree *new, int flush)
 171{
 172  struct double_list *dl;
 173  struct exec_range *aa;
 174  struct execdir_data *bb;
 175
 176  if (new && TT.topdir == -1) return;
 177
 178  for (dl = TT.argdata; dl; dl = dl->next) {
 179    if (dl->prev != (void *)1) continue;
 180    aa = (void *)dl;
 181    if (!aa->plus || (new && !aa->dir)) continue;
 182
 183    if (flush) {
 184
 185      // Flush pending "-execdir +" instances for this dir
 186      // or flush everything for -exec at top
 187      toys.exitval |= flush_exec(new, aa);
 188
 189      // pop per-directory struct
 190      if ((bb = aa->execdir)) {
 191        aa->execdir = bb->next;
 192        free(bb);
 193      }
 194    } else if (aa->dir) {
 195
 196      // Push new per-directory struct for -execdir/okdir + codepath. (Can't
 197      // use new->extra because command line may have multiple -execdir)
 198      bb = xzalloc(sizeof(struct execdir_data));
 199      bb->next = aa->execdir;
 200      aa->execdir = bb;
 201    }
 202  }
 203}
 204
 205// Call this with 0 for first pass argument parsing and syntax checking (which
 206// populates argdata). Later commands traverse argdata (in order) when they
 207// need "do once" results.
 208static int do_find(struct dirtree *new)
 209{
 210  int pcount = 0, print = 0, not = 0, active = !!new, test = active, recurse;
 211  struct double_list *argdata = TT.argdata;
 212  char *s, **ss;
 213
 214  recurse = DIRTREE_COMEAGAIN|(DIRTREE_SYMFOLLOW*!!(toys.optflags&FLAG_L));
 215
 216  // skip . and .. below topdir, handle -xdev and -depth
 217  if (new) {
 218    if (new->parent) {
 219      if (!dirtree_notdotdot(new)) return 0;
 220      if (TT.xdev && new->st.st_dev != new->parent->st.st_dev) recurse = 0;
 221    } else TT.start = new->name;
 222
 223    if (S_ISDIR(new->st.st_mode)) {
 224      // Descending into new directory
 225      if (!new->again) {
 226        struct dirtree *n;
 227
 228        for (n = new->parent; n; n = n->parent) {
 229          if (n->st.st_ino==new->st.st_ino && n->st.st_dev==new->st.st_dev) {
 230            error_msg("'%s': loop detected", s = dirtree_path(new, 0));
 231            free(s);
 232
 233            return 0;
 234          }
 235        }
 236
 237        if (TT.depth) {
 238          execdir(new, 0);
 239
 240          return recurse;
 241        }
 242      // Done with directory (COMEAGAIN call)
 243      } else {
 244        execdir(new, 1);
 245        recurse = 0;
 246        if (!TT.depth) return 0;
 247      }
 248    }
 249  }
 250
 251  // pcount: parentheses stack depth (using toybuf bytes, 4096 max depth)
 252  // test: result of most recent test
 253  // active: if 0 don't perform tests
 254  // not: a pending ! applies to this test (only set if performing tests)
 255  // print: saw one of print/ok/exec, no need for default -print
 256
 257  if (TT.filter) for (ss = TT.filter; *ss; ss++) {
 258    int check = active && test;
 259
 260    s = *ss;
 261
 262    // handle ! ( ) using toybuf as a stack
 263    if (*s != '-') {
 264      if (s[1]) goto error;
 265
 266      if (*s == '!') {
 267        // Don't invert if we're not making a decision
 268        if (check) not = !not;
 269
 270      // Save old "not" and "active" on toybuf stack.
 271      // Deactivate this parenthetical if !test
 272      // Note: test value should never change while !active
 273      } else if (*s == '(') {
 274        if (pcount == sizeof(toybuf)) goto error;
 275        toybuf[pcount++] = not+(active<<1);
 276        if (!check) active = 0;
 277        not = 0;
 278
 279      // Pop status, apply deferred not to test
 280      } else if (*s == ')') {
 281        if (--pcount < 0) goto error;
 282        // Pop active state, apply deferred not (which was only set if checking)
 283        active = (toybuf[pcount]>>1)&1;
 284        if (active && (toybuf[pcount]&1)) test = !test;
 285        not = 0;
 286      } else goto error;
 287
 288      continue;
 289    } else s++;
 290
 291    if (!strcmp(s, "xdev")) TT.xdev = 1;
 292    else if (!strcmp(s, "delete")) {
 293      // Delete forces depth first
 294      TT.depth = 1;
 295      if (new && check)
 296        test = !unlinkat(dirtree_parentfd(new), new->name,
 297          S_ISDIR(new->st.st_mode) ? AT_REMOVEDIR : 0);
 298    } else if (!strcmp(s, "depth")) TT.depth = 1;
 299    else if (!strcmp(s, "o") || !strcmp(s, "or")) {
 300      if (not) goto error;
 301      if (active) {
 302        if (!test) test = 1;
 303        else active = 0;     // decision has been made until next ")"
 304      }
 305    } else if (!strcmp(s, "not")) {
 306      if (check) not = !not;
 307      continue;
 308    // Mostly ignore NOP argument
 309    } else if (!strcmp(s, "a") || !strcmp(s, "and") || !strcmp(s, "noleaf")) {
 310      if (not) goto error;
 311
 312    } else if (!strcmp(s, "print") || !strcmp("print0", s)) {
 313      print++;
 314      if (check) do_print(new, s[5] ? 0 : '\n');
 315
 316    } else if (!strcmp(s, "empty")) {
 317      if (check) {
 318        // Alas neither st_size nor st_blocks reliably show an empty directory
 319        if (S_ISDIR(new->st.st_mode)) {
 320          int fd = openat(dirtree_parentfd(new), new->name, O_RDONLY);
 321          DIR *dfd = fdopendir(fd);
 322          struct dirent *de = (void *)1;
 323          if (dfd) {
 324            while ((de = readdir(dfd)) && isdotdot(de->d_name));
 325            closedir(dfd);
 326          }
 327          if (de) test = 0;
 328        } else if (S_ISREG(new->st.st_mode)) {
 329          if (new->st.st_size) test = 0;
 330        } else test = 0;
 331      }
 332    } else if (!strcmp(s, "nouser")) {
 333      if (check) if (bufgetpwuid(new->st.st_uid)) test = 0;
 334    } else if (!strcmp(s, "nogroup")) {
 335      if (check) if (bufgetgrgid(new->st.st_gid)) test = 0;
 336    } else if (!strcmp(s, "prune")) {
 337      if (check && S_ISDIR(new->st.st_mode) && !TT.depth) recurse = 0;
 338
 339    // Remaining filters take an argument
 340    } else {
 341      if (!strcmp(s, "name") || !strcmp(s, "iname")
 342        || !strcmp(s, "wholename") || !strcmp(s, "iwholename")
 343        || !strcmp(s, "path") || !strcmp(s, "ipath"))
 344      {
 345        int i = (*s == 'i'), is_path = (s[i] != 'n');
 346        char *arg = ss[1], *path = 0, *name = new ? new->name : arg;
 347
 348        // Handle path expansion and case flattening
 349        if (new && is_path) name = path = dirtree_path(new, 0);
 350        if (i) {
 351          if ((check || !new) && name) name = strlower(name);
 352          if (!new) dlist_add(&TT.argdata, name);
 353          else arg = ((struct double_list *)llist_pop(&argdata))->data;
 354        }
 355
 356        if (check) {
 357          test = !fnmatch(arg, name, FNM_PATHNAME*(!is_path));
 358          if (i) free(name);
 359        }
 360        free(path);
 361      } else if (!CFG_TOYBOX_LSM_NONE && !strcmp(s, "context")) {
 362        if (check) {
 363          char *path = dirtree_path(new, 0), *context;
 364
 365          if (lsm_get_context(path, &context) != -1) {
 366            test = !fnmatch(ss[1], context, 0);
 367            free(context);
 368          } else test = 0;
 369          free(path);
 370        }
 371      } else if (!strcmp(s, "perm")) {
 372        if (check) {
 373          char *m = ss[1];
 374          int match_min = *m == '-',
 375              match_any = *m == '/';
 376          mode_t m1 = string_to_mode(m+(match_min || match_any), 0),
 377                 m2 = new->st.st_mode & 07777;
 378
 379          if (match_min || match_any) m2 &= m1;
 380          test = match_any ? !m1 || m2 : m1 == m2;
 381        }
 382      } else if (!strcmp(s, "type")) {
 383        if (check) {
 384          int types[] = {S_IFBLK, S_IFCHR, S_IFDIR, S_IFLNK, S_IFIFO,
 385                         S_IFREG, S_IFSOCK}, i = stridx("bcdlpfs", *ss[1]);
 386
 387          if (i<0) error_exit("bad -type '%c'", *ss[1]);
 388          if ((new->st.st_mode & S_IFMT) != types[i]) test = 0;
 389        }
 390
 391      } else if (strchr("acm", *s)
 392        && (!strcmp(s+1, "time") || !strcmp(s+1, "min")))
 393      {
 394        if (check) {
 395          char *copy = ss[1];
 396          time_t thyme = (int []){new->st.st_atime, new->st.st_ctime,
 397                                  new->st.st_mtime}[stridx("acm", *s)];
 398          int len = strlen(copy), uu, units = (s[1]=='m') ? 60 : 86400;
 399
 400          if (len && -1!=(uu = stridx("dhms",tolower(copy[len-1])))) {
 401            copy = xstrdup(copy);
 402            copy[--len] = 0;
 403            units = (int []){86400, 3600, 60, 1}[uu];
 404          }
 405          test = compare_numsign(TT.now - thyme, units, copy);
 406          if (copy != ss[1]) free(copy);
 407        }
 408      } else if (!strcmp(s, "size")) {
 409        if (check) test = compare_numsign(new->st.st_size, 512, ss[1]);
 410      } else if (!strcmp(s, "links")) {
 411        if (check) test = compare_numsign(new->st.st_nlink, 0, ss[1]);
 412      } else if (!strcmp(s, "inum")) {
 413        if (check) test = compare_numsign(new->st.st_ino, 0, ss[1]);
 414      } else if (!strcmp(s, "mindepth") || !strcmp(s, "maxdepth")) {
 415        if (check) {
 416          struct dirtree *dt = new;
 417          int i = 0, d = atolx(ss[1]);
 418
 419          while ((dt = dt->parent)) i++;
 420          if (s[1] == 'i') {
 421            test = i >= d;
 422            if (i == d && not) recurse = 0;
 423          } else {
 424            test = i <= d;
 425            if (i == d && !not) recurse = 0;
 426          }
 427        }
 428      } else if (!strcmp(s, "user") || !strcmp(s, "group")
 429              || !strcmp(s, "newer"))
 430      {
 431        struct {
 432          void *next, *prev;
 433          union {
 434            uid_t uid;
 435            gid_t gid;
 436            struct timespec tm;
 437          } u;
 438        } *udl;
 439
 440        if (!new) {
 441          if (ss[1]) {
 442            udl = xmalloc(sizeof(*udl));
 443            dlist_add_nomalloc(&TT.argdata, (void *)udl);
 444
 445            if (*s == 'u') udl->u.uid = xgetuid(ss[1]);
 446            else if (*s == 'g') udl->u.gid = xgetgid(ss[1]);
 447            else {
 448              struct stat st;
 449
 450              xstat(ss[1], &st);
 451              udl->u.tm = st.st_mtim;
 452            }
 453          }
 454        } else {
 455          udl = (void *)llist_pop(&argdata);
 456          if (check) {
 457            if (*s == 'u') test = new->st.st_uid == udl->u.uid;
 458            else if (*s == 'g') test = new->st.st_gid == udl->u.gid;
 459            else {
 460              test = new->st.st_mtim.tv_sec > udl->u.tm.tv_sec;
 461              if (new->st.st_mtim.tv_sec == udl->u.tm.tv_sec)
 462                test = new->st.st_mtim.tv_nsec > udl->u.tm.tv_nsec;
 463            }
 464          }
 465        }
 466      } else if (!strcmp(s, "exec") || !strcmp("ok", s)
 467              || !strcmp(s, "execdir") || !strcmp(s, "okdir"))
 468      {
 469        struct exec_range *aa;
 470
 471        print++;
 472
 473        // Initial argument parsing pass
 474        if (!new) {
 475          int len;
 476
 477          // catch "-exec" with no args and "-exec \;"
 478          if (!ss[1] || !strcmp(ss[1], ";")) error_exit("'%s' needs 1 arg", s);
 479
 480          dlist_add_nomalloc(&TT.argdata, (void *)(aa = xzalloc(sizeof(*aa))));
 481          aa->argstart = ++ss;
 482          aa->curly = -1;
 483
 484          // Record command line arguments to -exec
 485          for (len = 0; ss[len]; len++) {
 486            if (!strcmp(ss[len], ";")) break;
 487            else if (!strcmp(ss[len], "{}")) {
 488              aa->curly = len;
 489              if (ss[len+1] && !strcmp(ss[len+1], "+")) {
 490                aa->plus++;
 491                len++;
 492                break;
 493              }
 494            } else aa->argsize += sizeof(char *) + strlen(ss[len]) + 1;
 495          }
 496          if (!ss[len]) error_exit("-exec without %s",
 497            aa->curly!=-1 ? "\\;" : "{}");
 498          ss += len;
 499          aa->arglen = len;
 500          aa->dir = !!strchr(s, 'd');
 501          if (TT.topdir == -1) TT.topdir = xopenro(".");
 502
 503        // collect names and execute commands
 504        } else {
 505          char *name, *ss1 = ss[1];
 506          struct execdir_data *bb;
 507
 508          // Grab command line exec argument list
 509          aa = (void *)llist_pop(&argdata);
 510          ss += aa->arglen + 1;
 511
 512          if (!check) goto cont;
 513          // name is always a new malloc, so we can always free it.
 514          name = aa->dir ? xstrdup(new->name) : dirtree_path(new, 0);
 515
 516          if (*s == 'o') {
 517            fprintf(stderr, "[%s] %s", ss1, name);
 518            if (!(test = yesno(0))) {
 519              free(name);
 520              goto cont;
 521            }
 522          }
 523
 524          // Add next name to list (global list without -dir, local with)
 525          bb = aa->execdir ? aa->execdir : &aa->exec;
 526          dlist_add(&bb->names, name);
 527          bb->namecount++;
 528
 529          // -exec + collates and saves result in exitval
 530          if (aa->plus) {
 531            // Mark entry so COMEAGAIN can call flush_exec() in parent.
 532            // This is never a valid pointer value for prev to have otherwise
 533            // Done here vs argument parsing pass so it's after dlist_terminate
 534            aa->prev = (void *)1;
 535
 536            // Flush if the child's environment space gets too large.
 537            // Linux caps individual arguments/variables at 131072 bytes,
 538            // so this counter can't wrap.
 539            if ((aa->plus += sizeof(char *)+strlen(name)+1) > TT.max_bytes) {
 540              aa->plus = 1;
 541              toys.exitval |= flush_exec(new, aa);
 542            }
 543          } else test = !flush_exec(new, aa);
 544        }
 545
 546        // Argument consumed, skip the check.
 547        goto cont;
 548      } else if (!strcmp(s, "printf")) {
 549        char *fmt, *ff, next[32], buf[64], ch;
 550        long ll;
 551        int len;
 552
 553        print++;
 554        if (check) for (fmt = ss[1]; *fmt; fmt++) {
 555          // Print the parts that aren't escapes
 556          if (*fmt == '\\') {
 557            if (!(ch = unescape(*++fmt))) error_exit("bad \\%c", *fmt);
 558            putchar(ch);
 559          } else if (*fmt != '%') putchar(*fmt);
 560          else if (*++fmt == '%') putchar('%');
 561          else {
 562            fmt = next_printf(ff = fmt-1, 0);
 563            if ((len = fmt-ff)>28) error_exit("bad %.*s", len+1, ff);
 564            memcpy(next, ff, len);
 565            ff = 0;
 566            ch = *fmt;
 567
 568            // long long is its own stack size on LP64, so handle seperately
 569            if (ch == 'i' || ch == 's') {
 570              strcpy(next+len, "lld");
 571              printf(next, (ch == 'i') ? (long long)new->st.st_ino
 572                : (long long)new->st.st_size);
 573            } else {
 574
 575              // LP64 says these are all a single "long" argument to printf
 576              strcpy(next+len, "s");
 577              if (ch == 'G') next[len] = 'd', ll = new->st.st_gid;
 578              else if (ch == 'm') next[len] = 'o', ll = new->st.st_mode&~S_IFMT;
 579              else if (ch == 'U') next[len] = 'd', ll = new->st.st_uid;
 580              else if (ch == 'f') ll = (long)new->name;
 581              else if (ch == 'g') ll = (long)getgroupname(new->st.st_gid);
 582              else if (ch == 'u') ll = (long)getusername(new->st.st_uid);
 583              else if (ch == 'l') {
 584                char *path = dirtree_path(new, 0);
 585
 586                ll = (long)(ff = xreadlink(path));
 587                free(path);
 588                if (!ll) ll = (long)"";
 589              } else if (ch == 'M') {
 590                mode_to_string(new->st.st_mode, buf);
 591                ll = (long)buf;
 592              } else if (ch == 'P') {
 593                ch = *TT.start;
 594                *TT.start = 0;
 595                ll = (long)(ff = dirtree_path(new, 0));
 596                *TT.start = ch;
 597              } else if (ch == 'p') ll = (long)(ff = dirtree_path(new, 0));
 598              else if (ch == 'T') {
 599                if (*++fmt!='@') error_exit("bad -printf %%T: %%T%c", *fmt);
 600                sprintf(buf, "%ld.%ld", new->st.st_mtim.tv_sec,
 601                             new->st.st_mtim.tv_nsec);
 602                ll = (long)buf;
 603              } else error_exit("bad -printf %%%c", ch);
 604
 605              printf(next, ll);
 606              free(ff);
 607            }
 608          }
 609        }
 610      } else goto error;
 611
 612      // This test can go at the end because we do a syntax checking
 613      // pass first. Putting it here gets the error message (-unknown
 614      // vs -known noarg) right.
 615      if (!*++ss) error_exit("'%s' needs 1 arg", --s);
 616    }
 617cont:
 618    // Apply pending "!" to result
 619    if (active && not) test = !test;
 620    not = 0;
 621  }
 622
 623  if (new) {
 624    // If there was no action, print
 625    if (!print && test) do_print(new, '\n');
 626
 627    if (S_ISDIR(new->st.st_mode)) execdir(new, 0);
 628
 629  } else dlist_terminate(TT.argdata);
 630
 631  return recurse;
 632
 633error:
 634  error_exit("bad arg '%s'", *ss);
 635}
 636
 637void find_main(void)
 638{
 639  int i, len;
 640  char **ss = toys.optargs;
 641
 642  TT.topdir = -1;
 643  TT.max_bytes = sysconf(_SC_ARG_MAX) - environ_bytes();
 644
 645  // Distinguish paths from filters
 646  for (len = 0; toys.optargs[len]; len++)
 647    if (strchr("-!(", *toys.optargs[len])) break;
 648  TT.filter = toys.optargs+len;
 649
 650  // use "." if no paths
 651  if (!len) {
 652    ss = (char *[]){"."};
 653    len = 1;
 654  }
 655
 656  // first pass argument parsing, verify args match up, handle "evaluate once"
 657  TT.now = time(0);
 658  do_find(0);
 659
 660  // Loop through paths
 661  for (i = 0; i < len; i++)
 662    dirtree_flagread(ss[i], DIRTREE_SYMFOLLOW*!!(toys.optflags&(FLAG_H|FLAG_L)),
 663      do_find);
 664
 665  execdir(0, 1);
 666
 667  if (CFG_TOYBOX_FREE) {
 668    close(TT.topdir);
 669    llist_traverse(TT.argdata, free);
 670  }
 671}
 672