1 /* Copyright (C) 1991-2016 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 General Public
6 License as published by the Free Software Foundation; either
7 version 3 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 General Public License for more details.
14 You should have received a copy of the GNU General Public
15 License along with the GNU C Library; if not, see
16 <http://www.gnu.org/licenses/>. */
19 /* Don't use __attribute__ __nonnull__ in this compilation unit. Otherwise gcc
20 optimizes away the pattern == NULL || pglob == NULL tests below. */
21 # define _GL_ARG_NONNULL(params)
28 #include <sys/types.h>
34 /* Outcomment the following line for production quality code. */
35 /* #define NDEBUG 1 */
38 #include <stdio.h> /* Needed on stupid SunOS for assert. */
43 #if !defined POSIX && defined _POSIX_VERSION
47 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
57 # define __set_errno(val) errno = (val)
67 # define strdup(str) __strdup (str)
68 # define sysconf(id) __sysconf (id)
69 # define closedir(dir) __closedir (dir)
70 # define opendir(name) __opendir (name)
71 # define readdir(str) __readdir64 (str)
72 # define getpwnam_r(name, bufp, buf, len, res) \
73 __getpwnam_r (name, bufp, buf, len, res)
75 # define __stat64(fname, buf) __xstat64 (_STAT_VER, fname, buf)
77 # define struct_stat64 struct stat64
79 # define __getlogin_r(buf, len) getlogin_r (buf, len)
80 # define __stat64(fname, buf) stat (fname, buf)
81 # define __fxstatat64(_, d, f, st, flag) fstatat (d, f, st, flag)
82 # define struct_stat64 struct stat
84 # define __alloca alloca
86 # define __readdir readdir
87 # define __glob_pattern_p glob_pattern_p
88 # define COMPILE_GLOB64
93 #include "flexmember.h"
95 #ifdef _SC_GETPW_R_SIZE_MAX
96 # define GETPW_R_SIZE_MAX() sysconf (_SC_GETPW_R_SIZE_MAX)
98 # define GETPW_R_SIZE_MAX() (-1)
100 #ifdef _SC_LOGIN_NAME_MAX
101 # define GET_LOGIN_NAME_MAX() sysconf (_SC_LOGIN_NAME_MAX)
103 # define GET_LOGIN_NAME_MAX() (-1)
106 static const char *next_brace_sub (const char *begin, int flags) __THROWNL;
108 /* A representation of a directory entry which does not depend on the
109 layout of struct dirent, or the size of ino_t. */
110 struct readdir_result
113 # if defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE
119 # if defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE
120 /* Initializer based on the d_type member of struct dirent. */
121 # define D_TYPE_TO_RESULT(source) (source)->d_type,
123 /* True if the directory entry D might be a symbolic link. */
125 readdir_result_might_be_symlink (struct readdir_result d)
127 return d.type == DT_UNKNOWN || d.type == DT_LNK;
130 /* True if the directory entry D might be a directory. */
132 readdir_result_might_be_dir (struct readdir_result d)
134 return d.type == DT_DIR || readdir_result_might_be_symlink (d);
136 # else /* defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE */
137 # define D_TYPE_TO_RESULT(source)
139 /* If we do not have type information, symbolic links and directories
140 are always a possibility. */
143 readdir_result_might_be_symlink (struct readdir_result d)
149 readdir_result_might_be_dir (struct readdir_result d)
154 # endif /* defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE */
156 # if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
157 /* Initializer for skip_entry. POSIX does not require that the d_ino
158 field be present, and some systems do not provide it. */
159 # define D_INO_TO_RESULT(source) false,
161 # define D_INO_TO_RESULT(source) (source)->d_ino == 0,
164 /* Construct an initializer for a struct readdir_result object from a
165 struct dirent *. No copy of the name is made. */
166 #define READDIR_RESULT_INITIALIZER(source) \
169 D_TYPE_TO_RESULT (source) \
170 D_INO_TO_RESULT (source) \
173 #endif /* !defined GLOB_ONLY_P */
175 /* Call gl_readdir on STREAM. This macro can be overridden to reduce
176 type safety if an old interface version needs to be supported. */
178 # define GL_READDIR(pglob, stream) ((pglob)->gl_readdir (stream))
181 /* Extract name and type from directory entry. No copy of the name is
182 made. If SOURCE is NULL, result name is NULL. Keep in sync with
183 convert_dirent64 below. */
184 static struct readdir_result
185 convert_dirent (const struct dirent *source)
189 struct readdir_result result = { NULL, };
192 struct readdir_result result = READDIR_RESULT_INITIALIZER (source);
196 #ifndef COMPILE_GLOB64
197 /* Like convert_dirent, but works on struct dirent64 instead. Keep in
198 sync with convert_dirent above. */
199 static struct readdir_result
200 convert_dirent64 (const struct dirent64 *source)
204 struct readdir_result result = { NULL, };
207 struct readdir_result result = READDIR_RESULT_INITIALIZER (source);
213 #ifndef attribute_hidden
214 # define attribute_hidden
217 #ifndef __attribute_noinline__
218 # if __GNUC__ < 3 || (__GNUC__ == 3 && __GNUC_MINOR__ < 1)
219 # define __attribute_noinline__ /* Ignore */
221 # define __attribute_noinline__ __attribute__ ((__noinline__))
225 #if ! defined __builtin_expect && __GNUC__ < 3
226 # define __builtin_expect(expr, expected) (expr)
229 #ifndef __glibc_unlikely
230 # define __glibc_unlikely(expr) __builtin_expect (expr, 0)
234 /* The results of opendir() in this file are not used with dirfd and fchdir,
235 and we do not leak fds to any single-threaded code that could use stdio,
236 therefore save some unnecessary recursion in fchdir.c and opendir_safer.c.
237 FIXME - if the kernel ever adds support for multi-thread safety for
238 avoiding standard fds, then we should use opendir_safer. */
239 # ifdef GNULIB_defined_opendir
242 # ifdef GNULIB_defined_closedir
246 /* Just use malloc. */
247 # define __libc_use_alloca(n) false
248 # define alloca_account(len, avar) ((void) (len), (void) (avar), (void *) 0)
249 # define extend_alloca_account(buf, len, newlen, avar) \
250 ((void) (buf), (void) (len), (void) (newlen), (void) (avar), (void *) 0)
253 #ifndef __has_builtin
254 # define __has_builtin(x) 0
257 /* Set *R = A + B. Return true if the answer is mathematically
258 incorrect due to overflow; in this case, *R is the low order
259 bits of the correct answer.. */
262 size_add_wrapv (size_t a, size_t b, size_t *r)
264 #if 5 <= __GNUC__ || __has_builtin (__builtin_add_overflow)
265 return __builtin_add_overflow (a, b, r);
273 glob_use_alloca (size_t alloca_used, size_t len)
276 return (!size_add_wrapv (alloca_used, len, &size)
277 && __libc_use_alloca (size));
280 static int glob_in_dir (const char *pattern, const char *directory,
281 int flags, int (*errfunc) (const char *, int),
282 glob_t *pglob, size_t alloca_used);
283 extern int __glob_pattern_type (const char *pattern, int quote)
287 static int prefix_array (const char *prefix, char **array, size_t n) __THROWNL;
288 static int collated_compare (const void *, const void *) __THROWNL;
291 /* Find the end of the sub-pattern in a brace expression. */
293 next_brace_sub (const char *cp, int flags)
297 if ((flags & GLOB_NOESCAPE) == 0 && *cp == '\\')
305 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
312 return *cp != '\0' ? cp : NULL;
315 #endif /* !defined GLOB_ONLY_P */
317 /* Do glob searching for PATTERN, placing results in PGLOB.
318 The bits defined above may be set in FLAGS.
319 If a directory cannot be opened or read and ERRFUNC is not nil,
320 it is called with the pathname that caused the error, and the
321 'errno' value from the failing call; if it returns non-zero
322 'glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
323 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
324 Otherwise, 'glob' returns zero. */
326 #ifdef GLOB_ATTRIBUTE
329 glob (const char *pattern, int flags, int (*errfunc) (const char *, int),
332 const char *filename;
333 char *dirname = NULL;
338 int dirname_modified;
339 int malloc_dirname = 0;
342 size_t alloca_used = 0;
344 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
346 __set_errno (EINVAL);
350 /* POSIX requires all slashes to be matched. This means that with
351 a trailing slash we must match only directories. */
352 if (pattern[0] && pattern[strlen (pattern) - 1] == '/')
353 flags |= GLOB_ONLYDIR;
355 if (!(flags & GLOB_DOOFFS))
356 /* Have to do this so 'globfree' knows where to start freeing. It
357 also makes all the code that uses gl_offs simpler. */
360 if (flags & GLOB_BRACE)
364 if (flags & GLOB_NOESCAPE)
365 begin = strchr (pattern, '{');
377 if (*begin == '\\' && begin[1] != '\0')
379 else if (*begin == '{')
388 /* Allocate working buffer large enough for our work. Note that
389 we have at least an opening and closing brace. */
397 size_t pattern_len = strlen (pattern) - 1;
398 int alloca_onealt = glob_use_alloca (alloca_used, pattern_len);
400 onealt = alloca_account (pattern_len, alloca_used);
403 onealt = malloc (pattern_len);
406 if (!(flags & GLOB_APPEND))
409 pglob->gl_pathv = NULL;
415 /* We know the prefix for all sub-patterns. */
416 alt_start = mempcpy (onealt, pattern, begin - pattern);
418 /* Find the first sub-pattern and at the same time find the
419 rest after the closing brace. */
420 next = next_brace_sub (begin + 1, flags);
423 /* It is an invalid expression. */
425 if (__glibc_unlikely (!alloca_onealt))
427 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
430 /* Now find the end of the whole brace expression. */
434 rest = next_brace_sub (rest + 1, flags);
436 /* It is an illegal expression. */
439 /* Please note that we now can be sure the brace expression
441 rest_len = strlen (++rest) + 1;
443 /* We have a brace expression. BEGIN points to the opening {,
444 NEXT points past the terminator of the first element, and END
445 points past the final }. We will accumulate result names from
446 recursive runs for each brace alternative in the buffer using
449 if (!(flags & GLOB_APPEND))
451 /* This call is to set a new vector, so clear out the
452 vector so we can append to it. */
454 pglob->gl_pathv = NULL;
456 firstc = pglob->gl_pathc;
463 /* Construct the new glob expression. */
464 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
466 result = glob (onealt,
467 ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))
468 | GLOB_APPEND), errfunc, pglob);
470 /* If we got an error, return it. */
471 if (result && result != GLOB_NOMATCH)
473 if (__glibc_unlikely (!alloca_onealt))
475 if (!(flags & GLOB_APPEND))
484 /* We saw the last entry. */
488 next = next_brace_sub (p, flags);
489 assert (next != NULL);
492 if (__glibc_unlikely (!alloca_onealt))
495 if (pglob->gl_pathc != firstc)
496 /* We found some entries. */
498 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
503 if (!(flags & GLOB_APPEND))
506 if (!(flags & GLOB_DOOFFS))
507 pglob->gl_pathv = NULL;
512 if (pglob->gl_offs >= SIZE_MAX / sizeof (char *))
515 pglob->gl_pathv = malloc ((pglob->gl_offs + 1) * sizeof (char *));
516 if (pglob->gl_pathv == NULL)
519 for (i = 0; i <= pglob->gl_offs; ++i)
520 pglob->gl_pathv[i] = NULL;
524 oldcount = pglob->gl_pathc + pglob->gl_offs;
526 /* Find the filename. */
527 filename = strrchr (pattern, '/');
528 #if defined __MSDOS__ || defined WINDOWS32
529 /* The case of "d:pattern". Since ':' is not allowed in
530 file names, we can safely assume that wherever it
531 happens in pattern, it signals the filename part. This
532 is so we could some day support patterns like "[a-z]:foo". */
533 if (filename == NULL)
534 filename = strchr (pattern, ':');
535 #endif /* __MSDOS__ || WINDOWS32 */
536 dirname_modified = 0;
537 if (filename == NULL)
539 /* This can mean two things: a simple name or "~name". The latter
540 case is nothing but a notation for a directory. */
541 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
543 dirname = (char *) pattern;
544 dirlen = strlen (pattern);
546 /* Set FILENAME to NULL as a special flag. This is ugly but
547 other solutions would require much more code. We test for
548 this special case below. */
553 if (__glibc_unlikely (pattern[0] == '\0'))
555 dirs.gl_pathv = NULL;
561 dirname = (char *) "";
563 dirname = (char *) ".";
568 else if (filename == pattern
569 || (filename == pattern + 1 && pattern[0] == '\\'
570 && (flags & GLOB_NOESCAPE) == 0))
572 /* "/pattern" or "\\/pattern". */
573 dirname = (char *) "/";
580 dirlen = filename - pattern;
581 #if defined __MSDOS__ || defined WINDOWS32
583 || (filename > pattern + 1 && filename[-1] == ':'))
588 drive_spec = __alloca (dirlen + 1);
589 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
590 /* For now, disallow wildcards in the drive spec, to
591 prevent infinite recursion in glob. */
592 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
594 /* If this is "d:pattern", we need to copy ':' to DIRNAME
595 as well. If it's "d:/pattern", don't remove the slash
596 from "d:/", since "d:" and "d:/" are not the same.*/
599 if (glob_use_alloca (alloca_used, dirlen + 1))
600 newp = alloca_account (dirlen + 1, alloca_used);
603 newp = malloc (dirlen + 1);
608 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
612 if (filename[0] == '\0'
613 #if defined __MSDOS__ || defined WINDOWS32
614 && dirname[dirlen - 1] != ':'
615 && (dirlen < 3 || dirname[dirlen - 2] != ':'
616 || dirname[dirlen - 1] != '/')
619 /* "pattern/". Expand "pattern", appending slashes. */
621 int orig_flags = flags;
623 if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\')
625 /* "pattern\\/". Remove the final backslash if it hasn't
627 char *p = (char *) &dirname[dirlen - 1];
629 while (p > dirname && p[-1] == '\\') --p;
630 if ((&dirname[dirlen] - p) & 1)
632 *(char *) &dirname[--dirlen] = '\0';
633 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
636 val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
638 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
639 | (flags & GLOB_MARK));
640 else if (val == GLOB_NOMATCH && flags != orig_flags)
642 /* Make sure globfree (&dirs); is a nop. */
643 dirs.gl_pathv = NULL;
645 oldcount = pglob->gl_pathc + pglob->gl_offs;
653 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
655 if (dirname[1] == '\0' || dirname[1] == '/'
656 || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\'
657 && (dirname[2] == '\0' || dirname[2] == '/')))
659 /* Look up home directory. */
660 char *home_dir = getenv ("HOME");
661 int malloc_home_dir = 0;
663 if (home_dir == NULL || home_dir[0] == '\0')
667 /* Windows NT defines HOMEDRIVE and HOMEPATH. But give preference
668 to HOME, because the user can change HOME. */
669 if (home_dir == NULL || home_dir[0] == '\0')
671 const char *home_drive = getenv ("HOMEDRIVE");
672 const char *home_path = getenv ("HOMEPATH");
674 if (home_drive != NULL && home_path != NULL)
676 size_t home_drive_len = strlen (home_drive);
677 size_t home_path_len = strlen (home_path);
678 char *mem = alloca (home_drive_len + home_path_len + 1);
680 memcpy (mem, home_drive, home_drive_len);
681 memcpy (mem + home_drive_len, home_path, home_path_len + 1);
685 home_dir = "c:/users/default"; /* poor default */
688 if (home_dir == NULL || home_dir[0] == '\0')
693 size_t buflen = GET_LOGIN_NAME_MAX () + 1;
696 /* 'sysconf' does not support _SC_LOGIN_NAME_MAX. Try
699 if (glob_use_alloca (alloca_used, buflen))
700 name = alloca_account (buflen, alloca_used);
703 name = malloc (buflen);
706 retval = GLOB_NOSPACE;
712 success = __getlogin_r (name, buflen) == 0;
716 # if defined HAVE_GETPWNAM_R || defined _LIBC
717 long int pwbuflenmax = GETPW_R_SIZE_MAX ();
718 size_t pwbuflen = pwbuflenmax;
721 char *malloc_pwtmpbuf = NULL;
725 if (! (0 < pwbuflenmax && pwbuflenmax <= SIZE_MAX))
726 /* Perhaps 'sysconf' does not support _SC_GETPW_R_SIZE_MAX.
727 Try a moderate value. */
730 if (glob_use_alloca (alloca_used, pwbuflen))
731 pwtmpbuf = alloca_account (pwbuflen, alloca_used);
734 pwtmpbuf = malloc (pwbuflen);
735 if (pwtmpbuf == NULL)
737 retval = GLOB_NOSPACE;
740 malloc_pwtmpbuf = pwtmpbuf;
743 while (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
753 v = size_add_wrapv (pwbuflen, pwbuflen, &newlen);
754 if (!v && malloc_pwtmpbuf == NULL
755 && glob_use_alloca (alloca_used, newlen))
756 pwtmpbuf = extend_alloca_account (pwtmpbuf, pwbuflen,
757 newlen, alloca_used);
760 char *newp = (v ? NULL
761 : realloc (malloc_pwtmpbuf, newlen));
764 free (malloc_pwtmpbuf);
765 retval = GLOB_NOSPACE;
768 malloc_pwtmpbuf = pwtmpbuf = newp;
776 if (__glibc_unlikely (malloc_name))
780 if (malloc_pwtmpbuf == NULL)
781 home_dir = p->pw_dir;
784 size_t home_dir_len = strlen (p->pw_dir) + 1;
785 if (glob_use_alloca (alloca_used, home_dir_len))
786 home_dir = alloca_account (home_dir_len,
790 home_dir = malloc (home_dir_len);
791 if (home_dir == NULL)
794 retval = GLOB_NOSPACE;
799 memcpy (home_dir, p->pw_dir, home_dir_len);
806 if (home_dir == NULL || home_dir[0] == '\0')
808 if (flags & GLOB_TILDE_CHECK)
810 if (__glibc_unlikely (malloc_home_dir))
812 retval = GLOB_NOMATCH;
816 home_dir = (char *) "~"; /* No luck. */
818 # endif /* WINDOWS32 */
820 /* Now construct the full directory. */
821 if (dirname[1] == '\0')
823 if (__glibc_unlikely (malloc_dirname))
827 dirlen = strlen (dirname);
828 malloc_dirname = malloc_home_dir;
833 size_t home_len = strlen (home_dir);
834 int use_alloca = glob_use_alloca (alloca_used, home_len + dirlen);
836 newp = alloca_account (home_len + dirlen, alloca_used);
839 newp = malloc (home_len + dirlen);
842 if (__glibc_unlikely (malloc_home_dir))
844 retval = GLOB_NOSPACE;
849 mempcpy (mempcpy (newp, home_dir, home_len),
850 &dirname[1], dirlen);
852 if (__glibc_unlikely (malloc_dirname))
856 dirlen += home_len - 1;
857 malloc_dirname = !use_alloca;
859 dirname_modified = 1;
861 # if !defined _AMIGA && !defined WINDOWS32
864 char *end_name = strchr (dirname, '/');
866 int malloc_user_name = 0;
867 char *unescape = NULL;
869 if (!(flags & GLOB_NOESCAPE))
871 if (end_name == NULL)
873 unescape = strchr (dirname, '\\');
875 end_name = strchr (unescape, '\0');
878 unescape = memchr (dirname, '\\', end_name - dirname);
880 if (end_name == NULL)
881 user_name = dirname + 1;
885 if (glob_use_alloca (alloca_used, end_name - dirname))
886 newp = alloca_account (end_name - dirname, alloca_used);
889 newp = malloc (end_name - dirname);
892 retval = GLOB_NOSPACE;
895 malloc_user_name = 1;
897 if (unescape != NULL)
899 char *p = mempcpy (newp, dirname + 1,
900 unescape - dirname - 1);
908 /* "~fo\\o\\" unescape to user_name "foo\\",
909 but "~fo\\o\\/" unescape to user_name
911 if (filename == NULL)
922 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
927 /* Look up specific user's home directory. */
930 # if defined HAVE_GETPWNAM_R || defined _LIBC
931 long int buflenmax = GETPW_R_SIZE_MAX ();
932 size_t buflen = buflenmax;
934 char *malloc_pwtmpbuf = NULL;
939 if (! (0 <= buflenmax && buflenmax <= SIZE_MAX))
940 /* Perhaps 'sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
944 if (glob_use_alloca (alloca_used, buflen))
945 pwtmpbuf = alloca_account (buflen, alloca_used);
948 pwtmpbuf = malloc (buflen);
949 if (pwtmpbuf == NULL)
952 if (__glibc_unlikely (malloc_user_name))
954 retval = GLOB_NOSPACE;
957 malloc_pwtmpbuf = pwtmpbuf;
960 while (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) != 0)
969 v = size_add_wrapv (buflen, buflen, &newlen);
970 if (!v && malloc_pwtmpbuf == NULL
971 && glob_use_alloca (alloca_used, newlen))
972 pwtmpbuf = extend_alloca_account (pwtmpbuf, buflen,
973 newlen, alloca_used);
976 char *newp = v ? NULL : realloc (malloc_pwtmpbuf, newlen);
979 free (malloc_pwtmpbuf);
982 malloc_pwtmpbuf = pwtmpbuf = newp;
987 p = getpwnam (user_name);
990 if (__glibc_unlikely (malloc_user_name))
993 /* If we found a home directory use this. */
996 size_t home_len = strlen (p->pw_dir);
997 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
999 if (__glibc_unlikely (malloc_dirname))
1003 if (glob_use_alloca (alloca_used, home_len + rest_len + 1))
1004 dirname = alloca_account (home_len + rest_len + 1,
1008 dirname = malloc (home_len + rest_len + 1);
1009 if (dirname == NULL)
1011 free (malloc_pwtmpbuf);
1012 retval = GLOB_NOSPACE;
1017 *((char *) mempcpy (mempcpy (dirname, p->pw_dir, home_len),
1018 end_name, rest_len)) = '\0';
1020 dirlen = home_len + rest_len;
1021 dirname_modified = 1;
1023 free (malloc_pwtmpbuf);
1027 free (malloc_pwtmpbuf);
1029 if (flags & GLOB_TILDE_CHECK)
1030 /* We have to regard it as an error if we cannot find the
1032 return GLOB_NOMATCH;
1036 # endif /* Not Amiga && not WINDOWS32. */
1039 /* Now test whether we looked for "~" or "~NAME". In this case we
1040 can give the answer now. */
1041 if (filename == NULL)
1046 /* Return the directory if we don't check for error or if it exists. */
1047 if ((flags & GLOB_NOCHECK)
1048 || (((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1049 ? ((*pglob->gl_stat) (dirname, &st) == 0
1050 && S_ISDIR (st.st_mode))
1051 : (__stat64 (dirname, &st64) == 0 && S_ISDIR (st64.st_mode)))))
1053 size_t newcount = pglob->gl_pathc + pglob->gl_offs;
1054 char **new_gl_pathv;
1056 if (newcount > SIZE_MAX / sizeof (char *) - 2)
1059 free (pglob->gl_pathv);
1060 pglob->gl_pathv = NULL;
1061 pglob->gl_pathc = 0;
1062 return GLOB_NOSPACE;
1065 new_gl_pathv = realloc (pglob->gl_pathv,
1066 (newcount + 2) * sizeof (char *));
1067 if (new_gl_pathv == NULL)
1069 pglob->gl_pathv = new_gl_pathv;
1071 if (flags & GLOB_MARK)
1074 pglob->gl_pathv[newcount] = malloc (dirlen + 2);
1075 if (pglob->gl_pathv[newcount] == NULL)
1077 p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);
1083 pglob->gl_pathv[newcount] = strdup (dirname);
1084 if (pglob->gl_pathv[newcount] == NULL)
1087 pglob->gl_pathv[++newcount] = NULL;
1089 pglob->gl_flags = flags;
1095 return GLOB_NOMATCH;
1098 meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));
1099 /* meta is 1 if correct glob pattern containing metacharacters.
1100 If meta has bit (1 << 2) set, it means there was an unterminated
1101 [ which we handle the same, using fnmatch. Broken unterminated
1102 pattern bracket expressions ought to be rare enough that it is
1103 not worth special casing them, fnmatch will do the right thing. */
1106 /* The directory name contains metacharacters, so we
1107 have to glob for the directory, and then glob for
1108 the pattern in each directory found. */
1111 if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\')
1113 /* "foo\\/bar". Remove the final backslash from dirname
1114 if it has not been quoted. */
1115 char *p = (char *) &dirname[dirlen - 1];
1117 while (p > dirname && p[-1] == '\\') --p;
1118 if ((&dirname[dirlen] - p) & 1)
1119 *(char *) &dirname[--dirlen] = '\0';
1122 if (__glibc_unlikely ((flags & GLOB_ALTDIRFUNC) != 0))
1124 /* Use the alternative access functions also in the recursive
1126 dirs.gl_opendir = pglob->gl_opendir;
1127 dirs.gl_readdir = pglob->gl_readdir;
1128 dirs.gl_closedir = pglob->gl_closedir;
1129 dirs.gl_stat = pglob->gl_stat;
1130 dirs.gl_lstat = pglob->gl_lstat;
1133 status = glob (dirname,
1134 ((flags & (GLOB_ERR | GLOB_NOESCAPE
1136 | GLOB_NOSORT | GLOB_ONLYDIR),
1140 if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH)
1145 /* We have successfully globbed the preceding directory name.
1146 For each name we found, call glob_in_dir on it and FILENAME,
1147 appending the results to PGLOB. */
1148 for (i = 0; i < dirs.gl_pathc; ++i)
1154 /* Make globbing interruptible in the bash shell. */
1155 extern int interrupt_state;
1157 if (interrupt_state)
1160 return GLOB_ABORTED;
1165 old_pathc = pglob->gl_pathc;
1166 status = glob_in_dir (filename, dirs.gl_pathv[i],
1167 ((flags | GLOB_APPEND)
1168 & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),
1169 errfunc, pglob, alloca_used);
1170 if (status == GLOB_NOMATCH)
1171 /* No matches in this directory. Try the next. */
1178 pglob->gl_pathc = 0;
1182 /* Stick the directory on the front of each name. */
1183 if (prefix_array (dirs.gl_pathv[i],
1184 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
1185 pglob->gl_pathc - old_pathc))
1189 pglob->gl_pathc = 0;
1190 return GLOB_NOSPACE;
1194 flags |= GLOB_MAGCHAR;
1196 /* We have ignored the GLOB_NOCHECK flag in the 'glob_in_dir' calls.
1197 But if we have not found any matching entry and the GLOB_NOCHECK
1198 flag was set we must return the input pattern itself. */
1199 if (pglob->gl_pathc + pglob->gl_offs == oldcount)
1203 if (flags & GLOB_NOCHECK)
1205 size_t newcount = pglob->gl_pathc + pglob->gl_offs;
1206 char **new_gl_pathv;
1208 if (newcount > SIZE_MAX / sizeof (char *) - 2)
1212 return GLOB_NOSPACE;
1215 new_gl_pathv = realloc (pglob->gl_pathv,
1216 (newcount + 2) * sizeof (char *));
1217 if (new_gl_pathv == NULL)
1219 pglob->gl_pathv = new_gl_pathv;
1221 pglob->gl_pathv[newcount] = strdup (pattern);
1222 if (pglob->gl_pathv[newcount] == NULL)
1226 pglob->gl_pathc = 0;
1227 return GLOB_NOSPACE;
1233 pglob->gl_pathv[newcount] = NULL;
1234 pglob->gl_flags = flags;
1239 return GLOB_NOMATCH;
1247 size_t old_pathc = pglob->gl_pathc;
1248 int orig_flags = flags;
1252 char *p = strchr (dirname, '\\'), *q;
1253 /* We need to unescape the dirname string. It is certainly
1254 allocated by alloca, as otherwise filename would be NULL
1255 or dirname wouldn't contain backslashes. */
1268 while (*p++ != '\0');
1269 dirname_modified = 1;
1271 if (dirname_modified)
1272 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
1273 status = glob_in_dir (filename, dirname, flags, errfunc, pglob,
1277 if (status == GLOB_NOMATCH && flags != orig_flags
1278 && pglob->gl_pathc + pglob->gl_offs == oldcount)
1280 /* Make sure globfree (&dirs); is a nop. */
1281 dirs.gl_pathv = NULL;
1290 /* Stick the directory on the front of each name. */
1291 if (prefix_array (dirname,
1292 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
1293 pglob->gl_pathc - old_pathc))
1296 pglob->gl_pathc = 0;
1297 return GLOB_NOSPACE;
1302 if (flags & GLOB_MARK)
1304 /* Append slashes to directory names. */
1309 for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)
1310 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1311 ? ((*pglob->gl_stat) (pglob->gl_pathv[i], &st) == 0
1312 && S_ISDIR (st.st_mode))
1313 : (__stat64 (pglob->gl_pathv[i], &st64) == 0
1314 && S_ISDIR (st64.st_mode))))
1316 size_t len = strlen (pglob->gl_pathv[i]) + 2;
1317 char *new = realloc (pglob->gl_pathv[i], len);
1321 pglob->gl_pathc = 0;
1322 return GLOB_NOSPACE;
1324 strcpy (&new[len - 2], "/");
1325 pglob->gl_pathv[i] = new;
1329 if (!(flags & GLOB_NOSORT))
1331 /* Sort the vector. */
1332 qsort (&pglob->gl_pathv[oldcount],
1333 pglob->gl_pathc + pglob->gl_offs - oldcount,
1334 sizeof (char *), collated_compare);
1338 if (__glibc_unlikely (malloc_dirname))
1343 #if defined _LIBC && !defined glob
1344 libc_hidden_def (glob)
1350 /* Free storage allocated in PGLOB by a previous 'glob' call. */
1352 globfree (glob_t *pglob)
1354 if (pglob->gl_pathv != NULL)
1357 for (i = 0; i < pglob->gl_pathc; ++i)
1358 free (pglob->gl_pathv[pglob->gl_offs + i]);
1359 free (pglob->gl_pathv);
1360 pglob->gl_pathv = NULL;
1363 #if defined _LIBC && !defined globfree
1364 libc_hidden_def (globfree)
1368 /* Do a collated comparison of A and B. */
1370 collated_compare (const void *a, const void *b)
1372 char *const *ps1 = a; char *s1 = *ps1;
1373 char *const *ps2 = b; char *s2 = *ps2;
1381 return strcoll (s1, s2);
1385 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1386 elements in place. Return nonzero if out of memory, zero if successful.
1387 A slash is inserted between DIRNAME and each elt of ARRAY,
1388 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1390 prefix_array (const char *dirname, char **array, size_t n)
1393 size_t dirlen = strlen (dirname);
1394 #if defined __MSDOS__ || defined WINDOWS32
1396 # define DIRSEP_CHAR sep_char
1398 # define DIRSEP_CHAR '/'
1401 if (dirlen == 1 && dirname[0] == '/')
1402 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1403 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1405 #if defined __MSDOS__ || defined WINDOWS32
1406 else if (dirlen > 1)
1408 if (dirname[dirlen - 1] == '/' && dirname[dirlen - 2] == ':')
1409 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1411 else if (dirname[dirlen - 1] == ':')
1413 /* DIRNAME is "d:". Use ':' instead of '/'. */
1420 for (i = 0; i < n; ++i)
1422 size_t eltlen = strlen (array[i]) + 1;
1423 char *new = malloc (dirlen + 1 + eltlen);
1432 char *endp = mempcpy (new, dirname, dirlen);
1433 *endp++ = DIRSEP_CHAR;
1434 mempcpy (endp, array[i], eltlen);
1444 /* We must not compile this function twice. */
1445 #ifndef NO_GLOB_PATTERN_P
1447 __glob_pattern_type (const char *pattern, int quote)
1452 for (p = pattern; *p != '\0'; ++p)
1481 /* Return nonzero if PATTERN contains any metacharacters.
1482 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
1484 __glob_pattern_p (const char *pattern, int quote)
1486 return __glob_pattern_type (pattern, quote) == 1;
1489 weak_alias (__glob_pattern_p, glob_pattern_p)
1494 /* We put this in a separate function mainly to allow the memory
1495 allocated with alloca to be recycled. */
1497 __attribute_noinline__
1498 link_exists2_p (const char *dir, size_t dirlen, const char *fname,
1500 # if !defined _LIBC && !HAVE_FSTATAT
1505 size_t fnamelen = strlen (fname);
1506 char *fullname = __alloca (dirlen + 1 + fnamelen + 1);
1509 mempcpy (mempcpy (mempcpy (fullname, dir, dirlen), "/", 1),
1510 fname, fnamelen + 1);
1512 # if !defined _LIBC && !HAVE_FSTATAT
1513 if (__builtin_expect ((flags & GLOB_ALTDIRFUNC) == 0, 1))
1516 return __stat64 (fullname, &st64) == 0;
1519 return (*pglob->gl_stat) (fullname, &st) == 0;
1522 /* Return true if DIR/FNAME exists. */
1524 link_exists_p (int dfd, const char *dir, size_t dirlen, const char *fname,
1525 glob_t *pglob, int flags)
1527 # if defined _LIBC || HAVE_FSTATAT
1528 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1529 return link_exists2_p (dir, dirlen, fname, pglob);
1532 /* dfd cannot be -1 here, because dirfd never returns -1 on
1533 glibc, or on hosts that have fstatat. */
1535 return __fxstatat64 (_STAT_VER, dfd, fname, &st64, 0) == 0;
1538 return link_exists2_p (dir, dirlen, fname, pglob, flags);
1541 #endif /* !defined GLOB_ONLY_P */
1544 /* Like 'glob', but PATTERN is a final pathname component,
1545 and matches are searched for in DIRECTORY.
1546 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1547 The GLOB_APPEND flag is assumed to be set (always appends). */
1549 glob_in_dir (const char *pattern, const char *directory, int flags,
1550 int (*errfunc) (const char *, int),
1551 glob_t *pglob, size_t alloca_used)
1553 size_t dirlen = strlen (directory);
1554 void *stream = NULL;
1557 struct globnames *next;
1561 struct globnames init_names;
1562 struct globnames *names = &init_names;
1563 struct globnames *names_alloca = &init_names;
1570 alloca_used += sizeof (init_names);
1572 init_names.next = NULL;
1573 init_names.count = sizeof init_names.name / sizeof init_names.name[0];
1575 meta = __glob_pattern_type (pattern, !(flags & GLOB_NOESCAPE));
1576 if (meta == 0 && (flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
1578 /* We need not do any tests. The PATTERN contains no meta
1579 characters and we must not return an error therefore the
1580 result will always contain exactly one name. */
1581 flags |= GLOB_NOCHECK;
1585 /* Since we use the normal file functions we can also use stat()
1586 to verify the file is there. */
1592 size_t patlen = strlen (pattern);
1594 bool alloca_fullname
1595 = (! size_add_wrapv (dirlen + 1, patlen + 1, &fullsize)
1596 && glob_use_alloca (alloca_used, fullsize));
1598 if (alloca_fullname)
1599 fullname = alloca_account (fullsize, alloca_used);
1602 fullname = malloc (fullsize);
1603 if (fullname == NULL)
1604 return GLOB_NOSPACE;
1607 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1609 pattern, patlen + 1);
1610 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1611 ? (*pglob->gl_stat) (fullname, &ust.st)
1612 : __stat64 (fullname, &ust.st64)) == 0)
1613 /* We found this file to be existing. Now tell the rest
1614 of the function to copy this name into the result. */
1615 flags |= GLOB_NOCHECK;
1617 if (__glibc_unlikely (!alloca_fullname))
1622 stream = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1623 ? (*pglob->gl_opendir) (directory)
1624 : opendir (directory));
1627 if (errno != ENOTDIR
1628 && ((errfunc != NULL && (*errfunc) (directory, errno))
1629 || (flags & GLOB_ERR)))
1630 return GLOB_ABORTED;
1634 int dfd = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1635 ? -1 : dirfd ((DIR *) stream));
1636 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1637 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1638 #if defined _AMIGA || defined VMS
1642 flags |= GLOB_MAGCHAR;
1646 struct readdir_result d;
1648 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1649 d = convert_dirent (GL_READDIR (pglob, stream));
1652 #ifdef COMPILE_GLOB64
1653 d = convert_dirent (__readdir (stream));
1655 d = convert_dirent64 (__readdir64 (stream));
1664 /* If we shall match only directories use the information
1665 provided by the dirent call if possible. */
1666 if ((flags & GLOB_ONLYDIR) && !readdir_result_might_be_dir (d))
1669 if (fnmatch (pattern, d.name, fnm_flags) == 0)
1671 /* If the file we found is a symlink we have to
1672 make sure the target file exists. */
1673 if (!readdir_result_might_be_symlink (d)
1674 || link_exists_p (dfd, directory, dirlen, d.name,
1677 if (cur == names->count)
1679 struct globnames *newnames;
1680 size_t count = names->count * 2;
1681 size_t nameoff = offsetof (struct globnames, name);
1682 size_t size = FLEXSIZEOF (struct globnames, name,
1683 count * sizeof (char *));
1684 if ((SIZE_MAX - nameoff) / 2 / sizeof (char *)
1687 if (glob_use_alloca (alloca_used, size))
1688 newnames = names_alloca
1689 = alloca_account (size, alloca_used);
1690 else if ((newnames = malloc (size))
1693 newnames->count = count;
1694 newnames->next = names;
1698 names->name[cur] = strdup (d.name);
1699 if (names->name[cur] == NULL)
1703 if (SIZE_MAX - pglob->gl_offs <= nfound)
1711 if (nfound == 0 && (flags & GLOB_NOCHECK))
1713 size_t len = strlen (pattern);
1715 names->name[cur] = malloc (len + 1);
1716 if (names->name[cur] == NULL)
1718 *((char *) mempcpy (names->name[cur++], pattern, len)) = '\0';
1721 result = GLOB_NOMATCH;
1724 char **new_gl_pathv;
1727 if (SIZE_MAX / sizeof (char *) - pglob->gl_pathc
1728 < pglob->gl_offs + nfound + 1)
1732 = realloc (pglob->gl_pathv,
1733 (pglob->gl_pathc + pglob->gl_offs + nfound + 1)
1736 if (new_gl_pathv == NULL)
1741 struct globnames *old = names;
1743 for (i = 0; i < cur; ++i)
1744 free (names->name[i]);
1745 names = names->next;
1746 /* NB: we will not leak memory here if we exit without
1747 freeing the current block assigned to OLD. At least
1748 the very first block is always allocated on the stack
1749 and this is the block assigned to OLD here. */
1752 assert (old == &init_names);
1756 if (old == names_alloca)
1757 names_alloca = names;
1761 result = GLOB_NOSPACE;
1767 struct globnames *old = names;
1769 for (i = 0; i < cur; ++i)
1770 new_gl_pathv[pglob->gl_offs + pglob->gl_pathc++]
1772 names = names->next;
1773 /* NB: we will not leak memory here if we exit without
1774 freeing the current block assigned to OLD. At least
1775 the very first block is always allocated on the stack
1776 and this is the block assigned to OLD here. */
1779 assert (old == &init_names);
1783 if (old == names_alloca)
1784 names_alloca = names;
1789 pglob->gl_pathv = new_gl_pathv;
1791 pglob->gl_pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
1793 pglob->gl_flags = flags;
1800 if (__glibc_unlikely (flags & GLOB_ALTDIRFUNC))
1801 (*pglob->gl_closedir) (stream);