1 /* find -- search for files in a directory hierarchy
2 Copyright (C) 1990, 91, 92, 93, 94, 2000,
3 2003, 2004, 2005 Free Software Foundation, Inc.
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 2, or (at your option)
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.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
20 /* GNU find was written by Eric Decker <cire@cisco.com>,
21 with enhancements by David MacKenzie <djm@gnu.org>,
22 Jay Plett <jay@silence.princeton.nj.us>,
23 and Tim Wood <axolotl!tim@toad.com>.
24 The idea for -print0 and xargs -0 came from
25 Dan Bernstein <brnstnd@kramden.acf.nyu.edu>.
26 Improvements have been made by James Youngman <jay@gnu.org>.
32 #define USE_SAFE_CHDIR 1
33 #undef STAT_MOUNTPOINTS
46 #ifdef HAVE_SYS_UTSNAME_H
47 #include <sys/utsname.h>
50 #include "../gnulib/lib/xalloc.h"
51 #include "../gnulib/lib/human.h"
52 #include "../gnulib/lib/canonicalize.h"
55 #include "savedirinfo.h"
67 # define _(Text) gettext (Text)
70 #define textdomain(Domain)
71 #define bindtextdomain(Package, Directory)
74 # define N_(String) gettext_noop (String)
76 /* See locate.c for explanation as to why not use (String) */
77 # define N_(String) String
80 #define apply_predicate(pathname, stat_buf_ptr, node) \
81 (*(node)->pred_func)((pathname), (stat_buf_ptr), (node))
83 #ifdef STAT_MOUNTPOINTS
84 static void init_mounted_dev_list(void);
87 static void process_top_path
PARAMS((char *pathname
, mode_t mode
));
88 static int process_path
PARAMS((char *pathname
, char *name
, boolean leaf
, char *parent
, mode_t type
));
89 static void process_dir
PARAMS((char *pathname
, char *name
, int pathlen
, struct stat
*statp
, char *parent
));
91 static void complete_pending_execdirs(struct predicate
*p
);
92 static void complete_pending_execs (struct predicate
*p
);
96 static boolean default_prints
PARAMS((struct predicate
*pred
));
98 /* Name this program was run with. */
101 /* All predicates for each path to process. */
102 struct predicate
*predicates
;
104 /* The last predicate allocated. */
105 struct predicate
*last_pred
;
107 /* The root of the evaluation tree. */
108 static struct predicate
*eval_tree
= NULL
;
111 struct options options
;
114 /* The full path of the initial working directory, or "." if
115 STARTING_DESC is nonnegative. */
116 char const *starting_dir
= ".";
118 /* A file descriptor open to the initial working directory.
119 Doing it this way allows us to work when the i.w.d. has
120 unreadable parents. */
123 /* The stat buffer of the initial working directory. */
124 struct stat starting_stat_buf
;
126 enum ChdirSymlinkHandling
128 SymlinkHandleDefault
, /* Normally the right choice */
129 SymlinkFollowOk
/* see comment in process_top_path() */
133 enum TraversalDirection
139 enum WdSanityCheckFatality
141 FATAL_IF_SANITY_CHECK_FAILS
,
142 RETRY_IF_SANITY_CHECK_FAILS
,
143 NON_FATAL_IF_SANITY_CHECK_FAILS
148 following_links(void)
150 switch (options
.symlink_handling
)
152 case SYMLINK_ALWAYS_DEREF
:
154 case SYMLINK_DEREF_ARGSONLY
:
155 return (state
.curdepth
== 0);
156 case SYMLINK_NEVER_DEREF
:
164 fallback_stat(const char *name
, struct stat
*p
, int prev_rv
)
166 /* Our original stat() call failed. Perhaps we can't follow a
167 * symbolic link. If that might be the problem, lstat() the link.
168 * Otherwise, admit defeat.
175 fprintf(stderr
, "fallback_stat(): stat(%s) failed; falling back on lstat()\n", name
);
177 return lstat(name
, p
);
184 case EOVERFLOW
: /* EOVERFLOW is not #defined on UNICOS. */
192 /* optionh_stat() implements the stat operation when the -H option is
195 * If the item to be examined is a command-line argument, we follow
196 * symbolic links. If the stat() call fails on the command-line item,
197 * we fall back on the properties of the symbolic link.
199 * If the item to be examined is not a command-line argument, we
200 * examine the link itself.
203 optionh_stat(const char *name
, struct stat
*p
)
205 if (0 == state
.curdepth
)
207 /* This file is from the command line; deference the link (if it
210 int rv
= stat(name
, p
);
212 return 0; /* success */
214 return fallback_stat(name
, p
, rv
);
218 /* Not a file on the command line; do not dereference the link.
220 return lstat(name
, p
);
224 /* optionl_stat() implements the stat operation when the -L option is
225 * in effect. That option makes us examine the thing the symbolic
226 * link points to, not the symbolic link itself.
229 optionl_stat(const char *name
, struct stat
*p
)
231 int rv
= stat(name
, p
);
233 return 0; /* normal case. */
235 return fallback_stat(name
, p
, rv
);
238 /* optionp_stat() implements the stat operation when the -P option is
239 * in effect (this is also the default). That option makes us examine
240 * the symbolic link itself, not the thing it points to.
243 optionp_stat(const char *name
, struct stat
*p
)
245 return lstat(name
, p
);
249 static uintmax_t stat_count
= 0u;
252 debug_stat (const char *file
, struct stat
*bufp
)
255 fprintf (stderr
, "debug_stat (%s)\n", file
);
256 switch (options
.symlink_handling
)
258 case SYMLINK_ALWAYS_DEREF
:
259 return optionl_stat(file
, bufp
);
260 case SYMLINK_DEREF_ARGSONLY
:
261 return optionh_stat(file
, bufp
);
262 case SYMLINK_NEVER_DEREF
:
263 return optionp_stat(file
, bufp
);
266 #endif /* DEBUG_STAT */
269 set_follow_state(enum SymlinkOption opt
)
273 case SYMLINK_ALWAYS_DEREF
: /* -L */
274 options
.xstat
= optionl_stat
;
275 options
.no_leaf_check
= true;
278 case SYMLINK_NEVER_DEREF
: /* -P (default) */
279 options
.xstat
= optionp_stat
;
280 /* Can't turn no_leaf_check off because the user might have specified
285 case SYMLINK_DEREF_ARGSONLY
: /* -H */
286 options
.xstat
= optionh_stat
;
287 options
.no_leaf_check
= true;
290 options
.symlink_handling
= opt
;
292 /* For DEBUG_STAT, the choice is made at runtime within debug_stat()
293 * by checking the contents of the symlink_handling variable.
295 #if defined(DEBUG_STAT)
296 options
.xstat
= debug_stat
;
297 #endif /* !DEBUG_STAT */
301 /* Complete any outstanding commands.
308 complete_pending_execs(eval_tree
);
309 complete_pending_execdirs(eval_tree
);
313 /* Get the stat information for a file, if it is
317 get_statinfo (const char *pathname
, const char *name
, struct stat
*p
)
319 if (!state
.have_stat
&& (*options
.xstat
) (name
, p
) != 0)
321 if (!options
.ignore_readdir_race
|| (errno
!= ENOENT
) )
323 error (0, errno
, "%s", pathname
);
324 state
.exit_status
= 1;
328 state
.have_stat
= true;
329 state
.have_type
= true;
330 state
.type
= p
->st_mode
;
334 /* Get the stat/type information for a file, if it is
338 get_info (const char *pathname
,
341 struct predicate
*pred_ptr
)
343 /* If we need the full stat info, or we need the type info but don't
344 * already have it, stat the file now.
347 if (pred_ptr
->need_stat
)
349 return get_statinfo(pathname
, state
.rel_pathname
, p
);
351 if ((pred_ptr
->need_type
&& (0 == state
.have_type
)))
353 return get_statinfo(pathname
, state
.rel_pathname
, p
);
358 /* Determine if we can use O_NOFOLLOW.
360 #if defined(O_NOFOLLOW)
367 if (0 == uname(&uts
))
369 /* POSIX requires that atof() ignore "unrecognised suffixes". */
370 release
= atof(uts
.release
);
372 if (0 == strcmp("Linux", uts
.sysname
))
374 /* Linux kernels 2.1.126 and earlier ignore the O_NOFOLLOW flag. */
375 return release
>= 2.2; /* close enough */
377 else if (0 == strcmp("FreeBSD", uts
.sysname
))
379 /* FreeBSD 3.0-CURRENT and later support it */
380 return release
>= 3.1;
384 /* Well, O_NOFOLLOW was defined, so we'll try to use it. */
390 main (int argc
, char **argv
)
393 const struct parser_table
*parse_entry
; /* Pointer to the parsing table entry for this expression. */
394 struct predicate
*cur_pred
;
395 char *predicate_name
; /* Name of predicate being parsed. */
396 int end_of_leading_options
= 0; /* First arg after any -H/-L etc. */
397 program_name
= argv
[0];
398 const struct parser_table
*entry_close
, *entry_print
, *entry_open
;
401 /* We call check_nofollow() before setlocale() because the numbers
402 * for which we check (in the results of uname) definitiely have "."
403 * as the decimal point indicator even under locales for which that
404 * is not normally true. Hence atof() would do the wrong thing
405 * if we call it after setlocale().
408 options
.open_nofollow_available
= check_nofollow();
410 options
.open_nofollow_available
= false;
413 options
.regex_options
= RE_SYNTAX_EMACS
;
415 #ifdef HAVE_SETLOCALE
416 setlocale (LC_ALL
, "");
418 bindtextdomain (PACKAGE
, LOCALEDIR
);
419 textdomain (PACKAGE
);
420 atexit (close_stdout
);
425 options
.warnings
= true;
429 options
.warnings
= false;
435 options
.do_dir_first
= true;
436 options
.maxdepth
= options
.mindepth
= -1;
437 options
.start_time
= time (NULL
);
438 options
.cur_day_start
= options
.start_time
- DAYSECS
;
439 options
.full_days
= false;
440 options
.stay_on_filesystem
= false;
441 options
.ignore_readdir_race
= false;
443 state
.exit_status
= 0;
445 #if defined(DEBUG_STAT)
446 options
.xstat
= debug_stat
;
447 #endif /* !DEBUG_STAT */
449 if (getenv("POSIXLY_CORRECT"))
450 options
.output_block_size
= 512;
452 options
.output_block_size
= 1024;
454 if (getenv("FIND_BLOCK_SIZE"))
456 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"));
459 #if LEAF_OPTIMISATION
460 /* The leaf optimisation is enabled. */
461 options
.no_leaf_check
= false;
463 /* The leaf optimisation is disabled. */
464 options
.no_leaf_check
= true;
467 set_follow_state(SYMLINK_NEVER_DEREF
); /* The default is equivalent to -P. */
470 fprintf (stderr
, "cur_day_start = %s", ctime (&options
.cur_day_start
));
473 /* Check for -P, -H or -L options. */
474 for (i
=1; (end_of_leading_options
= i
) < argc
; ++i
)
476 if (0 == strcmp("-H", argv
[i
]))
478 /* Meaning: dereference symbolic links on command line, but nowhere else. */
479 set_follow_state(SYMLINK_DEREF_ARGSONLY
);
481 else if (0 == strcmp("-L", argv
[i
]))
483 /* Meaning: dereference all symbolic links. */
484 set_follow_state(SYMLINK_ALWAYS_DEREF
);
486 else if (0 == strcmp("-P", argv
[i
]))
488 /* Meaning: never dereference symbolic links (default). */
489 set_follow_state(SYMLINK_NEVER_DEREF
);
491 else if (0 == strcmp("--", argv
[i
]))
493 /* -- signifies the end of options. */
494 end_of_leading_options
= i
+1; /* Next time start with the next option */
499 /* Hmm, must be one of
503 end_of_leading_options
= i
; /* Next time start with this option */
508 /* We are now processing the part of the "find" command line
509 * after the -H/-L options (if any).
512 /* fprintf(stderr, "rest: optind=%ld\n", (long)optind); */
514 /* Find where in ARGV the predicates begin. */
515 for (i
= end_of_leading_options
; i
< argc
&& strchr ("-!(),", argv
[i
][0]) == NULL
; i
++)
517 /* fprintf(stderr, "Looks like %s is not a predicate\n", argv[i]); */
521 /* Enclose the expression in `( ... )' so a default -print will
522 apply to the whole expression. */
523 entry_open
= find_parser("(");
524 entry_close
= find_parser(")");
525 entry_print
= find_parser("print");
526 assert(entry_open
!= NULL
);
527 assert(entry_close
!= NULL
);
528 assert(entry_print
!= NULL
);
530 parse_open (entry_open
, argv
, &argc
);
531 parse_begin_user_args(argv
, argc
, last_pred
, predicates
);
532 pred_sanity_check(last_pred
);
534 /* Build the input order list. */
537 if (strchr ("-!(),", argv
[i
][0]) == NULL
)
538 usage (_("paths must precede expression"));
539 predicate_name
= argv
[i
];
540 parse_entry
= find_parser (predicate_name
);
541 if (parse_entry
== NULL
)
543 /* Command line option not recognized */
544 error (1, 0, _("invalid predicate `%s'"), predicate_name
);
548 if (!(*(parse_entry
->parser_func
)) (parse_entry
, argv
, &i
))
551 /* Command line option requires an argument */
552 error (1, 0, _("missing argument to `%s'"), predicate_name
);
554 error (1, 0, _("invalid argument `%s' to `%s'"),
555 argv
[i
], predicate_name
);
558 pred_sanity_check(last_pred
);
559 pred_sanity_check(predicates
); /* XXX: expensive */
561 parse_end_user_args(argv
, argc
, last_pred
, predicates
);
563 if (predicates
->pred_next
== NULL
)
565 /* No predicates that do something other than set a global variable
566 were given; remove the unneeded initial `(' and add `-print'. */
567 cur_pred
= predicates
;
568 predicates
= last_pred
= predicates
->pred_next
;
569 free ((char *) cur_pred
);
570 parse_print (entry_print
, argv
, &argc
);
571 pred_sanity_check(last_pred
);
572 pred_sanity_check(predicates
); /* XXX: expensive */
574 else if (!default_prints (predicates
->pred_next
))
576 /* One or more predicates that produce output were given;
577 remove the unneeded initial `('. */
578 cur_pred
= predicates
;
579 predicates
= predicates
->pred_next
;
580 pred_sanity_check(predicates
); /* XXX: expensive */
581 free ((char *) cur_pred
);
585 /* `( user-supplied-expression ) -print'. */
586 parse_close (entry_close
, argv
, &argc
);
587 pred_sanity_check(last_pred
);
588 parse_print (entry_print
, argv
, &argc
);
589 pred_sanity_check(last_pred
);
590 pred_sanity_check(predicates
); /* XXX: expensive */
594 fprintf (stderr
, "Predicate List:\n");
595 print_list (stderr
, predicates
);
598 /* do a sanity check */
599 pred_sanity_check(predicates
);
601 /* Done parsing the predicates. Build the evaluation tree. */
602 cur_pred
= predicates
;
603 eval_tree
= get_expr (&cur_pred
, NO_PREC
);
605 /* Check if we have any left-over predicates (this fixes
606 * Debian bug #185202).
608 if (cur_pred
!= NULL
)
610 error (1, 0, _("unexpected extra predicate"));
614 fprintf (stderr
, "Eval Tree:\n");
615 print_tree (stderr
, eval_tree
, 0);
618 /* Rearrange the eval tree in optimal-predicate order. */
619 opt_expr (&eval_tree
);
621 /* Determine the point, if any, at which to stat the file. */
622 mark_stat (eval_tree
);
623 /* Determine the point, if any, at which to determine file type. */
624 mark_type (eval_tree
);
627 fprintf (stderr
, "Optimized Eval Tree:\n");
628 print_tree (stderr
, eval_tree
, 0);
629 fprintf (stderr
, "Optimized command line:\n");
630 print_optlist(stderr
, eval_tree
);
631 fprintf(stderr
, "\n");
634 /* safely_chdir() needs to check that it has ended up in the right place.
635 * To avoid bailing out when something gets automounted, it checks if
636 * the target directory appears to have had a directory mounted on it as
637 * we chdir()ed. The problem with this is that in order to notice that
638 * a filesystem was mounted, we would need to lstat() all the mount points.
639 * That strategy loses if our machine is a client of a dead NFS server.
641 * Hence if safely_chdir() and wd_sanity_check() can manage without needing
642 * to know the mounted device list, we do that.
644 if (!options
.open_nofollow_available
)
646 #ifdef STAT_MOUNTPOINTS
647 init_mounted_dev_list();
652 starting_desc
= open (".", O_RDONLY
);
653 if (0 <= starting_desc
&& fchdir (starting_desc
) != 0)
655 close (starting_desc
);
658 if (starting_desc
< 0)
660 starting_dir
= xgetcwd ();
662 error (1, errno
, _("cannot get current directory"));
664 if ((*options
.xstat
) (".", &starting_stat_buf
) != 0)
665 error (1, errno
, _("cannot get current directory"));
667 /* If no paths are given, default to ".". */
668 for (i
= end_of_leading_options
; i
< argc
&& strchr ("-!(),", argv
[i
][0]) == NULL
; i
++)
670 process_top_path (argv
[i
], 0);
673 /* If there were no path arguments, default to ".". */
674 if (i
== end_of_leading_options
)
677 * We use a temporary variable here because some actions modify
678 * the path temporarily. Hence if we use a string constant,
679 * we get a coredump. The best example of this is if we say
680 * "find -printf %H" (note, not "find . -printf %H").
682 char defaultpath
[2] = ".";
683 process_top_path (defaultpath
, 0);
686 /* If "-exec ... {} +" has been used, there may be some
687 * partially-full command lines which have been built,
688 * but which are not yet complete. Execute those now.
691 return state
.exit_status
;
696 specific_dirname(const char *dir
)
700 if (0 == strcmp(".", dir
))
702 /* OK, what's '.'? */
703 if (NULL
!= getcwd(dirbuf
, sizeof(dirbuf
)))
705 return strdup(dirbuf
);
714 char *result
= canonicalize_filename_mode(dir
, CAN_EXISTING
);
724 /* Return non-zero if FS is the name of a filesystem that is likely to
728 fs_likely_to_be_automounted(const char *fs
)
730 return ( (0==strcmp(fs
, "nfs")) || (0==strcmp(fs
, "autofs")) || (0==strcmp(fs
, "subfs")));
735 #ifdef STAT_MOUNTPOINTS
736 static dev_t
*mounted_devices
= NULL
;
737 static size_t num_mounted_devices
= 0u;
741 init_mounted_dev_list()
743 assert(NULL
== mounted_devices
);
744 assert(0 == num_mounted_devices
);
745 mounted_devices
= get_mounted_devices(&num_mounted_devices
);
749 refresh_mounted_dev_list(void)
753 free(mounted_devices
);
756 num_mounted_devices
= 0u;
757 init_mounted_dev_list();
761 /* Search for device DEV in the array LIST, which is of size N. */
763 dev_present(dev_t dev
, const dev_t
*list
, size_t n
)
769 if ( (*list
++) == dev
)
776 enum MountPointStateChange
778 MountPointRecentlyMounted
,
779 MountPointRecentlyUnmounted
,
780 MountPointStateUnchanged
785 static enum MountPointStateChange
786 get_mount_state(dev_t newdev
)
788 int new_is_present
, new_was_present
;
790 new_was_present
= dev_present(newdev
, mounted_devices
, num_mounted_devices
);
791 refresh_mounted_dev_list();
792 new_is_present
= dev_present(newdev
, mounted_devices
, num_mounted_devices
);
794 if (new_was_present
== new_is_present
)
795 return MountPointStateUnchanged
;
796 else if (new_is_present
)
797 return MountPointRecentlyMounted
;
799 return MountPointRecentlyUnmounted
;
804 /* We stat()ed a directory, chdir()ed into it (we know this
805 * since direction is TraversingDown), stat()ed it again,
806 * and noticed that the device numbers are different. Check
807 * if the filesystem was recently mounted.
809 * If it was, it looks like chdir()ing into the directory
810 * caused a filesystem to be mounted. Maybe automount is
811 * running. Anyway, that's probably OK - but it happens
812 * only when we are moving downward.
814 * We also allow for the possibility that a similar thing
815 * has happened with the unmounting of a filesystem. This
816 * is much rarer, as it relies on an automounter timeout
817 * occurring at exactly the wrong moment.
819 static enum WdSanityCheckFatality
820 dirchange_is_fatal(const char *specific_what
,
821 enum WdSanityCheckFatality isfatal
,
823 struct stat
*newinfo
)
825 enum MountPointStateChange transition
= get_mount_state(newinfo
->st_dev
);
828 case MountPointRecentlyUnmounted
:
829 isfatal
= NON_FATAL_IF_SANITY_CHECK_FAILS
;
833 _("Warning: filesystem %s has recently been unmounted."),
838 case MountPointRecentlyMounted
:
839 isfatal
= NON_FATAL_IF_SANITY_CHECK_FAILS
;
843 _("Warning: filesystem %s has recently been mounted."),
848 case MountPointStateUnchanged
:
849 /* leave isfatal as it is */
861 /* Examine the results of the stat() of a directory from before we
862 * entered or left it, with the results of stat()ing it afterward. If
863 * these are different, the filesystem tree has been modified while we
864 * were traversing it. That might be an attempt to use a race
865 * condition to persuade find to do something it didn't intend
866 * (e.g. an attempt by an ordinary user to exploit the fact that root
867 * sometimes runs find on the whole filesystem). However, this can
868 * also happen if automount is running (certainly on Solaris). With
869 * automount, moving into a directory can cause a filesystem to be
872 * To cope sensibly with this, we will raise an error if we see the
873 * device number change unless we are chdir()ing into a subdirectory,
874 * and the directory we moved into has been mounted or unmounted "recently".
875 * Here "recently" means since we started "find" or we last re-read
876 * the /etc/mnttab file.
878 * If the device number does not change but the inode does, that is a
881 * If the device number and inode are both the same, we are happy.
883 * If a filesystem is (un)mounted as we chdir() into the directory, that
884 * may mean that we're now examining a section of the filesystem that might
885 * have been excluded from consideration (via -prune or -quit for example).
886 * Hence we print a warning message to indicate that the output of find
887 * might be inconsistent due to the change in the filesystem.
890 wd_sanity_check(const char *thing_to_stat
,
891 const char *progname
,
895 struct stat
*newinfo
,
898 enum TraversalDirection direction
,
899 enum WdSanityCheckFatality isfatal
,
900 boolean
*changed
) /* output parameter */
903 char *specific_what
= NULL
;
908 if ((*options
.xstat
) (".", newinfo
) != 0)
909 error (1, errno
, "%s", thing_to_stat
);
911 if (old_dev
!= newinfo
->st_dev
)
914 specific_what
= specific_dirname(what
);
915 fstype
= filesystem_type(newinfo
);
916 silent
= fs_likely_to_be_automounted(fstype
);
918 /* This condition is rare, so once we are here it is
919 * reasonable to perform an expensive computation to
920 * determine if we should continue or fail.
922 if (TraversingDown
== direction
)
924 #ifdef STAT_MOUNTPOINTS
925 isfatal
= dirchange_is_fatal(specific_what
,isfatal
,silent
,newinfo
);
927 isfatal
= RETRY_IF_SANITY_CHECK_FAILS
;
933 case FATAL_IF_SANITY_CHECK_FAILS
:
935 fstype
= filesystem_type(newinfo
);
937 _("%s%s changed during execution of %s (old device number %ld, new device number %ld, filesystem type is %s) [ref %ld]"),
942 (long) newinfo
->st_dev
,
949 case NON_FATAL_IF_SANITY_CHECK_FAILS
:
951 /* Since the device has changed under us, the inode number
952 * will almost certainly also be different. However, we have
953 * already decided that this is not a problem. Hence we return
954 * without checking the inode number.
960 case RETRY_IF_SANITY_CHECK_FAILS
:
965 /* Device number was the same, check if the inode has changed. */
966 if (old_ino
!= newinfo
->st_ino
)
969 specific_what
= specific_dirname(what
);
970 fstype
= filesystem_type(newinfo
);
972 error ((isfatal
== FATAL_IF_SANITY_CHECK_FAILS
) ? 1 : 0,
973 0, /* no relevant errno value */
974 _("%s%s changed during execution of %s (old inode number %ld, new inode number %ld, filesystem type is %s) [ref %ld]"),
979 (long) newinfo
->st_ino
,
992 SafeChdirFailSymlink
,
995 SafeChdirFailWouldBeUnableToReturn
,
996 SafeChdirFailChdirFailed
,
997 SafeChdirFailNonexistent
1000 /* Safely perform a change in directory. We do this by calling
1001 * lstat() on the subdirectory, using chdir() to move into it, and
1002 * then lstat()ing ".". We compare the results of the two stat calls
1003 * to see if they are consistent. If not, we sound the alarm.
1005 * If following_links() is true, we do follow symbolic links.
1007 static enum SafeChdirStatus
1008 safely_chdir_lstat(const char *dest
,
1009 enum TraversalDirection direction
,
1010 struct stat
*statbuf_dest
,
1011 enum ChdirSymlinkHandling symlink_follow_option
,
1014 struct stat statbuf_arrived
;
1016 int saved_errno
; /* specific_dirname() changes errno. */
1017 boolean rv_set
= false;
1018 boolean statflag
= false;
1020 enum WdSanityCheckFatality isfatal
= RETRY_IF_SANITY_CHECK_FAILS
;
1022 saved_errno
= errno
= 0;
1024 dotfd
= open(".", O_RDONLY
);
1026 /* We jump back to here if wd_sanity_check()
1027 * recoverably triggers an alert.
1034 /* Stat the directory we're going to. */
1035 if (0 == options
.xstat(dest
, statbuf_dest
))
1040 /* symlink_follow_option might be set to SymlinkFollowOk, which
1041 * would allow us to chdir() into a symbolic link. This is
1042 * only useful for the case where the directory we're
1043 * chdir()ing into is the basename of a command line
1044 * argument, for example where "foo/bar/baz" is specified on
1045 * the command line. When -P is in effect (the default),
1046 * baz will not be followed if it is a symlink, but if bar
1047 * is a symlink, it _should_ be followed. Hence we need the
1048 * ability to override the policy set by following_links().
1050 if (!following_links() && S_ISLNK(statbuf_dest
->st_mode
))
1052 /* We're not supposed to be following links, but this is
1053 * a link. Check symlink_follow_option to see if we should
1054 * make a special exception.
1056 if (symlink_follow_option
== SymlinkFollowOk
)
1058 /* We need to re-stat() the file so that the
1059 * sanity check can pass.
1061 if (0 != stat(dest
, statbuf_dest
))
1063 rv
= SafeChdirFailNonexistent
;
1065 saved_errno
= errno
;
1072 /* Not following symlinks, so the attempt to
1073 * chdir() into a symlink should be prevented.
1075 rv
= SafeChdirFailSymlink
;
1077 saved_errno
= 0; /* silence the error message */
1083 /* Although the immediately following chdir() would detect
1084 * the fact that this is not a directory for us, this would
1085 * result in an extra system call that fails. Anybody
1086 * examining the system-call trace should ideally not be
1087 * concerned that something is actually failing.
1089 if (!S_ISDIR(statbuf_dest
->st_mode
))
1091 rv
= SafeChdirFailNotDir
;
1093 saved_errno
= 0; /* silence the error message */
1098 fprintf(stderr
, "safely_chdir(): chdir(\"%s\")\n", dest
);
1100 if (0 == chdir(dest
))
1102 /* check we ended up where we wanted to go */
1103 boolean changed
= false;
1104 if (!wd_sanity_check(".", program_name
, ".",
1105 statbuf_dest
->st_dev
,
1106 statbuf_dest
->st_ino
,
1108 0, __LINE__
, direction
,
1112 /* Only allow one failure. */
1113 if (RETRY_IF_SANITY_CHECK_FAILS
== isfatal
)
1115 if (0 == fchdir(dotfd
))
1117 isfatal
= FATAL_IF_SANITY_CHECK_FAILS
;
1122 /* Failed to return to original directory,
1123 * but we know that the current working
1124 * directory is not the one that we intend
1125 * to be in. Since fchdir() failed, we
1126 * can't recover from this and so this error
1130 "failed to return to parent directory");
1135 /* XXX: not sure what to use as an excuse here. */
1136 rv
= SafeChdirFailNonexistent
;
1148 saved_errno
= errno
;
1149 if (ENOENT
== saved_errno
)
1151 rv
= SafeChdirFailNonexistent
;
1153 if (options
.ignore_readdir_race
)
1154 errno
= 0; /* don't issue err msg */
1156 else if (ENOTDIR
== saved_errno
)
1158 /* This can happen if the we stat a directory,
1159 * and then filesystem activity changes it into
1162 saved_errno
= 0; /* don't issue err msg */
1163 rv
= SafeChdirFailNotDir
;
1168 rv
= SafeChdirFailChdirFailed
;
1176 saved_errno
= errno
;
1177 rv
= SafeChdirFailStat
;
1180 if ( (ENOENT
== saved_errno
) || (0 == state
.curdepth
))
1181 saved_errno
= 0; /* don't issue err msg */
1187 /* We do not have read permissions on "." */
1188 rv
= SafeChdirFailWouldBeUnableToReturn
;
1193 /* This is the success path, so we clear errno. The caller probably
1194 * won't be calling error() anyway.
1198 /* We use the same exit path for success or failure.
1199 * which has occurred is recorded in RV.
1202 /* We do not call error() as this would result in a duplicate error
1203 * message when the caller does the same thing.
1206 errno
= saved_errno
;
1214 *did_stat
= statflag
;
1219 #if defined(O_NOFOLLOW)
1220 /* Safely change working directory to the specified subdirectory. If
1221 * we are not allowed to follow symbolic links, we use open() with
1222 * O_NOFOLLOW, followed by fchdir(). This ensures that we don't
1223 * follow symbolic links (of course, we do follow them if the -L
1224 * option is in effect).
1226 static enum SafeChdirStatus
1227 safely_chdir_nofollow(const char *dest
,
1228 enum TraversalDirection direction
,
1229 struct stat
*statbuf_dest
,
1230 enum ChdirSymlinkHandling symlink_follow_option
,
1238 switch (symlink_follow_option
)
1240 case SymlinkFollowOk
:
1244 case SymlinkHandleDefault
:
1245 if (following_links())
1248 extraflags
= O_NOFOLLOW
;
1253 fd
= open(dest
, O_RDONLY
|extraflags
);
1259 return SafeChdirFailSymlink
; /* This is why we use O_NOFOLLOW */
1261 return SafeChdirFailNonexistent
;
1263 return SafeChdirFailChdirFailed
;
1268 if (0 == fchdir(fd
))
1275 int saved_errno
= errno
;
1277 errno
= saved_errno
;
1282 return SafeChdirFailNotDir
;
1285 case EBADF
: /* Shouldn't happen */
1289 return SafeChdirFailChdirFailed
;
1295 static enum SafeChdirStatus
1296 safely_chdir(const char *dest
,
1297 enum TraversalDirection direction
,
1298 struct stat
*statbuf_dest
,
1299 enum ChdirSymlinkHandling symlink_follow_option
,
1302 /* We're about to leave a directory. If there are any -execdir
1303 * argument lists which have been built but have not yet been
1304 * processed, do them now because they must be done in the same
1307 complete_pending_execdirs(eval_tree
);
1309 #if defined(O_NOFOLLOW)
1310 if (options
.open_nofollow_available
)
1311 return safely_chdir_nofollow(dest
, direction
, statbuf_dest
, symlink_follow_option
, did_stat
);
1313 return safely_chdir_lstat(dest
, direction
, statbuf_dest
, symlink_follow_option
, did_stat
);
1318 /* Safely go back to the starting directory. */
1322 struct stat stat_buf
;
1325 if (starting_desc
< 0)
1328 fprintf(stderr
, "chdir_back(): chdir(\"%s\")\n", starting_dir
);
1331 #ifdef STAT_MOUNTPOINTS
1332 /* We will need the mounted device list. Get it now if we don't
1335 if (NULL
== mounted_devices
)
1336 init_mounted_dev_list();
1339 if (chdir (starting_dir
) != 0)
1340 error (1, errno
, "%s", starting_dir
);
1342 wd_sanity_check(starting_dir
,
1345 starting_stat_buf
.st_dev
,
1346 starting_stat_buf
.st_ino
,
1347 &stat_buf
, 0, __LINE__
,
1349 FATAL_IF_SANITY_CHECK_FAILS
,
1355 fprintf(stderr
, "chdir_back(): chdir(<starting-point>)\n");
1357 if (fchdir (starting_desc
) != 0)
1358 error (1, errno
, "%s", starting_dir
);
1362 /* Move to the parent of a given directory and then call a function,
1363 * restoring the cwd. Don't bother changing directory if the
1364 * specified directory is a child of "." or is the root directory.
1367 at_top (char *pathname
,
1370 void (*action
)(char *pathname
,
1373 struct stat
*pstat
))
1376 char *parent_dir
= dir_name(pathname
);
1377 char *base
= base_name(pathname
);
1380 state
.path_length
= strlen (pathname
);
1382 if (0 == strcmp(pathname
, parent_dir
)
1383 || 0 == strcmp(parent_dir
, "."))
1390 enum TraversalDirection direction
;
1391 enum SafeChdirStatus chdir_status
;
1393 boolean did_stat
= false;
1396 if (0 == strcmp(base
, ".."))
1397 direction
= TraversingUp
;
1399 direction
= TraversingDown
;
1401 /* We pass SymlinkFollowOk to safely_chdir(), which allows it to
1402 * chdir() into a symbolic link. This is only useful for the
1403 * case where the directory we're chdir()ing into is the
1404 * basename of a command line argument, for example where
1405 * "foo/bar/baz" is specified on the command line. When -P is
1406 * in effect (the default), baz will not be followed if it is a
1407 * symlink, but if bar is a symlink, it _should_ be followed.
1408 * Hence we need the ability to override the policy set by
1409 * following_links().
1411 chdir_status
= safely_chdir(parent_dir
, direction
, &st
, SymlinkFollowOk
, &did_stat
);
1412 if (SafeChdirOK
!= chdir_status
)
1414 const char *what
= (SafeChdirFailWouldBeUnableToReturn
== chdir_status
) ? "." : parent_dir
;
1416 error (0, errno
, "%s", what
);
1418 error (0, 0, "Failed to safely change directory into `%s'",
1421 /* We can't process this command-line argument. */
1422 state
.exit_status
= 1;
1430 action(pathname
, base
, mode
, pstat
);
1439 static void do_process_top_dir(char *pathname
,
1444 process_path (pathname
, base
, false, ".", mode
);
1445 complete_pending_execdirs(eval_tree
);
1448 static void do_process_predicate(char *pathname
,
1453 state
.rel_pathname
= base
;
1454 apply_predicate (pathname
, pstat
, eval_tree
);
1460 /* Descend PATHNAME, which is a command-line argument.
1462 Actions like -execdir assume that we are in the
1463 parent directory of the file we're examining,
1464 and on entry to this function our working directory
1465 is whatever it was when find was invoked. Therefore
1466 If PATHNAME is "." we just leave things as they are.
1467 Otherwise, we figure out what the parent directory is,
1471 process_top_path (char *pathname
, mode_t mode
)
1473 at_top(pathname
, mode
, NULL
, do_process_top_dir
);
1477 /* Info on each directory in the current tree branch, to avoid
1478 getting stuck in symbolic link loops. */
1479 static struct dir_id
*dir_ids
= NULL
;
1480 /* Entries allocated in `dir_ids'. */
1481 static int dir_alloc
= 0;
1482 /* Index in `dir_ids' of directory currently being searched.
1483 This is always the last valid entry. */
1484 static int dir_curr
= -1;
1485 /* (Arbitrary) number of entries to grow `dir_ids' by. */
1486 #define DIR_ALLOC_STEP 32
1490 /* We've detected a filesystem loop. This is caused by one of
1493 * 1. Option -L is in effect and we've hit a symbolic link that
1494 * points to an ancestor. This is harmless. We won't traverse the
1497 * 2. We have hit a real cycle in the directory hierarchy. In this
1498 * case, we issue a diagnostic message (POSIX requires this) and we
1499 * skip that directory entry.
1502 issue_loop_warning(const char *name
, const char *pathname
, int level
)
1504 struct stat stbuf_link
;
1505 if (lstat(name
, &stbuf_link
) != 0)
1506 stbuf_link
.st_mode
= S_IFREG
;
1508 if (S_ISLNK(stbuf_link
.st_mode
))
1511 _("Symbolic link `%s' is part of a loop in the directory hierarchy; we have already visited the directory to which it points."),
1516 int distance
= 1 + (dir_curr
-level
);
1517 /* We have found an infinite loop. POSIX requires us to
1518 * issue a diagnostic. Usually we won't get to here
1519 * because when the leaf optimisation is on, it will cause
1520 * the subdirectory to be skipped. If /a/b/c/d is a hard
1521 * link to /a/b, then the link count of /a/b/c is 2,
1522 * because the ".." entry of /b/b/c/d points to /a, not
1526 _("Filesystem loop detected; `%s' has the same device number and inode as a directory which is %d %s."),
1530 _("level higher in the filesystem hierarchy") :
1531 _("levels higher in the filesystem hierarchy")));
1535 /* Take a "mode" indicator and fill in the files of 'state'.
1538 digest_mode(mode_t mode
,
1539 const char *pathname
,
1544 /* If we know the type of the directory entry, and it is not a
1545 * symbolic link, we may be able to avoid a stat() or lstat() call.
1549 if (S_ISLNK(mode
) && following_links())
1551 /* mode is wrong because we should have followed the symlink. */
1552 if (get_statinfo(pathname
, name
, pstat
) != 0)
1554 mode
= state
.type
= pstat
->st_mode
;
1555 state
.have_type
= true;
1559 state
.have_type
= true;
1560 pstat
->st_mode
= state
.type
= mode
;
1565 /* Mode is not yet known; may have to stat the file unless we
1566 * can deduce that it is not a directory (which is all we need to
1567 * know at this stage)
1571 state
.have_stat
= false;
1572 state
.have_type
= false;;
1577 if (get_statinfo(pathname
, name
, pstat
) != 0)
1580 /* If -L is in effect and we are dealing with a symlink,
1581 * st_mode is the mode of the pointed-to file, while mode is
1582 * the mode of the directory entry (S_IFLNK). Hence now
1583 * that we have the stat information, override "mode".
1585 state
.type
= pstat
->st_mode
;
1586 state
.have_type
= true;
1596 /* Recursively descend path PATHNAME, applying the predicates.
1597 LEAF is true if PATHNAME is known to be in a directory that has no
1598 more unexamined subdirectories, and therefore it is not a directory.
1599 Knowing this allows us to avoid calling stat as long as possible for
1602 NAME is PATHNAME relative to the current directory. We access NAME
1605 PARENT is the path of the parent of NAME, relative to find's
1608 Return nonzero iff PATHNAME is a directory. */
1611 process_path (char *pathname
, char *name
, boolean leaf
, char *parent
,
1614 struct stat stat_buf
;
1615 static dev_t root_dev
; /* Device ID of current argument pathname. */
1618 /* Assume it is a non-directory initially. */
1619 stat_buf
.st_mode
= 0;
1620 state
.rel_pathname
= name
;
1622 state
.have_stat
= false;
1623 state
.have_type
= false;
1625 if (!digest_mode(mode
, pathname
, name
, &stat_buf
, leaf
))
1628 if (!S_ISDIR (state
.type
))
1630 if (state
.curdepth
>= options
.mindepth
)
1631 apply_predicate (pathname
, &stat_buf
, eval_tree
);
1635 /* From here on, we're working on a directory. */
1638 /* Now we really need to stat the directory, even if we know the
1639 * type, because we need information like struct stat.st_rdev.
1641 if (get_statinfo(pathname
, name
, &stat_buf
) != 0)
1644 state
.have_stat
= true;
1645 mode
= state
.type
= stat_buf
.st_mode
; /* use full info now that we have it. */
1646 state
.stop_at_current_level
=
1647 options
.maxdepth
>= 0
1648 && state
.curdepth
>= options
.maxdepth
;
1650 /* If we've already seen this directory on this branch,
1651 don't descend it again. */
1652 for (i
= 0; i
<= dir_curr
; i
++)
1653 if (stat_buf
.st_ino
== dir_ids
[i
].ino
&&
1654 stat_buf
.st_dev
== dir_ids
[i
].dev
)
1656 state
.stop_at_current_level
= true;
1657 issue_loop_warning(name
, pathname
, i
);
1660 if (dir_alloc
<= ++dir_curr
)
1662 dir_alloc
+= DIR_ALLOC_STEP
;
1663 dir_ids
= (struct dir_id
*)
1664 xrealloc ((char *) dir_ids
, dir_alloc
* sizeof (struct dir_id
));
1666 dir_ids
[dir_curr
].ino
= stat_buf
.st_ino
;
1667 dir_ids
[dir_curr
].dev
= stat_buf
.st_dev
;
1669 if (options
.stay_on_filesystem
)
1671 if (state
.curdepth
== 0)
1672 root_dev
= stat_buf
.st_dev
;
1673 else if (stat_buf
.st_dev
!= root_dev
)
1674 state
.stop_at_current_level
= true;
1677 if (options
.do_dir_first
&& state
.curdepth
>= options
.mindepth
)
1678 apply_predicate (pathname
, &stat_buf
, eval_tree
);
1681 fprintf(stderr
, "pathname = %s, stop_at_current_level = %d\n",
1682 pathname
, state
.stop_at_current_level
);
1685 if (state
.stop_at_current_level
== false)
1686 /* Scan directory on disk. */
1687 process_dir (pathname
, name
, strlen (pathname
), &stat_buf
, parent
);
1689 if (options
.do_dir_first
== false && state
.curdepth
>= options
.mindepth
)
1691 /* The fields in 'state' are now out of date. Correct them.
1693 if (!digest_mode(mode
, pathname
, name
, &stat_buf
, leaf
))
1698 at_top(pathname
, mode
, &stat_buf
, do_process_predicate
);
1702 do_process_predicate(pathname
, name
, mode
, &stat_buf
);
1711 /* Examine the predicate list for instances of -execdir or -okdir
1712 * which have been terminated with '+' (build argument list) rather
1713 * than ';' (singles only). If there are any, run them (this will
1714 * have no effect if there are no arguments waiting).
1717 complete_pending_execdirs(struct predicate
*p
)
1719 #if defined(NEW_EXEC)
1723 complete_pending_execdirs(p
->pred_left
);
1725 if (p
->pred_func
== pred_execdir
|| p
->pred_func
== pred_okdir
)
1727 /* It's an exec-family predicate. p->args.exec_val is valid. */
1728 if (p
->args
.exec_vec
.multiple
)
1730 struct exec_val
*execp
= &p
->args
.exec_vec
;
1732 /* This one was terminated by '+' and so might have some
1733 * left... Run it if necessary.
1735 if (execp
->state
.todo
)
1737 /* There are not-yet-executed arguments. */
1738 launch (&execp
->ctl
, &execp
->state
);
1743 complete_pending_execdirs(p
->pred_right
);
1745 /* nothing to do. */
1750 /* Examine the predicate list for instances of -exec which have been
1751 * terminated with '+' (build argument list) rather than ';' (singles
1752 * only). If there are any, run them (this will have no effect if
1753 * there are no arguments waiting).
1756 complete_pending_execs(struct predicate
*p
)
1758 #if defined(NEW_EXEC)
1762 complete_pending_execs(p
->pred_left
);
1764 /* It's an exec-family predicate then p->args.exec_val is valid
1765 * and we can check it.
1767 if (p
->pred_func
== pred_exec
&& p
->args
.exec_vec
.multiple
)
1769 struct exec_val
*execp
= &p
->args
.exec_vec
;
1771 /* This one was terminated by '+' and so might have some
1772 * left... Run it if necessary. Set state.exit_status if
1773 * there are any problems.
1775 if (execp
->state
.todo
)
1777 /* There are not-yet-executed arguments. */
1778 launch (&execp
->ctl
, &execp
->state
);
1782 complete_pending_execs(p
->pred_right
);
1784 /* nothing to do. */
1790 /* Scan directory PATHNAME and recurse through process_path for each entry.
1792 PATHLEN is the length of PATHNAME.
1794 NAME is PATHNAME relative to the current directory.
1796 STATP is the results of *options.xstat on it.
1798 PARENT is the path of the parent of NAME, relative to find's
1799 starting directory. */
1802 process_dir (char *pathname
, char *name
, int pathlen
, struct stat
*statp
, char *parent
)
1804 int subdirs_left
; /* Number of unexamined subdirs in PATHNAME. */
1805 boolean subdirs_unreliable
; /* if true, cannot use dir link count as subdir limif (if false, it may STILL be unreliable) */
1806 int idx
; /* Which entry are we on? */
1807 struct stat stat_buf
;
1809 struct savedir_dirinfo
*dirinfo
;
1811 if (statp
->st_nlink
< 2)
1813 subdirs_unreliable
= true;
1817 subdirs_unreliable
= false; /* not necessarily right */
1818 subdirs_left
= statp
->st_nlink
- 2; /* Account for name and ".". */
1822 dirinfo
= xsavedir(name
, 0);
1825 if (dirinfo
== NULL
)
1828 error (0, errno
, "%s", pathname
);
1829 state
.exit_status
= 1;
1833 register char *namep
; /* Current point in `name_space'. */
1834 char *cur_path
; /* Full path of each file to process. */
1835 char *cur_name
; /* Base name of each file to process. */
1836 unsigned cur_path_size
; /* Bytes allocated for `cur_path'. */
1837 register unsigned file_len
; /* Length of each path to process. */
1838 register unsigned pathname_len
; /* PATHLEN plus trailing '/'. */
1839 boolean did_stat
= false;
1841 if (pathname
[pathlen
- 1] == '/')
1842 pathname_len
= pathlen
+ 1; /* For '\0'; already have '/'. */
1844 pathname_len
= pathlen
+ 2; /* For '/' and '\0'. */
1848 /* We're about to leave the directory. If there are any
1849 * -execdir argument lists which have been built but have not
1850 * yet been processed, do them now because they must be done in
1851 * the same directory.
1853 complete_pending_execdirs(eval_tree
);
1855 if (strcmp (name
, "."))
1857 enum SafeChdirStatus status
= safely_chdir (name
, TraversingDown
, &stat_buf
, SymlinkHandleDefault
, &did_stat
);
1861 /* If there had been a change but wd_sanity_check()
1862 * accepted it, we need to accept that on the
1863 * way back up as well, so modify our record
1864 * of what we think we should see later.
1865 * If there was no change, the assignments are a no-op.
1867 * However, before performing the assignment, we need to
1868 * check that we have the stat information. If O_NOFOLLOW
1869 * is available, safely_chdir() will not have needed to use
1870 * stat(), and so stat_buf will just contain random data.
1874 /* If there is a link we need to follow it. Hence
1875 * the direct call to stat() not through (options.xstat)
1877 if (0 != stat(".", &stat_buf
))
1878 break; /* skip the assignment. */
1880 dir_ids
[dir_curr
].dev
= stat_buf
.st_dev
;
1881 dir_ids
[dir_curr
].ino
= stat_buf
.st_ino
;
1885 case SafeChdirFailWouldBeUnableToReturn
:
1886 error (0, errno
, ".");
1887 state
.exit_status
= 1;
1890 case SafeChdirFailNonexistent
:
1891 case SafeChdirFailStat
:
1892 case SafeChdirFailSymlink
:
1893 case SafeChdirFailNotDir
:
1894 case SafeChdirFailChdirFailed
:
1895 error (0, errno
, "%s", pathname
);
1896 state
.exit_status
= 1;
1901 for (idx
=0; idx
< dirinfo
->size
; ++idx
)
1903 /* savedirinfo() may return dirinfo=NULL if extended information
1906 mode_t mode
= (dirinfo
->entries
[idx
].flags
& SavedirHaveFileType
) ?
1907 dirinfo
->entries
[idx
].type_info
: 0;
1908 namep
= dirinfo
->entries
[idx
].name
;
1910 /* Append this directory entry's name to the path being searched. */
1911 file_len
= pathname_len
+ strlen (namep
);
1912 if (file_len
> cur_path_size
)
1914 while (file_len
> cur_path_size
)
1915 cur_path_size
+= 1024;
1918 cur_path
= xmalloc (cur_path_size
);
1919 strcpy (cur_path
, pathname
);
1920 cur_path
[pathname_len
- 2] = '/';
1922 cur_name
= cur_path
+ pathname_len
- 1;
1923 strcpy (cur_name
, namep
);
1926 if (!options
.no_leaf_check
&& !subdirs_unreliable
)
1928 if (mode
&& S_ISDIR(mode
) && (subdirs_left
== 0))
1930 /* This is a subdirectory, but the number of directories we
1931 * have found now exceeds the number we would expect given
1932 * the hard link count on the parent. This is likely to be
1933 * a bug in the filesystem driver (e.g. Linux's
1934 * /proc filesystem) or may just be a fact that the OS
1935 * doesn't really handle hard links with Unix semantics.
1936 * In the latter case, -noleaf should be used routinely.
1938 error(0, 0, _("WARNING: Hard link count is wrong for %s: this may be a bug in your filesystem driver. Automatically turning on find's -noleaf option. Earlier results may have failed to include directories that should have been searched."),
1940 state
.exit_status
= 1; /* We know the result is wrong, now */
1941 options
.no_leaf_check
= true; /* Don't make same
1943 subdirs_left
= 1; /* band-aid for this iteration. */
1946 /* Normal case optimization. On normal Unix
1947 filesystems, a directory that has no subdirectories
1948 has two links: its name, and ".". Any additional
1949 links are to the ".." entries of its subdirectories.
1950 Once we have processed as many subdirectories as
1951 there are additional links, we know that the rest of
1952 the entries are non-directories -- in other words,
1954 subdirs_left
-= process_path (cur_path
, cur_name
,
1955 subdirs_left
== 0, pathname
,
1960 /* There might be weird (e.g., CD-ROM or MS-DOS) filesystems
1961 mounted, which don't have Unix-like directory link counts. */
1962 process_path (cur_path
, cur_name
, false, pathname
, mode
);
1969 /* We're about to leave the directory. If there are any
1970 * -execdir argument lists which have been built but have not
1971 * yet been processed, do them now because they must be done in
1972 * the same directory.
1974 complete_pending_execdirs(eval_tree
);
1977 if (strcmp (name
, "."))
1979 enum SafeChdirStatus status
;
1981 boolean did_stat
= false;
1983 /* We could go back and do the next command-line arg
1984 instead, maybe using longjmp. */
1986 boolean deref
= following_links() ? true : false;
1988 if ( (state
.curdepth
>0) && !deref
)
1996 status
= safely_chdir (dir
, TraversingUp
, &stat_buf
, SymlinkHandleDefault
, &did_stat
);
2002 case SafeChdirFailWouldBeUnableToReturn
:
2003 error (1, errno
, ".");
2006 case SafeChdirFailNonexistent
:
2007 case SafeChdirFailStat
:
2008 case SafeChdirFailSymlink
:
2009 case SafeChdirFailNotDir
:
2010 case SafeChdirFailChdirFailed
:
2011 error (1, errno
, "%s", pathname
);
2017 did
.dev
= dir_ids
[dir_curr
-1].dev
;
2018 did
.ino
= dir_ids
[dir_curr
-1].ino
;
2022 did
.dev
= starting_stat_buf
.st_dev
;
2023 did
.ino
= starting_stat_buf
.st_ino
;
2029 free_dirinfo(dirinfo
);
2033 /* Return true if there are no predicates with no_default_print in
2034 predicate list PRED, false if there are any.
2035 Returns true if default print should be performed */
2038 default_prints (struct predicate
*pred
)
2040 while (pred
!= NULL
)
2042 if (pred
->no_default_print
)
2044 pred
= pred
->pred_next
;