1 /* Copyright (C) 1991-2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
2 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 3 of the License, or
8 (at your option) any later version.
10 This program 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
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
25 #include <sys/types.h>
29 /* Outcomment the following line for production quality code. */
30 /* #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
44 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
54 # define __set_errno(val) errno = (val)
60 /* In GNU systems, <dirent.h> defines this macro for us. */
61 #ifndef _D_EXACT_NAMLEN
62 # define _D_EXACT_NAMLEN(dirent) strlen ((dirent)->d_name)
65 /* When used in the GNU libc the symbol _DIRENT_HAVE_D_TYPE is available
66 if the `d_type' member for `struct dirent' is available.
67 HAVE_STRUCT_DIRENT_D_TYPE plays the same role in GNULIB. */
68 #if defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE
69 /* True if the directory entry D must be of type T. */
70 # define DIRENT_MUST_BE(d, t) ((d)->d_type == (t))
72 /* True if the directory entry D might be a symbolic link. */
73 # define DIRENT_MIGHT_BE_SYMLINK(d) \
74 ((d)->d_type == DT_UNKNOWN || (d)->d_type == DT_LNK)
76 /* True if the directory entry D might be a directory. */
77 # define DIRENT_MIGHT_BE_DIR(d) \
78 ((d)->d_type == DT_DIR || DIRENT_MIGHT_BE_SYMLINK (d))
80 #else /* !HAVE_D_TYPE */
81 # define DIRENT_MUST_BE(d, t) false
82 # define DIRENT_MIGHT_BE_SYMLINK(d) true
83 # define DIRENT_MIGHT_BE_DIR(d) true
84 #endif /* HAVE_D_TYPE */
86 /* If the system has the `struct dirent64' type we use it internally. */
87 #if defined _LIBC && !defined COMPILE_GLOB64
88 # if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
89 # define CONVERT_D_INO(d64, d32)
91 # define CONVERT_D_INO(d64, d32) \
92 (d64)->d_ino = (d32)->d_ino;
95 # ifdef _DIRENT_HAVE_D_TYPE
96 # define CONVERT_D_TYPE(d64, d32) \
97 (d64)->d_type = (d32)->d_type;
99 # define CONVERT_D_TYPE(d64, d32)
102 # define CONVERT_DIRENT_DIRENT64(d64, d32) \
103 memcpy ((d64)->d_name, (d32)->d_name, _D_EXACT_NAMLEN (d32) + 1); \
104 CONVERT_D_INO (d64, d32) \
105 CONVERT_D_TYPE (d64, d32)
109 #if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
110 /* Posix does not require that the d_ino field be present, and some
111 systems do not provide it. */
112 # define REAL_DIR_ENTRY(dp) 1
114 # define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
120 /* NAME_MAX is usually defined in <dirent.h> or <limits.h>. */
123 # define NAME_MAX (sizeof (((struct dirent *) 0)->d_name))
130 # define strdup(str) __strdup (str)
131 # define sysconf(id) __sysconf (id)
132 # define closedir(dir) __closedir (dir)
133 # define opendir(name) __opendir (name)
134 # define readdir(str) __readdir64 (str)
135 # define getpwnam_r(name, bufp, buf, len, res) \
136 __getpwnam_r (name, bufp, buf, len, res)
138 # define __stat64(fname, buf) __xstat64 (_STAT_VER, fname, buf)
140 # define struct_stat64 struct stat64
142 # define __stat64(fname, buf) stat (fname, buf)
143 # define __fxstatat64(_, d, f, st, flag) fstatat (d, f, st, flag)
144 # define struct_stat64 struct stat
145 # define __stat(fname, buf) stat (fname, buf)
146 # define __alloca alloca
147 # define __readdir readdir
148 # define __readdir64 readdir64
149 # 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 and we do not leak fds to any single-threaded code that could use stdio,
188 therefore save some unnecessary recursion in fchdir.c and opendir_safer.c.
189 FIXME - if the kernel ever adds support for multi-thread safety for
190 avoiding standard fds, then we should use opendir_safer. */
195 /* The OS usually guarantees only one guard page at the bottom of the stack,
196 and a page size can be as small as 4096 bytes. So we cannot safely
197 allocate anything larger than 4096 bytes. Also care for the possibility
198 of a few compiler-allocated temporary stack slots. */
199 # define __libc_use_alloca(n) ((n) < 4032)
201 /* alloca is implemented with malloc, so just use malloc. */
202 # define __libc_use_alloca(n) 0
206 static int glob_in_dir (const char *pattern, const char *directory,
207 int flags, int (*errfunc) (const char *, int),
209 extern int __glob_pattern_type (const char *pattern, int quote)
212 #if !defined _LIBC || !defined GLOB_ONLY_P
213 static int prefix_array (const char *prefix, char **array, size_t n) __THROW;
214 static int collated_compare (const void *, const void *) __THROW;
217 /* Find the end of the sub-pattern in a brace expression. */
219 next_brace_sub (const char *cp, int flags)
221 unsigned int depth = 0;
223 if ((flags & GLOB_NOESCAPE) == 0 && *cp == '\\')
231 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
238 return *cp != '\0' ? cp : NULL;
241 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
243 /* Do glob searching for PATTERN, placing results in PGLOB.
244 The bits defined above may be set in FLAGS.
245 If a directory cannot be opened or read and ERRFUNC is not nil,
246 it is called with the pathname that caused the error, and the
247 `errno' value from the failing call; if it returns non-zero
248 `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
249 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
250 Otherwise, `glob' returns zero. */
252 #ifdef GLOB_ATTRIBUTE
255 glob (pattern, flags, errfunc, pglob)
256 const char * restrict pattern;
258 int (*errfunc) (const char *, int);
259 glob_t * restrict pglob;
261 const char *filename;
267 int dirname_modified;
270 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
272 __set_errno (EINVAL);
276 if (!(flags & GLOB_DOOFFS))
277 /* Have to do this so `globfree' knows where to start freeing. It
278 also makes all the code that uses gl_offs simpler. */
281 if (flags & GLOB_BRACE)
285 if (flags & GLOB_NOESCAPE)
286 begin = strchr (pattern, '{');
298 if (*begin == '\\' && begin[1] != '\0')
300 else if (*begin == '{')
309 /* Allocate working buffer large enough for our work. Note that
310 we have at least an opening and closing brace. */
318 char onealt[strlen (pattern) - 1];
320 char *onealt = malloc (strlen (pattern) - 1);
323 if (!(flags & GLOB_APPEND))
326 pglob->gl_pathv = NULL;
332 /* We know the prefix for all sub-patterns. */
333 alt_start = mempcpy (onealt, pattern, begin - pattern);
335 /* Find the first sub-pattern and at the same time find the
336 rest after the closing brace. */
337 next = next_brace_sub (begin + 1, flags);
340 /* It is an invalid expression. */
344 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
347 /* Now find the end of the whole brace expression. */
351 rest = next_brace_sub (rest + 1, flags);
354 /* It is an invalid expression. */
358 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
361 /* Please note that we now can be sure the brace expression
363 rest_len = strlen (++rest) + 1;
365 /* We have a brace expression. BEGIN points to the opening {,
366 NEXT points past the terminator of the first element, and END
367 points past the final }. We will accumulate result names from
368 recursive runs for each brace alternative in the buffer using
371 if (!(flags & GLOB_APPEND))
373 /* This call is to set a new vector, so clear out the
374 vector so we can append to it. */
376 pglob->gl_pathv = NULL;
378 firstc = pglob->gl_pathc;
385 /* Construct the new glob expression. */
386 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
388 result = glob (onealt,
389 ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))
390 | GLOB_APPEND), errfunc, pglob);
392 /* If we got an error, return it. */
393 if (result && result != GLOB_NOMATCH)
398 if (!(flags & GLOB_APPEND))
407 /* We saw the last entry. */
411 next = next_brace_sub (p, flags);
412 assert (next != NULL);
419 if (pglob->gl_pathc != firstc)
420 /* We found some entries. */
422 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
427 /* Find the filename. */
428 filename = strrchr (pattern, '/');
429 #if defined __MSDOS__ || defined WINDOWS32
430 /* The case of "d:pattern". Since `:' is not allowed in
431 file names, we can safely assume that wherever it
432 happens in pattern, it signals the filename part. This
433 is so we could some day support patterns like "[a-z]:foo". */
434 if (filename == NULL)
435 filename = strchr (pattern, ':');
436 #endif /* __MSDOS__ || WINDOWS32 */
437 dirname_modified = 0;
438 if (filename == NULL)
440 /* This can mean two things: a simple name or "~name". The latter
441 case is nothing but a notation for a directory. */
442 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
445 dirlen = strlen (pattern);
447 /* Set FILENAME to NULL as a special flag. This is ugly but
448 other solutions would require much more code. We test for
449 this special case below. */
463 else if (filename == pattern
464 || (filename == pattern + 1 && pattern[0] == '\\'
465 && (flags & GLOB_NOESCAPE) == 0))
467 /* "/pattern" or "\\/pattern". */
475 dirlen = filename - pattern;
476 #if defined __MSDOS__ || defined WINDOWS32
478 || (filename > pattern + 1 && filename[-1] == ':'))
483 drive_spec = __alloca (dirlen + 1);
484 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
485 /* For now, disallow wildcards in the drive spec, to
486 prevent infinite recursion in glob. */
487 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
489 /* If this is "d:pattern", we need to copy `:' to DIRNAME
490 as well. If it's "d:/pattern", don't remove the slash
491 from "d:/", since "d:" and "d:/" are not the same.*/
494 newp = __alloca (dirlen + 1);
495 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
499 if (filename[0] == '\0'
500 #if defined __MSDOS__ || defined WINDOWS32
501 && dirname[dirlen - 1] != ':'
502 && (dirlen < 3 || dirname[dirlen - 2] != ':'
503 || dirname[dirlen - 1] != '/')
506 /* "pattern/". Expand "pattern", appending slashes. */
508 int orig_flags = flags;
510 if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\')
512 /* "pattern\\/". Remove the final backslash if it hasn't
514 char *p = (char *) &dirname[dirlen - 1];
516 while (p > dirname && p[-1] == '\\') --p;
517 if ((&dirname[dirlen] - p) & 1)
519 *(char *) &dirname[--dirlen] = '\0';
520 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
523 val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
525 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
526 | (flags & GLOB_MARK));
527 else if (val == GLOB_NOMATCH && flags != orig_flags)
529 /* Make sure globfree (&dirs); is a nop. */
530 dirs.gl_pathv = NULL;
532 oldcount = pglob->gl_pathc + pglob->gl_offs;
539 if (!(flags & GLOB_APPEND))
542 if (!(flags & GLOB_DOOFFS))
543 pglob->gl_pathv = NULL;
547 pglob->gl_pathv = malloc ((pglob->gl_offs + 1) * sizeof (char *));
548 if (pglob->gl_pathv == NULL)
551 for (i = 0; i <= pglob->gl_offs; ++i)
552 pglob->gl_pathv[i] = NULL;
556 oldcount = pglob->gl_pathc + pglob->gl_offs;
558 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
560 if (dirname[1] == '\0' || dirname[1] == '/'
561 || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\'
562 && (dirname[2] == '\0' || dirname[2] == '/')))
564 /* Look up home directory. */
565 const char *home_dir = getenv ("HOME");
567 if (home_dir == NULL || home_dir[0] == '\0')
571 /* Windows NT defines HOMEDRIVE and HOMEPATH. But give preference
572 to HOME, because the user can change HOME. */
573 if (home_dir == NULL || home_dir[0] == '\0')
575 const char *home_drive = getenv ("HOMEDRIVE");
576 const char *home_path = getenv ("HOMEPATH");
578 if (home_drive != NULL && home_path != NULL)
580 size_t home_drive_len = strlen (home_drive);
581 size_t home_path_len = strlen (home_path);
582 char *mem = alloca (home_drive_len + home_path_len + 1);
584 memcpy (mem, home_drive, home_drive_len);
585 memcpy (mem + home_drive_len, home_path, home_path_len + 1);
589 home_dir = "c:/users/default"; /* poor default */
592 if (home_dir == NULL || home_dir[0] == '\0')
596 size_t buflen = GET_LOGIN_NAME_MAX () + 1;
599 /* `sysconf' does not support _SC_LOGIN_NAME_MAX. Try
602 name = __alloca (buflen);
604 success = getlogin_r (name, buflen) == 0;
608 # if defined HAVE_GETPWNAM_R || defined _LIBC
609 long int pwbuflen = GETPW_R_SIZE_MAX ();
616 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.
617 Try a moderate value. */
620 pwtmpbuf = __alloca (pwbuflen);
622 while (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
631 pwtmpbuf = extend_alloca (pwtmpbuf, pwbuflen,
635 pwtmpbuf = __alloca (pwbuflen);
643 home_dir = p->pw_dir;
646 if (home_dir == NULL || home_dir[0] == '\0')
648 if (flags & GLOB_TILDE_CHECK)
651 home_dir = "~"; /* No luck. */
653 # endif /* WINDOWS32 */
655 /* Now construct the full directory. */
656 if (dirname[1] == '\0')
659 dirlen = strlen (dirname);
664 size_t home_len = strlen (home_dir);
665 newp = __alloca (home_len + dirlen);
666 mempcpy (mempcpy (newp, home_dir, home_len),
667 &dirname[1], dirlen);
669 dirlen += home_len - 1;
671 dirname_modified = 1;
673 # if !defined _AMIGA && !defined WINDOWS32
676 char *end_name = strchr (dirname, '/');
677 const char *user_name;
678 const char *home_dir;
679 char *unescape = NULL;
681 if (!(flags & GLOB_NOESCAPE))
683 if (end_name == NULL)
685 unescape = strchr (dirname, '\\');
687 end_name = strchr (unescape, '\0');
690 unescape = memchr (dirname, '\\', end_name - dirname);
692 if (end_name == NULL)
693 user_name = dirname + 1;
697 newp = __alloca (end_name - dirname);
698 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
700 if (unescape != NULL)
702 char *p = mempcpy (newp, dirname + 1,
703 unescape - dirname - 1);
711 /* "~fo\\o\\" unescape to user_name "foo\\",
712 but "~fo\\o\\/" unescape to user_name
714 if (filename == NULL)
725 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
730 /* Look up specific user's home directory. */
733 # if defined HAVE_GETPWNAM_R || defined _LIBC
734 long int buflen = GETPW_R_SIZE_MAX ();
741 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
745 pwtmpbuf = __alloca (buflen);
747 while (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) != 0)
755 pwtmpbuf = extend_alloca (pwtmpbuf, buflen, 2 * buflen);
758 pwtmpbuf = __alloca (buflen);
763 p = getpwnam (user_name);
766 home_dir = p->pw_dir;
770 /* If we found a home directory use this. */
771 if (home_dir != NULL)
774 size_t home_len = strlen (home_dir);
775 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
776 newp = __alloca (home_len + rest_len + 1);
777 *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
778 end_name, rest_len)) = '\0';
780 dirlen = home_len + rest_len;
781 dirname_modified = 1;
784 if (flags & GLOB_TILDE_CHECK)
785 /* We have to regard it as an error if we cannot find the
789 # endif /* Not Amiga && not WINDOWS32. */
792 /* Now test whether we looked for "~" or "~NAME". In this case we
793 can give the answer now. */
794 if (filename == NULL)
799 /* Return the directory if we don't check for error or if it exists. */
800 if ((flags & GLOB_NOCHECK)
801 || (((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
802 ? ((*pglob->gl_stat) (dirname, &st) == 0
803 && S_ISDIR (st.st_mode))
804 : (__stat64 (dirname, &st64) == 0 && S_ISDIR (st64.st_mode)))))
806 int newcount = pglob->gl_pathc + pglob->gl_offs;
810 = realloc (pglob->gl_pathv, (newcount + 1 + 1) * sizeof (char *));
811 if (new_gl_pathv == NULL)
814 free (pglob->gl_pathv);
815 pglob->gl_pathv = NULL;
819 pglob->gl_pathv = new_gl_pathv;
821 if (flags & GLOB_MARK)
824 pglob->gl_pathv[newcount] = malloc (dirlen + 2);
825 if (pglob->gl_pathv[newcount] == NULL)
827 p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);
833 pglob->gl_pathv[newcount] = strdup (dirname);
834 if (pglob->gl_pathv[newcount] == NULL)
837 pglob->gl_pathv[++newcount] = NULL;
839 pglob->gl_flags = flags;
848 meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));
849 /* meta is 1 if correct glob pattern containing metacharacters.
850 If meta has bit (1 << 2) set, it means there was an unterminated
851 [ which we handle the same, using fnmatch. Broken unterminated
852 pattern bracket expressions ought to be rare enough that it is
853 not worth special casing them, fnmatch will do the right thing. */
856 /* The directory name contains metacharacters, so we
857 have to glob for the directory, and then glob for
858 the pattern in each directory found. */
861 if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\')
863 /* "foo\\/bar". Remove the final backslash from dirname
864 if it has not been quoted. */
865 char *p = (char *) &dirname[dirlen - 1];
867 while (p > dirname && p[-1] == '\\') --p;
868 if ((&dirname[dirlen] - p) & 1)
869 *(char *) &dirname[--dirlen] = '\0';
872 if (__builtin_expect ((flags & GLOB_ALTDIRFUNC) != 0, 0))
874 /* Use the alternative access functions also in the recursive
876 dirs.gl_opendir = pglob->gl_opendir;
877 dirs.gl_readdir = pglob->gl_readdir;
878 dirs.gl_closedir = pglob->gl_closedir;
879 dirs.gl_stat = pglob->gl_stat;
880 dirs.gl_lstat = pglob->gl_lstat;
883 status = glob (dirname,
884 ((flags & (GLOB_ERR | GLOB_NOESCAPE
886 | GLOB_NOSORT | GLOB_ONLYDIR),
890 if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH)
895 /* We have successfully globbed the preceding directory name.
896 For each name we found, call glob_in_dir on it and FILENAME,
897 appending the results to PGLOB. */
898 for (i = 0; i < dirs.gl_pathc; ++i)
904 /* Make globbing interruptible in the bash shell. */
905 extern int interrupt_state;
915 old_pathc = pglob->gl_pathc;
916 status = glob_in_dir (filename, dirs.gl_pathv[i],
917 ((flags | GLOB_APPEND)
918 & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),
920 if (status == GLOB_NOMATCH)
921 /* No matches in this directory. Try the next. */
932 /* Stick the directory on the front of each name. */
933 if (prefix_array (dirs.gl_pathv[i],
934 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
935 pglob->gl_pathc - old_pathc))
944 flags |= GLOB_MAGCHAR;
946 /* We have ignored the GLOB_NOCHECK flag in the `glob_in_dir' calls.
947 But if we have not found any matching entry and the GLOB_NOCHECK
948 flag was set we must return the input pattern itself. */
949 if (pglob->gl_pathc + pglob->gl_offs == oldcount)
953 if (flags & GLOB_NOCHECK)
955 int newcount = pglob->gl_pathc + pglob->gl_offs;
958 new_gl_pathv = realloc (pglob->gl_pathv,
959 (newcount + 2) * sizeof (char *));
960 if (new_gl_pathv == NULL)
965 pglob->gl_pathv = new_gl_pathv;
967 pglob->gl_pathv[newcount] = strdup (pattern);
968 if (pglob->gl_pathv[newcount] == NULL)
979 pglob->gl_pathv[newcount] = NULL;
980 pglob->gl_flags = flags;
993 int old_pathc = pglob->gl_pathc;
994 int orig_flags = flags;
998 char *p = strchr (dirname, '\\'), *q;
999 /* We need to unescape the dirname string. It is certainly
1000 allocated by alloca, as otherwise filename would be NULL
1001 or dirname wouldn't contain backslashes. */
1014 while (*p++ != '\0');
1015 dirname_modified = 1;
1017 if (dirname_modified)
1018 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
1019 status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
1022 if (status == GLOB_NOMATCH && flags != orig_flags
1023 && pglob->gl_pathc + pglob->gl_offs == oldcount)
1025 /* Make sure globfree (&dirs); is a nop. */
1026 dirs.gl_pathv = NULL;
1035 /* Stick the directory on the front of each name. */
1036 if (prefix_array (dirname,
1037 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
1038 pglob->gl_pathc - old_pathc))
1041 pglob->gl_pathc = 0;
1042 return GLOB_NOSPACE;
1047 if (flags & GLOB_MARK)
1049 /* Append slashes to directory names. */
1054 for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)
1055 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1056 ? ((*pglob->gl_stat) (pglob->gl_pathv[i], &st) == 0
1057 && S_ISDIR (st.st_mode))
1058 : (__stat64 (pglob->gl_pathv[i], &st64) == 0
1059 && S_ISDIR (st64.st_mode))))
1061 size_t len = strlen (pglob->gl_pathv[i]) + 2;
1062 char *new = realloc (pglob->gl_pathv[i], len);
1066 pglob->gl_pathc = 0;
1067 return GLOB_NOSPACE;
1069 strcpy (&new[len - 2], "/");
1070 pglob->gl_pathv[i] = new;
1074 if (!(flags & GLOB_NOSORT))
1076 /* Sort the vector. */
1077 qsort (&pglob->gl_pathv[oldcount],
1078 pglob->gl_pathc + pglob->gl_offs - oldcount,
1079 sizeof (char *), collated_compare);
1084 #if defined _LIBC && !defined glob
1085 libc_hidden_def (glob)
1089 #if !defined _LIBC || !defined GLOB_ONLY_P
1091 /* Free storage allocated in PGLOB by a previous `glob' call. */
1094 register glob_t *pglob;
1096 if (pglob->gl_pathv != NULL)
1099 for (i = 0; i < pglob->gl_pathc; ++i)
1100 if (pglob->gl_pathv[pglob->gl_offs + i] != NULL)
1101 free (pglob->gl_pathv[pglob->gl_offs + i]);
1102 free (pglob->gl_pathv);
1103 pglob->gl_pathv = NULL;
1106 #if defined _LIBC && !defined globfree
1107 libc_hidden_def (globfree)
1111 /* Do a collated comparison of A and B. */
1113 collated_compare (const void *a, const void *b)
1115 char *const *ps1 = a; char *s1 = *ps1;
1116 char *const *ps2 = b; char *s2 = *ps2;
1124 return strcoll (s1, s2);
1128 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1129 elements in place. Return nonzero if out of memory, zero if successful.
1130 A slash is inserted between DIRNAME and each elt of ARRAY,
1131 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1133 prefix_array (const char *dirname, char **array, size_t n)
1136 size_t dirlen = strlen (dirname);
1137 #if defined __MSDOS__ || defined WINDOWS32
1139 # define DIRSEP_CHAR sep_char
1141 # define DIRSEP_CHAR '/'
1144 if (dirlen == 1 && dirname[0] == '/')
1145 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1146 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1148 #if defined __MSDOS__ || defined WINDOWS32
1149 else if (dirlen > 1)
1151 if (dirname[dirlen - 1] == '/' && dirname[dirlen - 2] == ':')
1152 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1154 else if (dirname[dirlen - 1] == ':')
1156 /* DIRNAME is "d:". Use `:' instead of `/'. */
1163 for (i = 0; i < n; ++i)
1165 size_t eltlen = strlen (array[i]) + 1;
1166 char *new = malloc (dirlen + 1 + eltlen);
1175 char *endp = mempcpy (new, dirname, dirlen);
1176 *endp++ = DIRSEP_CHAR;
1177 mempcpy (endp, array[i], eltlen);
1187 /* We must not compile this function twice. */
1188 #if !defined _LIBC || !defined NO_GLOB_PATTERN_P
1190 __glob_pattern_type (pattern, quote)
1191 const char *pattern;
1194 register const char *p;
1197 for (p = pattern; *p != '\0'; ++p)
1226 /* Return nonzero if PATTERN contains any metacharacters.
1227 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
1229 __glob_pattern_p (pattern, quote)
1230 const char *pattern;
1233 return __glob_pattern_type (pattern, quote) == 1;
1236 weak_alias (__glob_pattern_p, glob_pattern_p)
1240 #endif /* !GLOB_ONLY_P */
1243 #if !defined _LIBC || !defined GLOB_ONLY_P
1244 /* We put this in a separate function mainly to allow the memory
1245 allocated with alloca to be recycled. */
1247 __attribute_noinline__
1248 link_exists2_p (const char *dir, size_t dirlen, const char *fname,
1250 # if !defined _LIBC && !HAVE_FSTATAT
1255 size_t fnamelen = strlen (fname);
1256 char *fullname = __alloca (dirlen + 1 + fnamelen + 1);
1259 mempcpy (mempcpy (mempcpy (fullname, dir, dirlen), "/", 1),
1260 fname, fnamelen + 1);
1262 # if !defined _LIBC && !HAVE_FSTATAT
1263 if (__builtin_expect ((flags & GLOB_ALTDIRFUNC) == 0, 1))
1266 return __stat64 (fullname, &st64) == 0;
1269 return (*pglob->gl_stat) (fullname, &st) == 0;
1272 /* Return true if DIR/FNAME exists. */
1274 link_exists_p (int dfd, const char *dir, size_t dirlen, const char *fname,
1275 glob_t *pglob, int flags)
1277 # if defined _LIBC || HAVE_FSTATAT
1278 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1279 return link_exists2_p (dir, dirlen, fname, pglob);
1283 return __fxstatat64 (_STAT_VER, dfd, fname, &st64, 0) == 0;
1286 return link_exists2_p (dir, dirlen, fname, pglob, flags);
1292 /* Like `glob', but PATTERN is a final pathname component,
1293 and matches are searched for in DIRECTORY.
1294 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1295 The GLOB_APPEND flag is assumed to be set (always appends). */
1297 glob_in_dir (const char *pattern, const char *directory, int flags,
1298 int (*errfunc) (const char *, int),
1301 size_t dirlen = strlen (directory);
1302 void *stream = NULL;
1305 struct globnames *next;
1309 #define INITIAL_COUNT sizeof (init_names.name) / sizeof (init_names.name[0])
1310 struct globnames init_names;
1311 struct globnames *names = &init_names;
1312 struct globnames *names_alloca = &init_names;
1314 size_t allocasize = sizeof (init_names);
1320 init_names.next = NULL;
1321 init_names.count = INITIAL_COUNT;
1323 meta = __glob_pattern_type (pattern, !(flags & GLOB_NOESCAPE));
1324 if (meta == 0 && (flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
1326 /* We need not do any tests. The PATTERN contains no meta
1327 characters and we must not return an error therefore the
1328 result will always contain exactly one name. */
1329 flags |= GLOB_NOCHECK;
1333 /* Since we use the normal file functions we can also use stat()
1334 to verify the file is there. */
1337 size_t patlen = strlen (pattern);
1338 char *fullname = __alloca (dirlen + 1 + patlen + 1);
1340 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1342 pattern, patlen + 1);
1343 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1344 ? (*pglob->gl_stat) (fullname, &st)
1345 : __stat64 (fullname, &st64)) == 0)
1346 /* We found this file to be existing. Now tell the rest
1347 of the function to copy this name into the result. */
1348 flags |= GLOB_NOCHECK;
1352 stream = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1353 ? (*pglob->gl_opendir) (directory)
1354 : opendir (directory));
1357 if (errno != ENOTDIR
1358 && ((errfunc != NULL && (*errfunc) (directory, errno))
1359 || (flags & GLOB_ERR)))
1360 return GLOB_ABORTED;
1364 int dfd = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1365 ? -1 : dirfd ((DIR *) stream));
1366 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1367 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1368 #if defined _AMIGA || defined VMS
1372 flags |= GLOB_MAGCHAR;
1378 #if defined _LIBC && !defined COMPILE_GLOB64
1382 struct dirent64 d64;
1383 char room [offsetof (struct dirent64, d_name[0])
1388 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1390 struct dirent *d32 = (*pglob->gl_readdir) (stream);
1393 CONVERT_DIRENT_DIRENT64 (&d64buf.d64, d32);
1400 d = __readdir64 (stream);
1402 struct dirent *d = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1403 ? ((struct dirent *)
1404 (*pglob->gl_readdir) (stream))
1405 : __readdir (stream));
1409 if (! REAL_DIR_ENTRY (d))
1412 /* If we shall match only directories use the information
1413 provided by the dirent call if possible. */
1414 if ((flags & GLOB_ONLYDIR) && !DIRENT_MIGHT_BE_DIR (d))
1419 if (fnmatch (pattern, name, fnm_flags) == 0)
1421 /* If the file we found is a symlink we have to
1422 make sure the target file exists. */
1423 if (!DIRENT_MIGHT_BE_SYMLINK (d)
1424 || link_exists_p (dfd, directory, dirlen, name, pglob,
1427 if (cur == names->count)
1429 struct globnames *newnames;
1430 size_t count = names->count * 2;
1431 size_t size = (sizeof (struct globnames)
1432 + ((count - INITIAL_COUNT)
1433 * sizeof (char *)));
1435 if (__libc_use_alloca (allocasize))
1436 newnames = names_alloca = __alloca (size);
1437 else if ((newnames = malloc (size))
1440 newnames->count = count;
1441 newnames->next = names;
1445 len = _D_EXACT_NAMLEN (d);
1446 names->name[cur] = malloc (len + 1);
1447 if (names->name[cur] == NULL)
1449 *((char *) mempcpy (names->name[cur++], name, len))
1458 if (nfound == 0 && (flags & GLOB_NOCHECK))
1460 size_t len = strlen (pattern);
1462 names->name[cur] = malloc (len + 1);
1463 if (names->name[cur] == NULL)
1465 *((char *) mempcpy (names->name[cur++], pattern, len)) = '\0';
1468 result = GLOB_NOMATCH;
1472 = realloc (pglob->gl_pathv,
1473 (pglob->gl_pathc + pglob->gl_offs + nfound + 1)
1477 if (new_gl_pathv == NULL)
1482 struct globnames *old = names;
1484 for (i = 0; i < cur; ++i)
1485 free (names->name[i]);
1486 names = names->next;
1487 /* NB: we will not leak memory here if we exit without
1488 freeing the current block assigned to OLD. At least
1489 the very first block is always allocated on the stack
1490 and this is the block assigned to OLD here. */
1493 assert (old == &init_names);
1497 if (old == names_alloca)
1498 names_alloca = names;
1502 result = GLOB_NOSPACE;
1508 struct globnames *old = names;
1510 for (i = 0; i < cur; ++i)
1511 new_gl_pathv[pglob->gl_offs + pglob->gl_pathc++]
1513 names = names->next;
1514 /* NB: we will not leak memory here if we exit without
1515 freeing the current block assigned to OLD. At least
1516 the very first block is always allocated on the stack
1517 and this is the block assigned to OLD here. */
1520 assert (old == &init_names);
1524 if (old == names_alloca)
1525 names_alloca = names;
1530 pglob->gl_pathv = new_gl_pathv;
1532 pglob->gl_pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
1534 pglob->gl_flags = flags;
1541 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1542 (*pglob->gl_closedir) (stream);