2001-10-31 Alexandre Oliva <aoliva@redhat.com>
[glibc/history.git] / io / ftw.c
blob76108510472558e547b8c16a9ed87678118e83c3
1 /* File tree walker functions.
2 Copyright (C) 1996-2003, 2004 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Ulrich Drepper <drepper@cygnus.com>, 1996.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; if not, write to the Free
18 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19 02111-1307 USA. */
21 #ifdef HAVE_CONFIG_H
22 # include <config.h>
23 #endif
25 #if __GNUC__
26 # define alloca __builtin_alloca
27 #else
28 # if HAVE_ALLOCA_H
29 # include <alloca.h>
30 # else
31 # ifdef _AIX
32 # pragma alloca
33 # else
34 char *alloca ();
35 # endif
36 # endif
37 #endif
39 #if defined _LIBC
40 # include <dirent.h>
41 # define NAMLEN(dirent) _D_EXACT_NAMLEN (dirent)
42 #else
43 # if HAVE_DIRENT_H
44 # include <dirent.h>
45 # define NAMLEN(dirent) strlen ((dirent)->d_name)
46 # else
47 # define dirent direct
48 # define NAMLEN(dirent) (dirent)->d_namlen
49 # if HAVE_SYS_NDIR_H
50 # include <sys/ndir.h>
51 # endif
52 # if HAVE_SYS_DIR_H
53 # include <sys/dir.h>
54 # endif
55 # if HAVE_NDIR_H
56 # include <ndir.h>
57 # endif
58 # endif
59 #endif
61 #include <errno.h>
62 #include <ftw.h>
63 #include <limits.h>
64 #include <search.h>
65 #include <stdlib.h>
66 #include <string.h>
67 #include <unistd.h>
68 #if HAVE_SYS_PARAM_H || defined _LIBC
69 # include <sys/param.h>
70 #endif
71 #ifdef _LIBC
72 # include <include/sys/stat.h>
73 #else
74 # include <sys/stat.h>
75 #endif
77 #if ! _LIBC && !HAVE_DECL_STPCPY && !defined stpcpy
78 char *stpcpy ();
79 #endif
81 #if ! _LIBC && ! defined HAVE_MEMPCPY && ! defined mempcpy
82 /* Be CAREFUL that there are no side effects in N. */
83 # define mempcpy(D, S, N) ((void *) ((char *) memcpy (D, S, N) + (N)))
84 #endif
86 /* #define NDEBUG 1 */
87 #include <assert.h>
89 #ifndef _LIBC
90 # undef __chdir
91 # define __chdir chdir
92 # undef __closedir
93 # define __closedir closedir
94 # undef __fchdir
95 # define __fchdir fchdir
96 # undef __getcwd
97 # define __getcwd(P, N) xgetcwd ()
98 extern char *xgetcwd (void);
99 # undef __mempcpy
100 # define __mempcpy mempcpy
101 # undef __opendir
102 # define __opendir opendir
103 # undef __readdir64
104 # define __readdir64 readdir
105 # undef __stpcpy
106 # define __stpcpy stpcpy
107 # undef __tdestroy
108 # define __tdestroy tdestroy
109 # undef __tfind
110 # define __tfind tfind
111 # undef __tsearch
112 # define __tsearch tsearch
113 # undef internal_function
114 # define internal_function /* empty */
115 # undef dirent64
116 # define dirent64 dirent
117 # undef MAX
118 # define MAX(a, b) ((a) > (b) ? (a) : (b))
119 #endif
121 /* Arrange to make lstat calls go through the wrapper function
122 on systems with an lstat function that does not dereference symlinks
123 that are specified with a trailing slash. */
124 #if ! _LIBC && ! LSTAT_FOLLOWS_SLASHED_SYMLINK
125 int rpl_lstat (const char *, struct stat *);
126 # undef lstat
127 # define lstat(Name, Stat_buf) rpl_lstat(Name, Stat_buf)
128 #endif
130 #ifndef __set_errno
131 # define __set_errno(Val) errno = (Val)
132 #endif
134 /* Support for the LFS API version. */
135 #ifndef FTW_NAME
136 # define FTW_NAME ftw
137 # define NFTW_NAME nftw
138 # define NFTW_OLD_NAME __old_nftw
139 # define NFTW_NEW_NAME __new_nftw
140 # define INO_T ino_t
141 # define STAT stat
142 # ifdef _LIBC
143 # define LXSTAT __lxstat
144 # define XSTAT __xstat
145 # else
146 # define LXSTAT(V,f,sb) lstat (f,sb)
147 # define XSTAT(V,f,sb) stat (f,sb)
148 # endif
149 # define FTW_FUNC_T __ftw_func_t
150 # define NFTW_FUNC_T __nftw_func_t
151 #endif
153 /* We define PATH_MAX if the system does not provide a definition.
154 This does not artificially limit any operation. PATH_MAX is simply
155 used as a guesstimate for the expected maximal path length.
156 Buffers will be enlarged if necessary. */
157 #ifndef PATH_MAX
158 # define PATH_MAX 1024
159 #endif
161 struct dir_data
163 DIR *stream;
164 char *content;
167 struct known_object
169 dev_t dev;
170 INO_T ino;
173 struct ftw_data
175 /* Array with pointers to open directory streams. */
176 struct dir_data **dirstreams;
177 size_t actdir;
178 size_t maxdir;
180 /* Buffer containing name of currently processed object. */
181 char *dirbuf;
182 size_t dirbufsize;
184 /* Passed as fourth argument to `nftw' callback. The `base' member
185 tracks the content of the `dirbuf'. */
186 struct FTW ftw;
188 /* Flags passed to `nftw' function. 0 for `ftw'. */
189 int flags;
191 /* Conversion array for flag values. It is the identity mapping for
192 `nftw' calls, otherwise it maps the values to those known by
193 `ftw'. */
194 const int *cvt_arr;
196 /* Callback function. We always use the `nftw' form. */
197 NFTW_FUNC_T func;
199 /* Device of starting point. Needed for FTW_MOUNT. */
200 dev_t dev;
202 /* Data structure for keeping fingerprints of already processed
203 object. This is needed when not using FTW_PHYS. */
204 void *known_objects;
208 /* Internally we use the FTW_* constants used for `nftw'. When invoked
209 as `ftw', map each flag to the subset of values used by `ftw'. */
210 static const int nftw_arr[] =
212 FTW_F, FTW_D, FTW_DNR, FTW_NS, FTW_SL, FTW_DP, FTW_SLN
215 static const int ftw_arr[] =
217 FTW_F, FTW_D, FTW_DNR, FTW_NS, FTW_F, FTW_D, FTW_NS
221 /* Forward declarations of local functions. */
222 static int ftw_dir (struct ftw_data *data, struct STAT *st,
223 struct dir_data *old_dir) internal_function;
226 static int
227 object_compare (const void *p1, const void *p2)
229 /* We don't need a sophisticated and useful comparison. We are only
230 interested in equality. However, we must be careful not to
231 accidentally compare `holes' in the structure. */
232 const struct known_object *kp1 = p1, *kp2 = p2;
233 int cmp1;
234 cmp1 = (kp1->ino > kp2->ino) - (kp1->ino < kp2->ino);
235 if (cmp1 != 0)
236 return cmp1;
237 return (kp1->dev > kp2->dev) - (kp1->dev < kp2->dev);
241 static inline int
242 add_object (struct ftw_data *data, struct STAT *st)
244 struct known_object *newp = malloc (sizeof (struct known_object));
245 if (newp == NULL)
246 return -1;
247 newp->dev = st->st_dev;
248 newp->ino = st->st_ino;
249 return __tsearch (newp, &data->known_objects, object_compare) ? 0 : -1;
253 static inline int
254 find_object (struct ftw_data *data, struct STAT *st)
256 struct known_object obj;
257 obj.dev = st->st_dev;
258 obj.ino = st->st_ino;
259 return __tfind (&obj, &data->known_objects, object_compare) != NULL;
263 static inline int
264 __attribute ((always_inline))
265 open_dir_stream (struct ftw_data *data, struct dir_data *dirp)
267 int result = 0;
269 if (data->dirstreams[data->actdir] != NULL)
271 /* Oh, oh. We must close this stream. Get all remaining
272 entries and store them as a list in the `content' member of
273 the `struct dir_data' variable. */
274 size_t bufsize = 1024;
275 char *buf = malloc (bufsize);
277 if (buf == NULL)
278 result = -1;
279 else
281 DIR *st = data->dirstreams[data->actdir]->stream;
282 struct dirent64 *d;
283 size_t actsize = 0;
285 while ((d = __readdir64 (st)) != NULL)
287 size_t this_len = NAMLEN (d);
288 if (actsize + this_len + 2 >= bufsize)
290 char *newp;
291 bufsize += MAX (1024, 2 * this_len);
292 newp = (char *) realloc (buf, bufsize);
293 if (newp == NULL)
295 /* No more memory. */
296 int save_err = errno;
297 free (buf);
298 __set_errno (save_err);
299 result = -1;
300 break;
302 buf = newp;
305 *((char *) __mempcpy (buf + actsize, d->d_name, this_len))
306 = '\0';
307 actsize += this_len + 1;
310 /* Terminate the list with an additional NUL byte. */
311 buf[actsize++] = '\0';
313 /* Shrink the buffer to what we actually need. */
314 data->dirstreams[data->actdir]->content = realloc (buf, actsize);
315 if (data->dirstreams[data->actdir]->content == NULL)
317 int save_err = errno;
318 free (buf);
319 __set_errno (save_err);
320 result = -1;
322 else
324 __closedir (st);
325 data->dirstreams[data->actdir]->stream = NULL;
326 data->dirstreams[data->actdir] = NULL;
331 /* Open the new stream. */
332 if (result == 0)
334 const char *name = ((data->flags & FTW_CHDIR)
335 ? data->dirbuf + data->ftw.base: data->dirbuf);
336 assert (data->dirstreams[data->actdir] == NULL);
338 dirp->stream = __opendir (name);
339 if (dirp->stream == NULL)
340 result = -1;
341 else
343 dirp->content = NULL;
344 data->dirstreams[data->actdir] = dirp;
346 if (++data->actdir == data->maxdir)
347 data->actdir = 0;
351 return result;
355 static int
356 internal_function
357 process_entry (struct ftw_data *data, struct dir_data *dir, const char *name,
358 size_t namlen)
360 struct STAT st;
361 int result = 0;
362 int flag = 0;
363 size_t new_buflen;
365 if (name[0] == '.' && (name[1] == '\0'
366 || (name[1] == '.' && name[2] == '\0')))
367 /* Don't process the "." and ".." entries. */
368 return 0;
370 new_buflen = data->ftw.base + namlen + 2;
371 if (data->dirbufsize < new_buflen)
373 /* Enlarge the buffer. */
374 char *newp;
376 data->dirbufsize = 2 * new_buflen;
377 newp = (char *) realloc (data->dirbuf, data->dirbufsize);
378 if (newp == NULL)
379 return -1;
380 data->dirbuf = newp;
383 *((char *) __mempcpy (data->dirbuf + data->ftw.base, name, namlen)) = '\0';
385 if ((data->flags & FTW_CHDIR) == 0)
386 name = data->dirbuf;
388 if (((data->flags & FTW_PHYS)
389 ? LXSTAT (_STAT_VER, name, &st)
390 : XSTAT (_STAT_VER, name, &st)) < 0)
392 if (errno != EACCES && errno != ENOENT)
393 result = -1;
394 else if (!(data->flags & FTW_PHYS)
395 && LXSTAT (_STAT_VER, name, &st) == 0
396 && S_ISLNK (st.st_mode))
397 flag = FTW_SLN;
398 else
399 flag = FTW_NS;
401 else
403 if (S_ISDIR (st.st_mode))
404 flag = FTW_D;
405 else if (S_ISLNK (st.st_mode))
406 flag = FTW_SL;
407 else
408 flag = FTW_F;
411 if (result == 0
412 && (flag == FTW_NS
413 || !(data->flags & FTW_MOUNT) || st.st_dev == data->dev))
415 if (flag == FTW_D)
417 if ((data->flags & FTW_PHYS)
418 || (!find_object (data, &st)
419 /* Remember the object. */
420 && (result = add_object (data, &st)) == 0))
421 result = ftw_dir (data, &st, dir);
423 else
424 result = (*data->func) (data->dirbuf, &st, data->cvt_arr[flag],
425 &data->ftw);
428 if ((data->flags & FTW_ACTIONRETVAL) && result == FTW_SKIP_SUBTREE)
429 result = 0;
431 return result;
435 static int
436 __attribute ((noinline))
437 internal_function
438 ftw_dir (struct ftw_data *data, struct STAT *st, struct dir_data *old_dir)
440 struct dir_data dir;
441 struct dirent64 *d;
442 int previous_base = data->ftw.base;
443 int result;
444 char *startp;
446 /* Open the stream for this directory. This might require that
447 another stream has to be closed. */
448 result = open_dir_stream (data, &dir);
449 if (result != 0)
451 if (errno == EACCES)
452 /* We cannot read the directory. Signal this with a special flag. */
453 result = (*data->func) (data->dirbuf, st, FTW_DNR, &data->ftw);
455 return result;
458 /* First, report the directory (if not depth-first). */
459 if (!(data->flags & FTW_DEPTH))
461 result = (*data->func) (data->dirbuf, st, FTW_D, &data->ftw);
462 if (result != 0)
464 int save_err;
465 fail:
466 save_err = errno;
467 __closedir (dir.stream);
468 __set_errno (save_err);
470 if (data->actdir-- == 0)
471 data->actdir = data->maxdir - 1;
472 data->dirstreams[data->actdir] = NULL;
473 return result;
477 /* If necessary, change to this directory. */
478 if (data->flags & FTW_CHDIR)
480 if (__fchdir (dirfd (dir.stream)) < 0)
482 result = -1;
483 goto fail;
487 /* Next, update the `struct FTW' information. */
488 ++data->ftw.level;
489 startp = strchr (data->dirbuf, '\0');
490 /* There always must be a directory name. */
491 assert (startp != data->dirbuf);
492 if (startp[-1] != '/')
493 *startp++ = '/';
494 data->ftw.base = startp - data->dirbuf;
496 while (dir.stream != NULL && (d = __readdir64 (dir.stream)) != NULL)
498 result = process_entry (data, &dir, d->d_name, NAMLEN (d));
499 if (result != 0)
500 break;
503 if (dir.stream != NULL)
505 /* The stream is still open. I.e., we did not need more
506 descriptors. Simply close the stream now. */
507 int save_err = errno;
509 assert (dir.content == NULL);
511 __closedir (dir.stream);
512 __set_errno (save_err);
514 if (data->actdir-- == 0)
515 data->actdir = data->maxdir - 1;
516 data->dirstreams[data->actdir] = NULL;
518 else
520 int save_err;
521 char *runp = dir.content;
523 while (result == 0 && *runp != '\0')
525 char *endp = strchr (runp, '\0');
527 result = process_entry (data, &dir, runp, endp - runp);
529 runp = endp + 1;
532 save_err = errno;
533 free (dir.content);
534 __set_errno (save_err);
537 if ((data->flags & FTW_ACTIONRETVAL) && result == FTW_SKIP_SIBLINGS)
538 result = 0;
540 /* Prepare the return, revert the `struct FTW' information. */
541 data->dirbuf[data->ftw.base - 1] = '\0';
542 --data->ftw.level;
543 data->ftw.base = previous_base;
545 /* Finally, if we process depth-first report the directory. */
546 if (result == 0 && (data->flags & FTW_DEPTH))
547 result = (*data->func) (data->dirbuf, st, FTW_DP, &data->ftw);
549 if (old_dir
550 && (data->flags & FTW_CHDIR)
551 && (result == 0
552 || ((data->flags & FTW_ACTIONRETVAL)
553 && (result != -1 && result != FTW_STOP))))
555 /* Change back to the parent directory. */
556 int done = 0;
557 if (old_dir->stream != NULL)
558 if (__fchdir (dirfd (old_dir->stream)) == 0)
559 done = 1;
561 if (!done)
563 if (data->ftw.base == 1)
565 if (__chdir ("/") < 0)
566 result = -1;
568 else
569 if (__chdir ("..") < 0)
570 result = -1;
574 return result;
578 static int
579 __attribute ((noinline))
580 internal_function
581 ftw_startup (const char *dir, int is_nftw, void *func, int descriptors,
582 int flags)
584 struct ftw_data data;
585 struct STAT st;
586 int result = 0;
587 int save_err;
588 char *cwd = NULL;
589 char *cp;
591 /* First make sure the parameters are reasonable. */
592 if (dir[0] == '\0')
594 __set_errno (ENOENT);
595 return -1;
598 data.maxdir = descriptors < 1 ? 1 : descriptors;
599 data.actdir = 0;
600 data.dirstreams = (struct dir_data **) alloca (data.maxdir
601 * sizeof (struct dir_data *));
602 memset (data.dirstreams, '\0', data.maxdir * sizeof (struct dir_data *));
604 /* PATH_MAX is always defined when we get here. */
605 data.dirbufsize = MAX (2 * strlen (dir), PATH_MAX);
606 data.dirbuf = (char *) malloc (data.dirbufsize);
607 if (data.dirbuf == NULL)
608 return -1;
609 cp = __stpcpy (data.dirbuf, dir);
610 /* Strip trailing slashes. */
611 while (cp > data.dirbuf + 1 && cp[-1] == '/')
612 --cp;
613 *cp = '\0';
615 data.ftw.level = 0;
617 /* Find basename. */
618 while (cp > data.dirbuf && cp[-1] != '/')
619 --cp;
620 data.ftw.base = cp - data.dirbuf;
622 data.flags = flags;
624 /* This assignment might seem to be strange but it is what we want.
625 The trick is that the first three arguments to the `ftw' and
626 `nftw' callback functions are equal. Therefore we can call in
627 every case the callback using the format of the `nftw' version
628 and get the correct result since the stack layout for a function
629 call in C allows this. */
630 data.func = (NFTW_FUNC_T) func;
632 /* Since we internally use the complete set of FTW_* values we need
633 to reduce the value range before calling a `ftw' callback. */
634 data.cvt_arr = is_nftw ? nftw_arr : ftw_arr;
636 /* No object known so far. */
637 data.known_objects = NULL;
639 /* Now go to the directory containing the initial file/directory. */
640 if (flags & FTW_CHDIR)
642 /* GNU extension ahead. */
643 cwd = __getcwd (NULL, 0);
644 if (cwd == NULL)
645 result = -1;
646 else if (data.ftw.base > 0)
648 /* Change to the directory the file is in. In data.dirbuf
649 we have a writable copy of the file name. Just NUL
650 terminate it for now and change the directory. */
651 if (data.ftw.base == 1)
652 /* I.e., the file is in the root directory. */
653 result = __chdir ("/");
654 else
656 char ch = data.dirbuf[data.ftw.base - 1];
657 data.dirbuf[data.ftw.base - 1] = '\0';
658 result = __chdir (data.dirbuf);
659 data.dirbuf[data.ftw.base - 1] = ch;
664 /* Get stat info for start directory. */
665 if (result == 0)
667 const char *name = ((data.flags & FTW_CHDIR)
668 ? data.dirbuf + data.ftw.base
669 : data.dirbuf);
671 if (((flags & FTW_PHYS)
672 ? LXSTAT (_STAT_VER, name, &st)
673 : XSTAT (_STAT_VER, name, &st)) < 0)
675 if (!(flags & FTW_PHYS)
676 && errno == ENOENT
677 && LXSTAT (_STAT_VER, name, &st) == 0
678 && S_ISLNK (st.st_mode))
679 result = (*data.func) (data.dirbuf, &st, data.cvt_arr[FTW_SLN],
680 &data.ftw);
681 else
682 /* No need to call the callback since we cannot say anything
683 about the object. */
684 result = -1;
686 else
688 if (S_ISDIR (st.st_mode))
690 /* Remember the device of the initial directory in case
691 FTW_MOUNT is given. */
692 data.dev = st.st_dev;
694 /* We know this directory now. */
695 if (!(flags & FTW_PHYS))
696 result = add_object (&data, &st);
698 if (result == 0)
699 result = ftw_dir (&data, &st, NULL);
701 else
703 int flag = S_ISLNK (st.st_mode) ? FTW_SL : FTW_F;
705 result = (*data.func) (data.dirbuf, &st, data.cvt_arr[flag],
706 &data.ftw);
710 if ((flags & FTW_ACTIONRETVAL)
711 && (result == FTW_SKIP_SUBTREE || result == FTW_SKIP_SIBLINGS))
712 result = 0;
715 /* Return to the start directory (if necessary). */
716 if (cwd != NULL)
718 int save_err = errno;
719 __chdir (cwd);
720 free (cwd);
721 __set_errno (save_err);
724 /* Free all memory. */
725 save_err = errno;
726 __tdestroy (data.known_objects, free);
727 free (data.dirbuf);
728 __set_errno (save_err);
730 return result;
735 /* Entry points. */
738 FTW_NAME (path, func, descriptors)
739 const char *path;
740 FTW_FUNC_T func;
741 int descriptors;
743 return ftw_startup (path, 0, func, descriptors, 0);
746 #ifndef _LIBC
748 NFTW_NAME (path, func, descriptors, flags)
749 const char *path;
750 NFTW_FUNC_T func;
751 int descriptors;
752 int flags;
754 return ftw_startup (path, 1, func, descriptors, flags);
756 #else
758 #include <shlib-compat.h>
760 int NFTW_NEW_NAME (const char *, NFTW_FUNC_T, int, int);
763 NFTW_NEW_NAME (path, func, descriptors, flags)
764 const char *path;
765 NFTW_FUNC_T func;
766 int descriptors;
767 int flags;
769 if (flags
770 & ~(FTW_PHYS | FTW_MOUNT | FTW_CHDIR | FTW_DEPTH | FTW_ACTIONRETVAL))
772 __set_errno (EINVAL);
773 return -1;
775 return ftw_startup (path, 1, func, descriptors, flags);
778 versioned_symbol (libc, NFTW_NEW_NAME, NFTW_NAME, GLIBC_2_3_3);
780 #if SHLIB_COMPAT(libc, GLIBC_2_1, GLIBC_2_3_3)
782 /* Older nftw* version just ignored all unknown flags. */
784 int NFTW_OLD_NAME (const char *, NFTW_FUNC_T, int, int);
787 attribute_compat_text_section
788 NFTW_OLD_NAME (path, func, descriptors, flags)
789 const char *path;
790 NFTW_FUNC_T func;
791 int descriptors;
792 int flags;
794 flags &= (FTW_PHYS | FTW_MOUNT | FTW_CHDIR | FTW_DEPTH);
795 return ftw_startup (path, 1, func, descriptors, flags);
798 compat_symbol (libc, NFTW_OLD_NAME, NFTW_NAME, GLIBC_2_1);
799 #endif
800 #endif