Fix memory leak in fnmatch
[glibc.git] / posix / glob.c
blob6df083a67a40026308453be55d40fc42643e6ac3
1 /* Copyright (C) 1991-2002, 2003, 2004, 2005, 2006, 2007, 2008, 2010
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 if (!(flags & GLOB_APPEND))
423 pglob->gl_pathc = 0;
424 if (!(flags & GLOB_DOOFFS))
425 pglob->gl_pathv = NULL;
426 else
428 size_t i;
429 pglob->gl_pathv = (char **) malloc ((pglob->gl_offs + 1)
430 * sizeof (char *));
431 if (pglob->gl_pathv == NULL)
432 return GLOB_NOSPACE;
434 for (i = 0; i <= pglob->gl_offs; ++i)
435 pglob->gl_pathv[i] = NULL;
439 oldcount = pglob->gl_pathc + pglob->gl_offs;
441 /* Find the filename. */
442 filename = strrchr (pattern, '/');
443 #if defined __MSDOS__ || defined WINDOWS32
444 /* The case of "d:pattern". Since `:' is not allowed in
445 file names, we can safely assume that wherever it
446 happens in pattern, it signals the filename part. This
447 is so we could some day support patterns like "[a-z]:foo". */
448 if (filename == NULL)
449 filename = strchr (pattern, ':');
450 #endif /* __MSDOS__ || WINDOWS32 */
451 dirname_modified = 0;
452 if (filename == NULL)
454 /* This can mean two things: a simple name or "~name". The latter
455 case is nothing but a notation for a directory. */
456 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
458 dirname = pattern;
459 dirlen = strlen (pattern);
461 /* Set FILENAME to NULL as a special flag. This is ugly but
462 other solutions would require much more code. We test for
463 this special case below. */
464 filename = NULL;
466 else
468 if (__builtin_expect (pattern[0] == '\0', 0))
470 dirs.gl_pathv = NULL;
471 goto no_matches;
474 filename = pattern;
475 #ifdef _AMIGA
476 dirname = "";
477 #else
478 dirname = ".";
479 #endif
480 dirlen = 0;
483 else if (filename == pattern
484 || (filename == pattern + 1 && pattern[0] == '\\'
485 && (flags & GLOB_NOESCAPE) == 0))
487 /* "/pattern" or "\\/pattern". */
488 dirname = "/";
489 dirlen = 1;
490 ++filename;
492 else
494 char *newp;
495 dirlen = filename - pattern;
496 #if defined __MSDOS__ || defined WINDOWS32
497 if (*filename == ':'
498 || (filename > pattern + 1 && filename[-1] == ':'))
500 char *drive_spec;
502 ++dirlen;
503 drive_spec = (char *) __alloca (dirlen + 1);
504 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
505 /* For now, disallow wildcards in the drive spec, to
506 prevent infinite recursion in glob. */
507 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
508 return GLOB_NOMATCH;
509 /* If this is "d:pattern", we need to copy `:' to DIRNAME
510 as well. If it's "d:/pattern", don't remove the slash
511 from "d:/", since "d:" and "d:/" are not the same.*/
513 #endif
514 newp = (char *) __alloca (dirlen + 1);
515 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
516 dirname = newp;
517 ++filename;
519 if (filename[0] == '\0'
520 #if defined __MSDOS__ || defined WINDOWS32
521 && dirname[dirlen - 1] != ':'
522 && (dirlen < 3 || dirname[dirlen - 2] != ':'
523 || dirname[dirlen - 1] != '/')
524 #endif
525 && dirlen > 1)
526 /* "pattern/". Expand "pattern", appending slashes. */
528 int orig_flags = flags;
529 if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\')
531 /* "pattern\\/". Remove the final backslash if it hasn't
532 been quoted. */
533 char *p = (char *) &dirname[dirlen - 1];
535 while (p > dirname && p[-1] == '\\') --p;
536 if ((&dirname[dirlen] - p) & 1)
538 *(char *) &dirname[--dirlen] = '\0';
539 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
542 int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
543 if (val == 0)
544 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
545 | (flags & GLOB_MARK));
546 else if (val == GLOB_NOMATCH && flags != orig_flags)
548 /* Make sure globfree (&dirs); is a nop. */
549 dirs.gl_pathv = NULL;
550 flags = orig_flags;
551 oldcount = pglob->gl_pathc + pglob->gl_offs;
552 goto no_matches;
554 return val;
558 #ifndef VMS
559 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
561 if (dirname[1] == '\0' || dirname[1] == '/'
562 || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\'
563 && (dirname[2] == '\0' || dirname[2] == '/')))
565 /* Look up home directory. */
566 const char *home_dir = getenv ("HOME");
567 # ifdef _AMIGA
568 if (home_dir == NULL || home_dir[0] == '\0')
569 home_dir = "SYS:";
570 # else
571 # ifdef WINDOWS32
572 if (home_dir == NULL || home_dir[0] == '\0')
573 home_dir = "c:/users/default"; /* poor default */
574 # else
575 if (home_dir == NULL || home_dir[0] == '\0')
577 int success;
578 char *name;
579 size_t buflen = GET_LOGIN_NAME_MAX () + 1;
581 if (buflen == 0)
582 /* `sysconf' does not support _SC_LOGIN_NAME_MAX. Try
583 a moderate value. */
584 buflen = 20;
585 name = (char *) __alloca (buflen);
587 success = getlogin_r (name, buflen) == 0;
588 if (success)
590 struct passwd *p;
591 # if defined HAVE_GETPWNAM_R || defined _LIBC
592 long int pwbuflen = GETPW_R_SIZE_MAX ();
593 char *pwtmpbuf;
594 struct passwd pwbuf;
595 int save = errno;
597 # ifndef _LIBC
598 if (pwbuflen == -1)
599 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.
600 Try a moderate value. */
601 pwbuflen = 1024;
602 # endif
603 pwtmpbuf = (char *) __alloca (pwbuflen);
605 while (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
606 != 0)
608 if (errno != ERANGE)
610 p = NULL;
611 break;
613 # ifdef _LIBC
614 pwtmpbuf = extend_alloca (pwtmpbuf, pwbuflen,
615 2 * pwbuflen);
616 # else
617 pwbuflen *= 2;
618 pwtmpbuf = (char *) __alloca (pwbuflen);
619 # endif
620 __set_errno (save);
622 # else
623 p = getpwnam (name);
624 # endif
625 if (p != NULL)
626 home_dir = p->pw_dir;
629 if (home_dir == NULL || home_dir[0] == '\0')
631 if (flags & GLOB_TILDE_CHECK)
632 return GLOB_NOMATCH;
633 else
634 home_dir = "~"; /* No luck. */
636 # endif /* WINDOWS32 */
637 # endif
638 /* Now construct the full directory. */
639 if (dirname[1] == '\0')
641 dirname = home_dir;
642 dirlen = strlen (dirname);
644 else
646 char *newp;
647 size_t home_len = strlen (home_dir);
648 newp = (char *) __alloca (home_len + dirlen);
649 mempcpy (mempcpy (newp, home_dir, home_len),
650 &dirname[1], dirlen);
651 dirname = newp;
652 dirlen += home_len - 1;
654 dirname_modified = 1;
656 # if !defined _AMIGA && !defined WINDOWS32
657 else
659 char *end_name = strchr (dirname, '/');
660 const char *user_name;
661 const char *home_dir;
662 char *unescape = NULL;
664 if (!(flags & GLOB_NOESCAPE))
666 if (end_name == NULL)
668 unescape = strchr (dirname, '\\');
669 if (unescape)
670 end_name = strchr (unescape, '\0');
672 else
673 unescape = memchr (dirname, '\\', end_name - dirname);
675 if (end_name == NULL)
676 user_name = dirname + 1;
677 else
679 char *newp;
680 newp = (char *) __alloca (end_name - dirname);
681 if (unescape != NULL)
683 char *p = mempcpy (newp, dirname + 1,
684 unescape - dirname - 1);
685 char *q = unescape;
686 while (*q != '\0')
688 if (*q == '\\')
690 if (q[1] == '\0')
692 /* "~fo\\o\\" unescape to user_name "foo\\",
693 but "~fo\\o\\/" unescape to user_name
694 "foo". */
695 if (filename == NULL)
696 *p++ = '\\';
697 break;
699 ++q;
701 *p++ = *q++;
703 *p = '\0';
705 else
706 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
707 = '\0';
708 user_name = newp;
711 /* Look up specific user's home directory. */
713 struct passwd *p;
714 # if defined HAVE_GETPWNAM_R || defined _LIBC
715 long int buflen = GETPW_R_SIZE_MAX ();
716 char *pwtmpbuf;
717 struct passwd pwbuf;
718 int save = errno;
720 # ifndef _LIBC
721 if (buflen == -1)
722 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
723 moderate value. */
724 buflen = 1024;
725 # endif
726 pwtmpbuf = (char *) __alloca (buflen);
728 while (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) != 0)
730 if (errno != ERANGE)
732 p = NULL;
733 break;
735 # ifdef _LIBC
736 pwtmpbuf = extend_alloca (pwtmpbuf, buflen, 2 * buflen);
737 # else
738 buflen *= 2;
739 pwtmpbuf = __alloca (buflen);
740 # endif
741 __set_errno (save);
743 # else
744 p = getpwnam (user_name);
745 # endif
746 if (p != NULL)
747 home_dir = p->pw_dir;
748 else
749 home_dir = NULL;
751 /* If we found a home directory use this. */
752 if (home_dir != NULL)
754 char *newp;
755 size_t home_len = strlen (home_dir);
756 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
757 newp = (char *) __alloca (home_len + rest_len + 1);
758 *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
759 end_name, rest_len)) = '\0';
760 dirname = newp;
761 dirlen = home_len + rest_len;
762 dirname_modified = 1;
764 else
765 if (flags & GLOB_TILDE_CHECK)
766 /* We have to regard it as an error if we cannot find the
767 home directory. */
768 return GLOB_NOMATCH;
770 # endif /* Not Amiga && not WINDOWS32. */
772 #endif /* Not VMS. */
774 /* Now test whether we looked for "~" or "~NAME". In this case we
775 can give the answer now. */
776 if (filename == NULL)
778 struct stat st;
779 struct_stat64 st64;
781 /* Return the directory if we don't check for error or if it exists. */
782 if ((flags & GLOB_NOCHECK)
783 || (((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
784 ? ((*pglob->gl_stat) (dirname, &st) == 0
785 && S_ISDIR (st.st_mode))
786 : (__stat64 (dirname, &st64) == 0 && S_ISDIR (st64.st_mode)))))
788 int newcount = pglob->gl_pathc + pglob->gl_offs;
789 char **new_gl_pathv;
791 new_gl_pathv
792 = (char **) realloc (pglob->gl_pathv,
793 (newcount + 1 + 1) * sizeof (char *));
794 if (new_gl_pathv == NULL)
796 nospace:
797 free (pglob->gl_pathv);
798 pglob->gl_pathv = NULL;
799 pglob->gl_pathc = 0;
800 return GLOB_NOSPACE;
802 pglob->gl_pathv = new_gl_pathv;
804 if (flags & GLOB_MARK)
806 char *p;
807 pglob->gl_pathv[newcount] = malloc (dirlen + 2);
808 if (pglob->gl_pathv[newcount] == NULL)
809 goto nospace;
810 p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);
811 p[0] = '/';
812 p[1] = '\0';
814 else
816 pglob->gl_pathv[newcount] = strdup (dirname);
817 if (pglob->gl_pathv[newcount] == NULL)
818 goto nospace;
820 pglob->gl_pathv[++newcount] = NULL;
821 ++pglob->gl_pathc;
822 pglob->gl_flags = flags;
824 return 0;
827 /* Not found. */
828 return GLOB_NOMATCH;
831 meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));
832 /* meta is 1 if correct glob pattern containing metacharacters.
833 If meta has bit (1 << 2) set, it means there was an unterminated
834 [ which we handle the same, using fnmatch. Broken unterminated
835 pattern bracket expressions ought to be rare enough that it is
836 not worth special casing them, fnmatch will do the right thing. */
837 if (meta & 5)
839 /* The directory name contains metacharacters, so we
840 have to glob for the directory, and then glob for
841 the pattern in each directory found. */
842 size_t i;
844 if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\')
846 /* "foo\\/bar". Remove the final backslash from dirname
847 if it has not been quoted. */
848 char *p = (char *) &dirname[dirlen - 1];
850 while (p > dirname && p[-1] == '\\') --p;
851 if ((&dirname[dirlen] - p) & 1)
852 *(char *) &dirname[--dirlen] = '\0';
855 if (__builtin_expect ((flags & GLOB_ALTDIRFUNC) != 0, 0))
857 /* Use the alternative access functions also in the recursive
858 call. */
859 dirs.gl_opendir = pglob->gl_opendir;
860 dirs.gl_readdir = pglob->gl_readdir;
861 dirs.gl_closedir = pglob->gl_closedir;
862 dirs.gl_stat = pglob->gl_stat;
863 dirs.gl_lstat = pglob->gl_lstat;
866 status = glob (dirname,
867 ((flags & (GLOB_ERR | GLOB_NOESCAPE
868 | GLOB_ALTDIRFUNC))
869 | GLOB_NOSORT | GLOB_ONLYDIR),
870 errfunc, &dirs);
871 if (status != 0)
873 if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH)
874 return status;
875 goto no_matches;
878 /* We have successfully globbed the preceding directory name.
879 For each name we found, call glob_in_dir on it and FILENAME,
880 appending the results to PGLOB. */
881 for (i = 0; i < dirs.gl_pathc; ++i)
883 int old_pathc;
885 #ifdef SHELL
887 /* Make globbing interruptible in the bash shell. */
888 extern int interrupt_state;
890 if (interrupt_state)
892 globfree (&dirs);
893 return GLOB_ABORTED;
896 #endif /* SHELL. */
898 old_pathc = pglob->gl_pathc;
899 status = glob_in_dir (filename, dirs.gl_pathv[i],
900 ((flags | GLOB_APPEND)
901 & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),
902 errfunc, pglob);
903 if (status == GLOB_NOMATCH)
904 /* No matches in this directory. Try the next. */
905 continue;
907 if (status != 0)
909 globfree (&dirs);
910 globfree (pglob);
911 pglob->gl_pathc = 0;
912 return status;
915 /* Stick the directory on the front of each name. */
916 if (prefix_array (dirs.gl_pathv[i],
917 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
918 pglob->gl_pathc - old_pathc))
920 globfree (&dirs);
921 globfree (pglob);
922 pglob->gl_pathc = 0;
923 return GLOB_NOSPACE;
927 flags |= GLOB_MAGCHAR;
929 /* We have ignored the GLOB_NOCHECK flag in the `glob_in_dir' calls.
930 But if we have not found any matching entry and the GLOB_NOCHECK
931 flag was set we must return the input pattern itself. */
932 if (pglob->gl_pathc + pglob->gl_offs == oldcount)
934 no_matches:
935 /* No matches. */
936 if (flags & GLOB_NOCHECK)
938 int newcount = pglob->gl_pathc + pglob->gl_offs;
939 char **new_gl_pathv;
941 new_gl_pathv = (char **) realloc (pglob->gl_pathv,
942 (newcount + 2)
943 * sizeof (char *));
944 if (new_gl_pathv == NULL)
946 globfree (&dirs);
947 return GLOB_NOSPACE;
949 pglob->gl_pathv = new_gl_pathv;
951 pglob->gl_pathv[newcount] = __strdup (pattern);
952 if (pglob->gl_pathv[newcount] == NULL)
954 globfree (&dirs);
955 globfree (pglob);
956 pglob->gl_pathc = 0;
957 return GLOB_NOSPACE;
960 ++pglob->gl_pathc;
961 ++newcount;
963 pglob->gl_pathv[newcount] = NULL;
964 pglob->gl_flags = flags;
966 else
968 globfree (&dirs);
969 return GLOB_NOMATCH;
973 globfree (&dirs);
975 else
977 int old_pathc = pglob->gl_pathc;
978 int orig_flags = flags;
980 if (meta & 2)
982 char *p = strchr (dirname, '\\'), *q;
983 /* We need to unescape the dirname string. It is certainly
984 allocated by alloca, as otherwise filename would be NULL
985 or dirname wouldn't contain backslashes. */
986 q = p;
989 if (*p == '\\')
991 *q = *++p;
992 --dirlen;
994 else
995 *q = *p;
996 ++q;
998 while (*p++ != '\0');
999 dirname_modified = 1;
1001 if (dirname_modified)
1002 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
1003 status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
1004 if (status != 0)
1006 if (status == GLOB_NOMATCH && flags != orig_flags
1007 && pglob->gl_pathc + pglob->gl_offs == oldcount)
1009 /* Make sure globfree (&dirs); is a nop. */
1010 dirs.gl_pathv = NULL;
1011 flags = orig_flags;
1012 goto no_matches;
1014 return status;
1017 if (dirlen > 0)
1019 /* Stick the directory on the front of each name. */
1020 if (prefix_array (dirname,
1021 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
1022 pglob->gl_pathc - old_pathc))
1024 globfree (pglob);
1025 pglob->gl_pathc = 0;
1026 return GLOB_NOSPACE;
1031 if (flags & GLOB_MARK)
1033 /* Append slashes to directory names. */
1034 size_t i;
1035 struct stat st;
1036 struct_stat64 st64;
1038 for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)
1039 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1040 ? ((*pglob->gl_stat) (pglob->gl_pathv[i], &st) == 0
1041 && S_ISDIR (st.st_mode))
1042 : (__stat64 (pglob->gl_pathv[i], &st64) == 0
1043 && S_ISDIR (st64.st_mode))))
1045 size_t len = strlen (pglob->gl_pathv[i]) + 2;
1046 char *new = realloc (pglob->gl_pathv[i], len);
1047 if (new == NULL)
1049 globfree (pglob);
1050 pglob->gl_pathc = 0;
1051 return GLOB_NOSPACE;
1053 strcpy (&new[len - 2], "/");
1054 pglob->gl_pathv[i] = new;
1058 if (!(flags & GLOB_NOSORT))
1060 /* Sort the vector. */
1061 qsort (&pglob->gl_pathv[oldcount],
1062 pglob->gl_pathc + pglob->gl_offs - oldcount,
1063 sizeof (char *), collated_compare);
1066 return 0;
1068 #if defined _LIBC && !defined glob
1069 libc_hidden_def (glob)
1070 #endif
1073 #if !defined _LIBC || !defined GLOB_ONLY_P
1075 /* Free storage allocated in PGLOB by a previous `glob' call. */
1076 void
1077 globfree (pglob)
1078 register glob_t *pglob;
1080 if (pglob->gl_pathv != NULL)
1082 size_t i;
1083 for (i = 0; i < pglob->gl_pathc; ++i)
1084 free (pglob->gl_pathv[pglob->gl_offs + i]);
1085 free (pglob->gl_pathv);
1086 pglob->gl_pathv = NULL;
1089 #if defined _LIBC && !defined globfree
1090 libc_hidden_def (globfree)
1091 #endif
1094 /* Do a collated comparison of A and B. */
1095 static int
1096 collated_compare (const void *a, const void *b)
1098 const char *const s1 = *(const char *const * const) a;
1099 const char *const s2 = *(const char *const * const) b;
1101 if (s1 == s2)
1102 return 0;
1103 if (s1 == NULL)
1104 return 1;
1105 if (s2 == NULL)
1106 return -1;
1107 return strcoll (s1, s2);
1111 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1112 elements in place. Return nonzero if out of memory, zero if successful.
1113 A slash is inserted between DIRNAME and each elt of ARRAY,
1114 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1115 static int
1116 prefix_array (const char *dirname, char **array, size_t n)
1118 register size_t i;
1119 size_t dirlen = strlen (dirname);
1120 #if defined __MSDOS__ || defined WINDOWS32
1121 int sep_char = '/';
1122 # define DIRSEP_CHAR sep_char
1123 #else
1124 # define DIRSEP_CHAR '/'
1125 #endif
1127 if (dirlen == 1 && dirname[0] == '/')
1128 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1129 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1130 dirlen = 0;
1131 #if defined __MSDOS__ || defined WINDOWS32
1132 else if (dirlen > 1)
1134 if (dirname[dirlen - 1] == '/' && dirname[dirlen - 2] == ':')
1135 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1136 --dirlen;
1137 else if (dirname[dirlen - 1] == ':')
1139 /* DIRNAME is "d:". Use `:' instead of `/'. */
1140 --dirlen;
1141 sep_char = ':';
1144 #endif
1146 for (i = 0; i < n; ++i)
1148 size_t eltlen = strlen (array[i]) + 1;
1149 char *new = (char *) malloc (dirlen + 1 + eltlen);
1150 if (new == NULL)
1152 while (i > 0)
1153 free (array[--i]);
1154 return 1;
1158 char *endp = mempcpy (new, dirname, dirlen);
1159 *endp++ = DIRSEP_CHAR;
1160 mempcpy (endp, array[i], eltlen);
1162 free (array[i]);
1163 array[i] = new;
1166 return 0;
1170 /* We must not compile this function twice. */
1171 #if !defined _LIBC || !defined NO_GLOB_PATTERN_P
1173 __glob_pattern_type (pattern, quote)
1174 const char *pattern;
1175 int quote;
1177 register const char *p;
1178 int ret = 0;
1180 for (p = pattern; *p != '\0'; ++p)
1181 switch (*p)
1183 case '?':
1184 case '*':
1185 return 1;
1187 case '\\':
1188 if (quote)
1190 if (p[1] != '\0')
1191 ++p;
1192 ret |= 2;
1194 break;
1196 case '[':
1197 ret |= 4;
1198 break;
1200 case ']':
1201 if (ret & 4)
1202 return 1;
1203 break;
1206 return ret;
1209 /* Return nonzero if PATTERN contains any metacharacters.
1210 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
1212 __glob_pattern_p (pattern, quote)
1213 const char *pattern;
1214 int quote;
1216 return __glob_pattern_type (pattern, quote) == 1;
1218 # ifdef _LIBC
1219 weak_alias (__glob_pattern_p, glob_pattern_p)
1220 # endif
1221 #endif
1223 #endif /* !GLOB_ONLY_P */
1226 /* We put this in a separate function mainly to allow the memory
1227 allocated with alloca to be recycled. */
1228 #if !defined _LIBC || !defined GLOB_ONLY_P
1229 static int
1230 __attribute_noinline__
1231 link_exists2_p (const char *dir, size_t dirlen, const char *fname,
1232 glob_t *pglob
1233 # ifndef _LIBC
1234 , int flags
1235 # endif
1238 size_t fnamelen = strlen (fname);
1239 char *fullname = (char *) __alloca (dirlen + 1 + fnamelen + 1);
1240 struct stat st;
1241 # ifndef _LIBC
1242 struct_stat64 st64;
1243 # endif
1245 mempcpy (mempcpy (mempcpy (fullname, dir, dirlen), "/", 1),
1246 fname, fnamelen + 1);
1248 # ifdef _LIBC
1249 return (*pglob->gl_stat) (fullname, &st) == 0;
1250 # else
1251 return ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1252 ? (*pglob->gl_stat) (fullname, &st)
1253 : __stat64 (fullname, &st64)) == 0);
1254 # endif
1256 # ifdef _LIBC
1257 # define link_exists_p(dfd, dirname, dirnamelen, fname, pglob, flags) \
1258 (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0) \
1259 ? link_exists2_p (dirname, dirnamelen, fname, pglob) \
1260 : ({ struct stat64 st64; \
1261 __fxstatat64 (_STAT_VER, dfd, fname, &st64, 0) == 0; }))
1262 # else
1263 # define link_exists_p(dfd, dirname, dirnamelen, fname, pglob, flags) \
1264 link_exists2_p (dirname, dirnamelen, fname, pglob, flags)
1265 # endif
1266 #endif
1269 /* Like `glob', but PATTERN is a final pathname component,
1270 and matches are searched for in DIRECTORY.
1271 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1272 The GLOB_APPEND flag is assumed to be set (always appends). */
1273 static int
1274 glob_in_dir (const char *pattern, const char *directory, int flags,
1275 int (*errfunc) (const char *, int),
1276 glob_t *pglob)
1278 size_t dirlen = strlen (directory);
1279 void *stream = NULL;
1280 struct globnames
1282 struct globnames *next;
1283 size_t count;
1284 char *name[64];
1286 #define INITIAL_COUNT sizeof (init_names.name) / sizeof (init_names.name[0])
1287 struct globnames init_names;
1288 struct globnames *names = &init_names;
1289 struct globnames *names_alloca = &init_names;
1290 size_t nfound = 0;
1291 size_t allocasize = sizeof (init_names);
1292 size_t cur = 0;
1293 int meta;
1294 int save;
1296 init_names.next = NULL;
1297 init_names.count = INITIAL_COUNT;
1299 meta = __glob_pattern_type (pattern, !(flags & GLOB_NOESCAPE));
1300 if (meta == 0 && (flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
1302 /* We need not do any tests. The PATTERN contains no meta
1303 characters and we must not return an error therefore the
1304 result will always contain exactly one name. */
1305 flags |= GLOB_NOCHECK;
1307 else if (meta == 0)
1309 /* Since we use the normal file functions we can also use stat()
1310 to verify the file is there. */
1311 struct stat st;
1312 struct_stat64 st64;
1313 size_t patlen = strlen (pattern);
1314 char *fullname = (char *) __alloca (dirlen + 1 + patlen + 1);
1316 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1317 "/", 1),
1318 pattern, patlen + 1);
1319 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1320 ? (*pglob->gl_stat) (fullname, &st)
1321 : __stat64 (fullname, &st64)) == 0)
1322 /* We found this file to be existing. Now tell the rest
1323 of the function to copy this name into the result. */
1324 flags |= GLOB_NOCHECK;
1326 else
1328 stream = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1329 ? (*pglob->gl_opendir) (directory)
1330 : opendir (directory));
1331 if (stream == NULL)
1333 if (errno != ENOTDIR
1334 && ((errfunc != NULL && (*errfunc) (directory, errno))
1335 || (flags & GLOB_ERR)))
1336 return GLOB_ABORTED;
1338 else
1340 #ifdef _LIBC
1341 int dfd = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1342 ? -1 : dirfd ((DIR *) stream));
1343 #endif
1344 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1345 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1346 #if defined _AMIGA || defined VMS
1347 | FNM_CASEFOLD
1348 #endif
1350 flags |= GLOB_MAGCHAR;
1352 while (1)
1354 const char *name;
1355 size_t len;
1356 #if defined _LIBC && !defined COMPILE_GLOB64
1357 struct dirent64 *d;
1358 union
1360 struct dirent64 d64;
1361 char room [offsetof (struct dirent64, d_name[0])
1362 + NAME_MAX + 1];
1364 d64buf;
1366 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1368 struct dirent *d32 = (*pglob->gl_readdir) (stream);
1369 if (d32 != NULL)
1371 CONVERT_DIRENT_DIRENT64 (&d64buf.d64, d32);
1372 d = &d64buf.d64;
1374 else
1375 d = NULL;
1377 else
1378 d = __readdir64 (stream);
1379 #else
1380 struct dirent *d = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1381 ? ((struct dirent *)
1382 (*pglob->gl_readdir) (stream))
1383 : __readdir (stream));
1384 #endif
1385 if (d == NULL)
1386 break;
1387 if (! REAL_DIR_ENTRY (d))
1388 continue;
1390 /* If we shall match only directories use the information
1391 provided by the dirent call if possible. */
1392 if ((flags & GLOB_ONLYDIR) && !DIRENT_MIGHT_BE_DIR (d))
1393 continue;
1395 name = d->d_name;
1397 if (fnmatch (pattern, name, fnm_flags) == 0)
1399 /* If the file we found is a symlink we have to
1400 make sure the target file exists. */
1401 if (!DIRENT_MIGHT_BE_SYMLINK (d)
1402 || link_exists_p (dfd, directory, dirlen, name, pglob,
1403 flags))
1405 if (cur == names->count)
1407 struct globnames *newnames;
1408 size_t count = names->count * 2;
1409 size_t size = (sizeof (struct globnames)
1410 + ((count - INITIAL_COUNT)
1411 * sizeof (char *)));
1412 allocasize += size;
1413 if (__libc_use_alloca (allocasize))
1414 newnames = names_alloca = __alloca (size);
1415 else if ((newnames = malloc (size))
1416 == NULL)
1417 goto memory_error;
1418 newnames->count = count;
1419 newnames->next = names;
1420 names = newnames;
1421 cur = 0;
1423 len = NAMLEN (d);
1424 names->name[cur] = (char *) malloc (len + 1);
1425 if (names->name[cur] == NULL)
1426 goto memory_error;
1427 *((char *) mempcpy (names->name[cur++], name, len))
1428 = '\0';
1429 ++nfound;
1436 if (nfound == 0 && (flags & GLOB_NOCHECK))
1438 size_t len = strlen (pattern);
1439 nfound = 1;
1440 names->name[cur] = (char *) malloc (len + 1);
1441 if (names->name[cur] == NULL)
1442 goto memory_error;
1443 *((char *) mempcpy (names->name[cur++], pattern, len)) = '\0';
1446 int result = GLOB_NOMATCH;
1447 if (nfound != 0)
1449 result = 0;
1451 char **new_gl_pathv;
1452 new_gl_pathv
1453 = (char **) realloc (pglob->gl_pathv,
1454 (pglob->gl_pathc + pglob->gl_offs + nfound + 1)
1455 * sizeof (char *));
1456 if (new_gl_pathv == NULL)
1458 memory_error:
1459 while (1)
1461 struct globnames *old = names;
1462 for (size_t i = 0; i < cur; ++i)
1463 free (names->name[i]);
1464 names = names->next;
1465 /* NB: we will not leak memory here if we exit without
1466 freeing the current block assigned to OLD. At least
1467 the very first block is always allocated on the stack
1468 and this is the block assigned to OLD here. */
1469 if (names == NULL)
1471 assert (old == &init_names);
1472 break;
1474 cur = names->count;
1475 if (old == names_alloca)
1476 names_alloca = names;
1477 else
1478 free (old);
1480 result = GLOB_NOSPACE;
1482 else
1484 while (1)
1486 struct globnames *old = names;
1487 for (size_t i = 0; i < cur; ++i)
1488 new_gl_pathv[pglob->gl_offs + pglob->gl_pathc++]
1489 = names->name[i];
1490 names = names->next;
1491 /* NB: we will not leak memory here if we exit without
1492 freeing the current block assigned to OLD. At least
1493 the very first block is always allocated on the stack
1494 and this is the block assigned to OLD here. */
1495 if (names == NULL)
1497 assert (old == &init_names);
1498 break;
1500 cur = names->count;
1501 if (old == names_alloca)
1502 names_alloca = names;
1503 else
1504 free (old);
1507 pglob->gl_pathv = new_gl_pathv;
1509 pglob->gl_pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
1511 pglob->gl_flags = flags;
1515 if (stream != NULL)
1517 save = errno;
1518 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1519 (*pglob->gl_closedir) (stream);
1520 else
1521 closedir (stream);
1522 __set_errno (save);
1525 return result;