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