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/>. */
22 /* Don't use __attribute__ __nonnull__ in this compilation unit. Otherwise gcc
23 optimizes away the pattern == NULL || pglob == NULL tests below. */
24 #define _GL_ARG_NONNULL(params)
29 #include <sys/types.h>
33 /* Outcomment the following line for production quality code. */
34 /* #define NDEBUG 1 */
39 #include <stdio.h> /* Needed on stupid SunOS for assert. */
41 #if !defined _LIBC || !defined GLOB_ONLY_P
44 #if !defined POSIX && defined _POSIX_VERSION
48 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
58 # define __set_errno(val) errno = (val)
64 /* In GNU systems, <dirent.h> defines this macro for us. */
65 #ifndef _D_EXACT_NAMLEN
66 # define _D_EXACT_NAMLEN(dirent) strlen ((dirent)->d_name)
69 /* When used in the GNU libc the symbol _DIRENT_HAVE_D_TYPE is available
70 if the `d_type' member for `struct dirent' is available.
71 HAVE_STRUCT_DIRENT_D_TYPE plays the same role in GNULIB. */
72 #if defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE
73 /* True if the directory entry D must be of type T. */
74 # define DIRENT_MUST_BE(d, t) ((d)->d_type == (t))
76 /* True if the directory entry D might be a symbolic link. */
77 # define DIRENT_MIGHT_BE_SYMLINK(d) \
78 ((d)->d_type == DT_UNKNOWN || (d)->d_type == DT_LNK)
80 /* True if the directory entry D might be a directory. */
81 # define DIRENT_MIGHT_BE_DIR(d) \
82 ((d)->d_type == DT_DIR || DIRENT_MIGHT_BE_SYMLINK (d))
84 #else /* !HAVE_D_TYPE */
85 # define DIRENT_MUST_BE(d, t) false
86 # define DIRENT_MIGHT_BE_SYMLINK(d) true
87 # define DIRENT_MIGHT_BE_DIR(d) true
88 #endif /* HAVE_D_TYPE */
90 /* If the system has the `struct dirent64' type we use it internally. */
91 #if defined _LIBC && !defined COMPILE_GLOB64
92 # if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
93 # define CONVERT_D_INO(d64, d32)
95 # define CONVERT_D_INO(d64, d32) \
96 (d64)->d_ino = (d32)->d_ino;
99 # ifdef _DIRENT_HAVE_D_TYPE
100 # define CONVERT_D_TYPE(d64, d32) \
101 (d64)->d_type = (d32)->d_type;
103 # define CONVERT_D_TYPE(d64, d32)
106 # define CONVERT_DIRENT_DIRENT64(d64, d32) \
107 memcpy ((d64)->d_name, (d32)->d_name, _D_EXACT_NAMLEN (d32) + 1); \
108 CONVERT_D_INO (d64, d32) \
109 CONVERT_D_TYPE (d64, d32)
113 #if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
114 /* Posix does not require that the d_ino field be present, and some
115 systems do not provide it. */
116 # define REAL_DIR_ENTRY(dp) 1
118 # define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
124 /* NAME_MAX is usually defined in <dirent.h> or <limits.h>. */
127 # define NAME_MAX (sizeof (((struct dirent *) 0)->d_name))
134 # define strdup(str) __strdup (str)
135 # define sysconf(id) __sysconf (id)
136 # define closedir(dir) __closedir (dir)
137 # define opendir(name) __opendir (name)
138 # define readdir(str) __readdir64 (str)
139 # define getpwnam_r(name, bufp, buf, len, res) \
140 __getpwnam_r (name, bufp, buf, len, res)
142 # define __stat64(fname, buf) __xstat64 (_STAT_VER, fname, buf)
144 # define struct_stat64 struct stat64
146 # define __stat64(fname, buf) stat (fname, buf)
147 # define __fxstatat64(_, d, f, st, flag) fstatat (d, f, st, flag)
148 # define struct_stat64 struct stat
149 # define __stat(fname, buf) stat (fname, buf)
150 # define __alloca alloca
151 # define __readdir readdir
152 # define __readdir64 readdir64
153 # define __glob_pattern_p glob_pattern_p
158 #ifdef _SC_GETPW_R_SIZE_MAX
159 # define GETPW_R_SIZE_MAX() sysconf (_SC_GETPW_R_SIZE_MAX)
161 # define GETPW_R_SIZE_MAX() (-1)
163 #ifdef _SC_LOGIN_NAME_MAX
164 # define GET_LOGIN_NAME_MAX() sysconf (_SC_LOGIN_NAME_MAX)
166 # define GET_LOGIN_NAME_MAX() (-1)
169 static const char *next_brace_sub (const char *begin, int flags) __THROW;
171 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
173 #ifndef attribute_hidden
174 # define attribute_hidden
177 #ifndef __attribute_noinline__
178 # if __GNUC__ < 3 || (__GNUC__ == 3 && __GNUC_MINOR__ < 1)
179 # define __attribute_noinline__ /* Ignore */
181 # define __attribute_noinline__ __attribute__ ((__noinline__))
185 #if ! defined __builtin_expect && __GNUC__ < 3
186 # define __builtin_expect(expr, expected) (expr)
190 /* The results of opendir() in this file are not used with dirfd and fchdir,
191 and we do not leak fds to any single-threaded code that could use stdio,
192 therefore save some unnecessary recursion in fchdir.c and opendir_safer.c.
193 FIXME - if the kernel ever adds support for multi-thread safety for
194 avoiding standard fds, then we should use opendir_safer. */
199 /* The OS usually guarantees only one guard page at the bottom of the stack,
200 and a page size can be as small as 4096 bytes. So we cannot safely
201 allocate anything larger than 4096 bytes. Also care for the possibility
202 of a few compiler-allocated temporary stack slots. */
203 # define __libc_use_alloca(n) ((n) < 4032)
205 /* alloca is implemented with malloc, so just use malloc. */
206 # define __libc_use_alloca(n) 0
210 static int glob_in_dir (const char *pattern, const char *directory,
211 int flags, int (*errfunc) (const char *, int),
213 extern int __glob_pattern_type (const char *pattern, int quote)
216 #if !defined _LIBC || !defined GLOB_ONLY_P
217 static int prefix_array (const char *prefix, char **array, size_t n) __THROW;
218 static int collated_compare (const void *, const void *) __THROW;
221 /* Find the end of the sub-pattern in a brace expression. */
223 next_brace_sub (const char *cp, int flags)
225 unsigned int depth = 0;
227 if ((flags & GLOB_NOESCAPE) == 0 && *cp == '\\')
235 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
242 return *cp != '\0' ? cp : NULL;
245 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
247 /* Do glob searching for PATTERN, placing results in PGLOB.
248 The bits defined above may be set in FLAGS.
249 If a directory cannot be opened or read and ERRFUNC is not nil,
250 it is called with the pathname that caused the error, and the
251 `errno' value from the failing call; if it returns non-zero
252 `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
253 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
254 Otherwise, `glob' returns zero. */
256 #ifdef GLOB_ATTRIBUTE
259 glob (pattern, flags, errfunc, pglob)
260 const char * restrict pattern;
262 int (*errfunc) (const char *, int);
263 glob_t * restrict pglob;
265 const char *filename;
271 int dirname_modified;
274 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
276 __set_errno (EINVAL);
280 if (!(flags & GLOB_DOOFFS))
281 /* Have to do this so `globfree' knows where to start freeing. It
282 also makes all the code that uses gl_offs simpler. */
285 if (flags & GLOB_BRACE)
289 if (flags & GLOB_NOESCAPE)
290 begin = strchr (pattern, '{');
302 if (*begin == '\\' && begin[1] != '\0')
304 else if (*begin == '{')
313 /* Allocate working buffer large enough for our work. Note that
314 we have at least an opening and closing brace. */
322 char onealt[strlen (pattern) - 1];
324 char *onealt = malloc (strlen (pattern) - 1);
327 if (!(flags & GLOB_APPEND))
330 pglob->gl_pathv = NULL;
336 /* We know the prefix for all sub-patterns. */
337 alt_start = mempcpy (onealt, pattern, begin - pattern);
339 /* Find the first sub-pattern and at the same time find the
340 rest after the closing brace. */
341 next = next_brace_sub (begin + 1, flags);
344 /* It is an invalid expression. */
348 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
351 /* Now find the end of the whole brace expression. */
355 rest = next_brace_sub (rest + 1, flags);
358 /* It is an invalid expression. */
362 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
365 /* Please note that we now can be sure the brace expression
367 rest_len = strlen (++rest) + 1;
369 /* We have a brace expression. BEGIN points to the opening {,
370 NEXT points past the terminator of the first element, and END
371 points past the final }. We will accumulate result names from
372 recursive runs for each brace alternative in the buffer using
375 if (!(flags & GLOB_APPEND))
377 /* This call is to set a new vector, so clear out the
378 vector so we can append to it. */
380 pglob->gl_pathv = NULL;
382 firstc = pglob->gl_pathc;
389 /* Construct the new glob expression. */
390 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
392 result = glob (onealt,
393 ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))
394 | GLOB_APPEND), errfunc, pglob);
396 /* If we got an error, return it. */
397 if (result && result != GLOB_NOMATCH)
402 if (!(flags & GLOB_APPEND))
411 /* We saw the last entry. */
415 next = next_brace_sub (p, flags);
416 assert (next != NULL);
423 if (pglob->gl_pathc != firstc)
424 /* We found some entries. */
426 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
431 /* Find the filename. */
432 filename = strrchr (pattern, '/');
433 #if defined __MSDOS__ || defined WINDOWS32
434 /* The case of "d:pattern". Since `:' is not allowed in
435 file names, we can safely assume that wherever it
436 happens in pattern, it signals the filename part. This
437 is so we could some day support patterns like "[a-z]:foo". */
438 if (filename == NULL)
439 filename = strchr (pattern, ':');
440 #endif /* __MSDOS__ || WINDOWS32 */
441 dirname_modified = 0;
442 if (filename == NULL)
444 /* This can mean two things: a simple name or "~name". The latter
445 case is nothing but a notation for a directory. */
446 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
449 dirlen = strlen (pattern);
451 /* Set FILENAME to NULL as a special flag. This is ugly but
452 other solutions would require much more code. We test for
453 this special case below. */
467 else if (filename == pattern
468 || (filename == pattern + 1 && pattern[0] == '\\'
469 && (flags & GLOB_NOESCAPE) == 0))
471 /* "/pattern" or "\\/pattern". */
479 dirlen = filename - pattern;
480 #if defined __MSDOS__ || defined WINDOWS32
482 || (filename > pattern + 1 && filename[-1] == ':'))
487 drive_spec = __alloca (dirlen + 1);
488 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
489 /* For now, disallow wildcards in the drive spec, to
490 prevent infinite recursion in glob. */
491 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
493 /* If this is "d:pattern", we need to copy `:' to DIRNAME
494 as well. If it's "d:/pattern", don't remove the slash
495 from "d:/", since "d:" and "d:/" are not the same.*/
498 newp = __alloca (dirlen + 1);
499 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
503 if (filename[0] == '\0'
504 #if defined __MSDOS__ || defined WINDOWS32
505 && dirname[dirlen - 1] != ':'
506 && (dirlen < 3 || dirname[dirlen - 2] != ':'
507 || dirname[dirlen - 1] != '/')
510 /* "pattern/". Expand "pattern", appending slashes. */
512 int orig_flags = flags;
514 if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\')
516 /* "pattern\\/". Remove the final backslash if it hasn't
518 char *p = (char *) &dirname[dirlen - 1];
520 while (p > dirname && p[-1] == '\\') --p;
521 if ((&dirname[dirlen] - p) & 1)
523 *(char *) &dirname[--dirlen] = '\0';
524 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
527 val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
529 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
530 | (flags & GLOB_MARK));
531 else if (val == GLOB_NOMATCH && flags != orig_flags)
533 /* Make sure globfree (&dirs); is a nop. */
534 dirs.gl_pathv = NULL;
536 oldcount = pglob->gl_pathc + pglob->gl_offs;
543 if (!(flags & GLOB_APPEND))
546 if (!(flags & GLOB_DOOFFS))
547 pglob->gl_pathv = NULL;
551 pglob->gl_pathv = malloc ((pglob->gl_offs + 1) * sizeof (char *));
552 if (pglob->gl_pathv == NULL)
555 for (i = 0; i <= pglob->gl_offs; ++i)
556 pglob->gl_pathv[i] = NULL;
560 oldcount = pglob->gl_pathc + pglob->gl_offs;
562 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
564 if (dirname[1] == '\0' || dirname[1] == '/'
565 || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\'
566 && (dirname[2] == '\0' || dirname[2] == '/')))
568 /* Look up home directory. */
569 const char *home_dir = getenv ("HOME");
571 if (home_dir == NULL || home_dir[0] == '\0')
575 /* Windows NT defines HOMEDRIVE and HOMEPATH. But give preference
576 to HOME, because the user can change HOME. */
577 if (home_dir == NULL || home_dir[0] == '\0')
579 const char *home_drive = getenv ("HOMEDRIVE");
580 const char *home_path = getenv ("HOMEPATH");
582 if (home_drive != NULL && home_path != NULL)
584 size_t home_drive_len = strlen (home_drive);
585 size_t home_path_len = strlen (home_path);
586 char *mem = alloca (home_drive_len + home_path_len + 1);
588 memcpy (mem, home_drive, home_drive_len);
589 memcpy (mem + home_drive_len, home_path, home_path_len + 1);
593 home_dir = "c:/users/default"; /* poor default */
596 if (home_dir == NULL || home_dir[0] == '\0')
600 size_t buflen = GET_LOGIN_NAME_MAX () + 1;
603 /* `sysconf' does not support _SC_LOGIN_NAME_MAX. Try
606 name = __alloca (buflen);
608 success = getlogin_r (name, buflen) == 0;
612 # if defined HAVE_GETPWNAM_R || defined _LIBC
613 long int pwbuflen = GETPW_R_SIZE_MAX ();
620 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.
621 Try a moderate value. */
624 pwtmpbuf = __alloca (pwbuflen);
626 while (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
635 pwtmpbuf = extend_alloca (pwtmpbuf, pwbuflen,
639 pwtmpbuf = __alloca (pwbuflen);
647 home_dir = p->pw_dir;
650 if (home_dir == NULL || home_dir[0] == '\0')
652 if (flags & GLOB_TILDE_CHECK)
655 home_dir = "~"; /* No luck. */
657 # endif /* WINDOWS32 */
659 /* Now construct the full directory. */
660 if (dirname[1] == '\0')
663 dirlen = strlen (dirname);
668 size_t home_len = strlen (home_dir);
669 newp = __alloca (home_len + dirlen);
670 mempcpy (mempcpy (newp, home_dir, home_len),
671 &dirname[1], dirlen);
673 dirlen += home_len - 1;
675 dirname_modified = 1;
677 # if !defined _AMIGA && !defined WINDOWS32
680 char *end_name = strchr (dirname, '/');
681 const char *user_name;
682 const char *home_dir;
683 char *unescape = NULL;
685 if (!(flags & GLOB_NOESCAPE))
687 if (end_name == NULL)
689 unescape = strchr (dirname, '\\');
691 end_name = strchr (unescape, '\0');
694 unescape = memchr (dirname, '\\', end_name - dirname);
696 if (end_name == NULL)
697 user_name = dirname + 1;
701 newp = __alloca (end_name - dirname);
702 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
704 if (unescape != NULL)
706 char *p = mempcpy (newp, dirname + 1,
707 unescape - dirname - 1);
715 /* "~fo\\o\\" unescape to user_name "foo\\",
716 but "~fo\\o\\/" unescape to user_name
718 if (filename == NULL)
729 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
734 /* Look up specific user's home directory. */
737 # if defined HAVE_GETPWNAM_R || defined _LIBC
738 long int buflen = GETPW_R_SIZE_MAX ();
745 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
749 pwtmpbuf = __alloca (buflen);
751 while (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) != 0)
759 pwtmpbuf = extend_alloca (pwtmpbuf, buflen, 2 * buflen);
762 pwtmpbuf = __alloca (buflen);
767 p = getpwnam (user_name);
770 home_dir = p->pw_dir;
774 /* If we found a home directory use this. */
775 if (home_dir != NULL)
778 size_t home_len = strlen (home_dir);
779 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
780 newp = __alloca (home_len + rest_len + 1);
781 *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
782 end_name, rest_len)) = '\0';
784 dirlen = home_len + rest_len;
785 dirname_modified = 1;
788 if (flags & GLOB_TILDE_CHECK)
789 /* We have to regard it as an error if we cannot find the
793 # endif /* Not Amiga && not WINDOWS32. */
796 /* Now test whether we looked for "~" or "~NAME". In this case we
797 can give the answer now. */
798 if (filename == NULL)
803 /* Return the directory if we don't check for error or if it exists. */
804 if ((flags & GLOB_NOCHECK)
805 || (((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
806 ? ((*pglob->gl_stat) (dirname, &st) == 0
807 && S_ISDIR (st.st_mode))
808 : (__stat64 (dirname, &st64) == 0 && S_ISDIR (st64.st_mode)))))
810 int newcount = pglob->gl_pathc + pglob->gl_offs;
814 = realloc (pglob->gl_pathv, (newcount + 1 + 1) * sizeof (char *));
815 if (new_gl_pathv == NULL)
818 free (pglob->gl_pathv);
819 pglob->gl_pathv = NULL;
823 pglob->gl_pathv = new_gl_pathv;
825 if (flags & GLOB_MARK)
828 pglob->gl_pathv[newcount] = malloc (dirlen + 2);
829 if (pglob->gl_pathv[newcount] == NULL)
831 p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);
837 pglob->gl_pathv[newcount] = strdup (dirname);
838 if (pglob->gl_pathv[newcount] == NULL)
841 pglob->gl_pathv[++newcount] = NULL;
843 pglob->gl_flags = flags;
852 meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));
853 /* meta is 1 if correct glob pattern containing metacharacters.
854 If meta has bit (1 << 2) set, it means there was an unterminated
855 [ which we handle the same, using fnmatch. Broken unterminated
856 pattern bracket expressions ought to be rare enough that it is
857 not worth special casing them, fnmatch will do the right thing. */
860 /* The directory name contains metacharacters, so we
861 have to glob for the directory, and then glob for
862 the pattern in each directory found. */
865 if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\')
867 /* "foo\\/bar". Remove the final backslash from dirname
868 if it has not been quoted. */
869 char *p = (char *) &dirname[dirlen - 1];
871 while (p > dirname && p[-1] == '\\') --p;
872 if ((&dirname[dirlen] - p) & 1)
873 *(char *) &dirname[--dirlen] = '\0';
876 if (__builtin_expect ((flags & GLOB_ALTDIRFUNC) != 0, 0))
878 /* Use the alternative access functions also in the recursive
880 dirs.gl_opendir = pglob->gl_opendir;
881 dirs.gl_readdir = pglob->gl_readdir;
882 dirs.gl_closedir = pglob->gl_closedir;
883 dirs.gl_stat = pglob->gl_stat;
884 dirs.gl_lstat = pglob->gl_lstat;
887 status = glob (dirname,
888 ((flags & (GLOB_ERR | GLOB_NOESCAPE
890 | GLOB_NOSORT | GLOB_ONLYDIR),
894 if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH)
899 /* We have successfully globbed the preceding directory name.
900 For each name we found, call glob_in_dir on it and FILENAME,
901 appending the results to PGLOB. */
902 for (i = 0; i < dirs.gl_pathc; ++i)
908 /* Make globbing interruptible in the bash shell. */
909 extern int interrupt_state;
919 old_pathc = pglob->gl_pathc;
920 status = glob_in_dir (filename, dirs.gl_pathv[i],
921 ((flags | GLOB_APPEND)
922 & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),
924 if (status == GLOB_NOMATCH)
925 /* No matches in this directory. Try the next. */
936 /* Stick the directory on the front of each name. */
937 if (prefix_array (dirs.gl_pathv[i],
938 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
939 pglob->gl_pathc - old_pathc))
948 flags |= GLOB_MAGCHAR;
950 /* We have ignored the GLOB_NOCHECK flag in the `glob_in_dir' calls.
951 But if we have not found any matching entry and the GLOB_NOCHECK
952 flag was set we must return the input pattern itself. */
953 if (pglob->gl_pathc + pglob->gl_offs == oldcount)
957 if (flags & GLOB_NOCHECK)
959 int newcount = pglob->gl_pathc + pglob->gl_offs;
962 new_gl_pathv = realloc (pglob->gl_pathv,
963 (newcount + 2) * sizeof (char *));
964 if (new_gl_pathv == NULL)
969 pglob->gl_pathv = new_gl_pathv;
971 pglob->gl_pathv[newcount] = strdup (pattern);
972 if (pglob->gl_pathv[newcount] == NULL)
983 pglob->gl_pathv[newcount] = NULL;
984 pglob->gl_flags = flags;
997 int old_pathc = pglob->gl_pathc;
998 int orig_flags = flags;
1002 char *p = strchr (dirname, '\\'), *q;
1003 /* We need to unescape the dirname string. It is certainly
1004 allocated by alloca, as otherwise filename would be NULL
1005 or dirname wouldn't contain backslashes. */
1018 while (*p++ != '\0');
1019 dirname_modified = 1;
1021 if (dirname_modified)
1022 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
1023 status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
1026 if (status == GLOB_NOMATCH && flags != orig_flags
1027 && pglob->gl_pathc + pglob->gl_offs == oldcount)
1029 /* Make sure globfree (&dirs); is a nop. */
1030 dirs.gl_pathv = NULL;
1039 /* Stick the directory on the front of each name. */
1040 if (prefix_array (dirname,
1041 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
1042 pglob->gl_pathc - old_pathc))
1045 pglob->gl_pathc = 0;
1046 return GLOB_NOSPACE;
1051 if (flags & GLOB_MARK)
1053 /* Append slashes to directory names. */
1058 for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)
1059 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1060 ? ((*pglob->gl_stat) (pglob->gl_pathv[i], &st) == 0
1061 && S_ISDIR (st.st_mode))
1062 : (__stat64 (pglob->gl_pathv[i], &st64) == 0
1063 && S_ISDIR (st64.st_mode))))
1065 size_t len = strlen (pglob->gl_pathv[i]) + 2;
1066 char *new = realloc (pglob->gl_pathv[i], len);
1070 pglob->gl_pathc = 0;
1071 return GLOB_NOSPACE;
1073 strcpy (&new[len - 2], "/");
1074 pglob->gl_pathv[i] = new;
1078 if (!(flags & GLOB_NOSORT))
1080 /* Sort the vector. */
1081 qsort (&pglob->gl_pathv[oldcount],
1082 pglob->gl_pathc + pglob->gl_offs - oldcount,
1083 sizeof (char *), collated_compare);
1088 #if defined _LIBC && !defined glob
1089 libc_hidden_def (glob)
1093 #if !defined _LIBC || !defined GLOB_ONLY_P
1095 /* Free storage allocated in PGLOB by a previous `glob' call. */
1098 register glob_t *pglob;
1100 if (pglob->gl_pathv != NULL)
1103 for (i = 0; i < pglob->gl_pathc; ++i)
1104 if (pglob->gl_pathv[pglob->gl_offs + i] != NULL)
1105 free (pglob->gl_pathv[pglob->gl_offs + i]);
1106 free (pglob->gl_pathv);
1107 pglob->gl_pathv = NULL;
1110 #if defined _LIBC && !defined globfree
1111 libc_hidden_def (globfree)
1115 /* Do a collated comparison of A and B. */
1117 collated_compare (const void *a, const void *b)
1119 char *const *ps1 = a; char *s1 = *ps1;
1120 char *const *ps2 = b; char *s2 = *ps2;
1128 return strcoll (s1, s2);
1132 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1133 elements in place. Return nonzero if out of memory, zero if successful.
1134 A slash is inserted between DIRNAME and each elt of ARRAY,
1135 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1137 prefix_array (const char *dirname, char **array, size_t n)
1140 size_t dirlen = strlen (dirname);
1141 #if defined __MSDOS__ || defined WINDOWS32
1143 # define DIRSEP_CHAR sep_char
1145 # define DIRSEP_CHAR '/'
1148 if (dirlen == 1 && dirname[0] == '/')
1149 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1150 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1152 #if defined __MSDOS__ || defined WINDOWS32
1153 else if (dirlen > 1)
1155 if (dirname[dirlen - 1] == '/' && dirname[dirlen - 2] == ':')
1156 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1158 else if (dirname[dirlen - 1] == ':')
1160 /* DIRNAME is "d:". Use `:' instead of `/'. */
1167 for (i = 0; i < n; ++i)
1169 size_t eltlen = strlen (array[i]) + 1;
1170 char *new = malloc (dirlen + 1 + eltlen);
1179 char *endp = mempcpy (new, dirname, dirlen);
1180 *endp++ = DIRSEP_CHAR;
1181 mempcpy (endp, array[i], eltlen);
1191 /* We must not compile this function twice. */
1192 #if !defined _LIBC || !defined NO_GLOB_PATTERN_P
1194 __glob_pattern_type (pattern, quote)
1195 const char *pattern;
1198 register const char *p;
1201 for (p = pattern; *p != '\0'; ++p)
1230 /* Return nonzero if PATTERN contains any metacharacters.
1231 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
1233 __glob_pattern_p (pattern, quote)
1234 const char *pattern;
1237 return __glob_pattern_type (pattern, quote) == 1;
1240 weak_alias (__glob_pattern_p, glob_pattern_p)
1244 #endif /* !GLOB_ONLY_P */
1247 #if !defined _LIBC || !defined GLOB_ONLY_P
1248 /* We put this in a separate function mainly to allow the memory
1249 allocated with alloca to be recycled. */
1251 __attribute_noinline__
1252 link_exists2_p (const char *dir, size_t dirlen, const char *fname,
1254 # if !defined _LIBC && !HAVE_FSTATAT
1259 size_t fnamelen = strlen (fname);
1260 char *fullname = __alloca (dirlen + 1 + fnamelen + 1);
1263 mempcpy (mempcpy (mempcpy (fullname, dir, dirlen), "/", 1),
1264 fname, fnamelen + 1);
1266 # if !defined _LIBC && !HAVE_FSTATAT
1267 if (__builtin_expect ((flags & GLOB_ALTDIRFUNC) == 0, 1))
1270 return __stat64 (fullname, &st64) == 0;
1273 return (*pglob->gl_stat) (fullname, &st) == 0;
1276 /* Return true if DIR/FNAME exists. */
1278 link_exists_p (int dfd, const char *dir, size_t dirlen, const char *fname,
1279 glob_t *pglob, int flags)
1281 # if defined _LIBC || HAVE_FSTATAT
1282 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1283 return link_exists2_p (dir, dirlen, fname, pglob);
1287 return __fxstatat64 (_STAT_VER, dfd, fname, &st64, 0) == 0;
1290 return link_exists2_p (dir, dirlen, fname, pglob, flags);
1296 /* Like `glob', but PATTERN is a final pathname component,
1297 and matches are searched for in DIRECTORY.
1298 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1299 The GLOB_APPEND flag is assumed to be set (always appends). */
1301 glob_in_dir (const char *pattern, const char *directory, int flags,
1302 int (*errfunc) (const char *, int),
1305 size_t dirlen = strlen (directory);
1306 void *stream = NULL;
1309 struct globnames *next;
1313 #define INITIAL_COUNT sizeof (init_names.name) / sizeof (init_names.name[0])
1314 struct globnames init_names;
1315 struct globnames *names = &init_names;
1316 struct globnames *names_alloca = &init_names;
1318 size_t allocasize = sizeof (init_names);
1324 init_names.next = NULL;
1325 init_names.count = INITIAL_COUNT;
1327 meta = __glob_pattern_type (pattern, !(flags & GLOB_NOESCAPE));
1328 if (meta == 0 && (flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
1330 /* We need not do any tests. The PATTERN contains no meta
1331 characters and we must not return an error therefore the
1332 result will always contain exactly one name. */
1333 flags |= GLOB_NOCHECK;
1337 /* Since we use the normal file functions we can also use stat()
1338 to verify the file is there. */
1341 size_t patlen = strlen (pattern);
1342 char *fullname = __alloca (dirlen + 1 + patlen + 1);
1344 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1346 pattern, patlen + 1);
1347 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1348 ? (*pglob->gl_stat) (fullname, &st)
1349 : __stat64 (fullname, &st64)) == 0)
1350 /* We found this file to be existing. Now tell the rest
1351 of the function to copy this name into the result. */
1352 flags |= GLOB_NOCHECK;
1356 stream = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1357 ? (*pglob->gl_opendir) (directory)
1358 : opendir (directory));
1361 if (errno != ENOTDIR
1362 && ((errfunc != NULL && (*errfunc) (directory, errno))
1363 || (flags & GLOB_ERR)))
1364 return GLOB_ABORTED;
1368 int dfd = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1369 ? -1 : dirfd ((DIR *) stream));
1370 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1371 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1372 #if defined _AMIGA || defined VMS
1376 flags |= GLOB_MAGCHAR;
1382 #if defined _LIBC && !defined COMPILE_GLOB64
1386 struct dirent64 d64;
1387 char room [offsetof (struct dirent64, d_name[0])
1392 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1394 struct dirent *d32 = (*pglob->gl_readdir) (stream);
1397 CONVERT_DIRENT_DIRENT64 (&d64buf.d64, d32);
1404 d = __readdir64 (stream);
1406 struct dirent *d = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1407 ? ((struct dirent *)
1408 (*pglob->gl_readdir) (stream))
1409 : __readdir (stream));
1413 if (! REAL_DIR_ENTRY (d))
1416 /* If we shall match only directories use the information
1417 provided by the dirent call if possible. */
1418 if ((flags & GLOB_ONLYDIR) && !DIRENT_MIGHT_BE_DIR (d))
1423 if (fnmatch (pattern, name, fnm_flags) == 0)
1425 /* If the file we found is a symlink we have to
1426 make sure the target file exists. */
1427 if (!DIRENT_MIGHT_BE_SYMLINK (d)
1428 || link_exists_p (dfd, directory, dirlen, name, pglob,
1431 if (cur == names->count)
1433 struct globnames *newnames;
1434 size_t count = names->count * 2;
1435 size_t size = (sizeof (struct globnames)
1436 + ((count - INITIAL_COUNT)
1437 * sizeof (char *)));
1439 if (__libc_use_alloca (allocasize))
1440 newnames = names_alloca = __alloca (size);
1441 else if ((newnames = malloc (size))
1444 newnames->count = count;
1445 newnames->next = names;
1449 len = _D_EXACT_NAMLEN (d);
1450 names->name[cur] = malloc (len + 1);
1451 if (names->name[cur] == NULL)
1453 *((char *) mempcpy (names->name[cur++], name, len))
1462 if (nfound == 0 && (flags & GLOB_NOCHECK))
1464 size_t len = strlen (pattern);
1466 names->name[cur] = malloc (len + 1);
1467 if (names->name[cur] == NULL)
1469 *((char *) mempcpy (names->name[cur++], pattern, len)) = '\0';
1472 result = GLOB_NOMATCH;
1476 = realloc (pglob->gl_pathv,
1477 (pglob->gl_pathc + pglob->gl_offs + nfound + 1)
1481 if (new_gl_pathv == NULL)
1486 struct globnames *old = names;
1488 for (i = 0; i < cur; ++i)
1489 free (names->name[i]);
1490 names = names->next;
1491 /* NB: we will not leak memory here if we exit without
1492 freeing the current block assigned to OLD. At least
1493 the very first block is always allocated on the stack
1494 and this is the block assigned to OLD here. */
1497 assert (old == &init_names);
1501 if (old == names_alloca)
1502 names_alloca = names;
1506 result = GLOB_NOSPACE;
1512 struct globnames *old = names;
1514 for (i = 0; i < cur; ++i)
1515 new_gl_pathv[pglob->gl_offs + pglob->gl_pathc++]
1517 names = names->next;
1518 /* NB: we will not leak memory here if we exit without
1519 freeing the current block assigned to OLD. At least
1520 the very first block is always allocated on the stack
1521 and this is the block assigned to OLD here. */
1524 assert (old == &init_names);
1528 if (old == names_alloca)
1529 names_alloca = names;
1534 pglob->gl_pathv = new_gl_pathv;
1536 pglob->gl_pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
1538 pglob->gl_flags = flags;
1545 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1546 (*pglob->gl_closedir) (stream);