1 /* find -- search for files in a directory hierarchy
2 Copyright (C) 1990, 91, 92, 93, 94, 2000, 2003, 2004 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)
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,
19 /* GNU find was written by Eric Decker <cire@cisco.com>,
20 with enhancements by David MacKenzie <djm@gnu.org>,
21 Jay Plett <jay@silence.princeton.nj.us>,
22 and Tim Wood <axolotl!tim@toad.com>.
23 The idea for -print0 and xargs -0 came from
24 Dan Bernstein <brnstnd@kramden.acf.nyu.edu>. */
29 #define USE_SAFE_CHDIR 1
30 #undef STAT_MOUNTPOINTS
43 #ifdef HAVE_SYS_UTSNAME_H
44 #include <sys/utsname.h>
47 #include "../gnulib/lib/xalloc.h"
48 #include "../gnulib/lib/human.h"
49 #include "../gnulib/lib/canonicalize.h"
52 #include "savedirinfo.h"
64 # define _(Text) gettext (Text)
67 #define textdomain(Domain)
68 #define bindtextdomain(Package, Directory)
71 # define N_(String) gettext_noop (String)
73 /* See locate.c for explanation as to why not use (String) */
74 # define N_(String) String
77 #define apply_predicate(pathname, stat_buf_ptr, node) \
78 (*(node)->pred_func)((pathname), (stat_buf_ptr), (node))
80 #ifdef STAT_MOUNTPOINTS
81 static void init_mounted_dev_list(void);
84 static void process_top_path
PARAMS((char *pathname
, mode_t mode
));
85 static int process_path
PARAMS((char *pathname
, char *name
, boolean leaf
, char *parent
, mode_t type
));
86 static void process_dir
PARAMS((char *pathname
, char *name
, int pathlen
, struct stat
*statp
, char *parent
));
88 static void complete_pending_execdirs(struct predicate
*p
);
89 static void complete_pending_execs (struct predicate
*p
);
93 static boolean default_prints
PARAMS((struct predicate
*pred
));
95 /* Name this program was run with. */
98 /* All predicates for each path to process. */
99 struct predicate
*predicates
;
101 /* The last predicate allocated. */
102 struct predicate
*last_pred
;
104 /* The root of the evaluation tree. */
105 static struct predicate
*eval_tree
= NULL
;
108 struct options options
;
111 /* The full path of the initial working directory, or "." if
112 STARTING_DESC is nonnegative. */
113 char const *starting_dir
= ".";
115 /* A file descriptor open to the initial working directory.
116 Doing it this way allows us to work when the i.w.d. has
117 unreadable parents. */
120 /* The stat buffer of the initial working directory. */
121 struct stat starting_stat_buf
;
123 enum ChdirSymlinkHandling
125 SymlinkHandleDefault
, /* Normally the right choice */
126 SymlinkFollowOk
/* see comment in process_top_path() */
130 enum TraversalDirection
136 enum WdSanityCheckFatality
138 FATAL_IF_SANITY_CHECK_FAILS
,
139 RETRY_IF_SANITY_CHECK_FAILS
,
140 NON_FATAL_IF_SANITY_CHECK_FAILS
145 following_links(void)
147 switch (options
.symlink_handling
)
149 case SYMLINK_ALWAYS_DEREF
:
151 case SYMLINK_DEREF_ARGSONLY
:
152 return (state
.curdepth
== 0);
153 case SYMLINK_NEVER_DEREF
:
161 fallback_stat(const char *name
, struct stat
*p
, int prev_rv
)
163 /* Our original stat() call failed. Perhaps we can't follow a
164 * symbolic link. If that might be the problem, lstat() the link.
165 * Otherwise, admit defeat.
172 fprintf(stderr
, "fallback_stat(): stat(%s) failed; falling back on lstat()\n", name
);
174 return lstat(name
, p
);
181 case EOVERFLOW
: /* EOVERFLOW is not #defined on UNICOS. */
189 /* optionh_stat() implements the stat operation when the -H option is
192 * If the item to be examined is a command-line argument, we follow
193 * symbolic links. If the stat() call fails on the command-line item,
194 * we fall back on the properties of the symbolic link.
196 * If the item to be examined is not a command-line argument, we
197 * examine the link itself.
200 optionh_stat(const char *name
, struct stat
*p
)
202 if (0 == state
.curdepth
)
204 /* This file is from the command line; deference the link (if it
207 int rv
= stat(name
, p
);
209 return 0; /* success */
211 return fallback_stat(name
, p
, rv
);
215 /* Not a file on the command line; do not dereference the link.
217 return lstat(name
, p
);
221 /* optionl_stat() implements the stat operation when the -L option is
222 * in effect. That option makes us examine the thing the symbolic
223 * link points to, not the symbolic link itself.
226 optionl_stat(const char *name
, struct stat
*p
)
228 int rv
= stat(name
, p
);
230 return 0; /* normal case. */
232 return fallback_stat(name
, p
, rv
);
235 /* optionp_stat() implements the stat operation when the -P option is
236 * in effect (this is also the default). That option makes us examine
237 * the symbolic link itself, not the thing it points to.
240 optionp_stat(const char *name
, struct stat
*p
)
242 return lstat(name
, p
);
246 static uintmax_t stat_count
= 0u;
249 debug_stat (const char *file
, struct stat
*bufp
)
252 fprintf (stderr
, "debug_stat (%s)\n", file
);
253 switch (options
.symlink_handling
)
255 case SYMLINK_ALWAYS_DEREF
:
256 return optionl_stat(file
, bufp
);
257 case SYMLINK_DEREF_ARGSONLY
:
258 return optionh_stat(file
, bufp
);
259 case SYMLINK_NEVER_DEREF
:
260 return optionp_stat(file
, bufp
);
263 #endif /* DEBUG_STAT */
266 set_follow_state(enum SymlinkOption opt
)
270 case SYMLINK_ALWAYS_DEREF
: /* -L */
271 options
.xstat
= optionl_stat
;
272 options
.no_leaf_check
= true;
275 case SYMLINK_NEVER_DEREF
: /* -P (default) */
276 options
.xstat
= optionp_stat
;
277 /* Can't turn no_leaf_check off because the user might have specified
282 case SYMLINK_DEREF_ARGSONLY
: /* -H */
283 options
.xstat
= optionh_stat
;
284 options
.no_leaf_check
= true;
287 options
.symlink_handling
= opt
;
289 /* For DEBUG_STAT, the choice is made at runtime within debug_stat()
290 * by checking the contents of the symlink_handling variable.
292 #if defined(DEBUG_STAT)
293 options
.xstat
= debug_stat
;
294 #endif /* !DEBUG_STAT */
298 /* Complete any outstanding commands.
305 complete_pending_execs(eval_tree
);
306 complete_pending_execdirs(eval_tree
);
310 /* Get the stat information for a file, if it is
314 get_statinfo (const char *pathname
, const char *name
, struct stat
*p
)
316 if (!state
.have_stat
&& (*options
.xstat
) (name
, p
) != 0)
318 if (!options
.ignore_readdir_race
|| (errno
!= ENOENT
) )
320 error (0, errno
, "%s", pathname
);
321 state
.exit_status
= 1;
325 state
.have_stat
= true;
326 state
.have_type
= true;
327 state
.type
= p
->st_mode
;
331 /* Get the stat/type information for a file, if it is
335 get_info (const char *pathname
,
338 struct predicate
*pred_ptr
)
340 /* If we need the full stat info, or we need the type info but don't
341 * already have it, stat the file now.
344 if (pred_ptr
->need_stat
)
346 return get_statinfo(pathname
, state
.rel_pathname
, p
);
348 if ((pred_ptr
->need_type
&& (0 == state
.have_type
)))
350 return get_statinfo(pathname
, state
.rel_pathname
, p
);
355 /* Determine if we can use O_NOFOLLOW.
357 #if defined(O_NOFOLLOW)
364 if (0 == uname(&uts
))
366 /* POSIX requires that atof() ignore "unrecognised suffixes". */
367 release
= atof(uts
.release
);
369 if (0 == strcmp("Linux", uts
.sysname
))
371 /* Linux kernels 2.1.126 and earlier ignore the O_NOFOLLOW flag. */
372 return release
>= 2.2; /* close enough */
374 else if (0 == strcmp("FreeBSD", uts
.sysname
))
376 /* FreeBSD 3.0-CURRENT and later support it */
377 return release
>= 3.1;
381 /* Well, O_NOFOLLOW was defined, so we'll try to use it. */
387 main (int argc
, char **argv
)
390 const struct parser_table
*parse_entry
; /* Pointer to the parsing table entry for this expression. */
391 struct predicate
*cur_pred
;
392 char *predicate_name
; /* Name of predicate being parsed. */
393 int end_of_leading_options
= 0; /* First arg after any -H/-L etc. */
394 program_name
= argv
[0];
395 const struct parser_table
*entry_close
, *entry_print
, *entry_open
;
398 /* We call check_nofollow() before setlocale() because the numbers
399 * for which we check (in the results of uname) definitiely have "."
400 * as the decimal point indicator even under locales for which that
401 * is not normally true. Hence atof() would do the wrong thing
402 * if we call it after setlocale().
405 options
.open_nofollow_available
= check_nofollow();
407 options
.open_nofollow_available
= false;
410 options
.regex_options
= RE_SYNTAX_EMACS
;
412 #ifdef HAVE_SETLOCALE
413 setlocale (LC_ALL
, "");
415 bindtextdomain (PACKAGE
, LOCALEDIR
);
416 textdomain (PACKAGE
);
417 atexit (close_stdout
);
422 options
.warnings
= true;
426 options
.warnings
= false;
432 options
.do_dir_first
= true;
433 options
.maxdepth
= options
.mindepth
= -1;
434 options
.start_time
= time (NULL
);
435 options
.cur_day_start
= options
.start_time
- DAYSECS
;
436 options
.full_days
= false;
437 options
.stay_on_filesystem
= false;
438 options
.ignore_readdir_race
= false;
440 state
.exit_status
= 0;
442 #if defined(DEBUG_STAT)
443 options
.xstat
= debug_stat
;
444 #endif /* !DEBUG_STAT */
446 if (getenv("POSIXLY_CORRECT"))
447 options
.output_block_size
= 512;
449 options
.output_block_size
= 1024;
451 if (getenv("FIND_BLOCK_SIZE"))
453 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"));
456 options
.no_leaf_check
= false;
457 set_follow_state(SYMLINK_NEVER_DEREF
); /* The default is equivalent to -P. */
460 fprintf (stderr
, "cur_day_start = %s", ctime (&options
.cur_day_start
));
463 /* Check for -P, -H or -L options. */
464 for (i
=1; (end_of_leading_options
= i
) < argc
; ++i
)
466 if (0 == strcmp("-H", argv
[i
]))
468 /* Meaning: dereference symbolic links on command line, but nowhere else. */
469 set_follow_state(SYMLINK_DEREF_ARGSONLY
);
471 else if (0 == strcmp("-L", argv
[i
]))
473 /* Meaning: dereference all symbolic links. */
474 set_follow_state(SYMLINK_ALWAYS_DEREF
);
476 else if (0 == strcmp("-P", argv
[i
]))
478 /* Meaning: never dereference symbolic links (default). */
479 set_follow_state(SYMLINK_NEVER_DEREF
);
481 else if (0 == strcmp("--", argv
[i
]))
483 /* -- signifies the end of options. */
484 end_of_leading_options
= i
+1; /* Next time start with the next option */
489 /* Hmm, must be one of
493 end_of_leading_options
= i
; /* Next time start with this option */
498 /* We are now processing the part of the "find" command line
499 * after the -H/-L options (if any).
502 /* fprintf(stderr, "rest: optind=%ld\n", (long)optind); */
504 /* Find where in ARGV the predicates begin. */
505 for (i
= end_of_leading_options
; i
< argc
&& strchr ("-!(),", argv
[i
][0]) == NULL
; i
++)
507 /* fprintf(stderr, "Looks like %s is not a predicate\n", argv[i]); */
511 /* Enclose the expression in `( ... )' so a default -print will
512 apply to the whole expression. */
513 entry_open
= find_parser("(");
514 entry_close
= find_parser(")");
515 entry_print
= find_parser("print");
516 assert(entry_open
!= NULL
);
517 assert(entry_close
!= NULL
);
518 assert(entry_print
!= NULL
);
520 parse_open (entry_open
, argv
, &argc
);
521 parse_begin_user_args(argv
, argc
, last_pred
, predicates
);
522 pred_sanity_check(last_pred
);
524 /* Build the input order list. */
527 if (strchr ("-!(),", argv
[i
][0]) == NULL
)
528 usage (_("paths must precede expression"));
529 predicate_name
= argv
[i
];
530 parse_entry
= find_parser (predicate_name
);
531 if (parse_entry
== NULL
)
533 /* Command line option not recognized */
534 error (1, 0, _("invalid predicate `%s'"), predicate_name
);
538 if (!(*(parse_entry
->parser_func
)) (parse_entry
, argv
, &i
))
541 /* Command line option requires an argument */
542 error (1, 0, _("missing argument to `%s'"), predicate_name
);
544 error (1, 0, _("invalid argument `%s' to `%s'"),
545 argv
[i
], predicate_name
);
548 pred_sanity_check(last_pred
);
549 pred_sanity_check(predicates
); /* XXX: expensive */
551 parse_end_user_args(argv
, argc
, last_pred
, predicates
);
553 if (predicates
->pred_next
== NULL
)
555 /* No predicates that do something other than set a global variable
556 were given; remove the unneeded initial `(' and add `-print'. */
557 cur_pred
= predicates
;
558 predicates
= last_pred
= predicates
->pred_next
;
559 free ((char *) cur_pred
);
560 parse_print (entry_print
, argv
, &argc
);
561 pred_sanity_check(last_pred
);
562 pred_sanity_check(predicates
); /* XXX: expensive */
564 else if (!default_prints (predicates
->pred_next
))
566 /* One or more predicates that produce output were given;
567 remove the unneeded initial `('. */
568 cur_pred
= predicates
;
569 predicates
= predicates
->pred_next
;
570 pred_sanity_check(predicates
); /* XXX: expensive */
571 free ((char *) cur_pred
);
575 /* `( user-supplied-expression ) -print'. */
576 parse_close (entry_close
, argv
, &argc
);
577 pred_sanity_check(last_pred
);
578 parse_print (entry_print
, argv
, &argc
);
579 pred_sanity_check(last_pred
);
580 pred_sanity_check(predicates
); /* XXX: expensive */
584 fprintf (stderr
, "Predicate List:\n");
585 print_list (stderr
, predicates
);
588 /* do a sanity check */
589 pred_sanity_check(predicates
);
591 /* Done parsing the predicates. Build the evaluation tree. */
592 cur_pred
= predicates
;
593 eval_tree
= get_expr (&cur_pred
, NO_PREC
);
595 /* Check if we have any left-over predicates (this fixes
596 * Debian bug #185202).
598 if (cur_pred
!= NULL
)
600 error (1, 0, _("unexpected extra predicate"));
604 fprintf (stderr
, "Eval Tree:\n");
605 print_tree (stderr
, eval_tree
, 0);
608 /* Rearrange the eval tree in optimal-predicate order. */
609 opt_expr (&eval_tree
);
611 /* Determine the point, if any, at which to stat the file. */
612 mark_stat (eval_tree
);
613 /* Determine the point, if any, at which to determine file type. */
614 mark_type (eval_tree
);
617 fprintf (stderr
, "Optimized Eval Tree:\n");
618 print_tree (stderr
, eval_tree
, 0);
619 fprintf (stderr
, "Optimized command line:\n");
620 print_optlist(stderr
, eval_tree
);
621 fprintf(stderr
, "\n");
624 /* safely_chdir() needs to check that it has ended up in the right place.
625 * To avoid bailing out when something gets automounted, it checks if
626 * the target directory appears to have had a directory mounted on it as
627 * we chdir()ed. The problem with this is that in order to notice that
628 * a filesystem was mounted, we would need to lstat() all the mount points.
629 * That strategy loses if our machine is a client of a dead NFS server.
631 * Hence if safely_chdir() and wd_sanity_check() can manage without needing
632 * to know the mounted device list, we do that.
634 if (!options
.open_nofollow_available
)
636 #ifdef STAT_MOUNTPOINTS
637 init_mounted_dev_list();
642 starting_desc
= open (".", O_RDONLY
);
643 if (0 <= starting_desc
&& fchdir (starting_desc
) != 0)
645 close (starting_desc
);
648 if (starting_desc
< 0)
650 starting_dir
= xgetcwd ();
652 error (1, errno
, _("cannot get current directory"));
654 if ((*options
.xstat
) (".", &starting_stat_buf
) != 0)
655 error (1, errno
, _("cannot get current directory"));
657 /* If no paths are given, default to ".". */
658 for (i
= end_of_leading_options
; i
< argc
&& strchr ("-!(),", argv
[i
][0]) == NULL
; i
++)
660 process_top_path (argv
[i
], 0);
663 /* If there were no path arguments, default to ".". */
664 if (i
== end_of_leading_options
)
667 * We use a temporary variable here because some actions modify
668 * the path temporarily. Hence if we use a string constant,
669 * we get a coredump. The best example of this is if we say
670 * "find -printf %H" (note, not "find . -printf %H").
672 char defaultpath
[2] = ".";
673 process_top_path (defaultpath
, 0);
676 /* If "-exec ... {} +" has been used, there may be some
677 * partially-full command lines which have been built,
678 * but which are not yet complete. Execute those now.
681 return state
.exit_status
;
686 specific_dirname(const char *dir
)
690 if (0 == strcmp(".", dir
))
692 /* OK, what's '.'? */
693 if (NULL
!= getcwd(dirbuf
, sizeof(dirbuf
)))
695 return strdup(dirbuf
);
704 char *result
= canonicalize_filename_mode(dir
, CAN_EXISTING
);
714 /* Return non-zero if FS is the name of a filesystem that is likely to
718 fs_likely_to_be_automounted(const char *fs
)
720 return ( (0==strcmp(fs
, "nfs")) || (0==strcmp(fs
, "autofs")) || (0==strcmp(fs
, "subfs")));
725 #ifdef STAT_MOUNTPOINTS
726 static dev_t
*mounted_devices
= NULL
;
727 static size_t num_mounted_devices
= 0u;
731 init_mounted_dev_list()
733 assert(NULL
== mounted_devices
);
734 assert(0 == num_mounted_devices
);
735 mounted_devices
= get_mounted_devices(&num_mounted_devices
);
739 refresh_mounted_dev_list(void)
743 free(mounted_devices
);
746 num_mounted_devices
= 0u;
747 init_mounted_dev_list();
751 /* Search for device DEV in the array LIST, which is of size N. */
753 dev_present(dev_t dev
, const dev_t
*list
, size_t n
)
759 if ( (*list
++) == dev
)
766 enum MountPointStateChange
768 MountPointRecentlyMounted
,
769 MountPointRecentlyUnmounted
,
770 MountPointStateUnchanged
775 static enum MountPointStateChange
776 get_mount_state(dev_t newdev
)
778 int new_is_present
, new_was_present
;
780 new_was_present
= dev_present(newdev
, mounted_devices
, num_mounted_devices
);
781 refresh_mounted_dev_list();
782 new_is_present
= dev_present(newdev
, mounted_devices
, num_mounted_devices
);
784 if (new_was_present
== new_is_present
)
785 return MountPointStateUnchanged
;
786 else if (new_is_present
)
787 return MountPointRecentlyMounted
;
789 return MountPointRecentlyUnmounted
;
794 /* We stat()ed a directory, chdir()ed into it (we know this
795 * since direction is TraversingDown), stat()ed it again,
796 * and noticed that the device numbers are different. Check
797 * if the filesystem was recently mounted.
799 * If it was, it looks like chdir()ing into the directory
800 * caused a filesystem to be mounted. Maybe automount is
801 * running. Anyway, that's probably OK - but it happens
802 * only when we are moving downward.
804 * We also allow for the possibility that a similar thing
805 * has happened with the unmounting of a filesystem. This
806 * is much rarer, as it relies on an automounter timeout
807 * occurring at exactly the wrong moment.
809 static enum WdSanityCheckFatality
810 dirchange_is_fatal(const char *specific_what
,
811 enum WdSanityCheckFatality isfatal
,
813 struct stat
*newinfo
)
815 enum MountPointStateChange transition
= get_mount_state(newinfo
->st_dev
);
818 case MountPointRecentlyUnmounted
:
819 isfatal
= NON_FATAL_IF_SANITY_CHECK_FAILS
;
823 _("Warning: filesystem %s has recently been unmounted."),
828 case MountPointRecentlyMounted
:
829 isfatal
= NON_FATAL_IF_SANITY_CHECK_FAILS
;
833 _("Warning: filesystem %s has recently been mounted."),
838 case MountPointStateUnchanged
:
839 /* leave isfatal as it is */
851 /* Examine the results of the stat() of a directory from before we
852 * entered or left it, with the results of stat()ing it afterward. If
853 * these are different, the filesystem tree has been modified while we
854 * were traversing it. That might be an attempt to use a race
855 * condition to persuade find to do something it didn't intend
856 * (e.g. an attempt by an ordinary user to exploit the fact that root
857 * sometimes runs find on the whole filesystem). However, this can
858 * also happen if automount is running (certainly on Solaris). With
859 * automount, moving into a directory can cause a filesystem to be
862 * To cope sensibly with this, we will raise an error if we see the
863 * device number change unless we are chdir()ing into a subdirectory,
864 * and the directory we moved into has been mounted or unmounted "recently".
865 * Here "recently" means since we started "find" or we last re-read
866 * the /etc/mnttab file.
868 * If the device number does not change but the inode does, that is a
871 * If the device number and inode are both the same, we are happy.
873 * If a filesystem is (un)mounted as we chdir() into the directory, that
874 * may mean that we're now examining a section of the filesystem that might
875 * have been excluded from consideration (via -prune or -quit for example).
876 * Hence we print a warning message to indicate that the output of find
877 * might be inconsistent due to the change in the filesystem.
880 wd_sanity_check(const char *thing_to_stat
,
881 const char *progname
,
885 struct stat
*newinfo
,
888 enum TraversalDirection direction
,
889 enum WdSanityCheckFatality isfatal
,
890 boolean
*changed
) /* output parameter */
893 char *specific_what
= NULL
;
898 if ((*options
.xstat
) (".", newinfo
) != 0)
899 error (1, errno
, "%s", thing_to_stat
);
901 if (old_dev
!= newinfo
->st_dev
)
904 specific_what
= specific_dirname(what
);
905 fstype
= filesystem_type(newinfo
);
906 silent
= fs_likely_to_be_automounted(fstype
);
908 /* This condition is rare, so once we are here it is
909 * reasonable to perform an expensive computation to
910 * determine if we should continue or fail.
912 if (TraversingDown
== direction
)
914 #ifdef STAT_MOUNTPOINTS
915 isfatal
= dirchange_is_fatal(specific_what
,isfatal
,silent
,newinfo
);
917 isfatal
= RETRY_IF_SANITY_CHECK_FAILS
;
923 case FATAL_IF_SANITY_CHECK_FAILS
:
925 fstype
= filesystem_type(newinfo
);
927 _("%s%s changed during execution of %s (old device number %ld, new device number %ld, filesystem type is %s) [ref %ld]"),
932 (long) newinfo
->st_dev
,
939 case NON_FATAL_IF_SANITY_CHECK_FAILS
:
941 /* Since the device has changed under us, the inode number
942 * will almost certainly also be different. However, we have
943 * already decided that this is not a problem. Hence we return
944 * without checking the inode number.
950 case RETRY_IF_SANITY_CHECK_FAILS
:
955 /* Device number was the same, check if the inode has changed. */
956 if (old_ino
!= newinfo
->st_ino
)
959 specific_what
= specific_dirname(what
);
960 fstype
= filesystem_type(newinfo
);
962 error ((isfatal
== FATAL_IF_SANITY_CHECK_FAILS
) ? 1 : 0,
963 0, /* no relevant errno value */
964 _("%s%s changed during execution of %s (old inode number %ld, new inode number %ld, filesystem type is %s) [ref %ld]"),
969 (long) newinfo
->st_ino
,
982 SafeChdirFailSymlink
,
985 SafeChdirFailWouldBeUnableToReturn
,
986 SafeChdirFailChdirFailed
,
987 SafeChdirFailNonexistent
990 /* Safely perform a change in directory. We do this by calling
991 * lstat() on the subdirectory, using chdir() to move into it, and
992 * then lstat()ing ".". We compare the results of the two stat calls
993 * to see if they are consistent. If not, we sound the alarm.
995 * If following_links() is true, we do follow symbolic links.
997 static enum SafeChdirStatus
998 safely_chdir_lstat(const char *dest
,
999 enum TraversalDirection direction
,
1000 struct stat
*statbuf_dest
,
1001 enum ChdirSymlinkHandling symlink_follow_option
,
1004 struct stat statbuf_arrived
;
1006 int saved_errno
; /* specific_dirname() changes errno. */
1007 boolean rv_set
= false;
1008 boolean statflag
= false;
1010 enum WdSanityCheckFatality isfatal
= RETRY_IF_SANITY_CHECK_FAILS
;
1012 saved_errno
= errno
= 0;
1014 dotfd
= open(".", O_RDONLY
);
1016 /* We jump back to here if wd_sanity_check()
1017 * recoverably triggers an alert.
1024 /* Stat the directory we're going to. */
1025 if (0 == options
.xstat(dest
, statbuf_dest
))
1030 /* symlink_follow_option might be set to SymlinkFollowOk, which
1031 * would allow us to chdir() into a symbolic link. This is
1032 * only useful for the case where the directory we're
1033 * chdir()ing into is the basename of a command line
1034 * argument, for example where "foo/bar/baz" is specified on
1035 * the command line. When -P is in effect (the default),
1036 * baz will not be followed if it is a symlink, but if bar
1037 * is a symlink, it _should_ be followed. Hence we need the
1038 * ability to override the policy set by following_links().
1040 if (!following_links() && S_ISLNK(statbuf_dest
->st_mode
))
1042 /* We're not supposed to be following links, but this is
1043 * a link. Check symlink_follow_option to see if we should
1044 * make a special exception.
1046 if (symlink_follow_option
== SymlinkFollowOk
)
1048 /* We need to re-stat() the file so that the
1049 * sanity check can pass.
1051 if (0 != stat(dest
, statbuf_dest
))
1053 rv
= SafeChdirFailNonexistent
;
1055 saved_errno
= errno
;
1062 /* Not following symlinks, so the attempt to
1063 * chdir() into a symlink should be prevented.
1065 rv
= SafeChdirFailSymlink
;
1067 saved_errno
= 0; /* silence the error message */
1073 /* Although the immediately following chdir() would detect
1074 * the fact that this is not a directory for us, this would
1075 * result in an extra system call that fails. Anybody
1076 * examining the system-call trace should ideally not be
1077 * concerned that something is actually failing.
1079 if (!S_ISDIR(statbuf_dest
->st_mode
))
1081 rv
= SafeChdirFailNotDir
;
1083 saved_errno
= 0; /* silence the error message */
1088 fprintf(stderr
, "safely_chdir(): chdir(\"%s\")\n", dest
);
1090 if (0 == chdir(dest
))
1092 /* check we ended up where we wanted to go */
1093 boolean changed
= false;
1094 if (!wd_sanity_check(".", program_name
, ".",
1095 statbuf_dest
->st_dev
,
1096 statbuf_dest
->st_ino
,
1098 0, __LINE__
, direction
,
1102 /* Only allow one failure. */
1103 if (RETRY_IF_SANITY_CHECK_FAILS
== isfatal
)
1105 if (0 == fchdir(dotfd
))
1107 isfatal
= FATAL_IF_SANITY_CHECK_FAILS
;
1112 /* Failed to return to original directory,
1113 * but we know that the current working
1114 * directory is not the one that we intend
1115 * to be in. Since fchdir() failed, we
1116 * can't recover from this and so this error
1120 "failed to return to parent directory");
1125 /* XXX: not sure what to use as an excuse here. */
1126 rv
= SafeChdirFailNonexistent
;
1138 saved_errno
= errno
;
1139 if (ENOENT
== saved_errno
)
1141 rv
= SafeChdirFailNonexistent
;
1143 if (options
.ignore_readdir_race
)
1144 errno
= 0; /* don't issue err msg */
1146 else if (ENOTDIR
== saved_errno
)
1148 /* This can happen if the we stat a directory,
1149 * and then filesystem activity changes it into
1152 saved_errno
= 0; /* don't issue err msg */
1153 rv
= SafeChdirFailNotDir
;
1158 rv
= SafeChdirFailChdirFailed
;
1166 saved_errno
= errno
;
1167 rv
= SafeChdirFailStat
;
1170 if ( (ENOENT
== saved_errno
) || (0 == state
.curdepth
))
1171 saved_errno
= 0; /* don't issue err msg */
1177 /* We do not have read permissions on "." */
1178 rv
= SafeChdirFailWouldBeUnableToReturn
;
1183 /* This is the success path, so we clear errno. The caller probably
1184 * won't be calling error() anyway.
1188 /* We use the same exit path for success or failure.
1189 * which has occurred is recorded in RV.
1192 /* We do not call error() as this would result in a duplicate error
1193 * message when the caller does the same thing.
1196 errno
= saved_errno
;
1204 *did_stat
= statflag
;
1209 #if defined(O_NOFOLLOW)
1210 /* Safely change working directory to the specified subdirectory. If
1211 * we are not allowed to follow symbolic links, we use open() with
1212 * O_NOFOLLOW, followed by fchdir(). This ensures that we don't
1213 * follow symbolic links (of course, we do follow them if the -L
1214 * option is in effect).
1216 static enum SafeChdirStatus
1217 safely_chdir_nofollow(const char *dest
,
1218 enum TraversalDirection direction
,
1219 struct stat
*statbuf_dest
,
1220 enum ChdirSymlinkHandling symlink_follow_option
,
1228 switch (symlink_follow_option
)
1230 case SymlinkFollowOk
:
1234 case SymlinkHandleDefault
:
1235 if (following_links())
1238 extraflags
= O_NOFOLLOW
;
1243 fd
= open(dest
, O_RDONLY
|extraflags
);
1249 return SafeChdirFailSymlink
; /* This is why we use O_NOFOLLOW */
1251 return SafeChdirFailNonexistent
;
1253 return SafeChdirFailChdirFailed
;
1258 if (0 == fchdir(fd
))
1265 int saved_errno
= errno
;
1267 errno
= saved_errno
;
1272 return SafeChdirFailNotDir
;
1275 case EBADF
: /* Shouldn't happen */
1279 return SafeChdirFailChdirFailed
;
1285 static enum SafeChdirStatus
1286 safely_chdir(const char *dest
,
1287 enum TraversalDirection direction
,
1288 struct stat
*statbuf_dest
,
1289 enum ChdirSymlinkHandling symlink_follow_option
,
1292 /* We're about to leave a directory. If there are any -execdir
1293 * argument lists which have been built but have not yet been
1294 * processed, do them now because they must be done in the same
1297 complete_pending_execdirs(eval_tree
);
1299 #if defined(O_NOFOLLOW)
1300 if (options
.open_nofollow_available
)
1301 return safely_chdir_nofollow(dest
, direction
, statbuf_dest
, symlink_follow_option
, did_stat
);
1303 return safely_chdir_lstat(dest
, direction
, statbuf_dest
, symlink_follow_option
, did_stat
);
1308 /* Safely go back to the starting directory. */
1312 struct stat stat_buf
;
1315 if (starting_desc
< 0)
1318 fprintf(stderr
, "chdir_back(): chdir(\"%s\")\n", starting_dir
);
1321 #ifdef STAT_MOUNTPOINTS
1322 /* We will need the mounted device list. Get it now if we don't
1325 if (NULL
== mounted_devices
)
1326 init_mounted_dev_list();
1329 if (chdir (starting_dir
) != 0)
1330 error (1, errno
, "%s", starting_dir
);
1332 wd_sanity_check(starting_dir
,
1335 starting_stat_buf
.st_dev
,
1336 starting_stat_buf
.st_ino
,
1337 &stat_buf
, 0, __LINE__
,
1339 FATAL_IF_SANITY_CHECK_FAILS
,
1345 fprintf(stderr
, "chdir_back(): chdir(<starting-point>)\n");
1347 if (fchdir (starting_desc
) != 0)
1348 error (1, errno
, "%s", starting_dir
);
1352 /* Move to the parent of a given directory and then call a function,
1353 * restoring the cwd. Don't bother changing directory if the
1354 * specified directory is a child of "." or is the root directory.
1357 at_top (char *pathname
,
1360 void (*action
)(char *pathname
,
1363 struct stat
*pstat
))
1366 char *parent_dir
= dir_name(pathname
);
1367 char *base
= base_name(pathname
);
1370 state
.path_length
= strlen (pathname
);
1372 if (0 == strcmp(pathname
, parent_dir
)
1373 || 0 == strcmp(parent_dir
, "."))
1380 enum TraversalDirection direction
;
1381 enum SafeChdirStatus chdir_status
;
1383 boolean did_stat
= false;
1386 if (0 == strcmp(base
, ".."))
1387 direction
= TraversingUp
;
1389 direction
= TraversingDown
;
1391 /* We pass SymlinkFollowOk to safely_chdir(), which allows it to
1392 * chdir() into a symbolic link. This is only useful for the
1393 * case where the directory we're chdir()ing into is the
1394 * basename of a command line argument, for example where
1395 * "foo/bar/baz" is specified on the command line. When -P is
1396 * in effect (the default), baz will not be followed if it is a
1397 * symlink, but if bar is a symlink, it _should_ be followed.
1398 * Hence we need the ability to override the policy set by
1399 * following_links().
1401 chdir_status
= safely_chdir(parent_dir
, direction
, &st
, SymlinkFollowOk
, &did_stat
);
1402 if (SafeChdirOK
!= chdir_status
)
1404 const char *what
= (SafeChdirFailWouldBeUnableToReturn
== chdir_status
) ? "." : parent_dir
;
1406 error (0, errno
, "%s", what
);
1408 error (0, 0, "Failed to safely change directory into `%s'",
1411 /* We can't process this command-line argument. */
1412 state
.exit_status
= 1;
1420 action(pathname
, base
, mode
, pstat
);
1429 static void do_process_top_dir(char *pathname
,
1434 process_path (pathname
, base
, false, ".", mode
);
1435 complete_pending_execdirs(eval_tree
);
1438 static void do_process_predicate(char *pathname
,
1443 state
.rel_pathname
= base
;
1444 apply_predicate (pathname
, pstat
, eval_tree
);
1450 /* Descend PATHNAME, which is a command-line argument.
1452 Actions like -execdir assume that we are in the
1453 parent directory of the file we're examining,
1454 and on entry to this function our working directory
1455 is whatever it was when find was invoked. Therefore
1456 If PATHNAME is "." we just leave things as they are.
1457 Otherwise, we figure out what the parent directory is,
1461 process_top_path (char *pathname
, mode_t mode
)
1463 at_top(pathname
, mode
, NULL
, do_process_top_dir
);
1467 /* Info on each directory in the current tree branch, to avoid
1468 getting stuck in symbolic link loops. */
1469 static struct dir_id
*dir_ids
= NULL
;
1470 /* Entries allocated in `dir_ids'. */
1471 static int dir_alloc
= 0;
1472 /* Index in `dir_ids' of directory currently being searched.
1473 This is always the last valid entry. */
1474 static int dir_curr
= -1;
1475 /* (Arbitrary) number of entries to grow `dir_ids' by. */
1476 #define DIR_ALLOC_STEP 32
1480 /* We've detected a filesystem loop. This is caused by one of
1483 * 1. Option -L is in effect and we've hit a symbolic link that
1484 * points to an ancestor. This is harmless. We won't traverse the
1487 * 2. We have hit a real cycle in the directory hierarchy. In this
1488 * case, we issue a diagnostic message (POSIX requires this) and we
1489 * skip that directory entry.
1492 issue_loop_warning(const char *name
, const char *pathname
, int level
)
1494 struct stat stbuf_link
;
1495 if (lstat(name
, &stbuf_link
) != 0)
1496 stbuf_link
.st_mode
= S_IFREG
;
1498 if (S_ISLNK(stbuf_link
.st_mode
))
1501 _("Symbolic link `%s' is part of a loop in the directory hierarchy; we have already visited the directory to which it points."),
1506 int distance
= 1 + (dir_curr
-level
);
1507 /* We have found an infinite loop. POSIX requires us to
1508 * issue a diagnostic. Usually we won't get to here
1509 * because when the leaf optimisation is on, it will cause
1510 * the subdirectory to be skipped. If /a/b/c/d is a hard
1511 * link to /a/b, then the link count of /a/b/c is 2,
1512 * because the ".." entry of /b/b/c/d points to /a, not
1516 _("Filesystem loop detected; `%s' has the same device number and inode as a directory which is %d %s."),
1520 _("level higher in the filesystem hierarchy") :
1521 _("levels higher in the filesystem hierarchy")));
1525 /* Take a "mode" indicator and fill in the files of 'state'.
1528 digest_mode(mode_t mode
,
1529 const char *pathname
,
1534 /* If we know the type of the directory entry, and it is not a
1535 * symbolic link, we may be able to avoid a stat() or lstat() call.
1539 if (S_ISLNK(mode
) && following_links())
1541 /* mode is wrong because we should have followed the symlink. */
1542 if (get_statinfo(pathname
, name
, pstat
) != 0)
1544 mode
= state
.type
= pstat
->st_mode
;
1545 state
.have_type
= true;
1549 state
.have_type
= true;
1550 pstat
->st_mode
= state
.type
= mode
;
1555 /* Mode is not yet known; may have to stat the file unless we
1556 * can deduce that it is not a directory (which is all we need to
1557 * know at this stage)
1561 state
.have_stat
= false;
1562 state
.have_type
= false;;
1567 if (get_statinfo(pathname
, name
, pstat
) != 0)
1570 /* If -L is in effect and we are dealing with a symlink,
1571 * st_mode is the mode of the pointed-to file, while mode is
1572 * the mode of the directory entry (S_IFLNK). Hence now
1573 * that we have the stat information, override "mode".
1575 state
.type
= pstat
->st_mode
;
1576 state
.have_type
= true;
1586 /* Recursively descend path PATHNAME, applying the predicates.
1587 LEAF is true if PATHNAME is known to be in a directory that has no
1588 more unexamined subdirectories, and therefore it is not a directory.
1589 Knowing this allows us to avoid calling stat as long as possible for
1592 NAME is PATHNAME relative to the current directory. We access NAME
1595 PARENT is the path of the parent of NAME, relative to find's
1598 Return nonzero iff PATHNAME is a directory. */
1601 process_path (char *pathname
, char *name
, boolean leaf
, char *parent
,
1604 struct stat stat_buf
;
1605 static dev_t root_dev
; /* Device ID of current argument pathname. */
1608 /* Assume it is a non-directory initially. */
1609 stat_buf
.st_mode
= 0;
1610 state
.rel_pathname
= name
;
1612 state
.have_stat
= false;
1613 state
.have_type
= false;
1615 if (!digest_mode(mode
, pathname
, name
, &stat_buf
, leaf
))
1618 if (!S_ISDIR (state
.type
))
1620 if (state
.curdepth
>= options
.mindepth
)
1621 apply_predicate (pathname
, &stat_buf
, eval_tree
);
1625 /* From here on, we're working on a directory. */
1628 /* Now we really need to stat the directory, even if we know the
1629 * type, because we need information like struct stat.st_rdev.
1631 if (get_statinfo(pathname
, name
, &stat_buf
) != 0)
1634 state
.have_stat
= true;
1635 mode
= state
.type
= stat_buf
.st_mode
; /* use full info now that we have it. */
1636 state
.stop_at_current_level
=
1637 options
.maxdepth
>= 0
1638 && state
.curdepth
>= options
.maxdepth
;
1640 /* If we've already seen this directory on this branch,
1641 don't descend it again. */
1642 for (i
= 0; i
<= dir_curr
; i
++)
1643 if (stat_buf
.st_ino
== dir_ids
[i
].ino
&&
1644 stat_buf
.st_dev
== dir_ids
[i
].dev
)
1646 state
.stop_at_current_level
= true;
1647 issue_loop_warning(name
, pathname
, i
);
1650 if (dir_alloc
<= ++dir_curr
)
1652 dir_alloc
+= DIR_ALLOC_STEP
;
1653 dir_ids
= (struct dir_id
*)
1654 xrealloc ((char *) dir_ids
, dir_alloc
* sizeof (struct dir_id
));
1656 dir_ids
[dir_curr
].ino
= stat_buf
.st_ino
;
1657 dir_ids
[dir_curr
].dev
= stat_buf
.st_dev
;
1659 if (options
.stay_on_filesystem
)
1661 if (state
.curdepth
== 0)
1662 root_dev
= stat_buf
.st_dev
;
1663 else if (stat_buf
.st_dev
!= root_dev
)
1664 state
.stop_at_current_level
= true;
1667 if (options
.do_dir_first
&& state
.curdepth
>= options
.mindepth
)
1668 apply_predicate (pathname
, &stat_buf
, eval_tree
);
1671 fprintf(stderr
, "pathname = %s, stop_at_current_level = %d\n",
1672 pathname
, state
.stop_at_current_level
);
1675 if (state
.stop_at_current_level
== false)
1676 /* Scan directory on disk. */
1677 process_dir (pathname
, name
, strlen (pathname
), &stat_buf
, parent
);
1679 if (options
.do_dir_first
== false && state
.curdepth
>= options
.mindepth
)
1681 /* The fields in 'state' are now out of date. Correct them.
1683 if (!digest_mode(mode
, pathname
, name
, &stat_buf
, leaf
))
1688 at_top(pathname
, mode
, &stat_buf
, do_process_predicate
);
1692 do_process_predicate(pathname
, name
, mode
, &stat_buf
);
1701 /* Examine the predicate list for instances of -execdir or -okdir
1702 * which have been terminated with '+' (build argument list) rather
1703 * than ';' (singles only). If there are any, run them (this will
1704 * have no effect if there are no arguments waiting).
1707 complete_pending_execdirs(struct predicate
*p
)
1709 #if defined(NEW_EXEC)
1713 complete_pending_execdirs(p
->pred_left
);
1715 if (p
->pred_func
== pred_execdir
|| p
->pred_func
== pred_okdir
)
1717 /* It's an exec-family predicate. p->args.exec_val is valid. */
1718 if (p
->args
.exec_vec
.multiple
)
1720 struct exec_val
*execp
= &p
->args
.exec_vec
;
1722 /* This one was terminated by '+' and so might have some
1723 * left... Run it if necessary.
1725 if (execp
->state
.todo
)
1727 /* There are not-yet-executed arguments. */
1728 launch (&execp
->ctl
, &execp
->state
);
1733 complete_pending_execdirs(p
->pred_right
);
1735 /* nothing to do. */
1740 /* Examine the predicate list for instances of -exec which have been
1741 * terminated with '+' (build argument list) rather than ';' (singles
1742 * only). If there are any, run them (this will have no effect if
1743 * there are no arguments waiting).
1746 complete_pending_execs(struct predicate
*p
)
1748 #if defined(NEW_EXEC)
1752 complete_pending_execs(p
->pred_left
);
1754 /* It's an exec-family predicate then p->args.exec_val is valid
1755 * and we can check it.
1757 if (p
->pred_func
== pred_exec
&& p
->args
.exec_vec
.multiple
)
1759 struct exec_val
*execp
= &p
->args
.exec_vec
;
1761 /* This one was terminated by '+' and so might have some
1762 * left... Run it if necessary. Set state.exit_status if
1763 * there are any problems.
1765 if (execp
->state
.todo
)
1767 /* There are not-yet-executed arguments. */
1768 launch (&execp
->ctl
, &execp
->state
);
1772 complete_pending_execs(p
->pred_right
);
1774 /* nothing to do. */
1780 /* Scan directory PATHNAME and recurse through process_path for each entry.
1782 PATHLEN is the length of PATHNAME.
1784 NAME is PATHNAME relative to the current directory.
1786 STATP is the results of *options.xstat on it.
1788 PARENT is the path of the parent of NAME, relative to find's
1789 starting directory. */
1792 process_dir (char *pathname
, char *name
, int pathlen
, struct stat
*statp
, char *parent
)
1794 int subdirs_left
; /* Number of unexamined subdirs in PATHNAME. */
1795 int idx
; /* Which entry are we on? */
1796 struct stat stat_buf
;
1798 struct savedir_dirinfo
*dirinfo
;
1799 subdirs_left
= statp
->st_nlink
- 2; /* Account for name and ".". */
1802 dirinfo
= xsavedir(name
, 0);
1805 if (dirinfo
== NULL
)
1808 error (0, errno
, "%s", pathname
);
1809 state
.exit_status
= 1;
1813 register char *namep
; /* Current point in `name_space'. */
1814 char *cur_path
; /* Full path of each file to process. */
1815 char *cur_name
; /* Base name of each file to process. */
1816 unsigned cur_path_size
; /* Bytes allocated for `cur_path'. */
1817 register unsigned file_len
; /* Length of each path to process. */
1818 register unsigned pathname_len
; /* PATHLEN plus trailing '/'. */
1819 boolean did_stat
= false;
1821 if (pathname
[pathlen
- 1] == '/')
1822 pathname_len
= pathlen
+ 1; /* For '\0'; already have '/'. */
1824 pathname_len
= pathlen
+ 2; /* For '/' and '\0'. */
1828 /* We're about to leave the directory. If there are any
1829 * -execdir argument lists which have been built but have not
1830 * yet been processed, do them now because they must be done in
1831 * the same directory.
1833 complete_pending_execdirs(eval_tree
);
1835 if (strcmp (name
, "."))
1837 enum SafeChdirStatus status
= safely_chdir (name
, TraversingDown
, &stat_buf
, SymlinkHandleDefault
, &did_stat
);
1841 /* If there had been a change but wd_sanity_check()
1842 * accepted it, we need to accept that on the
1843 * way back up as well, so modify our record
1844 * of what we think we should see later.
1845 * If there was no change, the assignments are a no-op.
1847 * However, before performing the assignment, we need to
1848 * check that we have the stat information. If O_NOFOLLOW
1849 * is available, safely_chdir() will not have needed to use
1850 * stat(), and so stat_buf will just contain random data.
1854 /* If there is a link we need to follow it. Hence
1855 * the direct call to stat() not through (options.xstat)
1857 if (0 != stat(".", &stat_buf
))
1858 break; /* skip the assignment. */
1860 dir_ids
[dir_curr
].dev
= stat_buf
.st_dev
;
1861 dir_ids
[dir_curr
].ino
= stat_buf
.st_ino
;
1865 case SafeChdirFailWouldBeUnableToReturn
:
1866 error (0, errno
, ".");
1867 state
.exit_status
= 1;
1870 case SafeChdirFailNonexistent
:
1871 case SafeChdirFailStat
:
1872 case SafeChdirFailSymlink
:
1873 case SafeChdirFailNotDir
:
1874 case SafeChdirFailChdirFailed
:
1875 error (0, errno
, "%s", pathname
);
1876 state
.exit_status
= 1;
1881 for (idx
=0; idx
< dirinfo
->size
; ++idx
)
1883 /* savedirinfo() may return dirinfo=NULL if extended information
1886 mode_t mode
= (dirinfo
->entries
[idx
].flags
& SavedirHaveFileType
) ?
1887 dirinfo
->entries
[idx
].type_info
: 0;
1888 namep
= dirinfo
->entries
[idx
].name
;
1890 /* Append this directory entry's name to the path being searched. */
1891 file_len
= pathname_len
+ strlen (namep
);
1892 if (file_len
> cur_path_size
)
1894 while (file_len
> cur_path_size
)
1895 cur_path_size
+= 1024;
1898 cur_path
= xmalloc (cur_path_size
);
1899 strcpy (cur_path
, pathname
);
1900 cur_path
[pathname_len
- 2] = '/';
1902 cur_name
= cur_path
+ pathname_len
- 1;
1903 strcpy (cur_name
, namep
);
1906 if (!options
.no_leaf_check
)
1908 if (mode
&& S_ISDIR(mode
) && (subdirs_left
== 0))
1910 /* This is a subdirectory, but the number of directories we
1911 * have found now exceeds the number we would expect given
1912 * the hard link count on the parent. This is likely to be
1913 * a bug in the filesystem driver (e.g. Linux's
1914 * /proc filesystem) or may just be a fact that the OS
1915 * doesn't really handle hard links with Unix semantics.
1916 * In the latter case, -noleaf should be used routinely.
1918 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."),
1920 state
.exit_status
= 1; /* We know the result is wrong, now */
1921 options
.no_leaf_check
= true; /* Don't make same
1923 subdirs_left
= 1; /* band-aid for this iteration. */
1926 /* Normal case optimization. On normal Unix
1927 filesystems, a directory that has no subdirectories
1928 has two links: its name, and ".". Any additional
1929 links are to the ".." entries of its subdirectories.
1930 Once we have processed as many subdirectories as
1931 there are additional links, we know that the rest of
1932 the entries are non-directories -- in other words,
1934 subdirs_left
-= process_path (cur_path
, cur_name
,
1935 subdirs_left
== 0, pathname
,
1940 /* There might be weird (e.g., CD-ROM or MS-DOS) filesystems
1941 mounted, which don't have Unix-like directory link counts. */
1942 process_path (cur_path
, cur_name
, false, pathname
, mode
);
1949 /* We're about to leave the directory. If there are any
1950 * -execdir argument lists which have been built but have not
1951 * yet been processed, do them now because they must be done in
1952 * the same directory.
1954 complete_pending_execdirs(eval_tree
);
1957 if (strcmp (name
, "."))
1959 enum SafeChdirStatus status
;
1961 boolean did_stat
= false;
1963 /* We could go back and do the next command-line arg
1964 instead, maybe using longjmp. */
1966 boolean deref
= following_links() ? true : false;
1968 if ( (state
.curdepth
>0) && !deref
)
1976 status
= safely_chdir (dir
, TraversingUp
, &stat_buf
, SymlinkHandleDefault
, &did_stat
);
1982 case SafeChdirFailWouldBeUnableToReturn
:
1983 error (1, errno
, ".");
1986 case SafeChdirFailNonexistent
:
1987 case SafeChdirFailStat
:
1988 case SafeChdirFailSymlink
:
1989 case SafeChdirFailNotDir
:
1990 case SafeChdirFailChdirFailed
:
1991 error (1, errno
, "%s", pathname
);
1997 did
.dev
= dir_ids
[dir_curr
-1].dev
;
1998 did
.ino
= dir_ids
[dir_curr
-1].ino
;
2002 did
.dev
= starting_stat_buf
.st_dev
;
2003 did
.ino
= starting_stat_buf
.st_ino
;
2009 free_dirinfo(dirinfo
);
2013 /* Return true if there are no predicates with no_default_print in
2014 predicate list PRED, false if there are any.
2015 Returns true if default print should be performed */
2018 default_prints (struct predicate
*pred
)
2020 while (pred
!= NULL
)
2022 if (pred
->no_default_print
)
2024 pred
= pred
->pred_next
;