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
153 #ifdef _SC_GETPW_R_SIZE_MAX
154 # define GETPW_R_SIZE_MAX() sysconf (_SC_GETPW_R_SIZE_MAX)
156 # define GETPW_R_SIZE_MAX() (-1)
158 #ifdef _SC_LOGIN_NAME_MAX
159 # define GET_LOGIN_NAME_MAX() sysconf (_SC_LOGIN_NAME_MAX)
161 # define GET_LOGIN_NAME_MAX() (-1)
164 static const char *next_brace_sub (const char *begin, int flags) __THROW;
166 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
168 #ifndef attribute_hidden
169 # define attribute_hidden
172 #ifndef __attribute_noinline__
173 # if __GNUC__ < 3 || (__GNUC__ == 3 && __GNUC_MINOR__ < 1)
174 # define __attribute_noinline__ /* Ignore */
176 # define __attribute_noinline__ __attribute__ ((__noinline__))
180 #if ! defined __builtin_expect && __GNUC__ < 3
181 # define __builtin_expect(expr, expected) (expr)
185 /* The results of opendir() in this file are not used with dirfd and fchdir,
186 therefore save some unnecessary work in fchdir.c. */
191 /* The OS usually guarantees only one guard page at the bottom of the stack,
192 and a page size can be as small as 4096 bytes. So we cannot safely
193 allocate anything larger than 4096 bytes. Also care for the possibility
194 of a few compiler-allocated temporary stack slots. */
195 # define __libc_use_alloca(n) ((n) < 4032)
197 /* alloca is implemented with malloc, so just use malloc. */
198 # define __libc_use_alloca(n) 0
202 static int glob_in_dir (const char *pattern, const char *directory,
203 int flags, int (*errfunc) (const char *, int),
205 extern int __glob_pattern_type (const char *pattern, int quote)
208 #if !defined _LIBC || !defined GLOB_ONLY_P
209 static int prefix_array (const char *prefix, char **array, size_t n) __THROW;
210 static int collated_compare (const void *, const void *) __THROW;
213 /* Find the end of the sub-pattern in a brace expression. */
215 next_brace_sub (const char *cp, int flags)
217 unsigned int depth = 0;
219 if ((flags & GLOB_NOESCAPE) == 0 && *cp == '\\')
227 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
234 return *cp != '\0' ? cp : NULL;
237 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
239 /* Do glob searching for PATTERN, placing results in PGLOB.
240 The bits defined above may be set in FLAGS.
241 If a directory cannot be opened or read and ERRFUNC is not nil,
242 it is called with the pathname that caused the error, and the
243 `errno' value from the failing call; if it returns non-zero
244 `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
245 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
246 Otherwise, `glob' returns zero. */
248 #ifdef GLOB_ATTRIBUTE
251 glob (pattern, flags, errfunc, pglob)
252 const char * restrict pattern;
254 int (*errfunc) (const char *, int);
255 glob_t * restrict pglob;
257 const char *filename;
263 int dirname_modified;
266 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
268 __set_errno (EINVAL);
272 if (!(flags & GLOB_DOOFFS))
273 /* Have to do this so `globfree' knows where to start freeing. It
274 also makes all the code that uses gl_offs simpler. */
277 if (flags & GLOB_BRACE)
281 if (flags & GLOB_NOESCAPE)
282 begin = strchr (pattern, '{');
294 if (*begin == '\\' && begin[1] != '\0')
296 else if (*begin == '{')
305 /* Allocate working buffer large enough for our work. Note that
306 we have at least an opening and closing brace. */
314 char onealt[strlen (pattern) - 1];
316 char *onealt = malloc (strlen (pattern) - 1);
319 if (!(flags & GLOB_APPEND))
322 pglob->gl_pathv = NULL;
328 /* We know the prefix for all sub-patterns. */
329 alt_start = mempcpy (onealt, pattern, begin - pattern);
331 /* Find the first sub-pattern and at the same time find the
332 rest after the closing brace. */
333 next = next_brace_sub (begin + 1, flags);
336 /* It is an invalid expression. */
340 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
343 /* Now find the end of the whole brace expression. */
347 rest = next_brace_sub (rest + 1, flags);
350 /* It is an invalid expression. */
354 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
357 /* Please note that we now can be sure the brace expression
359 rest_len = strlen (++rest) + 1;
361 /* We have a brace expression. BEGIN points to the opening {,
362 NEXT points past the terminator of the first element, and END
363 points past the final }. We will accumulate result names from
364 recursive runs for each brace alternative in the buffer using
367 if (!(flags & GLOB_APPEND))
369 /* This call is to set a new vector, so clear out the
370 vector so we can append to it. */
372 pglob->gl_pathv = NULL;
374 firstc = pglob->gl_pathc;
381 /* Construct the new glob expression. */
382 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
384 result = glob (onealt,
385 ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))
386 | GLOB_APPEND), errfunc, pglob);
388 /* If we got an error, return it. */
389 if (result && result != GLOB_NOMATCH)
394 if (!(flags & GLOB_APPEND))
403 /* We saw the last entry. */
407 next = next_brace_sub (p, flags);
408 assert (next != NULL);
415 if (pglob->gl_pathc != firstc)
416 /* We found some entries. */
418 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
423 /* Find the filename. */
424 filename = strrchr (pattern, '/');
425 #if defined __MSDOS__ || defined WINDOWS32
426 /* The case of "d:pattern". Since `:' is not allowed in
427 file names, we can safely assume that wherever it
428 happens in pattern, it signals the filename part. This
429 is so we could some day support patterns like "[a-z]:foo". */
430 if (filename == NULL)
431 filename = strchr (pattern, ':');
432 #endif /* __MSDOS__ || WINDOWS32 */
433 dirname_modified = 0;
434 if (filename == NULL)
436 /* This can mean two things: a simple name or "~name". The latter
437 case is nothing but a notation for a directory. */
438 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
441 dirlen = strlen (pattern);
443 /* Set FILENAME to NULL as a special flag. This is ugly but
444 other solutions would require much more code. We test for
445 this special case below. */
459 else if (filename == pattern
460 || (filename == pattern + 1 && pattern[0] == '\\'
461 && (flags & GLOB_NOESCAPE) == 0))
463 /* "/pattern" or "\\/pattern". */
471 dirlen = filename - pattern;
472 #if defined __MSDOS__ || defined WINDOWS32
474 || (filename > pattern + 1 && filename[-1] == ':'))
479 drive_spec = __alloca (dirlen + 1);
480 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
481 /* For now, disallow wildcards in the drive spec, to
482 prevent infinite recursion in glob. */
483 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
485 /* If this is "d:pattern", we need to copy `:' to DIRNAME
486 as well. If it's "d:/pattern", don't remove the slash
487 from "d:/", since "d:" and "d:/" are not the same.*/
490 newp = __alloca (dirlen + 1);
491 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
495 if (filename[0] == '\0'
496 #if defined __MSDOS__ || defined WINDOWS32
497 && dirname[dirlen - 1] != ':'
498 && (dirlen < 3 || dirname[dirlen - 2] != ':'
499 || dirname[dirlen - 1] != '/')
502 /* "pattern/". Expand "pattern", appending slashes. */
504 int orig_flags = flags;
506 if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\')
508 /* "pattern\\/". Remove the final backslash if it hasn't
510 char *p = (char *) &dirname[dirlen - 1];
512 while (p > dirname && p[-1] == '\\') --p;
513 if ((&dirname[dirlen] - p) & 1)
515 *(char *) &dirname[--dirlen] = '\0';
516 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
519 val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
521 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
522 | (flags & GLOB_MARK));
523 else if (val == GLOB_NOMATCH && flags != orig_flags)
525 /* Make sure globfree (&dirs); is a nop. */
526 dirs.gl_pathv = NULL;
528 oldcount = pglob->gl_pathc + pglob->gl_offs;
535 if (!(flags & GLOB_APPEND))
538 if (!(flags & GLOB_DOOFFS))
539 pglob->gl_pathv = NULL;
543 pglob->gl_pathv = malloc ((pglob->gl_offs + 1) * sizeof (char *));
544 if (pglob->gl_pathv == NULL)
547 for (i = 0; i <= pglob->gl_offs; ++i)
548 pglob->gl_pathv[i] = NULL;
552 oldcount = pglob->gl_pathc + pglob->gl_offs;
554 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
556 if (dirname[1] == '\0' || dirname[1] == '/'
557 || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\'
558 && (dirname[2] == '\0' || dirname[2] == '/')))
560 /* Look up home directory. */
561 const char *home_dir = getenv ("HOME");
563 if (home_dir == NULL || home_dir[0] == '\0')
567 if (home_dir == NULL || home_dir[0] == '\0')
568 home_dir = "c:/users/default"; /* poor default */
570 if (home_dir == NULL || home_dir[0] == '\0')
574 size_t buflen = GET_LOGIN_NAME_MAX () + 1;
577 /* `sysconf' does not support _SC_LOGIN_NAME_MAX. Try
580 name = __alloca (buflen);
582 success = getlogin_r (name, buflen) == 0;
586 # if defined HAVE_GETPWNAM_R || defined _LIBC
587 long int pwbuflen = GETPW_R_SIZE_MAX ();
594 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.
595 Try a moderate value. */
598 pwtmpbuf = __alloca (pwbuflen);
600 while (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
609 pwtmpbuf = extend_alloca (pwtmpbuf, pwbuflen,
613 pwtmpbuf = __alloca (pwbuflen);
621 home_dir = p->pw_dir;
624 if (home_dir == NULL || home_dir[0] == '\0')
626 if (flags & GLOB_TILDE_CHECK)
629 home_dir = "~"; /* No luck. */
631 # endif /* WINDOWS32 */
633 /* Now construct the full directory. */
634 if (dirname[1] == '\0')
637 dirlen = strlen (dirname);
642 size_t home_len = strlen (home_dir);
643 newp = __alloca (home_len + dirlen);
644 mempcpy (mempcpy (newp, home_dir, home_len),
645 &dirname[1], dirlen);
647 dirlen += home_len - 1;
649 dirname_modified = 1;
651 # if !defined _AMIGA && !defined WINDOWS32
654 char *end_name = strchr (dirname, '/');
655 const char *user_name;
656 const char *home_dir;
657 char *unescape = NULL;
659 if (!(flags & GLOB_NOESCAPE))
661 if (end_name == NULL)
663 unescape = strchr (dirname, '\\');
665 end_name = strchr (unescape, '\0');
668 unescape = memchr (dirname, '\\', end_name - dirname);
670 if (end_name == NULL)
671 user_name = dirname + 1;
675 newp = __alloca (end_name - dirname);
676 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
678 if (unescape != NULL)
680 char *p = mempcpy (newp, dirname + 1,
681 unescape - dirname - 1);
689 /* "~fo\\o\\" unescape to user_name "foo\\",
690 but "~fo\\o\\/" unescape to user_name
692 if (filename == NULL)
703 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
708 /* Look up specific user's home directory. */
711 # if defined HAVE_GETPWNAM_R || defined _LIBC
712 long int buflen = GETPW_R_SIZE_MAX ();
719 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
723 pwtmpbuf = __alloca (buflen);
725 while (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) != 0)
733 pwtmpbuf = extend_alloca (pwtmpbuf, buflen, 2 * buflen);
736 pwtmpbuf = __alloca (buflen);
741 p = getpwnam (user_name);
744 home_dir = p->pw_dir;
748 /* If we found a home directory use this. */
749 if (home_dir != NULL)
752 size_t home_len = strlen (home_dir);
753 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
754 newp = __alloca (home_len + rest_len + 1);
755 *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
756 end_name, rest_len)) = '\0';
758 dirlen = home_len + rest_len;
759 dirname_modified = 1;
762 if (flags & GLOB_TILDE_CHECK)
763 /* We have to regard it as an error if we cannot find the
767 # endif /* Not Amiga && not WINDOWS32. */
770 /* Now test whether we looked for "~" or "~NAME". In this case we
771 can give the answer now. */
772 if (filename == NULL)
777 /* Return the directory if we don't check for error or if it exists. */
778 if ((flags & GLOB_NOCHECK)
779 || (((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
780 ? ((*pglob->gl_stat) (dirname, &st) == 0
781 && S_ISDIR (st.st_mode))
782 : (__stat64 (dirname, &st64) == 0 && S_ISDIR (st64.st_mode)))))
784 int newcount = pglob->gl_pathc + pglob->gl_offs;
788 = realloc (pglob->gl_pathv, (newcount + 1 + 1) * sizeof (char *));
789 if (new_gl_pathv == NULL)
792 free (pglob->gl_pathv);
793 pglob->gl_pathv = NULL;
797 pglob->gl_pathv = new_gl_pathv;
799 if (flags & GLOB_MARK)
802 pglob->gl_pathv[newcount] = malloc (dirlen + 2);
803 if (pglob->gl_pathv[newcount] == NULL)
805 p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);
811 pglob->gl_pathv[newcount] = strdup (dirname);
812 if (pglob->gl_pathv[newcount] == NULL)
815 pglob->gl_pathv[++newcount] = NULL;
817 pglob->gl_flags = flags;
826 meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));
827 /* meta is 1 if correct glob pattern containing metacharacters.
828 If meta has bit (1 << 2) set, it means there was an unterminated
829 [ which we handle the same, using fnmatch. Broken unterminated
830 pattern bracket expressions ought to be rare enough that it is
831 not worth special casing them, fnmatch will do the right thing. */
834 /* The directory name contains metacharacters, so we
835 have to glob for the directory, and then glob for
836 the pattern in each directory found. */
839 if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\')
841 /* "foo\\/bar". Remove the final backslash from dirname
842 if it has not been quoted. */
843 char *p = (char *) &dirname[dirlen - 1];
845 while (p > dirname && p[-1] == '\\') --p;
846 if ((&dirname[dirlen] - p) & 1)
847 *(char *) &dirname[--dirlen] = '\0';
850 if (__builtin_expect ((flags & GLOB_ALTDIRFUNC) != 0, 0))
852 /* Use the alternative access functions also in the recursive
854 dirs.gl_opendir = pglob->gl_opendir;
855 dirs.gl_readdir = pglob->gl_readdir;
856 dirs.gl_closedir = pglob->gl_closedir;
857 dirs.gl_stat = pglob->gl_stat;
858 dirs.gl_lstat = pglob->gl_lstat;
861 status = glob (dirname,
862 ((flags & (GLOB_ERR | GLOB_NOESCAPE
864 | GLOB_NOSORT | GLOB_ONLYDIR),
868 if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH)
873 /* We have successfully globbed the preceding directory name.
874 For each name we found, call glob_in_dir on it and FILENAME,
875 appending the results to PGLOB. */
876 for (i = 0; i < dirs.gl_pathc; ++i)
882 /* Make globbing interruptible in the bash shell. */
883 extern int interrupt_state;
893 old_pathc = pglob->gl_pathc;
894 status = glob_in_dir (filename, dirs.gl_pathv[i],
895 ((flags | GLOB_APPEND)
896 & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),
898 if (status == GLOB_NOMATCH)
899 /* No matches in this directory. Try the next. */
910 /* Stick the directory on the front of each name. */
911 if (prefix_array (dirs.gl_pathv[i],
912 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
913 pglob->gl_pathc - old_pathc))
922 flags |= GLOB_MAGCHAR;
924 /* We have ignored the GLOB_NOCHECK flag in the `glob_in_dir' calls.
925 But if we have not found any matching entry and the GLOB_NOCHECK
926 flag was set we must return the input pattern itself. */
927 if (pglob->gl_pathc + pglob->gl_offs == oldcount)
931 if (flags & GLOB_NOCHECK)
933 int newcount = pglob->gl_pathc + pglob->gl_offs;
936 new_gl_pathv = realloc (pglob->gl_pathv,
937 (newcount + 2) * sizeof (char *));
938 if (new_gl_pathv == NULL)
943 pglob->gl_pathv = new_gl_pathv;
945 pglob->gl_pathv[newcount] = strdup (pattern);
946 if (pglob->gl_pathv[newcount] == NULL)
957 pglob->gl_pathv[newcount] = NULL;
958 pglob->gl_flags = flags;
971 int old_pathc = pglob->gl_pathc;
972 int orig_flags = flags;
976 char *p = strchr (dirname, '\\'), *q;
977 /* We need to unescape the dirname string. It is certainly
978 allocated by alloca, as otherwise filename would be NULL
979 or dirname wouldn't contain backslashes. */
992 while (*p++ != '\0');
993 dirname_modified = 1;
995 if (dirname_modified)
996 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
997 status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
1000 if (status == GLOB_NOMATCH && flags != orig_flags
1001 && pglob->gl_pathc + pglob->gl_offs == oldcount)
1003 /* Make sure globfree (&dirs); is a nop. */
1004 dirs.gl_pathv = NULL;
1013 /* Stick the directory on the front of each name. */
1014 if (prefix_array (dirname,
1015 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
1016 pglob->gl_pathc - old_pathc))
1019 pglob->gl_pathc = 0;
1020 return GLOB_NOSPACE;
1025 if (flags & GLOB_MARK)
1027 /* Append slashes to directory names. */
1032 for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)
1033 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1034 ? ((*pglob->gl_stat) (pglob->gl_pathv[i], &st) == 0
1035 && S_ISDIR (st.st_mode))
1036 : (__stat64 (pglob->gl_pathv[i], &st64) == 0
1037 && S_ISDIR (st64.st_mode))))
1039 size_t len = strlen (pglob->gl_pathv[i]) + 2;
1040 char *new = realloc (pglob->gl_pathv[i], len);
1044 pglob->gl_pathc = 0;
1045 return GLOB_NOSPACE;
1047 strcpy (&new[len - 2], "/");
1048 pglob->gl_pathv[i] = new;
1052 if (!(flags & GLOB_NOSORT))
1054 /* Sort the vector. */
1055 qsort (&pglob->gl_pathv[oldcount],
1056 pglob->gl_pathc + pglob->gl_offs - oldcount,
1057 sizeof (char *), collated_compare);
1062 #if defined _LIBC && !defined glob
1063 libc_hidden_def (glob)
1067 #if !defined _LIBC || !defined GLOB_ONLY_P
1069 /* Free storage allocated in PGLOB by a previous `glob' call. */
1072 register glob_t *pglob;
1074 if (pglob->gl_pathv != NULL)
1077 for (i = 0; i < pglob->gl_pathc; ++i)
1078 if (pglob->gl_pathv[pglob->gl_offs + i] != NULL)
1079 free (pglob->gl_pathv[pglob->gl_offs + i]);
1080 free (pglob->gl_pathv);
1081 pglob->gl_pathv = NULL;
1084 #if defined _LIBC && !defined globfree
1085 libc_hidden_def (globfree)
1089 /* Do a collated comparison of A and B. */
1091 collated_compare (const void *a, const void *b)
1093 char *const *ps1 = a; char *s1 = *ps1;
1094 char *const *ps2 = b; char *s2 = *ps2;
1102 return strcoll (s1, s2);
1106 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1107 elements in place. Return nonzero if out of memory, zero if successful.
1108 A slash is inserted between DIRNAME and each elt of ARRAY,
1109 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1111 prefix_array (const char *dirname, char **array, size_t n)
1114 size_t dirlen = strlen (dirname);
1115 #if defined __MSDOS__ || defined WINDOWS32
1117 # define DIRSEP_CHAR sep_char
1119 # define DIRSEP_CHAR '/'
1122 if (dirlen == 1 && dirname[0] == '/')
1123 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1124 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1126 #if defined __MSDOS__ || defined WINDOWS32
1127 else if (dirlen > 1)
1129 if (dirname[dirlen - 1] == '/' && dirname[dirlen - 2] == ':')
1130 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1132 else if (dirname[dirlen - 1] == ':')
1134 /* DIRNAME is "d:". Use `:' instead of `/'. */
1141 for (i = 0; i < n; ++i)
1143 size_t eltlen = strlen (array[i]) + 1;
1144 char *new = malloc (dirlen + 1 + eltlen);
1153 char *endp = mempcpy (new, dirname, dirlen);
1154 *endp++ = DIRSEP_CHAR;
1155 mempcpy (endp, array[i], eltlen);
1165 /* We must not compile this function twice. */
1166 #if !defined _LIBC || !defined NO_GLOB_PATTERN_P
1168 __glob_pattern_type (pattern, quote)
1169 const char *pattern;
1172 register const char *p;
1175 for (p = pattern; *p != '\0'; ++p)
1204 /* Return nonzero if PATTERN contains any metacharacters.
1205 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
1207 __glob_pattern_p (pattern, quote)
1208 const char *pattern;
1211 return __glob_pattern_type (pattern, quote) == 1;
1214 weak_alias (__glob_pattern_p, glob_pattern_p)
1218 #endif /* !GLOB_ONLY_P */
1221 /* We put this in a separate function mainly to allow the memory
1222 allocated with alloca to be recycled. */
1223 #if !defined _LIBC || !defined GLOB_ONLY_P
1225 __attribute_noinline__
1226 link_exists2_p (const char *dir, size_t dirlen, const char *fname,
1229 size_t fnamelen = strlen (fname);
1230 char *fullname = __alloca (dirlen + 1 + fnamelen + 1);
1233 mempcpy (mempcpy (mempcpy (fullname, dir, dirlen), "/", 1),
1234 fname, fnamelen + 1);
1236 return (*pglob->gl_stat) (fullname, &st) == 0;
1239 /* Return true if DIR/FNAME exists. */
1241 link_exists_p (int dfd, const char *dir, size_t dirlen, const char *fname,
1242 glob_t *pglob, int flags)
1244 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1245 return link_exists2_p (dir, dirlen, fname, pglob);
1249 return __fxstatat64 (_STAT_VER, dfd, fname, &st64, 0) == 0;
1255 /* Like `glob', but PATTERN is a final pathname component,
1256 and matches are searched for in DIRECTORY.
1257 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1258 The GLOB_APPEND flag is assumed to be set (always appends). */
1260 glob_in_dir (const char *pattern, const char *directory, int flags,
1261 int (*errfunc) (const char *, int),
1264 size_t dirlen = strlen (directory);
1265 void *stream = NULL;
1268 struct globnames *next;
1272 #define INITIAL_COUNT sizeof (init_names.name) / sizeof (init_names.name[0])
1273 struct globnames init_names;
1274 struct globnames *names = &init_names;
1275 struct globnames *names_alloca = &init_names;
1277 size_t allocasize = sizeof (init_names);
1283 init_names.next = NULL;
1284 init_names.count = INITIAL_COUNT;
1286 meta = __glob_pattern_type (pattern, !(flags & GLOB_NOESCAPE));
1287 if (meta == 0 && (flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
1289 /* We need not do any tests. The PATTERN contains no meta
1290 characters and we must not return an error therefore the
1291 result will always contain exactly one name. */
1292 flags |= GLOB_NOCHECK;
1296 /* Since we use the normal file functions we can also use stat()
1297 to verify the file is there. */
1300 size_t patlen = strlen (pattern);
1301 char *fullname = __alloca (dirlen + 1 + patlen + 1);
1303 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1305 pattern, patlen + 1);
1306 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1307 ? (*pglob->gl_stat) (fullname, &st)
1308 : __stat64 (fullname, &st64)) == 0)
1309 /* We found this file to be existing. Now tell the rest
1310 of the function to copy this name into the result. */
1311 flags |= GLOB_NOCHECK;
1315 stream = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1316 ? (*pglob->gl_opendir) (directory)
1317 : opendir (directory));
1320 if (errno != ENOTDIR
1321 && ((errfunc != NULL && (*errfunc) (directory, errno))
1322 || (flags & GLOB_ERR)))
1323 return GLOB_ABORTED;
1327 int dfd = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1328 ? -1 : dirfd ((DIR *) stream));
1329 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1330 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1331 #if defined _AMIGA || defined VMS
1335 flags |= GLOB_MAGCHAR;
1341 #if defined _LIBC && !defined COMPILE_GLOB64
1345 struct dirent64 d64;
1346 char room [offsetof (struct dirent64, d_name[0])
1351 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1353 struct dirent *d32 = (*pglob->gl_readdir) (stream);
1356 CONVERT_DIRENT_DIRENT64 (&d64buf.d64, d32);
1363 d = __readdir64 (stream);
1365 struct dirent *d = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1366 ? ((struct dirent *)
1367 (*pglob->gl_readdir) (stream))
1368 : __readdir (stream));
1372 if (! REAL_DIR_ENTRY (d))
1375 /* If we shall match only directories use the information
1376 provided by the dirent call if possible. */
1377 if ((flags & GLOB_ONLYDIR) && !DIRENT_MIGHT_BE_DIR (d))
1382 if (fnmatch (pattern, name, fnm_flags) == 0)
1384 /* If the file we found is a symlink we have to
1385 make sure the target file exists. */
1386 if (!DIRENT_MIGHT_BE_SYMLINK (d)
1387 || link_exists_p (dfd, directory, dirlen, name, pglob,
1390 if (cur == names->count)
1392 struct globnames *newnames;
1393 size_t count = names->count * 2;
1394 size_t size = (sizeof (struct globnames)
1395 + ((count - INITIAL_COUNT)
1396 * sizeof (char *)));
1398 if (__libc_use_alloca (allocasize))
1399 newnames = names_alloca = __alloca (size);
1400 else if ((newnames = malloc (size))
1403 newnames->count = count;
1404 newnames->next = names;
1408 len = _D_EXACT_NAMLEN (d);
1409 names->name[cur] = malloc (len + 1);
1410 if (names->name[cur] == NULL)
1412 *((char *) mempcpy (names->name[cur++], name, len))
1421 if (nfound == 0 && (flags & GLOB_NOCHECK))
1423 size_t len = strlen (pattern);
1425 names->name[cur] = malloc (len + 1);
1426 if (names->name[cur] == NULL)
1428 *((char *) mempcpy (names->name[cur++], pattern, len)) = '\0';
1431 result = GLOB_NOMATCH;
1435 = realloc (pglob->gl_pathv,
1436 (pglob->gl_pathc + pglob->gl_offs + nfound + 1)
1440 if (new_gl_pathv == NULL)
1445 struct globnames *old = names;
1446 for (size_t i = 0; i < cur; ++i)
1447 free (names->name[i]);
1448 names = names->next;
1449 /* NB: we will not leak memory here if we exit without
1450 freeing the current block assigned to OLD. At least
1451 the very first block is always allocated on the stack
1452 and this is the block assigned to OLD here. */
1455 assert (old == &init_names);
1459 if (old == names_alloca)
1460 names_alloca = names;
1464 result = GLOB_NOSPACE;
1470 struct globnames *old = names;
1471 for (size_t i = 0; i < cur; ++i)
1472 new_gl_pathv[pglob->gl_offs + pglob->gl_pathc++]
1474 names = names->next;
1475 /* NB: we will not leak memory here if we exit without
1476 freeing the current block assigned to OLD. At least
1477 the very first block is always allocated on the stack
1478 and this is the block assigned to OLD here. */
1481 assert (old == &init_names);
1485 if (old == names_alloca)
1486 names_alloca = names;
1491 pglob->gl_pathv = new_gl_pathv;
1493 pglob->gl_pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
1495 pglob->gl_flags = flags;
1502 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1503 (*pglob->gl_closedir) (stream);