1 /* Copyright (C) 1991-2024 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
9 The GNU C Library 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 GNU
12 Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public
15 License along with the GNU C Library; if not, see
16 <https://www.gnu.org/licenses/>. */
20 /* Don't use __attribute__ __nonnull__ in this compilation unit. Otherwise gcc
21 optimizes away the pattern == NULL test below. */
22 # define _GL_ARG_NONNULL(params)
24 # include <libc-config.h>
32 #include <sys/types.h>
34 #include <stdckdint.h>
40 #if defined _WIN32 && ! defined __CYGWIN__
56 # define strdup(str) __strdup (str)
57 # define sysconf(id) __sysconf (id)
58 # define closedir(dir) __closedir (dir)
59 # define opendir(name) __opendir (name)
61 # define dirfd(str) __dirfd (str)
62 # define readdir(str) __readdir64 (str)
63 # define getpwnam_r(name, bufp, buf, len, res) \
64 __getpwnam_r (name, bufp, buf, len, res)
65 # define FLEXIBLE_ARRAY_MEMBER
67 # define struct_stat struct stat
69 # ifndef struct_stat64
70 # define struct_stat64 struct stat64
73 # define GLOB_LSTAT gl_lstat
75 # ifndef GLOB_FSTATAT64
76 # define GLOB_FSTATAT64 __fstatat64
78 # include <shlib-compat.h>
81 # define __getlogin_r(buf, len) getlogin_r (buf, len)
82 # define __fxstatat64(_, d, f, st, flag) fstatat (d, f, st, flag)
84 # define __alloca alloca
86 # define __readdir readdir
87 # define COMPILE_GLOB64
88 # define struct_stat struct stat
89 # define struct_stat64 struct stat
90 # define GLOB_LSTAT gl_lstat
91 # define GLOB_FSTATAT64 fstatat
96 #include <flexmember.h>
97 #include <glob_internal.h>
98 #include <scratch_buffer.h>
100 static const char *next_brace_sub (const char *begin
, int flags
) __THROWNL
;
102 /* The type of ((struct dirent *) 0)->d_type is 'unsigned char' on most
103 platforms, but 'unsigned int' in the mingw from mingw.org. */
104 typedef uint_fast32_t dirent_type
;
106 #if !defined _LIBC && !defined HAVE_STRUCT_DIRENT_D_TYPE
107 /* Any distinct values will do here.
108 Undef any existing macros out of the way. */
112 # define DT_UNKNOWN 0
117 /* A representation of a directory entry which does not depend on the
118 layout of struct dirent, or the size of ino_t. */
119 struct readdir_result
122 #if defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE
127 /* Initialize and return type member of struct readdir_result. */
129 readdir_result_type (struct readdir_result d
)
131 #if defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE
132 # define D_TYPE_TO_RESULT(source) (source)->d_type,
135 # define D_TYPE_TO_RESULT(source)
140 /* Construct an initializer for a struct readdir_result object from a
141 struct dirent *. No copy of the name is made. */
142 #define READDIR_RESULT_INITIALIZER(source) \
145 D_TYPE_TO_RESULT (source) \
148 /* Call gl_readdir on STREAM. This macro can be overridden to reduce
149 type safety if an old interface version needs to be supported. */
151 # define GL_READDIR(pglob, stream) ((pglob)->gl_readdir (stream))
154 /* Extract name and type from directory entry. No copy of the name is
155 made. If SOURCE is NULL, result name is NULL. Keep in sync with
156 convert_dirent64 below. */
157 static struct readdir_result
158 convert_dirent (const struct dirent
*source
)
162 struct readdir_result result
= { NULL
, };
165 struct readdir_result result
= READDIR_RESULT_INITIALIZER (source
);
169 #ifndef COMPILE_GLOB64
170 /* Like convert_dirent, but works on struct dirent64 instead. Keep in
171 sync with convert_dirent above. */
172 static struct readdir_result
173 convert_dirent64 (const struct dirent64
*source
)
177 struct readdir_result result
= { NULL
, };
180 struct readdir_result result
= READDIR_RESULT_INITIALIZER (source
);
186 /* The results of opendir() in this file are used with dirfd. But they are
187 not used with fchdir, and we do not leak fds to any single-threaded code
188 that could use stdio, therefore save some unnecessary recursion in
189 fchdir.c and opendir_safer.c. */
190 # ifndef GNULIB_defined_DIR
191 # ifdef GNULIB_defined_opendir
194 # ifdef GNULIB_defined_closedir
199 /* Just use malloc. */
200 # define __libc_use_alloca(n) false
201 # define alloca_account(len, avar) ((void) (len), (void) (avar), (void *) 0)
202 # define extend_alloca_account(buf, len, newlen, avar) \
203 ((void) (buf), (void) (len), (void) (newlen), (void) (avar), (void *) 0)
207 glob_lstat (glob_t
*pglob
, int flags
, const char *fullname
)
209 /* Use on glob-lstat-compat.c to provide a compat symbol which does not
210 use lstat / gl_lstat. */
216 return (__glibc_unlikely (flags
& GLOB_ALTDIRFUNC
)
217 ? pglob
->GLOB_LSTAT (fullname
, &ust
.st
)
218 : GLOB_FSTATAT64 (AT_FDCWD
, fullname
, &ust
.st64
,
219 AT_SYMLINK_NOFOLLOW
));
223 glob_use_alloca (size_t alloca_used
, size_t len
)
226 return (!ckd_add (&size
, alloca_used
, len
)
227 && __libc_use_alloca (size
));
230 static int glob_in_dir (const char *pattern
, const char *directory
,
231 int flags
, int (*errfunc
) (const char *, int),
232 glob_t
*pglob
, size_t alloca_used
);
233 static int prefix_array (const char *prefix
, char **array
, size_t n
) __THROWNL
;
234 static int collated_compare (const void *, const void *) __THROWNL
;
237 /* Return true if FILENAME is a directory or a symbolic link to a directory.
238 Use FLAGS and PGLOB to resolve the filename. */
240 is_dir (char const *filename
, int flags
, glob_t
const *pglob
)
244 return (__glibc_unlikely (flags
& GLOB_ALTDIRFUNC
)
245 ? pglob
->gl_stat (filename
, &st
) == 0 && S_ISDIR (st
.st_mode
)
246 : (GLOB_FSTATAT64 (AT_FDCWD
, filename
, &st64
, 0) == 0
247 && S_ISDIR (st64
.st_mode
)));
250 /* Find the end of the sub-pattern in a brace expression. */
252 next_brace_sub (const char *cp
, int flags
)
256 if ((flags
& GLOB_NOESCAPE
) == 0 && *cp
== '\\')
264 if ((*cp
== '}' && depth
-- == 0) || (*cp
== ',' && depth
== 0))
271 return *cp
!= '\0' ? cp
: NULL
;
274 #ifndef GLOB_ATTRIBUTE
275 # define GLOB_ATTRIBUTE
278 /* Do glob searching for PATTERN, placing results in PGLOB.
279 The bits defined above may be set in FLAGS.
280 If a directory cannot be opened or read and ERRFUNC is not nil,
281 it is called with the pathname that caused the error, and the
282 'errno' value from the failing call; if it returns non-zero
283 'glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
284 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
285 Otherwise, 'glob' returns zero. */
288 __glob (const char *pattern
, int flags
, int (*errfunc
) (const char *, int),
291 const char *filename
;
292 char *dirname
= NULL
;
297 int dirname_modified
;
298 int malloc_dirname
= 0;
301 size_t alloca_used
= 0;
303 if (pattern
== NULL
|| pglob
== NULL
|| (flags
& ~__GLOB_FLAGS
) != 0)
305 __set_errno (EINVAL
);
309 /* POSIX requires all slashes to be matched. This means that with
310 a trailing slash we must match only directories. */
311 if (pattern
[0] && pattern
[strlen (pattern
) - 1] == '/')
312 flags
|= GLOB_ONLYDIR
;
314 if (!(flags
& GLOB_DOOFFS
))
315 /* Have to do this so 'globfree' knows where to start freeing. It
316 also makes all the code that uses gl_offs simpler. */
319 if (!(flags
& GLOB_APPEND
))
322 if (!(flags
& GLOB_DOOFFS
))
323 pglob
->gl_pathv
= NULL
;
328 if (pglob
->gl_offs
>= ~((size_t) 0) / sizeof (char *))
331 pglob
->gl_pathv
= (char **) malloc ((pglob
->gl_offs
+ 1)
333 if (pglob
->gl_pathv
== NULL
)
336 for (i
= 0; i
<= pglob
->gl_offs
; ++i
)
337 pglob
->gl_pathv
[i
] = NULL
;
341 if (flags
& GLOB_BRACE
)
345 if (flags
& GLOB_NOESCAPE
)
346 begin
= strchr (pattern
, '{');
358 if (*begin
== '\\' && begin
[1] != '\0')
360 else if (*begin
== '{')
369 /* Allocate working buffer large enough for our work. Note that
370 we have at least an opening and closing brace. */
378 size_t pattern_len
= strlen (pattern
) - 1;
379 int alloca_onealt
= glob_use_alloca (alloca_used
, pattern_len
);
381 onealt
= alloca_account (pattern_len
, alloca_used
);
384 onealt
= malloc (pattern_len
);
389 /* We know the prefix for all sub-patterns. */
390 alt_start
= mempcpy (onealt
, pattern
, begin
- pattern
);
392 /* Find the first sub-pattern and at the same time find the
393 rest after the closing brace. */
394 next
= next_brace_sub (begin
+ 1, flags
);
397 /* It is an invalid expression. */
399 if (__glibc_unlikely (!alloca_onealt
))
401 flags
&= ~GLOB_BRACE
;
405 /* Now find the end of the whole brace expression. */
409 rest
= next_brace_sub (rest
+ 1, flags
);
411 /* It is an illegal expression. */
414 /* Please note that we now can be sure the brace expression
416 rest_len
= strlen (++rest
) + 1;
418 /* We have a brace expression. BEGIN points to the opening {,
419 NEXT points past the terminator of the first element, and END
420 points past the final }. We will accumulate result names from
421 recursive runs for each brace alternative in the buffer using
423 firstc
= pglob
->gl_pathc
;
430 /* Construct the new glob expression. */
431 mempcpy (mempcpy (alt_start
, p
, next
- p
), rest
, rest_len
);
433 result
= __glob (onealt
,
434 ((flags
& ~(GLOB_NOCHECK
| GLOB_NOMAGIC
))
438 /* If we got an error, return it. */
439 if (result
&& result
!= GLOB_NOMATCH
)
441 if (__glibc_unlikely (!alloca_onealt
))
443 if (!(flags
& GLOB_APPEND
))
452 /* We saw the last entry. */
456 next
= next_brace_sub (p
, flags
);
457 assert (next
!= NULL
);
460 if (__glibc_unlikely (!alloca_onealt
))
463 if (pglob
->gl_pathc
!= firstc
)
464 /* We found some entries. */
466 else if (!(flags
& (GLOB_NOCHECK
|GLOB_NOMAGIC
)))
472 oldcount
= pglob
->gl_pathc
+ pglob
->gl_offs
;
474 /* Find the filename. */
475 filename
= strrchr (pattern
, '/');
477 #if defined __MSDOS__ || defined WINDOWS32
478 /* The case of "d:pattern". Since ':' is not allowed in
479 file names, we can safely assume that wherever it
480 happens in pattern, it signals the filename part. This
481 is so we could some day support patterns like "[a-z]:foo". */
482 if (filename
== NULL
)
483 filename
= strchr (pattern
, ':');
484 #endif /* __MSDOS__ || WINDOWS32 */
486 dirname_modified
= 0;
487 if (filename
== NULL
)
489 /* This can mean two things: a simple name or "~name". The latter
490 case is nothing but a notation for a directory. */
491 if ((flags
& (GLOB_TILDE
|GLOB_TILDE_CHECK
)) && pattern
[0] == '~')
493 dirname
= (char *) pattern
;
494 dirlen
= strlen (pattern
);
496 /* Set FILENAME to NULL as a special flag. This is ugly but
497 other solutions would require much more code. We test for
498 this special case below. */
503 if (__glibc_unlikely (pattern
[0] == '\0'))
505 dirs
.gl_pathv
= NULL
;
510 dirname
= (char *) ".";
514 else if (filename
== pattern
515 || (filename
== pattern
+ 1 && pattern
[0] == '\\'
516 && (flags
& GLOB_NOESCAPE
) == 0))
518 /* "/pattern" or "\\/pattern". */
519 dirname
= (char *) "/";
526 dirlen
= filename
- pattern
;
527 #if defined __MSDOS__ || defined WINDOWS32
529 || (filename
> pattern
+ 1 && filename
[-1] == ':'))
534 drive_spec
= __alloca (dirlen
+ 1);
535 *((char *) mempcpy (drive_spec
, pattern
, dirlen
)) = '\0';
536 /* For now, disallow wildcards in the drive spec, to
537 prevent infinite recursion in glob. */
538 if (__glob_pattern_p (drive_spec
, !(flags
& GLOB_NOESCAPE
)))
540 /* If this is "d:pattern", we need to copy ':' to DIRNAME
541 as well. If it's "d:/pattern", don't remove the slash
542 from "d:/", since "d:" and "d:/" are not the same.*/
546 if (glob_use_alloca (alloca_used
, dirlen
+ 1))
547 newp
= alloca_account (dirlen
+ 1, alloca_used
);
550 newp
= malloc (dirlen
+ 1);
555 *((char *) mempcpy (newp
, pattern
, dirlen
)) = '\0';
559 #if defined __MSDOS__ || defined WINDOWS32
560 bool drive_root
= (dirlen
> 1
561 && (dirname
[dirlen
- 1] == ':'
562 || (dirlen
> 2 && dirname
[dirlen
- 2] == ':'
563 && dirname
[dirlen
- 1] == '/')));
565 bool drive_root
= false;
568 if (filename
[0] == '\0' && dirlen
> 1 && !drive_root
)
569 /* "pattern/". Expand "pattern", appending slashes. */
571 int orig_flags
= flags
;
572 if (!(flags
& GLOB_NOESCAPE
) && dirname
[dirlen
- 1] == '\\')
574 /* "pattern\\/". Remove the final backslash if it hasn't
576 char *p
= (char *) &dirname
[dirlen
- 1];
578 while (p
> dirname
&& p
[-1] == '\\') --p
;
579 if ((&dirname
[dirlen
] - p
) & 1)
581 *(char *) &dirname
[--dirlen
] = '\0';
582 flags
&= ~(GLOB_NOCHECK
| GLOB_NOMAGIC
);
585 int val
= __glob (dirname
, flags
| GLOB_MARK
, errfunc
, pglob
);
587 pglob
->gl_flags
= ((pglob
->gl_flags
& ~GLOB_MARK
)
588 | (flags
& GLOB_MARK
));
589 else if (val
== GLOB_NOMATCH
&& flags
!= orig_flags
)
591 /* Make sure globfree (&dirs); is a nop. */
592 dirs
.gl_pathv
= NULL
;
594 oldcount
= pglob
->gl_pathc
+ pglob
->gl_offs
;
602 if ((flags
& (GLOB_TILDE
|GLOB_TILDE_CHECK
)) && dirname
[0] == '~')
604 if (dirname
[1] == '\0' || dirname
[1] == '/'
605 || (!(flags
& GLOB_NOESCAPE
) && dirname
[1] == '\\'
606 && (dirname
[2] == '\0' || dirname
[2] == '/')))
608 /* Look up home directory. */
609 char *home_dir
= getenv ("HOME");
610 int malloc_home_dir
= 0;
611 if (home_dir
== NULL
|| home_dir
[0] == '\0')
614 /* Windows NT defines HOMEDRIVE and HOMEPATH. But give
615 preference to HOME, because the user can change HOME. */
616 const char *home_drive
= getenv ("HOMEDRIVE");
617 const char *home_path
= getenv ("HOMEPATH");
619 if (home_drive
!= NULL
&& home_path
!= NULL
)
621 size_t home_drive_len
= strlen (home_drive
);
622 size_t home_path_len
= strlen (home_path
);
623 char *mem
= alloca (home_drive_len
+ home_path_len
+ 1);
625 memcpy (mem
, home_drive
, home_drive_len
);
626 memcpy (mem
+ home_drive_len
, home_path
, home_path_len
+ 1);
630 home_dir
= "c:/users/default"; /* poor default */
635 struct scratch_buffer s
;
636 scratch_buffer_init (&s
);
640 err
= __getlogin_r (s
.data
, s
.length
);
643 # if defined HAVE_GETPWNAM_R || defined _LIBC
644 size_t ssize
= strlen (s
.data
) + 1;
645 char *sdata
= s
.data
;
646 err
= getpwnam_r (sdata
, &pwbuf
, sdata
+ ssize
,
647 s
.length
- ssize
, &p
);
649 p
= getpwnam (s
.data
);
656 if (!scratch_buffer_grow (&s
))
658 retval
= GLOB_NOSPACE
;
664 home_dir
= strdup (p
->pw_dir
);
667 scratch_buffer_free (&s
);
668 if (err
== 0 && home_dir
== NULL
)
670 retval
= GLOB_NOSPACE
;
673 #endif /* WINDOWS32 */
675 if (home_dir
== NULL
|| home_dir
[0] == '\0')
677 if (__glibc_unlikely (malloc_home_dir
))
679 if (flags
& GLOB_TILDE_CHECK
)
681 retval
= GLOB_NOMATCH
;
686 home_dir
= (char *) "~"; /* No luck. */
690 /* Now construct the full directory. */
691 if (dirname
[1] == '\0')
693 if (__glibc_unlikely (malloc_dirname
))
697 dirlen
= strlen (dirname
);
698 malloc_dirname
= malloc_home_dir
;
703 size_t home_len
= strlen (home_dir
);
704 int use_alloca
= glob_use_alloca (alloca_used
, home_len
+ dirlen
);
706 newp
= alloca_account (home_len
+ dirlen
, alloca_used
);
709 newp
= malloc (home_len
+ dirlen
);
712 if (__glibc_unlikely (malloc_home_dir
))
714 retval
= GLOB_NOSPACE
;
719 mempcpy (mempcpy (newp
, home_dir
, home_len
),
720 &dirname
[1], dirlen
);
722 if (__glibc_unlikely (malloc_dirname
))
726 dirlen
+= home_len
- 1;
727 malloc_dirname
= !use_alloca
;
729 if (__glibc_unlikely (malloc_home_dir
))
732 dirname_modified
= 1;
737 /* Recognize ~user as a shorthand for the specified user's home
739 char *end_name
= strchr (dirname
, '/');
741 int malloc_user_name
= 0;
742 char *unescape
= NULL
;
744 if (!(flags
& GLOB_NOESCAPE
))
746 if (end_name
== NULL
)
748 unescape
= strchr (dirname
, '\\');
750 end_name
= strchr (unescape
, '\0');
753 unescape
= memchr (dirname
, '\\', end_name
- dirname
);
755 if (end_name
== NULL
)
756 user_name
= dirname
+ 1;
760 if (glob_use_alloca (alloca_used
, end_name
- dirname
))
761 newp
= alloca_account (end_name
- dirname
, alloca_used
);
764 newp
= malloc (end_name
- dirname
);
767 retval
= GLOB_NOSPACE
;
770 malloc_user_name
= 1;
772 if (unescape
!= NULL
)
774 char *p
= mempcpy (newp
, dirname
+ 1,
775 unescape
- dirname
- 1);
777 while (q
!= end_name
)
781 if (q
+ 1 == end_name
)
783 /* "~fo\\o\\" unescape to user_name "foo\\",
784 but "~fo\\o\\/" unescape to user_name
786 if (filename
== NULL
)
797 *((char *) mempcpy (newp
, dirname
+ 1, end_name
- dirname
- 1))
802 /* Look up specific user's home directory. */
805 struct scratch_buffer pwtmpbuf
;
806 scratch_buffer_init (&pwtmpbuf
);
808 # if defined HAVE_GETPWNAM_R || defined _LIBC
811 while (getpwnam_r (user_name
, &pwbuf
,
812 pwtmpbuf
.data
, pwtmpbuf
.length
, &p
)
815 if (!scratch_buffer_grow (&pwtmpbuf
))
817 retval
= GLOB_NOSPACE
;
822 p
= getpwnam (user_name
);
825 if (__glibc_unlikely (malloc_user_name
))
828 /* If we found a home directory use this. */
831 size_t home_len
= strlen (p
->pw_dir
);
832 size_t rest_len
= end_name
== NULL
? 0 : strlen (end_name
);
833 /* dirname contains end_name; we can't free it now. */
835 (__glibc_unlikely (malloc_dirname
) ? dirname
: NULL
);
840 if (glob_use_alloca (alloca_used
, home_len
+ rest_len
+ 1))
841 dirname
= alloca_account (home_len
+ rest_len
+ 1,
845 dirname
= malloc (home_len
+ rest_len
+ 1);
849 scratch_buffer_free (&pwtmpbuf
);
850 retval
= GLOB_NOSPACE
;
855 d
= mempcpy (dirname
, p
->pw_dir
, home_len
);
856 if (end_name
!= NULL
)
857 d
= mempcpy (d
, end_name
, rest_len
);
862 dirlen
= home_len
+ rest_len
;
863 dirname_modified
= 1;
867 if (flags
& GLOB_TILDE_CHECK
)
869 /* We have to regard it as an error if we cannot find the
871 retval
= GLOB_NOMATCH
;
875 scratch_buffer_free (&pwtmpbuf
);
877 #else /* WINDOWS32 */
878 /* On native Windows, access to a user's home directory
879 (via GetUserProfileDirectory) or to a user's environment
880 variables (via ExpandEnvironmentStringsForUser) requires
881 the credentials of the user. Therefore we cannot support
882 the ~user syntax on this platform.
883 Handling ~user specially (and treat it like plain ~) if
884 user is getenv ("USERNAME") would not be a good idea,
885 since it would make people think that ~user is supported
887 if (flags
& GLOB_TILDE_CHECK
)
889 retval
= GLOB_NOMATCH
;
892 #endif /* WINDOWS32 */
896 /* Now test whether we looked for "~" or "~NAME". In this case we
897 can give the answer now. */
898 if (filename
== NULL
)
900 size_t newcount
= pglob
->gl_pathc
+ pglob
->gl_offs
;
903 if (newcount
> SIZE_MAX
/ sizeof (char *) - 2)
906 free (pglob
->gl_pathv
);
907 pglob
->gl_pathv
= NULL
;
909 retval
= GLOB_NOSPACE
;
913 new_gl_pathv
= realloc (pglob
->gl_pathv
,
914 (newcount
+ 2) * sizeof (char *));
915 if (new_gl_pathv
== NULL
)
917 pglob
->gl_pathv
= new_gl_pathv
;
919 if (flags
& GLOB_MARK
&& is_dir (dirname
, flags
, pglob
))
922 pglob
->gl_pathv
[newcount
] = malloc (dirlen
+ 2);
923 if (pglob
->gl_pathv
[newcount
] == NULL
)
925 p
= mempcpy (pglob
->gl_pathv
[newcount
], dirname
, dirlen
);
928 if (__glibc_unlikely (malloc_dirname
))
933 if (__glibc_unlikely (malloc_dirname
))
934 pglob
->gl_pathv
[newcount
] = dirname
;
937 pglob
->gl_pathv
[newcount
] = strdup (dirname
);
938 if (pglob
->gl_pathv
[newcount
] == NULL
)
942 pglob
->gl_pathv
[++newcount
] = NULL
;
944 pglob
->gl_flags
= flags
;
949 meta
= __glob_pattern_type (dirname
, !(flags
& GLOB_NOESCAPE
));
950 /* meta is 1 if correct glob pattern containing metacharacters.
951 If meta has bit (1 << 2) set, it means there was an unterminated
952 [ which we handle the same, using fnmatch. Broken unterminated
953 pattern bracket expressions ought to be rare enough that it is
954 not worth special casing them, fnmatch will do the right thing. */
955 if (meta
& (GLOBPAT_SPECIAL
| GLOBPAT_BRACKET
))
957 /* The directory name contains metacharacters, so we
958 have to glob for the directory, and then glob for
959 the pattern in each directory found. */
962 if (!(flags
& GLOB_NOESCAPE
) && dirlen
> 0 && dirname
[dirlen
- 1] == '\\')
964 /* "foo\\/bar". Remove the final backslash from dirname
965 if it has not been quoted. */
966 char *p
= (char *) &dirname
[dirlen
- 1];
968 while (p
> dirname
&& p
[-1] == '\\') --p
;
969 if ((&dirname
[dirlen
] - p
) & 1)
970 *(char *) &dirname
[--dirlen
] = '\0';
973 if (__glibc_unlikely ((flags
& GLOB_ALTDIRFUNC
) != 0))
975 /* Use the alternative access functions also in the recursive
977 dirs
.gl_opendir
= pglob
->gl_opendir
;
978 dirs
.gl_readdir
= pglob
->gl_readdir
;
979 dirs
.gl_closedir
= pglob
->gl_closedir
;
980 dirs
.gl_stat
= pglob
->gl_stat
;
981 dirs
.gl_lstat
= pglob
->gl_lstat
;
984 status
= __glob (dirname
,
985 ((flags
& (GLOB_ERR
| GLOB_NOESCAPE
| GLOB_ALTDIRFUNC
))
986 | GLOB_NOSORT
| GLOB_ONLYDIR
),
990 if ((flags
& GLOB_NOCHECK
) == 0 || status
!= GLOB_NOMATCH
)
998 /* We have successfully globbed the preceding directory name.
999 For each name we found, call glob_in_dir on it and FILENAME,
1000 appending the results to PGLOB. */
1001 for (i
= 0; i
< dirs
.gl_pathc
; ++i
)
1005 old_pathc
= pglob
->gl_pathc
;
1006 status
= glob_in_dir (filename
, dirs
.gl_pathv
[i
],
1007 ((flags
| GLOB_APPEND
)
1008 & ~(GLOB_NOCHECK
| GLOB_NOMAGIC
)),
1009 errfunc
, pglob
, alloca_used
);
1010 if (status
== GLOB_NOMATCH
)
1011 /* No matches in this directory. Try the next. */
1018 pglob
->gl_pathc
= 0;
1023 /* Stick the directory on the front of each name. */
1024 if (prefix_array (dirs
.gl_pathv
[i
],
1025 &pglob
->gl_pathv
[old_pathc
+ pglob
->gl_offs
],
1026 pglob
->gl_pathc
- old_pathc
))
1030 pglob
->gl_pathc
= 0;
1031 retval
= GLOB_NOSPACE
;
1036 flags
|= GLOB_MAGCHAR
;
1038 /* We have ignored the GLOB_NOCHECK flag in the 'glob_in_dir' calls.
1039 But if we have not found any matching entry and the GLOB_NOCHECK
1040 flag was set we must return the input pattern itself. */
1041 if (pglob
->gl_pathc
+ pglob
->gl_offs
== oldcount
)
1045 if (flags
& GLOB_NOCHECK
)
1047 size_t newcount
= pglob
->gl_pathc
+ pglob
->gl_offs
;
1048 char **new_gl_pathv
;
1050 if (newcount
> SIZE_MAX
/ sizeof (char *) - 2)
1054 retval
= GLOB_NOSPACE
;
1058 new_gl_pathv
= realloc (pglob
->gl_pathv
,
1059 (newcount
+ 2) * sizeof (char *));
1060 if (new_gl_pathv
== NULL
)
1062 pglob
->gl_pathv
= new_gl_pathv
;
1064 pglob
->gl_pathv
[newcount
] = strdup (pattern
);
1065 if (pglob
->gl_pathv
[newcount
] == NULL
)
1069 pglob
->gl_pathc
= 0;
1070 retval
= GLOB_NOSPACE
;
1077 pglob
->gl_pathv
[newcount
] = NULL
;
1078 pglob
->gl_flags
= flags
;
1083 retval
= GLOB_NOMATCH
;
1092 size_t old_pathc
= pglob
->gl_pathc
;
1093 int orig_flags
= flags
;
1095 if (meta
& GLOBPAT_BACKSLASH
)
1097 char *p
= strchr (dirname
, '\\'), *q
;
1098 /* We need to unescape the dirname string. It is certainly
1099 allocated by alloca, as otherwise filename would be NULL
1100 or dirname wouldn't contain backslashes. */
1113 while (*p
++ != '\0');
1114 dirname_modified
= 1;
1116 if (dirname_modified
)
1117 flags
&= ~(GLOB_NOCHECK
| GLOB_NOMAGIC
);
1118 status
= glob_in_dir (filename
, dirname
, flags
, errfunc
, pglob
,
1122 if (status
== GLOB_NOMATCH
&& flags
!= orig_flags
1123 && pglob
->gl_pathc
+ pglob
->gl_offs
== oldcount
)
1125 /* Make sure globfree (&dirs); is a nop. */
1126 dirs
.gl_pathv
= NULL
;
1136 /* Stick the directory on the front of each name. */
1137 if (prefix_array (dirname
,
1138 &pglob
->gl_pathv
[old_pathc
+ pglob
->gl_offs
],
1139 pglob
->gl_pathc
- old_pathc
))
1142 pglob
->gl_pathc
= 0;
1143 retval
= GLOB_NOSPACE
;
1149 if (flags
& GLOB_MARK
)
1151 /* Append slashes to directory names. */
1154 for (i
= oldcount
; i
< pglob
->gl_pathc
+ pglob
->gl_offs
; ++i
)
1155 if (is_dir (pglob
->gl_pathv
[i
], flags
, pglob
))
1157 size_t len
= strlen (pglob
->gl_pathv
[i
]) + 2;
1158 char *new = realloc (pglob
->gl_pathv
[i
], len
);
1162 pglob
->gl_pathc
= 0;
1163 retval
= GLOB_NOSPACE
;
1166 strcpy (&new[len
- 2], "/");
1167 pglob
->gl_pathv
[i
] = new;
1171 if (!(flags
& GLOB_NOSORT
))
1173 /* Sort the vector. */
1174 qsort (&pglob
->gl_pathv
[oldcount
],
1175 pglob
->gl_pathc
+ pglob
->gl_offs
- oldcount
,
1176 sizeof (char *), collated_compare
);
1180 if (__glibc_unlikely (malloc_dirname
))
1185 #if defined _LIBC && !defined __glob
1186 versioned_symbol (libc
, __glob
, glob
, GLIBC_2_27
);
1187 libc_hidden_ver (__glob
, glob
)
1191 /* Do a collated comparison of A and B. */
1193 collated_compare (const void *a
, const void *b
)
1195 char *const *ps1
= a
; char *s1
= *ps1
;
1196 char *const *ps2
= b
; char *s2
= *ps2
;
1204 return strcoll (s1
, s2
);
1208 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1209 elements in place. Return nonzero if out of memory, zero if successful.
1210 A slash is inserted between DIRNAME and each elt of ARRAY,
1211 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1213 prefix_array (const char *dirname
, char **array
, size_t n
)
1216 size_t dirlen
= strlen (dirname
);
1217 char dirsep_char
= '/';
1219 if (dirlen
== 1 && dirname
[0] == '/')
1220 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1221 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1224 #if defined __MSDOS__ || defined WINDOWS32
1227 if (dirname
[dirlen
- 1] == '/' && dirname
[dirlen
- 2] == ':')
1228 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1230 else if (dirname
[dirlen
- 1] == ':')
1232 /* DIRNAME is "d:". Use ':' instead of '/'. */
1239 for (i
= 0; i
< n
; ++i
)
1241 size_t eltlen
= strlen (array
[i
]) + 1;
1242 char *new = malloc (dirlen
+ 1 + eltlen
);
1251 char *endp
= mempcpy (new, dirname
, dirlen
);
1252 *endp
++ = dirsep_char
;
1253 mempcpy (endp
, array
[i
], eltlen
);
1262 /* Like 'glob', but PATTERN is a final pathname component,
1263 and matches are searched for in DIRECTORY.
1264 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1265 The GLOB_APPEND flag is assumed to be set (always appends). */
1267 glob_in_dir (const char *pattern
, const char *directory
, int flags
,
1268 int (*errfunc
) (const char *, int),
1269 glob_t
*pglob
, size_t alloca_used
)
1271 size_t dirlen
= strlen (directory
);
1272 void *stream
= NULL
;
1273 struct scratch_buffer s
;
1274 scratch_buffer_init (&s
);
1275 # define GLOBNAMES_MEMBERS(nnames) \
1276 struct globnames *next; size_t count; char *name[nnames];
1277 struct globnames
{ GLOBNAMES_MEMBERS (FLEXIBLE_ARRAY_MEMBER
) };
1278 struct { GLOBNAMES_MEMBERS (64) } init_names_buf
;
1279 struct globnames
*init_names
= (struct globnames
*) &init_names_buf
;
1280 struct globnames
*names
= init_names
;
1281 struct globnames
*names_alloca
= init_names
;
1288 alloca_used
+= sizeof init_names_buf
;
1290 init_names
->next
= NULL
;
1291 init_names
->count
= ((sizeof init_names_buf
1292 - offsetof (struct globnames
, name
))
1293 / sizeof init_names
->name
[0]);
1295 meta
= __glob_pattern_type (pattern
, !(flags
& GLOB_NOESCAPE
));
1296 if (meta
== GLOBPAT_NONE
&& (flags
& (GLOB_NOCHECK
|GLOB_NOMAGIC
)))
1298 /* We need not do any tests. The PATTERN contains no meta
1299 characters and we must not return an error therefore the
1300 result will always contain exactly one name. */
1301 flags
|= GLOB_NOCHECK
;
1303 else if (meta
== GLOBPAT_NONE
)
1305 size_t patlen
= strlen (pattern
);
1307 bool alloca_fullname
1308 = (!ckd_add (&fullsize
, dirlen
+ 1, patlen
+ 1)
1309 && glob_use_alloca (alloca_used
, fullsize
));
1311 if (alloca_fullname
)
1312 fullname
= alloca_account (fullsize
, alloca_used
);
1315 fullname
= malloc (fullsize
);
1316 if (fullname
== NULL
)
1317 return GLOB_NOSPACE
;
1320 mempcpy (mempcpy (mempcpy (fullname
, directory
, dirlen
),
1322 pattern
, patlen
+ 1);
1323 if (glob_lstat (pglob
, flags
, fullname
) == 0
1324 || errno
== EOVERFLOW
)
1325 /* We found this file to be existing. Now tell the rest
1326 of the function to copy this name into the result. */
1327 flags
|= GLOB_NOCHECK
;
1329 if (__glibc_unlikely (!alloca_fullname
))
1334 stream
= (__builtin_expect (flags
& GLOB_ALTDIRFUNC
, 0)
1335 ? (*pglob
->gl_opendir
) (directory
)
1336 : opendir (directory
));
1339 if (errno
!= ENOTDIR
1340 && ((errfunc
!= NULL
&& (*errfunc
) (directory
, errno
))
1341 || (flags
& GLOB_ERR
)))
1342 return GLOB_ABORTED
;
1347 int dfd
= dirfd (dirp
);
1348 int fnm_flags
= ((!(flags
& GLOB_PERIOD
) ? FNM_PERIOD
: 0)
1349 | ((flags
& GLOB_NOESCAPE
) ? FNM_NOESCAPE
: 0));
1350 flags
|= GLOB_MAGCHAR
;
1354 struct readdir_result d
;
1356 if (__builtin_expect (flags
& GLOB_ALTDIRFUNC
, 0))
1357 d
= convert_dirent (GL_READDIR (pglob
, stream
));
1360 #ifdef COMPILE_GLOB64
1361 d
= convert_dirent (__readdir (stream
));
1363 d
= convert_dirent64 (__readdir64 (stream
));
1370 /* If we shall match only directories use the information
1371 provided by the dirent call if possible. */
1372 if (flags
& GLOB_ONLYDIR
)
1373 switch (readdir_result_type (d
))
1377 case DT_LNK
: case DT_UNKNOWN
:
1378 /* The filesystem was too lazy to give us a hint,
1379 so we have to do it the hard way. */
1380 if (__glibc_unlikely (dfd
< 0 || flags
& GLOB_ALTDIRFUNC
))
1382 size_t namelen
= strlen (d
.name
);
1383 size_t need
= dirlen
+ 1 + namelen
+ 1;
1385 && !scratch_buffer_set_array_size (&s
, need
, 1))
1387 char *p
= mempcpy (s
.data
, directory
, dirlen
);
1390 memcpy (p
, d
.name
, namelen
+ 1);
1391 if (! is_dir (s
.data
, flags
, pglob
))
1397 if (! (GLOB_FSTATAT64 (dfd
, d
.name
, &st64
, 0) == 0
1398 && S_ISDIR (st64
.st_mode
)))
1403 if (fnmatch (pattern
, d
.name
, fnm_flags
) == 0)
1405 if (cur
== names
->count
)
1407 struct globnames
*newnames
;
1408 size_t count
= names
->count
* 2;
1409 size_t nameoff
= offsetof (struct globnames
, name
);
1410 size_t size
= FLEXSIZEOF (struct globnames
, name
,
1411 count
* sizeof (char *));
1412 if ((SIZE_MAX
- nameoff
) / 2 / sizeof (char *)
1415 if (glob_use_alloca (alloca_used
, size
))
1416 newnames
= names_alloca
1417 = alloca_account (size
, alloca_used
);
1418 else if ((newnames
= malloc (size
))
1421 newnames
->count
= count
;
1422 newnames
->next
= names
;
1426 names
->name
[cur
] = strdup (d
.name
);
1427 if (names
->name
[cur
] == NULL
)
1431 if (SIZE_MAX
- pglob
->gl_offs
<= nfound
)
1438 if (nfound
== 0 && (flags
& GLOB_NOCHECK
))
1440 size_t len
= strlen (pattern
);
1442 names
->name
[cur
] = malloc (len
+ 1);
1443 if (names
->name
[cur
] == NULL
)
1445 *((char *) mempcpy (names
->name
[cur
++], pattern
, len
)) = '\0';
1448 result
= GLOB_NOMATCH
;
1451 char **new_gl_pathv
;
1454 if (SIZE_MAX
/ sizeof (char *) - pglob
->gl_pathc
1455 < pglob
->gl_offs
+ nfound
+ 1)
1459 = realloc (pglob
->gl_pathv
,
1460 (pglob
->gl_pathc
+ pglob
->gl_offs
+ nfound
+ 1)
1463 if (new_gl_pathv
== NULL
)
1468 struct globnames
*old
= names
;
1469 for (size_t i
= 0; i
< cur
; ++i
)
1470 free (names
->name
[i
]);
1471 names
= names
->next
;
1472 /* NB: we will not leak memory here if we exit without
1473 freeing the current block assigned to OLD. At least
1474 the very first block is always allocated on the stack
1475 and this is the block assigned to OLD here. */
1478 assert (old
== init_names
);
1482 if (old
== names_alloca
)
1483 names_alloca
= names
;
1487 result
= GLOB_NOSPACE
;
1493 struct globnames
*old
= names
;
1494 for (size_t i
= 0; i
< cur
; ++i
)
1495 new_gl_pathv
[pglob
->gl_offs
+ pglob
->gl_pathc
++]
1497 names
= names
->next
;
1498 /* NB: we will not leak memory here if we exit without
1499 freeing the current block assigned to OLD. At least
1500 the very first block is always allocated on the stack
1501 and this is the block assigned to OLD here. */
1504 assert (old
== init_names
);
1508 if (old
== names_alloca
)
1509 names_alloca
= names
;
1514 pglob
->gl_pathv
= new_gl_pathv
;
1516 pglob
->gl_pathv
[pglob
->gl_offs
+ pglob
->gl_pathc
] = NULL
;
1518 pglob
->gl_flags
= flags
;
1525 if (__glibc_unlikely (flags
& GLOB_ALTDIRFUNC
))
1526 (*pglob
->gl_closedir
) (stream
);
1532 scratch_buffer_free (&s
);