1 /* Copyright (C) 1991-2012 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
21 /* Don't use __attribute__ __nonnull__ in this compilation unit. Otherwise gcc
22 optimizes away the pattern == NULL || pglob == NULL tests below. */
23 #define _GL_ARG_NONNULL(params)
28 #include <sys/types.h>
32 /* Outcomment the following line for production quality code. */
33 /* #define NDEBUG 1 */
38 #include <stdio.h> /* Needed on stupid SunOS for assert. */
40 #if !defined _LIBC || !defined GLOB_ONLY_P
43 #if !defined POSIX && defined _POSIX_VERSION
47 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
57 # define __set_errno(val) errno = (val)
63 /* In GNU systems, <dirent.h> defines this macro for us. */
64 #ifndef _D_EXACT_NAMLEN
65 # define _D_EXACT_NAMLEN(dirent) strlen ((dirent)->d_name)
68 /* When used in the GNU libc the symbol _DIRENT_HAVE_D_TYPE is available
69 if the 'd_type' member for 'struct dirent' is available.
70 HAVE_STRUCT_DIRENT_D_TYPE plays the same role in GNULIB. */
71 #if defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE
72 /* True if the directory entry D must be of type T. */
73 # define DIRENT_MUST_BE(d, t) ((d)->d_type == (t))
75 /* True if the directory entry D might be a symbolic link. */
76 # define DIRENT_MIGHT_BE_SYMLINK(d) \
77 ((d)->d_type == DT_UNKNOWN || (d)->d_type == DT_LNK)
79 /* True if the directory entry D might be a directory. */
80 # define DIRENT_MIGHT_BE_DIR(d) \
81 ((d)->d_type == DT_DIR || DIRENT_MIGHT_BE_SYMLINK (d))
83 #else /* !HAVE_D_TYPE */
84 # define DIRENT_MUST_BE(d, t) false
85 # define DIRENT_MIGHT_BE_SYMLINK(d) true
86 # define DIRENT_MIGHT_BE_DIR(d) true
87 #endif /* HAVE_D_TYPE */
89 /* If the system has the 'struct dirent64' type we use it internally. */
90 #if defined _LIBC && !defined COMPILE_GLOB64
91 # if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
92 # define CONVERT_D_INO(d64, d32)
94 # define CONVERT_D_INO(d64, d32) \
95 (d64)->d_ino = (d32)->d_ino;
98 # ifdef _DIRENT_HAVE_D_TYPE
99 # define CONVERT_D_TYPE(d64, d32) \
100 (d64)->d_type = (d32)->d_type;
102 # define CONVERT_D_TYPE(d64, d32)
105 # define CONVERT_DIRENT_DIRENT64(d64, d32) \
106 memcpy ((d64)->d_name, (d32)->d_name, _D_EXACT_NAMLEN (d32) + 1); \
107 CONVERT_D_INO (d64, d32) \
108 CONVERT_D_TYPE (d64, d32)
112 #if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
113 /* Posix does not require that the d_ino field be present, and some
114 systems do not provide it. */
115 # define REAL_DIR_ENTRY(dp) 1
117 # define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
123 /* NAME_MAX is usually defined in <dirent.h> or <limits.h>. */
126 # define NAME_MAX (sizeof (((struct dirent *) 0)->d_name))
133 # define strdup(str) __strdup (str)
134 # define sysconf(id) __sysconf (id)
135 # define closedir(dir) __closedir (dir)
136 # define opendir(name) __opendir (name)
137 # define readdir(str) __readdir64 (str)
138 # define getpwnam_r(name, bufp, buf, len, res) \
139 __getpwnam_r (name, bufp, buf, len, res)
141 # define __stat64(fname, buf) __xstat64 (_STAT_VER, fname, buf)
143 # define struct_stat64 struct stat64
145 # define __stat64(fname, buf) stat (fname, buf)
146 # define __fxstatat64(_, d, f, st, flag) fstatat (d, f, st, flag)
147 # define struct_stat64 struct stat
148 # define __alloca alloca
149 # define __readdir readdir
150 # define __glob_pattern_p glob_pattern_p
155 #ifdef _SC_GETPW_R_SIZE_MAX
156 # define GETPW_R_SIZE_MAX() sysconf (_SC_GETPW_R_SIZE_MAX)
158 # define GETPW_R_SIZE_MAX() (-1)
160 #ifdef _SC_LOGIN_NAME_MAX
161 # define GET_LOGIN_NAME_MAX() sysconf (_SC_LOGIN_NAME_MAX)
163 # define GET_LOGIN_NAME_MAX() (-1)
166 static const char *next_brace_sub (const char *begin, int flags) __THROW;
168 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
170 #ifndef attribute_hidden
171 # define attribute_hidden
174 #ifndef __attribute_noinline__
175 # if __GNUC__ < 3 || (__GNUC__ == 3 && __GNUC_MINOR__ < 1)
176 # define __attribute_noinline__ /* Ignore */
178 # define __attribute_noinline__ __attribute__ ((__noinline__))
182 #if ! defined __builtin_expect && __GNUC__ < 3
183 # define __builtin_expect(expr, expected) (expr)
187 /* The results of opendir() in this file are not used with dirfd and fchdir,
188 and we do not leak fds to any single-threaded code that could use stdio,
189 therefore save some unnecessary recursion in fchdir.c and opendir_safer.c.
190 FIXME - if the kernel ever adds support for multi-thread safety for
191 avoiding standard fds, then we should use opendir_safer. */
196 /* The OS usually guarantees only one guard page at the bottom of the stack,
197 and a page size can be as small as 4096 bytes. So we cannot safely
198 allocate anything larger than 4096 bytes. Also care for the possibility
199 of a few compiler-allocated temporary stack slots. */
200 # define __libc_use_alloca(n) ((n) < 4032)
202 /* alloca is implemented with malloc, so just use malloc. */
203 # define __libc_use_alloca(n) 0
207 static int glob_in_dir (const char *pattern, const char *directory,
208 int flags, int (*errfunc) (const char *, int),
210 extern int __glob_pattern_type (const char *pattern, int quote)
213 #if !defined _LIBC || !defined GLOB_ONLY_P
214 static int prefix_array (const char *prefix, char **array, size_t n) __THROW;
215 static int collated_compare (const void *, const void *) __THROW;
218 /* Find the end of the sub-pattern in a brace expression. */
220 next_brace_sub (const char *cp, int flags)
222 unsigned int depth = 0;
224 if ((flags & GLOB_NOESCAPE) == 0 && *cp == '\\')
232 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
239 return *cp != '\0' ? cp : NULL;
242 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
244 /* Do glob searching for PATTERN, placing results in PGLOB.
245 The bits defined above may be set in FLAGS.
246 If a directory cannot be opened or read and ERRFUNC is not nil,
247 it is called with the pathname that caused the error, and the
248 'errno' value from the failing call; if it returns non-zero
249 'glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
250 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
251 Otherwise, 'glob' returns zero. */
253 #ifdef GLOB_ATTRIBUTE
256 glob (pattern, flags, errfunc, pglob)
257 const char * restrict pattern;
259 int (*errfunc) (const char *, int);
260 glob_t * restrict pglob;
262 const char *filename;
268 int dirname_modified;
271 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
273 __set_errno (EINVAL);
277 if (!(flags & GLOB_DOOFFS))
278 /* Have to do this so 'globfree' knows where to start freeing. It
279 also makes all the code that uses gl_offs simpler. */
282 if (flags & GLOB_BRACE)
286 if (flags & GLOB_NOESCAPE)
287 begin = strchr (pattern, '{');
299 if (*begin == '\\' && begin[1] != '\0')
301 else if (*begin == '{')
310 /* Allocate working buffer large enough for our work. Note that
311 we have at least an opening and closing brace. */
319 char onealt[strlen (pattern) - 1];
321 char *onealt = malloc (strlen (pattern) - 1);
324 if (!(flags & GLOB_APPEND))
327 pglob->gl_pathv = NULL;
333 /* We know the prefix for all sub-patterns. */
334 alt_start = mempcpy (onealt, pattern, begin - pattern);
336 /* Find the first sub-pattern and at the same time find the
337 rest after the closing brace. */
338 next = next_brace_sub (begin + 1, flags);
341 /* It is an invalid expression. */
345 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
348 /* Now find the end of the whole brace expression. */
352 rest = next_brace_sub (rest + 1, flags);
355 /* It is an invalid expression. */
359 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
362 /* Please note that we now can be sure the brace expression
364 rest_len = strlen (++rest) + 1;
366 /* We have a brace expression. BEGIN points to the opening {,
367 NEXT points past the terminator of the first element, and END
368 points past the final }. We will accumulate result names from
369 recursive runs for each brace alternative in the buffer using
372 if (!(flags & GLOB_APPEND))
374 /* This call is to set a new vector, so clear out the
375 vector so we can append to it. */
377 pglob->gl_pathv = NULL;
379 firstc = pglob->gl_pathc;
386 /* Construct the new glob expression. */
387 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
389 result = glob (onealt,
390 ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))
391 | GLOB_APPEND), errfunc, pglob);
393 /* If we got an error, return it. */
394 if (result && result != GLOB_NOMATCH)
399 if (!(flags & GLOB_APPEND))
408 /* We saw the last entry. */
412 next = next_brace_sub (p, flags);
413 assert (next != NULL);
420 if (pglob->gl_pathc != firstc)
421 /* We found some entries. */
423 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
428 /* Find the filename. */
429 filename = strrchr (pattern, '/');
430 #if defined __MSDOS__ || defined WINDOWS32
431 /* The case of "d:pattern". Since ':' is not allowed in
432 file names, we can safely assume that wherever it
433 happens in pattern, it signals the filename part. This
434 is so we could some day support patterns like "[a-z]:foo". */
435 if (filename == NULL)
436 filename = strchr (pattern, ':');
437 #endif /* __MSDOS__ || WINDOWS32 */
438 dirname_modified = 0;
439 if (filename == NULL)
441 /* This can mean two things: a simple name or "~name". The latter
442 case is nothing but a notation for a directory. */
443 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
446 dirlen = strlen (pattern);
448 /* Set FILENAME to NULL as a special flag. This is ugly but
449 other solutions would require much more code. We test for
450 this special case below. */
464 else if (filename == pattern
465 || (filename == pattern + 1 && pattern[0] == '\\'
466 && (flags & GLOB_NOESCAPE) == 0))
468 /* "/pattern" or "\\/pattern". */
476 dirlen = filename - pattern;
477 #if defined __MSDOS__ || defined WINDOWS32
479 || (filename > pattern + 1 && filename[-1] == ':'))
484 drive_spec = __alloca (dirlen + 1);
485 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
486 /* For now, disallow wildcards in the drive spec, to
487 prevent infinite recursion in glob. */
488 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
490 /* If this is "d:pattern", we need to copy ':' to DIRNAME
491 as well. If it's "d:/pattern", don't remove the slash
492 from "d:/", since "d:" and "d:/" are not the same.*/
495 newp = __alloca (dirlen + 1);
496 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
500 if (filename[0] == '\0'
501 #if defined __MSDOS__ || defined WINDOWS32
502 && dirname[dirlen - 1] != ':'
503 && (dirlen < 3 || dirname[dirlen - 2] != ':'
504 || dirname[dirlen - 1] != '/')
507 /* "pattern/". Expand "pattern", appending slashes. */
509 int orig_flags = flags;
511 if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\')
513 /* "pattern\\/". Remove the final backslash if it hasn't
515 char *p = (char *) &dirname[dirlen - 1];
517 while (p > dirname && p[-1] == '\\') --p;
518 if ((&dirname[dirlen] - p) & 1)
520 *(char *) &dirname[--dirlen] = '\0';
521 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
524 val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
526 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
527 | (flags & GLOB_MARK));
528 else if (val == GLOB_NOMATCH && flags != orig_flags)
530 /* Make sure globfree (&dirs); is a nop. */
531 dirs.gl_pathv = NULL;
533 oldcount = pglob->gl_pathc + pglob->gl_offs;
540 if (!(flags & GLOB_APPEND))
543 if (!(flags & GLOB_DOOFFS))
544 pglob->gl_pathv = NULL;
548 pglob->gl_pathv = malloc ((pglob->gl_offs + 1) * sizeof (char *));
549 if (pglob->gl_pathv == NULL)
552 for (i = 0; i <= pglob->gl_offs; ++i)
553 pglob->gl_pathv[i] = NULL;
557 oldcount = pglob->gl_pathc + pglob->gl_offs;
559 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
561 if (dirname[1] == '\0' || dirname[1] == '/'
562 || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\'
563 && (dirname[2] == '\0' || dirname[2] == '/')))
565 /* Look up home directory. */
566 const char *home_dir = getenv ("HOME");
568 if (home_dir == NULL || home_dir[0] == '\0')
572 /* Windows NT defines HOMEDRIVE and HOMEPATH. But give preference
573 to HOME, because the user can change HOME. */
574 if (home_dir == NULL || home_dir[0] == '\0')
576 const char *home_drive = getenv ("HOMEDRIVE");
577 const char *home_path = getenv ("HOMEPATH");
579 if (home_drive != NULL && home_path != NULL)
581 size_t home_drive_len = strlen (home_drive);
582 size_t home_path_len = strlen (home_path);
583 char *mem = alloca (home_drive_len + home_path_len + 1);
585 memcpy (mem, home_drive, home_drive_len);
586 memcpy (mem + home_drive_len, home_path, home_path_len + 1);
590 home_dir = "c:/users/default"; /* poor default */
593 if (home_dir == NULL || home_dir[0] == '\0')
597 size_t buflen = GET_LOGIN_NAME_MAX () + 1;
600 /* 'sysconf' does not support _SC_LOGIN_NAME_MAX. Try
603 name = __alloca (buflen);
605 success = getlogin_r (name, buflen) == 0;
609 # if defined HAVE_GETPWNAM_R || defined _LIBC
610 long int pwbuflen = GETPW_R_SIZE_MAX ();
617 /* 'sysconf' does not support _SC_GETPW_R_SIZE_MAX.
618 Try a moderate value. */
621 pwtmpbuf = __alloca (pwbuflen);
623 while (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
632 pwtmpbuf = extend_alloca (pwtmpbuf, pwbuflen,
636 pwtmpbuf = __alloca (pwbuflen);
644 home_dir = p->pw_dir;
647 if (home_dir == NULL || home_dir[0] == '\0')
649 if (flags & GLOB_TILDE_CHECK)
652 home_dir = "~"; /* No luck. */
654 # endif /* WINDOWS32 */
656 /* Now construct the full directory. */
657 if (dirname[1] == '\0')
660 dirlen = strlen (dirname);
665 size_t home_len = strlen (home_dir);
666 newp = __alloca (home_len + dirlen);
667 mempcpy (mempcpy (newp, home_dir, home_len),
668 &dirname[1], dirlen);
670 dirlen += home_len - 1;
672 dirname_modified = 1;
674 # if !defined _AMIGA && !defined WINDOWS32
677 char *end_name = strchr (dirname, '/');
678 const char *user_name;
679 const char *home_dir;
680 char *unescape = NULL;
682 if (!(flags & GLOB_NOESCAPE))
684 if (end_name == NULL)
686 unescape = strchr (dirname, '\\');
688 end_name = strchr (unescape, '\0');
691 unescape = memchr (dirname, '\\', end_name - dirname);
693 if (end_name == NULL)
694 user_name = dirname + 1;
698 newp = __alloca (end_name - dirname);
699 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
701 if (unescape != NULL)
703 char *p = mempcpy (newp, dirname + 1,
704 unescape - dirname - 1);
712 /* "~fo\\o\\" unescape to user_name "foo\\",
713 but "~fo\\o\\/" unescape to user_name
715 if (filename == NULL)
726 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
731 /* Look up specific user's home directory. */
734 # if defined HAVE_GETPWNAM_R || defined _LIBC
735 long int buflen = GETPW_R_SIZE_MAX ();
742 /* 'sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
746 pwtmpbuf = __alloca (buflen);
748 while (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) != 0)
756 pwtmpbuf = extend_alloca (pwtmpbuf, buflen, 2 * buflen);
759 pwtmpbuf = __alloca (buflen);
764 p = getpwnam (user_name);
767 home_dir = p->pw_dir;
771 /* If we found a home directory use this. */
772 if (home_dir != NULL)
775 size_t home_len = strlen (home_dir);
776 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
777 newp = __alloca (home_len + rest_len + 1);
778 *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
779 end_name, rest_len)) = '\0';
781 dirlen = home_len + rest_len;
782 dirname_modified = 1;
785 if (flags & GLOB_TILDE_CHECK)
786 /* We have to regard it as an error if we cannot find the
790 # endif /* Not Amiga && not WINDOWS32. */
793 /* Now test whether we looked for "~" or "~NAME". In this case we
794 can give the answer now. */
795 if (filename == NULL)
800 /* Return the directory if we don't check for error or if it exists. */
801 if ((flags & GLOB_NOCHECK)
802 || (((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
803 ? ((*pglob->gl_stat) (dirname, &st) == 0
804 && S_ISDIR (st.st_mode))
805 : (__stat64 (dirname, &st64) == 0 && S_ISDIR (st64.st_mode)))))
807 int newcount = pglob->gl_pathc + pglob->gl_offs;
811 = realloc (pglob->gl_pathv, (newcount + 1 + 1) * sizeof (char *));
812 if (new_gl_pathv == NULL)
815 free (pglob->gl_pathv);
816 pglob->gl_pathv = NULL;
820 pglob->gl_pathv = new_gl_pathv;
822 if (flags & GLOB_MARK)
825 pglob->gl_pathv[newcount] = malloc (dirlen + 2);
826 if (pglob->gl_pathv[newcount] == NULL)
828 p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);
834 pglob->gl_pathv[newcount] = strdup (dirname);
835 if (pglob->gl_pathv[newcount] == NULL)
838 pglob->gl_pathv[++newcount] = NULL;
840 pglob->gl_flags = flags;
849 meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));
850 /* meta is 1 if correct glob pattern containing metacharacters.
851 If meta has bit (1 << 2) set, it means there was an unterminated
852 [ which we handle the same, using fnmatch. Broken unterminated
853 pattern bracket expressions ought to be rare enough that it is
854 not worth special casing them, fnmatch will do the right thing. */
857 /* The directory name contains metacharacters, so we
858 have to glob for the directory, and then glob for
859 the pattern in each directory found. */
862 if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\')
864 /* "foo\\/bar". Remove the final backslash from dirname
865 if it has not been quoted. */
866 char *p = (char *) &dirname[dirlen - 1];
868 while (p > dirname && p[-1] == '\\') --p;
869 if ((&dirname[dirlen] - p) & 1)
870 *(char *) &dirname[--dirlen] = '\0';
873 if (__builtin_expect ((flags & GLOB_ALTDIRFUNC) != 0, 0))
875 /* Use the alternative access functions also in the recursive
877 dirs.gl_opendir = pglob->gl_opendir;
878 dirs.gl_readdir = pglob->gl_readdir;
879 dirs.gl_closedir = pglob->gl_closedir;
880 dirs.gl_stat = pglob->gl_stat;
881 dirs.gl_lstat = pglob->gl_lstat;
884 status = glob (dirname,
885 ((flags & (GLOB_ERR | GLOB_NOESCAPE
887 | GLOB_NOSORT | GLOB_ONLYDIR),
891 if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH)
896 /* We have successfully globbed the preceding directory name.
897 For each name we found, call glob_in_dir on it and FILENAME,
898 appending the results to PGLOB. */
899 for (i = 0; i < dirs.gl_pathc; ++i)
905 /* Make globbing interruptible in the bash shell. */
906 extern int interrupt_state;
916 old_pathc = pglob->gl_pathc;
917 status = glob_in_dir (filename, dirs.gl_pathv[i],
918 ((flags | GLOB_APPEND)
919 & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),
921 if (status == GLOB_NOMATCH)
922 /* No matches in this directory. Try the next. */
933 /* Stick the directory on the front of each name. */
934 if (prefix_array (dirs.gl_pathv[i],
935 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
936 pglob->gl_pathc - old_pathc))
945 flags |= GLOB_MAGCHAR;
947 /* We have ignored the GLOB_NOCHECK flag in the 'glob_in_dir' calls.
948 But if we have not found any matching entry and the GLOB_NOCHECK
949 flag was set we must return the input pattern itself. */
950 if (pglob->gl_pathc + pglob->gl_offs == oldcount)
954 if (flags & GLOB_NOCHECK)
956 int newcount = pglob->gl_pathc + pglob->gl_offs;
959 new_gl_pathv = realloc (pglob->gl_pathv,
960 (newcount + 2) * sizeof (char *));
961 if (new_gl_pathv == NULL)
966 pglob->gl_pathv = new_gl_pathv;
968 pglob->gl_pathv[newcount] = strdup (pattern);
969 if (pglob->gl_pathv[newcount] == NULL)
980 pglob->gl_pathv[newcount] = NULL;
981 pglob->gl_flags = flags;
994 int old_pathc = pglob->gl_pathc;
995 int orig_flags = flags;
999 char *p = strchr (dirname, '\\'), *q;
1000 /* We need to unescape the dirname string. It is certainly
1001 allocated by alloca, as otherwise filename would be NULL
1002 or dirname wouldn't contain backslashes. */
1015 while (*p++ != '\0');
1016 dirname_modified = 1;
1018 if (dirname_modified)
1019 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
1020 status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
1023 if (status == GLOB_NOMATCH && flags != orig_flags
1024 && pglob->gl_pathc + pglob->gl_offs == oldcount)
1026 /* Make sure globfree (&dirs); is a nop. */
1027 dirs.gl_pathv = NULL;
1036 /* Stick the directory on the front of each name. */
1037 if (prefix_array (dirname,
1038 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
1039 pglob->gl_pathc - old_pathc))
1042 pglob->gl_pathc = 0;
1043 return GLOB_NOSPACE;
1048 if (flags & GLOB_MARK)
1050 /* Append slashes to directory names. */
1055 for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)
1056 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1057 ? ((*pglob->gl_stat) (pglob->gl_pathv[i], &st) == 0
1058 && S_ISDIR (st.st_mode))
1059 : (__stat64 (pglob->gl_pathv[i], &st64) == 0
1060 && S_ISDIR (st64.st_mode))))
1062 size_t len = strlen (pglob->gl_pathv[i]) + 2;
1063 char *new = realloc (pglob->gl_pathv[i], len);
1067 pglob->gl_pathc = 0;
1068 return GLOB_NOSPACE;
1070 strcpy (&new[len - 2], "/");
1071 pglob->gl_pathv[i] = new;
1075 if (!(flags & GLOB_NOSORT))
1077 /* Sort the vector. */
1078 qsort (&pglob->gl_pathv[oldcount],
1079 pglob->gl_pathc + pglob->gl_offs - oldcount,
1080 sizeof (char *), collated_compare);
1085 #if defined _LIBC && !defined glob
1086 libc_hidden_def (glob)
1090 #if !defined _LIBC || !defined GLOB_ONLY_P
1092 /* Free storage allocated in PGLOB by a previous 'glob' call. */
1095 register glob_t *pglob;
1097 if (pglob->gl_pathv != NULL)
1100 for (i = 0; i < pglob->gl_pathc; ++i)
1101 if (pglob->gl_pathv[pglob->gl_offs + i] != NULL)
1102 free (pglob->gl_pathv[pglob->gl_offs + i]);
1103 free (pglob->gl_pathv);
1104 pglob->gl_pathv = NULL;
1107 #if defined _LIBC && !defined globfree
1108 libc_hidden_def (globfree)
1112 /* Do a collated comparison of A and B. */
1114 collated_compare (const void *a, const void *b)
1116 char *const *ps1 = a; char *s1 = *ps1;
1117 char *const *ps2 = b; char *s2 = *ps2;
1125 return strcoll (s1, s2);
1129 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1130 elements in place. Return nonzero if out of memory, zero if successful.
1131 A slash is inserted between DIRNAME and each elt of ARRAY,
1132 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1134 prefix_array (const char *dirname, char **array, size_t n)
1137 size_t dirlen = strlen (dirname);
1138 #if defined __MSDOS__ || defined WINDOWS32
1140 # define DIRSEP_CHAR sep_char
1142 # define DIRSEP_CHAR '/'
1145 if (dirlen == 1 && dirname[0] == '/')
1146 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1147 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1149 #if defined __MSDOS__ || defined WINDOWS32
1150 else if (dirlen > 1)
1152 if (dirname[dirlen - 1] == '/' && dirname[dirlen - 2] == ':')
1153 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1155 else if (dirname[dirlen - 1] == ':')
1157 /* DIRNAME is "d:". Use ':' instead of '/'. */
1164 for (i = 0; i < n; ++i)
1166 size_t eltlen = strlen (array[i]) + 1;
1167 char *new = malloc (dirlen + 1 + eltlen);
1176 char *endp = mempcpy (new, dirname, dirlen);
1177 *endp++ = DIRSEP_CHAR;
1178 mempcpy (endp, array[i], eltlen);
1188 /* We must not compile this function twice. */
1189 #if !defined _LIBC || !defined NO_GLOB_PATTERN_P
1191 __glob_pattern_type (pattern, quote)
1192 const char *pattern;
1195 register const char *p;
1198 for (p = pattern; *p != '\0'; ++p)
1227 /* Return nonzero if PATTERN contains any metacharacters.
1228 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
1230 __glob_pattern_p (pattern, quote)
1231 const char *pattern;
1234 return __glob_pattern_type (pattern, quote) == 1;
1237 weak_alias (__glob_pattern_p, glob_pattern_p)
1241 #endif /* !GLOB_ONLY_P */
1244 #if !defined _LIBC || !defined GLOB_ONLY_P
1245 /* We put this in a separate function mainly to allow the memory
1246 allocated with alloca to be recycled. */
1248 __attribute_noinline__
1249 link_exists2_p (const char *dir, size_t dirlen, const char *fname,
1251 # if !defined _LIBC && !HAVE_FSTATAT
1256 size_t fnamelen = strlen (fname);
1257 char *fullname = __alloca (dirlen + 1 + fnamelen + 1);
1260 mempcpy (mempcpy (mempcpy (fullname, dir, dirlen), "/", 1),
1261 fname, fnamelen + 1);
1263 # if !defined _LIBC && !HAVE_FSTATAT
1264 if (__builtin_expect ((flags & GLOB_ALTDIRFUNC) == 0, 1))
1267 return __stat64 (fullname, &st64) == 0;
1270 return (*pglob->gl_stat) (fullname, &st) == 0;
1273 /* Return true if DIR/FNAME exists. */
1275 link_exists_p (int dfd, const char *dir, size_t dirlen, const char *fname,
1276 glob_t *pglob, int flags)
1278 # if defined _LIBC || HAVE_FSTATAT
1279 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1280 return link_exists2_p (dir, dirlen, fname, pglob);
1283 /* dfd cannot be -1 here, because dirfd never returns -1 on
1284 glibc, or on hosts that have fstatat. */
1286 return __fxstatat64 (_STAT_VER, dfd, fname, &st64, 0) == 0;
1289 return link_exists2_p (dir, dirlen, fname, pglob, flags);
1295 /* Like 'glob', but PATTERN is a final pathname component,
1296 and matches are searched for in DIRECTORY.
1297 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1298 The GLOB_APPEND flag is assumed to be set (always appends). */
1300 glob_in_dir (const char *pattern, const char *directory, int flags,
1301 int (*errfunc) (const char *, int),
1304 size_t dirlen = strlen (directory);
1305 void *stream = NULL;
1308 struct globnames *next;
1312 #define INITIAL_COUNT sizeof (init_names.name) / sizeof (init_names.name[0])
1313 struct globnames init_names;
1314 struct globnames *names = &init_names;
1315 struct globnames *names_alloca = &init_names;
1317 size_t allocasize = sizeof (init_names);
1323 init_names.next = NULL;
1324 init_names.count = INITIAL_COUNT;
1326 meta = __glob_pattern_type (pattern, !(flags & GLOB_NOESCAPE));
1327 if (meta == 0 && (flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
1329 /* We need not do any tests. The PATTERN contains no meta
1330 characters and we must not return an error therefore the
1331 result will always contain exactly one name. */
1332 flags |= GLOB_NOCHECK;
1336 /* Since we use the normal file functions we can also use stat()
1337 to verify the file is there. */
1340 size_t patlen = strlen (pattern);
1341 char *fullname = __alloca (dirlen + 1 + patlen + 1);
1343 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1345 pattern, patlen + 1);
1346 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1347 ? (*pglob->gl_stat) (fullname, &st)
1348 : __stat64 (fullname, &st64)) == 0)
1349 /* We found this file to be existing. Now tell the rest
1350 of the function to copy this name into the result. */
1351 flags |= GLOB_NOCHECK;
1355 stream = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1356 ? (*pglob->gl_opendir) (directory)
1357 : opendir (directory));
1360 if (errno != ENOTDIR
1361 && ((errfunc != NULL && (*errfunc) (directory, errno))
1362 || (flags & GLOB_ERR)))
1363 return GLOB_ABORTED;
1367 int dfd = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1368 ? -1 : dirfd ((DIR *) stream));
1369 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1370 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1371 #if defined _AMIGA || defined VMS
1375 flags |= GLOB_MAGCHAR;
1381 #if defined _LIBC && !defined COMPILE_GLOB64
1385 struct dirent64 d64;
1386 char room [offsetof (struct dirent64, d_name[0])
1391 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1393 struct dirent *d32 = (*pglob->gl_readdir) (stream);
1396 CONVERT_DIRENT_DIRENT64 (&d64buf.d64, d32);
1403 d = __readdir64 (stream);
1405 struct dirent *d = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1406 ? ((struct dirent *)
1407 (*pglob->gl_readdir) (stream))
1408 : __readdir (stream));
1412 if (! REAL_DIR_ENTRY (d))
1415 /* If we shall match only directories use the information
1416 provided by the dirent call if possible. */
1417 if ((flags & GLOB_ONLYDIR) && !DIRENT_MIGHT_BE_DIR (d))
1422 if (fnmatch (pattern, name, fnm_flags) == 0)
1424 /* If the file we found is a symlink we have to
1425 make sure the target file exists. */
1426 if (!DIRENT_MIGHT_BE_SYMLINK (d)
1427 || link_exists_p (dfd, directory, dirlen, name, pglob,
1430 if (cur == names->count)
1432 struct globnames *newnames;
1433 size_t count = names->count * 2;
1434 size_t size = (sizeof (struct globnames)
1435 + ((count - INITIAL_COUNT)
1436 * sizeof (char *)));
1438 if (__libc_use_alloca (allocasize))
1439 newnames = names_alloca = __alloca (size);
1440 else if ((newnames = malloc (size))
1443 newnames->count = count;
1444 newnames->next = names;
1448 len = _D_EXACT_NAMLEN (d);
1449 names->name[cur] = malloc (len + 1);
1450 if (names->name[cur] == NULL)
1452 *((char *) mempcpy (names->name[cur++], name, len))
1461 if (nfound == 0 && (flags & GLOB_NOCHECK))
1463 size_t len = strlen (pattern);
1465 names->name[cur] = malloc (len + 1);
1466 if (names->name[cur] == NULL)
1468 *((char *) mempcpy (names->name[cur++], pattern, len)) = '\0';
1471 result = GLOB_NOMATCH;
1475 = realloc (pglob->gl_pathv,
1476 (pglob->gl_pathc + pglob->gl_offs + nfound + 1)
1480 if (new_gl_pathv == NULL)
1485 struct globnames *old = names;
1487 for (i = 0; i < cur; ++i)
1488 free (names->name[i]);
1489 names = names->next;
1490 /* NB: we will not leak memory here if we exit without
1491 freeing the current block assigned to OLD. At least
1492 the very first block is always allocated on the stack
1493 and this is the block assigned to OLD here. */
1496 assert (old == &init_names);
1500 if (old == names_alloca)
1501 names_alloca = names;
1505 result = GLOB_NOSPACE;
1511 struct globnames *old = names;
1513 for (i = 0; i < cur; ++i)
1514 new_gl_pathv[pglob->gl_offs + pglob->gl_pathc++]
1516 names = names->next;
1517 /* NB: we will not leak memory here if we exit without
1518 freeing the current block assigned to OLD. At least
1519 the very first block is always allocated on the stack
1520 and this is the block assigned to OLD here. */
1523 assert (old == &init_names);
1527 if (old == names_alloca)
1528 names_alloca = names;
1533 pglob->gl_pathv = new_gl_pathv;
1535 pglob->gl_pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
1537 pglob->gl_flags = flags;
1544 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1545 (*pglob->gl_closedir) (stream);