Updated to fedora-glibc-20071010T2047
[glibc.git] / posix / glob.c
blobd6a1a4a2d1618eb04f102387296b5b71c2ea3434
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
458 || (filename == pattern + 1 && pattern[0] == '\\'
459 && (flags & GLOB_NOESCAPE) == 0))
461 /* "/pattern" or "\\/pattern". */
462 dirname = "/";
463 dirlen = 1;
464 ++filename;
466 else
468 char *newp;
469 dirlen = filename - pattern;
470 #if defined __MSDOS__ || defined WINDOWS32
471 if (*filename == ':'
472 || (filename > pattern + 1 && filename[-1] == ':'))
474 char *drive_spec;
476 ++dirlen;
477 drive_spec = (char *) __alloca (dirlen + 1);
478 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
479 /* For now, disallow wildcards in the drive spec, to
480 prevent infinite recursion in glob. */
481 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
482 return GLOB_NOMATCH;
483 /* If this is "d:pattern", we need to copy `:' to DIRNAME
484 as well. If it's "d:/pattern", don't remove the slash
485 from "d:/", since "d:" and "d:/" are not the same.*/
487 #endif
488 newp = (char *) __alloca (dirlen + 1);
489 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
490 dirname = newp;
491 ++filename;
493 if (filename[0] == '\0'
494 #if defined __MSDOS__ || defined WINDOWS32
495 && dirname[dirlen - 1] != ':'
496 && (dirlen < 3 || dirname[dirlen - 2] != ':'
497 || dirname[dirlen - 1] != '/')
498 #endif
499 && dirlen > 1)
500 /* "pattern/". Expand "pattern", appending slashes. */
502 int orig_flags = flags;
503 if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\')
505 /* "pattern\\/". Remove the final backslash if it hasn't
506 been quoted. */
507 char *p = (char *) &dirname[dirlen - 1];
509 while (p > dirname && p[-1] == '\\') --p;
510 if ((&dirname[dirlen] - p) & 1)
512 *(char *) &dirname[--dirlen] = '\0';
513 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
516 int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
517 if (val == 0)
518 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
519 | (flags & GLOB_MARK));
520 else if (val == GLOB_NOMATCH && flags != orig_flags)
522 /* Make sure globfree (&dirs); is a nop. */
523 dirs.gl_pathv = NULL;
524 flags = orig_flags;
525 oldcount = pglob->gl_pathc + pglob->gl_offs;
526 goto no_matches;
528 return val;
532 if (!(flags & GLOB_APPEND))
534 pglob->gl_pathc = 0;
535 if (!(flags & GLOB_DOOFFS))
536 pglob->gl_pathv = NULL;
537 else
539 size_t i;
540 pglob->gl_pathv = (char **) malloc ((pglob->gl_offs + 1)
541 * sizeof (char *));
542 if (pglob->gl_pathv == NULL)
543 return GLOB_NOSPACE;
545 for (i = 0; i <= pglob->gl_offs; ++i)
546 pglob->gl_pathv[i] = NULL;
550 oldcount = pglob->gl_pathc + pglob->gl_offs;
552 #ifndef VMS
553 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
555 if (dirname[1] == '\0' || dirname[1] == '/'
556 || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\'
557 && (dirname[2] == '\0' || dirname[2] == '/')))
559 /* Look up home directory. */
560 const char *home_dir = getenv ("HOME");
561 # ifdef _AMIGA
562 if (home_dir == NULL || home_dir[0] == '\0')
563 home_dir = "SYS:";
564 # else
565 # ifdef WINDOWS32
566 if (home_dir == NULL || home_dir[0] == '\0')
567 home_dir = "c:/users/default"; /* poor default */
568 # else
569 if (home_dir == NULL || home_dir[0] == '\0')
571 int success;
572 char *name;
573 size_t buflen = GET_LOGIN_NAME_MAX () + 1;
575 if (buflen == 0)
576 /* `sysconf' does not support _SC_LOGIN_NAME_MAX. Try
577 a moderate value. */
578 buflen = 20;
579 name = (char *) __alloca (buflen);
581 success = getlogin_r (name, buflen) == 0;
582 if (success)
584 struct passwd *p;
585 # if defined HAVE_GETPWNAM_R || defined _LIBC
586 long int pwbuflen = GETPW_R_SIZE_MAX ();
587 char *pwtmpbuf;
588 struct passwd pwbuf;
589 int save = errno;
591 # ifndef _LIBC
592 if (pwbuflen == -1)
593 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.
594 Try a moderate value. */
595 pwbuflen = 1024;
596 # endif
597 pwtmpbuf = (char *) __alloca (pwbuflen);
599 while (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
600 != 0)
602 if (errno != ERANGE)
604 p = NULL;
605 break;
607 # ifdef _LIBC
608 pwtmpbuf = extend_alloca (pwtmpbuf, pwbuflen,
609 2 * pwbuflen);
610 # else
611 pwbuflen *= 2;
612 pwtmpbuf = (char *) __alloca (pwbuflen);
613 # endif
614 __set_errno (save);
616 # else
617 p = getpwnam (name);
618 # endif
619 if (p != NULL)
620 home_dir = p->pw_dir;
623 if (home_dir == NULL || home_dir[0] == '\0')
625 if (flags & GLOB_TILDE_CHECK)
626 return GLOB_NOMATCH;
627 else
628 home_dir = "~"; /* No luck. */
630 # endif /* WINDOWS32 */
631 # endif
632 /* Now construct the full directory. */
633 if (dirname[1] == '\0')
635 dirname = home_dir;
636 dirlen = strlen (dirname);
638 else
640 char *newp;
641 size_t home_len = strlen (home_dir);
642 newp = (char *) __alloca (home_len + dirlen);
643 mempcpy (mempcpy (newp, home_dir, home_len),
644 &dirname[1], dirlen);
645 dirname = newp;
646 dirlen += home_len - 1;
648 dirname_modified = 1;
650 # if !defined _AMIGA && !defined WINDOWS32
651 else
653 char *end_name = strchr (dirname, '/');
654 const char *user_name;
655 const char *home_dir;
656 char *unescape = NULL;
658 if (!(flags & GLOB_NOESCAPE))
660 if (end_name == NULL)
662 unescape = strchr (dirname, '\\');
663 if (unescape)
664 end_name = strchr (unescape, '\0');
666 else
667 unescape = memchr (dirname, '\\', end_name - dirname);
669 if (end_name == NULL)
670 user_name = dirname + 1;
671 else
673 char *newp;
674 newp = (char *) __alloca (end_name - dirname);
675 if (unescape != NULL)
677 char *p = mempcpy (newp, dirname + 1,
678 unescape - dirname - 1);
679 char *q = unescape;
680 while (*q != '\0')
682 if (*q == '\\')
684 if (q[1] == '\0')
686 /* "~fo\\o\\" unescape to user_name "foo\\",
687 but "~fo\\o\\/" unescape to user_name
688 "foo". */
689 if (filename == NULL)
690 *p++ = '\\';
691 break;
693 ++q;
695 *p++ = *q++;
697 *p = '\0';
699 else
700 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
701 = '\0';
702 user_name = newp;
705 /* Look up specific user's home directory. */
707 struct passwd *p;
708 # if defined HAVE_GETPWNAM_R || defined _LIBC
709 long int buflen = GETPW_R_SIZE_MAX ();
710 char *pwtmpbuf;
711 struct passwd pwbuf;
712 int save = errno;
714 # ifndef _LIBC
715 if (buflen == -1)
716 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
717 moderate value. */
718 buflen = 1024;
719 # endif
720 pwtmpbuf = (char *) __alloca (buflen);
722 while (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) != 0)
724 if (errno != ERANGE)
726 p = NULL;
727 break;
729 # ifdef _LIBC
730 pwtmpbuf = extend_alloca (pwtmpbuf, buflen, 2 * buflen);
731 # else
732 buflen *= 2;
733 pwtmpbuf = __alloca (buflen);
734 # endif
735 __set_errno (save);
737 # else
738 p = getpwnam (user_name);
739 # endif
740 if (p != NULL)
741 home_dir = p->pw_dir;
742 else
743 home_dir = NULL;
745 /* If we found a home directory use this. */
746 if (home_dir != NULL)
748 char *newp;
749 size_t home_len = strlen (home_dir);
750 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
751 newp = (char *) __alloca (home_len + rest_len + 1);
752 *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
753 end_name, rest_len)) = '\0';
754 dirname = newp;
755 dirlen = home_len + rest_len;
756 dirname_modified = 1;
758 else
759 if (flags & GLOB_TILDE_CHECK)
760 /* We have to regard it as an error if we cannot find the
761 home directory. */
762 return GLOB_NOMATCH;
764 # endif /* Not Amiga && not WINDOWS32. */
766 #endif /* Not VMS. */
768 /* Now test whether we looked for "~" or "~NAME". In this case we
769 can give the answer now. */
770 if (filename == NULL)
772 struct stat st;
773 struct_stat64 st64;
775 /* Return the directory if we don't check for error or if it exists. */
776 if ((flags & GLOB_NOCHECK)
777 || (((flags & GLOB_ALTDIRFUNC)
778 ? ((*pglob->gl_stat) (dirname, &st) == 0
779 && S_ISDIR (st.st_mode))
780 : (__stat64 (dirname, &st64) == 0 && S_ISDIR (st64.st_mode)))))
782 int newcount = pglob->gl_pathc + pglob->gl_offs;
783 char **new_gl_pathv;
785 new_gl_pathv
786 = (char **) realloc (pglob->gl_pathv,
787 (newcount + 1 + 1) * sizeof (char *));
788 if (new_gl_pathv == NULL)
790 nospace:
791 free (pglob->gl_pathv);
792 pglob->gl_pathv = NULL;
793 pglob->gl_pathc = 0;
794 return GLOB_NOSPACE;
796 pglob->gl_pathv = new_gl_pathv;
798 if (flags & GLOB_MARK)
800 char *p;
801 pglob->gl_pathv[newcount] = malloc (dirlen + 2);
802 if (pglob->gl_pathv[newcount] == NULL)
803 goto nospace;
804 p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);
805 p[0] = '/';
806 p[1] = '\0';
808 else
810 pglob->gl_pathv[newcount] = strdup (dirname);
811 if (pglob->gl_pathv[newcount] == NULL)
812 goto nospace;
814 pglob->gl_pathv[++newcount] = NULL;
815 ++pglob->gl_pathc;
816 pglob->gl_flags = flags;
818 return 0;
821 /* Not found. */
822 return GLOB_NOMATCH;
825 meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));
826 /* meta is 1 if correct glob pattern containing metacharacters.
827 If meta has bit (1 << 2) set, it means there was an unterminated
828 [ which we handle the same, using fnmatch. Broken unterminated
829 pattern bracket expressions ought to be rare enough that it is
830 not worth special casing them, fnmatch will do the right thing. */
831 if (meta & 5)
833 /* The directory name contains metacharacters, so we
834 have to glob for the directory, and then glob for
835 the pattern in each directory found. */
836 size_t i;
838 if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\')
840 /* "foo\\/bar". Remove the final backslash from dirname
841 if it has not been quoted. */
842 char *p = (char *) &dirname[dirlen - 1];
844 while (p > dirname && p[-1] == '\\') --p;
845 if ((&dirname[dirlen] - p) & 1)
846 *(char *) &dirname[--dirlen] = '\0';
849 if ((flags & GLOB_ALTDIRFUNC) != 0)
851 /* Use the alternative access functions also in the recursive
852 call. */
853 dirs.gl_opendir = pglob->gl_opendir;
854 dirs.gl_readdir = pglob->gl_readdir;
855 dirs.gl_closedir = pglob->gl_closedir;
856 dirs.gl_stat = pglob->gl_stat;
857 dirs.gl_lstat = pglob->gl_lstat;
860 status = glob (dirname,
861 ((flags & (GLOB_ERR | GLOB_NOESCAPE
862 | GLOB_ALTDIRFUNC))
863 | GLOB_NOSORT | GLOB_ONLYDIR),
864 errfunc, &dirs);
865 if (status != 0)
867 if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH)
868 return status;
869 goto no_matches;
872 /* We have successfully globbed the preceding directory name.
873 For each name we found, call glob_in_dir on it and FILENAME,
874 appending the results to PGLOB. */
875 for (i = 0; i < dirs.gl_pathc; ++i)
877 int old_pathc;
879 #ifdef SHELL
881 /* Make globbing interruptible in the bash shell. */
882 extern int interrupt_state;
884 if (interrupt_state)
886 globfree (&dirs);
887 return GLOB_ABORTED;
890 #endif /* SHELL. */
892 old_pathc = pglob->gl_pathc;
893 status = glob_in_dir (filename, dirs.gl_pathv[i],
894 ((flags | GLOB_APPEND)
895 & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),
896 errfunc, pglob);
897 if (status == GLOB_NOMATCH)
898 /* No matches in this directory. Try the next. */
899 continue;
901 if (status != 0)
903 globfree (&dirs);
904 globfree (pglob);
905 pglob->gl_pathc = 0;
906 return status;
909 /* Stick the directory on the front of each name. */
910 if (prefix_array (dirs.gl_pathv[i],
911 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
912 pglob->gl_pathc - old_pathc))
914 globfree (&dirs);
915 globfree (pglob);
916 pglob->gl_pathc = 0;
917 return GLOB_NOSPACE;
921 flags |= GLOB_MAGCHAR;
923 /* We have ignored the GLOB_NOCHECK flag in the `glob_in_dir' calls.
924 But if we have not found any matching entry and the GLOB_NOCHECK
925 flag was set we must return the input pattern itself. */
926 if (pglob->gl_pathc + pglob->gl_offs == oldcount)
928 no_matches:
929 /* No matches. */
930 if (flags & GLOB_NOCHECK)
932 int newcount = pglob->gl_pathc + pglob->gl_offs;
933 char **new_gl_pathv;
935 new_gl_pathv = (char **) realloc (pglob->gl_pathv,
936 (newcount + 2)
937 * sizeof (char *));
938 if (new_gl_pathv == NULL)
940 globfree (&dirs);
941 return GLOB_NOSPACE;
943 pglob->gl_pathv = new_gl_pathv;
945 pglob->gl_pathv[newcount] = __strdup (pattern);
946 if (pglob->gl_pathv[newcount] == NULL)
948 globfree (&dirs);
949 globfree (pglob);
950 pglob->gl_pathc = 0;
951 return GLOB_NOSPACE;
954 ++pglob->gl_pathc;
955 ++newcount;
957 pglob->gl_pathv[newcount] = NULL;
958 pglob->gl_flags = flags;
960 else
962 globfree (&dirs);
963 return GLOB_NOMATCH;
967 globfree (&dirs);
969 else
971 int old_pathc = pglob->gl_pathc;
972 int orig_flags = flags;
974 if (meta & 2)
976 char *p = strchr (dirname, '\\'), *q;
977 /* We need to unescape the dirname string. It is certainly
978 allocated by alloca, as otherwise filename would be NULL
979 or dirname wouldn't contain backslashes. */
980 q = p;
983 if (*p == '\\')
985 *q = *++p;
986 --dirlen;
988 else
989 *q = *p;
990 ++q;
992 while (*p++ != '\0');
993 dirname_modified = 1;
995 if (dirname_modified)
996 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
997 status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
998 if (status != 0)
1000 if (status == GLOB_NOMATCH && flags != orig_flags
1001 && pglob->gl_pathc + pglob->gl_offs == oldcount)
1003 /* Make sure globfree (&dirs); is a nop. */
1004 dirs.gl_pathv = NULL;
1005 flags = orig_flags;
1006 goto no_matches;
1008 return status;
1011 if (dirlen > 0)
1013 /* Stick the directory on the front of each name. */
1014 if (prefix_array (dirname,
1015 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
1016 pglob->gl_pathc - old_pathc))
1018 globfree (pglob);
1019 pglob->gl_pathc = 0;
1020 return GLOB_NOSPACE;
1025 if (flags & GLOB_MARK)
1027 /* Append slashes to directory names. */
1028 size_t i;
1029 struct stat st;
1030 struct_stat64 st64;
1032 for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)
1033 if (((flags & GLOB_ALTDIRFUNC)
1034 ? ((*pglob->gl_stat) (pglob->gl_pathv[i], &st) == 0
1035 && S_ISDIR (st.st_mode))
1036 : (__stat64 (pglob->gl_pathv[i], &st64) == 0
1037 && S_ISDIR (st64.st_mode))))
1039 size_t len = strlen (pglob->gl_pathv[i]) + 2;
1040 char *new = realloc (pglob->gl_pathv[i], len);
1041 if (new == NULL)
1043 globfree (pglob);
1044 pglob->gl_pathc = 0;
1045 return GLOB_NOSPACE;
1047 strcpy (&new[len - 2], "/");
1048 pglob->gl_pathv[i] = new;
1052 if (!(flags & GLOB_NOSORT))
1054 /* Sort the vector. */
1055 qsort (&pglob->gl_pathv[oldcount],
1056 pglob->gl_pathc + pglob->gl_offs - oldcount,
1057 sizeof (char *), collated_compare);
1060 return 0;
1062 #if defined _LIBC && !defined glob
1063 libc_hidden_def (glob)
1064 #endif
1067 #if !defined _LIBC || !defined GLOB_ONLY_P
1069 /* Free storage allocated in PGLOB by a previous `glob' call. */
1070 void
1071 globfree (pglob)
1072 register glob_t *pglob;
1074 if (pglob->gl_pathv != NULL)
1076 size_t i;
1077 for (i = 0; i < pglob->gl_pathc; ++i)
1078 if (pglob->gl_pathv[pglob->gl_offs + i] != NULL)
1079 free (pglob->gl_pathv[pglob->gl_offs + i]);
1080 free (pglob->gl_pathv);
1081 pglob->gl_pathv = NULL;
1084 #if defined _LIBC && !defined globfree
1085 libc_hidden_def (globfree)
1086 #endif
1089 /* Do a collated comparison of A and B. */
1090 static int
1091 collated_compare (const void *a, const void *b)
1093 const char *const s1 = *(const char *const * const) a;
1094 const char *const s2 = *(const char *const * const) b;
1096 if (s1 == s2)
1097 return 0;
1098 if (s1 == NULL)
1099 return 1;
1100 if (s2 == NULL)
1101 return -1;
1102 return strcoll (s1, s2);
1106 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1107 elements in place. Return nonzero if out of memory, zero if successful.
1108 A slash is inserted between DIRNAME and each elt of ARRAY,
1109 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1110 static int
1111 prefix_array (const char *dirname, char **array, size_t n)
1113 register size_t i;
1114 size_t dirlen = strlen (dirname);
1115 #if defined __MSDOS__ || defined WINDOWS32
1116 int sep_char = '/';
1117 # define DIRSEP_CHAR sep_char
1118 #else
1119 # define DIRSEP_CHAR '/'
1120 #endif
1122 if (dirlen == 1 && dirname[0] == '/')
1123 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1124 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1125 dirlen = 0;
1126 #if defined __MSDOS__ || defined WINDOWS32
1127 else if (dirlen > 1)
1129 if (dirname[dirlen - 1] == '/' && dirname[dirlen - 2] == ':')
1130 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1131 --dirlen;
1132 else if (dirname[dirlen - 1] == ':')
1134 /* DIRNAME is "d:". Use `:' instead of `/'. */
1135 --dirlen;
1136 sep_char = ':';
1139 #endif
1141 for (i = 0; i < n; ++i)
1143 size_t eltlen = strlen (array[i]) + 1;
1144 char *new = (char *) malloc (dirlen + 1 + eltlen);
1145 if (new == NULL)
1147 while (i > 0)
1148 free (array[--i]);
1149 return 1;
1153 char *endp = mempcpy (new, dirname, dirlen);
1154 *endp++ = DIRSEP_CHAR;
1155 mempcpy (endp, array[i], eltlen);
1157 free (array[i]);
1158 array[i] = new;
1161 return 0;
1165 /* We must not compile this function twice. */
1166 #if !defined _LIBC || !defined NO_GLOB_PATTERN_P
1168 __glob_pattern_type (pattern, quote)
1169 const char *pattern;
1170 int quote;
1172 register const char *p;
1173 int ret = 0;
1175 for (p = pattern; *p != '\0'; ++p)
1176 switch (*p)
1178 case '?':
1179 case '*':
1180 return 1;
1182 case '\\':
1183 if (quote)
1185 if (p[1] != '\0')
1186 ++p;
1187 ret |= 2;
1189 break;
1191 case '[':
1192 ret |= 4;
1193 break;
1195 case ']':
1196 if (ret & 4)
1197 return 1;
1198 break;
1201 return ret;
1204 /* Return nonzero if PATTERN contains any metacharacters.
1205 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
1207 __glob_pattern_p (pattern, quote)
1208 const char *pattern;
1209 int quote;
1211 return __glob_pattern_type (pattern, quote) == 1;
1213 # ifdef _LIBC
1214 weak_alias (__glob_pattern_p, glob_pattern_p)
1215 # endif
1216 #endif
1218 #endif /* !GLOB_ONLY_P */
1221 /* We put this in a separate function mainly to allow the memory
1222 allocated with alloca to be recycled. */
1223 #if !defined _LIBC || !defined GLOB_ONLY_P
1224 static int
1225 link_exists_p (const char *dir, size_t dirlen, const char *fname,
1226 glob_t *pglob, int flags)
1228 size_t fnamelen = strlen (fname);
1229 char *fullname = (char *) __alloca (dirlen + 1 + fnamelen + 1);
1230 struct stat st;
1231 struct_stat64 st64;
1233 mempcpy (mempcpy (mempcpy (fullname, dir, dirlen), "/", 1),
1234 fname, fnamelen + 1);
1236 return (((flags & GLOB_ALTDIRFUNC)
1237 ? (*pglob->gl_stat) (fullname, &st)
1238 : __stat64 (fullname, &st64)) == 0);
1240 #endif
1243 /* Like `glob', but PATTERN is a final pathname component,
1244 and matches are searched for in DIRECTORY.
1245 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1246 The GLOB_APPEND flag is assumed to be set (always appends). */
1247 static int
1248 glob_in_dir (const char *pattern, const char *directory, int flags,
1249 int (*errfunc) (const char *, int),
1250 glob_t *pglob)
1252 size_t dirlen = strlen (directory);
1253 void *stream = NULL;
1254 struct globnames
1256 struct globnames *next;
1257 size_t count;
1258 char *name[64];
1260 #define INITIAL_COUNT sizeof (init_names.name) / sizeof (init_names.name[0])
1261 struct globnames init_names;
1262 struct globnames *names = &init_names;
1263 struct globnames *names_alloca = &init_names;
1264 size_t nfound = 0;
1265 size_t allocasize = sizeof (init_names);
1266 size_t cur = 0;
1267 int meta;
1268 int save;
1270 init_names.next = NULL;
1271 init_names.count = INITIAL_COUNT;
1273 meta = __glob_pattern_type (pattern, !(flags & GLOB_NOESCAPE));
1274 if (meta == 0 && (flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
1276 /* We need not do any tests. The PATTERN contains no meta
1277 characters and we must not return an error therefore the
1278 result will always contain exactly one name. */
1279 flags |= GLOB_NOCHECK;
1281 else if (meta == 0)
1283 /* Since we use the normal file functions we can also use stat()
1284 to verify the file is there. */
1285 struct stat st;
1286 struct_stat64 st64;
1287 size_t patlen = strlen (pattern);
1288 char *fullname = (char *) __alloca (dirlen + 1 + patlen + 1);
1290 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1291 "/", 1),
1292 pattern, patlen + 1);
1293 if (((flags & GLOB_ALTDIRFUNC)
1294 ? (*pglob->gl_stat) (fullname, &st)
1295 : __stat64 (fullname, &st64)) == 0)
1296 /* We found this file to be existing. Now tell the rest
1297 of the function to copy this name into the result. */
1298 flags |= GLOB_NOCHECK;
1300 else
1302 stream = ((flags & GLOB_ALTDIRFUNC)
1303 ? (*pglob->gl_opendir) (directory)
1304 : opendir (directory));
1305 if (stream == NULL)
1307 if (errno != ENOTDIR
1308 && ((errfunc != NULL && (*errfunc) (directory, errno))
1309 || (flags & GLOB_ERR)))
1310 return GLOB_ABORTED;
1312 else
1314 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1315 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1316 #if defined _AMIGA || defined VMS
1317 | FNM_CASEFOLD
1318 #endif
1320 flags |= GLOB_MAGCHAR;
1322 while (1)
1324 const char *name;
1325 size_t len;
1326 #if defined _LIBC && !defined COMPILE_GLOB64
1327 struct dirent64 *d;
1328 union
1330 struct dirent64 d64;
1331 char room [offsetof (struct dirent64, d_name[0])
1332 + NAME_MAX + 1];
1334 d64buf;
1336 if (flags & GLOB_ALTDIRFUNC)
1338 struct dirent *d32 = (*pglob->gl_readdir) (stream);
1339 if (d32 != NULL)
1341 CONVERT_DIRENT_DIRENT64 (&d64buf.d64, d32);
1342 d = &d64buf.d64;
1344 else
1345 d = NULL;
1347 else
1348 d = __readdir64 (stream);
1349 #else
1350 struct dirent *d = ((flags & GLOB_ALTDIRFUNC)
1351 ? ((struct dirent *)
1352 (*pglob->gl_readdir) (stream))
1353 : __readdir (stream));
1354 #endif
1355 if (d == NULL)
1356 break;
1357 if (! REAL_DIR_ENTRY (d))
1358 continue;
1360 /* If we shall match only directories use the information
1361 provided by the dirent call if possible. */
1362 if ((flags & GLOB_ONLYDIR) && !DIRENT_MIGHT_BE_DIR (d))
1363 continue;
1365 name = d->d_name;
1367 if (fnmatch (pattern, name, fnm_flags) == 0)
1369 /* If the file we found is a symlink we have to
1370 make sure the target file exists. */
1371 if (!DIRENT_MIGHT_BE_SYMLINK (d)
1372 || link_exists_p (directory, dirlen, name, pglob,
1373 flags))
1375 if (cur == names->count)
1377 struct globnames *newnames;
1378 size_t count = names->count * 2;
1379 size_t size = (sizeof (struct globnames)
1380 + ((count - INITIAL_COUNT)
1381 * sizeof (char *)));
1382 allocasize += size;
1383 if (__libc_use_alloca (allocasize))
1384 newnames = names_alloca = __alloca (size);
1385 else if ((newnames = malloc (size))
1386 == NULL)
1387 goto memory_error;
1388 newnames->count = count;
1389 newnames->next = names;
1390 names = newnames;
1391 cur = 0;
1393 len = NAMLEN (d);
1394 names->name[cur] = (char *) malloc (len + 1);
1395 if (names->name[cur] == NULL)
1396 goto memory_error;
1397 *((char *) mempcpy (names->name[cur++], name, len))
1398 = '\0';
1399 ++nfound;
1406 if (nfound == 0 && (flags & GLOB_NOCHECK))
1408 size_t len = strlen (pattern);
1409 nfound = 1;
1410 names->name[cur] = (char *) malloc (len + 1);
1411 if (names->name[cur] == NULL)
1412 goto memory_error;
1413 *((char *) mempcpy (names->name[cur++], pattern, len)) = '\0';
1416 int result = GLOB_NOMATCH;
1417 if (nfound != 0)
1419 result = 0;
1421 char **new_gl_pathv;
1422 new_gl_pathv
1423 = (char **) realloc (pglob->gl_pathv,
1424 (pglob->gl_pathc + pglob->gl_offs + nfound + 1)
1425 * sizeof (char *));
1426 if (new_gl_pathv == NULL)
1428 memory_error:
1429 while (1)
1431 struct globnames *old = names;
1432 for (size_t i = 0; i < cur; ++i)
1433 free (names->name[i]);
1434 names = names->next;
1435 /* NB: we will not leak memory here if we exit without
1436 freeing the current block assigned to OLD. At least
1437 the very first block is always allocated on the stack
1438 and this is the block assigned to OLD here. */
1439 if (names == NULL)
1441 assert (old == &init_names);
1442 break;
1444 cur = names->count;
1445 if (old == names_alloca)
1446 names_alloca = names;
1447 else
1448 free (old);
1450 result = GLOB_NOSPACE;
1452 else
1454 while (1)
1456 struct globnames *old = names;
1457 for (size_t i = 0; i < cur; ++i)
1458 new_gl_pathv[pglob->gl_offs + pglob->gl_pathc++]
1459 = names->name[i];
1460 names = names->next;
1461 /* NB: we will not leak memory here if we exit without
1462 freeing the current block assigned to OLD. At least
1463 the very first block is always allocated on the stack
1464 and this is the block assigned to OLD here. */
1465 if (names == NULL)
1467 assert (old == &init_names);
1468 break;
1470 cur = names->count;
1471 if (old == names_alloca)
1472 names_alloca = names;
1473 else
1474 free (old);
1477 pglob->gl_pathv = new_gl_pathv;
1479 pglob->gl_pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
1481 pglob->gl_flags = flags;
1485 if (stream != NULL)
1487 save = errno;
1488 if (flags & GLOB_ALTDIRFUNC)
1489 (*pglob->gl_closedir) (stream);
1490 else
1491 closedir (stream);
1492 __set_errno (save);
1495 return result;