1 /* Copyright (C) 1991-2011 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 __stat(fname, buf) stat (fname, buf)
149 # define __alloca alloca
150 # define __readdir readdir
151 # define __readdir64 readdir64
152 # define __glob_pattern_p glob_pattern_p
157 #ifdef _SC_GETPW_R_SIZE_MAX
158 # define GETPW_R_SIZE_MAX() sysconf (_SC_GETPW_R_SIZE_MAX)
160 # define GETPW_R_SIZE_MAX() (-1)
162 #ifdef _SC_LOGIN_NAME_MAX
163 # define GET_LOGIN_NAME_MAX() sysconf (_SC_LOGIN_NAME_MAX)
165 # define GET_LOGIN_NAME_MAX() (-1)
168 static const char *next_brace_sub (const char *begin, int flags) __THROW;
170 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
172 #ifndef attribute_hidden
173 # define attribute_hidden
176 #ifndef __attribute_noinline__
177 # if __GNUC__ < 3 || (__GNUC__ == 3 && __GNUC_MINOR__ < 1)
178 # define __attribute_noinline__ /* Ignore */
180 # define __attribute_noinline__ __attribute__ ((__noinline__))
184 #if ! defined __builtin_expect && __GNUC__ < 3
185 # define __builtin_expect(expr, expected) (expr)
189 /* The results of opendir() in this file are not used with dirfd and fchdir,
190 and we do not leak fds to any single-threaded code that could use stdio,
191 therefore save some unnecessary recursion in fchdir.c and opendir_safer.c.
192 FIXME - if the kernel ever adds support for multi-thread safety for
193 avoiding standard fds, then we should use opendir_safer. */
198 /* The OS usually guarantees only one guard page at the bottom of the stack,
199 and a page size can be as small as 4096 bytes. So we cannot safely
200 allocate anything larger than 4096 bytes. Also care for the possibility
201 of a few compiler-allocated temporary stack slots. */
202 # define __libc_use_alloca(n) ((n) < 4032)
204 /* alloca is implemented with malloc, so just use malloc. */
205 # define __libc_use_alloca(n) 0
209 static int glob_in_dir (const char *pattern, const char *directory,
210 int flags, int (*errfunc) (const char *, int),
212 extern int __glob_pattern_type (const char *pattern, int quote)
215 #if !defined _LIBC || !defined GLOB_ONLY_P
216 static int prefix_array (const char *prefix, char **array, size_t n) __THROW;
217 static int collated_compare (const void *, const void *) __THROW;
220 /* Find the end of the sub-pattern in a brace expression. */
222 next_brace_sub (const char *cp, int flags)
224 unsigned int depth = 0;
226 if ((flags & GLOB_NOESCAPE) == 0 && *cp == '\\')
234 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
241 return *cp != '\0' ? cp : NULL;
244 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
246 /* Do glob searching for PATTERN, placing results in PGLOB.
247 The bits defined above may be set in FLAGS.
248 If a directory cannot be opened or read and ERRFUNC is not nil,
249 it is called with the pathname that caused the error, and the
250 `errno' value from the failing call; if it returns non-zero
251 `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
252 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
253 Otherwise, `glob' returns zero. */
255 #ifdef GLOB_ATTRIBUTE
258 glob (pattern, flags, errfunc, pglob)
259 const char * restrict pattern;
261 int (*errfunc) (const char *, int);
262 glob_t * restrict pglob;
264 const char *filename;
270 int dirname_modified;
273 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
275 __set_errno (EINVAL);
279 if (!(flags & GLOB_DOOFFS))
280 /* Have to do this so `globfree' knows where to start freeing. It
281 also makes all the code that uses gl_offs simpler. */
284 if (flags & GLOB_BRACE)
288 if (flags & GLOB_NOESCAPE)
289 begin = strchr (pattern, '{');
301 if (*begin == '\\' && begin[1] != '\0')
303 else if (*begin == '{')
312 /* Allocate working buffer large enough for our work. Note that
313 we have at least an opening and closing brace. */
321 char onealt[strlen (pattern) - 1];
323 char *onealt = malloc (strlen (pattern) - 1);
326 if (!(flags & GLOB_APPEND))
329 pglob->gl_pathv = NULL;
335 /* We know the prefix for all sub-patterns. */
336 alt_start = mempcpy (onealt, pattern, begin - pattern);
338 /* Find the first sub-pattern and at the same time find the
339 rest after the closing brace. */
340 next = next_brace_sub (begin + 1, flags);
343 /* It is an invalid expression. */
347 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
350 /* Now find the end of the whole brace expression. */
354 rest = next_brace_sub (rest + 1, flags);
357 /* It is an invalid expression. */
361 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
364 /* Please note that we now can be sure the brace expression
366 rest_len = strlen (++rest) + 1;
368 /* We have a brace expression. BEGIN points to the opening {,
369 NEXT points past the terminator of the first element, and END
370 points past the final }. We will accumulate result names from
371 recursive runs for each brace alternative in the buffer using
374 if (!(flags & GLOB_APPEND))
376 /* This call is to set a new vector, so clear out the
377 vector so we can append to it. */
379 pglob->gl_pathv = NULL;
381 firstc = pglob->gl_pathc;
388 /* Construct the new glob expression. */
389 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
391 result = glob (onealt,
392 ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))
393 | GLOB_APPEND), errfunc, pglob);
395 /* If we got an error, return it. */
396 if (result && result != GLOB_NOMATCH)
401 if (!(flags & GLOB_APPEND))
410 /* We saw the last entry. */
414 next = next_brace_sub (p, flags);
415 assert (next != NULL);
422 if (pglob->gl_pathc != firstc)
423 /* We found some entries. */
425 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
430 /* Find the filename. */
431 filename = strrchr (pattern, '/');
432 #if defined __MSDOS__ || defined WINDOWS32
433 /* The case of "d:pattern". Since `:' is not allowed in
434 file names, we can safely assume that wherever it
435 happens in pattern, it signals the filename part. This
436 is so we could some day support patterns like "[a-z]:foo". */
437 if (filename == NULL)
438 filename = strchr (pattern, ':');
439 #endif /* __MSDOS__ || WINDOWS32 */
440 dirname_modified = 0;
441 if (filename == NULL)
443 /* This can mean two things: a simple name or "~name". The latter
444 case is nothing but a notation for a directory. */
445 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
448 dirlen = strlen (pattern);
450 /* Set FILENAME to NULL as a special flag. This is ugly but
451 other solutions would require much more code. We test for
452 this special case below. */
466 else if (filename == pattern
467 || (filename == pattern + 1 && pattern[0] == '\\'
468 && (flags & GLOB_NOESCAPE) == 0))
470 /* "/pattern" or "\\/pattern". */
478 dirlen = filename - pattern;
479 #if defined __MSDOS__ || defined WINDOWS32
481 || (filename > pattern + 1 && filename[-1] == ':'))
486 drive_spec = __alloca (dirlen + 1);
487 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
488 /* For now, disallow wildcards in the drive spec, to
489 prevent infinite recursion in glob. */
490 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
492 /* If this is "d:pattern", we need to copy `:' to DIRNAME
493 as well. If it's "d:/pattern", don't remove the slash
494 from "d:/", since "d:" and "d:/" are not the same.*/
497 newp = __alloca (dirlen + 1);
498 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
502 if (filename[0] == '\0'
503 #if defined __MSDOS__ || defined WINDOWS32
504 && dirname[dirlen - 1] != ':'
505 && (dirlen < 3 || dirname[dirlen - 2] != ':'
506 || dirname[dirlen - 1] != '/')
509 /* "pattern/". Expand "pattern", appending slashes. */
511 int orig_flags = flags;
513 if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\')
515 /* "pattern\\/". Remove the final backslash if it hasn't
517 char *p = (char *) &dirname[dirlen - 1];
519 while (p > dirname && p[-1] == '\\') --p;
520 if ((&dirname[dirlen] - p) & 1)
522 *(char *) &dirname[--dirlen] = '\0';
523 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
526 val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
528 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
529 | (flags & GLOB_MARK));
530 else if (val == GLOB_NOMATCH && flags != orig_flags)
532 /* Make sure globfree (&dirs); is a nop. */
533 dirs.gl_pathv = NULL;
535 oldcount = pglob->gl_pathc + pglob->gl_offs;
542 if (!(flags & GLOB_APPEND))
545 if (!(flags & GLOB_DOOFFS))
546 pglob->gl_pathv = NULL;
550 pglob->gl_pathv = malloc ((pglob->gl_offs + 1) * sizeof (char *));
551 if (pglob->gl_pathv == NULL)
554 for (i = 0; i <= pglob->gl_offs; ++i)
555 pglob->gl_pathv[i] = NULL;
559 oldcount = pglob->gl_pathc + pglob->gl_offs;
561 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
563 if (dirname[1] == '\0' || dirname[1] == '/'
564 || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\'
565 && (dirname[2] == '\0' || dirname[2] == '/')))
567 /* Look up home directory. */
568 const char *home_dir = getenv ("HOME");
570 if (home_dir == NULL || home_dir[0] == '\0')
574 /* Windows NT defines HOMEDRIVE and HOMEPATH. But give preference
575 to HOME, because the user can change HOME. */
576 if (home_dir == NULL || home_dir[0] == '\0')
578 const char *home_drive = getenv ("HOMEDRIVE");
579 const char *home_path = getenv ("HOMEPATH");
581 if (home_drive != NULL && home_path != NULL)
583 size_t home_drive_len = strlen (home_drive);
584 size_t home_path_len = strlen (home_path);
585 char *mem = alloca (home_drive_len + home_path_len + 1);
587 memcpy (mem, home_drive, home_drive_len);
588 memcpy (mem + home_drive_len, home_path, home_path_len + 1);
592 home_dir = "c:/users/default"; /* poor default */
595 if (home_dir == NULL || home_dir[0] == '\0')
599 size_t buflen = GET_LOGIN_NAME_MAX () + 1;
602 /* `sysconf' does not support _SC_LOGIN_NAME_MAX. Try
605 name = __alloca (buflen);
607 success = getlogin_r (name, buflen) == 0;
611 # if defined HAVE_GETPWNAM_R || defined _LIBC
612 long int pwbuflen = GETPW_R_SIZE_MAX ();
619 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.
620 Try a moderate value. */
623 pwtmpbuf = __alloca (pwbuflen);
625 while (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
634 pwtmpbuf = extend_alloca (pwtmpbuf, pwbuflen,
638 pwtmpbuf = __alloca (pwbuflen);
646 home_dir = p->pw_dir;
649 if (home_dir == NULL || home_dir[0] == '\0')
651 if (flags & GLOB_TILDE_CHECK)
654 home_dir = "~"; /* No luck. */
656 # endif /* WINDOWS32 */
658 /* Now construct the full directory. */
659 if (dirname[1] == '\0')
662 dirlen = strlen (dirname);
667 size_t home_len = strlen (home_dir);
668 newp = __alloca (home_len + dirlen);
669 mempcpy (mempcpy (newp, home_dir, home_len),
670 &dirname[1], dirlen);
672 dirlen += home_len - 1;
674 dirname_modified = 1;
676 # if !defined _AMIGA && !defined WINDOWS32
679 char *end_name = strchr (dirname, '/');
680 const char *user_name;
681 const char *home_dir;
682 char *unescape = NULL;
684 if (!(flags & GLOB_NOESCAPE))
686 if (end_name == NULL)
688 unescape = strchr (dirname, '\\');
690 end_name = strchr (unescape, '\0');
693 unescape = memchr (dirname, '\\', end_name - dirname);
695 if (end_name == NULL)
696 user_name = dirname + 1;
700 newp = __alloca (end_name - dirname);
701 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
703 if (unescape != NULL)
705 char *p = mempcpy (newp, dirname + 1,
706 unescape - dirname - 1);
714 /* "~fo\\o\\" unescape to user_name "foo\\",
715 but "~fo\\o\\/" unescape to user_name
717 if (filename == NULL)
728 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
733 /* Look up specific user's home directory. */
736 # if defined HAVE_GETPWNAM_R || defined _LIBC
737 long int buflen = GETPW_R_SIZE_MAX ();
744 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
748 pwtmpbuf = __alloca (buflen);
750 while (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) != 0)
758 pwtmpbuf = extend_alloca (pwtmpbuf, buflen, 2 * buflen);
761 pwtmpbuf = __alloca (buflen);
766 p = getpwnam (user_name);
769 home_dir = p->pw_dir;
773 /* If we found a home directory use this. */
774 if (home_dir != NULL)
777 size_t home_len = strlen (home_dir);
778 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
779 newp = __alloca (home_len + rest_len + 1);
780 *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
781 end_name, rest_len)) = '\0';
783 dirlen = home_len + rest_len;
784 dirname_modified = 1;
787 if (flags & GLOB_TILDE_CHECK)
788 /* We have to regard it as an error if we cannot find the
792 # endif /* Not Amiga && not WINDOWS32. */
795 /* Now test whether we looked for "~" or "~NAME". In this case we
796 can give the answer now. */
797 if (filename == NULL)
802 /* Return the directory if we don't check for error or if it exists. */
803 if ((flags & GLOB_NOCHECK)
804 || (((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
805 ? ((*pglob->gl_stat) (dirname, &st) == 0
806 && S_ISDIR (st.st_mode))
807 : (__stat64 (dirname, &st64) == 0 && S_ISDIR (st64.st_mode)))))
809 int newcount = pglob->gl_pathc + pglob->gl_offs;
813 = realloc (pglob->gl_pathv, (newcount + 1 + 1) * sizeof (char *));
814 if (new_gl_pathv == NULL)
817 free (pglob->gl_pathv);
818 pglob->gl_pathv = NULL;
822 pglob->gl_pathv = new_gl_pathv;
824 if (flags & GLOB_MARK)
827 pglob->gl_pathv[newcount] = malloc (dirlen + 2);
828 if (pglob->gl_pathv[newcount] == NULL)
830 p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);
836 pglob->gl_pathv[newcount] = strdup (dirname);
837 if (pglob->gl_pathv[newcount] == NULL)
840 pglob->gl_pathv[++newcount] = NULL;
842 pglob->gl_flags = flags;
851 meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));
852 /* meta is 1 if correct glob pattern containing metacharacters.
853 If meta has bit (1 << 2) set, it means there was an unterminated
854 [ which we handle the same, using fnmatch. Broken unterminated
855 pattern bracket expressions ought to be rare enough that it is
856 not worth special casing them, fnmatch will do the right thing. */
859 /* The directory name contains metacharacters, so we
860 have to glob for the directory, and then glob for
861 the pattern in each directory found. */
864 if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\')
866 /* "foo\\/bar". Remove the final backslash from dirname
867 if it has not been quoted. */
868 char *p = (char *) &dirname[dirlen - 1];
870 while (p > dirname && p[-1] == '\\') --p;
871 if ((&dirname[dirlen] - p) & 1)
872 *(char *) &dirname[--dirlen] = '\0';
875 if (__builtin_expect ((flags & GLOB_ALTDIRFUNC) != 0, 0))
877 /* Use the alternative access functions also in the recursive
879 dirs.gl_opendir = pglob->gl_opendir;
880 dirs.gl_readdir = pglob->gl_readdir;
881 dirs.gl_closedir = pglob->gl_closedir;
882 dirs.gl_stat = pglob->gl_stat;
883 dirs.gl_lstat = pglob->gl_lstat;
886 status = glob (dirname,
887 ((flags & (GLOB_ERR | GLOB_NOESCAPE
889 | GLOB_NOSORT | GLOB_ONLYDIR),
893 if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH)
898 /* We have successfully globbed the preceding directory name.
899 For each name we found, call glob_in_dir on it and FILENAME,
900 appending the results to PGLOB. */
901 for (i = 0; i < dirs.gl_pathc; ++i)
907 /* Make globbing interruptible in the bash shell. */
908 extern int interrupt_state;
918 old_pathc = pglob->gl_pathc;
919 status = glob_in_dir (filename, dirs.gl_pathv[i],
920 ((flags | GLOB_APPEND)
921 & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),
923 if (status == GLOB_NOMATCH)
924 /* No matches in this directory. Try the next. */
935 /* Stick the directory on the front of each name. */
936 if (prefix_array (dirs.gl_pathv[i],
937 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
938 pglob->gl_pathc - old_pathc))
947 flags |= GLOB_MAGCHAR;
949 /* We have ignored the GLOB_NOCHECK flag in the `glob_in_dir' calls.
950 But if we have not found any matching entry and the GLOB_NOCHECK
951 flag was set we must return the input pattern itself. */
952 if (pglob->gl_pathc + pglob->gl_offs == oldcount)
956 if (flags & GLOB_NOCHECK)
958 int newcount = pglob->gl_pathc + pglob->gl_offs;
961 new_gl_pathv = realloc (pglob->gl_pathv,
962 (newcount + 2) * sizeof (char *));
963 if (new_gl_pathv == NULL)
968 pglob->gl_pathv = new_gl_pathv;
970 pglob->gl_pathv[newcount] = strdup (pattern);
971 if (pglob->gl_pathv[newcount] == NULL)
982 pglob->gl_pathv[newcount] = NULL;
983 pglob->gl_flags = flags;
996 int old_pathc = pglob->gl_pathc;
997 int orig_flags = flags;
1001 char *p = strchr (dirname, '\\'), *q;
1002 /* We need to unescape the dirname string. It is certainly
1003 allocated by alloca, as otherwise filename would be NULL
1004 or dirname wouldn't contain backslashes. */
1017 while (*p++ != '\0');
1018 dirname_modified = 1;
1020 if (dirname_modified)
1021 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
1022 status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
1025 if (status == GLOB_NOMATCH && flags != orig_flags
1026 && pglob->gl_pathc + pglob->gl_offs == oldcount)
1028 /* Make sure globfree (&dirs); is a nop. */
1029 dirs.gl_pathv = NULL;
1038 /* Stick the directory on the front of each name. */
1039 if (prefix_array (dirname,
1040 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
1041 pglob->gl_pathc - old_pathc))
1044 pglob->gl_pathc = 0;
1045 return GLOB_NOSPACE;
1050 if (flags & GLOB_MARK)
1052 /* Append slashes to directory names. */
1057 for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)
1058 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1059 ? ((*pglob->gl_stat) (pglob->gl_pathv[i], &st) == 0
1060 && S_ISDIR (st.st_mode))
1061 : (__stat64 (pglob->gl_pathv[i], &st64) == 0
1062 && S_ISDIR (st64.st_mode))))
1064 size_t len = strlen (pglob->gl_pathv[i]) + 2;
1065 char *new = realloc (pglob->gl_pathv[i], len);
1069 pglob->gl_pathc = 0;
1070 return GLOB_NOSPACE;
1072 strcpy (&new[len - 2], "/");
1073 pglob->gl_pathv[i] = new;
1077 if (!(flags & GLOB_NOSORT))
1079 /* Sort the vector. */
1080 qsort (&pglob->gl_pathv[oldcount],
1081 pglob->gl_pathc + pglob->gl_offs - oldcount,
1082 sizeof (char *), collated_compare);
1087 #if defined _LIBC && !defined glob
1088 libc_hidden_def (glob)
1092 #if !defined _LIBC || !defined GLOB_ONLY_P
1094 /* Free storage allocated in PGLOB by a previous `glob' call. */
1097 register glob_t *pglob;
1099 if (pglob->gl_pathv != NULL)
1102 for (i = 0; i < pglob->gl_pathc; ++i)
1103 if (pglob->gl_pathv[pglob->gl_offs + i] != NULL)
1104 free (pglob->gl_pathv[pglob->gl_offs + i]);
1105 free (pglob->gl_pathv);
1106 pglob->gl_pathv = NULL;
1109 #if defined _LIBC && !defined globfree
1110 libc_hidden_def (globfree)
1114 /* Do a collated comparison of A and B. */
1116 collated_compare (const void *a, const void *b)
1118 char *const *ps1 = a; char *s1 = *ps1;
1119 char *const *ps2 = b; char *s2 = *ps2;
1127 return strcoll (s1, s2);
1131 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1132 elements in place. Return nonzero if out of memory, zero if successful.
1133 A slash is inserted between DIRNAME and each elt of ARRAY,
1134 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1136 prefix_array (const char *dirname, char **array, size_t n)
1139 size_t dirlen = strlen (dirname);
1140 #if defined __MSDOS__ || defined WINDOWS32
1142 # define DIRSEP_CHAR sep_char
1144 # define DIRSEP_CHAR '/'
1147 if (dirlen == 1 && dirname[0] == '/')
1148 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1149 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1151 #if defined __MSDOS__ || defined WINDOWS32
1152 else if (dirlen > 1)
1154 if (dirname[dirlen - 1] == '/' && dirname[dirlen - 2] == ':')
1155 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1157 else if (dirname[dirlen - 1] == ':')
1159 /* DIRNAME is "d:". Use `:' instead of `/'. */
1166 for (i = 0; i < n; ++i)
1168 size_t eltlen = strlen (array[i]) + 1;
1169 char *new = malloc (dirlen + 1 + eltlen);
1178 char *endp = mempcpy (new, dirname, dirlen);
1179 *endp++ = DIRSEP_CHAR;
1180 mempcpy (endp, array[i], eltlen);
1190 /* We must not compile this function twice. */
1191 #if !defined _LIBC || !defined NO_GLOB_PATTERN_P
1193 __glob_pattern_type (pattern, quote)
1194 const char *pattern;
1197 register const char *p;
1200 for (p = pattern; *p != '\0'; ++p)
1229 /* Return nonzero if PATTERN contains any metacharacters.
1230 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
1232 __glob_pattern_p (pattern, quote)
1233 const char *pattern;
1236 return __glob_pattern_type (pattern, quote) == 1;
1239 weak_alias (__glob_pattern_p, glob_pattern_p)
1243 #endif /* !GLOB_ONLY_P */
1246 #if !defined _LIBC || !defined GLOB_ONLY_P
1247 /* We put this in a separate function mainly to allow the memory
1248 allocated with alloca to be recycled. */
1250 __attribute_noinline__
1251 link_exists2_p (const char *dir, size_t dirlen, const char *fname,
1253 # if !defined _LIBC && !HAVE_FSTATAT
1258 size_t fnamelen = strlen (fname);
1259 char *fullname = __alloca (dirlen + 1 + fnamelen + 1);
1262 mempcpy (mempcpy (mempcpy (fullname, dir, dirlen), "/", 1),
1263 fname, fnamelen + 1);
1265 # if !defined _LIBC && !HAVE_FSTATAT
1266 if (__builtin_expect ((flags & GLOB_ALTDIRFUNC) == 0, 1))
1269 return __stat64 (fullname, &st64) == 0;
1272 return (*pglob->gl_stat) (fullname, &st) == 0;
1275 /* Return true if DIR/FNAME exists. */
1277 link_exists_p (int dfd, const char *dir, size_t dirlen, const char *fname,
1278 glob_t *pglob, int flags)
1280 # if defined _LIBC || HAVE_FSTATAT
1281 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1282 return link_exists2_p (dir, dirlen, fname, pglob);
1285 /* dfd cannot be -1 here, because dirfd never returns -1 on
1286 glibc, or on hosts that have fstatat. */
1288 return __fxstatat64 (_STAT_VER, dfd, fname, &st64, 0) == 0;
1291 return link_exists2_p (dir, dirlen, fname, pglob, flags);
1297 /* Like `glob', but PATTERN is a final pathname component,
1298 and matches are searched for in DIRECTORY.
1299 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1300 The GLOB_APPEND flag is assumed to be set (always appends). */
1302 glob_in_dir (const char *pattern, const char *directory, int flags,
1303 int (*errfunc) (const char *, int),
1306 size_t dirlen = strlen (directory);
1307 void *stream = NULL;
1310 struct globnames *next;
1314 #define INITIAL_COUNT sizeof (init_names.name) / sizeof (init_names.name[0])
1315 struct globnames init_names;
1316 struct globnames *names = &init_names;
1317 struct globnames *names_alloca = &init_names;
1319 size_t allocasize = sizeof (init_names);
1325 init_names.next = NULL;
1326 init_names.count = INITIAL_COUNT;
1328 meta = __glob_pattern_type (pattern, !(flags & GLOB_NOESCAPE));
1329 if (meta == 0 && (flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
1331 /* We need not do any tests. The PATTERN contains no meta
1332 characters and we must not return an error therefore the
1333 result will always contain exactly one name. */
1334 flags |= GLOB_NOCHECK;
1338 /* Since we use the normal file functions we can also use stat()
1339 to verify the file is there. */
1342 size_t patlen = strlen (pattern);
1343 char *fullname = __alloca (dirlen + 1 + patlen + 1);
1345 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1347 pattern, patlen + 1);
1348 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1349 ? (*pglob->gl_stat) (fullname, &st)
1350 : __stat64 (fullname, &st64)) == 0)
1351 /* We found this file to be existing. Now tell the rest
1352 of the function to copy this name into the result. */
1353 flags |= GLOB_NOCHECK;
1357 stream = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1358 ? (*pglob->gl_opendir) (directory)
1359 : opendir (directory));
1362 if (errno != ENOTDIR
1363 && ((errfunc != NULL && (*errfunc) (directory, errno))
1364 || (flags & GLOB_ERR)))
1365 return GLOB_ABORTED;
1369 int dfd = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1370 ? -1 : dirfd ((DIR *) stream));
1371 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1372 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1373 #if defined _AMIGA || defined VMS
1377 flags |= GLOB_MAGCHAR;
1383 #if defined _LIBC && !defined COMPILE_GLOB64
1387 struct dirent64 d64;
1388 char room [offsetof (struct dirent64, d_name[0])
1393 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1395 struct dirent *d32 = (*pglob->gl_readdir) (stream);
1398 CONVERT_DIRENT_DIRENT64 (&d64buf.d64, d32);
1405 d = __readdir64 (stream);
1407 struct dirent *d = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1408 ? ((struct dirent *)
1409 (*pglob->gl_readdir) (stream))
1410 : __readdir (stream));
1414 if (! REAL_DIR_ENTRY (d))
1417 /* If we shall match only directories use the information
1418 provided by the dirent call if possible. */
1419 if ((flags & GLOB_ONLYDIR) && !DIRENT_MIGHT_BE_DIR (d))
1424 if (fnmatch (pattern, name, fnm_flags) == 0)
1426 /* If the file we found is a symlink we have to
1427 make sure the target file exists. */
1428 if (!DIRENT_MIGHT_BE_SYMLINK (d)
1429 || link_exists_p (dfd, directory, dirlen, name, pglob,
1432 if (cur == names->count)
1434 struct globnames *newnames;
1435 size_t count = names->count * 2;
1436 size_t size = (sizeof (struct globnames)
1437 + ((count - INITIAL_COUNT)
1438 * sizeof (char *)));
1440 if (__libc_use_alloca (allocasize))
1441 newnames = names_alloca = __alloca (size);
1442 else if ((newnames = malloc (size))
1445 newnames->count = count;
1446 newnames->next = names;
1450 len = _D_EXACT_NAMLEN (d);
1451 names->name[cur] = malloc (len + 1);
1452 if (names->name[cur] == NULL)
1454 *((char *) mempcpy (names->name[cur++], name, len))
1463 if (nfound == 0 && (flags & GLOB_NOCHECK))
1465 size_t len = strlen (pattern);
1467 names->name[cur] = malloc (len + 1);
1468 if (names->name[cur] == NULL)
1470 *((char *) mempcpy (names->name[cur++], pattern, len)) = '\0';
1473 result = GLOB_NOMATCH;
1477 = realloc (pglob->gl_pathv,
1478 (pglob->gl_pathc + pglob->gl_offs + nfound + 1)
1482 if (new_gl_pathv == NULL)
1487 struct globnames *old = names;
1489 for (i = 0; i < cur; ++i)
1490 free (names->name[i]);
1491 names = names->next;
1492 /* NB: we will not leak memory here if we exit without
1493 freeing the current block assigned to OLD. At least
1494 the very first block is always allocated on the stack
1495 and this is the block assigned to OLD here. */
1498 assert (old == &init_names);
1502 if (old == names_alloca)
1503 names_alloca = names;
1507 result = GLOB_NOSPACE;
1513 struct globnames *old = names;
1515 for (i = 0; i < cur; ++i)
1516 new_gl_pathv[pglob->gl_offs + pglob->gl_pathc++]
1518 names = names->next;
1519 /* NB: we will not leak memory here if we exit without
1520 freeing the current block assigned to OLD. At least
1521 the very first block is always allocated on the stack
1522 and this is the block assigned to OLD here. */
1525 assert (old == &init_names);
1529 if (old == names_alloca)
1530 names_alloca = names;
1535 pglob->gl_pathv = new_gl_pathv;
1537 pglob->gl_pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
1539 pglob->gl_flags = flags;
1546 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1547 (*pglob->gl_closedir) (stream);