mirrored from git://git.sv.gnu.org/gnulib.git
/
fts.c
2134 lines (1927 loc) · 73.5 KB
/
fts.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Traverse a file hierarchy.
Copyright (C) 2004-2018 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>. */
/*-
* Copyright (c) 1990, 1993, 1994
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <config.h>
#if defined LIBC_SCCS && !defined GCC_LINT && !defined lint
static char sccsid[] = "@(#)fts.c 8.6 (Berkeley) 8/14/94";
#endif
#include "fts_.h"
#if HAVE_SYS_PARAM_H || defined _LIBC
# include <sys/param.h>
#endif
#ifdef _LIBC
# include <include/sys/stat.h>
#else
# include <sys/stat.h>
#endif
#include <fcntl.h>
#include <errno.h>
#include <stdalign.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#if ! _LIBC
# include "fcntl--.h"
# include "flexmember.h"
# include "openat.h"
# include "same-inode.h"
#endif
#include <dirent.h>
#ifndef _D_EXACT_NAMLEN
# define _D_EXACT_NAMLEN(dirent) strlen ((dirent)->d_name)
#endif
#if HAVE_STRUCT_DIRENT_D_TYPE
/* True if the type of the directory entry D is known. */
# define DT_IS_KNOWN(d) ((d)->d_type != DT_UNKNOWN)
/* True if the type of the directory entry D must be T. */
# define DT_MUST_BE(d, t) ((d)->d_type == (t))
# define D_TYPE(d) ((d)->d_type)
#else
# define DT_IS_KNOWN(d) false
# define DT_MUST_BE(d, t) false
# define D_TYPE(d) DT_UNKNOWN
# undef DT_UNKNOWN
# define DT_UNKNOWN 0
/* Any nonzero values will do here, so long as they're distinct.
Undef any existing macros out of the way. */
# undef DT_BLK
# undef DT_CHR
# undef DT_DIR
# undef DT_FIFO
# undef DT_LNK
# undef DT_REG
# undef DT_SOCK
# define DT_BLK 1
# define DT_CHR 2
# define DT_DIR 3
# define DT_FIFO 4
# define DT_LNK 5
# define DT_REG 6
# define DT_SOCK 7
#endif
#ifndef S_IFLNK
# define S_IFLNK 0
#endif
#ifndef S_IFSOCK
# define S_IFSOCK 0
#endif
enum
{
NOT_AN_INODE_NUMBER = 0
};
#ifdef D_INO_IN_DIRENT
# define D_INO(dp) (dp)->d_ino
#else
/* Some systems don't have inodes, so fake them to avoid lots of ifdefs. */
# define D_INO(dp) NOT_AN_INODE_NUMBER
#endif
/* If possible (see max_entries, below), read no more than this many directory
entries at a time. Without this limit (i.e., when using non-NULL
fts_compar), processing a directory with 4,000,000 entries requires ~1GiB
of memory, and handling 64M entries would require 16GiB of memory. */
#ifndef FTS_MAX_READDIR_ENTRIES
# define FTS_MAX_READDIR_ENTRIES 100000
#endif
/* If there are more than this many entries in a directory,
and the conditions mentioned below are satisfied, then sort
the entries on inode number before any further processing. */
#ifndef FTS_INODE_SORT_DIR_ENTRIES_THRESHOLD
# define FTS_INODE_SORT_DIR_ENTRIES_THRESHOLD 10000
#endif
enum
{
_FTS_INODE_SORT_DIR_ENTRIES_THRESHOLD = FTS_INODE_SORT_DIR_ENTRIES_THRESHOLD
};
enum Fts_stat
{
FTS_NO_STAT_REQUIRED = 1,
FTS_STAT_REQUIRED = 2
};
#ifdef _LIBC
# undef close
# define close __close
# undef closedir
# define closedir __closedir
# undef fchdir
# define fchdir __fchdir
# undef open
# define open __open
# undef readdir
# define readdir __readdir
#else
# undef internal_function
# define internal_function /* empty */
#endif
#ifndef __set_errno
# define __set_errno(Val) errno = (Val)
#endif
/* If this host provides the openat function, then we can avoid
attempting to open "." in some initialization code below. */
#ifdef HAVE_OPENAT
# define HAVE_OPENAT_SUPPORT 1
#else
# define HAVE_OPENAT_SUPPORT 0
#endif
#ifdef NDEBUG
# define fts_assert(expr) ((void) (0 && (expr)))
#else
# define fts_assert(expr) \
do \
{ \
if (!(expr)) \
abort (); \
} \
while (false)
#endif
#ifndef FALLTHROUGH
# if __GNUC__ < 7
# define FALLTHROUGH ((void) 0)
# else
# define FALLTHROUGH __attribute__ ((__fallthrough__))
# endif
#endif
static FTSENT *fts_alloc (FTS *, const char *, size_t) internal_function;
static FTSENT *fts_build (FTS *, int) internal_function;
static void fts_lfree (FTSENT *) internal_function;
static void fts_load (FTS *, FTSENT *) internal_function;
static size_t fts_maxarglen (char * const *) internal_function;
static void fts_padjust (FTS *, FTSENT *) internal_function;
static bool fts_palloc (FTS *, size_t) internal_function;
static FTSENT *fts_sort (FTS *, FTSENT *, size_t) internal_function;
static unsigned short int fts_stat (FTS *, FTSENT *, bool) internal_function;
static int fts_safe_changedir (FTS *, FTSENT *, int, const char *)
internal_function;
#include "fts-cycle.c"
#ifndef MAX
# define MAX(a,b) ((a) > (b) ? (a) : (b))
#endif
#ifndef SIZE_MAX
# define SIZE_MAX ((size_t) -1)
#endif
#define ISDOT(a) (a[0] == '.' && (!a[1] || (a[1] == '.' && !a[2])))
#define STREQ(a, b) (strcmp (a, b) == 0)
#define CLR(opt) (sp->fts_options &= ~(opt))
#define ISSET(opt) (sp->fts_options & (opt))
#define SET(opt) (sp->fts_options |= (opt))
/* FIXME: FTS_NOCHDIR is now misnamed.
Call it FTS_USE_FULL_RELATIVE_FILE_NAMES instead. */
#define FCHDIR(sp, fd) \
(!ISSET(FTS_NOCHDIR) && (ISSET(FTS_CWDFD) \
? (cwd_advance_fd ((sp), (fd), true), 0) \
: fchdir (fd)))
/* fts_build flags */
/* FIXME: make this an enum */
#define BCHILD 1 /* fts_children */
#define BNAMES 2 /* fts_children, names only */
#define BREAD 3 /* fts_read */
#if FTS_DEBUG
# include <inttypes.h>
# include <stdint.h>
# include <stdio.h>
# include "getcwdat.h"
bool fts_debug = false;
# define Dprintf(x) do { if (fts_debug) printf x; } while (false)
#else
# define Dprintf(x)
# define fd_ring_check(x)
# define fd_ring_print(a, b, c)
#endif
#define LEAVE_DIR(Fts, Ent, Tag) \
do \
{ \
Dprintf ((" %s-leaving: %s\n", Tag, (Ent)->fts_path)); \
leave_dir (Fts, Ent); \
fd_ring_check (Fts); \
} \
while (false)
static void
fd_ring_clear (I_ring *fd_ring)
{
while ( ! i_ring_empty (fd_ring))
{
int fd = i_ring_pop (fd_ring);
if (0 <= fd)
close (fd);
}
}
/* Overload the fts_statp->st_size member (otherwise unused, when
fts_info is FTS_NSOK) to indicate whether fts_read should stat
this entry or not. */
static void
fts_set_stat_required (FTSENT *p, bool required)
{
fts_assert (p->fts_info == FTS_NSOK);
p->fts_statp->st_size = (required
? FTS_STAT_REQUIRED
: FTS_NO_STAT_REQUIRED);
}
/* file-descriptor-relative opendir. */
/* FIXME: if others need this function, move it into lib/openat.c */
static DIR *
internal_function
opendirat (int fd, char const *dir, int extra_flags, int *pdir_fd)
{
int open_flags = (O_RDONLY | O_CLOEXEC | O_DIRECTORY | O_NOCTTY
| O_NONBLOCK | extra_flags);
int new_fd = openat (fd, dir, open_flags);
DIR *dirp;
if (new_fd < 0)
return NULL;
dirp = fdopendir (new_fd);
if (dirp)
*pdir_fd = new_fd;
else
{
int saved_errno = errno;
close (new_fd);
errno = saved_errno;
}
return dirp;
}
/* Virtual fchdir. Advance SP's working directory file descriptor,
SP->fts_cwd_fd, to FD, and push the previous value onto the fd_ring.
CHDIR_DOWN_ONE is true if FD corresponds to an entry in the directory
open on sp->fts_cwd_fd; i.e., to move the working directory one level
down. */
static void
internal_function
cwd_advance_fd (FTS *sp, int fd, bool chdir_down_one)
{
int old = sp->fts_cwd_fd;
fts_assert (old != fd || old == AT_FDCWD);
if (chdir_down_one)
{
/* Push "old" onto the ring.
If the displaced file descriptor is non-negative, close it. */
int prev_fd_in_slot = i_ring_push (&sp->fts_fd_ring, old);
fd_ring_print (sp, stderr, "post-push");
if (0 <= prev_fd_in_slot)
close (prev_fd_in_slot); /* ignore any close failure */
}
else if ( ! ISSET (FTS_NOCHDIR))
{
if (0 <= old)
close (old); /* ignore any close failure */
}
sp->fts_cwd_fd = fd;
}
/* Restore the initial, pre-traversal, "working directory".
In FTS_CWDFD mode, we merely call cwd_advance_fd, otherwise,
we may actually change the working directory.
Return 0 upon success. Upon failure, set errno and return nonzero. */
static int
restore_initial_cwd (FTS *sp)
{
int fail = FCHDIR (sp, ISSET (FTS_CWDFD) ? AT_FDCWD : sp->fts_rfd);
fd_ring_clear (&(sp->fts_fd_ring));
return fail;
}
/* Open the directory DIR if possible, and return a file
descriptor. Return -1 and set errno on failure. It doesn't matter
whether the file descriptor has read or write access. */
static int
internal_function
diropen (FTS const *sp, char const *dir)
{
int open_flags = (O_SEARCH | O_CLOEXEC | O_DIRECTORY | O_NOCTTY | O_NONBLOCK
| (ISSET (FTS_PHYSICAL) ? O_NOFOLLOW : 0)
| (ISSET (FTS_NOATIME) ? O_NOATIME : 0));
int fd = (ISSET (FTS_CWDFD)
? openat (sp->fts_cwd_fd, dir, open_flags)
: open (dir, open_flags));
return fd;
}
FTS *
fts_open (char * const *argv,
register int options,
int (*compar) (FTSENT const **, FTSENT const **))
{
register FTS *sp;
register FTSENT *p, *root;
register size_t nitems;
FTSENT *parent = NULL;
FTSENT *tmp = NULL; /* pacify gcc */
bool defer_stat;
/* Options check. */
if (options & ~FTS_OPTIONMASK) {
__set_errno (EINVAL);
return (NULL);
}
if ((options & FTS_NOCHDIR) && (options & FTS_CWDFD)) {
__set_errno (EINVAL);
return (NULL);
}
if ( ! (options & (FTS_LOGICAL | FTS_PHYSICAL))) {
__set_errno (EINVAL);
return (NULL);
}
/* Allocate/initialize the stream */
if ((sp = malloc(sizeof(FTS))) == NULL)
return (NULL);
memset(sp, 0, sizeof(FTS));
sp->fts_compar = compar;
sp->fts_options = options;
/* Logical walks turn on NOCHDIR; symbolic links are too hard. */
if (ISSET(FTS_LOGICAL)) {
SET(FTS_NOCHDIR);
CLR(FTS_CWDFD);
}
/* Initialize fts_cwd_fd. */
sp->fts_cwd_fd = AT_FDCWD;
if ( ISSET(FTS_CWDFD) && ! HAVE_OPENAT_SUPPORT)
{
/* While it isn't technically necessary to open "." this
early, doing it here saves us the trouble of ensuring
later (where it'd be messier) that "." can in fact
be opened. If not, revert to FTS_NOCHDIR mode. */
int fd = open (".",
O_SEARCH | (ISSET (FTS_NOATIME) ? O_NOATIME : 0));
if (fd < 0)
{
/* Even if "." is unreadable, don't revert to FTS_NOCHDIR mode
on systems like Linux+PROC_FS, where our openat emulation
is good enough. Note: on a system that emulates
openat via /proc, this technique can still fail, but
only in extreme conditions, e.g., when the working
directory cannot be saved (i.e. save_cwd fails) --
and that happens on Linux only when "." is unreadable
and the CWD would be longer than PATH_MAX.
FIXME: once Linux kernel openat support is well established,
replace the above open call and this entire if/else block
with the body of the if-block below. */
if ( openat_needs_fchdir ())
{
SET(FTS_NOCHDIR);
CLR(FTS_CWDFD);
}
}
else
{
close (fd);
}
}
/*
* Start out with 1K of file name space, and enough, in any case,
* to hold the user's file names.
*/
#ifndef MAXPATHLEN
# define MAXPATHLEN 1024
#endif
{
size_t maxarglen = fts_maxarglen(argv);
if (! fts_palloc(sp, MAX(maxarglen, MAXPATHLEN)))
goto mem1;
}
/* Allocate/initialize root's parent. */
if (*argv != NULL) {
if ((parent = fts_alloc(sp, "", 0)) == NULL)
goto mem2;
parent->fts_level = FTS_ROOTPARENTLEVEL;
parent->fts_n_dirs_remaining = -1;
}
/* The classic fts implementation would call fts_stat with
a new entry for each iteration of the loop below.
If the comparison function is not specified or if the
FTS_DEFER_STAT option is in effect, don't stat any entry
in this loop. This is an attempt to minimize the interval
between the initial stat/lstat/fstatat and the point at which
a directory argument is first opened. This matters for any
directory command line argument that resides on a file system
without genuine i-nodes. If you specify FTS_DEFER_STAT along
with a comparison function, that function must not access any
data via the fts_statp pointer. */
defer_stat = (compar == NULL || ISSET(FTS_DEFER_STAT));
/* Allocate/initialize root(s). */
for (root = NULL, nitems = 0; *argv != NULL; ++argv, ++nitems) {
/* *Do* allow zero-length file names. */
size_t len = strlen(*argv);
if ( ! (options & FTS_VERBATIM))
{
/* If there are two or more trailing slashes, trim all but one,
but don't change "//" to "/", and do map "///" to "/". */
char const *v = *argv;
if (2 < len && v[len - 1] == '/')
while (1 < len && v[len - 2] == '/')
--len;
}
if ((p = fts_alloc(sp, *argv, len)) == NULL)
goto mem3;
p->fts_level = FTS_ROOTLEVEL;
p->fts_parent = parent;
p->fts_accpath = p->fts_name;
/* Even when defer_stat is true, be sure to stat the first
command line argument, since fts_read (at least with
FTS_XDEV) requires that. */
if (defer_stat && root != NULL) {
p->fts_info = FTS_NSOK;
fts_set_stat_required(p, true);
} else {
p->fts_info = fts_stat(sp, p, false);
}
/*
* If comparison routine supplied, traverse in sorted
* order; otherwise traverse in the order specified.
*/
if (compar) {
p->fts_link = root;
root = p;
} else {
p->fts_link = NULL;
if (root == NULL)
tmp = root = p;
else {
tmp->fts_link = p;
tmp = p;
}
}
}
if (compar && nitems > 1)
root = fts_sort(sp, root, nitems);
/*
* Allocate a dummy pointer and make fts_read think that we've just
* finished the node before the root(s); set p->fts_info to FTS_INIT
* so that everything about the "current" node is ignored.
*/
if ((sp->fts_cur = fts_alloc(sp, "", 0)) == NULL)
goto mem3;
sp->fts_cur->fts_link = root;
sp->fts_cur->fts_info = FTS_INIT;
if (! setup_dir (sp))
goto mem3;
/*
* If using chdir(2), grab a file descriptor pointing to dot to ensure
* that we can get back here; this could be avoided for some file names,
* but almost certainly not worth the effort. Slashes, symbolic links,
* and ".." are all fairly nasty problems. Note, if we can't get the
* descriptor we run anyway, just more slowly.
*/
if (!ISSET(FTS_NOCHDIR) && !ISSET(FTS_CWDFD)
&& (sp->fts_rfd = diropen (sp, ".")) < 0)
SET(FTS_NOCHDIR);
i_ring_init (&sp->fts_fd_ring, -1);
return (sp);
mem3: fts_lfree(root);
free(parent);
mem2: free(sp->fts_path);
mem1: free(sp);
return (NULL);
}
static void
internal_function
fts_load (FTS *sp, register FTSENT *p)
{
register size_t len;
register char *cp;
/*
* Load the stream structure for the next traversal. Since we don't
* actually enter the directory until after the preorder visit, set
* the fts_accpath field specially so the chdir gets done to the right
* place and the user can access the first node. From fts_open it's
* known that the file name will fit.
*/
len = p->fts_pathlen = p->fts_namelen;
memmove(sp->fts_path, p->fts_name, len + 1);
if ((cp = strrchr(p->fts_name, '/')) && (cp != p->fts_name || cp[1])) {
len = strlen(++cp);
memmove(p->fts_name, cp, len + 1);
p->fts_namelen = len;
}
p->fts_accpath = p->fts_path = sp->fts_path;
}
int
fts_close (FTS *sp)
{
register FTSENT *freep, *p;
int saved_errno = 0;
/*
* This still works if we haven't read anything -- the dummy structure
* points to the root list, so we step through to the end of the root
* list which has a valid parent pointer.
*/
if (sp->fts_cur) {
for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
freep = p;
p = p->fts_link != NULL ? p->fts_link : p->fts_parent;
free(freep);
}
free(p);
}
/* Free up child linked list, sort array, file name buffer. */
if (sp->fts_child)
fts_lfree(sp->fts_child);
free(sp->fts_array);
free(sp->fts_path);
if (ISSET(FTS_CWDFD))
{
if (0 <= sp->fts_cwd_fd)
if (close (sp->fts_cwd_fd))
saved_errno = errno;
}
else if (!ISSET(FTS_NOCHDIR))
{
/* Return to original directory, save errno if necessary. */
if (fchdir(sp->fts_rfd))
saved_errno = errno;
/* If close fails, record errno only if saved_errno is zero,
so that we report the probably-more-meaningful fchdir errno. */
if (close (sp->fts_rfd))
if (saved_errno == 0)
saved_errno = errno;
}
fd_ring_clear (&sp->fts_fd_ring);
if (sp->fts_leaf_optimization_works_ht)
hash_free (sp->fts_leaf_optimization_works_ht);
free_dir (sp);
/* Free up the stream pointer. */
free(sp);
/* Set errno and return. */
if (saved_errno) {
__set_errno (saved_errno);
return (-1);
}
return (0);
}
/* Minimum link count of a traditional Unix directory. When leaf
optimization is OK and MIN_DIR_NLINK <= st_nlink, then st_nlink is
an upper bound on the number of subdirectories (counting "." and
".."). */
enum { MIN_DIR_NLINK = 2 };
/* Whether leaf optimization is OK for a directory. */
enum leaf_optimization
{
/* st_nlink is not reliable for this directory's subdirectories. */
NO_LEAF_OPTIMIZATION,
/* Leaf optimization is OK, but is not useful for avoiding stat calls. */
OK_LEAF_OPTIMIZATION,
/* Leaf optimization is not only OK: it is useful for avoiding
stat calls, because dirent.d_type does not work. */
NOSTAT_LEAF_OPTIMIZATION
};
#if defined __linux__ \
&& HAVE_SYS_VFS_H && HAVE_FSTATFS && HAVE_STRUCT_STATFS_F_TYPE
# include <sys/vfs.h>
/* Linux-specific constants from coreutils' src/fs.h */
# define S_MAGIC_AFS 0x5346414F
# define S_MAGIC_NFS 0x6969
# define S_MAGIC_PROC 0x9FA0
# define S_MAGIC_REISERFS 0x52654973
# define S_MAGIC_TMPFS 0x1021994
# define S_MAGIC_XFS 0x58465342
# ifdef HAVE___FSWORD_T
typedef __fsword_t fsword;
# else
typedef long int fsword;
# endif
/* Map a stat.st_dev number to a file system type number f_ftype. */
struct dev_type
{
dev_t st_dev;
fsword f_type;
};
/* Use a tiny initial size. If a traversal encounters more than
a few devices, the cost of growing/rehashing this table will be
rendered negligible by the number of inodes processed. */
enum { DEV_TYPE_HT_INITIAL_SIZE = 13 };
static size_t
dev_type_hash (void const *x, size_t table_size)
{
struct dev_type const *ax = x;
uintmax_t dev = ax->st_dev;
return dev % table_size;
}
static bool
dev_type_compare (void const *x, void const *y)
{
struct dev_type const *ax = x;
struct dev_type const *ay = y;
return ax->st_dev == ay->st_dev;
}
/* Return the file system type of P, or 0 if not known.
Try to cache known values. */
static fsword
filesystem_type (FTSENT const *p)
{
FTS *sp = p->fts_fts;
Hash_table *h = sp->fts_leaf_optimization_works_ht;
struct dev_type *ent;
struct statfs fs_buf;
/* If we're not in CWDFD mode, don't bother with this optimization,
since the caller is not serious about performance. */
if (!ISSET (FTS_CWDFD))
return 0;
if (! h)
h = sp->fts_leaf_optimization_works_ht
= hash_initialize (DEV_TYPE_HT_INITIAL_SIZE, NULL, dev_type_hash,
dev_type_compare, free);
if (h)
{
struct dev_type tmp;
tmp.st_dev = p->fts_statp->st_dev;
ent = hash_lookup (h, &tmp);
if (ent)
return ent->f_type;
}
/* Look-up failed. Query directly and cache the result. */
if (fstatfs (p->fts_fts->fts_cwd_fd, &fs_buf) != 0)
return 0;
if (h)
{
struct dev_type *t2 = malloc (sizeof *t2);
if (t2)
{
t2->st_dev = p->fts_statp->st_dev;
t2->f_type = fs_buf.f_type;
ent = hash_insert (h, t2);
if (ent)
fts_assert (ent == t2);
else
free (t2);
}
}
return fs_buf.f_type;
}
/* Return false if it is easy to determine the file system type of the
directory P, and sorting dirents on inode numbers is known not to
improve traversal performance with that type of file system.
Otherwise, return true. */
static bool
dirent_inode_sort_may_be_useful (FTSENT const *p)
{
/* Skip the sort only if we can determine efficiently
that skipping it is the right thing to do.
The cost of performing an unnecessary sort is negligible,
while the cost of *not* performing it can be O(N^2) with
a very large constant. */
switch (filesystem_type (p))
{
case S_MAGIC_TMPFS:
case S_MAGIC_NFS:
/* On a file system of any of these types, sorting
is unnecessary, and hence wasteful. */
return false;
default:
return true;
}
}
/* Given an FTS entry P for a directory D,
return true if it is both useful and valid to apply leaf optimization.
The optimization is useful only for file systems that lack usable
dirent.d_type info. The optimization is valid if an st_nlink value
of at least MIN_DIR_NLINK is an upper bound on the number of
subdirectories of D, counting "." and ".." as subdirectories. */
static enum leaf_optimization
leaf_optimization (FTSENT const *p)
{
switch (filesystem_type (p))
{
/* List here the file system types that may lack usable dirent.d_type
info, yet for which the optimization does apply. */
case S_MAGIC_REISERFS:
case S_MAGIC_XFS: /* XFS lacked it until 2013-08-22 commit. */
return NOSTAT_LEAF_OPTIMIZATION;
case 0:
/* Leaf optimization is unsafe if the file system type is unknown. */
FALLTHROUGH;
case S_MAGIC_AFS:
/* Although AFS mount points are not counted in st_nlink, they
act like directories. See <https://bugs.debian.org/143111>. */
FALLTHROUGH;
case S_MAGIC_NFS:
/* NFS provides usable dirent.d_type but not necessarily for all entries
of large directories, so as per <https://bugzilla.redhat.com/1252549>
NFS should return true. However st_nlink values are not accurate on
all implementations as per <https://bugzilla.redhat.com/1299169>. */
FALLTHROUGH;
case S_MAGIC_PROC:
/* Per <https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=143111> /proc
may have bogus stat.st_nlink values. */
return NO_LEAF_OPTIMIZATION;
default:
return OK_LEAF_OPTIMIZATION;
}
}
#else
static bool
dirent_inode_sort_may_be_useful (FTSENT const *p _GL_UNUSED)
{
return true;
}
static enum leaf_optimization
leaf_optimization (FTSENT const *p _GL_UNUSED)
{
return NO_LEAF_OPTIMIZATION;
}
#endif
/*
* Special case of "/" at the end of the file name so that slashes aren't
* appended which would cause file names to be written as "....//foo".
*/
#define NAPPEND(p) \
(p->fts_path[p->fts_pathlen - 1] == '/' \
? p->fts_pathlen - 1 : p->fts_pathlen)
FTSENT *
fts_read (register FTS *sp)
{
register FTSENT *p, *tmp;
register unsigned short int instr;
register char *t;
/* If finished or unrecoverable error, return NULL. */
if (sp->fts_cur == NULL || ISSET(FTS_STOP))
return (NULL);
/* Set current node pointer. */
p = sp->fts_cur;
/* Save and zero out user instructions. */
instr = p->fts_instr;
p->fts_instr = FTS_NOINSTR;
/* Any type of file may be re-visited; re-stat and re-turn. */
if (instr == FTS_AGAIN) {
p->fts_info = fts_stat(sp, p, false);
return (p);
}
Dprintf (("fts_read: p=%s\n",
p->fts_info == FTS_INIT ? "" : p->fts_path));
/*
* Following a symlink -- SLNONE test allows application to see
* SLNONE and recover. If indirecting through a symlink, have
* keep a pointer to current location. If unable to get that
* pointer, follow fails.
*/
if (instr == FTS_FOLLOW &&
(p->fts_info == FTS_SL || p->fts_info == FTS_SLNONE)) {
p->fts_info = fts_stat(sp, p, true);
if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
if ((p->fts_symfd = diropen (sp, ".")) < 0) {
p->fts_errno = errno;
p->fts_info = FTS_ERR;
} else
p->fts_flags |= FTS_SYMFOLLOW;
}
goto check_for_dir;
}
/* Directory in pre-order. */
if (p->fts_info == FTS_D) {
/* If skipped or crossed mount point, do post-order visit. */
if (instr == FTS_SKIP ||
(ISSET(FTS_XDEV) && p->fts_statp->st_dev != sp->fts_dev)) {
if (p->fts_flags & FTS_SYMFOLLOW)
(void)close(p->fts_symfd);
if (sp->fts_child) {
fts_lfree(sp->fts_child);
sp->fts_child = NULL;
}
p->fts_info = FTS_DP;
LEAVE_DIR (sp, p, "1");
return (p);
}
/* Rebuild if only read the names and now traversing. */
if (sp->fts_child != NULL && ISSET(FTS_NAMEONLY)) {
CLR(FTS_NAMEONLY);
fts_lfree(sp->fts_child);
sp->fts_child = NULL;
}
/*
* Cd to the subdirectory.
*
* If have already read and now fail to chdir, whack the list
* to make the names come out right, and set the parent errno
* so the application will eventually get an error condition.
* Set the FTS_DONTCHDIR flag so that when we logically change
* directories back to the parent we don't do a chdir.
*
* If haven't read do so. If the read fails, fts_build sets
* FTS_STOP or the fts_info field of the node.
*/
if (sp->fts_child != NULL) {
if (fts_safe_changedir(sp, p, -1, p->fts_accpath)) {
p->fts_errno = errno;
p->fts_flags |= FTS_DONTCHDIR;
for (p = sp->fts_child; p != NULL;
p = p->fts_link)
p->fts_accpath =
p->fts_parent->fts_accpath;
}
} else if ((sp->fts_child = fts_build(sp, BREAD)) == NULL) {
if (ISSET(FTS_STOP))
return (NULL);
/* If fts_build's call to fts_safe_changedir failed
because it was not able to fchdir into a
subdirectory, tell the caller. */
if (p->fts_errno && p->fts_info != FTS_DNR)
p->fts_info = FTS_ERR;
LEAVE_DIR (sp, p, "2");
return (p);
}
p = sp->fts_child;
sp->fts_child = NULL;
goto name;
}
/* Move to the next node on this level. */
next: tmp = p;
/* If we have so many directory entries that we're reading them
in batches, and we've reached the end of the current batch,
read in a new batch. */
if (p->fts_link == NULL && p->fts_parent->fts_dirp)
{
p = tmp->fts_parent;
sp->fts_cur = p;
sp->fts_path[p->fts_pathlen] = '\0';
if ((p = fts_build (sp, BREAD)) == NULL)
{
if (ISSET(FTS_STOP))
return NULL;
goto cd_dot_dot;
}
free(tmp);
goto name;
}
if ((p = p->fts_link) != NULL) {
sp->fts_cur = p;
free(tmp);
/*
* If reached the top, return to the original directory (or