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 struct_stat64 struct stat
138 # define __stat(fname, buf) stat (fname, buf)
139 # define __alloca alloca
140 # define __readdir readdir
141 # define __readdir64 readdir64
142 # define __glob_pattern_p glob_pattern_p
148 #ifdef _SC_GETPW_R_SIZE_MAX
149 # define GETPW_R_SIZE_MAX() sysconf (_SC_GETPW_R_SIZE_MAX)
151 # define GETPW_R_SIZE_MAX() (-1)
153 #ifdef _SC_LOGIN_NAME_MAX
154 # define GET_LOGIN_NAME_MAX() sysconf (_SC_LOGIN_NAME_MAX)
156 # define GET_LOGIN_NAME_MAX() (-1)
159 static const char *next_brace_sub (const char *begin, int flags) __THROW;
161 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
163 #ifndef attribute_hidden
164 # define attribute_hidden
167 #ifndef __attribute_noinline__
168 # if __GNUC__ < 3 || (__GNUC__ == 3 && __GNUC_MINOR__ < 1)
169 # define __attribute_noinline__ /* Ignore */
171 # define __attribute_noinline__ __attribute__ ((__noinline__))
175 #if ! defined __builtin_expect && __GNUC__ < 3
176 # define __builtin_expect(expr, expected) (expr)
180 /* The results of opendir() in this file are not used with dirfd and fchdir,
181 therefore save some unnecessary work in fchdir.c. */
186 /* The OS usually guarantees only one guard page at the bottom of the stack,
187 and a page size can be as small as 4096 bytes. So we cannot safely
188 allocate anything larger than 4096 bytes. Also care for the possibility
189 of a few compiler-allocated temporary stack slots. */
190 # define __libc_use_alloca(n) ((n) < 4032)
192 /* alloca is implemented with malloc, so just use malloc. */
193 # define __libc_use_alloca(n) 0
197 static int glob_in_dir (const char *pattern, const char *directory,
198 int flags, int (*errfunc) (const char *, int),
200 extern int __glob_pattern_type (const char *pattern, int quote)
203 #if !defined _LIBC || !defined GLOB_ONLY_P
204 static int prefix_array (const char *prefix, char **array, size_t n) __THROW;
205 static int collated_compare (const void *, const void *) __THROW;
208 /* Find the end of the sub-pattern in a brace expression. */
210 next_brace_sub (const char *cp, int flags)
212 unsigned int depth = 0;
214 if ((flags & GLOB_NOESCAPE) == 0 && *cp == '\\')
222 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
229 return *cp != '\0' ? cp : NULL;
232 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
234 /* Do glob searching for PATTERN, placing results in PGLOB.
235 The bits defined above may be set in FLAGS.
236 If a directory cannot be opened or read and ERRFUNC is not nil,
237 it is called with the pathname that caused the error, and the
238 `errno' value from the failing call; if it returns non-zero
239 `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
240 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
241 Otherwise, `glob' returns zero. */
243 #ifdef GLOB_ATTRIBUTE
246 glob (pattern, flags, errfunc, pglob)
247 const char * restrict pattern;
249 int (*errfunc) (const char *, int);
250 glob_t * restrict pglob;
252 const char *filename;
258 int dirname_modified;
261 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
263 __set_errno (EINVAL);
267 if (!(flags & GLOB_DOOFFS))
268 /* Have to do this so `globfree' knows where to start freeing. It
269 also makes all the code that uses gl_offs simpler. */
272 if (flags & GLOB_BRACE)
276 if (flags & GLOB_NOESCAPE)
277 begin = strchr (pattern, '{');
289 if (*begin == '\\' && begin[1] != '\0')
291 else if (*begin == '{')
300 /* Allocate working buffer large enough for our work. Note that
301 we have at least an opening and closing brace. */
309 char onealt[strlen (pattern) - 1];
311 char *onealt = malloc (strlen (pattern) - 1);
314 if (!(flags & GLOB_APPEND))
317 pglob->gl_pathv = NULL;
323 /* We know the prefix for all sub-patterns. */
324 alt_start = mempcpy (onealt, pattern, begin - pattern);
326 /* Find the first sub-pattern and at the same time find the
327 rest after the closing brace. */
328 next = next_brace_sub (begin + 1, flags);
331 /* It is an invalid expression. */
335 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
338 /* Now find the end of the whole brace expression. */
342 rest = next_brace_sub (rest + 1, flags);
345 /* It is an invalid expression. */
349 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
352 /* Please note that we now can be sure the brace expression
354 rest_len = strlen (++rest) + 1;
356 /* We have a brace expression. BEGIN points to the opening {,
357 NEXT points past the terminator of the first element, and END
358 points past the final }. We will accumulate result names from
359 recursive runs for each brace alternative in the buffer using
362 if (!(flags & GLOB_APPEND))
364 /* This call is to set a new vector, so clear out the
365 vector so we can append to it. */
367 pglob->gl_pathv = NULL;
369 firstc = pglob->gl_pathc;
376 /* Construct the new glob expression. */
377 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
379 result = glob (onealt,
380 ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))
381 | GLOB_APPEND), errfunc, pglob);
383 /* If we got an error, return it. */
384 if (result && result != GLOB_NOMATCH)
389 if (!(flags & GLOB_APPEND))
398 /* We saw the last entry. */
402 next = next_brace_sub (p, flags);
403 assert (next != NULL);
410 if (pglob->gl_pathc != firstc)
411 /* We found some entries. */
413 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
418 /* Find the filename. */
419 filename = strrchr (pattern, '/');
420 #if defined __MSDOS__ || defined WINDOWS32
421 /* The case of "d:pattern". Since `:' is not allowed in
422 file names, we can safely assume that wherever it
423 happens in pattern, it signals the filename part. This
424 is so we could some day support patterns like "[a-z]:foo". */
425 if (filename == NULL)
426 filename = strchr (pattern, ':');
427 #endif /* __MSDOS__ || WINDOWS32 */
428 dirname_modified = 0;
429 if (filename == NULL)
431 /* This can mean two things: a simple name or "~name". The latter
432 case is nothing but a notation for a directory. */
433 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
436 dirlen = strlen (pattern);
438 /* Set FILENAME to NULL as a special flag. This is ugly but
439 other solutions would require much more code. We test for
440 this special case below. */
454 else if (filename == pattern
455 || (filename == pattern + 1 && pattern[0] == '\\'
456 && (flags & GLOB_NOESCAPE) == 0))
458 /* "/pattern" or "\\/pattern". */
466 dirlen = filename - pattern;
467 #if defined __MSDOS__ || defined WINDOWS32
469 || (filename > pattern + 1 && filename[-1] == ':'))
474 drive_spec = __alloca (dirlen + 1);
475 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
476 /* For now, disallow wildcards in the drive spec, to
477 prevent infinite recursion in glob. */
478 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
480 /* If this is "d:pattern", we need to copy `:' to DIRNAME
481 as well. If it's "d:/pattern", don't remove the slash
482 from "d:/", since "d:" and "d:/" are not the same.*/
485 newp = __alloca (dirlen + 1);
486 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
490 if (filename[0] == '\0'
491 #if defined __MSDOS__ || defined WINDOWS32
492 && dirname[dirlen - 1] != ':'
493 && (dirlen < 3 || dirname[dirlen - 2] != ':'
494 || dirname[dirlen - 1] != '/')
497 /* "pattern/". Expand "pattern", appending slashes. */
499 int orig_flags = flags;
501 if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\')
503 /* "pattern\\/". Remove the final backslash if it hasn't
505 char *p = (char *) &dirname[dirlen - 1];
507 while (p > dirname && p[-1] == '\\') --p;
508 if ((&dirname[dirlen] - p) & 1)
510 *(char *) &dirname[--dirlen] = '\0';
511 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
514 val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
516 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
517 | (flags & GLOB_MARK));
518 else if (val == GLOB_NOMATCH && flags != orig_flags)
520 /* Make sure globfree (&dirs); is a nop. */
521 dirs.gl_pathv = NULL;
523 oldcount = pglob->gl_pathc + pglob->gl_offs;
530 if (!(flags & GLOB_APPEND))
533 if (!(flags & GLOB_DOOFFS))
534 pglob->gl_pathv = NULL;
538 pglob->gl_pathv = malloc ((pglob->gl_offs + 1) * sizeof (char *));
539 if (pglob->gl_pathv == NULL)
542 for (i = 0; i <= pglob->gl_offs; ++i)
543 pglob->gl_pathv[i] = NULL;
547 oldcount = pglob->gl_pathc + pglob->gl_offs;
549 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
551 if (dirname[1] == '\0' || dirname[1] == '/'
552 || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\'
553 && (dirname[2] == '\0' || dirname[2] == '/')))
555 /* Look up home directory. */
556 const char *home_dir = getenv ("HOME");
558 if (home_dir == NULL || home_dir[0] == '\0')
562 if (home_dir == NULL || home_dir[0] == '\0')
563 home_dir = "c:/users/default"; /* poor default */
565 if (home_dir == NULL || home_dir[0] == '\0')
569 size_t buflen = GET_LOGIN_NAME_MAX () + 1;
572 /* `sysconf' does not support _SC_LOGIN_NAME_MAX. Try
575 name = __alloca (buflen);
577 success = getlogin_r (name, buflen) == 0;
581 # if defined HAVE_GETPWNAM_R || defined _LIBC
582 long int pwbuflen = GETPW_R_SIZE_MAX ();
589 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.
590 Try a moderate value. */
593 pwtmpbuf = __alloca (pwbuflen);
595 while (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
604 pwtmpbuf = extend_alloca (pwtmpbuf, pwbuflen,
608 pwtmpbuf = __alloca (pwbuflen);
616 home_dir = p->pw_dir;
619 if (home_dir == NULL || home_dir[0] == '\0')
621 if (flags & GLOB_TILDE_CHECK)
624 home_dir = "~"; /* No luck. */
626 # endif /* WINDOWS32 */
628 /* Now construct the full directory. */
629 if (dirname[1] == '\0')
632 dirlen = strlen (dirname);
637 size_t home_len = strlen (home_dir);
638 newp = __alloca (home_len + dirlen);
639 mempcpy (mempcpy (newp, home_dir, home_len),
640 &dirname[1], dirlen);
642 dirlen += home_len - 1;
644 dirname_modified = 1;
646 # if !defined _AMIGA && !defined WINDOWS32
649 char *end_name = strchr (dirname, '/');
650 const char *user_name;
651 const char *home_dir;
652 char *unescape = NULL;
654 if (!(flags & GLOB_NOESCAPE))
656 if (end_name == NULL)
658 unescape = strchr (dirname, '\\');
660 end_name = strchr (unescape, '\0');
663 unescape = memchr (dirname, '\\', end_name - dirname);
665 if (end_name == NULL)
666 user_name = dirname + 1;
670 newp = __alloca (end_name - dirname);
671 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
673 if (unescape != NULL)
675 char *p = mempcpy (newp, dirname + 1,
676 unescape - dirname - 1);
684 /* "~fo\\o\\" unescape to user_name "foo\\",
685 but "~fo\\o\\/" unescape to user_name
687 if (filename == NULL)
698 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
703 /* Look up specific user's home directory. */
706 # if defined HAVE_GETPWNAM_R || defined _LIBC
707 long int buflen = GETPW_R_SIZE_MAX ();
714 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
718 pwtmpbuf = __alloca (buflen);
720 while (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) != 0)
728 pwtmpbuf = extend_alloca (pwtmpbuf, buflen, 2 * buflen);
731 pwtmpbuf = __alloca (buflen);
736 p = getpwnam (user_name);
739 home_dir = p->pw_dir;
743 /* If we found a home directory use this. */
744 if (home_dir != NULL)
747 size_t home_len = strlen (home_dir);
748 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
749 newp = __alloca (home_len + rest_len + 1);
750 *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
751 end_name, rest_len)) = '\0';
753 dirlen = home_len + rest_len;
754 dirname_modified = 1;
757 if (flags & GLOB_TILDE_CHECK)
758 /* We have to regard it as an error if we cannot find the
762 # endif /* Not Amiga && not WINDOWS32. */
765 /* Now test whether we looked for "~" or "~NAME". In this case we
766 can give the answer now. */
767 if (filename == NULL)
772 /* Return the directory if we don't check for error or if it exists. */
773 if ((flags & GLOB_NOCHECK)
774 || (((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
775 ? ((*pglob->gl_stat) (dirname, &st) == 0
776 && S_ISDIR (st.st_mode))
777 : (__stat64 (dirname, &st64) == 0 && S_ISDIR (st64.st_mode)))))
779 int newcount = pglob->gl_pathc + pglob->gl_offs;
783 = realloc (pglob->gl_pathv, (newcount + 1 + 1) * sizeof (char *));
784 if (new_gl_pathv == NULL)
787 free (pglob->gl_pathv);
788 pglob->gl_pathv = NULL;
792 pglob->gl_pathv = new_gl_pathv;
794 if (flags & GLOB_MARK)
797 pglob->gl_pathv[newcount] = malloc (dirlen + 2);
798 if (pglob->gl_pathv[newcount] == NULL)
800 p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);
806 pglob->gl_pathv[newcount] = strdup (dirname);
807 if (pglob->gl_pathv[newcount] == NULL)
810 pglob->gl_pathv[++newcount] = NULL;
812 pglob->gl_flags = flags;
821 meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));
822 /* meta is 1 if correct glob pattern containing metacharacters.
823 If meta has bit (1 << 2) set, it means there was an unterminated
824 [ which we handle the same, using fnmatch. Broken unterminated
825 pattern bracket expressions ought to be rare enough that it is
826 not worth special casing them, fnmatch will do the right thing. */
829 /* The directory name contains metacharacters, so we
830 have to glob for the directory, and then glob for
831 the pattern in each directory found. */
834 if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\')
836 /* "foo\\/bar". Remove the final backslash from dirname
837 if it has not been quoted. */
838 char *p = (char *) &dirname[dirlen - 1];
840 while (p > dirname && p[-1] == '\\') --p;
841 if ((&dirname[dirlen] - p) & 1)
842 *(char *) &dirname[--dirlen] = '\0';
845 if (__builtin_expect ((flags & GLOB_ALTDIRFUNC) != 0, 0))
847 /* Use the alternative access functions also in the recursive
849 dirs.gl_opendir = pglob->gl_opendir;
850 dirs.gl_readdir = pglob->gl_readdir;
851 dirs.gl_closedir = pglob->gl_closedir;
852 dirs.gl_stat = pglob->gl_stat;
853 dirs.gl_lstat = pglob->gl_lstat;
856 status = glob (dirname,
857 ((flags & (GLOB_ERR | GLOB_NOESCAPE
859 | GLOB_NOSORT | GLOB_ONLYDIR),
863 if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH)
868 /* We have successfully globbed the preceding directory name.
869 For each name we found, call glob_in_dir on it and FILENAME,
870 appending the results to PGLOB. */
871 for (i = 0; i < dirs.gl_pathc; ++i)
877 /* Make globbing interruptible in the bash shell. */
878 extern int interrupt_state;
888 old_pathc = pglob->gl_pathc;
889 status = glob_in_dir (filename, dirs.gl_pathv[i],
890 ((flags | GLOB_APPEND)
891 & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),
893 if (status == GLOB_NOMATCH)
894 /* No matches in this directory. Try the next. */
905 /* Stick the directory on the front of each name. */
906 if (prefix_array (dirs.gl_pathv[i],
907 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
908 pglob->gl_pathc - old_pathc))
917 flags |= GLOB_MAGCHAR;
919 /* We have ignored the GLOB_NOCHECK flag in the `glob_in_dir' calls.
920 But if we have not found any matching entry and the GLOB_NOCHECK
921 flag was set we must return the input pattern itself. */
922 if (pglob->gl_pathc + pglob->gl_offs == oldcount)
926 if (flags & GLOB_NOCHECK)
928 int newcount = pglob->gl_pathc + pglob->gl_offs;
931 new_gl_pathv = realloc (pglob->gl_pathv,
932 (newcount + 2) * sizeof (char *));
933 if (new_gl_pathv == NULL)
938 pglob->gl_pathv = new_gl_pathv;
940 pglob->gl_pathv[newcount] = strdup (pattern);
941 if (pglob->gl_pathv[newcount] == NULL)
952 pglob->gl_pathv[newcount] = NULL;
953 pglob->gl_flags = flags;
966 int old_pathc = pglob->gl_pathc;
967 int orig_flags = flags;
971 char *p = strchr (dirname, '\\'), *q;
972 /* We need to unescape the dirname string. It is certainly
973 allocated by alloca, as otherwise filename would be NULL
974 or dirname wouldn't contain backslashes. */
987 while (*p++ != '\0');
988 dirname_modified = 1;
990 if (dirname_modified)
991 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
992 status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
995 if (status == GLOB_NOMATCH && flags != orig_flags
996 && pglob->gl_pathc + pglob->gl_offs == oldcount)
998 /* Make sure globfree (&dirs); is a nop. */
999 dirs.gl_pathv = NULL;
1008 /* Stick the directory on the front of each name. */
1009 if (prefix_array (dirname,
1010 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
1011 pglob->gl_pathc - old_pathc))
1014 pglob->gl_pathc = 0;
1015 return GLOB_NOSPACE;
1020 if (flags & GLOB_MARK)
1022 /* Append slashes to directory names. */
1027 for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)
1028 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1029 ? ((*pglob->gl_stat) (pglob->gl_pathv[i], &st) == 0
1030 && S_ISDIR (st.st_mode))
1031 : (__stat64 (pglob->gl_pathv[i], &st64) == 0
1032 && S_ISDIR (st64.st_mode))))
1034 size_t len = strlen (pglob->gl_pathv[i]) + 2;
1035 char *new = realloc (pglob->gl_pathv[i], len);
1039 pglob->gl_pathc = 0;
1040 return GLOB_NOSPACE;
1042 strcpy (&new[len - 2], "/");
1043 pglob->gl_pathv[i] = new;
1047 if (!(flags & GLOB_NOSORT))
1049 /* Sort the vector. */
1050 qsort (&pglob->gl_pathv[oldcount],
1051 pglob->gl_pathc + pglob->gl_offs - oldcount,
1052 sizeof (char *), collated_compare);
1057 #if defined _LIBC && !defined glob
1058 libc_hidden_def (glob)
1062 #if !defined _LIBC || !defined GLOB_ONLY_P
1064 /* Free storage allocated in PGLOB by a previous `glob' call. */
1067 register glob_t *pglob;
1069 if (pglob->gl_pathv != NULL)
1072 for (i = 0; i < pglob->gl_pathc; ++i)
1073 if (pglob->gl_pathv[pglob->gl_offs + i] != NULL)
1074 free (pglob->gl_pathv[pglob->gl_offs + i]);
1075 free (pglob->gl_pathv);
1076 pglob->gl_pathv = NULL;
1079 #if defined _LIBC && !defined globfree
1080 libc_hidden_def (globfree)
1084 /* Do a collated comparison of A and B. */
1086 collated_compare (const void *a, const void *b)
1088 char *const *ps1 = a; char *s1 = *ps1;
1089 char *const *ps2 = b; char *s2 = *ps2;
1097 return strcoll (s1, s2);
1101 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1102 elements in place. Return nonzero if out of memory, zero if successful.
1103 A slash is inserted between DIRNAME and each elt of ARRAY,
1104 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1106 prefix_array (const char *dirname, char **array, size_t n)
1109 size_t dirlen = strlen (dirname);
1110 #if defined __MSDOS__ || defined WINDOWS32
1112 # define DIRSEP_CHAR sep_char
1114 # define DIRSEP_CHAR '/'
1117 if (dirlen == 1 && dirname[0] == '/')
1118 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1119 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1121 #if defined __MSDOS__ || defined WINDOWS32
1122 else if (dirlen > 1)
1124 if (dirname[dirlen - 1] == '/' && dirname[dirlen - 2] == ':')
1125 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1127 else if (dirname[dirlen - 1] == ':')
1129 /* DIRNAME is "d:". Use `:' instead of `/'. */
1136 for (i = 0; i < n; ++i)
1138 size_t eltlen = strlen (array[i]) + 1;
1139 char *new = malloc (dirlen + 1 + eltlen);
1148 char *endp = mempcpy (new, dirname, dirlen);
1149 *endp++ = DIRSEP_CHAR;
1150 mempcpy (endp, array[i], eltlen);
1160 /* We must not compile this function twice. */
1161 #if !defined _LIBC || !defined NO_GLOB_PATTERN_P
1163 __glob_pattern_type (pattern, quote)
1164 const char *pattern;
1167 register const char *p;
1170 for (p = pattern; *p != '\0'; ++p)
1199 /* Return nonzero if PATTERN contains any metacharacters.
1200 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
1202 __glob_pattern_p (pattern, quote)
1203 const char *pattern;
1206 return __glob_pattern_type (pattern, quote) == 1;
1209 weak_alias (__glob_pattern_p, glob_pattern_p)
1213 #endif /* !GLOB_ONLY_P */
1216 /* We put this in a separate function mainly to allow the memory
1217 allocated with alloca to be recycled. */
1218 #if !defined _LIBC || !defined GLOB_ONLY_P
1220 __attribute_noinline__
1221 link_exists2_p (const char *dir, size_t dirlen, const char *fname,
1228 size_t fnamelen = strlen (fname);
1229 char *fullname = __alloca (dirlen + 1 + fnamelen + 1);
1235 mempcpy (mempcpy (mempcpy (fullname, dir, dirlen), "/", 1),
1236 fname, fnamelen + 1);
1239 return (*pglob->gl_stat) (fullname, &st) == 0;
1241 return ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1242 ? (*pglob->gl_stat) (fullname, &st)
1243 : __stat64 (fullname, &st64)) == 0);
1247 # define link_exists_p(dfd, dirname, dirnamelen, fname, pglob, flags) \
1248 (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0) \
1249 ? link_exists2_p (dirname, dirnamelen, fname, pglob) \
1250 : ({ struct stat64 st64; \
1251 __fxstatat64 (_STAT_VER, dfd, fname, &st64, 0) == 0; }))
1253 # define link_exists_p(dfd, dirname, dirnamelen, fname, pglob, flags) \
1254 link_exists2_p (dirname, dirnamelen, fname, pglob, flags)
1259 /* Like `glob', but PATTERN is a final pathname component,
1260 and matches are searched for in DIRECTORY.
1261 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1262 The GLOB_APPEND flag is assumed to be set (always appends). */
1264 glob_in_dir (const char *pattern, const char *directory, int flags,
1265 int (*errfunc) (const char *, int),
1268 size_t dirlen = strlen (directory);
1269 void *stream = NULL;
1272 struct globnames *next;
1276 #define INITIAL_COUNT sizeof (init_names.name) / sizeof (init_names.name[0])
1277 struct globnames init_names;
1278 struct globnames *names = &init_names;
1279 struct globnames *names_alloca = &init_names;
1281 size_t allocasize = sizeof (init_names);
1287 init_names.next = NULL;
1288 init_names.count = INITIAL_COUNT;
1290 meta = __glob_pattern_type (pattern, !(flags & GLOB_NOESCAPE));
1291 if (meta == 0 && (flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
1293 /* We need not do any tests. The PATTERN contains no meta
1294 characters and we must not return an error therefore the
1295 result will always contain exactly one name. */
1296 flags |= GLOB_NOCHECK;
1300 /* Since we use the normal file functions we can also use stat()
1301 to verify the file is there. */
1304 size_t patlen = strlen (pattern);
1305 char *fullname = __alloca (dirlen + 1 + patlen + 1);
1307 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1309 pattern, patlen + 1);
1310 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1311 ? (*pglob->gl_stat) (fullname, &st)
1312 : __stat64 (fullname, &st64)) == 0)
1313 /* We found this file to be existing. Now tell the rest
1314 of the function to copy this name into the result. */
1315 flags |= GLOB_NOCHECK;
1319 stream = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1320 ? (*pglob->gl_opendir) (directory)
1321 : opendir (directory));
1324 if (errno != ENOTDIR
1325 && ((errfunc != NULL && (*errfunc) (directory, errno))
1326 || (flags & GLOB_ERR)))
1327 return GLOB_ABORTED;
1332 int dfd = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1333 ? -1 : dirfd ((DIR *) stream));
1335 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1336 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1337 #if defined _AMIGA || defined VMS
1341 flags |= GLOB_MAGCHAR;
1347 #if defined _LIBC && !defined COMPILE_GLOB64
1351 struct dirent64 d64;
1352 char room [offsetof (struct dirent64, d_name[0])
1357 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1359 struct dirent *d32 = (*pglob->gl_readdir) (stream);
1362 CONVERT_DIRENT_DIRENT64 (&d64buf.d64, d32);
1369 d = __readdir64 (stream);
1371 struct dirent *d = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1372 ? ((struct dirent *)
1373 (*pglob->gl_readdir) (stream))
1374 : __readdir (stream));
1378 if (! REAL_DIR_ENTRY (d))
1381 /* If we shall match only directories use the information
1382 provided by the dirent call if possible. */
1383 if ((flags & GLOB_ONLYDIR) && !DIRENT_MIGHT_BE_DIR (d))
1388 if (fnmatch (pattern, name, fnm_flags) == 0)
1390 /* If the file we found is a symlink we have to
1391 make sure the target file exists. */
1392 if (!DIRENT_MIGHT_BE_SYMLINK (d)
1393 || link_exists_p (dfd, directory, dirlen, name, pglob,
1396 if (cur == names->count)
1398 struct globnames *newnames;
1399 size_t count = names->count * 2;
1400 size_t size = (sizeof (struct globnames)
1401 + ((count - INITIAL_COUNT)
1402 * sizeof (char *)));
1404 if (__libc_use_alloca (allocasize))
1405 newnames = names_alloca = __alloca (size);
1406 else if ((newnames = malloc (size))
1409 newnames->count = count;
1410 newnames->next = names;
1414 len = _D_EXACT_NAMLEN (d);
1415 names->name[cur] = malloc (len + 1);
1416 if (names->name[cur] == NULL)
1418 *((char *) mempcpy (names->name[cur++], name, len))
1427 if (nfound == 0 && (flags & GLOB_NOCHECK))
1429 size_t len = strlen (pattern);
1431 names->name[cur] = malloc (len + 1);
1432 if (names->name[cur] == NULL)
1434 *((char *) mempcpy (names->name[cur++], pattern, len)) = '\0';
1437 result = GLOB_NOMATCH;
1441 = realloc (pglob->gl_pathv,
1442 (pglob->gl_pathc + pglob->gl_offs + nfound + 1)
1446 if (new_gl_pathv == NULL)
1451 struct globnames *old = names;
1452 for (size_t i = 0; i < cur; ++i)
1453 free (names->name[i]);
1454 names = names->next;
1455 /* NB: we will not leak memory here if we exit without
1456 freeing the current block assigned to OLD. At least
1457 the very first block is always allocated on the stack
1458 and this is the block assigned to OLD here. */
1461 assert (old == &init_names);
1465 if (old == names_alloca)
1466 names_alloca = names;
1470 result = GLOB_NOSPACE;
1476 struct globnames *old = names;
1477 for (size_t i = 0; i < cur; ++i)
1478 new_gl_pathv[pglob->gl_offs + pglob->gl_pathc++]
1480 names = names->next;
1481 /* NB: we will not leak memory here if we exit without
1482 freeing the current block assigned to OLD. At least
1483 the very first block is always allocated on the stack
1484 and this is the block assigned to OLD here. */
1487 assert (old == &init_names);
1491 if (old == names_alloca)
1492 names_alloca = names;
1497 pglob->gl_pathv = new_gl_pathv;
1499 pglob->gl_pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
1501 pglob->gl_flags = flags;
1508 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1509 (*pglob->gl_closedir) (stream);