1 /* Copyright (C) 1991-2002, 2003, 2004, 2005, 2006, 2007, 2008
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
50 # define __set_errno(val) errno = (val)
56 /* In GNU systems, <dirent.h> defines this macro for us. */
57 #ifndef _D_EXACT_NAMLEN
58 # define _D_EXACT_NAMLEN(dirent) strlen ((dirent)->d_name)
61 /* When used in the GNU libc the symbol _DIRENT_HAVE_D_TYPE is available
62 if the `d_type' member for `struct dirent' is available.
63 HAVE_STRUCT_DIRENT_D_TYPE plays the same role in GNULIB. */
64 #if defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE
65 /* True if the directory entry D must be of type T. */
66 # define DIRENT_MUST_BE(d, t) ((d)->d_type == (t))
68 /* True if the directory entry D might be a symbolic link. */
69 # define DIRENT_MIGHT_BE_SYMLINK(d) \
70 ((d)->d_type == DT_UNKNOWN || (d)->d_type == DT_LNK)
72 /* True if the directory entry D might be a directory. */
73 # define DIRENT_MIGHT_BE_DIR(d) \
74 ((d)->d_type == DT_DIR || DIRENT_MIGHT_BE_SYMLINK (d))
76 #else /* !HAVE_D_TYPE */
77 # define DIRENT_MUST_BE(d, t) false
78 # define DIRENT_MIGHT_BE_SYMLINK(d) true
79 # define DIRENT_MIGHT_BE_DIR(d) true
80 #endif /* HAVE_D_TYPE */
82 /* If the system has the `struct dirent64' type we use it internally. */
83 #if defined _LIBC && !defined COMPILE_GLOB64
84 # if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
85 # define CONVERT_D_INO(d64, d32)
87 # define CONVERT_D_INO(d64, d32) \
88 (d64)->d_ino = (d32)->d_ino;
91 # ifdef _DIRENT_HAVE_D_TYPE
92 # define CONVERT_D_TYPE(d64, d32) \
93 (d64)->d_type = (d32)->d_type;
95 # define CONVERT_D_TYPE(d64, d32)
98 # define CONVERT_DIRENT_DIRENT64(d64, d32) \
99 memcpy ((d64)->d_name, (d32)->d_name, _D_EXACT_NAMLEN (d32) + 1); \
100 CONVERT_D_INO (d64, d32) \
101 CONVERT_D_TYPE (d64, d32)
105 #if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
106 /* Posix does not require that the d_ino field be present, and some
107 systems do not provide it. */
108 # define REAL_DIR_ENTRY(dp) 1
110 # define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
116 /* NAME_MAX is usually defined in <dirent.h> or <limits.h>. */
119 # define NAME_MAX (sizeof (((struct dirent *) 0)->d_name))
126 # define strdup(str) __strdup (str)
127 # define sysconf(id) __sysconf (id)
128 # define closedir(dir) __closedir (dir)
129 # define opendir(name) __opendir (name)
130 # define readdir(str) __readdir64 (str)
131 # define getpwnam_r(name, bufp, buf, len, res) \
132 __getpwnam_r (name, bufp, buf, len, res)
134 # define __stat64(fname, buf) __xstat64 (_STAT_VER, fname, buf)
136 # define struct_stat64 struct stat64
138 # define __stat64(fname, buf) stat (fname, buf)
139 # define __fxstatat64(_, d, f, st, flag) fstatat (d, f, st, flag)
140 # define struct_stat64 struct stat
141 # define __stat(fname, buf) stat (fname, buf)
142 # define __alloca alloca
143 # define __readdir readdir
144 # define __readdir64 readdir64
145 # define __glob_pattern_p glob_pattern_p
154 #ifdef _SC_GETPW_R_SIZE_MAX
155 # define GETPW_R_SIZE_MAX() sysconf (_SC_GETPW_R_SIZE_MAX)
157 # define GETPW_R_SIZE_MAX() (-1)
159 #ifdef _SC_LOGIN_NAME_MAX
160 # define GET_LOGIN_NAME_MAX() sysconf (_SC_LOGIN_NAME_MAX)
162 # define GET_LOGIN_NAME_MAX() (-1)
165 static const char *next_brace_sub (const char *begin, int flags) __THROW;
167 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
169 #ifndef attribute_hidden
170 # define attribute_hidden
173 #ifndef __attribute_noinline__
174 # if __GNUC__ < 3 || (__GNUC__ == 3 && __GNUC_MINOR__ < 1)
175 # define __attribute_noinline__ /* Ignore */
177 # define __attribute_noinline__ __attribute__ ((__noinline__))
181 #if ! defined __builtin_expect && __GNUC__ < 3
182 # define __builtin_expect(expr, expected) (expr)
186 /* The results of opendir() in this file are not used with dirfd and fchdir,
187 therefore save some unnecessary work in fchdir.c. */
192 /* The OS usually guarantees only one guard page at the bottom of the stack,
193 and a page size can be as small as 4096 bytes. So we cannot safely
194 allocate anything larger than 4096 bytes. Also care for the possibility
195 of a few compiler-allocated temporary stack slots. */
196 # define __libc_use_alloca(n) ((n) < 4032)
198 /* alloca is implemented with malloc, so just use malloc. */
199 # define __libc_use_alloca(n) 0
203 static int glob_in_dir (const char *pattern, const char *directory,
204 int flags, int (*errfunc) (const char *, int),
206 extern int __glob_pattern_type (const char *pattern, int quote)
209 #if !defined _LIBC || !defined GLOB_ONLY_P
210 static int prefix_array (const char *prefix, char **array, size_t n) __THROW;
211 static int collated_compare (const void *, const void *) __THROW;
214 /* Find the end of the sub-pattern in a brace expression. */
216 next_brace_sub (const char *cp, int flags)
218 unsigned int depth = 0;
220 if ((flags & GLOB_NOESCAPE) == 0 && *cp == '\\')
228 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
235 return *cp != '\0' ? cp : NULL;
238 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
240 /* Do glob searching for PATTERN, placing results in PGLOB.
241 The bits defined above may be set in FLAGS.
242 If a directory cannot be opened or read and ERRFUNC is not nil,
243 it is called with the pathname that caused the error, and the
244 `errno' value from the failing call; if it returns non-zero
245 `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
246 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
247 Otherwise, `glob' returns zero. */
249 #ifdef GLOB_ATTRIBUTE
252 glob (pattern, flags, errfunc, pglob)
253 const char * restrict pattern;
255 int (*errfunc) (const char *, int);
256 glob_t * restrict pglob;
258 const char *filename;
264 int dirname_modified;
267 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
269 __set_errno (EINVAL);
273 if (!(flags & GLOB_DOOFFS))
274 /* Have to do this so `globfree' knows where to start freeing. It
275 also makes all the code that uses gl_offs simpler. */
278 if (flags & GLOB_BRACE)
282 if (flags & GLOB_NOESCAPE)
283 begin = strchr (pattern, '{');
295 if (*begin == '\\' && begin[1] != '\0')
297 else if (*begin == '{')
306 /* Allocate working buffer large enough for our work. Note that
307 we have at least an opening and closing brace. */
315 char onealt[strlen (pattern) - 1];
317 char *onealt = malloc (strlen (pattern) - 1);
320 if (!(flags & GLOB_APPEND))
323 pglob->gl_pathv = NULL;
329 /* We know the prefix for all sub-patterns. */
330 alt_start = mempcpy (onealt, pattern, begin - pattern);
332 /* Find the first sub-pattern and at the same time find the
333 rest after the closing brace. */
334 next = next_brace_sub (begin + 1, flags);
337 /* It is an invalid expression. */
341 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
344 /* Now find the end of the whole brace expression. */
348 rest = next_brace_sub (rest + 1, flags);
351 /* It is an invalid expression. */
355 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
358 /* Please note that we now can be sure the brace expression
360 rest_len = strlen (++rest) + 1;
362 /* We have a brace expression. BEGIN points to the opening {,
363 NEXT points past the terminator of the first element, and END
364 points past the final }. We will accumulate result names from
365 recursive runs for each brace alternative in the buffer using
368 if (!(flags & GLOB_APPEND))
370 /* This call is to set a new vector, so clear out the
371 vector so we can append to it. */
373 pglob->gl_pathv = NULL;
375 firstc = pglob->gl_pathc;
382 /* Construct the new glob expression. */
383 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
385 result = glob (onealt,
386 ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))
387 | GLOB_APPEND), errfunc, pglob);
389 /* If we got an error, return it. */
390 if (result && result != GLOB_NOMATCH)
395 if (!(flags & GLOB_APPEND))
404 /* We saw the last entry. */
408 next = next_brace_sub (p, flags);
409 assert (next != NULL);
416 if (pglob->gl_pathc != firstc)
417 /* We found some entries. */
419 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
424 /* Find the filename. */
425 filename = strrchr (pattern, '/');
426 #if defined __MSDOS__ || defined WINDOWS32
427 /* The case of "d:pattern". Since `:' is not allowed in
428 file names, we can safely assume that wherever it
429 happens in pattern, it signals the filename part. This
430 is so we could some day support patterns like "[a-z]:foo". */
431 if (filename == NULL)
432 filename = strchr (pattern, ':');
433 #endif /* __MSDOS__ || WINDOWS32 */
434 dirname_modified = 0;
435 if (filename == NULL)
437 /* This can mean two things: a simple name or "~name". The latter
438 case is nothing but a notation for a directory. */
439 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
442 dirlen = strlen (pattern);
444 /* Set FILENAME to NULL as a special flag. This is ugly but
445 other solutions would require much more code. We test for
446 this special case below. */
460 else if (filename == pattern
461 || (filename == pattern + 1 && pattern[0] == '\\'
462 && (flags & GLOB_NOESCAPE) == 0))
464 /* "/pattern" or "\\/pattern". */
472 dirlen = filename - pattern;
473 #if defined __MSDOS__ || defined WINDOWS32
475 || (filename > pattern + 1 && filename[-1] == ':'))
480 drive_spec = __alloca (dirlen + 1);
481 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
482 /* For now, disallow wildcards in the drive spec, to
483 prevent infinite recursion in glob. */
484 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
486 /* If this is "d:pattern", we need to copy `:' to DIRNAME
487 as well. If it's "d:/pattern", don't remove the slash
488 from "d:/", since "d:" and "d:/" are not the same.*/
491 newp = __alloca (dirlen + 1);
492 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
496 if (filename[0] == '\0'
497 #if defined __MSDOS__ || defined WINDOWS32
498 && dirname[dirlen - 1] != ':'
499 && (dirlen < 3 || dirname[dirlen - 2] != ':'
500 || dirname[dirlen - 1] != '/')
503 /* "pattern/". Expand "pattern", appending slashes. */
505 int orig_flags = flags;
507 if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\')
509 /* "pattern\\/". Remove the final backslash if it hasn't
511 char *p = (char *) &dirname[dirlen - 1];
513 while (p > dirname && p[-1] == '\\') --p;
514 if ((&dirname[dirlen] - p) & 1)
516 *(char *) &dirname[--dirlen] = '\0';
517 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
520 val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
522 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
523 | (flags & GLOB_MARK));
524 else if (val == GLOB_NOMATCH && flags != orig_flags)
526 /* Make sure globfree (&dirs); is a nop. */
527 dirs.gl_pathv = NULL;
529 oldcount = pglob->gl_pathc + pglob->gl_offs;
536 if (!(flags & GLOB_APPEND))
539 if (!(flags & GLOB_DOOFFS))
540 pglob->gl_pathv = NULL;
544 pglob->gl_pathv = malloc ((pglob->gl_offs + 1) * sizeof (char *));
545 if (pglob->gl_pathv == NULL)
548 for (i = 0; i <= pglob->gl_offs; ++i)
549 pglob->gl_pathv[i] = NULL;
553 oldcount = pglob->gl_pathc + pglob->gl_offs;
555 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
557 if (dirname[1] == '\0' || dirname[1] == '/'
558 || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\'
559 && (dirname[2] == '\0' || dirname[2] == '/')))
561 /* Look up home directory. */
562 const char *home_dir = getenv ("HOME");
564 if (home_dir == NULL || home_dir[0] == '\0')
568 if (home_dir == NULL || home_dir[0] == '\0')
569 home_dir = "c:/users/default"; /* poor default */
571 if (home_dir == NULL || home_dir[0] == '\0')
575 size_t buflen = GET_LOGIN_NAME_MAX () + 1;
578 /* `sysconf' does not support _SC_LOGIN_NAME_MAX. Try
581 name = __alloca (buflen);
583 success = getlogin_r (name, buflen) == 0;
587 # if defined HAVE_GETPWNAM_R || defined _LIBC
588 long int pwbuflen = GETPW_R_SIZE_MAX ();
595 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.
596 Try a moderate value. */
599 pwtmpbuf = __alloca (pwbuflen);
601 while (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
610 pwtmpbuf = extend_alloca (pwtmpbuf, pwbuflen,
614 pwtmpbuf = __alloca (pwbuflen);
622 home_dir = p->pw_dir;
625 if (home_dir == NULL || home_dir[0] == '\0')
627 if (flags & GLOB_TILDE_CHECK)
630 home_dir = "~"; /* No luck. */
632 # endif /* WINDOWS32 */
634 /* Now construct the full directory. */
635 if (dirname[1] == '\0')
638 dirlen = strlen (dirname);
643 size_t home_len = strlen (home_dir);
644 newp = __alloca (home_len + dirlen);
645 mempcpy (mempcpy (newp, home_dir, home_len),
646 &dirname[1], dirlen);
648 dirlen += home_len - 1;
650 dirname_modified = 1;
652 # if !defined _AMIGA && !defined WINDOWS32
655 char *end_name = strchr (dirname, '/');
656 const char *user_name;
657 const char *home_dir;
658 char *unescape = NULL;
660 if (!(flags & GLOB_NOESCAPE))
662 if (end_name == NULL)
664 unescape = strchr (dirname, '\\');
666 end_name = strchr (unescape, '\0');
669 unescape = memchr (dirname, '\\', end_name - dirname);
671 if (end_name == NULL)
672 user_name = dirname + 1;
676 newp = __alloca (end_name - dirname);
677 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
679 if (unescape != NULL)
681 char *p = mempcpy (newp, dirname + 1,
682 unescape - dirname - 1);
690 /* "~fo\\o\\" unescape to user_name "foo\\",
691 but "~fo\\o\\/" unescape to user_name
693 if (filename == NULL)
704 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
709 /* Look up specific user's home directory. */
712 # if defined HAVE_GETPWNAM_R || defined _LIBC
713 long int buflen = GETPW_R_SIZE_MAX ();
720 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
724 pwtmpbuf = __alloca (buflen);
726 while (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) != 0)
734 pwtmpbuf = extend_alloca (pwtmpbuf, buflen, 2 * buflen);
737 pwtmpbuf = __alloca (buflen);
742 p = getpwnam (user_name);
745 home_dir = p->pw_dir;
749 /* If we found a home directory use this. */
750 if (home_dir != NULL)
753 size_t home_len = strlen (home_dir);
754 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
755 newp = __alloca (home_len + rest_len + 1);
756 *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
757 end_name, rest_len)) = '\0';
759 dirlen = home_len + rest_len;
760 dirname_modified = 1;
763 if (flags & GLOB_TILDE_CHECK)
764 /* We have to regard it as an error if we cannot find the
768 # endif /* Not Amiga && not WINDOWS32. */
771 /* Now test whether we looked for "~" or "~NAME". In this case we
772 can give the answer now. */
773 if (filename == NULL)
778 /* Return the directory if we don't check for error or if it exists. */
779 if ((flags & GLOB_NOCHECK)
780 || (((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
781 ? ((*pglob->gl_stat) (dirname, &st) == 0
782 && S_ISDIR (st.st_mode))
783 : (__stat64 (dirname, &st64) == 0 && S_ISDIR (st64.st_mode)))))
785 int newcount = pglob->gl_pathc + pglob->gl_offs;
789 = realloc (pglob->gl_pathv, (newcount + 1 + 1) * sizeof (char *));
790 if (new_gl_pathv == NULL)
793 free (pglob->gl_pathv);
794 pglob->gl_pathv = NULL;
798 pglob->gl_pathv = new_gl_pathv;
800 if (flags & GLOB_MARK)
803 pglob->gl_pathv[newcount] = malloc (dirlen + 2);
804 if (pglob->gl_pathv[newcount] == NULL)
806 p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);
812 pglob->gl_pathv[newcount] = strdup (dirname);
813 if (pglob->gl_pathv[newcount] == NULL)
816 pglob->gl_pathv[++newcount] = NULL;
818 pglob->gl_flags = flags;
827 meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));
828 /* meta is 1 if correct glob pattern containing metacharacters.
829 If meta has bit (1 << 2) set, it means there was an unterminated
830 [ which we handle the same, using fnmatch. Broken unterminated
831 pattern bracket expressions ought to be rare enough that it is
832 not worth special casing them, fnmatch will do the right thing. */
835 /* The directory name contains metacharacters, so we
836 have to glob for the directory, and then glob for
837 the pattern in each directory found. */
840 if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\')
842 /* "foo\\/bar". Remove the final backslash from dirname
843 if it has not been quoted. */
844 char *p = (char *) &dirname[dirlen - 1];
846 while (p > dirname && p[-1] == '\\') --p;
847 if ((&dirname[dirlen] - p) & 1)
848 *(char *) &dirname[--dirlen] = '\0';
851 if (__builtin_expect ((flags & GLOB_ALTDIRFUNC) != 0, 0))
853 /* Use the alternative access functions also in the recursive
855 dirs.gl_opendir = pglob->gl_opendir;
856 dirs.gl_readdir = pglob->gl_readdir;
857 dirs.gl_closedir = pglob->gl_closedir;
858 dirs.gl_stat = pglob->gl_stat;
859 dirs.gl_lstat = pglob->gl_lstat;
862 status = glob (dirname,
863 ((flags & (GLOB_ERR | GLOB_NOESCAPE
865 | GLOB_NOSORT | GLOB_ONLYDIR),
869 if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH)
874 /* We have successfully globbed the preceding directory name.
875 For each name we found, call glob_in_dir on it and FILENAME,
876 appending the results to PGLOB. */
877 for (i = 0; i < dirs.gl_pathc; ++i)
883 /* Make globbing interruptible in the bash shell. */
884 extern int interrupt_state;
894 old_pathc = pglob->gl_pathc;
895 status = glob_in_dir (filename, dirs.gl_pathv[i],
896 ((flags | GLOB_APPEND)
897 & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),
899 if (status == GLOB_NOMATCH)
900 /* No matches in this directory. Try the next. */
911 /* Stick the directory on the front of each name. */
912 if (prefix_array (dirs.gl_pathv[i],
913 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
914 pglob->gl_pathc - old_pathc))
923 flags |= GLOB_MAGCHAR;
925 /* We have ignored the GLOB_NOCHECK flag in the `glob_in_dir' calls.
926 But if we have not found any matching entry and the GLOB_NOCHECK
927 flag was set we must return the input pattern itself. */
928 if (pglob->gl_pathc + pglob->gl_offs == oldcount)
932 if (flags & GLOB_NOCHECK)
934 int newcount = pglob->gl_pathc + pglob->gl_offs;
937 new_gl_pathv = realloc (pglob->gl_pathv,
938 (newcount + 2) * sizeof (char *));
939 if (new_gl_pathv == NULL)
944 pglob->gl_pathv = new_gl_pathv;
946 pglob->gl_pathv[newcount] = strdup (pattern);
947 if (pglob->gl_pathv[newcount] == NULL)
958 pglob->gl_pathv[newcount] = NULL;
959 pglob->gl_flags = flags;
972 int old_pathc = pglob->gl_pathc;
973 int orig_flags = flags;
977 char *p = strchr (dirname, '\\'), *q;
978 /* We need to unescape the dirname string. It is certainly
979 allocated by alloca, as otherwise filename would be NULL
980 or dirname wouldn't contain backslashes. */
993 while (*p++ != '\0');
994 dirname_modified = 1;
996 if (dirname_modified)
997 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
998 status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
1001 if (status == GLOB_NOMATCH && flags != orig_flags
1002 && pglob->gl_pathc + pglob->gl_offs == oldcount)
1004 /* Make sure globfree (&dirs); is a nop. */
1005 dirs.gl_pathv = NULL;
1014 /* Stick the directory on the front of each name. */
1015 if (prefix_array (dirname,
1016 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
1017 pglob->gl_pathc - old_pathc))
1020 pglob->gl_pathc = 0;
1021 return GLOB_NOSPACE;
1026 if (flags & GLOB_MARK)
1028 /* Append slashes to directory names. */
1033 for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)
1034 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1035 ? ((*pglob->gl_stat) (pglob->gl_pathv[i], &st) == 0
1036 && S_ISDIR (st.st_mode))
1037 : (__stat64 (pglob->gl_pathv[i], &st64) == 0
1038 && S_ISDIR (st64.st_mode))))
1040 size_t len = strlen (pglob->gl_pathv[i]) + 2;
1041 char *new = realloc (pglob->gl_pathv[i], len);
1045 pglob->gl_pathc = 0;
1046 return GLOB_NOSPACE;
1048 strcpy (&new[len - 2], "/");
1049 pglob->gl_pathv[i] = new;
1053 if (!(flags & GLOB_NOSORT))
1055 /* Sort the vector. */
1056 qsort (&pglob->gl_pathv[oldcount],
1057 pglob->gl_pathc + pglob->gl_offs - oldcount,
1058 sizeof (char *), collated_compare);
1063 #if defined _LIBC && !defined glob
1064 libc_hidden_def (glob)
1068 #if !defined _LIBC || !defined GLOB_ONLY_P
1070 /* Free storage allocated in PGLOB by a previous `glob' call. */
1073 register glob_t *pglob;
1075 if (pglob->gl_pathv != NULL)
1078 for (i = 0; i < pglob->gl_pathc; ++i)
1079 if (pglob->gl_pathv[pglob->gl_offs + i] != NULL)
1080 free (pglob->gl_pathv[pglob->gl_offs + i]);
1081 free (pglob->gl_pathv);
1082 pglob->gl_pathv = NULL;
1085 #if defined _LIBC && !defined globfree
1086 libc_hidden_def (globfree)
1090 /* Do a collated comparison of A and B. */
1092 collated_compare (const void *a, const void *b)
1094 char *const *ps1 = a; char *s1 = *ps1;
1095 char *const *ps2 = b; char *s2 = *ps2;
1103 return strcoll (s1, s2);
1107 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1108 elements in place. Return nonzero if out of memory, zero if successful.
1109 A slash is inserted between DIRNAME and each elt of ARRAY,
1110 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1112 prefix_array (const char *dirname, char **array, size_t n)
1115 size_t dirlen = strlen (dirname);
1116 #if defined __MSDOS__ || defined WINDOWS32
1118 # define DIRSEP_CHAR sep_char
1120 # define DIRSEP_CHAR '/'
1123 if (dirlen == 1 && dirname[0] == '/')
1124 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1125 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1127 #if defined __MSDOS__ || defined WINDOWS32
1128 else if (dirlen > 1)
1130 if (dirname[dirlen - 1] == '/' && dirname[dirlen - 2] == ':')
1131 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1133 else if (dirname[dirlen - 1] == ':')
1135 /* DIRNAME is "d:". Use `:' instead of `/'. */
1142 for (i = 0; i < n; ++i)
1144 size_t eltlen = strlen (array[i]) + 1;
1145 char *new = malloc (dirlen + 1 + eltlen);
1154 char *endp = mempcpy (new, dirname, dirlen);
1155 *endp++ = DIRSEP_CHAR;
1156 mempcpy (endp, array[i], eltlen);
1166 /* We must not compile this function twice. */
1167 #if !defined _LIBC || !defined NO_GLOB_PATTERN_P
1169 __glob_pattern_type (pattern, quote)
1170 const char *pattern;
1173 register const char *p;
1176 for (p = pattern; *p != '\0'; ++p)
1205 /* Return nonzero if PATTERN contains any metacharacters.
1206 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
1208 __glob_pattern_p (pattern, quote)
1209 const char *pattern;
1212 return __glob_pattern_type (pattern, quote) == 1;
1215 weak_alias (__glob_pattern_p, glob_pattern_p)
1219 #endif /* !GLOB_ONLY_P */
1222 #if !defined _LIBC || !defined GLOB_ONLY_P
1223 /* We put this in a separate function mainly to allow the memory
1224 allocated with alloca to be recycled. */
1226 __attribute_noinline__
1227 link_exists2_p (const char *dir, size_t dirlen, const char *fname,
1229 # if !defined _LIBC && !HAVE_FSTATAT
1234 size_t fnamelen = strlen (fname);
1235 char *fullname = __alloca (dirlen + 1 + fnamelen + 1);
1238 mempcpy (mempcpy (mempcpy (fullname, dir, dirlen), "/", 1),
1239 fname, fnamelen + 1);
1241 # if !defined _LIBC && !HAVE_FSTATAT
1242 if (__builtin_expect ((flags & GLOB_ALTDIRFUNC) == 0, 1))
1245 return __stat64 (fullname, &st64) == 0;
1248 return (*pglob->gl_stat) (fullname, &st) == 0;
1251 /* Return true if DIR/FNAME exists. */
1253 link_exists_p (int dfd, const char *dir, size_t dirlen, const char *fname,
1254 glob_t *pglob, int flags)
1256 # if defined _LIBC || HAVE_FSTATAT
1257 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1258 return link_exists2_p (dir, dirlen, fname, pglob);
1262 return __fxstatat64 (_STAT_VER, dfd, fname, &st64, 0) == 0;
1265 return link_exists2_p (dir, dirlen, fname, pglob, flags);
1271 /* Like `glob', but PATTERN is a final pathname component,
1272 and matches are searched for in DIRECTORY.
1273 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1274 The GLOB_APPEND flag is assumed to be set (always appends). */
1276 glob_in_dir (const char *pattern, const char *directory, int flags,
1277 int (*errfunc) (const char *, int),
1280 size_t dirlen = strlen (directory);
1281 void *stream = NULL;
1284 struct globnames *next;
1288 #define INITIAL_COUNT sizeof (init_names.name) / sizeof (init_names.name[0])
1289 struct globnames init_names;
1290 struct globnames *names = &init_names;
1291 struct globnames *names_alloca = &init_names;
1293 size_t allocasize = sizeof (init_names);
1299 init_names.next = NULL;
1300 init_names.count = INITIAL_COUNT;
1302 meta = __glob_pattern_type (pattern, !(flags & GLOB_NOESCAPE));
1303 if (meta == 0 && (flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
1305 /* We need not do any tests. The PATTERN contains no meta
1306 characters and we must not return an error therefore the
1307 result will always contain exactly one name. */
1308 flags |= GLOB_NOCHECK;
1312 /* Since we use the normal file functions we can also use stat()
1313 to verify the file is there. */
1316 size_t patlen = strlen (pattern);
1317 char *fullname = __alloca (dirlen + 1 + patlen + 1);
1319 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1321 pattern, patlen + 1);
1322 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1323 ? (*pglob->gl_stat) (fullname, &st)
1324 : __stat64 (fullname, &st64)) == 0)
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;
1331 stream = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1332 ? (*pglob->gl_opendir) (directory)
1333 : opendir (directory));
1336 if (errno != ENOTDIR
1337 && ((errfunc != NULL && (*errfunc) (directory, errno))
1338 || (flags & GLOB_ERR)))
1339 return GLOB_ABORTED;
1343 int dfd = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1344 ? -1 : dirfd ((DIR *) stream));
1345 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1346 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1347 #if defined _AMIGA || defined VMS
1351 flags |= GLOB_MAGCHAR;
1357 #if defined _LIBC && !defined COMPILE_GLOB64
1361 struct dirent64 d64;
1362 char room [offsetof (struct dirent64, d_name[0])
1367 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1369 struct dirent *d32 = (*pglob->gl_readdir) (stream);
1372 CONVERT_DIRENT_DIRENT64 (&d64buf.d64, d32);
1379 d = __readdir64 (stream);
1381 struct dirent *d = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1382 ? ((struct dirent *)
1383 (*pglob->gl_readdir) (stream))
1384 : __readdir (stream));
1388 if (! REAL_DIR_ENTRY (d))
1391 /* If we shall match only directories use the information
1392 provided by the dirent call if possible. */
1393 if ((flags & GLOB_ONLYDIR) && !DIRENT_MIGHT_BE_DIR (d))
1398 if (fnmatch (pattern, name, fnm_flags) == 0)
1400 /* If the file we found is a symlink we have to
1401 make sure the target file exists. */
1402 if (!DIRENT_MIGHT_BE_SYMLINK (d)
1403 || link_exists_p (dfd, directory, dirlen, name, pglob,
1406 if (cur == names->count)
1408 struct globnames *newnames;
1409 size_t count = names->count * 2;
1410 size_t size = (sizeof (struct globnames)
1411 + ((count - INITIAL_COUNT)
1412 * sizeof (char *)));
1414 if (__libc_use_alloca (allocasize))
1415 newnames = names_alloca = __alloca (size);
1416 else if ((newnames = malloc (size))
1419 newnames->count = count;
1420 newnames->next = names;
1424 len = _D_EXACT_NAMLEN (d);
1425 names->name[cur] = malloc (len + 1);
1426 if (names->name[cur] == NULL)
1428 *((char *) mempcpy (names->name[cur++], name, len))
1437 if (nfound == 0 && (flags & GLOB_NOCHECK))
1439 size_t len = strlen (pattern);
1441 names->name[cur] = malloc (len + 1);
1442 if (names->name[cur] == NULL)
1444 *((char *) mempcpy (names->name[cur++], pattern, len)) = '\0';
1447 result = GLOB_NOMATCH;
1451 = realloc (pglob->gl_pathv,
1452 (pglob->gl_pathc + pglob->gl_offs + nfound + 1)
1456 if (new_gl_pathv == NULL)
1461 struct globnames *old = names;
1463 for (i = 0; i < cur; ++i)
1464 free (names->name[i]);
1465 names = names->next;
1466 /* NB: we will not leak memory here if we exit without
1467 freeing the current block assigned to OLD. At least
1468 the very first block is always allocated on the stack
1469 and this is the block assigned to OLD here. */
1472 assert (old == &init_names);
1476 if (old == names_alloca)
1477 names_alloca = names;
1481 result = GLOB_NOSPACE;
1487 struct globnames *old = names;
1489 for (i = 0; i < cur; ++i)
1490 new_gl_pathv[pglob->gl_offs + pglob->gl_pathc++]
1492 names = names->next;
1493 /* NB: we will not leak memory here if we exit without
1494 freeing the current block assigned to OLD. At least
1495 the very first block is always allocated on the stack
1496 and this is the block assigned to OLD here. */
1499 assert (old == &init_names);
1503 if (old == names_alloca)
1504 names_alloca = names;
1509 pglob->gl_pathv = new_gl_pathv;
1511 pglob->gl_pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
1513 pglob->gl_flags = flags;
1520 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1521 (*pglob->gl_closedir) (stream);