Updated to fedora-glibc-20070221T1011
[glibc.git] / posix / glob.c
blob6d8a8913408b17ba56c3be015682d1705f030f1d
1 /* Copyright (C) 1991-2002, 2003, 2004, 2005, 2006, 2007
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
18 02111-1307 USA. */
20 #ifdef HAVE_CONFIG_H
21 # include <config.h>
22 #endif
24 #include <glob.h>
26 #include <errno.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <stddef.h>
31 /* Outcomment the following line for production quality code. */
32 /* #define NDEBUG 1 */
33 #include <assert.h>
35 #include <stdio.h> /* Needed on stupid SunOS for assert. */
37 #if !defined _LIBC || !defined GLOB_ONLY_P
38 #if defined HAVE_UNISTD_H || defined _LIBC
39 # include <unistd.h>
40 # ifndef POSIX
41 # ifdef _POSIX_VERSION
42 # define POSIX
43 # endif
44 # endif
45 #endif
47 #include <pwd.h>
49 #include <errno.h>
50 #ifndef __set_errno
51 # define __set_errno(val) errno = (val)
52 #endif
54 #if defined HAVE_DIRENT_H || defined __GNU_LIBRARY__
55 # include <dirent.h>
56 # define NAMLEN(dirent) strlen((dirent)->d_name)
57 #else
58 # define dirent direct
59 # define NAMLEN(dirent) (dirent)->d_namlen
60 # ifdef HAVE_SYS_NDIR_H
61 # include <sys/ndir.h>
62 # endif
63 # ifdef HAVE_SYS_DIR_H
64 # include <sys/dir.h>
65 # endif
66 # ifdef HAVE_NDIR_H
67 # include <ndir.h>
68 # endif
69 # ifdef HAVE_VMSDIR_H
70 # include "vmsdir.h"
71 # endif /* HAVE_VMSDIR_H */
72 #endif
75 /* In GNU systems, <dirent.h> defines this macro for us. */
76 #ifdef _D_NAMLEN
77 # undef NAMLEN
78 # define NAMLEN(d) _D_NAMLEN(d)
79 #endif
81 /* When used in the GNU libc the symbol _DIRENT_HAVE_D_TYPE is available
82 if the `d_type' member for `struct dirent' is available.
83 HAVE_STRUCT_DIRENT_D_TYPE plays the same role in GNULIB. */
84 #if defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE
85 /* True if the directory entry D must be of type T. */
86 # define DIRENT_MUST_BE(d, t) ((d)->d_type == (t))
88 /* True if the directory entry D might be a symbolic link. */
89 # define DIRENT_MIGHT_BE_SYMLINK(d) \
90 ((d)->d_type == DT_UNKNOWN || (d)->d_type == DT_LNK)
92 /* True if the directory entry D might be a directory. */
93 # define DIRENT_MIGHT_BE_DIR(d) \
94 ((d)->d_type == DT_DIR || DIRENT_MIGHT_BE_SYMLINK (d))
96 #else /* !HAVE_D_TYPE */
97 # define DIRENT_MUST_BE(d, t) false
98 # define DIRENT_MIGHT_BE_SYMLINK(d) true
99 # define DIRENT_MIGHT_BE_DIR(d) true
100 #endif /* HAVE_D_TYPE */
102 /* If the system has the `struct dirent64' type we use it internally. */
103 #if defined _LIBC && !defined COMPILE_GLOB64
104 # if defined HAVE_DIRENT_H || defined __GNU_LIBRARY__
105 # define CONVERT_D_NAMLEN(d64, d32)
106 # else
107 # define CONVERT_D_NAMLEN(d64, d32) \
108 (d64)->d_namlen = (d32)->d_namlen;
109 # endif
111 # if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
112 # define CONVERT_D_INO(d64, d32)
113 # else
114 # define CONVERT_D_INO(d64, d32) \
115 (d64)->d_ino = (d32)->d_ino;
116 # endif
118 # ifdef _DIRENT_HAVE_D_TYPE
119 # define CONVERT_D_TYPE(d64, d32) \
120 (d64)->d_type = (d32)->d_type;
121 # else
122 # define CONVERT_D_TYPE(d64, d32)
123 # endif
125 # define CONVERT_DIRENT_DIRENT64(d64, d32) \
126 memcpy ((d64)->d_name, (d32)->d_name, NAMLEN (d32) + 1); \
127 CONVERT_D_NAMLEN (d64, d32) \
128 CONVERT_D_INO (d64, d32) \
129 CONVERT_D_TYPE (d64, d32)
130 #endif
133 #if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
134 /* Posix does not require that the d_ino field be present, and some
135 systems do not provide it. */
136 # define REAL_DIR_ENTRY(dp) 1
137 #else
138 # define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
139 #endif /* POSIX */
141 #include <stdlib.h>
142 #include <string.h>
144 /* NAME_MAX is usually defined in <dirent.h> or <limits.h>. */
145 #include <limits.h>
146 #ifndef NAME_MAX
147 # define NAME_MAX (sizeof (((struct dirent *) 0)->d_name))
148 #endif
150 #include <alloca.h>
152 #ifdef _LIBC
153 # undef strdup
154 # define strdup(str) __strdup (str)
155 # define sysconf(id) __sysconf (id)
156 # define closedir(dir) __closedir (dir)
157 # define opendir(name) __opendir (name)
158 # define readdir(str) __readdir64 (str)
159 # define getpwnam_r(name, bufp, buf, len, res) \
160 __getpwnam_r (name, bufp, buf, len, res)
161 # ifndef __stat64
162 # define __stat64(fname, buf) __xstat64 (_STAT_VER, fname, buf)
163 # endif
164 # define struct_stat64 struct stat64
165 #else /* !_LIBC */
166 # include "getlogin_r.h"
167 # include "mempcpy.h"
168 # include "stat-macros.h"
169 # include "strdup.h"
170 # define __stat64(fname, buf) stat (fname, buf)
171 # define struct_stat64 struct stat
172 # define __stat(fname, buf) stat (fname, buf)
173 # define __alloca alloca
174 # define __readdir readdir
175 # define __readdir64 readdir64
176 # define __glob_pattern_p glob_pattern_p
177 #endif /* _LIBC */
179 #include <fnmatch.h>
181 #ifdef _SC_GETPW_R_SIZE_MAX
182 # define GETPW_R_SIZE_MAX() sysconf (_SC_GETPW_R_SIZE_MAX)
183 #else
184 # define GETPW_R_SIZE_MAX() (-1)
185 #endif
186 #ifdef _SC_LOGIN_NAME_MAX
187 # define GET_LOGIN_NAME_MAX() sysconf (_SC_LOGIN_NAME_MAX)
188 #else
189 # define GET_LOGIN_NAME_MAX() (-1)
190 #endif
192 static const char *next_brace_sub (const char *begin, int flags) __THROW;
194 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
196 #ifndef attribute_hidden
197 # define attribute_hidden
198 #endif
200 static int glob_in_dir (const char *pattern, const char *directory,
201 int flags, int (*errfunc) (const char *, int),
202 glob_t *pglob);
203 extern int __glob_pattern_type (const char *pattern, int quote)
204 attribute_hidden;
206 #if !defined _LIBC || !defined GLOB_ONLY_P
207 static int prefix_array (const char *prefix, char **array, size_t n) __THROW;
208 static int collated_compare (const void *, const void *) __THROW;
211 /* Find the end of the sub-pattern in a brace expression. */
212 static const char *
213 next_brace_sub (const char *cp, int flags)
215 unsigned int depth = 0;
216 while (*cp != '\0')
217 if ((flags & GLOB_NOESCAPE) == 0 && *cp == '\\')
219 if (*++cp == '\0')
220 break;
221 ++cp;
223 else
225 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
226 break;
228 if (*cp++ == '{')
229 depth++;
232 return *cp != '\0' ? cp : NULL;
235 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
237 /* Do glob searching for PATTERN, placing results in PGLOB.
238 The bits defined above may be set in FLAGS.
239 If a directory cannot be opened or read and ERRFUNC is not nil,
240 it is called with the pathname that caused the error, and the
241 `errno' value from the failing call; if it returns non-zero
242 `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
243 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
244 Otherwise, `glob' returns zero. */
246 #ifdef GLOB_ATTRIBUTE
247 GLOB_ATTRIBUTE
248 #endif
249 glob (pattern, flags, errfunc, pglob)
250 const char *pattern;
251 int flags;
252 int (*errfunc) (const char *, int);
253 glob_t *pglob;
255 const char *filename;
256 const char *dirname;
257 size_t dirlen;
258 int status;
259 size_t oldcount;
260 int meta;
261 int dirname_modified;
262 glob_t dirs;
264 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
266 __set_errno (EINVAL);
267 return -1;
270 if (!(flags & GLOB_DOOFFS))
271 /* Have to do this so `globfree' knows where to start freeing. It
272 also makes all the code that uses gl_offs simpler. */
273 pglob->gl_offs = 0;
275 if (flags & GLOB_BRACE)
277 const char *begin;
279 if (flags & GLOB_NOESCAPE)
280 begin = strchr (pattern, '{');
281 else
283 begin = pattern;
284 while (1)
286 if (*begin == '\0')
288 begin = NULL;
289 break;
292 if (*begin == '\\' && begin[1] != '\0')
293 ++begin;
294 else if (*begin == '{')
295 break;
297 ++begin;
301 if (begin != NULL)
303 /* Allocate working buffer large enough for our work. Note that
304 we have at least an opening and closing brace. */
305 size_t firstc;
306 char *alt_start;
307 const char *p;
308 const char *next;
309 const char *rest;
310 size_t rest_len;
311 #ifdef __GNUC__
312 char onealt[strlen (pattern) - 1];
313 #else
314 char *onealt = (char *) malloc (strlen (pattern) - 1);
315 if (onealt == NULL)
317 if (!(flags & GLOB_APPEND))
319 pglob->gl_pathc = 0;
320 pglob->gl_pathv = NULL;
322 return GLOB_NOSPACE;
324 #endif
326 /* We know the prefix for all sub-patterns. */
327 alt_start = mempcpy (onealt, pattern, begin - pattern);
329 /* Find the first sub-pattern and at the same time find the
330 rest after the closing brace. */
331 next = next_brace_sub (begin + 1, flags);
332 if (next == NULL)
334 /* It is an illegal expression. */
335 #ifndef __GNUC__
336 free (onealt);
337 #endif
338 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
341 /* Now find the end of the whole brace expression. */
342 rest = next;
343 while (*rest != '}')
345 rest = next_brace_sub (rest + 1, flags);
346 if (rest == NULL)
348 /* It is an illegal expression. */
349 #ifndef __GNUC__
350 free (onealt);
351 #endif
352 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
355 /* Please note that we now can be sure the brace expression
356 is well-formed. */
357 rest_len = strlen (++rest) + 1;
359 /* We have a brace expression. BEGIN points to the opening {,
360 NEXT points past the terminator of the first element, and END
361 points past the final }. We will accumulate result names from
362 recursive runs for each brace alternative in the buffer using
363 GLOB_APPEND. */
365 if (!(flags & GLOB_APPEND))
367 /* This call is to set a new vector, so clear out the
368 vector so we can append to it. */
369 pglob->gl_pathc = 0;
370 pglob->gl_pathv = NULL;
372 firstc = pglob->gl_pathc;
374 p = begin + 1;
375 while (1)
377 int result;
379 /* Construct the new glob expression. */
380 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
382 result = glob (onealt,
383 ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))
384 | GLOB_APPEND), errfunc, pglob);
386 /* If we got an error, return it. */
387 if (result && result != GLOB_NOMATCH)
389 #ifndef __GNUC__
390 free (onealt);
391 #endif
392 if (!(flags & GLOB_APPEND))
394 globfree (pglob);
395 pglob->gl_pathc = 0;
397 return result;
400 if (*next == '}')
401 /* We saw the last entry. */
402 break;
404 p = next + 1;
405 next = next_brace_sub (p, flags);
406 assert (next != NULL);
409 #ifndef __GNUC__
410 free (onealt);
411 #endif
413 if (pglob->gl_pathc != firstc)
414 /* We found some entries. */
415 return 0;
416 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
417 return GLOB_NOMATCH;
421 /* Find the filename. */
422 filename = strrchr (pattern, '/');
423 #if defined __MSDOS__ || defined WINDOWS32
424 /* The case of "d:pattern". Since `:' is not allowed in
425 file names, we can safely assume that wherever it
426 happens in pattern, it signals the filename part. This
427 is so we could some day support patterns like "[a-z]:foo". */
428 if (filename == NULL)
429 filename = strchr (pattern, ':');
430 #endif /* __MSDOS__ || WINDOWS32 */
431 dirname_modified = 0;
432 if (filename == NULL)
434 /* This can mean two things: a simple name or "~name". The latter
435 case is nothing but a notation for a directory. */
436 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
438 dirname = pattern;
439 dirlen = strlen (pattern);
441 /* Set FILENAME to NULL as a special flag. This is ugly but
442 other solutions would require much more code. We test for
443 this special case below. */
444 filename = NULL;
446 else
448 filename = pattern;
449 #ifdef _AMIGA
450 dirname = "";
451 #else
452 dirname = ".";
453 #endif
454 dirlen = 0;
457 else if (filename == pattern)
459 /* "/pattern". */
460 dirname = "/";
461 dirlen = 1;
462 ++filename;
464 else
466 char *newp;
467 dirlen = filename - pattern;
468 #if defined __MSDOS__ || defined WINDOWS32
469 if (*filename == ':'
470 || (filename > pattern + 1 && filename[-1] == ':'))
472 char *drive_spec;
474 ++dirlen;
475 drive_spec = (char *) __alloca (dirlen + 1);
476 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
477 /* For now, disallow wildcards in the drive spec, to
478 prevent infinite recursion in glob. */
479 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
480 return GLOB_NOMATCH;
481 /* If this is "d:pattern", we need to copy `:' to DIRNAME
482 as well. If it's "d:/pattern", don't remove the slash
483 from "d:/", since "d:" and "d:/" are not the same.*/
485 #endif
486 newp = (char *) __alloca (dirlen + 1);
487 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
488 dirname = newp;
489 ++filename;
491 if (filename[0] == '\0'
492 #if defined __MSDOS__ || defined WINDOWS32
493 && dirname[dirlen - 1] != ':'
494 && (dirlen < 3 || dirname[dirlen - 2] != ':'
495 || dirname[dirlen - 1] != '/')
496 #endif
497 && dirlen > 1)
498 /* "pattern/". Expand "pattern", appending slashes. */
500 int orig_flags = flags;
501 if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\')
503 /* "pattern\\/". Remove the final backslash if it hasn't
504 been quoted. */
505 char *p = (char *) &dirname[dirlen - 1];
507 while (p > dirname && p[-1] == '\\') --p;
508 if ((&dirname[dirlen] - p) & 1)
510 *(char *) &dirname[--dirlen] = '\0';
511 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
514 int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
515 if (val == 0)
516 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
517 | (flags & GLOB_MARK));
518 else if (val == GLOB_NOMATCH && flags != orig_flags)
520 /* Make sure globfree (&dirs); is a nop. */
521 dirs.gl_pathv = NULL;
522 flags = orig_flags;
523 oldcount = pglob->gl_pathc + pglob->gl_offs;
524 goto no_matches;
526 return val;
530 if (!(flags & GLOB_APPEND))
532 pglob->gl_pathc = 0;
533 if (!(flags & GLOB_DOOFFS))
534 pglob->gl_pathv = NULL;
535 else
537 size_t i;
538 pglob->gl_pathv = (char **) malloc ((pglob->gl_offs + 1)
539 * sizeof (char *));
540 if (pglob->gl_pathv == NULL)
541 return GLOB_NOSPACE;
543 for (i = 0; i <= pglob->gl_offs; ++i)
544 pglob->gl_pathv[i] = NULL;
548 oldcount = pglob->gl_pathc + pglob->gl_offs;
550 #ifndef VMS
551 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
553 if (dirname[1] == '\0' || dirname[1] == '/'
554 || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\'
555 && (dirname[2] == '\0' || dirname[2] == '/')))
557 /* Look up home directory. */
558 const char *home_dir = getenv ("HOME");
559 # ifdef _AMIGA
560 if (home_dir == NULL || home_dir[0] == '\0')
561 home_dir = "SYS:";
562 # else
563 # ifdef WINDOWS32
564 if (home_dir == NULL || home_dir[0] == '\0')
565 home_dir = "c:/users/default"; /* poor default */
566 # else
567 if (home_dir == NULL || home_dir[0] == '\0')
569 int success;
570 char *name;
571 size_t buflen = GET_LOGIN_NAME_MAX () + 1;
573 if (buflen == 0)
574 /* `sysconf' does not support _SC_LOGIN_NAME_MAX. Try
575 a moderate value. */
576 buflen = 20;
577 name = (char *) __alloca (buflen);
579 success = getlogin_r (name, buflen) == 0;
580 if (success)
582 struct passwd *p;
583 # if defined HAVE_GETPWNAM_R || defined _LIBC
584 long int pwbuflen = GETPW_R_SIZE_MAX ();
585 char *pwtmpbuf;
586 struct passwd pwbuf;
587 int save = errno;
589 # ifndef _LIBC
590 if (pwbuflen == -1)
591 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.
592 Try a moderate value. */
593 pwbuflen = 1024;
594 # endif
595 pwtmpbuf = (char *) __alloca (pwbuflen);
597 while (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
598 != 0)
600 if (errno != ERANGE)
602 p = NULL;
603 break;
605 # ifdef _LIBC
606 pwtmpbuf = extend_alloca (pwtmpbuf, pwbuflen,
607 2 * pwbuflen);
608 # else
609 pwbuflen *= 2;
610 pwtmpbuf = (char *) __alloca (pwbuflen);
611 # endif
612 __set_errno (save);
614 # else
615 p = getpwnam (name);
616 # endif
617 if (p != NULL)
618 home_dir = p->pw_dir;
621 if (home_dir == NULL || home_dir[0] == '\0')
623 if (flags & GLOB_TILDE_CHECK)
624 return GLOB_NOMATCH;
625 else
626 home_dir = "~"; /* No luck. */
628 # endif /* WINDOWS32 */
629 # endif
630 /* Now construct the full directory. */
631 if (dirname[1] == '\0')
633 dirname = home_dir;
634 dirlen = strlen (dirname);
636 else
638 char *newp;
639 size_t home_len = strlen (home_dir);
640 newp = (char *) __alloca (home_len + dirlen);
641 mempcpy (mempcpy (newp, home_dir, home_len),
642 &dirname[1], dirlen);
643 dirname = newp;
644 dirlen += home_len - 1;
646 dirname_modified = 1;
648 # if !defined _AMIGA && !defined WINDOWS32
649 else
651 char *end_name = strchr (dirname, '/');
652 const char *user_name;
653 const char *home_dir;
654 char *unescape = NULL;
656 if (!(flags & GLOB_NOESCAPE))
658 if (end_name == NULL)
660 unescape = strchr (dirname, '\\');
661 if (unescape)
662 end_name = strchr (unescape, '\0');
664 else
665 unescape = memchr (dirname, '\\', end_name - dirname);
667 if (end_name == NULL)
668 user_name = dirname + 1;
669 else
671 char *newp;
672 newp = (char *) __alloca (end_name - dirname);
673 if (unescape != NULL)
675 char *p = mempcpy (newp, dirname + 1,
676 unescape - dirname - 1);
677 char *q = unescape;
678 while (*q != '\0')
680 if (*q == '\\')
682 if (q[1] == '\0')
684 /* "~fo\\o\\" unescape to user_name "foo\\",
685 but "~fo\\o\\/" unescape to user_name
686 "foo". */
687 if (filename == NULL)
688 *p++ = '\\';
689 break;
691 ++q;
693 *p++ = *q++;
695 *p = '\0';
697 else
698 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
699 = '\0';
700 user_name = newp;
703 /* Look up specific user's home directory. */
705 struct passwd *p;
706 # if defined HAVE_GETPWNAM_R || defined _LIBC
707 long int buflen = GETPW_R_SIZE_MAX ();
708 char *pwtmpbuf;
709 struct passwd pwbuf;
710 int save = errno;
712 # ifndef _LIBC
713 if (buflen == -1)
714 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
715 moderate value. */
716 buflen = 1024;
717 # endif
718 pwtmpbuf = (char *) __alloca (buflen);
720 while (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) != 0)
722 if (errno != ERANGE)
724 p = NULL;
725 break;
727 # ifdef _LIBC
728 pwtmpbuf = extend_alloca (pwtmpbuf, buflen, 2 * buflen);
729 # else
730 buflen *= 2;
731 pwtmpbuf = __alloca (buflen);
732 # endif
733 __set_errno (save);
735 # else
736 p = getpwnam (user_name);
737 # endif
738 if (p != NULL)
739 home_dir = p->pw_dir;
740 else
741 home_dir = NULL;
743 /* If we found a home directory use this. */
744 if (home_dir != NULL)
746 char *newp;
747 size_t home_len = strlen (home_dir);
748 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
749 newp = (char *) __alloca (home_len + rest_len + 1);
750 *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
751 end_name, rest_len)) = '\0';
752 dirname = newp;
753 dirlen = home_len + rest_len;
754 dirname_modified = 1;
756 else
757 if (flags & GLOB_TILDE_CHECK)
758 /* We have to regard it as an error if we cannot find the
759 home directory. */
760 return GLOB_NOMATCH;
762 # endif /* Not Amiga && not WINDOWS32. */
764 #endif /* Not VMS. */
766 /* Now test whether we looked for "~" or "~NAME". In this case we
767 can give the answer now. */
768 if (filename == NULL)
770 struct stat st;
771 struct_stat64 st64;
773 /* Return the directory if we don't check for error or if it exists. */
774 if ((flags & GLOB_NOCHECK)
775 || (((flags & GLOB_ALTDIRFUNC)
776 ? ((*pglob->gl_stat) (dirname, &st) == 0
777 && S_ISDIR (st.st_mode))
778 : (__stat64 (dirname, &st64) == 0 && S_ISDIR (st64.st_mode)))))
780 int newcount = pglob->gl_pathc + pglob->gl_offs;
781 char **new_gl_pathv;
783 new_gl_pathv
784 = (char **) realloc (pglob->gl_pathv,
785 (newcount + 1 + 1) * sizeof (char *));
786 if (new_gl_pathv == NULL)
788 nospace:
789 free (pglob->gl_pathv);
790 pglob->gl_pathv = NULL;
791 pglob->gl_pathc = 0;
792 return GLOB_NOSPACE;
794 pglob->gl_pathv = new_gl_pathv;
796 if (flags & GLOB_MARK)
798 char *p;
799 pglob->gl_pathv[newcount] = malloc (dirlen + 2);
800 if (pglob->gl_pathv[newcount] == NULL)
801 goto nospace;
802 p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);
803 p[0] = '/';
804 p[1] = '\0';
806 else
808 pglob->gl_pathv[newcount] = strdup (dirname);
809 if (pglob->gl_pathv[newcount] == NULL)
810 goto nospace;
812 pglob->gl_pathv[++newcount] = NULL;
813 ++pglob->gl_pathc;
814 pglob->gl_flags = flags;
816 return 0;
819 /* Not found. */
820 return GLOB_NOMATCH;
823 meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));
824 /* meta is 1 if correct glob pattern containing metacharacters.
825 If meta has bit (1 << 2) set, it means there was an unterminated
826 [ which we handle the same, using fnmatch. Broken unterminated
827 pattern bracket expressions ought to be rare enough that it is
828 not worth special casing them, fnmatch will do the right thing. */
829 if (meta & 5)
831 /* The directory name contains metacharacters, so we
832 have to glob for the directory, and then glob for
833 the pattern in each directory found. */
834 size_t i;
836 if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\')
838 /* "foo\\/bar". Remove the final backslash from dirname
839 if it has not been quoted. */
840 char *p = (char *) &dirname[dirlen - 1];
842 while (p > dirname && p[-1] == '\\') --p;
843 if ((&dirname[dirlen] - p) & 1)
844 *(char *) &dirname[--dirlen] = '\0';
847 if ((flags & GLOB_ALTDIRFUNC) != 0)
849 /* Use the alternative access functions also in the recursive
850 call. */
851 dirs.gl_opendir = pglob->gl_opendir;
852 dirs.gl_readdir = pglob->gl_readdir;
853 dirs.gl_closedir = pglob->gl_closedir;
854 dirs.gl_stat = pglob->gl_stat;
855 dirs.gl_lstat = pglob->gl_lstat;
858 status = glob (dirname,
859 ((flags & (GLOB_ERR | GLOB_NOESCAPE
860 | GLOB_ALTDIRFUNC))
861 | GLOB_NOSORT | GLOB_ONLYDIR),
862 errfunc, &dirs);
863 if (status != 0)
865 if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH)
866 return status;
867 goto no_matches;
870 /* We have successfully globbed the preceding directory name.
871 For each name we found, call glob_in_dir on it and FILENAME,
872 appending the results to PGLOB. */
873 for (i = 0; i < dirs.gl_pathc; ++i)
875 int old_pathc;
877 #ifdef SHELL
879 /* Make globbing interruptible in the bash shell. */
880 extern int interrupt_state;
882 if (interrupt_state)
884 globfree (&dirs);
885 return GLOB_ABORTED;
888 #endif /* SHELL. */
890 old_pathc = pglob->gl_pathc;
891 status = glob_in_dir (filename, dirs.gl_pathv[i],
892 ((flags | GLOB_APPEND)
893 & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),
894 errfunc, pglob);
895 if (status == GLOB_NOMATCH)
896 /* No matches in this directory. Try the next. */
897 continue;
899 if (status != 0)
901 globfree (&dirs);
902 globfree (pglob);
903 pglob->gl_pathc = 0;
904 return status;
907 /* Stick the directory on the front of each name. */
908 if (prefix_array (dirs.gl_pathv[i],
909 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
910 pglob->gl_pathc - old_pathc))
912 globfree (&dirs);
913 globfree (pglob);
914 pglob->gl_pathc = 0;
915 return GLOB_NOSPACE;
919 flags |= GLOB_MAGCHAR;
921 /* We have ignored the GLOB_NOCHECK flag in the `glob_in_dir' calls.
922 But if we have not found any matching entry and the GLOB_NOCHECK
923 flag was set we must return the input pattern itself. */
924 if (pglob->gl_pathc + pglob->gl_offs == oldcount)
926 no_matches:
927 /* No matches. */
928 if (flags & GLOB_NOCHECK)
930 int newcount = pglob->gl_pathc + pglob->gl_offs;
931 char **new_gl_pathv;
933 new_gl_pathv = (char **) realloc (pglob->gl_pathv,
934 (newcount + 2)
935 * sizeof (char *));
936 if (new_gl_pathv == NULL)
938 globfree (&dirs);
939 return GLOB_NOSPACE;
941 pglob->gl_pathv = new_gl_pathv;
943 pglob->gl_pathv[newcount] = __strdup (pattern);
944 if (pglob->gl_pathv[newcount] == NULL)
946 globfree (&dirs);
947 globfree (pglob);
948 pglob->gl_pathc = 0;
949 return GLOB_NOSPACE;
952 ++pglob->gl_pathc;
953 ++newcount;
955 pglob->gl_pathv[newcount] = NULL;
956 pglob->gl_flags = flags;
958 else
960 globfree (&dirs);
961 return GLOB_NOMATCH;
965 globfree (&dirs);
967 else
969 int old_pathc = pglob->gl_pathc;
970 int orig_flags = flags;
972 if (meta & 2)
974 char *p = strchr (dirname, '\\'), *q;
975 /* We need to unescape the dirname string. It is certainly
976 allocated by alloca, as otherwise filename would be NULL
977 or dirname wouldn't contain backslashes. */
978 q = p;
981 if (*p == '\\')
983 *q = *++p;
984 --dirlen;
986 else
987 *q = *p;
988 ++q;
990 while (*p++ != '\0');
991 dirname_modified = 1;
993 if (dirname_modified)
994 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
995 status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
996 if (status != 0)
998 if (status == GLOB_NOMATCH && flags != orig_flags
999 && pglob->gl_pathc + pglob->gl_offs == oldcount)
1001 /* Make sure globfree (&dirs); is a nop. */
1002 dirs.gl_pathv = NULL;
1003 flags = orig_flags;
1004 goto no_matches;
1006 return status;
1009 if (dirlen > 0)
1011 /* Stick the directory on the front of each name. */
1012 if (prefix_array (dirname,
1013 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
1014 pglob->gl_pathc - old_pathc))
1016 globfree (pglob);
1017 pglob->gl_pathc = 0;
1018 return GLOB_NOSPACE;
1023 if (flags & GLOB_MARK)
1025 /* Append slashes to directory names. */
1026 size_t i;
1027 struct stat st;
1028 struct_stat64 st64;
1030 for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)
1031 if (((flags & GLOB_ALTDIRFUNC)
1032 ? ((*pglob->gl_stat) (pglob->gl_pathv[i], &st) == 0
1033 && S_ISDIR (st.st_mode))
1034 : (__stat64 (pglob->gl_pathv[i], &st64) == 0
1035 && S_ISDIR (st64.st_mode))))
1037 size_t len = strlen (pglob->gl_pathv[i]) + 2;
1038 char *new = realloc (pglob->gl_pathv[i], len);
1039 if (new == NULL)
1041 globfree (pglob);
1042 pglob->gl_pathc = 0;
1043 return GLOB_NOSPACE;
1045 strcpy (&new[len - 2], "/");
1046 pglob->gl_pathv[i] = new;
1050 if (!(flags & GLOB_NOSORT))
1052 /* Sort the vector. */
1053 qsort (&pglob->gl_pathv[oldcount],
1054 pglob->gl_pathc + pglob->gl_offs - oldcount,
1055 sizeof (char *), collated_compare);
1058 return 0;
1060 #if defined _LIBC && !defined glob
1061 libc_hidden_def (glob)
1062 #endif
1065 #if !defined _LIBC || !defined GLOB_ONLY_P
1067 /* Free storage allocated in PGLOB by a previous `glob' call. */
1068 void
1069 globfree (pglob)
1070 register glob_t *pglob;
1072 if (pglob->gl_pathv != NULL)
1074 size_t i;
1075 for (i = 0; i < pglob->gl_pathc; ++i)
1076 if (pglob->gl_pathv[pglob->gl_offs + i] != NULL)
1077 free (pglob->gl_pathv[pglob->gl_offs + i]);
1078 free (pglob->gl_pathv);
1079 pglob->gl_pathv = NULL;
1082 #if defined _LIBC && !defined globfree
1083 libc_hidden_def (globfree)
1084 #endif
1087 /* Do a collated comparison of A and B. */
1088 static int
1089 collated_compare (const void *a, const void *b)
1091 const char *const s1 = *(const char *const * const) a;
1092 const char *const s2 = *(const char *const * const) b;
1094 if (s1 == s2)
1095 return 0;
1096 if (s1 == NULL)
1097 return 1;
1098 if (s2 == NULL)
1099 return -1;
1100 return strcoll (s1, s2);
1104 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1105 elements in place. Return nonzero if out of memory, zero if successful.
1106 A slash is inserted between DIRNAME and each elt of ARRAY,
1107 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1108 static int
1109 prefix_array (const char *dirname, char **array, size_t n)
1111 register size_t i;
1112 size_t dirlen = strlen (dirname);
1113 #if defined __MSDOS__ || defined WINDOWS32
1114 int sep_char = '/';
1115 # define DIRSEP_CHAR sep_char
1116 #else
1117 # define DIRSEP_CHAR '/'
1118 #endif
1120 if (dirlen == 1 && dirname[0] == '/')
1121 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1122 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1123 dirlen = 0;
1124 #if defined __MSDOS__ || defined WINDOWS32
1125 else if (dirlen > 1)
1127 if (dirname[dirlen - 1] == '/' && dirname[dirlen - 2] == ':')
1128 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1129 --dirlen;
1130 else if (dirname[dirlen - 1] == ':')
1132 /* DIRNAME is "d:". Use `:' instead of `/'. */
1133 --dirlen;
1134 sep_char = ':';
1137 #endif
1139 for (i = 0; i < n; ++i)
1141 size_t eltlen = strlen (array[i]) + 1;
1142 char *new = (char *) malloc (dirlen + 1 + eltlen);
1143 if (new == NULL)
1145 while (i > 0)
1146 free (array[--i]);
1147 return 1;
1151 char *endp = mempcpy (new, dirname, dirlen);
1152 *endp++ = DIRSEP_CHAR;
1153 mempcpy (endp, array[i], eltlen);
1155 free (array[i]);
1156 array[i] = new;
1159 return 0;
1163 /* We must not compile this function twice. */
1164 #if !defined _LIBC || !defined NO_GLOB_PATTERN_P
1166 __glob_pattern_type (pattern, quote)
1167 const char *pattern;
1168 int quote;
1170 register const char *p;
1171 int ret = 0;
1173 for (p = pattern; *p != '\0'; ++p)
1174 switch (*p)
1176 case '?':
1177 case '*':
1178 return 1;
1180 case '\\':
1181 if (quote)
1183 if (p[1] != '\0')
1184 ++p;
1185 ret |= 2;
1187 break;
1189 case '[':
1190 ret |= 4;
1191 break;
1193 case ']':
1194 if (ret & 4)
1195 return 1;
1196 break;
1199 return ret;
1202 /* Return nonzero if PATTERN contains any metacharacters.
1203 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
1205 __glob_pattern_p (pattern, quote)
1206 const char *pattern;
1207 int quote;
1209 return __glob_pattern_type (pattern, quote) == 1;
1211 # ifdef _LIBC
1212 weak_alias (__glob_pattern_p, glob_pattern_p)
1213 # endif
1214 #endif
1216 #endif /* !GLOB_ONLY_P */
1219 /* We put this in a separate function mainly to allow the memory
1220 allocated with alloca to be recycled. */
1221 #if !defined _LIBC || !defined GLOB_ONLY_P
1222 static int
1223 link_exists_p (const char *dir, size_t dirlen, const char *fname,
1224 glob_t *pglob, int flags)
1226 size_t fnamelen = strlen (fname);
1227 char *fullname = (char *) __alloca (dirlen + 1 + fnamelen + 1);
1228 struct stat st;
1229 struct_stat64 st64;
1231 mempcpy (mempcpy (mempcpy (fullname, dir, dirlen), "/", 1),
1232 fname, fnamelen + 1);
1234 return (((flags & GLOB_ALTDIRFUNC)
1235 ? (*pglob->gl_stat) (fullname, &st)
1236 : __stat64 (fullname, &st64)) == 0);
1238 #endif
1241 /* Like `glob', but PATTERN is a final pathname component,
1242 and matches are searched for in DIRECTORY.
1243 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1244 The GLOB_APPEND flag is assumed to be set (always appends). */
1245 static int
1246 glob_in_dir (const char *pattern, const char *directory, int flags,
1247 int (*errfunc) (const char *, int),
1248 glob_t *pglob)
1250 size_t dirlen = strlen (directory);
1251 void *stream = NULL;
1252 struct globnames
1254 struct globnames *next;
1255 size_t count;
1256 char *name[64];
1258 #define INITIAL_COUNT sizeof (init_names.name) / sizeof (init_names.name[0])
1259 struct globnames init_names;
1260 struct globnames *names = &init_names;
1261 struct globnames *names_alloca = &init_names;
1262 size_t nfound = 0;
1263 size_t allocasize = sizeof (init_names);
1264 size_t cur = 0;
1265 int meta;
1266 int save;
1268 init_names.next = NULL;
1269 init_names.count = INITIAL_COUNT;
1271 meta = __glob_pattern_type (pattern, !(flags & GLOB_NOESCAPE));
1272 if (meta == 0 && (flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
1274 /* We need not do any tests. The PATTERN contains no meta
1275 characters and we must not return an error therefore the
1276 result will always contain exactly one name. */
1277 flags |= GLOB_NOCHECK;
1279 else if (meta == 0)
1281 /* Since we use the normal file functions we can also use stat()
1282 to verify the file is there. */
1283 struct stat st;
1284 struct_stat64 st64;
1285 size_t patlen = strlen (pattern);
1286 char *fullname = (char *) __alloca (dirlen + 1 + patlen + 1);
1288 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1289 "/", 1),
1290 pattern, patlen + 1);
1291 if (((flags & GLOB_ALTDIRFUNC)
1292 ? (*pglob->gl_stat) (fullname, &st)
1293 : __stat64 (fullname, &st64)) == 0)
1294 /* We found this file to be existing. Now tell the rest
1295 of the function to copy this name into the result. */
1296 flags |= GLOB_NOCHECK;
1298 else
1300 stream = ((flags & GLOB_ALTDIRFUNC)
1301 ? (*pglob->gl_opendir) (directory)
1302 : opendir (directory));
1303 if (stream == NULL)
1305 if (errno != ENOTDIR
1306 && ((errfunc != NULL && (*errfunc) (directory, errno))
1307 || (flags & GLOB_ERR)))
1308 return GLOB_ABORTED;
1310 else
1312 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1313 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1314 #if defined _AMIGA || defined VMS
1315 | FNM_CASEFOLD
1316 #endif
1318 flags |= GLOB_MAGCHAR;
1320 while (1)
1322 const char *name;
1323 size_t len;
1324 #if defined _LIBC && !defined COMPILE_GLOB64
1325 struct dirent64 *d;
1326 union
1328 struct dirent64 d64;
1329 char room [offsetof (struct dirent64, d_name[0])
1330 + NAME_MAX + 1];
1332 d64buf;
1334 if (flags & GLOB_ALTDIRFUNC)
1336 struct dirent *d32 = (*pglob->gl_readdir) (stream);
1337 if (d32 != NULL)
1339 CONVERT_DIRENT_DIRENT64 (&d64buf.d64, d32);
1340 d = &d64buf.d64;
1342 else
1343 d = NULL;
1345 else
1346 d = __readdir64 (stream);
1347 #else
1348 struct dirent *d = ((flags & GLOB_ALTDIRFUNC)
1349 ? ((struct dirent *)
1350 (*pglob->gl_readdir) (stream))
1351 : __readdir (stream));
1352 #endif
1353 if (d == NULL)
1354 break;
1355 if (! REAL_DIR_ENTRY (d))
1356 continue;
1358 /* If we shall match only directories use the information
1359 provided by the dirent call if possible. */
1360 if ((flags & GLOB_ONLYDIR) && !DIRENT_MIGHT_BE_DIR (d))
1361 continue;
1363 name = d->d_name;
1365 if (fnmatch (pattern, name, fnm_flags) == 0)
1367 /* If the file we found is a symlink we have to
1368 make sure the target file exists. */
1369 if (!DIRENT_MIGHT_BE_SYMLINK (d)
1370 || link_exists_p (directory, dirlen, name, pglob,
1371 flags))
1373 if (cur == names->count)
1375 struct globnames *newnames;
1376 size_t count = names->count * 2;
1377 size_t size = (sizeof (struct globnames)
1378 + ((count - INITIAL_COUNT)
1379 * sizeof (char *)));
1380 allocasize += size;
1381 if (__libc_use_alloca (allocasize))
1382 newnames = names_alloca = __alloca (size);
1383 else if ((newnames = malloc (size))
1384 == NULL)
1385 goto memory_error;
1386 newnames->count = count;
1387 newnames->next = names;
1388 names = newnames;
1389 cur = 0;
1391 len = NAMLEN (d);
1392 names->name[cur] = (char *) malloc (len + 1);
1393 if (names->name[cur] == NULL)
1394 goto memory_error;
1395 *((char *) mempcpy (names->name[cur++], name, len))
1396 = '\0';
1397 ++nfound;
1404 if (nfound == 0 && (flags & GLOB_NOCHECK))
1406 size_t len = strlen (pattern);
1407 nfound = 1;
1408 names->name[cur] = (char *) malloc (len + 1);
1409 if (names->name[cur] == NULL)
1410 goto memory_error;
1411 *((char *) mempcpy (names->name[cur++], pattern, len)) = '\0';
1414 int result = GLOB_NOMATCH;
1415 if (nfound != 0)
1417 result = 0;
1419 char **new_gl_pathv;
1420 new_gl_pathv
1421 = (char **) realloc (pglob->gl_pathv,
1422 (pglob->gl_pathc + pglob->gl_offs + nfound + 1)
1423 * sizeof (char *));
1424 if (new_gl_pathv == NULL)
1426 memory_error:
1427 while (1)
1429 struct globnames *old = names;
1430 for (size_t i = 0; i < cur; ++i)
1431 free (names->name[i]);
1432 names = names->next;
1433 /* NB: we will not leak memory here if we exit without
1434 freeing the current block assigned to OLD. At least
1435 the very first block is always allocated on the stack
1436 and this is the block assigned to OLD here. */
1437 if (names == NULL)
1439 assert (old == &init_names);
1440 break;
1442 cur = names->count;
1443 if (old == names_alloca)
1444 names_alloca = names;
1445 else
1446 free (old);
1448 result = GLOB_NOSPACE;
1450 else
1452 while (1)
1454 struct globnames *old = names;
1455 for (size_t i = 0; i < cur; ++i)
1456 new_gl_pathv[pglob->gl_offs + pglob->gl_pathc++]
1457 = names->name[i];
1458 names = names->next;
1459 /* NB: we will not leak memory here if we exit without
1460 freeing the current block assigned to OLD. At least
1461 the very first block is always allocated on the stack
1462 and this is the block assigned to OLD here. */
1463 if (names == NULL)
1465 assert (old == &init_names);
1466 break;
1468 cur = names->count;
1469 if (old == names_alloca)
1470 names_alloca = names;
1471 else
1472 free (old);
1475 pglob->gl_pathv = new_gl_pathv;
1477 pglob->gl_pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
1479 pglob->gl_flags = flags;
1483 if (stream != NULL)
1485 save = errno;
1486 if (flags & GLOB_ALTDIRFUNC)
1487 (*pglob->gl_closedir) (stream);
1488 else
1489 closedir (stream);
1490 __set_errno (save);
1493 return result;