Update.
[glibc.git] / sysdeps / generic / glob.c
blob5fc094ebe70bdb5b1dd78b06dad53181ca923622
1 /* Copyright (C) 1991,92,93,94,95,96,97,98 Free Software Foundation, Inc.
3 This library is free software; you can redistribute it and/or
4 modify it under the terms of the GNU Library General Public License as
5 published by the Free Software Foundation; either version 2 of the
6 License, or (at your option) any later version.
8 This library is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 Library General Public License for more details.
13 You should have received a copy of the GNU Library General Public
14 License along with this library; see the file COPYING.LIB. If not,
15 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 Boston, MA 02111-1307, USA. */
18 /* AIX requires this to be the first thing in the file. */
19 #if defined _AIX && !defined __GNUC__
20 #pragma alloca
21 #endif
23 #ifdef HAVE_CONFIG_H
24 # include <config.h>
25 #endif
27 /* Enable GNU extensions in glob.h. */
28 #ifndef _GNU_SOURCE
29 # define _GNU_SOURCE 1
30 #endif
32 #include <errno.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
36 /* Outcomment the following line for production quality code. */
37 /* #define NDEBUG 1 */
38 #include <assert.h>
40 #include <stdio.h> /* Needed on stupid SunOS for assert. */
43 /* Comment out all this code if we are using the GNU C Library, and are not
44 actually compiling the library itself. This code is part of the GNU C
45 Library, but also included in many other GNU distributions. Compiling
46 and linking in this code is a waste when using the GNU C library
47 (especially if it is a shared library). Rather than having every GNU
48 program understand `configure --with-gnu-libc' and omit the object files,
49 it is simpler to just do this in the source for each such file. */
51 #define GLOB_INTERFACE_VERSION 1
52 #if !defined _LIBC && defined __GNU_LIBRARY__ && __GNU_LIBRARY__ > 1
53 # include <gnu-versions.h>
54 # if _GNU_GLOB_INTERFACE_VERSION == GLOB_INTERFACE_VERSION
55 # define ELIDE_CODE
56 # endif
57 #endif
59 #ifndef ELIDE_CODE
61 #if defined STDC_HEADERS || defined __GNU_LIBRARY__
62 # include <stddef.h>
63 #endif
65 #if defined HAVE_UNISTD_H || defined _LIBC
66 # include <unistd.h>
67 # ifndef POSIX
68 # ifdef _POSIX_VERSION
69 # define POSIX
70 # endif
71 # endif
72 #endif
74 #if !defined _AMIGA && !defined VMS && !defined WINDOWS32
75 # include <pwd.h>
76 #endif
78 #if !defined __GNU_LIBRARY__ && !defined STDC_HEADERS
79 extern int errno;
80 #endif
81 #ifndef __set_errno
82 # define __set_errno(val) errno = (val)
83 #endif
85 #ifndef NULL
86 # define NULL 0
87 #endif
90 #if defined HAVE_DIRENT_H || defined __GNU_LIBRARY__
91 # include <dirent.h>
92 # define NAMLEN(dirent) strlen((dirent)->d_name)
93 #else
94 # define dirent direct
95 # define NAMLEN(dirent) (dirent)->d_namlen
96 # ifdef HAVE_SYS_NDIR_H
97 # include <sys/ndir.h>
98 # endif
99 # ifdef HAVE_SYS_DIR_H
100 # include <sys/dir.h>
101 # endif
102 # ifdef HAVE_NDIR_H
103 # include <ndir.h>
104 # endif
105 # ifdef HAVE_VMSDIR_H
106 # include "vmsdir.h"
107 # endif /* HAVE_VMSDIR_H */
108 #endif
111 /* In GNU systems, <dirent.h> defines this macro for us. */
112 #ifdef _D_NAMLEN
113 # undef NAMLEN
114 # define NAMLEN(d) _D_NAMLEN(d)
115 #endif
117 /* When used in the GNU libc the symbol _DIRENT_HAVE_D_TYPE is available
118 if the `d_type' member for `struct dirent' is available. */
119 #ifdef _DIRENT_HAVE_D_TYPE
120 # define HAVE_D_TYPE 1
121 #endif
124 #if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
125 /* Posix does not require that the d_ino field be present, and some
126 systems do not provide it. */
127 # define REAL_DIR_ENTRY(dp) 1
128 #else
129 # define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
130 #endif /* POSIX */
132 #if defined STDC_HEADERS || defined __GNU_LIBRARY__
133 # include <stdlib.h>
134 # include <string.h>
135 # define ANSI_STRING
136 #else /* No standard headers. */
138 extern char *getenv ();
140 # ifdef HAVE_STRING_H
141 # include <string.h>
142 # define ANSI_STRING
143 # else
144 # include <strings.h>
145 # endif
146 # ifdef HAVE_MEMORY_H
147 # include <memory.h>
148 # endif
150 extern char *malloc (), *realloc ();
151 extern void free ();
153 extern void qsort ();
154 extern void abort (), exit ();
156 #endif /* Standard headers. */
158 #ifdef HAVE_GETLOGIN_R
159 extern int getlogin_r __P ((char *, size_t));
160 #else
161 extern char *getlogin __P ((void));
162 #endif
164 #ifndef ANSI_STRING
166 # ifndef bzero
167 extern void bzero ();
168 # endif
169 # ifndef bcopy
170 extern void bcopy ();
171 # endif
173 # define memcpy(d, s, n) bcopy ((s), (d), (n))
174 # define strrchr rindex
175 /* memset is only used for zero here, but let's be paranoid. */
176 # define memset(s, better_be_zero, n) \
177 ((void) ((better_be_zero) == 0 ? (bzero((s), (n)), 0) : (abort(), 0)))
178 #endif /* Not ANSI_STRING. */
180 #if !defined HAVE_STRCOLL && !defined _LIBC
181 # define strcoll strcmp
182 #endif
184 #if !defined HAVE_MEMPCPY && __GLIBC__ - 0 == 2 && __GLIBC_MINOR__ >= 1
185 # define HAVE_MEMPCPY 1
186 # define mempcpy(Dest, Src, Len) __mempcpy (Dest, Src, Len)
187 #endif
189 #ifndef __GNU_LIBRARY__
190 # ifdef __GNUC__
191 __inline
192 # endif
193 # ifndef __SASC
194 # ifdef WINDOWS32
195 static void *
196 # else
197 static char *
198 # endif
199 my_realloc (p, n)
200 char *p;
201 unsigned int n;
203 /* These casts are the for sake of the broken Ultrix compiler,
204 which warns of illegal pointer combinations otherwise. */
205 if (p == NULL)
206 return (char *) malloc (n);
207 return (char *) realloc (p, n);
209 # define realloc my_realloc
210 # endif /* __SASC */
211 #endif /* __GNU_LIBRARY__ */
214 #if !defined __alloca && !defined __GNU_LIBRARY__
216 # ifdef __GNUC__
217 # undef alloca
218 # define alloca(n) __builtin_alloca (n)
219 # else /* Not GCC. */
220 # ifdef HAVE_ALLOCA_H
221 # include <alloca.h>
222 # else /* Not HAVE_ALLOCA_H. */
223 # ifndef _AIX
224 # ifdef WINDOWS32
225 # include <malloc.h>
226 # else
227 extern char *alloca ();
228 # endif /* WINDOWS32 */
229 # endif /* Not _AIX. */
230 # endif /* sparc or HAVE_ALLOCA_H. */
231 # endif /* GCC. */
233 # define __alloca alloca
235 #endif
237 #ifndef __GNU_LIBRARY__
238 # define __stat stat
239 # ifdef STAT_MACROS_BROKEN
240 # undef S_ISDIR
241 # endif
242 # ifndef S_ISDIR
243 # define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
244 # endif
245 #endif
247 #ifdef _LIBC
248 # undef strdup
249 # define strdup(str) __strdup (str)
250 # define sysconf(id) __sysconf (id)
251 # define closedir(dir) __closedir (dir)
252 # define opendir(name) __opendir (name)
253 # define readdir(str) __readdir (str)
254 # define getpwnam_r(name, bufp, buf, len, res) \
255 __getpwnam_r (name, bufp, buf, len, res)
256 #endif
258 #if !(defined STDC_HEADERS || defined __GNU_LIBRARY__)
259 # undef size_t
260 # define size_t unsigned int
261 #endif
263 /* Some system header files erroneously define these.
264 We want our own definitions from <fnmatch.h> to take precedence. */
265 #ifndef __GNU_LIBRARY__
266 # undef FNM_PATHNAME
267 # undef FNM_NOESCAPE
268 # undef FNM_PERIOD
269 #endif
270 #include <fnmatch.h>
272 /* Some system header files erroneously define these.
273 We want our own definitions from <glob.h> to take precedence. */
274 #ifndef __GNU_LIBRARY__
275 # undef GLOB_ERR
276 # undef GLOB_MARK
277 # undef GLOB_NOSORT
278 # undef GLOB_DOOFFS
279 # undef GLOB_NOCHECK
280 # undef GLOB_APPEND
281 # undef GLOB_NOESCAPE
282 # undef GLOB_PERIOD
283 #endif
284 #include <glob.h>
286 static
287 #if __GNUC__ - 0 >= 2
288 inline
289 #endif
290 const char *next_brace_sub __P ((const char *begin));
291 static int glob_in_dir __P ((const char *pattern, const char *directory,
292 int flags,
293 int (*errfunc) __P ((const char *, int)),
294 glob_t *pglob));
295 static int prefix_array __P ((const char *prefix, char **array, size_t n));
296 static int collated_compare __P ((const __ptr_t, const __ptr_t));
299 /* Find the end of the sub-pattern in a brace expression. We define
300 this as an inline function if the compiler permits. */
301 static
302 #if __GNUC__ - 0 >= 2
303 inline
304 #endif
305 const char *
306 next_brace_sub (begin)
307 const char *begin;
309 unsigned int depth = 0;
310 const char *cp = begin;
312 while (1)
314 if (depth == 0)
316 if (*cp != ',' && *cp != '}' && *cp != '\0')
318 if (*cp == '{')
319 ++depth;
320 ++cp;
321 continue;
324 else
326 while (*cp != '\0' && (*cp != '}' || depth > 0))
328 if (*cp == '}')
329 --depth;
330 ++cp;
332 if (*cp == '\0')
333 /* An incorrectly terminated brace expression. */
334 return NULL;
336 continue;
338 break;
341 return cp;
344 /* Do glob searching for PATTERN, placing results in PGLOB.
345 The bits defined above may be set in FLAGS.
346 If a directory cannot be opened or read and ERRFUNC is not nil,
347 it is called with the pathname that caused the error, and the
348 `errno' value from the failing call; if it returns non-zero
349 `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
350 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
351 Otherwise, `glob' returns zero. */
353 glob (pattern, flags, errfunc, pglob)
354 const char *pattern;
355 int flags;
356 int (*errfunc) __P ((const char *, int));
357 glob_t *pglob;
359 const char *filename;
360 const char *dirname;
361 size_t dirlen;
362 int status;
363 int oldcount;
365 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
367 __set_errno (EINVAL);
368 return -1;
371 if (flags & GLOB_BRACE)
373 const char *begin = strchr (pattern, '{');
374 if (begin != NULL)
376 /* Allocate working buffer large enough for our work. Note that
377 we have at least an opening and closing brace. */
378 int firstc;
379 char *alt_start;
380 const char *p;
381 const char *next;
382 const char *rest;
383 size_t rest_len;
384 #ifdef __GNUC__
385 char onealt[strlen (pattern) - 1];
386 #else
387 char *onealt = (char *) malloc (strlen (pattern) - 1);
388 if (onealt == NULL)
390 if (!(flags & GLOB_APPEND))
391 globfree (pglob);
392 return GLOB_NOSPACE;
394 #endif
396 /* We know the prefix for all sub-patterns. */
397 #ifdef HAVE_MEMPCPY
398 alt_start = mempcpy (onealt, pattern, begin - pattern);
399 #else
400 memcpy (onealt, pattern, begin - pattern);
401 alt_start = &onealt[begin - pattern];
402 #endif
404 /* Find the first sub-pattern and at the same time find the
405 rest after the closing brace. */
406 next = next_brace_sub (begin + 1);
407 if (next == NULL)
409 /* It is an illegal expression. */
410 #ifndef __GNUC__
411 free (onealt);
412 #endif
413 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
416 /* Now find the end of the whole brace expression. */
417 rest = next;
418 while (*rest != '}')
420 rest = next_brace_sub (rest + 1);
421 if (rest == NULL)
423 /* It is an illegal expression. */
424 #ifndef __GNUC__
425 free (onealt);
426 #endif
427 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
430 /* Please note that we now can be sure the brace expression
431 is well-formed. */
432 rest_len = strlen (++rest) + 1;
434 /* We have a brace expression. BEGIN points to the opening {,
435 NEXT points past the terminator of the first element, and END
436 points past the final }. We will accumulate result names from
437 recursive runs for each brace alternative in the buffer using
438 GLOB_APPEND. */
440 if (!(flags & GLOB_APPEND))
442 /* This call is to set a new vector, so clear out the
443 vector so we can append to it. */
444 pglob->gl_pathc = 0;
445 pglob->gl_pathv = NULL;
447 firstc = pglob->gl_pathc;
449 p = begin + 1;
450 while (1)
452 int result;
454 /* Construct the new glob expression. */
455 #ifdef HAVE_MEMPCPY
456 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
457 #else
458 memcpy (alt_start, p, next - p);
459 memcpy (&alt_start[next - p], rest, rest_len);
460 #endif
462 result = glob (onealt,
463 ((flags & ~(GLOB_NOCHECK|GLOB_NOMAGIC))
464 | GLOB_APPEND), errfunc, pglob);
466 /* If we got an error, return it. */
467 if (result && result != GLOB_NOMATCH)
469 #ifndef __GNUC__
470 free (onealt);
471 #endif
472 if (!(flags & GLOB_APPEND))
473 globfree (pglob);
474 return result;
477 if (*next == '}')
478 /* We saw the last entry. */
479 break;
481 p = next + 1;
482 next = next_brace_sub (p);
483 assert (next != NULL);
486 #ifndef __GNUC__
487 free (onealt);
488 #endif
490 if (pglob->gl_pathc != firstc)
491 /* We found some entries. */
492 return 0;
493 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
494 return GLOB_NOMATCH;
498 /* Find the filename. */
499 filename = strrchr (pattern, '/');
500 #if defined __MSDOS__ || defined WINDOWS32
501 /* The case of "d:pattern". Since `:' is not allowed in
502 file names, we can safely assume that wherever it
503 happens in pattern, it signals the filename part. This
504 is so we could some day support patterns like "[a-z]:foo". */
505 if (filename == NULL)
506 filename = strchr (pattern, ':');
507 #endif /* __MSDOS__ || WINDOWS32 */
508 if (filename == NULL)
510 /* This can mean two things: a simple name or "~name". The later
511 case is nothing but a notation for a directory. */
512 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
514 dirname = pattern;
515 dirlen = strlen (pattern);
517 /* Set FILENAME to NULL as a special flag. This is ugly but
518 other solutions would require much more code. We test for
519 this special case below. */
520 filename = NULL;
522 else
524 filename = pattern;
525 #ifdef _AMIGA
526 dirname = "";
527 #else
528 dirname = ".";
529 #endif
530 dirlen = 0;
533 else if (filename == pattern)
535 /* "/pattern". */
536 dirname = "/";
537 dirlen = 1;
538 ++filename;
540 else
542 char *newp;
543 dirlen = filename - pattern;
544 #if defined __MSDOS__ || defined WINDOWS32
545 if (*filename == ':'
546 || (filename > pattern + 1 && filename[-1] == ':'))
548 char *drive_spec;
550 ++dirlen;
551 drive_spec = (char *) __alloca (dirlen + 1);
552 #ifdef HAVE_MEMPCPY
553 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
554 #else
555 memcpy (drive_spec, pattern, dirlen);
556 drive_spec[dirlen] = '\0';
557 #endif
558 /* For now, disallow wildcards in the drive spec, to
559 prevent infinite recursion in glob. */
560 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
561 return GLOB_NOMATCH;
562 /* If this is "d:pattern", we need to copy `:' to DIRNAME
563 as well. If it's "d:/pattern", don't remove the slash
564 from "d:/", since "d:" and "d:/" are not the same.*/
566 #endif
567 newp = (char *) __alloca (dirlen + 1);
568 #ifdef HAVE_MEMPCPY
569 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
570 #else
571 memcpy (newp, pattern, dirlen);
572 newp[dirlen] = '\0';
573 #endif
574 dirname = newp;
575 ++filename;
577 if (filename[0] == '\0'
578 #if defined __MSDOS__ || defined WINDOWS32
579 && dirname[dirlen - 1] != ':'
580 && (dirlen < 3 || dirname[dirlen - 2] != ':'
581 || dirname[dirlen - 1] != '/')
582 #endif
583 && dirlen > 1)
584 /* "pattern/". Expand "pattern", appending slashes. */
586 int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
587 if (val == 0)
588 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
589 | (flags & GLOB_MARK));
590 return val;
594 if (!(flags & GLOB_APPEND))
596 pglob->gl_pathc = 0;
597 pglob->gl_pathv = NULL;
600 oldcount = pglob->gl_pathc;
602 #ifndef VMS
603 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
605 if (dirname[1] == '\0' || dirname[1] == '/')
607 /* Look up home directory. */
608 const char *home_dir = getenv ("HOME");
609 # ifdef _AMIGA
610 if (home_dir == NULL || home_dir[0] == '\0')
611 home_dir = "SYS:";
612 # else
613 # ifdef WINDOWS32
614 if (home_dir == NULL || home_dir[0] == '\0')
615 home_dir = "c:/users/default"; /* poor default */
616 # else
617 if (home_dir == NULL || home_dir[0] == '\0')
619 int success;
620 char *name;
621 # if defined HAVE_GETLOGIN_R || defined _LIBC
622 size_t buflen = sysconf (_SC_LOGIN_NAME_MAX) + 1;
624 if (buflen == 0)
625 /* `sysconf' does not support _SC_LOGIN_NAME_MAX. Try
626 a moderate value. */
627 buflen = 20;
628 name = (char *) __alloca (buflen);
630 success = getlogin_r (name, buflen) >= 0;
631 # else
632 success = (name = getlogin ()) != NULL;
633 # endif
634 if (success)
636 struct passwd *p;
637 # if defined HAVE_GETPWNAM_R || defined _LIBC
638 size_t pwbuflen = sysconf (_SC_GETPW_R_SIZE_MAX);
639 char *pwtmpbuf;
640 struct passwd pwbuf;
642 if (pwbuflen == -1)
643 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.
644 Try a moderate value. */
645 pwbuflen = 1024;
646 pwtmpbuf = (char *) __alloca (pwbuflen);
648 success = (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
649 >= 0);
650 # else
651 p = getpwnam (name);
652 success = p != NULL;
653 # endif
654 if (success)
655 home_dir = p->pw_dir;
658 if (home_dir == NULL || home_dir[0] == '\0')
659 if (flags & GLOB_TILDE_CHECK)
660 return GLOB_NOMATCH;
661 else
662 home_dir = "~"; /* No luck. */
663 # endif /* WINDOWS32 */
664 # endif
665 /* Now construct the full directory. */
666 if (dirname[1] == '\0')
667 dirname = home_dir;
668 else
670 char *newp;
671 size_t home_len = strlen (home_dir);
672 newp = (char *) __alloca (home_len + dirlen);
673 # ifdef HAVE_MEMPCPY
674 mempcpy (mempcpy (newp, home_dir, home_len),
675 &dirname[1], dirlen);
676 # else
677 memcpy (newp, home_dir, home_len);
678 memcpy (&newp[home_len], &dirname[1], dirlen);
679 # endif
680 dirname = newp;
683 # if !defined _AMIGA && !defined WINDOWS32
684 else
686 char *end_name = strchr (dirname, '/');
687 const char *user_name;
688 const char *home_dir;
690 if (end_name == NULL)
691 user_name = dirname + 1;
692 else
694 char *newp;
695 newp = (char *) __alloca (end_name - dirname);
696 # ifdef HAVE_MEMPCPY
697 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
698 = '\0';
699 # else
700 memcpy (newp, dirname + 1, end_name - dirname);
701 newp[end_name - dirname - 1] = '\0';
702 # endif
703 user_name = newp;
706 /* Look up specific user's home directory. */
708 struct passwd *p;
709 # if defined HAVE_GETPWNAM_R || defined _LIBC
710 size_t buflen = sysconf (_SC_GETPW_R_SIZE_MAX);
711 char *pwtmpbuf;
712 struct passwd pwbuf;
714 if (buflen == -1)
715 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
716 moderate value. */
717 buflen = 1024;
718 pwtmpbuf = (char *) __alloca (buflen);
720 if (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) >= 0)
721 home_dir = p->pw_dir;
722 else
723 home_dir = NULL;
724 # else
725 p = getpwnam (user_name);
726 if (p != NULL)
727 home_dir = p->pw_dir;
728 else
729 home_dir = NULL;
730 # endif
732 /* If we found a home directory use this. */
733 if (home_dir != NULL)
735 char *newp;
736 size_t home_len = strlen (home_dir);
737 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
738 newp = (char *) __alloca (home_len + rest_len + 1);
739 # ifdef HAVE_MEMPCPY
740 *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
741 end_name, rest_len)) = '\0';
742 # else
743 memcpy (newp, home_dir, home_len);
744 memcpy (&newp[home_len], end_name, rest_len);
745 newp[home_len + rest_len] = '\0';
746 # endif
747 dirname = newp;
749 else
750 if (flags & GLOB_TILDE_CHECK)
751 /* We have to regard it as an error if we cannot find the
752 home directory. */
753 return GLOB_NOMATCH;
755 # endif /* Not Amiga && not WINDOWS32. */
757 #endif /* Not VMS. */
759 /* Now test whether we looked for "~" or "~NAME". In this case we
760 can give the answer now. */
761 if (filename == NULL)
763 struct stat st;
765 /* Return the directory if we don't check for error or if it exists. */
766 if ((flags & GLOB_NOCHECK)
767 || (((flags & GLOB_ALTDIRFUNC)
768 ? (*pglob->gl_stat) (dirname, &st)
769 : __stat (dirname, &st)) == 0
770 && S_ISDIR (st.st_mode)))
772 pglob->gl_pathv
773 = (char **) realloc (pglob->gl_pathv,
774 (pglob->gl_pathc +
775 ((flags & GLOB_DOOFFS) ?
776 pglob->gl_offs : 0) +
777 1 + 1) *
778 sizeof (char *));
779 if (pglob->gl_pathv == NULL)
780 return GLOB_NOSPACE;
782 if (flags & GLOB_DOOFFS)
783 while (pglob->gl_pathc < pglob->gl_offs)
784 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
786 #if defined HAVE_STRDUP || defined _LIBC
787 pglob->gl_pathv[pglob->gl_pathc] = strdup (dirname);
788 #else
790 size_t len = strlen (dirname) + 1;
791 char *dircopy = malloc (len);
792 if (dircopy != NULL)
793 pglob->gl_pathv[pglob->gl_pathc] = memcpy (dircopy, dirname,
794 len);
796 #endif
797 if (pglob->gl_pathv[pglob->gl_pathc] == NULL)
799 free (pglob->gl_pathv);
800 return GLOB_NOSPACE;
802 pglob->gl_pathv[++pglob->gl_pathc] = NULL;
803 pglob->gl_flags = flags;
805 return 0;
808 /* Not found. */
809 return GLOB_NOMATCH;
812 if (__glob_pattern_p (dirname, !(flags & GLOB_NOESCAPE)))
814 /* The directory name contains metacharacters, so we
815 have to glob for the directory, and then glob for
816 the pattern in each directory found. */
817 glob_t dirs;
818 register int i;
820 status = glob (dirname,
821 ((flags & (GLOB_ERR | GLOB_NOCHECK | GLOB_NOESCAPE))
822 | GLOB_NOSORT | GLOB_ONLYDIR),
823 errfunc, &dirs);
824 if (status != 0)
825 return status;
827 /* We have successfully globbed the preceding directory name.
828 For each name we found, call glob_in_dir on it and FILENAME,
829 appending the results to PGLOB. */
830 for (i = 0; i < dirs.gl_pathc; ++i)
832 int old_pathc;
834 #ifdef SHELL
836 /* Make globbing interruptible in the bash shell. */
837 extern int interrupt_state;
839 if (interrupt_state)
841 globfree (&dirs);
842 globfree (&files);
843 return GLOB_ABORTED;
846 #endif /* SHELL. */
848 old_pathc = pglob->gl_pathc;
849 status = glob_in_dir (filename, dirs.gl_pathv[i],
850 ((flags | GLOB_APPEND)
851 & ~(GLOB_NOCHECK | GLOB_ERR)),
852 errfunc, pglob);
853 if (status == GLOB_NOMATCH)
854 /* No matches in this directory. Try the next. */
855 continue;
857 if (status != 0)
859 globfree (&dirs);
860 globfree (pglob);
861 return status;
864 /* Stick the directory on the front of each name. */
865 if (prefix_array (dirs.gl_pathv[i],
866 &pglob->gl_pathv[old_pathc],
867 pglob->gl_pathc - old_pathc))
869 globfree (&dirs);
870 globfree (pglob);
871 return GLOB_NOSPACE;
875 flags |= GLOB_MAGCHAR;
877 /* We have ignored the GLOB_NOCHECK flag in the `glob_in_dir' calls.
878 But if we have not found any matching entry and thie GLOB_NOCHECK
879 flag was set we must return the list consisting of the disrectory
880 names followed by the filename. */
881 if (pglob->gl_pathc == oldcount)
882 /* No matches. */
883 if (flags & GLOB_NOCHECK)
885 size_t filename_len = strlen (filename) + 1;
886 char **new_pathv;
887 struct stat st;
889 /* This is an pessimistic guess about the size. */
890 pglob->gl_pathv
891 = (char **) realloc (pglob->gl_pathv,
892 (pglob->gl_pathc +
893 ((flags & GLOB_DOOFFS) ?
894 pglob->gl_offs : 0) +
895 dirs.gl_pathc + 1) *
896 sizeof (char *));
897 if (pglob->gl_pathv == NULL)
899 globfree (&dirs);
900 return GLOB_NOSPACE;
903 if (flags & GLOB_DOOFFS)
904 while (pglob->gl_pathc < pglob->gl_offs)
905 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
907 for (i = 0; i < dirs.gl_pathc; ++i)
909 const char *dir = dirs.gl_pathv[i];
910 size_t dir_len = strlen (dir);
912 /* First check whether this really is a directory. */
913 if (((flags & GLOB_ALTDIRFUNC)
914 ? (*pglob->gl_stat) (dir, &st) : __stat (dir, &st)) != 0
915 || !S_ISDIR (st.st_mode))
916 /* No directory, ignore this entry. */
917 continue;
919 pglob->gl_pathv[pglob->gl_pathc] = malloc (dir_len + 1
920 + filename_len);
921 if (pglob->gl_pathv[pglob->gl_pathc] == NULL)
923 globfree (&dirs);
924 globfree (pglob);
925 return GLOB_NOSPACE;
928 #ifdef HAVE_MEMPCPY
929 mempcpy (mempcpy (mempcpy (pglob->gl_pathv[pglob->gl_pathc],
930 dir, dir_len),
931 "/", 1),
932 filename, filename_len);
933 #else
934 memcpy (pglob->gl_pathv[pglob->gl_pathc], dir, dir_len);
935 pglob->gl_pathv[pglob->gl_pathc][dir_len] = '/';
936 memcpy (&pglob->gl_pathv[pglob->gl_pathc][dir_len + 1],
937 filename, filename_len);
938 #endif
939 ++pglob->gl_pathc;
942 pglob->gl_pathv[pglob->gl_pathc] = NULL;
943 pglob->gl_flags = flags;
945 /* Now we know how large the gl_pathv vector must be. */
946 new_pathv = (char **) realloc (pglob->gl_pathv,
947 ((pglob->gl_pathc + 1)
948 * sizeof (char *)));
949 if (new_pathv != NULL)
950 pglob->gl_pathv = new_pathv;
952 else
953 return GLOB_NOMATCH;
955 globfree (&dirs);
957 else
959 status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
960 if (status != 0)
961 return status;
963 if (dirlen > 0)
965 /* Stick the directory on the front of each name. */
966 int ignore = oldcount;
968 if ((flags & GLOB_DOOFFS) && ignore < pglob->gl_offs)
969 ignore = pglob->gl_offs;
971 if (prefix_array (dirname,
972 &pglob->gl_pathv[ignore],
973 pglob->gl_pathc - ignore))
975 globfree (pglob);
976 return GLOB_NOSPACE;
981 if (flags & GLOB_MARK)
983 /* Append slashes to directory names. */
984 int i;
985 struct stat st;
986 for (i = oldcount; i < pglob->gl_pathc; ++i)
987 if (((flags & GLOB_ALTDIRFUNC)
988 ? (*pglob->gl_stat) (pglob->gl_pathv[i], &st)
989 : __stat (pglob->gl_pathv[i], &st)) == 0
990 && S_ISDIR (st.st_mode))
992 size_t len = strlen (pglob->gl_pathv[i]) + 2;
993 char *new = realloc (pglob->gl_pathv[i], len);
994 if (new == NULL)
996 globfree (pglob);
997 return GLOB_NOSPACE;
999 strcpy (&new[len - 2], "/");
1000 pglob->gl_pathv[i] = new;
1004 if (!(flags & GLOB_NOSORT))
1006 /* Sort the vector. */
1007 int non_sort = oldcount;
1009 if ((flags & GLOB_DOOFFS) && pglob->gl_offs > oldcount)
1010 non_sort = pglob->gl_offs;
1012 qsort ((__ptr_t) &pglob->gl_pathv[non_sort],
1013 pglob->gl_pathc - non_sort,
1014 sizeof (char *), collated_compare);
1017 return 0;
1021 /* Free storage allocated in PGLOB by a previous `glob' call. */
1022 void
1023 globfree (pglob)
1024 register glob_t *pglob;
1026 if (pglob->gl_pathv != NULL)
1028 register int i;
1029 for (i = 0; i < pglob->gl_pathc; ++i)
1030 if (pglob->gl_pathv[i] != NULL)
1031 free ((__ptr_t) pglob->gl_pathv[i]);
1032 free ((__ptr_t) pglob->gl_pathv);
1037 /* Do a collated comparison of A and B. */
1038 static int
1039 collated_compare (a, b)
1040 const __ptr_t a;
1041 const __ptr_t b;
1043 const char *const s1 = *(const char *const * const) a;
1044 const char *const s2 = *(const char *const * const) b;
1046 if (s1 == s2)
1047 return 0;
1048 if (s1 == NULL)
1049 return 1;
1050 if (s2 == NULL)
1051 return -1;
1052 return strcoll (s1, s2);
1056 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1057 elements in place. Return nonzero if out of memory, zero if successful.
1058 A slash is inserted between DIRNAME and each elt of ARRAY,
1059 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1060 static int
1061 prefix_array (dirname, array, n)
1062 const char *dirname;
1063 char **array;
1064 size_t n;
1066 register size_t i;
1067 size_t dirlen = strlen (dirname);
1068 #if defined __MSDOS__ || defined WINDOWS32
1069 int sep_char = '/';
1070 # define DIRSEP_CHAR sep_char
1071 #else
1072 # define DIRSEP_CHAR '/'
1073 #endif
1075 if (dirlen == 1 && dirname[0] == '/')
1076 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1077 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1078 dirlen = 0;
1079 #if defined __MSDOS__ || defined WINDOWS32
1080 else if (dirlen > 1)
1082 if (dirname[dirlen - 1] == '/')
1083 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1084 --dirlen;
1085 else if (dirname[dirlen - 1] == ':')
1087 /* DIRNAME is "d:". Use `:' instead of `/'. */
1088 --dirlen;
1089 sep_char = ':';
1092 #endif
1094 for (i = 0; i < n; ++i)
1096 size_t eltlen = strlen (array[i]) + 1;
1097 char *new = (char *) malloc (dirlen + 1 + eltlen);
1098 if (new == NULL)
1100 while (i > 0)
1101 free ((__ptr_t) array[--i]);
1102 return 1;
1105 #ifdef HAVE_MEMPCPY
1107 char *endp = (char *) mempcpy (new, dirname, dirlen);
1108 *endp++ = DIRSEP_CHAR;
1109 mempcpy (endp, array[i], eltlen);
1111 #else
1112 memcpy (new, dirname, dirlen);
1113 new[dirlen] = DIRSEP_CHAR;
1114 memcpy (&new[dirlen + 1], array[i], eltlen);
1115 #endif
1116 free ((__ptr_t) array[i]);
1117 array[i] = new;
1120 return 0;
1124 /* Return nonzero if PATTERN contains any metacharacters.
1125 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
1127 __glob_pattern_p (pattern, quote)
1128 const char *pattern;
1129 int quote;
1131 register const char *p;
1132 int open = 0;
1134 for (p = pattern; *p != '\0'; ++p)
1135 switch (*p)
1137 case '?':
1138 case '*':
1139 return 1;
1141 case '\\':
1142 if (quote && p[1] != '\0')
1143 ++p;
1144 break;
1146 case '[':
1147 open = 1;
1148 break;
1150 case ']':
1151 if (open)
1152 return 1;
1153 break;
1156 return 0;
1158 #ifdef _LIBC
1159 weak_alias (__glob_pattern_p, glob_pattern_p)
1160 #endif
1163 /* Like `glob', but PATTERN is a final pathname component,
1164 and matches are searched for in DIRECTORY.
1165 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1166 The GLOB_APPEND flag is assumed to be set (always appends). */
1167 static int
1168 glob_in_dir (pattern, directory, flags, errfunc, pglob)
1169 const char *pattern;
1170 const char *directory;
1171 int flags;
1172 int (*errfunc) __P ((const char *, int));
1173 glob_t *pglob;
1175 __ptr_t stream = NULL;
1177 struct globlink
1179 struct globlink *next;
1180 char *name;
1182 struct globlink *names = NULL;
1183 size_t nfound;
1184 int meta;
1185 int save;
1187 meta = __glob_pattern_p (pattern, !(flags & GLOB_NOESCAPE));
1188 if (meta == 0)
1190 if (flags & (GLOB_NOCHECK|GLOB_NOMAGIC))
1191 /* We need not do any tests. The PATTERN contains no meta
1192 characters and we must not return an error therefore the
1193 result will always contain exactly one name. */
1194 flags |= GLOB_NOCHECK;
1195 else
1197 /* Since we use the normal file functions we can also use stat()
1198 to verify the file is there. */
1199 struct stat st;
1200 size_t patlen = strlen (pattern);
1201 size_t dirlen = strlen (directory);
1202 char *fullname = (char *) __alloca (dirlen + 1 + patlen + 1);
1204 # ifdef HAVE_MEMPCPY
1205 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1206 "/", 1),
1207 pattern, patlen + 1);
1208 # else
1209 memcpy (fullname, directory, dirlen);
1210 fullname[dirlen] = '/';
1211 memcpy (&fullname[dirlen + 1], pattern, patlen + 1);
1212 # endif
1213 if (((flags & GLOB_ALTDIRFUNC)
1214 ? (*pglob->gl_stat) (fullname, &st)
1215 : __stat (fullname, &st)) == 0)
1216 /* We found this file to be existing. Now tell the rest
1217 of the function to copy this name into the result. */
1218 flags |= GLOB_NOCHECK;
1221 nfound = 0;
1223 else
1225 if (pattern[0] == '\0')
1227 /* This is a special case for matching directories like in
1228 "*a/". */
1229 names = (struct globlink *) __alloca (sizeof (struct globlink));
1230 names->name = (char *) malloc (1);
1231 if (names->name == NULL)
1232 goto memory_error;
1233 names->name[0] = '\0';
1234 names->next = NULL;
1235 nfound = 1;
1236 meta = 0;
1238 else
1240 stream = ((flags & GLOB_ALTDIRFUNC)
1241 ? (*pglob->gl_opendir) (directory)
1242 : (__ptr_t) opendir (directory));
1243 if (stream == NULL)
1245 if ((errfunc != NULL && (*errfunc) (directory, errno))
1246 || (flags & GLOB_ERR))
1247 return GLOB_ABORTED;
1248 nfound = 0;
1249 meta = 0;
1251 else
1253 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1254 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1255 #if defined _AMIGA || defined VMS
1256 | FNM_CASEFOLD
1257 #endif
1259 nfound = 0;
1260 flags |= GLOB_MAGCHAR;
1262 while (1)
1264 const char *name;
1265 size_t len;
1266 struct dirent *d = ((flags & GLOB_ALTDIRFUNC)
1267 ? (*pglob->gl_readdir) (stream)
1268 : readdir ((DIR *) stream));
1269 if (d == NULL)
1270 break;
1271 if (! REAL_DIR_ENTRY (d))
1272 continue;
1274 #ifdef HAVE_D_TYPE
1275 /* If we shall match only directories use the information
1276 provided by the dirent call if possible. */
1277 if ((flags & GLOB_ONLYDIR)
1278 && d->d_type != DT_UNKNOWN && d->d_type != DT_DIR)
1279 continue;
1280 #endif
1282 name = d->d_name;
1284 if (fnmatch (pattern, name, fnm_flags) == 0)
1286 struct globlink *new = (struct globlink *)
1287 __alloca (sizeof (struct globlink));
1288 len = NAMLEN (d);
1289 new->name = (char *) malloc (len + 1);
1290 if (new->name == NULL)
1291 goto memory_error;
1292 #ifdef HAVE_MEMPCPY
1293 *((char *) mempcpy ((__ptr_t) new->name, name, len))
1294 = '\0';
1295 #else
1296 memcpy ((__ptr_t) new->name, name, len);
1297 new->name[len] = '\0';
1298 #endif
1299 new->next = names;
1300 names = new;
1301 ++nfound;
1308 if (nfound == 0 && (flags & GLOB_NOCHECK))
1310 size_t len = strlen (pattern);
1311 nfound = 1;
1312 names = (struct globlink *) __alloca (sizeof (struct globlink));
1313 names->next = NULL;
1314 names->name = (char *) malloc (len + 1);
1315 if (names->name == NULL)
1316 goto memory_error;
1317 #ifdef HAVE_MEMPCPY
1318 *((char *) mempcpy (names->name, pattern, len)) = '\0';
1319 #else
1320 memcpy (names->name, pattern, len);
1321 names->name[len] = '\0';
1322 #endif
1325 if (nfound != 0)
1327 pglob->gl_pathv
1328 = (char **) realloc (pglob->gl_pathv,
1329 (pglob->gl_pathc +
1330 ((flags & GLOB_DOOFFS) ? pglob->gl_offs : 0) +
1331 nfound + 1) *
1332 sizeof (char *));
1333 if (pglob->gl_pathv == NULL)
1334 goto memory_error;
1336 if (flags & GLOB_DOOFFS)
1337 while (pglob->gl_pathc < pglob->gl_offs)
1338 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
1340 for (; names != NULL; names = names->next)
1341 pglob->gl_pathv[pglob->gl_pathc++] = names->name;
1342 pglob->gl_pathv[pglob->gl_pathc] = NULL;
1344 pglob->gl_flags = flags;
1347 save = errno;
1348 if (stream != NULL)
1349 if (flags & GLOB_ALTDIRFUNC)
1350 (*pglob->gl_closedir) (stream);
1351 else
1352 closedir ((DIR *) stream);
1353 __set_errno (save);
1355 return nfound == 0 ? GLOB_NOMATCH : 0;
1357 memory_error:
1359 int save = errno;
1360 if (flags & GLOB_ALTDIRFUNC)
1361 (*pglob->gl_closedir) (stream);
1362 else
1363 closedir ((DIR *) stream);
1364 __set_errno (save);
1366 while (names != NULL)
1368 if (names->name != NULL)
1369 free ((__ptr_t) names->name);
1370 names = names->next;
1372 return GLOB_NOSPACE;
1375 #endif /* Not ELIDE_CODE. */