Eliminated a few compiler warnings
[findutils.git] / find / util.c
blobc84dae85b3691067e04f910aab20020d5d19fb43
1 /* util.c -- functions for initializing new tree elements, and other things.
2 Copyright (C) 1990, 91, 92, 93, 94, 2000, 2003, 2004, 2005 Free Software Foundation, Inc.
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 2, or (at your option)
7 any later version.
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.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
17 USA.
20 #include "defs.h"
22 #ifdef HAVE_FCNTL_H
23 #include <fcntl.h>
24 #else
25 #include <sys/file.h>
26 #endif
27 #ifdef HAVE_SYS_UTSNAME_H
28 #include <sys/utsname.h>
29 #endif
31 #include "xalloc.h"
32 #include "quotearg.h"
35 #if ENABLE_NLS
36 # include <libintl.h>
37 # define _(Text) gettext (Text)
38 #else
39 # define _(Text) Text
40 #endif
41 #ifdef gettext_noop
42 # define N_(String) gettext_noop (String)
43 #else
44 /* See locate.c for explanation as to why not use (String) */
45 # define N_(String) String
46 #endif
48 #include <ctype.h>
49 #include <string.h>
50 #include <limits.h>
51 #include <assert.h>
54 struct debug_option_assoc
56 char *name;
57 int val;
58 char *docstring;
60 static struct debug_option_assoc debugassoc[] =
62 { "help", DebugHelp, "Explain the various -D options" },
63 { "tree", DebugExpressionTree, "Display the expression tree" },
64 { "search",DebugSearch, "Navigate the directory tree verbosely" },
65 { "stat", DebugStat, "Trace calls to stat(2) and lstat(2)" },
66 { "opt", DebugExpressionTree|DebugTreeOpt, "Show diagnostic information relating to optimisation" }
68 #define N_DEBUGASSOC (sizeof(debugassoc)/sizeof(debugassoc[0]))
73 /* Add a primary of predicate type PRED_FUNC (described by ENTRY) to the predicate input list.
75 Return a pointer to the predicate node just inserted.
77 Fills in the following cells of the new predicate node:
79 pred_func PRED_FUNC
80 args(.str) NULL
81 p_type PRIMARY_TYPE
82 p_prec NO_PREC
84 Other cells that need to be filled in are defaulted by
85 get_new_pred_chk_op, which is used to insure that the prior node is
86 either not there at all (we are the very first node) or is an
87 operator. */
89 struct predicate *
90 insert_primary_withpred (const struct parser_table *entry, PRED_FUNC pred_func)
92 struct predicate *new_pred;
94 new_pred = get_new_pred_chk_op (entry);
95 new_pred->pred_func = pred_func;
96 new_pred->p_name = entry->parser_name;
97 new_pred->args.str = NULL;
98 new_pred->p_type = PRIMARY_TYPE;
99 new_pred->p_prec = NO_PREC;
100 return new_pred;
103 /* Add a primary described by ENTRY to the predicate input list.
105 Return a pointer to the predicate node just inserted.
107 Fills in the following cells of the new predicate node:
109 pred_func PRED_FUNC
110 args(.str) NULL
111 p_type PRIMARY_TYPE
112 p_prec NO_PREC
114 Other cells that need to be filled in are defaulted by
115 get_new_pred_chk_op, which is used to insure that the prior node is
116 either not there at all (we are the very first node) or is an
117 operator. */
118 struct predicate *
119 insert_primary (const struct parser_table *entry)
121 assert(entry->pred_func != NULL);
122 return insert_primary_withpred(entry, entry->pred_func);
127 static void
128 show_valid_debug_options(FILE *fp, int full)
130 int i;
131 if (full)
133 fprintf(fp, "Valid arguments for -D:\n");
134 for (i=0; i<N_DEBUGASSOC; ++i)
136 fprintf(fp, "%-10s %s\n",
137 debugassoc[i].name,
138 debugassoc[i].docstring);
141 else
143 for (i=0; i<N_DEBUGASSOC; ++i)
145 fprintf(fp, "%s%s", (i>0 ? "|" : ""), debugassoc[i].name);
150 void
151 usage (FILE *fp, int status, char *msg)
153 if (msg)
154 fprintf (fp, "%s: %s\n", program_name, msg);
156 fprintf (fp, _("Usage: %s [-H] [-L] [-P] [-Olevel] [-D "), program_name);
157 show_valid_debug_options(fp, 0);
158 fprintf (fp, _("] [path...] [expression]\n"));
159 if (0 != status)
160 exit (status);
164 /* Get the stat information for a file, if it is
165 * not already known.
168 get_statinfo (const char *pathname, const char *name, struct stat *p)
170 if (!state.have_stat && (*options.xstat) (name, p) != 0)
172 if (!options.ignore_readdir_race || (errno != ENOENT) )
174 error (0, errno, "%s", pathname);
175 state.exit_status = 1;
177 return -1;
179 state.have_stat = true;
180 state.have_type = true;
181 state.type = p->st_mode;
182 return 0;
186 /* Get the stat/type information for a file, if it is
187 * not already known.
190 get_info (const char *pathname,
191 const char *name,
192 struct stat *p,
193 struct predicate *pred_ptr)
195 /* If we need the full stat info, or we need the type info but don't
196 * already have it, stat the file now.
198 (void) name;
199 if (pred_ptr->need_stat)
201 return get_statinfo(pathname, state.rel_pathname, p);
203 if ((pred_ptr->need_type && (0 == state.have_type)))
205 return get_statinfo(pathname, state.rel_pathname, p);
207 return 0;
210 /* Determine if we can use O_NOFOLLOW.
212 #if defined(O_NOFOLLOW)
213 boolean
214 check_nofollow(void)
216 struct utsname uts;
217 float release;
219 if (0 == uname(&uts))
221 /* POSIX requires that atof() ignore "unrecognised suffixes". */
222 release = atof(uts.release);
224 if (0 == strcmp("Linux", uts.sysname))
226 /* Linux kernels 2.1.126 and earlier ignore the O_NOFOLLOW flag. */
227 return release >= 2.2; /* close enough */
229 else if (0 == strcmp("FreeBSD", uts.sysname))
231 /* FreeBSD 3.0-CURRENT and later support it */
232 return release >= 3.1;
236 /* Well, O_NOFOLLOW was defined, so we'll try to use it. */
237 return true;
239 #endif
243 /* Examine the predicate list for instances of -execdir or -okdir
244 * which have been terminated with '+' (build argument list) rather
245 * than ';' (singles only). If there are any, run them (this will
246 * have no effect if there are no arguments waiting).
248 void
249 complete_pending_execdirs(struct predicate *p)
251 if (NULL == p)
252 return;
254 complete_pending_execdirs(p->pred_left);
256 if (p->pred_func == pred_execdir || p->pred_func == pred_okdir)
258 /* It's an exec-family predicate. p->args.exec_val is valid. */
259 if (p->args.exec_vec.multiple)
261 struct exec_val *execp = &p->args.exec_vec;
263 /* This one was terminated by '+' and so might have some
264 * left... Run it if necessary.
266 if (execp->state.todo)
268 /* There are not-yet-executed arguments. */
269 launch (&execp->ctl, &execp->state);
274 complete_pending_execdirs(p->pred_right);
278 /* Examine the predicate list for instances of -exec which have been
279 * terminated with '+' (build argument list) rather than ';' (singles
280 * only). If there are any, run them (this will have no effect if
281 * there are no arguments waiting).
283 void
284 complete_pending_execs(struct predicate *p)
286 if (NULL == p)
287 return;
289 complete_pending_execs(p->pred_left);
291 /* It's an exec-family predicate then p->args.exec_val is valid
292 * and we can check it.
294 if (p->pred_func == pred_exec && p->args.exec_vec.multiple)
296 struct exec_val *execp = &p->args.exec_vec;
298 /* This one was terminated by '+' and so might have some
299 * left... Run it if necessary. Set state.exit_status if
300 * there are any problems.
302 if (execp->state.todo)
304 /* There are not-yet-executed arguments. */
305 launch (&execp->ctl, &execp->state);
309 complete_pending_execs(p->pred_right);
313 /* Complete any outstanding commands.
315 void
316 cleanup(void)
318 struct predicate *eval_tree = get_eval_tree();
319 if (eval_tree)
321 complete_pending_execs(eval_tree);
322 complete_pending_execdirs(eval_tree);
327 static int
328 fallback_stat(const char *name, struct stat *p, int prev_rv)
330 /* Our original stat() call failed. Perhaps we can't follow a
331 * symbolic link. If that might be the problem, lstat() the link.
332 * Otherwise, admit defeat.
334 switch (errno)
336 case ENOENT:
337 case ENOTDIR:
338 if (options.debug_options & DebugStat)
339 fprintf(stderr, "fallback_stat(): stat(%s) failed; falling back on lstat()\n", name);
340 return lstat(name, p);
342 case EACCES:
343 case EIO:
344 case ELOOP:
345 case ENAMETOOLONG:
346 #ifdef EOVERFLOW
347 case EOVERFLOW: /* EOVERFLOW is not #defined on UNICOS. */
348 #endif
349 default:
350 return prev_rv;
355 /* optionh_stat() implements the stat operation when the -H option is
356 * in effect.
358 * If the item to be examined is a command-line argument, we follow
359 * symbolic links. If the stat() call fails on the command-line item,
360 * we fall back on the properties of the symbolic link.
362 * If the item to be examined is not a command-line argument, we
363 * examine the link itself.
365 int
366 optionh_stat(const char *name, struct stat *p)
368 if (0 == state.curdepth)
370 /* This file is from the command line; deference the link (if it
371 * is a link).
373 int rv = stat(name, p);
374 if (0 == rv)
375 return 0; /* success */
376 else
377 return fallback_stat(name, p, rv);
379 else
381 /* Not a file on the command line; do not dereference the link.
383 return lstat(name, p);
387 /* optionl_stat() implements the stat operation when the -L option is
388 * in effect. That option makes us examine the thing the symbolic
389 * link points to, not the symbolic link itself.
391 int
392 optionl_stat(const char *name, struct stat *p)
394 int rv = stat(name, p);
395 if (0 == rv)
396 return 0; /* normal case. */
397 else
398 return fallback_stat(name, p, rv);
401 /* optionp_stat() implements the stat operation when the -P option is
402 * in effect (this is also the default). That option makes us examine
403 * the symbolic link itself, not the thing it points to.
405 int
406 optionp_stat(const char *name, struct stat *p)
408 return lstat(name, p);
412 static uintmax_t stat_count = 0u;
415 debug_stat (const char *file, struct stat *bufp)
417 ++stat_count;
418 fprintf (stderr, "debug_stat (%s)\n", file);
419 switch (options.symlink_handling)
421 case SYMLINK_ALWAYS_DEREF:
422 return optionl_stat(file, bufp);
423 case SYMLINK_DEREF_ARGSONLY:
424 return optionh_stat(file, bufp);
425 case SYMLINK_NEVER_DEREF:
426 return optionp_stat(file, bufp);
428 /*NOTREACHED*/
429 assert(false);
430 return -1;
435 following_links(void)
437 switch (options.symlink_handling)
439 case SYMLINK_ALWAYS_DEREF:
440 return 1;
441 case SYMLINK_DEREF_ARGSONLY:
442 return (state.curdepth == 0);
443 case SYMLINK_NEVER_DEREF:
444 default:
445 return 0;
450 /* Take a "mode" indicator and fill in the files of 'state'.
453 digest_mode(mode_t mode,
454 const char *pathname,
455 const char *name,
456 struct stat *pstat,
457 boolean leaf)
459 /* If we know the type of the directory entry, and it is not a
460 * symbolic link, we may be able to avoid a stat() or lstat() call.
462 if (mode)
464 if (S_ISLNK(mode) && following_links())
466 /* mode is wrong because we should have followed the symlink. */
467 if (get_statinfo(pathname, name, pstat) != 0)
468 return 0;
469 mode = state.type = pstat->st_mode;
470 state.have_type = true;
472 else
474 state.have_type = true;
475 pstat->st_mode = state.type = mode;
478 else
480 /* Mode is not yet known; may have to stat the file unless we
481 * can deduce that it is not a directory (which is all we need to
482 * know at this stage)
484 if (leaf)
486 state.have_stat = false;
487 state.have_type = false;;
488 state.type = 0;
490 else
492 if (get_statinfo(pathname, name, pstat) != 0)
493 return 0;
495 /* If -L is in effect and we are dealing with a symlink,
496 * st_mode is the mode of the pointed-to file, while mode is
497 * the mode of the directory entry (S_IFLNK). Hence now
498 * that we have the stat information, override "mode".
500 state.type = pstat->st_mode;
501 state.have_type = true;
505 /* success. */
506 return 1;
510 /* Return true if there are no predicates with no_default_print in
511 predicate list PRED, false if there are any.
512 Returns true if default print should be performed */
514 boolean
515 default_prints (struct predicate *pred)
517 while (pred != NULL)
519 if (pred->no_default_print)
520 return (false);
521 pred = pred->pred_next;
523 return (true);
526 boolean
527 looks_like_expression(const char *arg, boolean leading)
529 switch (arg[0])
531 case '-':
532 if (arg[1]) /* "-foo" is an expression. */
533 return true;
534 else
535 return false; /* Just "-" is a filename. */
536 break;
538 case ')':
539 case ',':
540 if (arg[1])
541 return false; /* )x and ,z are not expressions */
542 else
543 return !leading; /* A leading ) or , is not either */
545 /* ( and ! are part of an expression, but (2 and !foo are
546 * filenames.
548 case '!':
549 case '(':
550 if (arg[1])
551 return false;
552 else
553 return true;
555 default:
556 return false;
560 static void
561 process_debug_options(char *arg)
563 const char *p;
564 char *token_context = NULL;
565 const char delimiters[] = ",";
566 boolean empty = true;
567 size_t i;
569 p = strtok_r(arg, delimiters, &token_context);
570 while (p)
572 empty = false;
574 for (i=0; i<N_DEBUGASSOC; ++i)
576 if (0 == strcmp(debugassoc[i].name, p))
578 options.debug_options |= debugassoc[i].val;
579 break;
582 if (i >= N_DEBUGASSOC)
584 error(0, 0, _("Ignoring unrecognised debug flag %s"),
585 quotearg_n_style(0, locale_quoting_style, arg));
587 p = strtok_r(NULL, delimiters, &token_context);
589 if (empty)
591 error(1, 0, _("Empty argument to the -D option."));
593 else if (options.debug_options & DebugHelp)
595 show_valid_debug_options(stdout, 1);
596 exit(0);
600 static void
601 process_optimisation_option(const char *arg)
603 if (0 == arg[0])
605 error(1, 0, _("The -O option must be immediately followed by a decimal integer"));
607 else
609 unsigned long opt_level;
610 char *end;
612 if (!isdigit( (unsigned char) arg[0] ))
614 error(1, 0, _("Please specify a decimal number immediately after -O"));
616 else
618 int prev_errno = errno;
619 errno = 0;
621 opt_level = strtoul(arg, &end, 10);
622 if ( (0==opt_level) && (end==arg) )
624 error(1, 0, _("Please specify a decimal number immediately after -O"));
626 else if (*end)
628 /* unwanted trailing characters. */
629 error(1, 0, _("Invalid optimisation level %s"), arg);
631 else if ( (ULONG_MAX==opt_level) && errno)
633 error(1, errno, _("Invalid optimisation level %s"), arg);
635 else if (opt_level > USHRT_MAX)
637 /* tricky to test, as on some platforms USHORT_MAX and ULONG_MAX
638 * can have the same value, though this is unusual.
640 error(1, 0, _("Optimisation level %lu is too high. "
641 "If you want to find files very quickly, "
642 "consider using GNU locate."),
643 opt_level);
645 else
647 options.optimisation_level = opt_level;
648 errno = prev_errno;
655 process_leading_options(int argc, char *argv[])
657 int i, end_of_leading_options;
659 for (i=1; (end_of_leading_options = i) < argc; ++i)
661 if (0 == strcmp("-H", argv[i]))
663 /* Meaning: dereference symbolic links on command line, but nowhere else. */
664 set_follow_state(SYMLINK_DEREF_ARGSONLY);
666 else if (0 == strcmp("-L", argv[i]))
668 /* Meaning: dereference all symbolic links. */
669 set_follow_state(SYMLINK_ALWAYS_DEREF);
671 else if (0 == strcmp("-P", argv[i]))
673 /* Meaning: never dereference symbolic links (default). */
674 set_follow_state(SYMLINK_NEVER_DEREF);
676 else if (0 == strcmp("--", argv[i]))
678 /* -- signifies the end of options. */
679 end_of_leading_options = i+1; /* Next time start with the next option */
680 break;
682 else if (0 == strcmp("-D", argv[i]))
684 process_debug_options(argv[i+1]);
685 ++i; /* skip the argument too. */
687 else if (0 == strncmp("-O", argv[i], 2))
689 process_optimisation_option(argv[i]+2);
691 else
693 /* Hmm, must be one of
694 * (a) A path name
695 * (b) A predicate
697 end_of_leading_options = i; /* Next time start with this option */
698 break;
701 return end_of_leading_options;
704 void
705 set_option_defaults(struct options *p)
707 /* We call check_nofollow() before setlocale() because the numbers
708 * for which we check (in the results of uname) definitiely have "."
709 * as the decimal point indicator even under locales for which that
710 * is not normally true. Hence atof() would do the wrong thing
711 * if we call it after setlocale().
713 #ifdef O_NOFOLLOW
714 p->open_nofollow_available = check_nofollow();
715 #else
716 p->open_nofollow_available = false;
717 #endif
719 p->regex_options = RE_SYNTAX_EMACS;
721 if (isatty(0))
723 p->warnings = true;
724 p->literal_control_chars = false;
726 else
728 p->warnings = false;
729 p->literal_control_chars = false; /* may change */
733 p->do_dir_first = true;
734 p->maxdepth = p->mindepth = -1;
735 p->start_time = time (NULL);
736 p->cur_day_start = p->start_time - DAYSECS;
737 p->full_days = false;
738 p->stay_on_filesystem = false;
739 p->ignore_readdir_race = false;
741 if (getenv("POSIXLY_CORRECT"))
742 p->output_block_size = 512;
743 else
744 p->output_block_size = 1024;
746 p->debug_options = 0uL;
747 p->optimisation_level = 0;
749 if (getenv("FIND_BLOCK_SIZE"))
751 error (1, 0, _("The environment variable FIND_BLOCK_SIZE is not supported, the only thing that affects the block size is the POSIXLY_CORRECT environment variable"));
754 #if LEAF_OPTIMISATION
755 /* The leaf optimisation is enabled. */
756 p->no_leaf_check = false;
757 #else
758 /* The leaf optimisation is disabled. */
759 p->no_leaf_check = true;
760 #endif
762 set_follow_state(SYMLINK_NEVER_DEREF); /* The default is equivalent to -P. */