(root)/
findutils-4.9.0/
find/
util.c
       1  /* util.c -- functions for initializing new tree elements, and other things.
       2     Copyright (C) 1990-2022 Free Software Foundation, Inc.
       3  
       4     This program is free software: you can redistribute it and/or modify
       5     it under the terms of the GNU General Public License as published by
       6     the Free Software Foundation, either version 3 of the License, or
       7     (at your option) any later version.
       8  
       9     This program is distributed in the hope that it will be useful,
      10     but WITHOUT ANY WARRANTY; without even the implied warranty of
      11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12     GNU General Public License for more details.
      13  
      14     You should have received a copy of the GNU General Public License
      15     along with this program.  If not, see <https://www.gnu.org/licenses/>.
      16  */
      17  
      18  /* config.h must always come first. */
      19  #include <config.h>
      20  
      21  /* system headers. */
      22  #include <assert.h>
      23  #include <ctype.h>
      24  #include <errno.h>
      25  #include <fcntl.h>
      26  #include <limits.h>
      27  #include <string.h>
      28  #include <sys/stat.h> /* for fstatat() */
      29  #include <sys/time.h>
      30  #include <sys/utsname.h>
      31  
      32  /* gnulib headers. */
      33  #include "error.h"
      34  #include "fdleak.h"
      35  #include "progname.h"
      36  #include "quotearg.h"
      37  #include "save-cwd.h"
      38  #include "timespec.h"
      39  #include "xalloc.h"
      40  
      41  /* find headers. */
      42  #include "defs.h"
      43  #include "die.h"
      44  #include "dircallback.h"
      45  #include "bugreports.h"
      46  #include "system.h"
      47  
      48  
      49  struct debug_option_assoc
      50  {
      51    const char *name;
      52    int    val;
      53    const char *docstring;
      54  };
      55  static struct debug_option_assoc debugassoc[] =
      56    {
      57      { "exec", DebugExec, "Show diagnostic information relating to -exec, -execdir, -ok and -okdir" },
      58      { "opt",  DebugExpressionTree|DebugTreeOpt, "Show diagnostic information relating to optimisation" },
      59      { "rates", DebugSuccessRates, "Indicate how often each predicate succeeded" },
      60      { "search",DebugSearch, "Navigate the directory tree verbosely" },
      61      { "stat", DebugStat, "Trace calls to stat(2) and lstat(2)" },
      62      { "time", DebugTime, "Show diagnostic information relating to time-of-day and timestamp comparisons" },
      63      { "tree", DebugExpressionTree, "Display the expression tree" },
      64  
      65      { "all", DebugAll, "Set all of the debug flags (but help)" },
      66      { "help", DebugHelp, "Explain the various -D options" },
      67    };
      68  #define N_DEBUGASSOC (sizeof(debugassoc)/sizeof(debugassoc[0]))
      69  
      70  
      71  
      72  
      73  /* Add a primary of predicate type PRED_FUNC (described by ENTRY) to the predicate input list.
      74  
      75     Return a pointer to the predicate node just inserted.
      76  
      77     Fills in the following cells of the new predicate node:
      78  
      79     pred_func	    PRED_FUNC
      80     args(.str)	    NULL
      81     p_type	    PRIMARY_TYPE
      82     p_prec	    NO_PREC
      83  
      84     Other cells that need to be filled in are defaulted by
      85     get_new_pred_chk_op, which is used to ensure that the prior node is
      86     either not there at all (we are the very first node) or is an
      87     operator. */
      88  
      89  struct predicate *
      90  insert_primary_withpred (const struct parser_table *entry,
      91  			 PRED_FUNC pred_func,
      92  			 const char *arg)
      93  {
      94    struct predicate *new_pred;
      95  
      96    new_pred = get_new_pred_chk_op (entry, arg);
      97    new_pred->pred_func = pred_func;
      98    new_pred->p_name = entry->parser_name;
      99    new_pred->args.str = NULL;
     100    new_pred->p_type = PRIMARY_TYPE;
     101    new_pred->p_prec = NO_PREC;
     102    return new_pred;
     103  }
     104  
     105  /* Add a primary described by ENTRY to the predicate input list.
     106  
     107     Return a pointer to the predicate node just inserted.
     108  
     109     Fills in the following cells of the new predicate node:
     110  
     111     pred_func	    PRED_FUNC
     112     args(.str)	    NULL
     113     p_type	    PRIMARY_TYPE
     114     p_prec	    NO_PREC
     115  
     116     Other cells that need to be filled in are defaulted by
     117     get_new_pred_chk_op, which is used to ensure that the prior node is
     118     either not there at all (we are the very first node) or is an
     119     operator. */
     120  struct predicate *
     121  insert_primary (const struct parser_table *entry, const char *arg)
     122  {
     123    assert (entry->pred_func != NULL);
     124    return insert_primary_withpred (entry, entry->pred_func, arg);
     125  }
     126  
     127  struct predicate *
     128  insert_primary_noarg (const struct parser_table *entry)
     129  {
     130    return insert_primary (entry, NULL);
     131  }
     132  
     133  
     134  
     135  static void
     136  show_valid_debug_options (int full)
     137  {
     138    size_t i;
     139    fputs (_("Valid arguments for -D:\n"), stdout);
     140    if (full)
     141      {
     142        for (i=0; i<N_DEBUGASSOC; ++i)
     143  	{
     144  	  fprintf (stdout, "%-10s %s\n",
     145  		   debugassoc[i].name,
     146  		   debugassoc[i].docstring);
     147  	}
     148      }
     149    else
     150      {
     151        for (i=0; i<N_DEBUGASSOC; ++i)
     152  	{
     153  	  fprintf (stdout, "%s%s", (i>0 ? ", " : ""), debugassoc[i].name);
     154  	}
     155      }
     156  }
     157  
     158  void
     159  usage (int status)
     160  {
     161    if (status != EXIT_SUCCESS)
     162      {
     163        fprintf (stderr, _("Try '%s --help' for more information.\n"), program_name);
     164        exit (status);
     165      }
     166  
     167  #define HTL(t) fputs (t, stdout);
     168  
     169    fprintf (stdout, _("\
     170  Usage: %s [-H] [-L] [-P] [-Olevel] [-D debugopts] [path...] [expression]\n"),
     171             program_name);
     172  
     173    HTL (_("\n\
     174  Default path is the current directory; default expression is -print.\n\
     175  Expression may consist of: operators, options, tests, and actions.\n"));
     176    HTL (_("\n\
     177  Operators (decreasing precedence; -and is implicit where no others are given):\n\
     178        ( EXPR )   ! EXPR   -not EXPR   EXPR1 -a EXPR2   EXPR1 -and EXPR2\n\
     179        EXPR1 -o EXPR2   EXPR1 -or EXPR2   EXPR1 , EXPR2\n"));
     180    HTL (_("\n\
     181  Positional options (always true):\n\
     182        -daystart -follow -nowarn -regextype -warn\n"));
     183    HTL (_("\n\
     184  Normal options (always true, specified before other expressions):\n\
     185        -depth -files0-from FILE -maxdepth LEVELS -mindepth LEVELS\n\
     186         -mount -noleaf -xdev -ignore_readdir_race -noignore_readdir_race\n"));
     187    HTL (_("\n\
     188  Tests (N can be +N or -N or N):\n\
     189        -amin N -anewer FILE -atime N -cmin N -cnewer FILE -context CONTEXT\n\
     190        -ctime N -empty -false -fstype TYPE -gid N -group NAME -ilname PATTERN\n\
     191        -iname PATTERN -inum N -iwholename PATTERN -iregex PATTERN\n\
     192        -links N -lname PATTERN -mmin N -mtime N -name PATTERN -newer FILE\n\
     193        -nouser -nogroup -path PATTERN -perm [-/]MODE -regex PATTERN\n\
     194        -readable -writable -executable\n\
     195        -wholename PATTERN -size N[bcwkMG] -true -type [bcdpflsD] -uid N\n\
     196        -used N -user NAME -xtype [bcdpfls]\n"));
     197    HTL (_("\n\
     198  Actions:\n\
     199        -delete -print0 -printf FORMAT -fprintf FILE FORMAT -print \n\
     200        -fprint0 FILE -fprint FILE -ls -fls FILE -prune -quit\n\
     201        -exec COMMAND ; -exec COMMAND {} + -ok COMMAND ;\n\
     202        -execdir COMMAND ; -execdir COMMAND {} + -okdir COMMAND ;\n"));
     203  
     204    HTL (_("\n\
     205  Other common options:\n"));
     206    HTL (_("      --help                   display this help and exit\n"));
     207    HTL (_("      --version                output version information and exit\n\n"));
     208  
     209    show_valid_debug_options (0);
     210    HTL (_("\n\
     211  Use '-D help' for a description of the options, or see find(1)\n\
     212  \n"));
     213  
     214    explain_how_to_report_bugs (stdout, program_name);
     215    exit (status);
     216  }
     217  
     218  void
     219  set_stat_placeholders (struct stat *p)
     220  {
     221    (void) p; /* silence warning for systems lacking these fields. */
     222  #if HAVE_STRUCT_STAT_ST_BIRTHTIME
     223    p->st_birthtime = 0;
     224  #endif
     225  #if HAVE_STRUCT_STAT_ST_BIRTHTIMENSEC
     226    p->st_birthtimensec = 0;
     227  #endif
     228  #if HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC_TV_NSEC
     229    p->st_birthtimespec.tv_nsec = -1;
     230  #endif
     231  #if HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC_TV_SEC
     232    p->st_birthtimespec.tv_sec = 0;
     233  #else
     234    /* Avoid pointless compiler warning about unused parameters if none of these
     235       macros are set to nonzero values. */
     236    (void) p;
     237  #endif
     238  }
     239  
     240  
     241  /* Get the stat information for a file, if it is
     242   * not already known.  Returns 0 on success.
     243   */
     244  int
     245  get_statinfo (const char *pathname, const char *name, struct stat *p)
     246  {
     247    /* Set markers in fields so we have a good idea if the implementation
     248     * didn't bother to set them (e.g., NetBSD st_birthtimespec for MS-DOS
     249     * files)
     250     */
     251    if (!state.have_stat)
     252      {
     253        set_stat_placeholders (p);
     254        if (0 == (*options.xstat) (name, p))
     255  	{
     256  	  if (00000 == p->st_mode)
     257  	    {
     258  	      /* Savannah bug #16378. */
     259  	      error (0, 0, _("WARNING: file %s appears to have mode 0000"),
     260  		     quotearg_n_style (0, options.err_quoting_style, name));
     261  	      state.exit_status = EXIT_FAILURE;
     262  	    }
     263  	}
     264        else
     265  	{
     266  	  if (!options.ignore_readdir_race || (errno != ENOENT) )
     267  	    {
     268  	      nonfatal_target_file_error (errno, pathname);
     269  	    }
     270  	  return -1;
     271  	}
     272      }
     273    state.have_stat = true;
     274    state.have_type = true;
     275    state.type = p->st_mode;
     276  
     277    return 0;
     278  }
     279  
     280  /* Get the stat/type/inode information for a file, if it is not
     281   * already known.   Returns 0 on success (or if we did nothing).
     282   */
     283  static int
     284  get_info (const char *pathname,
     285  	  struct stat *p,
     286  	  struct predicate *pred_ptr)
     287  {
     288    bool todo = false;
     289  
     290    /* If we need the full stat info, or we need the type info but don't
     291     * already have it, stat the file now.
     292     */
     293    if (pred_ptr->need_stat && !state.have_stat)
     294      {
     295        todo = true;		/* need full stat info */
     296      }
     297    else if (pred_ptr->need_type && !state.have_type)
     298      {
     299        todo = true;		/* need to stat to get the type */
     300      }
     301    else if (pred_ptr->need_inum)
     302      {
     303        if (!p->st_ino)
     304  	{
     305  	  todo = true;		/* need to stat to get the inode number */
     306  	}
     307        else if ((!state.have_type) || S_ISDIR(p->st_mode))
     308  	{
     309  	  /* For now we decide not to trust struct dirent.d_ino for
     310  	   * directory entries that are subdirectories, in case this
     311  	   * subdirectory is a mount point.  We also need to call a
     312  	   * stat function if we don't have st_ino (i.e. it is zero).
     313  	   */
     314  	  todo = true;
     315  	}
     316      }
     317    if (todo)
     318      {
     319        if (get_statinfo (pathname, state.rel_pathname, p) != 0)
     320  	return -1;		/* failure. */
     321      }
     322    return 0;			/* success, or nothing to do. */
     323  }
     324  
     325  /* Determine if we can use O_NOFOLLOW.
     326   */
     327  #if defined O_NOFOLLOW
     328  bool
     329  check_nofollow (void)
     330  {
     331    struct utsname uts;
     332    float  release;
     333  
     334    if (0 == O_NOFOLLOW)
     335      {
     336        return false;
     337      }
     338  
     339    if (0 == uname (&uts))
     340      {
     341        /* POSIX requires that atof ignores "unrecognised suffixes"; we specifically
     342         * want that behaviour. */
     343        double (*conversion)(const char*) = atof;  /* avoid sc_prohibit_atoi_atof check. */
     344        release = conversion (uts.release);
     345  
     346        if (0 == strcmp ("Linux", uts.sysname))
     347  	{
     348  	  /* Linux kernels 2.1.126 and earlier ignore the O_NOFOLLOW flag. */
     349  	  return release >= 2.2f; /* close enough */
     350  	}
     351        else if (0 == strcmp ("FreeBSD", uts.sysname))
     352  	{
     353  	  /* FreeBSD 3.0-CURRENT and later support it */
     354  	  return release >= 3.1f;
     355  	}
     356      }
     357  
     358    /* Well, O_NOFOLLOW was defined, so we'll try to use it. */
     359    return true;
     360  }
     361  #endif
     362  
     363  
     364  static int
     365  exec_cb (void *context)
     366  {
     367    struct exec_val *execp = context;
     368    bc_do_exec (&execp->ctl, &execp->state);
     369    return 0;
     370  }
     371  
     372  static void
     373  do_exec (struct exec_val *execp)
     374  {
     375    run_in_dir (execp->wd_for_exec, exec_cb, execp);
     376    if (execp->wd_for_exec != initial_wd)
     377      {
     378        free_cwd (execp->wd_for_exec);
     379        free (execp->wd_for_exec);
     380        execp->wd_for_exec = NULL;
     381      }
     382  }
     383  
     384  
     385  /* Examine the predicate list for instances of -execdir or -okdir
     386   * which have been terminated with '+' (build argument list) rather
     387   * than ';' (singles only).  If there are any, run them (this will
     388   * have no effect if there are no arguments waiting).
     389   */
     390  static void
     391  do_complete_pending_execdirs (struct predicate *p)
     392  {
     393    if (NULL == p)
     394      return;
     395  
     396    assert (state.execdirs_outstanding);
     397  
     398    do_complete_pending_execdirs (p->pred_left);
     399  
     400    if (pred_is (p, pred_execdir) || pred_is(p, pred_okdir))
     401      {
     402        /* It's an exec-family predicate.  p->args.exec_val is valid. */
     403        if (p->args.exec_vec.multiple)
     404  	{
     405  	  struct exec_val *execp = &p->args.exec_vec;
     406  
     407  	  /* This one was terminated by '+' and so might have some
     408  	   * left... Run it if necessary.
     409  	   */
     410  	  if (execp->state.todo)
     411  	    {
     412  	      /* There are not-yet-executed arguments. */
     413  	      do_exec (execp);
     414  	    }
     415  	}
     416      }
     417  
     418    do_complete_pending_execdirs (p->pred_right);
     419  }
     420  
     421  void
     422  complete_pending_execdirs (void)
     423  {
     424    if (state.execdirs_outstanding)
     425      {
     426        do_complete_pending_execdirs (get_eval_tree());
     427        state.execdirs_outstanding = false;
     428      }
     429  }
     430  
     431  
     432  
     433  /* Examine the predicate list for instances of -exec which have been
     434   * terminated with '+' (build argument list) rather than ';' (singles
     435   * only).  If there are any, run them (this will have no effect if
     436   * there are no arguments waiting).
     437   */
     438  void
     439  complete_pending_execs (struct predicate *p)
     440  {
     441    if (NULL == p)
     442      return;
     443  
     444    complete_pending_execs (p->pred_left);
     445  
     446    /* It's an exec-family predicate then p->args.exec_val is valid
     447     * and we can check it.
     448     */
     449    /* XXX: what about pred_ok() ? */
     450    if (pred_is (p, pred_exec) && p->args.exec_vec.multiple)
     451      {
     452        struct exec_val *execp = &p->args.exec_vec;
     453  
     454        /* This one was terminated by '+' and so might have some
     455         * left... Run it if necessary.  Set state.exit_status if
     456         * there are any problems.
     457         */
     458        if (execp->state.todo)
     459  	{
     460  	  /* There are not-yet-executed arguments. */
     461  	  bc_do_exec (&execp->ctl, &execp->state);
     462  	}
     463      }
     464  
     465    complete_pending_execs (p->pred_right);
     466  }
     467  
     468  void
     469  record_initial_cwd (void)
     470  {
     471    initial_wd = xmalloc (sizeof (*initial_wd));
     472    if (0 != save_cwd (initial_wd))
     473      {
     474        die (EXIT_FAILURE, errno,
     475  	   _("Failed to save initial working directory%s%s"),
     476  	   (initial_wd->desc < 0 && initial_wd->name) ? ": " : "",
     477  	   (initial_wd->desc < 0 && initial_wd->name) ? initial_wd->name : "");
     478      }
     479  }
     480  
     481  static void
     482  cleanup_initial_cwd (void)
     483  {
     484    if (0 == restore_cwd (initial_wd))
     485      {
     486        free_cwd (initial_wd);
     487        free (initial_wd);
     488        initial_wd = NULL;
     489      }
     490    else
     491      {
     492        /* since we may already be in atexit, die with _exit(). */
     493        error (0, errno,
     494  	     _("Failed to restore initial working directory%s%s"),
     495  	     (initial_wd->desc < 0 && initial_wd->name) ? ": " : "",
     496  	     (initial_wd->desc < 0 && initial_wd->name) ? initial_wd->name : "");
     497        _exit (EXIT_FAILURE);
     498      }
     499  }
     500  
     501  
     502  static void
     503  traverse_tree (struct predicate *tree,
     504  			  void (*callback)(struct predicate*))
     505  {
     506    if (tree->pred_left)
     507      traverse_tree (tree->pred_left, callback);
     508  
     509    callback (tree);
     510  
     511    if (tree->pred_right)
     512      traverse_tree (tree->pred_right, callback);
     513  }
     514  
     515  /* After sharefile_destroy is called, our output file
     516   * pointers will be dangling (fclose will already have
     517   * been called on them).  NULL these out.
     518   */
     519  static void
     520  undangle_file_pointers (struct predicate *p)
     521  {
     522    if (pred_is (p, pred_fprint)
     523        || pred_is (p, pred_fprintf)
     524        || pred_is (p, pred_fls)
     525        || pred_is (p, pred_fprint0))
     526      {
     527        /* The file was already fclose()d by sharefile_destroy. */
     528        p->args.printf_vec.stream = NULL;
     529      }
     530  }
     531  
     532  /* Complete any outstanding commands.
     533   * Flush and close any open files.
     534   */
     535  void
     536  cleanup (void)
     537  {
     538    struct predicate *eval_tree = get_eval_tree ();
     539    if (eval_tree)
     540      {
     541        traverse_tree (eval_tree, complete_pending_execs);
     542        complete_pending_execdirs ();
     543      }
     544  
     545    /* Close output files and NULL out references to them. */
     546    sharefile_destroy (state.shared_files);
     547    if (eval_tree)
     548      traverse_tree (eval_tree, undangle_file_pointers);
     549  
     550    cleanup_initial_cwd ();
     551  
     552    if (fd_leak_check_is_enabled ())
     553      {
     554        complain_about_leaky_fds ();
     555        forget_non_cloexec_fds ();
     556      }
     557  
     558    if (fflush (stdout) == EOF)
     559      nonfatal_nontarget_file_error (errno, "standard output");
     560  }
     561  
     562  
     563  static int
     564  fallback_stat (const char *name, struct stat *p, int prev_rv)
     565  {
     566    /* Our original stat() call failed.  Perhaps we can't follow a
     567     * symbolic link.  If that might be the problem, lstat() the link.
     568     * Otherwise, admit defeat.
     569     */
     570    switch (errno)
     571      {
     572      case ENOENT:
     573      case ENOTDIR:
     574        if (options.debug_options & DebugStat)
     575  	fprintf(stderr, "fallback_stat(): stat(%s) failed; falling back on lstat()\n", name);
     576        return fstatat(state.cwd_dir_fd, name, p, AT_SYMLINK_NOFOLLOW);
     577  
     578      case EACCES:
     579      case EIO:
     580      case ELOOP:
     581      case ENAMETOOLONG:
     582  #ifdef EOVERFLOW
     583      case EOVERFLOW:	    /* EOVERFLOW is not #defined on UNICOS. */
     584  #endif
     585      default:
     586        return prev_rv;
     587      }
     588  }
     589  
     590  
     591  /* optionh_stat() implements the stat operation when the -H option is
     592   * in effect.
     593   *
     594   * If the item to be examined is a command-line argument, we follow
     595   * symbolic links.  If the stat() call fails on the command-line item,
     596   * we fall back on the properties of the symbolic link.
     597   *
     598   * If the item to be examined is not a command-line argument, we
     599   * examine the link itself.
     600   */
     601  int
     602  optionh_stat (const char *name, struct stat *p)
     603  {
     604    if (AT_FDCWD != state.cwd_dir_fd)
     605      assert (state.cwd_dir_fd >= 0);
     606    set_stat_placeholders (p);
     607    if (0 == state.curdepth)
     608      {
     609        /* This file is from the command line; deference the link (if it
     610         * is a link).
     611         */
     612        int rv;
     613        rv = fstatat (state.cwd_dir_fd, name, p, 0);
     614        if (0 == rv)
     615  	return 0;		/* success */
     616        else
     617  	return fallback_stat (name, p, rv);
     618      }
     619    else
     620      {
     621        /* Not a file on the command line; do not dereference the link.
     622         */
     623        return fstatat (state.cwd_dir_fd, name, p, AT_SYMLINK_NOFOLLOW);
     624      }
     625  }
     626  
     627  /* optionl_stat() implements the stat operation when the -L option is
     628   * in effect.  That option makes us examine the thing the symbolic
     629   * link points to, not the symbolic link itself.
     630   */
     631  int
     632  optionl_stat(const char *name, struct stat *p)
     633  {
     634    int rv;
     635    if (AT_FDCWD != state.cwd_dir_fd)
     636      assert (state.cwd_dir_fd >= 0);
     637  
     638    set_stat_placeholders (p);
     639    rv = fstatat (state.cwd_dir_fd, name, p, 0);
     640    if (0 == rv)
     641      return 0;			/* normal case. */
     642    else
     643      return fallback_stat (name, p, rv);
     644  }
     645  
     646  /* optionp_stat() implements the stat operation when the -P option is
     647   * in effect (this is also the default).  That option makes us examine
     648   * the symbolic link itself, not the thing it points to.
     649   */
     650  int
     651  optionp_stat (const char *name, struct stat *p)
     652  {
     653    assert ((state.cwd_dir_fd >= 0) || (state.cwd_dir_fd==AT_FDCWD));
     654    set_stat_placeholders (p);
     655    return fstatat (state.cwd_dir_fd, name, p, AT_SYMLINK_NOFOLLOW);
     656  }
     657  
     658  
     659  static uintmax_t stat_count = 0u;
     660  
     661  int
     662  debug_stat (const char *file, struct stat *bufp)
     663  {
     664    ++stat_count;
     665    fprintf (stderr, "debug_stat (%s)\n", file);
     666  
     667    switch (options.symlink_handling)
     668      {
     669      case SYMLINK_ALWAYS_DEREF:
     670        return optionl_stat (file, bufp);
     671      case SYMLINK_DEREF_ARGSONLY:
     672        return optionh_stat (file, bufp);
     673      case SYMLINK_NEVER_DEREF:
     674        return optionp_stat (file, bufp);
     675      }
     676    /*NOTREACHED*/
     677    assert (0);
     678    return -1;
     679  }
     680  
     681  
     682  bool
     683  following_links(void)
     684  {
     685    switch (options.symlink_handling)
     686      {
     687      case SYMLINK_ALWAYS_DEREF:
     688        return true;
     689      case SYMLINK_DEREF_ARGSONLY:
     690        return (state.curdepth == 0);
     691      case SYMLINK_NEVER_DEREF:
     692      default:
     693        return false;
     694      }
     695  }
     696  
     697  
     698  /* Take a "mode" indicator and fill in the files of 'state'.
     699   */
     700  bool
     701  digest_mode (mode_t *mode,
     702  	     const char *pathname,
     703  	     const char *name,
     704  	     struct stat *pstat,
     705  	     bool leaf)
     706  {
     707    /* If we know the type of the directory entry, and it is not a
     708     * symbolic link, we may be able to avoid a stat() or lstat() call.
     709     */
     710    if (*mode)
     711      {
     712        if (S_ISLNK(*mode) && following_links())
     713  	{
     714  	  /* mode is wrong because we should have followed the symlink. */
     715  	  if (get_statinfo (pathname, name, pstat) != 0)
     716  	    return false;
     717  	  *mode = state.type = pstat->st_mode;
     718  	  state.have_type = true;
     719  	}
     720        else
     721  	{
     722  	  state.have_type = true;
     723  	  pstat->st_mode = state.type = *mode;
     724  	}
     725      }
     726    else
     727      {
     728        /* Mode is not yet known; may have to stat the file unless we
     729         * can deduce that it is not a directory (which is all we need to
     730         * know at this stage)
     731         */
     732        if (leaf)
     733  	{
     734  	  state.have_stat = false;
     735  	  state.have_type = false;
     736  	  state.type = 0;
     737  	}
     738        else
     739  	{
     740  	  if (get_statinfo (pathname, name, pstat) != 0)
     741  	    return false;
     742  
     743  	  /* If -L is in effect and we are dealing with a symlink,
     744  	   * st_mode is the mode of the pointed-to file, while mode is
     745  	   * the mode of the directory entry (S_IFLNK).  Hence now
     746  	   * that we have the stat information, override "mode".
     747  	   */
     748  	  state.type = *mode = pstat->st_mode;
     749  	  state.have_type = true;
     750  	}
     751      }
     752  
     753    /* success. */
     754    return true;
     755  }
     756  
     757  
     758  /* Return true if there are no predicates with no_default_print in
     759     predicate list PRED, false if there are any.
     760     Returns true if default print should be performed */
     761  
     762  bool
     763  default_prints (struct predicate *pred)
     764  {
     765    while (pred != NULL)
     766      {
     767        if (pred->no_default_print)
     768  	return (false);
     769        pred = pred->pred_next;
     770      }
     771    return (true);
     772  }
     773  
     774  bool
     775  looks_like_expression (const char *arg, bool leading)
     776  {
     777    switch (arg[0])
     778      {
     779      case '-':
     780        if (arg[1])		/* "-foo" is an expression.  */
     781  	return true;
     782        else
     783  	return false;		/* Just "-" is a filename. */
     784        break;
     785  
     786      case ')':
     787      case ',':
     788        if (arg[1])
     789  	return false;		/* )x and ,z are not expressions */
     790        else
     791  	return !leading;	/* A leading ) or , is not either */
     792  
     793        /* ( and ! are part of an expression, but (2 and !foo are
     794         * filenames.
     795         */
     796      case '!':
     797      case '(':
     798        if (arg[1])
     799  	return false;
     800        else
     801  	return true;
     802  
     803      default:
     804        return false;
     805      }
     806  }
     807  
     808  static void
     809  process_debug_options (char *arg)
     810  {
     811    const char *p;
     812    char *token_context = NULL;
     813    const char delimiters[] = ",";
     814    bool empty = true;
     815    size_t i;
     816  
     817    p = strtok_r (arg, delimiters, &token_context);
     818    while (p)
     819      {
     820        empty = false;
     821  
     822        for (i=0; i<N_DEBUGASSOC; ++i)
     823  	{
     824  	  if (0 == strcmp (debugassoc[i].name, p))
     825  	    {
     826  	      options.debug_options |= debugassoc[i].val;
     827  	      break;
     828  	    }
     829  	}
     830        if (i >= N_DEBUGASSOC)
     831  	{
     832  	  error (0, 0, _("Ignoring unrecognised debug flag %s"),
     833  		 quotearg_n_style (0, options.err_quoting_style, arg));
     834  	}
     835        p = strtok_r (NULL, delimiters, &token_context);
     836      }
     837    if (empty)
     838      {
     839        error (0, 0, _("Empty argument to the -D option."));
     840        usage (EXIT_FAILURE);
     841      }
     842    else if (options.debug_options & DebugHelp)
     843      {
     844        show_valid_debug_options (1);
     845        exit (EXIT_SUCCESS);
     846      }
     847  }
     848  
     849  
     850  static void
     851  process_optimisation_option (const char *arg)
     852  {
     853    if (0 == arg[0])
     854      {
     855        die (EXIT_FAILURE, 0,
     856  	   _("The -O option must be immediately followed by a decimal integer"));
     857      }
     858    else
     859      {
     860        unsigned long opt_level;
     861        char *end;
     862  
     863        if (!isdigit ( (unsigned char) arg[0] ))
     864  	{
     865  	  die (EXIT_FAILURE, 0,
     866  	       _("Please specify a decimal number immediately after -O"));
     867  	}
     868        else
     869  	{
     870  	  int prev_errno = errno;
     871  	  errno  = 0;
     872  
     873  	  opt_level = strtoul (arg, &end, 10);
     874  	  if ( (0==opt_level) && (end==arg) )
     875  	    {
     876  	      die (EXIT_FAILURE, 0,
     877  		   _("Please specify a decimal number immediately after -O"));
     878  	    }
     879  	  else if (*end)
     880  	    {
     881  	      /* unwanted trailing characters. */
     882  	      die (EXIT_FAILURE, 0, _("Invalid optimisation level %s"), arg);
     883  	    }
     884  	  else if ( (ULONG_MAX==opt_level) && errno)
     885  	    {
     886  	      die (EXIT_FAILURE, errno,
     887  		   _("Invalid optimisation level %s"), arg);
     888  	    }
     889  	  else if (opt_level > USHRT_MAX)
     890  	    {
     891  	      /* tricky to test, as on some platforms USHORT_MAX and ULONG_MAX
     892  	       * can have the same value, though this is unusual.
     893  	       */
     894  	      die (EXIT_FAILURE, 0,
     895  		   _("Optimisation level %lu is too high.  "
     896  		     "If you want to find files very quickly, "
     897  		     "consider using GNU locate."),
     898  		   opt_level);
     899  	    }
     900  	  else
     901  	    {
     902  	      options.optimisation_level = opt_level;
     903  	      errno = prev_errno;
     904  	    }
     905  	}
     906      }
     907  }
     908  
     909  int
     910  process_leading_options (int argc, char *argv[])
     911  {
     912    int i, end_of_leading_options;
     913  
     914    for (i=1; (end_of_leading_options = i) < argc; ++i)
     915      {
     916        if (0 == strcmp ("-H", argv[i]))
     917  	{
     918  	  /* Meaning: dereference symbolic links on command line, but nowhere else. */
     919  	  set_follow_state (SYMLINK_DEREF_ARGSONLY);
     920  	}
     921        else if (0 == strcmp ("-L", argv[i]))
     922  	{
     923  	  /* Meaning: dereference all symbolic links. */
     924  	  set_follow_state (SYMLINK_ALWAYS_DEREF);
     925  	}
     926        else if (0 == strcmp ("-P", argv[i]))
     927  	{
     928  	  /* Meaning: never dereference symbolic links (default). */
     929  	  set_follow_state (SYMLINK_NEVER_DEREF);
     930  	}
     931        else if (0 == strcmp ("--", argv[i]))
     932  	{
     933  	  /* -- signifies the end of options. */
     934  	  end_of_leading_options = i+1;	/* Next time start with the next option */
     935  	  break;
     936  	}
     937        else if (0 == strcmp ("-D", argv[i]))
     938  	{
     939  	  if (argc <= i+1)
     940  	    {
     941  	      error (0, 0, _("Missing argument after the -D option."));
     942  	      usage (EXIT_FAILURE);
     943  	    }
     944  	  process_debug_options (argv[i+1]);
     945  	  ++i;			/* skip the argument too. */
     946  	}
     947        else if (0 == strncmp ("-O", argv[i], 2))
     948  	{
     949  	  process_optimisation_option (argv[i]+2);
     950  	}
     951        else
     952  	{
     953  	  /* Hmm, must be one of
     954  	   * (a) A path name
     955  	   * (b) A predicate
     956  	   */
     957  	  end_of_leading_options = i; /* Next time start with this option */
     958  	  break;
     959  	}
     960      }
     961    return end_of_leading_options;
     962  }
     963  
     964  static struct timespec
     965  now(void)
     966  {
     967    struct timespec retval;
     968    struct timeval tv;
     969    time_t t;
     970  
     971    if (0 == gettimeofday (&tv, NULL))
     972      {
     973        retval.tv_sec  = tv.tv_sec;
     974        retval.tv_nsec = tv.tv_usec * 1000; /* convert unit from microseconds to nanoseconds */
     975        return retval;
     976      }
     977    t = time (NULL);
     978    assert (t != (time_t)-1);
     979    retval.tv_sec = t;
     980    retval.tv_nsec = 0;
     981    return retval;
     982  }
     983  
     984  void
     985  set_option_defaults (struct options *p)
     986  {
     987    if (getenv ("POSIXLY_CORRECT"))
     988      p->posixly_correct = true;
     989    else
     990      p->posixly_correct = false;
     991  
     992    /* We call check_nofollow() before setlocale() because the numbers
     993     * for which we check (in the results of uname) definitiely have "."
     994     * as the decimal point indicator even under locales for which that
     995     * is not normally true.   Hence atof would do the wrong thing
     996     * if we call it after setlocale().
     997     */
     998  #ifdef O_NOFOLLOW
     999    p->open_nofollow_available = check_nofollow ();
    1000  #else
    1001    p->open_nofollow_available = false;
    1002  #endif
    1003  
    1004    p->regex_options = RE_SYNTAX_EMACS;
    1005  
    1006    if (isatty (0))
    1007      {
    1008        p->warnings = true;
    1009        p->literal_control_chars = false;
    1010      }
    1011    else
    1012      {
    1013        p->warnings = false;
    1014        p->literal_control_chars = false; /* may change */
    1015      }
    1016    if (p->posixly_correct)
    1017      {
    1018        p->warnings = false;
    1019      }
    1020  
    1021    p->do_dir_first = true;
    1022    p->explicit_depth = false;
    1023    p->maxdepth = p->mindepth = -1;
    1024  
    1025    p->start_time = now ();
    1026    p->cur_day_start.tv_sec = p->start_time.tv_sec - DAYSECS;
    1027    p->cur_day_start.tv_nsec = p->start_time.tv_nsec;
    1028  
    1029    p->full_days = false;
    1030    p->stay_on_filesystem = false;
    1031    p->ignore_readdir_race = false;
    1032  
    1033    if (p->posixly_correct)
    1034      p->output_block_size = 512;
    1035    else
    1036      p->output_block_size = 1024;
    1037  
    1038    p->debug_options = 0uL;
    1039    p->optimisation_level = 2;
    1040  
    1041    if (getenv ("FIND_BLOCK_SIZE"))
    1042      {
    1043        die (EXIT_FAILURE, 0,
    1044  	   _("The environment variable FIND_BLOCK_SIZE is not supported, "
    1045  	     "the only thing that affects the block size is the "
    1046  	     "POSIXLY_CORRECT environment variable"));
    1047      }
    1048  
    1049  #if LEAF_OPTIMISATION
    1050    /* The leaf optimisation is enabled. */
    1051    p->no_leaf_check = false;
    1052  #else
    1053    /* The leaf optimisation is disabled. */
    1054    p->no_leaf_check = true;
    1055  #endif
    1056  
    1057    set_follow_state (SYMLINK_NEVER_DEREF); /* The default is equivalent to -P. */
    1058  
    1059    p->err_quoting_style = locale_quoting_style;
    1060  
    1061    p->files0_from = NULL;
    1062    p->ok_prompt_stdin = false;
    1063  }
    1064  
    1065  
    1066  /* apply_predicate
    1067   *
    1068   */
    1069  bool
    1070  apply_predicate(const char *pathname, struct stat *stat_buf, struct predicate *p)
    1071  {
    1072    ++p->perf.visits;
    1073  
    1074    if (p->need_stat || p->need_type || p->need_inum)
    1075      {
    1076        /* We may need a stat here. */
    1077        if (get_info(pathname, stat_buf, p) != 0)
    1078  	    return false;
    1079      }
    1080    if ((p->pred_func)(pathname, stat_buf, p))
    1081      {
    1082        ++(p->perf.successes);
    1083        return true;
    1084      }
    1085    else
    1086      {
    1087        return false;
    1088      }
    1089  }
    1090  
    1091  
    1092  /* is_exec_in_local_dir
    1093   *
    1094   */
    1095  bool
    1096  is_exec_in_local_dir (const PRED_FUNC pred_func)
    1097  {
    1098    return pred_execdir == pred_func || pred_okdir == pred_func;
    1099  }
    1100  
    1101  /* safely_quote_err_filename
    1102   *
    1103   */
    1104  const char *
    1105  safely_quote_err_filename (int n, char const *arg)
    1106  {
    1107    return quotearg_n_style (n, options.err_quoting_style, arg);
    1108  }
    1109  
    1110  /* report_file_err
    1111   */
    1112  static void
    1113  report_file_err(int exitval, int errno_value,
    1114  		bool is_target_file, const char *name)
    1115  {
    1116    /* It is important that the errno value is passed in as a function
    1117     * argument before we call safely_quote_err_filename(), because otherwise
    1118     * we might find that safely_quote_err_filename() changes errno.
    1119     */
    1120    if (!is_target_file || !state.already_issued_stat_error_msg)
    1121      {
    1122        error (exitval, errno_value, "%s", safely_quote_err_filename (0, name));
    1123        state.exit_status = EXIT_FAILURE;
    1124      }
    1125    if (is_target_file)
    1126      {
    1127        state.already_issued_stat_error_msg = true;
    1128      }
    1129  }
    1130  
    1131  /* nonfatal_target_file_error
    1132   */
    1133  void
    1134  nonfatal_target_file_error (int errno_value, const char *name)
    1135  {
    1136    report_file_err (0, errno_value, true, name);
    1137  }
    1138  
    1139  /* fatal_target_file_error
    1140   *
    1141   * Report an error on a target file (i.e. a file we are searching).
    1142   * Such errors are only reported once per searched file.
    1143   *
    1144   */
    1145  void
    1146  fatal_target_file_error(int errno_value, const char *name)
    1147  {
    1148    report_file_err (1, errno_value, true, name);
    1149    /*NOTREACHED*/
    1150    abort ();
    1151  }
    1152  
    1153  /* nonfatal_nontarget_file_error
    1154   *
    1155   */
    1156  void
    1157  nonfatal_nontarget_file_error (int errno_value, const char *name)
    1158  {
    1159    report_file_err (0, errno_value, false, name);
    1160  }
    1161  
    1162  /* fatal_nontarget_file_error
    1163   *
    1164   */
    1165  void
    1166  fatal_nontarget_file_error(int errno_value, const char *name)
    1167  {
    1168    /* We're going to exit fatally, so make sure we always issue the error
    1169     * message, even if it will be duplicate.   Motivation: otherwise it may
    1170     * not be clear what went wrong.
    1171     */
    1172    state.already_issued_stat_error_msg = false;
    1173    report_file_err (1, errno_value, false, name);
    1174    /*NOTREACHED*/
    1175    abort ();
    1176  }