1 /* Copyright (C) 1991-2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
2 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, write to the Free
17 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
27 #include <sys/types.h>
31 /* Outcomment the following line for production quality code. */
32 /* #define NDEBUG 1 */
37 #include <stdio.h> /* Needed on stupid SunOS for assert. */
39 #if !defined _LIBC || !defined GLOB_ONLY_P
42 #if !defined POSIX && defined _POSIX_VERSION
46 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
56 # define __set_errno(val) errno = (val)
62 /* In GNU systems, <dirent.h> defines this macro for us. */
63 #ifndef _D_EXACT_NAMLEN
64 # define _D_EXACT_NAMLEN(dirent) strlen ((dirent)->d_name)
67 /* When used in the GNU libc the symbol _DIRENT_HAVE_D_TYPE is available
68 if the `d_type' member for `struct dirent' is available.
69 HAVE_STRUCT_DIRENT_D_TYPE plays the same role in GNULIB. */
70 #if defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE
71 /* True if the directory entry D must be of type T. */
72 # define DIRENT_MUST_BE(d, t) ((d)->d_type == (t))
74 /* True if the directory entry D might be a symbolic link. */
75 # define DIRENT_MIGHT_BE_SYMLINK(d) \
76 ((d)->d_type == DT_UNKNOWN || (d)->d_type == DT_LNK)
78 /* True if the directory entry D might be a directory. */
79 # define DIRENT_MIGHT_BE_DIR(d) \
80 ((d)->d_type == DT_DIR || DIRENT_MIGHT_BE_SYMLINK (d))
82 #else /* !HAVE_D_TYPE */
83 # define DIRENT_MUST_BE(d, t) false
84 # define DIRENT_MIGHT_BE_SYMLINK(d) true
85 # define DIRENT_MIGHT_BE_DIR(d) true
86 #endif /* HAVE_D_TYPE */
88 /* If the system has the `struct dirent64' type we use it internally. */
89 #if defined _LIBC && !defined COMPILE_GLOB64
90 # if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
91 # define CONVERT_D_INO(d64, d32)
93 # define CONVERT_D_INO(d64, d32) \
94 (d64)->d_ino = (d32)->d_ino;
97 # ifdef _DIRENT_HAVE_D_TYPE
98 # define CONVERT_D_TYPE(d64, d32) \
99 (d64)->d_type = (d32)->d_type;
101 # define CONVERT_D_TYPE(d64, d32)
104 # define CONVERT_DIRENT_DIRENT64(d64, d32) \
105 memcpy ((d64)->d_name, (d32)->d_name, _D_EXACT_NAMLEN (d32) + 1); \
106 CONVERT_D_INO (d64, d32) \
107 CONVERT_D_TYPE (d64, d32)
111 #if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
112 /* Posix does not require that the d_ino field be present, and some
113 systems do not provide it. */
114 # define REAL_DIR_ENTRY(dp) 1
116 # define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
122 /* NAME_MAX is usually defined in <dirent.h> or <limits.h>. */
125 # define NAME_MAX (sizeof (((struct dirent *) 0)->d_name))
132 # define strdup(str) __strdup (str)
133 # define sysconf(id) __sysconf (id)
134 # define closedir(dir) __closedir (dir)
135 # define opendir(name) __opendir (name)
136 # define readdir(str) __readdir64 (str)
137 # define getpwnam_r(name, bufp, buf, len, res) \
138 __getpwnam_r (name, bufp, buf, len, res)
140 # define __stat64(fname, buf) __xstat64 (_STAT_VER, fname, buf)
142 # define struct_stat64 struct stat64
144 # define __stat64(fname, buf) stat (fname, buf)
145 # define __fxstatat64(_, d, f, st, flag) fstatat (d, f, st, flag)
146 # define struct_stat64 struct stat
147 # define __stat(fname, buf) stat (fname, buf)
148 # define __alloca alloca
149 # define __readdir readdir
150 # define __readdir64 readdir64
151 # define __glob_pattern_p glob_pattern_p
156 #ifdef _SC_GETPW_R_SIZE_MAX
157 # define GETPW_R_SIZE_MAX() sysconf (_SC_GETPW_R_SIZE_MAX)
159 # define GETPW_R_SIZE_MAX() (-1)
161 #ifdef _SC_LOGIN_NAME_MAX
162 # define GET_LOGIN_NAME_MAX() sysconf (_SC_LOGIN_NAME_MAX)
164 # define GET_LOGIN_NAME_MAX() (-1)
167 static const char *next_brace_sub (const char *begin, int flags) __THROW;
169 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
171 #ifndef attribute_hidden
172 # define attribute_hidden
175 #ifndef __attribute_noinline__
176 # if __GNUC__ < 3 || (__GNUC__ == 3 && __GNUC_MINOR__ < 1)
177 # define __attribute_noinline__ /* Ignore */
179 # define __attribute_noinline__ __attribute__ ((__noinline__))
183 #if ! defined __builtin_expect && __GNUC__ < 3
184 # define __builtin_expect(expr, expected) (expr)
188 /* The results of opendir() in this file are not used with dirfd and fchdir,
189 and we do not leak fds to any single-threaded code that could use stdio,
190 therefore save some unnecessary recursion in fchdir.c and opendir_safer.c.
191 FIXME - if the kernel ever adds support for multi-thread safety for
192 avoiding standard fds, then we should use opendir_safer. */
197 /* The OS usually guarantees only one guard page at the bottom of the stack,
198 and a page size can be as small as 4096 bytes. So we cannot safely
199 allocate anything larger than 4096 bytes. Also care for the possibility
200 of a few compiler-allocated temporary stack slots. */
201 # define __libc_use_alloca(n) ((n) < 4032)
203 /* alloca is implemented with malloc, so just use malloc. */
204 # define __libc_use_alloca(n) 0
208 static int glob_in_dir (const char *pattern, const char *directory,
209 int flags, int (*errfunc) (const char *, int),
211 extern int __glob_pattern_type (const char *pattern, int quote)
214 #if !defined _LIBC || !defined GLOB_ONLY_P
215 static int prefix_array (const char *prefix, char **array, size_t n) __THROW;
216 static int collated_compare (const void *, const void *) __THROW;
219 /* Find the end of the sub-pattern in a brace expression. */
221 next_brace_sub (const char *cp, int flags)
223 unsigned int depth = 0;
225 if ((flags & GLOB_NOESCAPE) == 0 && *cp == '\\')
233 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
240 return *cp != '\0' ? cp : NULL;
243 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
245 /* Do glob searching for PATTERN, placing results in PGLOB.
246 The bits defined above may be set in FLAGS.
247 If a directory cannot be opened or read and ERRFUNC is not nil,
248 it is called with the pathname that caused the error, and the
249 `errno' value from the failing call; if it returns non-zero
250 `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
251 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
252 Otherwise, `glob' returns zero. */
254 #ifdef GLOB_ATTRIBUTE
257 glob (pattern, flags, errfunc, pglob)
258 const char * restrict pattern;
260 int (*errfunc) (const char *, int);
261 glob_t * restrict pglob;
263 const char *filename;
269 int dirname_modified;
272 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
274 __set_errno (EINVAL);
278 if (!(flags & GLOB_DOOFFS))
279 /* Have to do this so `globfree' knows where to start freeing. It
280 also makes all the code that uses gl_offs simpler. */
283 if (flags & GLOB_BRACE)
287 if (flags & GLOB_NOESCAPE)
288 begin = strchr (pattern, '{');
300 if (*begin == '\\' && begin[1] != '\0')
302 else if (*begin == '{')
311 /* Allocate working buffer large enough for our work. Note that
312 we have at least an opening and closing brace. */
320 char onealt[strlen (pattern) - 1];
322 char *onealt = malloc (strlen (pattern) - 1);
325 if (!(flags & GLOB_APPEND))
328 pglob->gl_pathv = NULL;
334 /* We know the prefix for all sub-patterns. */
335 alt_start = mempcpy (onealt, pattern, begin - pattern);
337 /* Find the first sub-pattern and at the same time find the
338 rest after the closing brace. */
339 next = next_brace_sub (begin + 1, flags);
342 /* It is an invalid expression. */
346 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
349 /* Now find the end of the whole brace expression. */
353 rest = next_brace_sub (rest + 1, flags);
356 /* It is an invalid expression. */
360 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
363 /* Please note that we now can be sure the brace expression
365 rest_len = strlen (++rest) + 1;
367 /* We have a brace expression. BEGIN points to the opening {,
368 NEXT points past the terminator of the first element, and END
369 points past the final }. We will accumulate result names from
370 recursive runs for each brace alternative in the buffer using
373 if (!(flags & GLOB_APPEND))
375 /* This call is to set a new vector, so clear out the
376 vector so we can append to it. */
378 pglob->gl_pathv = NULL;
380 firstc = pglob->gl_pathc;
387 /* Construct the new glob expression. */
388 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
390 result = glob (onealt,
391 ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))
392 | GLOB_APPEND), errfunc, pglob);
394 /* If we got an error, return it. */
395 if (result && result != GLOB_NOMATCH)
400 if (!(flags & GLOB_APPEND))
409 /* We saw the last entry. */
413 next = next_brace_sub (p, flags);
414 assert (next != NULL);
421 if (pglob->gl_pathc != firstc)
422 /* We found some entries. */
424 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
429 /* Find the filename. */
430 filename = strrchr (pattern, '/');
431 #if defined __MSDOS__ || defined WINDOWS32
432 /* The case of "d:pattern". Since `:' is not allowed in
433 file names, we can safely assume that wherever it
434 happens in pattern, it signals the filename part. This
435 is so we could some day support patterns like "[a-z]:foo". */
436 if (filename == NULL)
437 filename = strchr (pattern, ':');
438 #endif /* __MSDOS__ || WINDOWS32 */
439 dirname_modified = 0;
440 if (filename == NULL)
442 /* This can mean two things: a simple name or "~name". The latter
443 case is nothing but a notation for a directory. */
444 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
447 dirlen = strlen (pattern);
449 /* Set FILENAME to NULL as a special flag. This is ugly but
450 other solutions would require much more code. We test for
451 this special case below. */
465 else if (filename == pattern
466 || (filename == pattern + 1 && pattern[0] == '\\'
467 && (flags & GLOB_NOESCAPE) == 0))
469 /* "/pattern" or "\\/pattern". */
477 dirlen = filename - pattern;
478 #if defined __MSDOS__ || defined WINDOWS32
480 || (filename > pattern + 1 && filename[-1] == ':'))
485 drive_spec = __alloca (dirlen + 1);
486 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
487 /* For now, disallow wildcards in the drive spec, to
488 prevent infinite recursion in glob. */
489 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
491 /* If this is "d:pattern", we need to copy `:' to DIRNAME
492 as well. If it's "d:/pattern", don't remove the slash
493 from "d:/", since "d:" and "d:/" are not the same.*/
496 newp = __alloca (dirlen + 1);
497 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
501 if (filename[0] == '\0'
502 #if defined __MSDOS__ || defined WINDOWS32
503 && dirname[dirlen - 1] != ':'
504 && (dirlen < 3 || dirname[dirlen - 2] != ':'
505 || dirname[dirlen - 1] != '/')
508 /* "pattern/". Expand "pattern", appending slashes. */
510 int orig_flags = flags;
512 if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\')
514 /* "pattern\\/". Remove the final backslash if it hasn't
516 char *p = (char *) &dirname[dirlen - 1];
518 while (p > dirname && p[-1] == '\\') --p;
519 if ((&dirname[dirlen] - p) & 1)
521 *(char *) &dirname[--dirlen] = '\0';
522 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
525 val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
527 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
528 | (flags & GLOB_MARK));
529 else if (val == GLOB_NOMATCH && flags != orig_flags)
531 /* Make sure globfree (&dirs); is a nop. */
532 dirs.gl_pathv = NULL;
534 oldcount = pglob->gl_pathc + pglob->gl_offs;
541 if (!(flags & GLOB_APPEND))
544 if (!(flags & GLOB_DOOFFS))
545 pglob->gl_pathv = NULL;
549 pglob->gl_pathv = malloc ((pglob->gl_offs + 1) * sizeof (char *));
550 if (pglob->gl_pathv == NULL)
553 for (i = 0; i <= pglob->gl_offs; ++i)
554 pglob->gl_pathv[i] = NULL;
558 oldcount = pglob->gl_pathc + pglob->gl_offs;
560 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
562 if (dirname[1] == '\0' || dirname[1] == '/'
563 || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\'
564 && (dirname[2] == '\0' || dirname[2] == '/')))
566 /* Look up home directory. */
567 const char *home_dir = getenv ("HOME");
569 if (home_dir == NULL || home_dir[0] == '\0')
573 /* Windows NT defines HOMEDRIVE and HOMEPATH. But give preference
574 to HOME, because the user can change HOME. */
575 if (home_dir == NULL || home_dir[0] == '\0')
577 const char *home_drive = getenv ("HOMEDRIVE");
578 const char *home_path = getenv ("HOMEPATH");
580 if (home_drive != NULL && home_path != NULL)
582 size_t home_drive_len = strlen (home_drive);
583 size_t home_path_len = strlen (home_path);
584 char *mem = alloca (home_drive_len + home_path_len + 1);
586 memcpy (mem, home_drive, home_drive_len);
587 memcpy (mem + home_drive_len, home_path, home_path_len + 1);
591 home_dir = "c:/users/default"; /* poor default */
594 if (home_dir == NULL || home_dir[0] == '\0')
598 size_t buflen = GET_LOGIN_NAME_MAX () + 1;
601 /* `sysconf' does not support _SC_LOGIN_NAME_MAX. Try
604 name = __alloca (buflen);
606 success = getlogin_r (name, buflen) == 0;
610 # if defined HAVE_GETPWNAM_R || defined _LIBC
611 long int pwbuflen = GETPW_R_SIZE_MAX ();
618 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.
619 Try a moderate value. */
622 pwtmpbuf = __alloca (pwbuflen);
624 while (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
633 pwtmpbuf = extend_alloca (pwtmpbuf, pwbuflen,
637 pwtmpbuf = __alloca (pwbuflen);
645 home_dir = p->pw_dir;
648 if (home_dir == NULL || home_dir[0] == '\0')
650 if (flags & GLOB_TILDE_CHECK)
653 home_dir = "~"; /* No luck. */
655 # endif /* WINDOWS32 */
657 /* Now construct the full directory. */
658 if (dirname[1] == '\0')
661 dirlen = strlen (dirname);
666 size_t home_len = strlen (home_dir);
667 newp = __alloca (home_len + dirlen);
668 mempcpy (mempcpy (newp, home_dir, home_len),
669 &dirname[1], dirlen);
671 dirlen += home_len - 1;
673 dirname_modified = 1;
675 # if !defined _AMIGA && !defined WINDOWS32
678 char *end_name = strchr (dirname, '/');
679 const char *user_name;
680 const char *home_dir;
681 char *unescape = NULL;
683 if (!(flags & GLOB_NOESCAPE))
685 if (end_name == NULL)
687 unescape = strchr (dirname, '\\');
689 end_name = strchr (unescape, '\0');
692 unescape = memchr (dirname, '\\', end_name - dirname);
694 if (end_name == NULL)
695 user_name = dirname + 1;
699 newp = __alloca (end_name - dirname);
700 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
702 if (unescape != NULL)
704 char *p = mempcpy (newp, dirname + 1,
705 unescape - dirname - 1);
713 /* "~fo\\o\\" unescape to user_name "foo\\",
714 but "~fo\\o\\/" unescape to user_name
716 if (filename == NULL)
727 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
732 /* Look up specific user's home directory. */
735 # if defined HAVE_GETPWNAM_R || defined _LIBC
736 long int buflen = GETPW_R_SIZE_MAX ();
743 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
747 pwtmpbuf = __alloca (buflen);
749 while (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) != 0)
757 pwtmpbuf = extend_alloca (pwtmpbuf, buflen, 2 * buflen);
760 pwtmpbuf = __alloca (buflen);
765 p = getpwnam (user_name);
768 home_dir = p->pw_dir;
772 /* If we found a home directory use this. */
773 if (home_dir != NULL)
776 size_t home_len = strlen (home_dir);
777 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
778 newp = __alloca (home_len + rest_len + 1);
779 *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
780 end_name, rest_len)) = '\0';
782 dirlen = home_len + rest_len;
783 dirname_modified = 1;
786 if (flags & GLOB_TILDE_CHECK)
787 /* We have to regard it as an error if we cannot find the
791 # endif /* Not Amiga && not WINDOWS32. */
794 /* Now test whether we looked for "~" or "~NAME". In this case we
795 can give the answer now. */
796 if (filename == NULL)
801 /* Return the directory if we don't check for error or if it exists. */
802 if ((flags & GLOB_NOCHECK)
803 || (((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
804 ? ((*pglob->gl_stat) (dirname, &st) == 0
805 && S_ISDIR (st.st_mode))
806 : (__stat64 (dirname, &st64) == 0 && S_ISDIR (st64.st_mode)))))
808 int newcount = pglob->gl_pathc + pglob->gl_offs;
812 = realloc (pglob->gl_pathv, (newcount + 1 + 1) * sizeof (char *));
813 if (new_gl_pathv == NULL)
816 free (pglob->gl_pathv);
817 pglob->gl_pathv = NULL;
821 pglob->gl_pathv = new_gl_pathv;
823 if (flags & GLOB_MARK)
826 pglob->gl_pathv[newcount] = malloc (dirlen + 2);
827 if (pglob->gl_pathv[newcount] == NULL)
829 p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);
835 pglob->gl_pathv[newcount] = strdup (dirname);
836 if (pglob->gl_pathv[newcount] == NULL)
839 pglob->gl_pathv[++newcount] = NULL;
841 pglob->gl_flags = flags;
850 meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));
851 /* meta is 1 if correct glob pattern containing metacharacters.
852 If meta has bit (1 << 2) set, it means there was an unterminated
853 [ which we handle the same, using fnmatch. Broken unterminated
854 pattern bracket expressions ought to be rare enough that it is
855 not worth special casing them, fnmatch will do the right thing. */
858 /* The directory name contains metacharacters, so we
859 have to glob for the directory, and then glob for
860 the pattern in each directory found. */
863 if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\')
865 /* "foo\\/bar". Remove the final backslash from dirname
866 if it has not been quoted. */
867 char *p = (char *) &dirname[dirlen - 1];
869 while (p > dirname && p[-1] == '\\') --p;
870 if ((&dirname[dirlen] - p) & 1)
871 *(char *) &dirname[--dirlen] = '\0';
874 if (__builtin_expect ((flags & GLOB_ALTDIRFUNC) != 0, 0))
876 /* Use the alternative access functions also in the recursive
878 dirs.gl_opendir = pglob->gl_opendir;
879 dirs.gl_readdir = pglob->gl_readdir;
880 dirs.gl_closedir = pglob->gl_closedir;
881 dirs.gl_stat = pglob->gl_stat;
882 dirs.gl_lstat = pglob->gl_lstat;
885 status = glob (dirname,
886 ((flags & (GLOB_ERR | GLOB_NOESCAPE
888 | GLOB_NOSORT | GLOB_ONLYDIR),
892 if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH)
897 /* We have successfully globbed the preceding directory name.
898 For each name we found, call glob_in_dir on it and FILENAME,
899 appending the results to PGLOB. */
900 for (i = 0; i < dirs.gl_pathc; ++i)
906 /* Make globbing interruptible in the bash shell. */
907 extern int interrupt_state;
917 old_pathc = pglob->gl_pathc;
918 status = glob_in_dir (filename, dirs.gl_pathv[i],
919 ((flags | GLOB_APPEND)
920 & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),
922 if (status == GLOB_NOMATCH)
923 /* No matches in this directory. Try the next. */
934 /* Stick the directory on the front of each name. */
935 if (prefix_array (dirs.gl_pathv[i],
936 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
937 pglob->gl_pathc - old_pathc))
946 flags |= GLOB_MAGCHAR;
948 /* We have ignored the GLOB_NOCHECK flag in the `glob_in_dir' calls.
949 But if we have not found any matching entry and the GLOB_NOCHECK
950 flag was set we must return the input pattern itself. */
951 if (pglob->gl_pathc + pglob->gl_offs == oldcount)
955 if (flags & GLOB_NOCHECK)
957 int newcount = pglob->gl_pathc + pglob->gl_offs;
960 new_gl_pathv = realloc (pglob->gl_pathv,
961 (newcount + 2) * sizeof (char *));
962 if (new_gl_pathv == NULL)
967 pglob->gl_pathv = new_gl_pathv;
969 pglob->gl_pathv[newcount] = strdup (pattern);
970 if (pglob->gl_pathv[newcount] == NULL)
981 pglob->gl_pathv[newcount] = NULL;
982 pglob->gl_flags = flags;
995 int old_pathc = pglob->gl_pathc;
996 int orig_flags = flags;
1000 char *p = strchr (dirname, '\\'), *q;
1001 /* We need to unescape the dirname string. It is certainly
1002 allocated by alloca, as otherwise filename would be NULL
1003 or dirname wouldn't contain backslashes. */
1016 while (*p++ != '\0');
1017 dirname_modified = 1;
1019 if (dirname_modified)
1020 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
1021 status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
1024 if (status == GLOB_NOMATCH && flags != orig_flags
1025 && pglob->gl_pathc + pglob->gl_offs == oldcount)
1027 /* Make sure globfree (&dirs); is a nop. */
1028 dirs.gl_pathv = NULL;
1037 /* Stick the directory on the front of each name. */
1038 if (prefix_array (dirname,
1039 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
1040 pglob->gl_pathc - old_pathc))
1043 pglob->gl_pathc = 0;
1044 return GLOB_NOSPACE;
1049 if (flags & GLOB_MARK)
1051 /* Append slashes to directory names. */
1056 for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)
1057 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1058 ? ((*pglob->gl_stat) (pglob->gl_pathv[i], &st) == 0
1059 && S_ISDIR (st.st_mode))
1060 : (__stat64 (pglob->gl_pathv[i], &st64) == 0
1061 && S_ISDIR (st64.st_mode))))
1063 size_t len = strlen (pglob->gl_pathv[i]) + 2;
1064 char *new = realloc (pglob->gl_pathv[i], len);
1068 pglob->gl_pathc = 0;
1069 return GLOB_NOSPACE;
1071 strcpy (&new[len - 2], "/");
1072 pglob->gl_pathv[i] = new;
1076 if (!(flags & GLOB_NOSORT))
1078 /* Sort the vector. */
1079 qsort (&pglob->gl_pathv[oldcount],
1080 pglob->gl_pathc + pglob->gl_offs - oldcount,
1081 sizeof (char *), collated_compare);
1086 #if defined _LIBC && !defined glob
1087 libc_hidden_def (glob)
1091 #if !defined _LIBC || !defined GLOB_ONLY_P
1093 /* Free storage allocated in PGLOB by a previous `glob' call. */
1096 register glob_t *pglob;
1098 if (pglob->gl_pathv != NULL)
1101 for (i = 0; i < pglob->gl_pathc; ++i)
1102 if (pglob->gl_pathv[pglob->gl_offs + i] != NULL)
1103 free (pglob->gl_pathv[pglob->gl_offs + i]);
1104 free (pglob->gl_pathv);
1105 pglob->gl_pathv = NULL;
1108 #if defined _LIBC && !defined globfree
1109 libc_hidden_def (globfree)
1113 /* Do a collated comparison of A and B. */
1115 collated_compare (const void *a, const void *b)
1117 char *const *ps1 = a; char *s1 = *ps1;
1118 char *const *ps2 = b; char *s2 = *ps2;
1126 return strcoll (s1, s2);
1130 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1131 elements in place. Return nonzero if out of memory, zero if successful.
1132 A slash is inserted between DIRNAME and each elt of ARRAY,
1133 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1135 prefix_array (const char *dirname, char **array, size_t n)
1138 size_t dirlen = strlen (dirname);
1139 #if defined __MSDOS__ || defined WINDOWS32
1141 # define DIRSEP_CHAR sep_char
1143 # define DIRSEP_CHAR '/'
1146 if (dirlen == 1 && dirname[0] == '/')
1147 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1148 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1150 #if defined __MSDOS__ || defined WINDOWS32
1151 else if (dirlen > 1)
1153 if (dirname[dirlen - 1] == '/' && dirname[dirlen - 2] == ':')
1154 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1156 else if (dirname[dirlen - 1] == ':')
1158 /* DIRNAME is "d:". Use `:' instead of `/'. */
1165 for (i = 0; i < n; ++i)
1167 size_t eltlen = strlen (array[i]) + 1;
1168 char *new = malloc (dirlen + 1 + eltlen);
1177 char *endp = mempcpy (new, dirname, dirlen);
1178 *endp++ = DIRSEP_CHAR;
1179 mempcpy (endp, array[i], eltlen);
1189 /* We must not compile this function twice. */
1190 #if !defined _LIBC || !defined NO_GLOB_PATTERN_P
1192 __glob_pattern_type (pattern, quote)
1193 const char *pattern;
1196 register const char *p;
1199 for (p = pattern; *p != '\0'; ++p)
1228 /* Return nonzero if PATTERN contains any metacharacters.
1229 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
1231 __glob_pattern_p (pattern, quote)
1232 const char *pattern;
1235 return __glob_pattern_type (pattern, quote) == 1;
1238 weak_alias (__glob_pattern_p, glob_pattern_p)
1242 #endif /* !GLOB_ONLY_P */
1245 #if !defined _LIBC || !defined GLOB_ONLY_P
1246 /* We put this in a separate function mainly to allow the memory
1247 allocated with alloca to be recycled. */
1249 __attribute_noinline__
1250 link_exists2_p (const char *dir, size_t dirlen, const char *fname,
1252 # if !defined _LIBC && !HAVE_FSTATAT
1257 size_t fnamelen = strlen (fname);
1258 char *fullname = __alloca (dirlen + 1 + fnamelen + 1);
1261 mempcpy (mempcpy (mempcpy (fullname, dir, dirlen), "/", 1),
1262 fname, fnamelen + 1);
1264 # if !defined _LIBC && !HAVE_FSTATAT
1265 if (__builtin_expect ((flags & GLOB_ALTDIRFUNC) == 0, 1))
1268 return __stat64 (fullname, &st64) == 0;
1271 return (*pglob->gl_stat) (fullname, &st) == 0;
1274 /* Return true if DIR/FNAME exists. */
1276 link_exists_p (int dfd, const char *dir, size_t dirlen, const char *fname,
1277 glob_t *pglob, int flags)
1279 # if defined _LIBC || HAVE_FSTATAT
1280 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1281 return link_exists2_p (dir, dirlen, fname, pglob);
1285 return __fxstatat64 (_STAT_VER, dfd, fname, &st64, 0) == 0;
1288 return link_exists2_p (dir, dirlen, fname, pglob, flags);
1294 /* Like `glob', but PATTERN is a final pathname component,
1295 and matches are searched for in DIRECTORY.
1296 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1297 The GLOB_APPEND flag is assumed to be set (always appends). */
1299 glob_in_dir (const char *pattern, const char *directory, int flags,
1300 int (*errfunc) (const char *, int),
1303 size_t dirlen = strlen (directory);
1304 void *stream = NULL;
1307 struct globnames *next;
1311 #define INITIAL_COUNT sizeof (init_names.name) / sizeof (init_names.name[0])
1312 struct globnames init_names;
1313 struct globnames *names = &init_names;
1314 struct globnames *names_alloca = &init_names;
1316 size_t allocasize = sizeof (init_names);
1322 init_names.next = NULL;
1323 init_names.count = INITIAL_COUNT;
1325 meta = __glob_pattern_type (pattern, !(flags & GLOB_NOESCAPE));
1326 if (meta == 0 && (flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
1328 /* We need not do any tests. The PATTERN contains no meta
1329 characters and we must not return an error therefore the
1330 result will always contain exactly one name. */
1331 flags |= GLOB_NOCHECK;
1335 /* Since we use the normal file functions we can also use stat()
1336 to verify the file is there. */
1339 size_t patlen = strlen (pattern);
1340 char *fullname = __alloca (dirlen + 1 + patlen + 1);
1342 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1344 pattern, patlen + 1);
1345 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1346 ? (*pglob->gl_stat) (fullname, &st)
1347 : __stat64 (fullname, &st64)) == 0)
1348 /* We found this file to be existing. Now tell the rest
1349 of the function to copy this name into the result. */
1350 flags |= GLOB_NOCHECK;
1354 stream = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1355 ? (*pglob->gl_opendir) (directory)
1356 : opendir (directory));
1359 if (errno != ENOTDIR
1360 && ((errfunc != NULL && (*errfunc) (directory, errno))
1361 || (flags & GLOB_ERR)))
1362 return GLOB_ABORTED;
1366 int dfd = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1367 ? -1 : dirfd ((DIR *) stream));
1368 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1369 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1370 #if defined _AMIGA || defined VMS
1374 flags |= GLOB_MAGCHAR;
1380 #if defined _LIBC && !defined COMPILE_GLOB64
1384 struct dirent64 d64;
1385 char room [offsetof (struct dirent64, d_name[0])
1390 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1392 struct dirent *d32 = (*pglob->gl_readdir) (stream);
1395 CONVERT_DIRENT_DIRENT64 (&d64buf.d64, d32);
1402 d = __readdir64 (stream);
1404 struct dirent *d = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1405 ? ((struct dirent *)
1406 (*pglob->gl_readdir) (stream))
1407 : __readdir (stream));
1411 if (! REAL_DIR_ENTRY (d))
1414 /* If we shall match only directories use the information
1415 provided by the dirent call if possible. */
1416 if ((flags & GLOB_ONLYDIR) && !DIRENT_MIGHT_BE_DIR (d))
1421 if (fnmatch (pattern, name, fnm_flags) == 0)
1423 /* If the file we found is a symlink we have to
1424 make sure the target file exists. */
1425 if (!DIRENT_MIGHT_BE_SYMLINK (d)
1426 || link_exists_p (dfd, directory, dirlen, name, pglob,
1429 if (cur == names->count)
1431 struct globnames *newnames;
1432 size_t count = names->count * 2;
1433 size_t size = (sizeof (struct globnames)
1434 + ((count - INITIAL_COUNT)
1435 * sizeof (char *)));
1437 if (__libc_use_alloca (allocasize))
1438 newnames = names_alloca = __alloca (size);
1439 else if ((newnames = malloc (size))
1442 newnames->count = count;
1443 newnames->next = names;
1447 len = _D_EXACT_NAMLEN (d);
1448 names->name[cur] = malloc (len + 1);
1449 if (names->name[cur] == NULL)
1451 *((char *) mempcpy (names->name[cur++], name, len))
1460 if (nfound == 0 && (flags & GLOB_NOCHECK))
1462 size_t len = strlen (pattern);
1464 names->name[cur] = malloc (len + 1);
1465 if (names->name[cur] == NULL)
1467 *((char *) mempcpy (names->name[cur++], pattern, len)) = '\0';
1470 result = GLOB_NOMATCH;
1474 = realloc (pglob->gl_pathv,
1475 (pglob->gl_pathc + pglob->gl_offs + nfound + 1)
1479 if (new_gl_pathv == NULL)
1484 struct globnames *old = names;
1486 for (i = 0; i < cur; ++i)
1487 free (names->name[i]);
1488 names = names->next;
1489 /* NB: we will not leak memory here if we exit without
1490 freeing the current block assigned to OLD. At least
1491 the very first block is always allocated on the stack
1492 and this is the block assigned to OLD here. */
1495 assert (old == &init_names);
1499 if (old == names_alloca)
1500 names_alloca = names;
1504 result = GLOB_NOSPACE;
1510 struct globnames *old = names;
1512 for (i = 0; i < cur; ++i)
1513 new_gl_pathv[pglob->gl_offs + pglob->gl_pathc++]
1515 names = names->next;
1516 /* NB: we will not leak memory here if we exit without
1517 freeing the current block assigned to OLD. At least
1518 the very first block is always allocated on the stack
1519 and this is the block assigned to OLD here. */
1522 assert (old == &init_names);
1526 if (old == names_alloca)
1527 names_alloca = names;
1532 pglob->gl_pathv = new_gl_pathv;
1534 pglob->gl_pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
1536 pglob->gl_flags = flags;
1543 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1544 (*pglob->gl_closedir) (stream);