Fix for starting point /foo/bar/baz where bar is a symlink but baz is not - we should...
[findutils.git] / find / find.c
blobd2f536295509ac8c0f0ff075e603088a86a4e2a8
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)
7 any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
17 USA.*/
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>. */
27 #include "defs.h"
29 #define USE_SAFE_CHDIR 1
31 #include <errno.h>
32 #include <assert.h>
35 #ifdef HAVE_FCNTL_H
36 #include <fcntl.h>
37 #else
38 #include <sys/file.h>
39 #endif
41 #include "../gnulib/lib/xalloc.h"
42 #include "../gnulib/lib/human.h"
43 #include "../gnulib/lib/canonicalize.h"
44 #include "closeout.h"
45 #include <modetype.h>
46 #include "savedirinfo.h"
47 #include "buildcmd.h"
48 #include "dirname.h"
50 #ifdef HAVE_LOCALE_H
51 #include <locale.h>
52 #endif
54 #if ENABLE_NLS
55 # include <libintl.h>
56 # define _(Text) gettext (Text)
57 #else
58 # define _(Text) Text
59 #define textdomain(Domain)
60 #define bindtextdomain(Package, Directory)
61 #endif
62 #ifdef gettext_noop
63 # define N_(String) gettext_noop (String)
64 #else
65 /* See locate.c for explanation as to why not use (String) */
66 # define N_(String) String
67 #endif
69 #define apply_predicate(pathname, stat_buf_ptr, node) \
70 (*(node)->pred_func)((pathname), (stat_buf_ptr), (node))
73 static void init_mounted_dev_list(void);
74 static void process_top_path PARAMS((char *pathname, mode_t mode));
75 static int process_path PARAMS((char *pathname, char *name, boolean leaf, char *parent, mode_t type));
76 static void process_dir PARAMS((char *pathname, char *name, int pathlen, struct stat *statp, char *parent));
78 static void complete_pending_execdirs(struct predicate *p);
79 static void complete_pending_execs (struct predicate *p);
83 static boolean default_prints PARAMS((struct predicate *pred));
85 /* Name this program was run with. */
86 char *program_name;
88 /* All predicates for each path to process. */
89 struct predicate *predicates;
91 /* The last predicate allocated. */
92 struct predicate *last_pred;
94 /* The root of the evaluation tree. */
95 static struct predicate *eval_tree = NULL;
98 struct options options;
99 struct state state;
101 /* The full path of the initial working directory, or "." if
102 STARTING_DESC is nonnegative. */
103 char const *starting_dir = ".";
105 /* A file descriptor open to the initial working directory.
106 Doing it this way allows us to work when the i.w.d. has
107 unreadable parents. */
108 int starting_desc;
110 /* The stat buffer of the initial working directory. */
111 struct stat starting_stat_buf;
113 enum ChdirSymlinkHandling
115 SymlinkHandleDefault, /* Normally the right choice */
116 SymlinkFollowOk /* see comment in process_top_path() */
120 enum TraversalDirection
122 TraversingUp,
123 TraversingDown
128 following_links(void)
130 switch (options.symlink_handling)
132 case SYMLINK_ALWAYS_DEREF:
133 return 1;
134 case SYMLINK_DEREF_ARGSONLY:
135 return (state.curdepth == 0);
136 case SYMLINK_NEVER_DEREF:
137 default:
138 return 0;
143 static int
144 fallback_stat(const char *name, struct stat *p, int prev_rv)
146 /* Our original stat() call failed. Perhaps we can't follow a
147 * symbolic link. If that might be the problem, lstat() the link.
148 * Otherwise, admit defeat.
150 switch (errno)
152 case ENOENT:
153 case ENOTDIR:
154 #ifdef DEBUG_STAT
155 fprintf(stderr, "fallback_stat(): stat(%s) failed; falling back on lstat()\n", name);
156 #endif
157 return lstat(name, p);
159 case EACCES:
160 case EIO:
161 case ELOOP:
162 case ENAMETOOLONG:
163 #ifdef EOVERFLOW
164 case EOVERFLOW: /* EOVERFLOW is not #defined on UNICOS. */
165 #endif
166 default:
167 return prev_rv;
172 /* optionh_stat() implements the stat operation when the -H option is
173 * in effect.
175 * If the item to be examined is a command-line argument, we follow
176 * symbolic links. If the stat() call fails on the command-line item,
177 * we fall back on the properties of the symbolic link.
179 * If the item to be examined is not a command-line argument, we
180 * examine the link itself.
182 int
183 optionh_stat(const char *name, struct stat *p)
185 if (0 == state.curdepth)
187 /* This file is from the command line; deference the link (if it
188 * is a link).
190 int rv = stat(name, p);
191 if (0 == rv)
192 return 0; /* success */
193 else
194 return fallback_stat(name, p, rv);
196 else
198 /* Not a file on the command line; do not derefernce the link.
200 return lstat(name, p);
204 /* optionl_stat() implements the stat operation when the -L option is
205 * in effect. That option makes us examine the thing the symbolic
206 * link points to, not the symbolic link itself.
208 int
209 optionl_stat(const char *name, struct stat *p)
211 int rv = stat(name, p);
212 if (0 == rv)
213 return 0; /* normal case. */
214 else
215 return fallback_stat(name, p, rv);
218 /* optionp_stat() implements the stat operation when the -P option is
219 * in effect (this is also the default). That option makes us examine
220 * the symbolic link itself, not the thing it points to.
222 int
223 optionp_stat(const char *name, struct stat *p)
225 return lstat(name, p);
228 #ifdef DEBUG_STAT
229 static uintmax_t stat_count = 0u;
231 static int
232 debug_stat (const char *file, struct stat *bufp)
234 ++stat_count;
235 fprintf (stderr, "debug_stat (%s)\n", file);
236 switch (options.symlink_handling)
238 case SYMLINK_ALWAYS_DEREF:
239 return optionl_stat(file, bufp);
240 case SYMLINK_DEREF_ARGSONLY:
241 return optionh_stat(file, bufp);
242 case SYMLINK_NEVER_DEREF:
243 return optionp_stat(file, bufp);
246 #endif /* DEBUG_STAT */
248 void
249 set_follow_state(enum SymlinkOption opt)
251 switch (opt)
253 case SYMLINK_ALWAYS_DEREF: /* -L */
254 options.xstat = optionl_stat;
255 options.no_leaf_check = true;
256 break;
258 case SYMLINK_NEVER_DEREF: /* -P (default) */
259 options.xstat = optionp_stat;
260 /* Can't turn no_leaf_check off because the user might have specified
261 * -noleaf anyway
263 break;
265 case SYMLINK_DEREF_ARGSONLY: /* -H */
266 options.xstat = optionh_stat;
267 options.no_leaf_check = true;
270 options.symlink_handling = opt;
272 /* For DBEUG_STAT, the choice is made at runtime within debug_stat()
273 * by checking the contents of the symlink_handling variable.
275 #if defined(DEBUG_STAT)
276 options.xstat = debug_stat;
277 #endif /* !DEBUG_STAT */
281 /* Complete any outstanding commands.
283 void
284 cleanup(void)
286 if (eval_tree)
288 complete_pending_execs(eval_tree);
289 complete_pending_execdirs(eval_tree);
293 /* Get the stat information for a file, if it is
294 * not already known.
297 get_statinfo (const char *pathname, const char *name, struct stat *p)
299 if (!state.have_stat && (*options.xstat) (name, p) != 0)
301 if (!options.ignore_readdir_race || (errno != ENOENT) )
303 error (0, errno, "%s", pathname);
304 state.exit_status = 1;
306 return -1;
308 state.have_stat = true;
309 state.have_type = true;
310 state.type = p->st_mode;
311 return 0;
314 /* Get the stat/type information for a file, if it is
315 * not already known.
318 get_info (const char *pathname,
319 const char *name,
320 struct stat *p,
321 struct predicate *pred_ptr)
323 /* If we need the full stat info, or we need the type info but don't
324 * already have it, stat the file now.
326 (void) name;
327 if (pred_ptr->need_stat)
329 return get_statinfo(pathname, state.rel_pathname, p);
331 if ((pred_ptr->need_type && (0 == state.have_type)))
333 return get_statinfo(pathname, state.rel_pathname, p);
335 return 0;
339 main (int argc, char **argv)
341 int i;
342 PFB parse_function; /* Pointer to the function which parses. */
343 struct predicate *cur_pred;
344 char *predicate_name; /* Name of predicate being parsed. */
345 int end_of_leading_options = 0; /* First arg after any -H/-L etc. */
346 program_name = argv[0];
348 #ifdef HAVE_SETLOCALE
349 setlocale (LC_ALL, "");
350 #endif
351 bindtextdomain (PACKAGE, LOCALEDIR);
352 textdomain (PACKAGE);
353 atexit (close_stdout);
356 if (isatty(0))
358 options.warnings = true;
360 else
362 options.warnings = false;
366 predicates = NULL;
367 last_pred = NULL;
368 options.do_dir_first = true;
369 options.maxdepth = options.mindepth = -1;
370 options.start_time = time (NULL);
371 options.cur_day_start = options.start_time - DAYSECS;
372 options.full_days = false;
373 options.stay_on_filesystem = false;
374 options.ignore_readdir_race = false;
376 state.exit_status = 0;
378 #if defined(DEBUG_STAT)
379 options.xstat = debug_stat;
380 #endif /* !DEBUG_STAT */
382 if (getenv("POSIXLY_CORRECT"))
383 options.output_block_size = 512;
384 else
385 options.output_block_size = 1024;
387 if (getenv("FIND_BLOCK_SIZE"))
389 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"));
392 options.no_leaf_check = false;
393 set_follow_state(SYMLINK_NEVER_DEREF); /* The default is equivalent to -P. */
395 init_mounted_dev_list();
397 #ifdef DEBUG
398 fprintf (stderr, "cur_day_start = %s", ctime (&options.cur_day_start));
399 #endif /* DEBUG */
401 /* Check for -P, -H or -L options. */
402 for (i=1; (end_of_leading_options = i) < argc; ++i)
404 if (0 == strcmp("-H", argv[i]))
406 /* Meaning: dereference symbolic links on command line, but nowhere else. */
407 set_follow_state(SYMLINK_DEREF_ARGSONLY);
409 else if (0 == strcmp("-L", argv[i]))
411 /* Meaning: dereference all symbolic links. */
412 set_follow_state(SYMLINK_ALWAYS_DEREF);
414 else if (0 == strcmp("-P", argv[i]))
416 /* Meaning: never dereference symbolic links (default). */
417 set_follow_state(SYMLINK_NEVER_DEREF);
419 else if (0 == strcmp("--", argv[i]))
421 /* -- signifies the end of options. */
422 end_of_leading_options = i+1; /* Next time start with the next option */
423 break;
425 else
427 /* Hmm, must be one of
428 * (a) A path name
429 * (b) A predicate
431 end_of_leading_options = i; /* Next time start with this option */
432 break;
436 /* We are now processing the part of the "find" command line
437 * after the -H/-L options (if any).
440 /* fprintf(stderr, "rest: optind=%ld\n", (long)optind); */
442 /* Find where in ARGV the predicates begin. */
443 for (i = end_of_leading_options; i < argc && strchr ("-!(),", argv[i][0]) == NULL; i++)
445 /* fprintf(stderr, "Looks like %s is not a predicate\n", argv[i]); */
446 /* Do nothing. */ ;
449 /* Enclose the expression in `( ... )' so a default -print will
450 apply to the whole expression. */
451 parse_open (argv, &argc);
452 /* Build the input order list. */
453 while (i < argc)
455 if (strchr ("-!(),", argv[i][0]) == NULL)
456 usage (_("paths must precede expression"));
457 predicate_name = argv[i];
458 parse_function = find_parser (predicate_name);
459 if (parse_function == NULL)
460 /* Command line option not recognized */
461 error (1, 0, _("invalid predicate `%s'"), predicate_name);
462 i++;
463 if (!(*parse_function) (argv, &i))
465 if (argv[i] == NULL)
466 /* Command line option requires an argument */
467 error (1, 0, _("missing argument to `%s'"), predicate_name);
468 else
469 error (1, 0, _("invalid argument `%s' to `%s'"),
470 argv[i], predicate_name);
473 if (predicates->pred_next == NULL)
475 /* No predicates that do something other than set a global variable
476 were given; remove the unneeded initial `(' and add `-print'. */
477 cur_pred = predicates;
478 predicates = last_pred = predicates->pred_next;
479 free ((char *) cur_pred);
480 parse_print (argv, &argc);
482 else if (!default_prints (predicates->pred_next))
484 /* One or more predicates that produce output were given;
485 remove the unneeded initial `('. */
486 cur_pred = predicates;
487 predicates = predicates->pred_next;
488 free ((char *) cur_pred);
490 else
492 /* `( user-supplied-expression ) -print'. */
493 parse_close (argv, &argc);
494 parse_print (argv, &argc);
497 #ifdef DEBUG
498 fprintf (stderr, _("Predicate List:\n"));
499 print_list (stderr, predicates);
500 #endif /* DEBUG */
502 /* Done parsing the predicates. Build the evaluation tree. */
503 cur_pred = predicates;
504 eval_tree = get_expr (&cur_pred, NO_PREC);
506 /* Check if we have any left-over predicates (this fixes
507 * Debian bug #185202).
509 if (cur_pred != NULL)
511 error (1, 0, _("unexpected extra predicate"));
514 #ifdef DEBUG
515 fprintf (stderr, _("Eval Tree:\n"));
516 print_tree (stderr, eval_tree, 0);
517 #endif /* DEBUG */
519 /* Rearrange the eval tree in optimal-predicate order. */
520 opt_expr (&eval_tree);
522 /* Determine the point, if any, at which to stat the file. */
523 mark_stat (eval_tree);
524 /* Determine the point, if any, at which to determine file type. */
525 mark_type (eval_tree);
527 #ifdef DEBUG
528 fprintf (stderr, _("Optimized Eval Tree:\n"));
529 print_tree (stderr, eval_tree, 0);
530 fprintf (stderr, _("Optimized command line:\n"));
531 print_optlist(stderr, eval_tree);
532 fprintf(stderr, "\n");
533 #endif /* DEBUG */
535 starting_desc = open (".", O_RDONLY);
536 if (0 <= starting_desc && fchdir (starting_desc) != 0)
538 close (starting_desc);
539 starting_desc = -1;
541 if (starting_desc < 0)
543 starting_dir = xgetcwd ();
544 if (! starting_dir)
545 error (1, errno, _("cannot get current directory"));
547 if ((*options.xstat) (".", &starting_stat_buf) != 0)
548 error (1, errno, _("cannot get current directory"));
550 /* If no paths are given, default to ".". */
551 for (i = end_of_leading_options; i < argc && strchr ("-!(),", argv[i][0]) == NULL; i++)
553 process_top_path (argv[i], 0);
556 /* If there were no path arguments, default to ".". */
557 if (i == end_of_leading_options)
560 * We use a temporary variable here because some actions modify
561 * the path temporarily. Hence if we use a string constant,
562 * we get a coredump. The best example of this is if we say
563 * "find -printf %H" (note, not "find . -printf %H").
565 char defaultpath[2] = ".";
566 process_top_path (defaultpath, 0);
569 /* If "-exec ... {} +" has been used, there may be some
570 * partially-full command lines which have been built,
571 * but which are not yet complete. Execute those now.
573 cleanup();
574 return state.exit_status;
578 static char *
579 specific_dirname(const char *dir)
581 char dirname[1024];
583 if (0 == strcmp(".", dir))
585 /* OK, what's '.'? */
586 if (NULL != getcwd(dirname, sizeof(dirname)))
588 return strdup(dirname);
590 else
592 return strdup(dir);
595 else
597 char *result = canonicalize_filename_mode(dir, CAN_EXISTING);
598 if (NULL == result)
599 return strdup(dir);
600 else
601 return result;
605 static dev_t *mounted_devices = NULL;
606 static size_t num_mounted_devices = 0u;
609 static void
610 init_mounted_dev_list()
612 assert(NULL == mounted_devices);
613 assert(0 == num_mounted_devices);
614 mounted_devices = get_mounted_devices(&num_mounted_devices);
617 static void
618 refresh_mounted_dev_list(void)
620 if (mounted_devices)
622 free(mounted_devices);
623 mounted_devices = 0;
625 num_mounted_devices = 0u;
626 init_mounted_dev_list();
630 /* Search for device DEV in the array LIST, which is of size N. */
631 static int
632 dev_present(dev_t dev, const dev_t *list, size_t n)
634 if (list)
636 while (n-- > 0u)
638 if ( (*list++) == dev )
639 return 1;
642 return 0;
645 enum MountPointStateChange
647 MountPointRecentlyMounted,
648 MountPointRecentlyUnmounted,
649 MountPointStateUnchanged
654 static enum MountPointStateChange
655 get_mount_state(dev_t newdev)
657 int new_is_present, new_was_present;
659 new_was_present = dev_present(newdev, mounted_devices, num_mounted_devices);
660 refresh_mounted_dev_list();
661 new_is_present = dev_present(newdev, mounted_devices, num_mounted_devices);
663 if (new_was_present == new_is_present)
664 return MountPointStateUnchanged;
665 else if (new_is_present)
666 return MountPointRecentlyMounted;
667 else
668 return MountPointRecentlyUnmounted;
672 /* Return non-zero if FS is the name of a filesystem that is likely to
673 * be automounted
675 static int
676 fs_likely_to_be_automounted(const char *fs)
678 return ( (0==strcmp(fs, "nfs")) || (0==strcmp(fs, "autofs")) || (0==strcmp(fs, "subfs")));
681 enum WdSanityCheckFatality
683 FATAL_IF_SANITY_CHECK_FAILS,
684 NON_FATAL_IF_SANITY_CHECK_FAILS
688 /* Examine the results of the stat() of a directory from before we
689 * entered or left it, with the results of stat()ing it afterward. If
690 * these are different, the filesystem tree has been modified while we
691 * were traversing it. That might be an attempt to use a race
692 * condition to persuade find to do something it didn't intend
693 * (e.g. an attempt by an ordinary user to exploit the fact that root
694 * sometimes runs find on the whole filesystem). However, this can
695 * also happen if automount is running (certainly on Solaris). With
696 * automount, moving into a directory can cause a filesystem to be
697 * mounted there.
699 * To cope sensibly with this, we will raise an error if we see the
700 * device number change unless we are chdir()ing into a subdirectory,
701 * and the directory we moved into has been mounted or unmounted "recently".
702 * Here "recently" means since we started "find" or we last re-read
703 * the /etc/mnttab file.
705 * If the device number does not change but the inode does, that is a
706 * problem.
708 * If the device number and inode are both the same, we are happy.
710 * If a filesystem is (un)mounted as we chdir() into the directory, that
711 * may mean that we're now examining a section of the filesystem that might
712 * have been excluded from consideration (via -prune or -quit for example).
713 * Hence we print a warning message to indicate that the output of find
714 * might be inconsistent due to the change in the filesystem.
716 static boolean
717 wd_sanity_check(const char *thing_to_stat,
718 const char *program_name,
719 const char *what,
720 dev_t old_dev,
721 ino_t old_ino,
722 struct stat *newinfo,
723 int parent,
724 int line_no,
725 enum TraversalDirection direction,
726 enum WdSanityCheckFatality isfatal,
727 boolean *changed) /* output parameter */
729 const char *fstype;
730 char *specific_what = NULL;
731 int silent = 0;
733 *changed = false;
735 if ((*options.xstat) (".", newinfo) != 0)
736 error (1, errno, "%s", thing_to_stat);
738 if (old_dev != newinfo->st_dev)
740 *changed = true;
741 specific_what = specific_dirname(what);
742 fstype = filesystem_type(newinfo);
743 silent = fs_likely_to_be_automounted(fstype);
745 /* This condition is rare, so once we are here it is
746 * reasonable to perform an expensive computation to
747 * determine if we should continue or fail.
749 if (TraversingDown == direction)
751 /* We stat()ed a directory, chdir()ed into it (we know this
752 * since direction is TraversingDown), stat()ed it again,
753 * and noticed that the device numbers are different. Check
754 * if the filesystem was recently mounted.
756 * If it was, it looks like chdir()ing into the directory
757 * caused a filesystem to be mounted. Maybe automount is
758 * running. Anyway, that's probably OK - but it happens
759 * only when we are moving downward.
761 * We also allow for the possibility that a similar thing
762 * has happened with the unmounting of a filesystem. This
763 * is much rarer, as it relies on an automounter timeout
764 * occurring at exactly the wrong moment.
766 enum MountPointStateChange transition = get_mount_state(newinfo->st_dev);
767 switch (transition)
769 case MountPointRecentlyUnmounted:
770 isfatal = NON_FATAL_IF_SANITY_CHECK_FAILS;
771 if (!silent)
773 error (0, 0,
774 _("Warning: filesystem %s has recently been unmounted."),
775 specific_what);
777 break;
779 case MountPointRecentlyMounted:
780 isfatal = NON_FATAL_IF_SANITY_CHECK_FAILS;
781 if (!silent)
783 error (0, 0,
784 _("Warning: filesystem %s has recently been mounted."),
785 specific_what);
787 break;
789 case MountPointStateUnchanged:
790 /* leave isfatal as it is */
791 break;
795 if (FATAL_IF_SANITY_CHECK_FAILS == isfatal)
797 fstype = filesystem_type(newinfo);
798 error (1, 0,
799 _("%s%s changed during execution of %s (old device number %ld, new device number %ld, filesystem type is %s) [ref %ld]"),
800 specific_what,
801 parent ? "/.." : "",
802 program_name,
803 (long) old_dev,
804 (long) newinfo->st_dev,
805 fstype,
806 line_no);
807 /*NOTREACHED*/
808 return false;
810 else
812 /* Since the device has changed under us, the inode number
813 * will almost certainly also be different. However, we have
814 * already decided that this is not a problem. Hence we return
815 * without checking the inode number.
817 free(specific_what);
818 return true;
822 /* Device number was the same, check if the inode has changed. */
823 if (old_ino != newinfo->st_ino)
825 *changed = true;
826 specific_what = specific_dirname(what);
827 fstype = filesystem_type(newinfo);
829 error ((isfatal == FATAL_IF_SANITY_CHECK_FAILS) ? 1 : 0,
830 0, /* no relevant errno value */
831 _("%s%s changed during execution of %s (old inode number %ld, new inode number %ld, filesystem type is %s) [ref %ld]"),
832 specific_what,
833 parent ? "/.." : "",
834 program_name,
835 (long) old_ino,
836 (long) newinfo->st_ino,
837 fstype,
838 line_no);
839 free(specific_what);
840 return false;
843 return true;
846 enum SafeChdirStatus
848 SafeChdirOK,
849 SafeChdirFailSymlink,
850 SafeChdirFailNotDir,
851 SafeChdirFailStat,
852 SafeChdirFailWouldBeUnableToReturn,
853 SafeChdirFailChdirFailed,
854 SafeChdirFailNonexistent
857 /* Safely perform a change in directory.
860 static enum SafeChdirStatus
861 safely_chdir(const char *dest,
862 enum TraversalDirection direction,
863 struct stat *statbuf_dest,
864 enum ChdirSymlinkHandling symlink_handling)
866 struct stat statbuf_arrived;
867 int rv, dotfd=-1;
868 int saved_errno; /* specific_dirname() changes errno. */
869 char *name = NULL;
870 boolean rv_set = false;
872 /* We're about to leave a directory. If there are any -execdir
873 * argument lists which have been built but have not yet been
874 * processed, do them now because they must be done in the same
875 * directory.
877 complete_pending_execdirs(eval_tree);
880 saved_errno = errno = 0;
881 dotfd = open(".", O_RDONLY);
882 if (dotfd >= 0)
884 /* Stat the directory we're going to. */
885 if (0 == options.xstat(dest, statbuf_dest))
887 #ifdef S_ISLNK
888 /* symlink_handling might be set to SymlinkFollowOk, which
889 * would allow us to chdir() into a symbolic link. This is
890 * only useful for the case where the directory we're
891 * chdir()ing into is the basename of a command line
892 * argument, for example where "foo/bar/baz" is specified on
893 * the command line. When -P is in effect (the default),
894 * baz will not be followed if it is a symlink, but if bar
895 * is a symlink, it _should_ be followed. Hence we need the
896 * ability to override the policy set by following_links().
898 if (!following_links() && S_ISLNK(statbuf_dest->st_mode))
900 /* We're not supposed to be following links, but this is
901 * a link. Check symlink_handling to see if we should
902 * make a special exception.
904 if (symlink_handling == SymlinkFollowOk)
906 /* We need to re-stat() the file so that the
907 * sanity check can pass.
909 if (0 != stat(dest, statbuf_dest))
911 rv = SafeChdirFailNonexistent;
912 rv_set = true;
913 saved_errno = errno;
914 goto fail;
917 else
919 /* Not following symlinks, so the attempt to
920 * chdir() into a symlink should be prevented.
922 rv = SafeChdirFailSymlink;
923 rv_set = true;
924 saved_errno = 0; /* silence the error message */
925 goto fail;
928 #endif
929 #ifdef S_ISDIR
930 /* Although the immediately following chdir() would detect
931 * the fact that this is not a directory for us, this would
932 * result in an extra system call that fails. Anybody
933 * examining the system-call trace should ideally not be
934 * concerned that something is actually failing.
936 if (!S_ISDIR(statbuf_dest->st_mode))
938 rv = SafeChdirFailNotDir;
939 rv_set = true;
940 saved_errno = 0; /* silence the error message */
941 goto fail;
943 #endif
944 #ifdef DEBUG_STAT
945 fprintf(stderr, "safely_chdir(): chdir(\"%s\")\n", dest);
946 #endif
947 if (0 == chdir(dest))
949 /* check we ended up where we wanted to go */
950 boolean changed = false;
951 wd_sanity_check(".", program_name, ".",
952 statbuf_dest->st_dev,
953 statbuf_dest->st_ino,
954 &statbuf_arrived,
955 0, __LINE__, direction,
956 FATAL_IF_SANITY_CHECK_FAILS,
957 &changed);
958 close(dotfd);
959 return SafeChdirOK;
961 else
963 saved_errno = errno;
964 if (ENOENT == saved_errno)
966 rv = SafeChdirFailNonexistent;
967 rv_set = true;
968 if (options.ignore_readdir_race)
969 errno = 0; /* don't issue err msg */
970 else
971 name = specific_dirname(dest);
973 else if (ENOTDIR == saved_errno)
975 /* This can happen if the we stat a directory,
976 * and then filesystem activity changes it into
977 * a non-directory.
979 saved_errno = 0; /* don't issue err msg */
980 rv = SafeChdirFailNotDir;
981 rv_set = true;
983 else
985 rv = SafeChdirFailChdirFailed;
986 rv_set = true;
987 name = specific_dirname(dest);
989 goto fail;
992 else
994 saved_errno = errno;
995 rv = SafeChdirFailStat;
996 rv_set = true;
997 name = specific_dirname(dest);
998 if ( (ENOENT == saved_errno) || (0 == state.curdepth))
999 saved_errno = 0; /* don't issue err msg */
1000 goto fail;
1003 else
1005 /* We do not have read permissions on "." */
1006 rv = SafeChdirFailWouldBeUnableToReturn;
1007 rv_set = true;
1008 goto fail;
1011 saved_errno = 0;
1013 /* We use the same exit path for successs or failure.
1014 * which has occurred is recorded in RV.
1016 fail:
1017 if (saved_errno)
1019 errno = saved_errno;
1021 /* do not call error() as this would result in a duplicate error message
1022 * when the caller does the same thing.
1026 free(name);
1027 name = NULL;
1029 if (dotfd >= 0)
1031 close(dotfd);
1032 dotfd = -1;
1034 assert(rv_set);
1035 return rv;
1039 /* Safely go back to the starting directory. */
1040 static void
1041 chdir_back (void)
1043 struct stat stat_buf;
1044 boolean dummy;
1046 if (starting_desc < 0)
1048 #ifdef DEBUG_STAT
1049 fprintf(stderr, "chdir_back(): chdir(\"%s\")\n", starting_dir);
1050 #endif
1051 if (chdir (starting_dir) != 0)
1052 error (1, errno, "%s", starting_dir);
1054 wd_sanity_check(starting_dir,
1055 program_name,
1056 starting_dir,
1057 starting_stat_buf.st_dev,
1058 starting_stat_buf.st_ino,
1059 &stat_buf, 0, __LINE__,
1060 TraversingUp,
1061 FATAL_IF_SANITY_CHECK_FAILS,
1062 &dummy);
1064 else
1066 #ifdef DEBUG_STAT
1067 fprintf(stderr, "chdir_back(): chdir(<starting-point>)\n");
1068 #endif
1069 if (fchdir (starting_desc) != 0)
1070 error (1, errno, "%s", starting_dir);
1074 /* Descend PATHNAME, which is a command-line argument.
1075 Actions like -execdir assume that we are in the
1076 parent directory of the file we're examining,
1077 and on entry to this function our working directory
1078 is whetever it was when find was invoked. Therefore
1079 If PATHNAME is "." we just leave things as they are.
1080 Otherwise, we figure out what the parent directory is,
1081 and move to that.
1083 static void
1084 process_top_path (char *pathname, mode_t mode)
1086 int dirchange;
1087 char *parent_dir = dir_name(pathname);
1088 char *base = base_name(pathname);
1090 state.curdepth = 0;
1091 state.path_length = strlen (pathname);
1093 if (0 == strcmp(pathname, parent_dir))
1095 dirchange = 0;
1096 base = pathname;
1098 else
1100 enum TraversalDirection direction;
1101 enum SafeChdirStatus chdir_status;
1102 struct stat st;
1104 dirchange = 1;
1105 if (0 == strcmp(base, ".."))
1106 direction = TraversingUp;
1107 else
1108 direction = TraversingDown;
1110 /* We pass SymlinkFollowOk to safely_chdir(), which allows it to
1111 * chdir() into a symbolic link. This is only useful for the
1112 * case where the directory we're chdir()ing into is the
1113 * basename of a command line argument, for example where
1114 * "foo/bar/baz" is specified on the command line. When -P is
1115 * in effect (the default), baz will not be followed if it is a
1116 * symlink, but if bar is a symlink, it _should_ be followed.
1117 * Hence we need the ability to override the policy set by
1118 * following_links().
1120 chdir_status = safely_chdir(parent_dir, direction, &st, SymlinkFollowOk);
1121 if (SafeChdirOK != chdir_status)
1123 if (errno)
1124 error (0, errno, "%s", parent_dir);
1125 else
1126 error (0, 0, "Failed to safely change directory into `%s'",
1127 parent_dir);
1129 /* We can't process this command-line argument. */
1130 state.exit_status = 1;
1131 return;
1135 free (parent_dir);
1136 parent_dir = NULL;
1138 process_path (pathname, base, false, ".", mode);
1139 complete_pending_execdirs(eval_tree);
1141 if (dirchange)
1143 chdir_back();
1148 /* Info on each directory in the current tree branch, to avoid
1149 getting stuck in symbolic link loops. */
1150 static struct dir_id *dir_ids = NULL;
1151 /* Entries allocated in `dir_ids'. */
1152 static int dir_alloc = 0;
1153 /* Index in `dir_ids' of directory currently being searched.
1154 This is always the last valid entry. */
1155 static int dir_curr = -1;
1156 /* (Arbitrary) number of entries to grow `dir_ids' by. */
1157 #define DIR_ALLOC_STEP 32
1161 /* We've detected a filesystem loop. This is caused by one of
1162 * two things:
1164 * 1. Option -L is in effect and we've hit a symbolic link that
1165 * points to an ancestor. This is harmless. We won't traverse the
1166 * symbolic link.
1168 * 2. We have hit a real cycle in the directory hierarchy. In this
1169 * case, we issue a diagnostic message (POSIX requires this) and we
1170 * skip that directory entry.
1172 static void
1173 issue_loop_warning(const char *name, const char *pathname, int level)
1175 struct stat stbuf_link;
1176 if (lstat(name, &stbuf_link) != 0)
1177 stbuf_link.st_mode = S_IFREG;
1179 if (S_ISLNK(stbuf_link.st_mode))
1181 error(0, 0,
1182 _("Symbolic link `%s' is part of a loop in the directory hierarchy; we have already visited the directory to which it points."),
1183 pathname);
1185 else
1187 int distance = 1 + (dir_curr-level);
1188 /* We have found an infinite loop. POSIX requires us to
1189 * issue a diagnostic. Usually we won't get to here
1190 * because when the leaf optimisation is on, it will cause
1191 * the subdirectory to be skipped. If /a/b/c/d is a hard
1192 * link to /a/b, then the link count of /a/b/c is 2,
1193 * because the ".." entry of /b/b/c/d points to /a, not
1194 * to /a/b/c.
1196 error(0, 0,
1197 _("Filesystem loop detected; `%s' has the same device number and inode as a directory which is %d %s."),
1198 pathname,
1199 distance,
1200 (distance == 1 ?
1201 _("level higher in the filesystem hierarchy") :
1202 _("levels higher in the filesystem hierarchy")));
1206 /* Recursively descend path PATHNAME, applying the predicates.
1207 LEAF is true if PATHNAME is known to be in a directory that has no
1208 more unexamined subdirectories, and therefore it is not a directory.
1209 Knowing this allows us to avoid calling stat as long as possible for
1210 leaf files.
1212 NAME is PATHNAME relative to the current directory. We access NAME
1213 but print PATHNAME.
1215 PARENT is the path of the parent of NAME, relative to find's
1216 starting directory.
1218 Return nonzero iff PATHNAME is a directory. */
1220 static int
1221 process_path (char *pathname, char *name, boolean leaf, char *parent,
1222 mode_t mode)
1224 struct stat stat_buf;
1225 static dev_t root_dev; /* Device ID of current argument pathname. */
1226 int i;
1228 /* Assume it is a non-directory initially. */
1229 stat_buf.st_mode = 0;
1230 state.rel_pathname = name;
1231 state.type = 0;
1232 state.have_stat = false;
1233 state.have_type = false;
1235 /* If we know the type of the directory entry, and it is not a
1236 * symbolic link, we may be able to avoid a stat() or lstat() call.
1238 if (mode)
1240 if (S_ISLNK(mode) && following_links())
1242 /* mode is wrong because we should have followed the symlink. */
1243 if (get_statinfo(pathname, name, &stat_buf) != 0)
1244 return 0;
1245 mode = state.type = stat_buf.st_mode;
1246 state.have_type = true;
1248 else
1250 state.have_type = true;
1251 stat_buf.st_mode = state.type = mode;
1254 else
1256 /* Mode is not yet known; may have to stat the file unless we
1257 * can deduce that it is not a directory (which is all we need to
1258 * know at this stage)
1260 if (leaf)
1262 state.have_stat = false;
1263 state.have_type = false;;
1264 state.type = 0;
1266 else
1268 if (get_statinfo(pathname, name, &stat_buf) != 0)
1269 return 0;
1271 /* If -L is in effect and we are dealing with a symlink,
1272 * st_mode is the mode of the pointed-to file, while mode is
1273 * the mode of the directory entry (S_IFLNK). Hence now
1274 * that we have the stat information, override "mode".
1276 state.type = stat_buf.st_mode;
1277 state.have_type = true;
1281 if (!S_ISDIR (state.type))
1283 if (state.curdepth >= options.mindepth)
1284 apply_predicate (pathname, &stat_buf, eval_tree);
1285 return 0;
1288 /* From here on, we're working on a directory. */
1291 /* Now we really need to stat the directory, even if we knoe the
1292 * type, because we need information like struct stat.st_rdev.
1294 if (get_statinfo(pathname, name, &stat_buf) != 0)
1295 return 0;
1297 state.have_stat = true;
1298 mode = state.type = stat_buf.st_mode; /* use full info now that we have it. */
1299 state.stop_at_current_level =
1300 options.maxdepth >= 0
1301 && state.curdepth >= options.maxdepth;
1303 /* If we've already seen this directory on this branch,
1304 don't descend it again. */
1305 for (i = 0; i <= dir_curr; i++)
1306 if (stat_buf.st_ino == dir_ids[i].ino &&
1307 stat_buf.st_dev == dir_ids[i].dev)
1309 state.stop_at_current_level = true;
1310 issue_loop_warning(name, pathname, i);
1313 if (dir_alloc <= ++dir_curr)
1315 dir_alloc += DIR_ALLOC_STEP;
1316 dir_ids = (struct dir_id *)
1317 xrealloc ((char *) dir_ids, dir_alloc * sizeof (struct dir_id));
1319 dir_ids[dir_curr].ino = stat_buf.st_ino;
1320 dir_ids[dir_curr].dev = stat_buf.st_dev;
1322 if (options.stay_on_filesystem)
1324 if (state.curdepth == 0)
1325 root_dev = stat_buf.st_dev;
1326 else if (stat_buf.st_dev != root_dev)
1327 state.stop_at_current_level = true;
1330 if (options.do_dir_first && state.curdepth >= options.mindepth)
1331 apply_predicate (pathname, &stat_buf, eval_tree);
1333 #ifdef DEBUG
1334 fprintf(stderr, "pathname = %s, stop_at_current_level = %d\n",
1335 pathname, state.stop_at_current_level);
1336 #endif /* DEBUG */
1338 if (state.stop_at_current_level == false)
1339 /* Scan directory on disk. */
1340 process_dir (pathname, name, strlen (pathname), &stat_buf, parent);
1342 if (options.do_dir_first == false && state.curdepth >= options.mindepth)
1344 state.rel_pathname = name;
1345 apply_predicate (pathname, &stat_buf, eval_tree);
1348 dir_curr--;
1350 return 1;
1353 /* Examine the predicate list for instances of -execdir or -okdir
1354 * which have been terminated with '+' (build argument list) rather
1355 * than ';' (singles only). If there are any, run them (this will
1356 * have no effect if there are no arguments waiting).
1358 static void
1359 complete_pending_execdirs(struct predicate *p)
1361 #if defined(NEW_EXEC)
1362 if (NULL == p)
1363 return;
1365 complete_pending_execdirs(p->pred_left);
1367 if (p->pred_func == pred_execdir || p->pred_func == pred_okdir)
1369 /* It's an exec-family predicate. p->args.exec_val is valid. */
1370 if (p->args.exec_vec.multiple)
1372 struct exec_val *execp = &p->args.exec_vec;
1374 /* This one was terminated by '+' and so might have some
1375 * left... Run it if neccessary.
1377 if (execp->state.todo)
1379 /* There are not-yet-executed arguments. */
1380 launch (&execp->ctl, &execp->state);
1385 complete_pending_execdirs(p->pred_right);
1386 #else
1387 /* nothing to do. */
1388 return;
1389 #endif
1392 /* Examine the predicate list for instances of -exec which have been
1393 * terminated with '+' (build argument list) rather than ';' (singles
1394 * only). If there are any, run them (this will have no effect if
1395 * there are no arguments waiting).
1397 static void
1398 complete_pending_execs(struct predicate *p)
1400 #if defined(NEW_EXEC)
1401 if (NULL == p)
1402 return;
1404 complete_pending_execs(p->pred_left);
1406 /* It's an exec-family predicate then p->args.exec_val is valid
1407 * and we can check it.
1409 if (p->pred_func == pred_exec && p->args.exec_vec.multiple)
1411 struct exec_val *execp = &p->args.exec_vec;
1413 /* This one was terminated by '+' and so might have some
1414 * left... Run it if neccessary. Set state.exit_status if
1415 * there are any problems.
1417 if (execp->state.todo)
1419 /* There are not-yet-executed arguments. */
1420 launch (&execp->ctl, &execp->state);
1424 complete_pending_execs(p->pred_right);
1425 #else
1426 /* nothing to do. */
1427 return;
1428 #endif
1432 /* Scan directory PATHNAME and recurse through process_path for each entry.
1434 PATHLEN is the length of PATHNAME.
1436 NAME is PATHNAME relative to the current directory.
1438 STATP is the results of *options.xstat on it.
1440 PARENT is the path of the parent of NAME, relative to find's
1441 starting directory. */
1443 static void
1444 process_dir (char *pathname, char *name, int pathlen, struct stat *statp, char *parent)
1446 char *name_space; /* Names of files in PATHNAME. */
1447 int subdirs_left; /* Number of unexamined subdirs in PATHNAME. */
1448 int idx; /* Which entry are we on? */
1449 struct stat stat_buf;
1450 struct savedir_dirinfo *dirinfo;
1452 subdirs_left = statp->st_nlink - 2; /* Account for name and ".". */
1454 errno = 0;
1455 name_space = savedirinfo (name, &dirinfo);
1457 if (name_space == NULL)
1459 assert(errno != 0);
1460 error (0, errno, "%s", pathname);
1461 state.exit_status = 1;
1463 else
1465 register char *namep; /* Current point in `name_space'. */
1466 char *cur_path; /* Full path of each file to process. */
1467 char *cur_name; /* Base name of each file to process. */
1468 unsigned cur_path_size; /* Bytes allocated for `cur_path'. */
1469 register unsigned file_len; /* Length of each path to process. */
1470 register unsigned pathname_len; /* PATHLEN plus trailing '/'. */
1472 if (pathname[pathlen - 1] == '/')
1473 pathname_len = pathlen + 1; /* For '\0'; already have '/'. */
1474 else
1475 pathname_len = pathlen + 2; /* For '/' and '\0'. */
1476 cur_path_size = 0;
1477 cur_path = NULL;
1479 /* We're about to leave the directory. If there are any
1480 * -execdir argument lists which have been built but have not
1481 * yet been processed, do them now because they must be done in
1482 * the same directory.
1484 complete_pending_execdirs(eval_tree);
1486 #if USE_SAFE_CHDIR
1487 if (strcmp (name, "."))
1489 enum SafeChdirStatus status = safely_chdir (name, TraversingDown, &stat_buf, SymlinkHandleDefault);
1490 switch (status)
1492 case SafeChdirOK:
1493 /* If there had been a change but wd_sanity_check()
1494 * accepted it, we need to accept that on the
1495 * way back up as well, so modify our record
1496 * of what we think we should see later.
1497 * If there was no change, the assignments are a no-op.
1499 dir_ids[dir_curr].dev = stat_buf.st_dev;
1500 dir_ids[dir_curr].ino = stat_buf.st_ino;
1501 break;
1503 case SafeChdirFailNonexistent:
1504 case SafeChdirFailStat:
1505 case SafeChdirFailWouldBeUnableToReturn:
1506 case SafeChdirFailSymlink:
1507 case SafeChdirFailNotDir:
1508 case SafeChdirFailChdirFailed:
1509 error (0, errno, "%s", pathname);
1510 state.exit_status = 1;
1511 return;
1514 #else
1515 if (0 != strcmp (name, "."))
1517 #ifdef DEBUG_STAT
1518 fprintf(stderr, "process_dir(): chdir(\"%s\")\n", name);
1519 #endif
1520 if (chdir (name) < 0)
1522 error (0, errno, "%s", pathname);
1523 exit_status = 1;
1524 return;
1529 /* Check that we are where we should be. */
1530 if (1)
1532 boolean changed = false;
1533 wd_sanity_check(pathname,
1534 program_name,
1535 ".",
1536 dir_ids[dir_curr].dev,
1537 dir_ids[dir_curr].ino,
1538 &stat_buf, 0, __LINE__,
1539 TraversingDown,
1540 FATAL_IF_SANITY_CHECK_FAILS,
1541 &changed);
1542 if (changed)
1544 /* If there had been a change but wd_sanity_check()
1545 * accepted it, we need to accept that on the
1546 * way back up as well, so modify our record
1547 * of what we think we should see later.
1549 dir_ids[dir_curr].dev = stat_buf.st_dev;
1550 dir_ids[dir_curr].ino = stat_buf.st_ino;
1553 #endif
1555 for (idx=0, namep = name_space; *namep; namep += file_len - pathname_len + 1, ++idx)
1557 /* savedirinfo() may return dirinfo=NULL if extended information
1558 * is not available.
1560 mode_t mode = dirinfo ? dirinfo[idx].type_info : 0;
1562 /* Append this directory entry's name to the path being searched. */
1563 file_len = pathname_len + strlen (namep);
1564 if (file_len > cur_path_size)
1566 while (file_len > cur_path_size)
1567 cur_path_size += 1024;
1568 if (cur_path)
1569 free (cur_path);
1570 cur_path = xmalloc (cur_path_size);
1571 strcpy (cur_path, pathname);
1572 cur_path[pathname_len - 2] = '/';
1574 cur_name = cur_path + pathname_len - 1;
1575 strcpy (cur_name, namep);
1577 state.curdepth++;
1578 if (!options.no_leaf_check)
1580 if (mode && S_ISDIR(mode) && (subdirs_left == 0))
1582 /* This is a subdirectory, but the number of directories we
1583 * have found now exceeds the number we would expect given
1584 * the hard link count on the parent. This is likely to be
1585 * a bug in the filesystem driver (e.g. Linux's
1586 * /proc filesystem) or may just be a fact that the OS
1587 * doesn't really handle hard links with Unix semantics.
1588 * In the latter case, -noleaf should be used routinely.
1590 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."),
1591 parent);
1592 state.exit_status = 1; /* We know the result is wrong, now */
1593 options.no_leaf_check = true; /* Don't make same
1594 mistake again */
1595 subdirs_left = 1; /* band-aid for this iteration. */
1598 /* Normal case optimization. On normal Unix
1599 filesystems, a directory that has no subdirectories
1600 has two links: its name, and ".". Any additional
1601 links are to the ".." entries of its subdirectories.
1602 Once we have processed as many subdirectories as
1603 there are additional links, we know that the rest of
1604 the entries are non-directories -- in other words,
1605 leaf files. */
1606 subdirs_left -= process_path (cur_path, cur_name,
1607 subdirs_left == 0, pathname,
1608 mode);
1610 else
1612 /* There might be weird (e.g., CD-ROM or MS-DOS) filesystems
1613 mounted, which don't have Unix-like directory link counts. */
1614 process_path (cur_path, cur_name, false, pathname, mode);
1617 state.curdepth--;
1621 /* We're about to leave the directory. If there are any
1622 * -execdir argument lists which have been built but have not
1623 * yet been processed, do them now because they must be done in
1624 * the same directory.
1626 complete_pending_execdirs(eval_tree);
1628 #if USE_SAFE_CHDIR
1629 if (strcmp (name, "."))
1631 enum SafeChdirStatus status;
1632 struct dir_id did;
1633 boolean changed = false;
1635 /* We could go back and do the next command-line arg
1636 instead, maybe using longjmp. */
1637 char const *dir;
1638 boolean deref = following_links() ? true : false;
1640 if ( (state.curdepth>0) && !deref)
1641 dir = "..";
1642 else
1644 chdir_back ();
1645 dir = parent;
1648 status = safely_chdir (dir, TraversingUp, &stat_buf, SymlinkHandleDefault);
1649 switch (status)
1651 case SafeChdirOK:
1652 break;
1654 case SafeChdirFailNonexistent:
1655 case SafeChdirFailStat:
1656 case SafeChdirFailWouldBeUnableToReturn:
1657 case SafeChdirFailSymlink:
1658 case SafeChdirFailNotDir:
1659 case SafeChdirFailChdirFailed:
1660 error (1, errno, "%s", pathname);
1661 return;
1664 if (dir_curr > 0)
1666 did.dev = dir_ids[dir_curr-1].dev;
1667 did.ino = dir_ids[dir_curr-1].ino;
1669 else
1671 did.dev = starting_stat_buf.st_dev;
1672 did.ino = starting_stat_buf.st_ino;
1675 wd_sanity_check(pathname,
1676 program_name,
1677 parent,
1678 did.dev,
1679 did.ino,
1680 &stat_buf,
1681 deref ? 1 : 0,
1682 __LINE__,
1683 TraversingUp,
1684 FATAL_IF_SANITY_CHECK_FAILS,
1685 &changed);
1687 #else
1688 if (strcmp (name, "."))
1690 /* We could go back and do the next command-line arg
1691 instead, maybe using longjmp. */
1692 char const *dir;
1693 boolean deref = following_links() ? true : false;
1695 if (!deref)
1696 dir = "..";
1697 else
1699 chdir_back ();
1700 dir = parent;
1703 #ifdef DEBUG_STAT
1704 fprintf(stderr, "process_dir(): chdir(\"%s\")\n", dir);
1705 #endif
1706 if (chdir (dir) != 0)
1707 error (1, errno, "%s", parent);
1709 /* Check that we are where we should be. */
1710 if (1)
1712 boolean changed = false;
1713 struct stat tmp;
1714 int problem_is_with_parent;
1716 memset(&tmp, 0, sizeof(tmp));
1717 if (dir_curr > 0)
1719 tmp.st_dev = dir_ids[dir_curr-1].dev;
1720 tmp.st_ino = dir_ids[dir_curr-1].ino;
1722 else
1724 tmp.st_dev = starting_stat_buf.st_dev;
1725 tmp.st_ino = starting_stat_buf.st_ino;
1728 problem_is_with_parent = deref ? 1 : 0;
1729 wd_sanity_check(pathname,
1730 program_name,
1731 parent,
1732 tmp.st_dev,
1733 tmp.st_ino,
1734 &stat_buf,
1735 problem_is_with_parent, __LINE__,
1736 TraversingUp,
1737 FATAL_IF_SANITY_CHECK_FAILS,
1738 &changed);
1741 #endif
1743 if (cur_path)
1744 free (cur_path);
1745 free (name_space);
1746 free (dirinfo);
1750 /* Return true if there are no predicates with no_default_print in
1751 predicate list PRED, false if there are any.
1752 Returns true if default print should be performed */
1754 static boolean
1755 default_prints (struct predicate *pred)
1757 while (pred != NULL)
1759 if (pred->no_default_print)
1760 return (false);
1761 pred = pred->pred_next;
1763 return (true);