1 /* Copyright (C) 1991-2002, 2003, 2004, 2005, 2006, 2007, 2008
2 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, write to the Free
17 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
27 #include <sys/types.h>
31 /* Outcomment the following line for production quality code. */
32 /* #define NDEBUG 1 */
37 #include <stdio.h> /* Needed on stupid SunOS for assert. */
39 #if !defined _LIBC || !defined GLOB_ONLY_P
42 #if !defined POSIX && defined _POSIX_VERSION
46 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
56 # define __set_errno(val) errno = (val)
62 /* In GNU systems, <dirent.h> defines this macro for us. */
63 #ifndef _D_EXACT_NAMLEN
64 # define _D_EXACT_NAMLEN(dirent) strlen ((dirent)->d_name)
67 /* When used in the GNU libc the symbol _DIRENT_HAVE_D_TYPE is available
68 if the `d_type' member for `struct dirent' is available.
69 HAVE_STRUCT_DIRENT_D_TYPE plays the same role in GNULIB. */
70 #if defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE
71 /* True if the directory entry D must be of type T. */
72 # define DIRENT_MUST_BE(d, t) ((d)->d_type == (t))
74 /* True if the directory entry D might be a symbolic link. */
75 # define DIRENT_MIGHT_BE_SYMLINK(d) \
76 ((d)->d_type == DT_UNKNOWN || (d)->d_type == DT_LNK)
78 /* True if the directory entry D might be a directory. */
79 # define DIRENT_MIGHT_BE_DIR(d) \
80 ((d)->d_type == DT_DIR || DIRENT_MIGHT_BE_SYMLINK (d))
82 #else /* !HAVE_D_TYPE */
83 # define DIRENT_MUST_BE(d, t) false
84 # define DIRENT_MIGHT_BE_SYMLINK(d) true
85 # define DIRENT_MIGHT_BE_DIR(d) true
86 #endif /* HAVE_D_TYPE */
88 /* If the system has the `struct dirent64' type we use it internally. */
89 #if defined _LIBC && !defined COMPILE_GLOB64
90 # if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
91 # define CONVERT_D_INO(d64, d32)
93 # define CONVERT_D_INO(d64, d32) \
94 (d64)->d_ino = (d32)->d_ino;
97 # ifdef _DIRENT_HAVE_D_TYPE
98 # define CONVERT_D_TYPE(d64, d32) \
99 (d64)->d_type = (d32)->d_type;
101 # define CONVERT_D_TYPE(d64, d32)
104 # define CONVERT_DIRENT_DIRENT64(d64, d32) \
105 memcpy ((d64)->d_name, (d32)->d_name, _D_EXACT_NAMLEN (d32) + 1); \
106 CONVERT_D_INO (d64, d32) \
107 CONVERT_D_TYPE (d64, d32)
111 #if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
112 /* Posix does not require that the d_ino field be present, and some
113 systems do not provide it. */
114 # define REAL_DIR_ENTRY(dp) 1
116 # define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
122 /* NAME_MAX is usually defined in <dirent.h> or <limits.h>. */
125 # define NAME_MAX (sizeof (((struct dirent *) 0)->d_name))
132 # define strdup(str) __strdup (str)
133 # define sysconf(id) __sysconf (id)
134 # define closedir(dir) __closedir (dir)
135 # define opendir(name) __opendir (name)
136 # define readdir(str) __readdir64 (str)
137 # define getpwnam_r(name, bufp, buf, len, res) \
138 __getpwnam_r (name, bufp, buf, len, res)
140 # define __stat64(fname, buf) __xstat64 (_STAT_VER, fname, buf)
142 # define struct_stat64 struct stat64
144 # define __stat64(fname, buf) stat (fname, buf)
145 # define __fxstatat64(_, d, f, st, flag) fstatat (d, f, st, flag)
146 # define struct_stat64 struct stat
147 # define __stat(fname, buf) stat (fname, buf)
148 # define __alloca alloca
149 # define __readdir readdir
150 # define __readdir64 readdir64
151 # define __glob_pattern_p glob_pattern_p
156 #ifdef _SC_GETPW_R_SIZE_MAX
157 # define GETPW_R_SIZE_MAX() sysconf (_SC_GETPW_R_SIZE_MAX)
159 # define GETPW_R_SIZE_MAX() (-1)
161 #ifdef _SC_LOGIN_NAME_MAX
162 # define GET_LOGIN_NAME_MAX() sysconf (_SC_LOGIN_NAME_MAX)
164 # define GET_LOGIN_NAME_MAX() (-1)
167 static const char *next_brace_sub (const char *begin, int flags) __THROW;
169 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
171 #ifndef attribute_hidden
172 # define attribute_hidden
175 #ifndef __attribute_noinline__
176 # if __GNUC__ < 3 || (__GNUC__ == 3 && __GNUC_MINOR__ < 1)
177 # define __attribute_noinline__ /* Ignore */
179 # define __attribute_noinline__ __attribute__ ((__noinline__))
183 #if ! defined __builtin_expect && __GNUC__ < 3
184 # define __builtin_expect(expr, expected) (expr)
188 /* The results of opendir() in this file are not used with dirfd and fchdir,
189 therefore save some unnecessary work in fchdir.c. */
194 /* The OS usually guarantees only one guard page at the bottom of the stack,
195 and a page size can be as small as 4096 bytes. So we cannot safely
196 allocate anything larger than 4096 bytes. Also care for the possibility
197 of a few compiler-allocated temporary stack slots. */
198 # define __libc_use_alloca(n) ((n) < 4032)
200 /* alloca is implemented with malloc, so just use malloc. */
201 # define __libc_use_alloca(n) 0
205 static int glob_in_dir (const char *pattern, const char *directory,
206 int flags, int (*errfunc) (const char *, int),
208 extern int __glob_pattern_type (const char *pattern, int quote)
211 #if !defined _LIBC || !defined GLOB_ONLY_P
212 static int prefix_array (const char *prefix, char **array, size_t n) __THROW;
213 static int collated_compare (const void *, const void *) __THROW;
216 /* Find the end of the sub-pattern in a brace expression. */
218 next_brace_sub (const char *cp, int flags)
220 unsigned int depth = 0;
222 if ((flags & GLOB_NOESCAPE) == 0 && *cp == '\\')
230 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
237 return *cp != '\0' ? cp : NULL;
240 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
242 /* Do glob searching for PATTERN, placing results in PGLOB.
243 The bits defined above may be set in FLAGS.
244 If a directory cannot be opened or read and ERRFUNC is not nil,
245 it is called with the pathname that caused the error, and the
246 `errno' value from the failing call; if it returns non-zero
247 `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
248 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
249 Otherwise, `glob' returns zero. */
251 #ifdef GLOB_ATTRIBUTE
254 glob (pattern, flags, errfunc, pglob)
255 const char * restrict pattern;
257 int (*errfunc) (const char *, int);
258 glob_t * restrict pglob;
260 const char *filename;
266 int dirname_modified;
269 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
271 __set_errno (EINVAL);
275 if (!(flags & GLOB_DOOFFS))
276 /* Have to do this so `globfree' knows where to start freeing. It
277 also makes all the code that uses gl_offs simpler. */
280 if (flags & GLOB_BRACE)
284 if (flags & GLOB_NOESCAPE)
285 begin = strchr (pattern, '{');
297 if (*begin == '\\' && begin[1] != '\0')
299 else if (*begin == '{')
308 /* Allocate working buffer large enough for our work. Note that
309 we have at least an opening and closing brace. */
317 char onealt[strlen (pattern) - 1];
319 char *onealt = malloc (strlen (pattern) - 1);
322 if (!(flags & GLOB_APPEND))
325 pglob->gl_pathv = NULL;
331 /* We know the prefix for all sub-patterns. */
332 alt_start = mempcpy (onealt, pattern, begin - pattern);
334 /* Find the first sub-pattern and at the same time find the
335 rest after the closing brace. */
336 next = next_brace_sub (begin + 1, flags);
339 /* It is an invalid expression. */
343 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
346 /* Now find the end of the whole brace expression. */
350 rest = next_brace_sub (rest + 1, flags);
353 /* It is an invalid expression. */
357 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
360 /* Please note that we now can be sure the brace expression
362 rest_len = strlen (++rest) + 1;
364 /* We have a brace expression. BEGIN points to the opening {,
365 NEXT points past the terminator of the first element, and END
366 points past the final }. We will accumulate result names from
367 recursive runs for each brace alternative in the buffer using
370 if (!(flags & GLOB_APPEND))
372 /* This call is to set a new vector, so clear out the
373 vector so we can append to it. */
375 pglob->gl_pathv = NULL;
377 firstc = pglob->gl_pathc;
384 /* Construct the new glob expression. */
385 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
387 result = glob (onealt,
388 ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))
389 | GLOB_APPEND), errfunc, pglob);
391 /* If we got an error, return it. */
392 if (result && result != GLOB_NOMATCH)
397 if (!(flags & GLOB_APPEND))
406 /* We saw the last entry. */
410 next = next_brace_sub (p, flags);
411 assert (next != NULL);
418 if (pglob->gl_pathc != firstc)
419 /* We found some entries. */
421 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
426 /* Find the filename. */
427 filename = strrchr (pattern, '/');
428 #if defined __MSDOS__ || defined WINDOWS32
429 /* The case of "d:pattern". Since `:' is not allowed in
430 file names, we can safely assume that wherever it
431 happens in pattern, it signals the filename part. This
432 is so we could some day support patterns like "[a-z]:foo". */
433 if (filename == NULL)
434 filename = strchr (pattern, ':');
435 #endif /* __MSDOS__ || WINDOWS32 */
436 dirname_modified = 0;
437 if (filename == NULL)
439 /* This can mean two things: a simple name or "~name". The latter
440 case is nothing but a notation for a directory. */
441 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
444 dirlen = strlen (pattern);
446 /* Set FILENAME to NULL as a special flag. This is ugly but
447 other solutions would require much more code. We test for
448 this special case below. */
462 else if (filename == pattern
463 || (filename == pattern + 1 && pattern[0] == '\\'
464 && (flags & GLOB_NOESCAPE) == 0))
466 /* "/pattern" or "\\/pattern". */
474 dirlen = filename - pattern;
475 #if defined __MSDOS__ || defined WINDOWS32
477 || (filename > pattern + 1 && filename[-1] == ':'))
482 drive_spec = __alloca (dirlen + 1);
483 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
484 /* For now, disallow wildcards in the drive spec, to
485 prevent infinite recursion in glob. */
486 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
488 /* If this is "d:pattern", we need to copy `:' to DIRNAME
489 as well. If it's "d:/pattern", don't remove the slash
490 from "d:/", since "d:" and "d:/" are not the same.*/
493 newp = __alloca (dirlen + 1);
494 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
498 if (filename[0] == '\0'
499 #if defined __MSDOS__ || defined WINDOWS32
500 && dirname[dirlen - 1] != ':'
501 && (dirlen < 3 || dirname[dirlen - 2] != ':'
502 || dirname[dirlen - 1] != '/')
505 /* "pattern/". Expand "pattern", appending slashes. */
507 int orig_flags = flags;
509 if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\')
511 /* "pattern\\/". Remove the final backslash if it hasn't
513 char *p = (char *) &dirname[dirlen - 1];
515 while (p > dirname && p[-1] == '\\') --p;
516 if ((&dirname[dirlen] - p) & 1)
518 *(char *) &dirname[--dirlen] = '\0';
519 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
522 val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
524 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
525 | (flags & GLOB_MARK));
526 else if (val == GLOB_NOMATCH && flags != orig_flags)
528 /* Make sure globfree (&dirs); is a nop. */
529 dirs.gl_pathv = NULL;
531 oldcount = pglob->gl_pathc + pglob->gl_offs;
538 if (!(flags & GLOB_APPEND))
541 if (!(flags & GLOB_DOOFFS))
542 pglob->gl_pathv = NULL;
546 pglob->gl_pathv = malloc ((pglob->gl_offs + 1) * sizeof (char *));
547 if (pglob->gl_pathv == NULL)
550 for (i = 0; i <= pglob->gl_offs; ++i)
551 pglob->gl_pathv[i] = NULL;
555 oldcount = pglob->gl_pathc + pglob->gl_offs;
557 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
559 if (dirname[1] == '\0' || dirname[1] == '/'
560 || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\'
561 && (dirname[2] == '\0' || dirname[2] == '/')))
563 /* Look up home directory. */
564 const char *home_dir = getenv ("HOME");
566 if (home_dir == NULL || home_dir[0] == '\0')
570 /* Windows NT defines HOMEDRIVE and HOMEPATH. But give preference
571 to HOME, because the user can change HOME. */
572 if (home_dir == NULL || home_dir[0] == '\0')
574 const char *home_drive = getenv ("HOMEDRIVE");
575 const char *home_path = getenv ("HOMEPATH");
577 if (home_drive != NULL && home_path != NULL)
579 size_t home_drive_len = strlen (home_drive);
580 size_t home_path_len = strlen (home_path);
581 char *mem = alloca (home_drive_len + home_path_len + 1);
583 memcpy (mem, home_drive, home_drive_len);
584 memcpy (mem + home_drive_len, home_path, home_path_len + 1);
588 home_dir = "c:/users/default"; /* poor default */
591 if (home_dir == NULL || home_dir[0] == '\0')
595 size_t buflen = GET_LOGIN_NAME_MAX () + 1;
598 /* `sysconf' does not support _SC_LOGIN_NAME_MAX. Try
601 name = __alloca (buflen);
603 success = getlogin_r (name, buflen) == 0;
607 # if defined HAVE_GETPWNAM_R || defined _LIBC
608 long int pwbuflen = GETPW_R_SIZE_MAX ();
615 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.
616 Try a moderate value. */
619 pwtmpbuf = __alloca (pwbuflen);
621 while (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
630 pwtmpbuf = extend_alloca (pwtmpbuf, pwbuflen,
634 pwtmpbuf = __alloca (pwbuflen);
642 home_dir = p->pw_dir;
645 if (home_dir == NULL || home_dir[0] == '\0')
647 if (flags & GLOB_TILDE_CHECK)
650 home_dir = "~"; /* No luck. */
652 # endif /* WINDOWS32 */
654 /* Now construct the full directory. */
655 if (dirname[1] == '\0')
658 dirlen = strlen (dirname);
663 size_t home_len = strlen (home_dir);
664 newp = __alloca (home_len + dirlen);
665 mempcpy (mempcpy (newp, home_dir, home_len),
666 &dirname[1], dirlen);
668 dirlen += home_len - 1;
670 dirname_modified = 1;
672 # if !defined _AMIGA && !defined WINDOWS32
675 char *end_name = strchr (dirname, '/');
676 const char *user_name;
677 const char *home_dir;
678 char *unescape = NULL;
680 if (!(flags & GLOB_NOESCAPE))
682 if (end_name == NULL)
684 unescape = strchr (dirname, '\\');
686 end_name = strchr (unescape, '\0');
689 unescape = memchr (dirname, '\\', end_name - dirname);
691 if (end_name == NULL)
692 user_name = dirname + 1;
696 newp = __alloca (end_name - dirname);
697 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
699 if (unescape != NULL)
701 char *p = mempcpy (newp, dirname + 1,
702 unescape - dirname - 1);
710 /* "~fo\\o\\" unescape to user_name "foo\\",
711 but "~fo\\o\\/" unescape to user_name
713 if (filename == NULL)
724 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
729 /* Look up specific user's home directory. */
732 # if defined HAVE_GETPWNAM_R || defined _LIBC
733 long int buflen = GETPW_R_SIZE_MAX ();
740 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
744 pwtmpbuf = __alloca (buflen);
746 while (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) != 0)
754 pwtmpbuf = extend_alloca (pwtmpbuf, buflen, 2 * buflen);
757 pwtmpbuf = __alloca (buflen);
762 p = getpwnam (user_name);
765 home_dir = p->pw_dir;
769 /* If we found a home directory use this. */
770 if (home_dir != NULL)
773 size_t home_len = strlen (home_dir);
774 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
775 newp = __alloca (home_len + rest_len + 1);
776 *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
777 end_name, rest_len)) = '\0';
779 dirlen = home_len + rest_len;
780 dirname_modified = 1;
783 if (flags & GLOB_TILDE_CHECK)
784 /* We have to regard it as an error if we cannot find the
788 # endif /* Not Amiga && not WINDOWS32. */
791 /* Now test whether we looked for "~" or "~NAME". In this case we
792 can give the answer now. */
793 if (filename == NULL)
798 /* Return the directory if we don't check for error or if it exists. */
799 if ((flags & GLOB_NOCHECK)
800 || (((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
801 ? ((*pglob->gl_stat) (dirname, &st) == 0
802 && S_ISDIR (st.st_mode))
803 : (__stat64 (dirname, &st64) == 0 && S_ISDIR (st64.st_mode)))))
805 int newcount = pglob->gl_pathc + pglob->gl_offs;
809 = realloc (pglob->gl_pathv, (newcount + 1 + 1) * sizeof (char *));
810 if (new_gl_pathv == NULL)
813 free (pglob->gl_pathv);
814 pglob->gl_pathv = NULL;
818 pglob->gl_pathv = new_gl_pathv;
820 if (flags & GLOB_MARK)
823 pglob->gl_pathv[newcount] = malloc (dirlen + 2);
824 if (pglob->gl_pathv[newcount] == NULL)
826 p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);
832 pglob->gl_pathv[newcount] = strdup (dirname);
833 if (pglob->gl_pathv[newcount] == NULL)
836 pglob->gl_pathv[++newcount] = NULL;
838 pglob->gl_flags = flags;
847 meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));
848 /* meta is 1 if correct glob pattern containing metacharacters.
849 If meta has bit (1 << 2) set, it means there was an unterminated
850 [ which we handle the same, using fnmatch. Broken unterminated
851 pattern bracket expressions ought to be rare enough that it is
852 not worth special casing them, fnmatch will do the right thing. */
855 /* The directory name contains metacharacters, so we
856 have to glob for the directory, and then glob for
857 the pattern in each directory found. */
860 if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\')
862 /* "foo\\/bar". Remove the final backslash from dirname
863 if it has not been quoted. */
864 char *p = (char *) &dirname[dirlen - 1];
866 while (p > dirname && p[-1] == '\\') --p;
867 if ((&dirname[dirlen] - p) & 1)
868 *(char *) &dirname[--dirlen] = '\0';
871 if (__builtin_expect ((flags & GLOB_ALTDIRFUNC) != 0, 0))
873 /* Use the alternative access functions also in the recursive
875 dirs.gl_opendir = pglob->gl_opendir;
876 dirs.gl_readdir = pglob->gl_readdir;
877 dirs.gl_closedir = pglob->gl_closedir;
878 dirs.gl_stat = pglob->gl_stat;
879 dirs.gl_lstat = pglob->gl_lstat;
882 status = glob (dirname,
883 ((flags & (GLOB_ERR | GLOB_NOESCAPE
885 | GLOB_NOSORT | GLOB_ONLYDIR),
889 if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH)
894 /* We have successfully globbed the preceding directory name.
895 For each name we found, call glob_in_dir on it and FILENAME,
896 appending the results to PGLOB. */
897 for (i = 0; i < dirs.gl_pathc; ++i)
903 /* Make globbing interruptible in the bash shell. */
904 extern int interrupt_state;
914 old_pathc = pglob->gl_pathc;
915 status = glob_in_dir (filename, dirs.gl_pathv[i],
916 ((flags | GLOB_APPEND)
917 & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),
919 if (status == GLOB_NOMATCH)
920 /* No matches in this directory. Try the next. */
931 /* Stick the directory on the front of each name. */
932 if (prefix_array (dirs.gl_pathv[i],
933 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
934 pglob->gl_pathc - old_pathc))
943 flags |= GLOB_MAGCHAR;
945 /* We have ignored the GLOB_NOCHECK flag in the `glob_in_dir' calls.
946 But if we have not found any matching entry and the GLOB_NOCHECK
947 flag was set we must return the input pattern itself. */
948 if (pglob->gl_pathc + pglob->gl_offs == oldcount)
952 if (flags & GLOB_NOCHECK)
954 int newcount = pglob->gl_pathc + pglob->gl_offs;
957 new_gl_pathv = realloc (pglob->gl_pathv,
958 (newcount + 2) * sizeof (char *));
959 if (new_gl_pathv == NULL)
964 pglob->gl_pathv = new_gl_pathv;
966 pglob->gl_pathv[newcount] = strdup (pattern);
967 if (pglob->gl_pathv[newcount] == NULL)
978 pglob->gl_pathv[newcount] = NULL;
979 pglob->gl_flags = flags;
992 int old_pathc = pglob->gl_pathc;
993 int orig_flags = flags;
997 char *p = strchr (dirname, '\\'), *q;
998 /* We need to unescape the dirname string. It is certainly
999 allocated by alloca, as otherwise filename would be NULL
1000 or dirname wouldn't contain backslashes. */
1013 while (*p++ != '\0');
1014 dirname_modified = 1;
1016 if (dirname_modified)
1017 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
1018 status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
1021 if (status == GLOB_NOMATCH && flags != orig_flags
1022 && pglob->gl_pathc + pglob->gl_offs == oldcount)
1024 /* Make sure globfree (&dirs); is a nop. */
1025 dirs.gl_pathv = NULL;
1034 /* Stick the directory on the front of each name. */
1035 if (prefix_array (dirname,
1036 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
1037 pglob->gl_pathc - old_pathc))
1040 pglob->gl_pathc = 0;
1041 return GLOB_NOSPACE;
1046 if (flags & GLOB_MARK)
1048 /* Append slashes to directory names. */
1053 for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)
1054 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1055 ? ((*pglob->gl_stat) (pglob->gl_pathv[i], &st) == 0
1056 && S_ISDIR (st.st_mode))
1057 : (__stat64 (pglob->gl_pathv[i], &st64) == 0
1058 && S_ISDIR (st64.st_mode))))
1060 size_t len = strlen (pglob->gl_pathv[i]) + 2;
1061 char *new = realloc (pglob->gl_pathv[i], len);
1065 pglob->gl_pathc = 0;
1066 return GLOB_NOSPACE;
1068 strcpy (&new[len - 2], "/");
1069 pglob->gl_pathv[i] = new;
1073 if (!(flags & GLOB_NOSORT))
1075 /* Sort the vector. */
1076 qsort (&pglob->gl_pathv[oldcount],
1077 pglob->gl_pathc + pglob->gl_offs - oldcount,
1078 sizeof (char *), collated_compare);
1083 #if defined _LIBC && !defined glob
1084 libc_hidden_def (glob)
1088 #if !defined _LIBC || !defined GLOB_ONLY_P
1090 /* Free storage allocated in PGLOB by a previous `glob' call. */
1093 register glob_t *pglob;
1095 if (pglob->gl_pathv != NULL)
1098 for (i = 0; i < pglob->gl_pathc; ++i)
1099 if (pglob->gl_pathv[pglob->gl_offs + i] != NULL)
1100 free (pglob->gl_pathv[pglob->gl_offs + i]);
1101 free (pglob->gl_pathv);
1102 pglob->gl_pathv = NULL;
1105 #if defined _LIBC && !defined globfree
1106 libc_hidden_def (globfree)
1110 /* Do a collated comparison of A and B. */
1112 collated_compare (const void *a, const void *b)
1114 char *const *ps1 = a; char *s1 = *ps1;
1115 char *const *ps2 = b; char *s2 = *ps2;
1123 return strcoll (s1, s2);
1127 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1128 elements in place. Return nonzero if out of memory, zero if successful.
1129 A slash is inserted between DIRNAME and each elt of ARRAY,
1130 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1132 prefix_array (const char *dirname, char **array, size_t n)
1135 size_t dirlen = strlen (dirname);
1136 #if defined __MSDOS__ || defined WINDOWS32
1138 # define DIRSEP_CHAR sep_char
1140 # define DIRSEP_CHAR '/'
1143 if (dirlen == 1 && dirname[0] == '/')
1144 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1145 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1147 #if defined __MSDOS__ || defined WINDOWS32
1148 else if (dirlen > 1)
1150 if (dirname[dirlen - 1] == '/' && dirname[dirlen - 2] == ':')
1151 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1153 else if (dirname[dirlen - 1] == ':')
1155 /* DIRNAME is "d:". Use `:' instead of `/'. */
1162 for (i = 0; i < n; ++i)
1164 size_t eltlen = strlen (array[i]) + 1;
1165 char *new = malloc (dirlen + 1 + eltlen);
1174 char *endp = mempcpy (new, dirname, dirlen);
1175 *endp++ = DIRSEP_CHAR;
1176 mempcpy (endp, array[i], eltlen);
1186 /* We must not compile this function twice. */
1187 #if !defined _LIBC || !defined NO_GLOB_PATTERN_P
1189 __glob_pattern_type (pattern, quote)
1190 const char *pattern;
1193 register const char *p;
1196 for (p = pattern; *p != '\0'; ++p)
1225 /* Return nonzero if PATTERN contains any metacharacters.
1226 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
1228 __glob_pattern_p (pattern, quote)
1229 const char *pattern;
1232 return __glob_pattern_type (pattern, quote) == 1;
1235 weak_alias (__glob_pattern_p, glob_pattern_p)
1239 #endif /* !GLOB_ONLY_P */
1242 #if !defined _LIBC || !defined GLOB_ONLY_P
1243 /* We put this in a separate function mainly to allow the memory
1244 allocated with alloca to be recycled. */
1246 __attribute_noinline__
1247 link_exists2_p (const char *dir, size_t dirlen, const char *fname,
1249 # if !defined _LIBC && !HAVE_FSTATAT
1254 size_t fnamelen = strlen (fname);
1255 char *fullname = __alloca (dirlen + 1 + fnamelen + 1);
1258 mempcpy (mempcpy (mempcpy (fullname, dir, dirlen), "/", 1),
1259 fname, fnamelen + 1);
1261 # if !defined _LIBC && !HAVE_FSTATAT
1262 if (__builtin_expect ((flags & GLOB_ALTDIRFUNC) == 0, 1))
1265 return __stat64 (fullname, &st64) == 0;
1268 return (*pglob->gl_stat) (fullname, &st) == 0;
1271 /* Return true if DIR/FNAME exists. */
1273 link_exists_p (int dfd, const char *dir, size_t dirlen, const char *fname,
1274 glob_t *pglob, int flags)
1276 # if defined _LIBC || HAVE_FSTATAT
1277 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1278 return link_exists2_p (dir, dirlen, fname, pglob);
1282 return __fxstatat64 (_STAT_VER, dfd, fname, &st64, 0) == 0;
1285 return link_exists2_p (dir, dirlen, fname, pglob, flags);
1291 /* Like `glob', but PATTERN is a final pathname component,
1292 and matches are searched for in DIRECTORY.
1293 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1294 The GLOB_APPEND flag is assumed to be set (always appends). */
1296 glob_in_dir (const char *pattern, const char *directory, int flags,
1297 int (*errfunc) (const char *, int),
1300 size_t dirlen = strlen (directory);
1301 void *stream = NULL;
1304 struct globnames *next;
1308 #define INITIAL_COUNT sizeof (init_names.name) / sizeof (init_names.name[0])
1309 struct globnames init_names;
1310 struct globnames *names = &init_names;
1311 struct globnames *names_alloca = &init_names;
1313 size_t allocasize = sizeof (init_names);
1319 init_names.next = NULL;
1320 init_names.count = INITIAL_COUNT;
1322 meta = __glob_pattern_type (pattern, !(flags & GLOB_NOESCAPE));
1323 if (meta == 0 && (flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
1325 /* We need not do any tests. The PATTERN contains no meta
1326 characters and we must not return an error therefore the
1327 result will always contain exactly one name. */
1328 flags |= GLOB_NOCHECK;
1332 /* Since we use the normal file functions we can also use stat()
1333 to verify the file is there. */
1336 size_t patlen = strlen (pattern);
1337 char *fullname = __alloca (dirlen + 1 + patlen + 1);
1339 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1341 pattern, patlen + 1);
1342 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1343 ? (*pglob->gl_stat) (fullname, &st)
1344 : __stat64 (fullname, &st64)) == 0)
1345 /* We found this file to be existing. Now tell the rest
1346 of the function to copy this name into the result. */
1347 flags |= GLOB_NOCHECK;
1351 stream = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1352 ? (*pglob->gl_opendir) (directory)
1353 : opendir (directory));
1356 if (errno != ENOTDIR
1357 && ((errfunc != NULL && (*errfunc) (directory, errno))
1358 || (flags & GLOB_ERR)))
1359 return GLOB_ABORTED;
1363 int dfd = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1364 ? -1 : dirfd ((DIR *) stream));
1365 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1366 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1367 #if defined _AMIGA || defined VMS
1371 flags |= GLOB_MAGCHAR;
1377 #if defined _LIBC && !defined COMPILE_GLOB64
1381 struct dirent64 d64;
1382 char room [offsetof (struct dirent64, d_name[0])
1387 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1389 struct dirent *d32 = (*pglob->gl_readdir) (stream);
1392 CONVERT_DIRENT_DIRENT64 (&d64buf.d64, d32);
1399 d = __readdir64 (stream);
1401 struct dirent *d = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1402 ? ((struct dirent *)
1403 (*pglob->gl_readdir) (stream))
1404 : __readdir (stream));
1408 if (! REAL_DIR_ENTRY (d))
1411 /* If we shall match only directories use the information
1412 provided by the dirent call if possible. */
1413 if ((flags & GLOB_ONLYDIR) && !DIRENT_MIGHT_BE_DIR (d))
1418 if (fnmatch (pattern, name, fnm_flags) == 0)
1420 /* If the file we found is a symlink we have to
1421 make sure the target file exists. */
1422 if (!DIRENT_MIGHT_BE_SYMLINK (d)
1423 || link_exists_p (dfd, directory, dirlen, name, pglob,
1426 if (cur == names->count)
1428 struct globnames *newnames;
1429 size_t count = names->count * 2;
1430 size_t size = (sizeof (struct globnames)
1431 + ((count - INITIAL_COUNT)
1432 * sizeof (char *)));
1434 if (__libc_use_alloca (allocasize))
1435 newnames = names_alloca = __alloca (size);
1436 else if ((newnames = malloc (size))
1439 newnames->count = count;
1440 newnames->next = names;
1444 len = _D_EXACT_NAMLEN (d);
1445 names->name[cur] = malloc (len + 1);
1446 if (names->name[cur] == NULL)
1448 *((char *) mempcpy (names->name[cur++], name, len))
1457 if (nfound == 0 && (flags & GLOB_NOCHECK))
1459 size_t len = strlen (pattern);
1461 names->name[cur] = malloc (len + 1);
1462 if (names->name[cur] == NULL)
1464 *((char *) mempcpy (names->name[cur++], pattern, len)) = '\0';
1467 result = GLOB_NOMATCH;
1471 = realloc (pglob->gl_pathv,
1472 (pglob->gl_pathc + pglob->gl_offs + nfound + 1)
1476 if (new_gl_pathv == NULL)
1481 struct globnames *old = names;
1483 for (i = 0; i < cur; ++i)
1484 free (names->name[i]);
1485 names = names->next;
1486 /* NB: we will not leak memory here if we exit without
1487 freeing the current block assigned to OLD. At least
1488 the very first block is always allocated on the stack
1489 and this is the block assigned to OLD here. */
1492 assert (old == &init_names);
1496 if (old == names_alloca)
1497 names_alloca = names;
1501 result = GLOB_NOSPACE;
1507 struct globnames *old = names;
1509 for (i = 0; i < cur; ++i)
1510 new_gl_pathv[pglob->gl_offs + pglob->gl_pathc++]
1512 names = names->next;
1513 /* NB: we will not leak memory here if we exit without
1514 freeing the current block assigned to OLD. At least
1515 the very first block is always allocated on the stack
1516 and this is the block assigned to OLD here. */
1519 assert (old == &init_names);
1523 if (old == names_alloca)
1524 names_alloca = names;
1529 pglob->gl_pathv = new_gl_pathv;
1531 pglob->gl_pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
1533 pglob->gl_flags = flags;
1540 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1541 (*pglob->gl_closedir) (stream);