1 /* Copyright (C) 1991-2002, 2003, 2004, 2005, 2006, 2007
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 */
35 #include <stdio.h> /* Needed on stupid SunOS for assert. */
37 #if !defined _LIBC || !defined GLOB_ONLY_P
40 #if !defined POSIX && defined _POSIX_VERSION
48 # define __set_errno(val) errno = (val)
54 /* In GNU systems, <dirent.h> defines this macro for us. */
55 #ifndef _D_EXACT_NAMLEN
56 # define _D_EXACT_NAMLEN(dirent) strlen ((dirent)->d_name)
59 /* When used in the GNU libc the symbol _DIRENT_HAVE_D_TYPE is available
60 if the `d_type' member for `struct dirent' is available.
61 HAVE_STRUCT_DIRENT_D_TYPE plays the same role in GNULIB. */
62 #if defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE
63 /* True if the directory entry D must be of type T. */
64 # define DIRENT_MUST_BE(d, t) ((d)->d_type == (t))
66 /* True if the directory entry D might be a symbolic link. */
67 # define DIRENT_MIGHT_BE_SYMLINK(d) \
68 ((d)->d_type == DT_UNKNOWN || (d)->d_type == DT_LNK)
70 /* True if the directory entry D might be a directory. */
71 # define DIRENT_MIGHT_BE_DIR(d) \
72 ((d)->d_type == DT_DIR || DIRENT_MIGHT_BE_SYMLINK (d))
74 #else /* !HAVE_D_TYPE */
75 # define DIRENT_MUST_BE(d, t) false
76 # define DIRENT_MIGHT_BE_SYMLINK(d) true
77 # define DIRENT_MIGHT_BE_DIR(d) true
78 #endif /* HAVE_D_TYPE */
80 /* If the system has the `struct dirent64' type we use it internally. */
81 #if defined _LIBC && !defined COMPILE_GLOB64
82 # if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
83 # define CONVERT_D_INO(d64, d32)
85 # define CONVERT_D_INO(d64, d32) \
86 (d64)->d_ino = (d32)->d_ino;
89 # ifdef _DIRENT_HAVE_D_TYPE
90 # define CONVERT_D_TYPE(d64, d32) \
91 (d64)->d_type = (d32)->d_type;
93 # define CONVERT_D_TYPE(d64, d32)
96 # define CONVERT_DIRENT_DIRENT64(d64, d32) \
97 memcpy ((d64)->d_name, (d32)->d_name, _D_EXACT_NAMLEN (d32) + 1); \
98 CONVERT_D_INO (d64, d32) \
99 CONVERT_D_TYPE (d64, d32)
103 #if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
104 /* Posix does not require that the d_ino field be present, and some
105 systems do not provide it. */
106 # define REAL_DIR_ENTRY(dp) 1
108 # define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
114 /* NAME_MAX is usually defined in <dirent.h> or <limits.h>. */
117 # define NAME_MAX (sizeof (((struct dirent *) 0)->d_name))
124 # define strdup(str) __strdup (str)
125 # define sysconf(id) __sysconf (id)
126 # define closedir(dir) __closedir (dir)
127 # define opendir(name) __opendir (name)
128 # define readdir(str) __readdir64 (str)
129 # define getpwnam_r(name, bufp, buf, len, res) \
130 __getpwnam_r (name, bufp, buf, len, res)
132 # define __stat64(fname, buf) __xstat64 (_STAT_VER, fname, buf)
134 # define struct_stat64 struct stat64
136 # define __stat64(fname, buf) stat (fname, buf)
137 # define __fxstatat64(_, d, f, st, flag) fstatat (d, f, st, flag)
138 # define struct_stat64 struct stat
139 # define __stat(fname, buf) stat (fname, buf)
140 # define __alloca alloca
141 # define __readdir readdir
142 # define __readdir64 readdir64
143 # define __glob_pattern_p glob_pattern_p
152 #ifdef _SC_GETPW_R_SIZE_MAX
153 # define GETPW_R_SIZE_MAX() sysconf (_SC_GETPW_R_SIZE_MAX)
155 # define GETPW_R_SIZE_MAX() (-1)
157 #ifdef _SC_LOGIN_NAME_MAX
158 # define GET_LOGIN_NAME_MAX() sysconf (_SC_LOGIN_NAME_MAX)
160 # define GET_LOGIN_NAME_MAX() (-1)
163 static const char *next_brace_sub (const char *begin, int flags) __THROW;
165 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
167 #ifndef attribute_hidden
168 # define attribute_hidden
171 #ifndef __attribute_noinline__
172 # if __GNUC__ < 3 || (__GNUC__ == 3 && __GNUC_MINOR__ < 1)
173 # define __attribute_noinline__ /* Ignore */
175 # define __attribute_noinline__ __attribute__ ((__noinline__))
179 #if ! defined __builtin_expect && __GNUC__ < 3
180 # define __builtin_expect(expr, expected) (expr)
184 /* The results of opendir() in this file are not used with dirfd and fchdir,
185 therefore save some unnecessary work in fchdir.c. */
190 /* The OS usually guarantees only one guard page at the bottom of the stack,
191 and a page size can be as small as 4096 bytes. So we cannot safely
192 allocate anything larger than 4096 bytes. Also care for the possibility
193 of a few compiler-allocated temporary stack slots. */
194 # define __libc_use_alloca(n) ((n) < 4032)
196 /* alloca is implemented with malloc, so just use malloc. */
197 # define __libc_use_alloca(n) 0
201 static int glob_in_dir (const char *pattern, const char *directory,
202 int flags, int (*errfunc) (const char *, int),
204 extern int __glob_pattern_type (const char *pattern, int quote)
207 #if !defined _LIBC || !defined GLOB_ONLY_P
208 static int prefix_array (const char *prefix, char **array, size_t n) __THROW;
209 static int collated_compare (const void *, const void *) __THROW;
212 /* Find the end of the sub-pattern in a brace expression. */
214 next_brace_sub (const char *cp, int flags)
216 unsigned int depth = 0;
218 if ((flags & GLOB_NOESCAPE) == 0 && *cp == '\\')
226 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
233 return *cp != '\0' ? cp : NULL;
236 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
238 /* Do glob searching for PATTERN, placing results in PGLOB.
239 The bits defined above may be set in FLAGS.
240 If a directory cannot be opened or read and ERRFUNC is not nil,
241 it is called with the pathname that caused the error, and the
242 `errno' value from the failing call; if it returns non-zero
243 `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
244 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
245 Otherwise, `glob' returns zero. */
247 #ifdef GLOB_ATTRIBUTE
250 glob (pattern, flags, errfunc, pglob)
251 const char * restrict pattern;
253 int (*errfunc) (const char *, int);
254 glob_t * restrict pglob;
256 const char *filename;
262 int dirname_modified;
265 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
267 __set_errno (EINVAL);
271 if (!(flags & GLOB_DOOFFS))
272 /* Have to do this so `globfree' knows where to start freeing. It
273 also makes all the code that uses gl_offs simpler. */
276 if (flags & GLOB_BRACE)
280 if (flags & GLOB_NOESCAPE)
281 begin = strchr (pattern, '{');
293 if (*begin == '\\' && begin[1] != '\0')
295 else if (*begin == '{')
304 /* Allocate working buffer large enough for our work. Note that
305 we have at least an opening and closing brace. */
313 char onealt[strlen (pattern) - 1];
315 char *onealt = malloc (strlen (pattern) - 1);
318 if (!(flags & GLOB_APPEND))
321 pglob->gl_pathv = NULL;
327 /* We know the prefix for all sub-patterns. */
328 alt_start = mempcpy (onealt, pattern, begin - pattern);
330 /* Find the first sub-pattern and at the same time find the
331 rest after the closing brace. */
332 next = next_brace_sub (begin + 1, flags);
335 /* It is an invalid expression. */
339 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
342 /* Now find the end of the whole brace expression. */
346 rest = next_brace_sub (rest + 1, flags);
349 /* It is an invalid expression. */
353 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
356 /* Please note that we now can be sure the brace expression
358 rest_len = strlen (++rest) + 1;
360 /* We have a brace expression. BEGIN points to the opening {,
361 NEXT points past the terminator of the first element, and END
362 points past the final }. We will accumulate result names from
363 recursive runs for each brace alternative in the buffer using
366 if (!(flags & GLOB_APPEND))
368 /* This call is to set a new vector, so clear out the
369 vector so we can append to it. */
371 pglob->gl_pathv = NULL;
373 firstc = pglob->gl_pathc;
380 /* Construct the new glob expression. */
381 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
383 result = glob (onealt,
384 ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))
385 | GLOB_APPEND), errfunc, pglob);
387 /* If we got an error, return it. */
388 if (result && result != GLOB_NOMATCH)
393 if (!(flags & GLOB_APPEND))
402 /* We saw the last entry. */
406 next = next_brace_sub (p, flags);
407 assert (next != NULL);
414 if (pglob->gl_pathc != firstc)
415 /* We found some entries. */
417 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
422 /* Find the filename. */
423 filename = strrchr (pattern, '/');
424 #if defined __MSDOS__ || defined WINDOWS32
425 /* The case of "d:pattern". Since `:' is not allowed in
426 file names, we can safely assume that wherever it
427 happens in pattern, it signals the filename part. This
428 is so we could some day support patterns like "[a-z]:foo". */
429 if (filename == NULL)
430 filename = strchr (pattern, ':');
431 #endif /* __MSDOS__ || WINDOWS32 */
432 dirname_modified = 0;
433 if (filename == NULL)
435 /* This can mean two things: a simple name or "~name". The latter
436 case is nothing but a notation for a directory. */
437 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
440 dirlen = strlen (pattern);
442 /* Set FILENAME to NULL as a special flag. This is ugly but
443 other solutions would require much more code. We test for
444 this special case below. */
458 else if (filename == pattern
459 || (filename == pattern + 1 && pattern[0] == '\\'
460 && (flags & GLOB_NOESCAPE) == 0))
462 /* "/pattern" or "\\/pattern". */
470 dirlen = filename - pattern;
471 #if defined __MSDOS__ || defined WINDOWS32
473 || (filename > pattern + 1 && filename[-1] == ':'))
478 drive_spec = __alloca (dirlen + 1);
479 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
480 /* For now, disallow wildcards in the drive spec, to
481 prevent infinite recursion in glob. */
482 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
484 /* If this is "d:pattern", we need to copy `:' to DIRNAME
485 as well. If it's "d:/pattern", don't remove the slash
486 from "d:/", since "d:" and "d:/" are not the same.*/
489 newp = __alloca (dirlen + 1);
490 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
494 if (filename[0] == '\0'
495 #if defined __MSDOS__ || defined WINDOWS32
496 && dirname[dirlen - 1] != ':'
497 && (dirlen < 3 || dirname[dirlen - 2] != ':'
498 || dirname[dirlen - 1] != '/')
501 /* "pattern/". Expand "pattern", appending slashes. */
503 int orig_flags = flags;
505 if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\')
507 /* "pattern\\/". Remove the final backslash if it hasn't
509 char *p = (char *) &dirname[dirlen - 1];
511 while (p > dirname && p[-1] == '\\') --p;
512 if ((&dirname[dirlen] - p) & 1)
514 *(char *) &dirname[--dirlen] = '\0';
515 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
518 val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
520 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
521 | (flags & GLOB_MARK));
522 else if (val == GLOB_NOMATCH && flags != orig_flags)
524 /* Make sure globfree (&dirs); is a nop. */
525 dirs.gl_pathv = NULL;
527 oldcount = pglob->gl_pathc + pglob->gl_offs;
534 if (!(flags & GLOB_APPEND))
537 if (!(flags & GLOB_DOOFFS))
538 pglob->gl_pathv = NULL;
542 pglob->gl_pathv = malloc ((pglob->gl_offs + 1) * sizeof (char *));
543 if (pglob->gl_pathv == NULL)
546 for (i = 0; i <= pglob->gl_offs; ++i)
547 pglob->gl_pathv[i] = NULL;
551 oldcount = pglob->gl_pathc + pglob->gl_offs;
553 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
555 if (dirname[1] == '\0' || dirname[1] == '/'
556 || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\'
557 && (dirname[2] == '\0' || dirname[2] == '/')))
559 /* Look up home directory. */
560 const char *home_dir = getenv ("HOME");
562 if (home_dir == NULL || home_dir[0] == '\0')
566 if (home_dir == NULL || home_dir[0] == '\0')
567 home_dir = "c:/users/default"; /* poor default */
569 if (home_dir == NULL || home_dir[0] == '\0')
573 size_t buflen = GET_LOGIN_NAME_MAX () + 1;
576 /* `sysconf' does not support _SC_LOGIN_NAME_MAX. Try
579 name = __alloca (buflen);
581 success = getlogin_r (name, buflen) == 0;
585 # if defined HAVE_GETPWNAM_R || defined _LIBC
586 long int pwbuflen = GETPW_R_SIZE_MAX ();
593 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.
594 Try a moderate value. */
597 pwtmpbuf = __alloca (pwbuflen);
599 while (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
608 pwtmpbuf = extend_alloca (pwtmpbuf, pwbuflen,
612 pwtmpbuf = __alloca (pwbuflen);
620 home_dir = p->pw_dir;
623 if (home_dir == NULL || home_dir[0] == '\0')
625 if (flags & GLOB_TILDE_CHECK)
628 home_dir = "~"; /* No luck. */
630 # endif /* WINDOWS32 */
632 /* Now construct the full directory. */
633 if (dirname[1] == '\0')
636 dirlen = strlen (dirname);
641 size_t home_len = strlen (home_dir);
642 newp = __alloca (home_len + dirlen);
643 mempcpy (mempcpy (newp, home_dir, home_len),
644 &dirname[1], dirlen);
646 dirlen += home_len - 1;
648 dirname_modified = 1;
650 # if !defined _AMIGA && !defined WINDOWS32
653 char *end_name = strchr (dirname, '/');
654 const char *user_name;
655 const char *home_dir;
656 char *unescape = NULL;
658 if (!(flags & GLOB_NOESCAPE))
660 if (end_name == NULL)
662 unescape = strchr (dirname, '\\');
664 end_name = strchr (unescape, '\0');
667 unescape = memchr (dirname, '\\', end_name - dirname);
669 if (end_name == NULL)
670 user_name = dirname + 1;
674 newp = __alloca (end_name - dirname);
675 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
677 if (unescape != NULL)
679 char *p = mempcpy (newp, dirname + 1,
680 unescape - dirname - 1);
688 /* "~fo\\o\\" unescape to user_name "foo\\",
689 but "~fo\\o\\/" unescape to user_name
691 if (filename == NULL)
702 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
707 /* Look up specific user's home directory. */
710 # if defined HAVE_GETPWNAM_R || defined _LIBC
711 long int buflen = GETPW_R_SIZE_MAX ();
718 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
722 pwtmpbuf = __alloca (buflen);
724 while (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) != 0)
732 pwtmpbuf = extend_alloca (pwtmpbuf, buflen, 2 * buflen);
735 pwtmpbuf = __alloca (buflen);
740 p = getpwnam (user_name);
743 home_dir = p->pw_dir;
747 /* If we found a home directory use this. */
748 if (home_dir != NULL)
751 size_t home_len = strlen (home_dir);
752 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
753 newp = __alloca (home_len + rest_len + 1);
754 *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
755 end_name, rest_len)) = '\0';
757 dirlen = home_len + rest_len;
758 dirname_modified = 1;
761 if (flags & GLOB_TILDE_CHECK)
762 /* We have to regard it as an error if we cannot find the
766 # endif /* Not Amiga && not WINDOWS32. */
769 /* Now test whether we looked for "~" or "~NAME". In this case we
770 can give the answer now. */
771 if (filename == NULL)
776 /* Return the directory if we don't check for error or if it exists. */
777 if ((flags & GLOB_NOCHECK)
778 || (((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
779 ? ((*pglob->gl_stat) (dirname, &st) == 0
780 && S_ISDIR (st.st_mode))
781 : (__stat64 (dirname, &st64) == 0 && S_ISDIR (st64.st_mode)))))
783 int newcount = pglob->gl_pathc + pglob->gl_offs;
787 = realloc (pglob->gl_pathv, (newcount + 1 + 1) * sizeof (char *));
788 if (new_gl_pathv == NULL)
791 free (pglob->gl_pathv);
792 pglob->gl_pathv = NULL;
796 pglob->gl_pathv = new_gl_pathv;
798 if (flags & GLOB_MARK)
801 pglob->gl_pathv[newcount] = malloc (dirlen + 2);
802 if (pglob->gl_pathv[newcount] == NULL)
804 p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);
810 pglob->gl_pathv[newcount] = strdup (dirname);
811 if (pglob->gl_pathv[newcount] == NULL)
814 pglob->gl_pathv[++newcount] = NULL;
816 pglob->gl_flags = flags;
825 meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));
826 /* meta is 1 if correct glob pattern containing metacharacters.
827 If meta has bit (1 << 2) set, it means there was an unterminated
828 [ which we handle the same, using fnmatch. Broken unterminated
829 pattern bracket expressions ought to be rare enough that it is
830 not worth special casing them, fnmatch will do the right thing. */
833 /* The directory name contains metacharacters, so we
834 have to glob for the directory, and then glob for
835 the pattern in each directory found. */
838 if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\')
840 /* "foo\\/bar". Remove the final backslash from dirname
841 if it has not been quoted. */
842 char *p = (char *) &dirname[dirlen - 1];
844 while (p > dirname && p[-1] == '\\') --p;
845 if ((&dirname[dirlen] - p) & 1)
846 *(char *) &dirname[--dirlen] = '\0';
849 if (__builtin_expect ((flags & GLOB_ALTDIRFUNC) != 0, 0))
851 /* Use the alternative access functions also in the recursive
853 dirs.gl_opendir = pglob->gl_opendir;
854 dirs.gl_readdir = pglob->gl_readdir;
855 dirs.gl_closedir = pglob->gl_closedir;
856 dirs.gl_stat = pglob->gl_stat;
857 dirs.gl_lstat = pglob->gl_lstat;
860 status = glob (dirname,
861 ((flags & (GLOB_ERR | GLOB_NOESCAPE
863 | GLOB_NOSORT | GLOB_ONLYDIR),
867 if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH)
872 /* We have successfully globbed the preceding directory name.
873 For each name we found, call glob_in_dir on it and FILENAME,
874 appending the results to PGLOB. */
875 for (i = 0; i < dirs.gl_pathc; ++i)
881 /* Make globbing interruptible in the bash shell. */
882 extern int interrupt_state;
892 old_pathc = pglob->gl_pathc;
893 status = glob_in_dir (filename, dirs.gl_pathv[i],
894 ((flags | GLOB_APPEND)
895 & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),
897 if (status == GLOB_NOMATCH)
898 /* No matches in this directory. Try the next. */
909 /* Stick the directory on the front of each name. */
910 if (prefix_array (dirs.gl_pathv[i],
911 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
912 pglob->gl_pathc - old_pathc))
921 flags |= GLOB_MAGCHAR;
923 /* We have ignored the GLOB_NOCHECK flag in the `glob_in_dir' calls.
924 But if we have not found any matching entry and the GLOB_NOCHECK
925 flag was set we must return the input pattern itself. */
926 if (pglob->gl_pathc + pglob->gl_offs == oldcount)
930 if (flags & GLOB_NOCHECK)
932 int newcount = pglob->gl_pathc + pglob->gl_offs;
935 new_gl_pathv = realloc (pglob->gl_pathv,
936 (newcount + 2) * sizeof (char *));
937 if (new_gl_pathv == NULL)
942 pglob->gl_pathv = new_gl_pathv;
944 pglob->gl_pathv[newcount] = strdup (pattern);
945 if (pglob->gl_pathv[newcount] == NULL)
956 pglob->gl_pathv[newcount] = NULL;
957 pglob->gl_flags = flags;
970 int old_pathc = pglob->gl_pathc;
971 int orig_flags = flags;
975 char *p = strchr (dirname, '\\'), *q;
976 /* We need to unescape the dirname string. It is certainly
977 allocated by alloca, as otherwise filename would be NULL
978 or dirname wouldn't contain backslashes. */
991 while (*p++ != '\0');
992 dirname_modified = 1;
994 if (dirname_modified)
995 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
996 status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
999 if (status == GLOB_NOMATCH && flags != orig_flags
1000 && pglob->gl_pathc + pglob->gl_offs == oldcount)
1002 /* Make sure globfree (&dirs); is a nop. */
1003 dirs.gl_pathv = NULL;
1012 /* Stick the directory on the front of each name. */
1013 if (prefix_array (dirname,
1014 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
1015 pglob->gl_pathc - old_pathc))
1018 pglob->gl_pathc = 0;
1019 return GLOB_NOSPACE;
1024 if (flags & GLOB_MARK)
1026 /* Append slashes to directory names. */
1031 for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)
1032 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1033 ? ((*pglob->gl_stat) (pglob->gl_pathv[i], &st) == 0
1034 && S_ISDIR (st.st_mode))
1035 : (__stat64 (pglob->gl_pathv[i], &st64) == 0
1036 && S_ISDIR (st64.st_mode))))
1038 size_t len = strlen (pglob->gl_pathv[i]) + 2;
1039 char *new = realloc (pglob->gl_pathv[i], len);
1043 pglob->gl_pathc = 0;
1044 return GLOB_NOSPACE;
1046 strcpy (&new[len - 2], "/");
1047 pglob->gl_pathv[i] = new;
1051 if (!(flags & GLOB_NOSORT))
1053 /* Sort the vector. */
1054 qsort (&pglob->gl_pathv[oldcount],
1055 pglob->gl_pathc + pglob->gl_offs - oldcount,
1056 sizeof (char *), collated_compare);
1061 #if defined _LIBC && !defined glob
1062 libc_hidden_def (glob)
1066 #if !defined _LIBC || !defined GLOB_ONLY_P
1068 /* Free storage allocated in PGLOB by a previous `glob' call. */
1071 register glob_t *pglob;
1073 if (pglob->gl_pathv != NULL)
1076 for (i = 0; i < pglob->gl_pathc; ++i)
1077 if (pglob->gl_pathv[pglob->gl_offs + i] != NULL)
1078 free (pglob->gl_pathv[pglob->gl_offs + i]);
1079 free (pglob->gl_pathv);
1080 pglob->gl_pathv = NULL;
1083 #if defined _LIBC && !defined globfree
1084 libc_hidden_def (globfree)
1088 /* Do a collated comparison of A and B. */
1090 collated_compare (const void *a, const void *b)
1092 char *const *ps1 = a; char *s1 = *ps1;
1093 char *const *ps2 = b; char *s2 = *ps2;
1101 return strcoll (s1, s2);
1105 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1106 elements in place. Return nonzero if out of memory, zero if successful.
1107 A slash is inserted between DIRNAME and each elt of ARRAY,
1108 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1110 prefix_array (const char *dirname, char **array, size_t n)
1113 size_t dirlen = strlen (dirname);
1114 #if defined __MSDOS__ || defined WINDOWS32
1116 # define DIRSEP_CHAR sep_char
1118 # define DIRSEP_CHAR '/'
1121 if (dirlen == 1 && dirname[0] == '/')
1122 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1123 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1125 #if defined __MSDOS__ || defined WINDOWS32
1126 else if (dirlen > 1)
1128 if (dirname[dirlen - 1] == '/' && dirname[dirlen - 2] == ':')
1129 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1131 else if (dirname[dirlen - 1] == ':')
1133 /* DIRNAME is "d:". Use `:' instead of `/'. */
1140 for (i = 0; i < n; ++i)
1142 size_t eltlen = strlen (array[i]) + 1;
1143 char *new = malloc (dirlen + 1 + eltlen);
1152 char *endp = mempcpy (new, dirname, dirlen);
1153 *endp++ = DIRSEP_CHAR;
1154 mempcpy (endp, array[i], eltlen);
1164 /* We must not compile this function twice. */
1165 #if !defined _LIBC || !defined NO_GLOB_PATTERN_P
1167 __glob_pattern_type (pattern, quote)
1168 const char *pattern;
1171 register const char *p;
1174 for (p = pattern; *p != '\0'; ++p)
1203 /* Return nonzero if PATTERN contains any metacharacters.
1204 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
1206 __glob_pattern_p (pattern, quote)
1207 const char *pattern;
1210 return __glob_pattern_type (pattern, quote) == 1;
1213 weak_alias (__glob_pattern_p, glob_pattern_p)
1217 #endif /* !GLOB_ONLY_P */
1220 #if !defined _LIBC || !defined GLOB_ONLY_P
1221 /* We put this in a separate function mainly to allow the memory
1222 allocated with alloca to be recycled. */
1224 __attribute_noinline__
1225 link_exists2_p (const char *dir, size_t dirlen, const char *fname,
1227 # if !defined _LIBC && !HAVE_FSTATAT
1232 size_t fnamelen = strlen (fname);
1233 char *fullname = __alloca (dirlen + 1 + fnamelen + 1);
1236 mempcpy (mempcpy (mempcpy (fullname, dir, dirlen), "/", 1),
1237 fname, fnamelen + 1);
1239 # if !defined _LIBC && !HAVE_FSTATAT
1240 if (__builtin_expect ((flags & GLOB_ALTDIRFUNC) == 0, 1))
1243 return __stat64 (fullname, &st64) == 0;
1246 return (*pglob->gl_stat) (fullname, &st) == 0;
1249 /* Return true if DIR/FNAME exists. */
1251 link_exists_p (int dfd, const char *dir, size_t dirlen, const char *fname,
1252 glob_t *pglob, int flags)
1254 # if defined _LIBC || HAVE_FSTATAT
1255 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1256 return link_exists2_p (dir, dirlen, fname, pglob);
1260 return __fxstatat64 (_STAT_VER, dfd, fname, &st64, 0) == 0;
1263 return link_exists2_p (dir, dirlen, fname, pglob, flags);
1269 /* Like `glob', but PATTERN is a final pathname component,
1270 and matches are searched for in DIRECTORY.
1271 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1272 The GLOB_APPEND flag is assumed to be set (always appends). */
1274 glob_in_dir (const char *pattern, const char *directory, int flags,
1275 int (*errfunc) (const char *, int),
1278 size_t dirlen = strlen (directory);
1279 void *stream = NULL;
1282 struct globnames *next;
1286 #define INITIAL_COUNT sizeof (init_names.name) / sizeof (init_names.name[0])
1287 struct globnames init_names;
1288 struct globnames *names = &init_names;
1289 struct globnames *names_alloca = &init_names;
1291 size_t allocasize = sizeof (init_names);
1297 init_names.next = NULL;
1298 init_names.count = INITIAL_COUNT;
1300 meta = __glob_pattern_type (pattern, !(flags & GLOB_NOESCAPE));
1301 if (meta == 0 && (flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
1303 /* We need not do any tests. The PATTERN contains no meta
1304 characters and we must not return an error therefore the
1305 result will always contain exactly one name. */
1306 flags |= GLOB_NOCHECK;
1310 /* Since we use the normal file functions we can also use stat()
1311 to verify the file is there. */
1314 size_t patlen = strlen (pattern);
1315 char *fullname = __alloca (dirlen + 1 + patlen + 1);
1317 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1319 pattern, patlen + 1);
1320 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1321 ? (*pglob->gl_stat) (fullname, &st)
1322 : __stat64 (fullname, &st64)) == 0)
1323 /* We found this file to be existing. Now tell the rest
1324 of the function to copy this name into the result. */
1325 flags |= GLOB_NOCHECK;
1329 stream = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1330 ? (*pglob->gl_opendir) (directory)
1331 : opendir (directory));
1334 if (errno != ENOTDIR
1335 && ((errfunc != NULL && (*errfunc) (directory, errno))
1336 || (flags & GLOB_ERR)))
1337 return GLOB_ABORTED;
1341 int dfd = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1342 ? -1 : dirfd ((DIR *) stream));
1343 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1344 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1345 #if defined _AMIGA || defined VMS
1349 flags |= GLOB_MAGCHAR;
1355 #if defined _LIBC && !defined COMPILE_GLOB64
1359 struct dirent64 d64;
1360 char room [offsetof (struct dirent64, d_name[0])
1365 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1367 struct dirent *d32 = (*pglob->gl_readdir) (stream);
1370 CONVERT_DIRENT_DIRENT64 (&d64buf.d64, d32);
1377 d = __readdir64 (stream);
1379 struct dirent *d = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1380 ? ((struct dirent *)
1381 (*pglob->gl_readdir) (stream))
1382 : __readdir (stream));
1386 if (! REAL_DIR_ENTRY (d))
1389 /* If we shall match only directories use the information
1390 provided by the dirent call if possible. */
1391 if ((flags & GLOB_ONLYDIR) && !DIRENT_MIGHT_BE_DIR (d))
1396 if (fnmatch (pattern, name, fnm_flags) == 0)
1398 /* If the file we found is a symlink we have to
1399 make sure the target file exists. */
1400 if (!DIRENT_MIGHT_BE_SYMLINK (d)
1401 || link_exists_p (dfd, directory, dirlen, name, pglob,
1404 if (cur == names->count)
1406 struct globnames *newnames;
1407 size_t count = names->count * 2;
1408 size_t size = (sizeof (struct globnames)
1409 + ((count - INITIAL_COUNT)
1410 * sizeof (char *)));
1412 if (__libc_use_alloca (allocasize))
1413 newnames = names_alloca = __alloca (size);
1414 else if ((newnames = malloc (size))
1417 newnames->count = count;
1418 newnames->next = names;
1422 len = _D_EXACT_NAMLEN (d);
1423 names->name[cur] = malloc (len + 1);
1424 if (names->name[cur] == NULL)
1426 *((char *) mempcpy (names->name[cur++], name, len))
1435 if (nfound == 0 && (flags & GLOB_NOCHECK))
1437 size_t len = strlen (pattern);
1439 names->name[cur] = malloc (len + 1);
1440 if (names->name[cur] == NULL)
1442 *((char *) mempcpy (names->name[cur++], pattern, len)) = '\0';
1445 result = GLOB_NOMATCH;
1449 = realloc (pglob->gl_pathv,
1450 (pglob->gl_pathc + pglob->gl_offs + nfound + 1)
1454 if (new_gl_pathv == NULL)
1459 struct globnames *old = names;
1461 for (i = 0; i < cur; ++i)
1462 free (names->name[i]);
1463 names = names->next;
1464 /* NB: we will not leak memory here if we exit without
1465 freeing the current block assigned to OLD. At least
1466 the very first block is always allocated on the stack
1467 and this is the block assigned to OLD here. */
1470 assert (old == &init_names);
1474 if (old == names_alloca)
1475 names_alloca = names;
1479 result = GLOB_NOSPACE;
1485 struct globnames *old = names;
1487 for (i = 0; i < cur; ++i)
1488 new_gl_pathv[pglob->gl_offs + pglob->gl_pathc++]
1490 names = names->next;
1491 /* NB: we will not leak memory here if we exit without
1492 freeing the current block assigned to OLD. At least
1493 the very first block is always allocated on the stack
1494 and this is the block assigned to OLD here. */
1497 assert (old == &init_names);
1501 if (old == names_alloca)
1502 names_alloca = names;
1507 pglob->gl_pathv = new_gl_pathv;
1509 pglob->gl_pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
1511 pglob->gl_flags = flags;
1518 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1519 (*pglob->gl_closedir) (stream);