Update.
[glibc.git] / sysdeps / generic / glob.c
blob509fc1b972884c0a4910eee83a9abd291b53a914
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 # define __stat(fname, buf) __xstat (_STAT_VER, fname, buf)
257 #endif
259 #if !(defined STDC_HEADERS || defined __GNU_LIBRARY__)
260 # undef size_t
261 # define size_t unsigned int
262 #endif
264 /* Some system header files erroneously define these.
265 We want our own definitions from <fnmatch.h> to take precedence. */
266 #ifndef __GNU_LIBRARY__
267 # undef FNM_PATHNAME
268 # undef FNM_NOESCAPE
269 # undef FNM_PERIOD
270 #endif
271 #include <fnmatch.h>
273 /* Some system header files erroneously define these.
274 We want our own definitions from <glob.h> to take precedence. */
275 #ifndef __GNU_LIBRARY__
276 # undef GLOB_ERR
277 # undef GLOB_MARK
278 # undef GLOB_NOSORT
279 # undef GLOB_DOOFFS
280 # undef GLOB_NOCHECK
281 # undef GLOB_APPEND
282 # undef GLOB_NOESCAPE
283 # undef GLOB_PERIOD
284 #endif
285 #include <glob.h>
287 static
288 #if __GNUC__ - 0 >= 2
289 inline
290 #endif
291 const char *next_brace_sub __P ((const char *begin));
292 static int glob_in_dir __P ((const char *pattern, const char *directory,
293 int flags,
294 int (*errfunc) __P ((const char *, int)),
295 glob_t *pglob));
296 static int prefix_array __P ((const char *prefix, char **array, size_t n));
297 static int collated_compare __P ((const __ptr_t, const __ptr_t));
300 /* Find the end of the sub-pattern in a brace expression. We define
301 this as an inline function if the compiler permits. */
302 static
303 #if __GNUC__ - 0 >= 2
304 inline
305 #endif
306 const char *
307 next_brace_sub (begin)
308 const char *begin;
310 unsigned int depth = 0;
311 const char *cp = begin;
313 while (1)
315 if (depth == 0)
317 if (*cp != ',' && *cp != '}' && *cp != '\0')
319 if (*cp == '{')
320 ++depth;
321 ++cp;
322 continue;
325 else
327 while (*cp != '\0' && (*cp != '}' || depth > 0))
329 if (*cp == '}')
330 --depth;
331 ++cp;
333 if (*cp == '\0')
334 /* An incorrectly terminated brace expression. */
335 return NULL;
337 continue;
339 break;
342 return cp;
345 /* Do glob searching for PATTERN, placing results in PGLOB.
346 The bits defined above may be set in FLAGS.
347 If a directory cannot be opened or read and ERRFUNC is not nil,
348 it is called with the pathname that caused the error, and the
349 `errno' value from the failing call; if it returns non-zero
350 `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
351 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
352 Otherwise, `glob' returns zero. */
354 glob (pattern, flags, errfunc, pglob)
355 const char *pattern;
356 int flags;
357 int (*errfunc) __P ((const char *, int));
358 glob_t *pglob;
360 const char *filename;
361 const char *dirname;
362 size_t dirlen;
363 int status;
364 int oldcount;
366 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
368 __set_errno (EINVAL);
369 return -1;
372 if (flags & GLOB_BRACE)
374 const char *begin = strchr (pattern, '{');
375 if (begin != NULL)
377 /* Allocate working buffer large enough for our work. Note that
378 we have at least an opening and closing brace. */
379 int firstc;
380 char *alt_start;
381 const char *p;
382 const char *next;
383 const char *rest;
384 size_t rest_len;
385 #ifdef __GNUC__
386 char onealt[strlen (pattern) - 1];
387 #else
388 char *onealt = (char *) malloc (strlen (pattern) - 1);
389 if (onealt == NULL)
391 if (!(flags & GLOB_APPEND))
392 globfree (pglob);
393 return GLOB_NOSPACE;
395 #endif
397 /* We know the prefix for all sub-patterns. */
398 #ifdef HAVE_MEMPCPY
399 alt_start = mempcpy (onealt, pattern, begin - pattern);
400 #else
401 memcpy (onealt, pattern, begin - pattern);
402 alt_start = &onealt[begin - pattern];
403 #endif
405 /* Find the first sub-pattern and at the same time find the
406 rest after the closing brace. */
407 next = next_brace_sub (begin + 1);
408 if (next == NULL)
410 /* It is an illegal expression. */
411 #ifndef __GNUC__
412 free (onealt);
413 #endif
414 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
417 /* Now find the end of the whole brace expression. */
418 rest = next;
419 while (*rest != '}')
421 rest = next_brace_sub (rest + 1);
422 if (rest == NULL)
424 /* It is an illegal expression. */
425 #ifndef __GNUC__
426 free (onealt);
427 #endif
428 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
431 /* Please note that we now can be sure the brace expression
432 is well-formed. */
433 rest_len = strlen (++rest) + 1;
435 /* We have a brace expression. BEGIN points to the opening {,
436 NEXT points past the terminator of the first element, and END
437 points past the final }. We will accumulate result names from
438 recursive runs for each brace alternative in the buffer using
439 GLOB_APPEND. */
441 if (!(flags & GLOB_APPEND))
443 /* This call is to set a new vector, so clear out the
444 vector so we can append to it. */
445 pglob->gl_pathc = 0;
446 pglob->gl_pathv = NULL;
448 firstc = pglob->gl_pathc;
450 p = begin + 1;
451 while (1)
453 int result;
455 /* Construct the new glob expression. */
456 #ifdef HAVE_MEMPCPY
457 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
458 #else
459 memcpy (alt_start, p, next - p);
460 memcpy (&alt_start[next - p], rest, rest_len);
461 #endif
463 result = glob (onealt,
464 ((flags & ~(GLOB_NOCHECK|GLOB_NOMAGIC))
465 | GLOB_APPEND), errfunc, pglob);
467 /* If we got an error, return it. */
468 if (result && result != GLOB_NOMATCH)
470 #ifndef __GNUC__
471 free (onealt);
472 #endif
473 if (!(flags & GLOB_APPEND))
474 globfree (pglob);
475 return result;
478 if (*next == '}')
479 /* We saw the last entry. */
480 break;
482 p = next + 1;
483 next = next_brace_sub (p);
484 assert (next != NULL);
487 #ifndef __GNUC__
488 free (onealt);
489 #endif
491 if (pglob->gl_pathc != firstc)
492 /* We found some entries. */
493 return 0;
494 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
495 return GLOB_NOMATCH;
499 /* Find the filename. */
500 filename = strrchr (pattern, '/');
501 #if defined __MSDOS__ || defined WINDOWS32
502 /* The case of "d:pattern". Since `:' is not allowed in
503 file names, we can safely assume that wherever it
504 happens in pattern, it signals the filename part. This
505 is so we could some day support patterns like "[a-z]:foo". */
506 if (filename == NULL)
507 filename = strchr (pattern, ':');
508 #endif /* __MSDOS__ || WINDOWS32 */
509 if (filename == NULL)
511 /* This can mean two things: a simple name or "~name". The later
512 case is nothing but a notation for a directory. */
513 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
515 dirname = pattern;
516 dirlen = strlen (pattern);
518 /* Set FILENAME to NULL as a special flag. This is ugly but
519 other solutions would require much more code. We test for
520 this special case below. */
521 filename = NULL;
523 else
525 filename = pattern;
526 #ifdef _AMIGA
527 dirname = "";
528 #else
529 dirname = ".";
530 #endif
531 dirlen = 0;
534 else if (filename == pattern)
536 /* "/pattern". */
537 dirname = "/";
538 dirlen = 1;
539 ++filename;
541 else
543 char *newp;
544 dirlen = filename - pattern;
545 #if defined __MSDOS__ || defined WINDOWS32
546 if (*filename == ':'
547 || (filename > pattern + 1 && filename[-1] == ':'))
549 char *drive_spec;
551 ++dirlen;
552 drive_spec = (char *) __alloca (dirlen + 1);
553 #ifdef HAVE_MEMPCPY
554 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
555 #else
556 memcpy (drive_spec, pattern, dirlen);
557 drive_spec[dirlen] = '\0';
558 #endif
559 /* For now, disallow wildcards in the drive spec, to
560 prevent infinite recursion in glob. */
561 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
562 return GLOB_NOMATCH;
563 /* If this is "d:pattern", we need to copy `:' to DIRNAME
564 as well. If it's "d:/pattern", don't remove the slash
565 from "d:/", since "d:" and "d:/" are not the same.*/
567 #endif
568 newp = (char *) __alloca (dirlen + 1);
569 #ifdef HAVE_MEMPCPY
570 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
571 #else
572 memcpy (newp, pattern, dirlen);
573 newp[dirlen] = '\0';
574 #endif
575 dirname = newp;
576 ++filename;
578 if (filename[0] == '\0'
579 #if defined __MSDOS__ || defined WINDOWS32
580 && dirname[dirlen - 1] != ':'
581 && (dirlen < 3 || dirname[dirlen - 2] != ':'
582 || dirname[dirlen - 1] != '/')
583 #endif
584 && dirlen > 1)
585 /* "pattern/". Expand "pattern", appending slashes. */
587 int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
588 if (val == 0)
589 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
590 | (flags & GLOB_MARK));
591 return val;
595 if (!(flags & GLOB_APPEND))
597 pglob->gl_pathc = 0;
598 pglob->gl_pathv = NULL;
601 oldcount = pglob->gl_pathc;
603 #ifndef VMS
604 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
606 if (dirname[1] == '\0' || dirname[1] == '/')
608 /* Look up home directory. */
609 const char *home_dir = getenv ("HOME");
610 # ifdef _AMIGA
611 if (home_dir == NULL || home_dir[0] == '\0')
612 home_dir = "SYS:";
613 # else
614 # ifdef WINDOWS32
615 if (home_dir == NULL || home_dir[0] == '\0')
616 home_dir = "c:/users/default"; /* poor default */
617 # else
618 if (home_dir == NULL || home_dir[0] == '\0')
620 int success;
621 char *name;
622 # if defined HAVE_GETLOGIN_R || defined _LIBC
623 size_t buflen = sysconf (_SC_LOGIN_NAME_MAX) + 1;
625 if (buflen == 0)
626 /* `sysconf' does not support _SC_LOGIN_NAME_MAX. Try
627 a moderate value. */
628 buflen = 20;
629 name = (char *) __alloca (buflen);
631 success = getlogin_r (name, buflen) >= 0;
632 # else
633 success = (name = getlogin ()) != NULL;
634 # endif
635 if (success)
637 struct passwd *p;
638 # if defined HAVE_GETPWNAM_R || defined _LIBC
639 size_t pwbuflen = sysconf (_SC_GETPW_R_SIZE_MAX);
640 char *pwtmpbuf;
641 struct passwd pwbuf;
643 if (pwbuflen == -1)
644 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.
645 Try a moderate value. */
646 pwbuflen = 1024;
647 pwtmpbuf = (char *) __alloca (pwbuflen);
649 success = (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
650 >= 0);
651 # else
652 p = getpwnam (name);
653 success = p != NULL;
654 # endif
655 if (success)
656 home_dir = p->pw_dir;
659 if (home_dir == NULL || home_dir[0] == '\0')
660 if (flags & GLOB_TILDE_CHECK)
661 return GLOB_NOMATCH;
662 else
663 home_dir = "~"; /* No luck. */
664 # endif /* WINDOWS32 */
665 # endif
666 /* Now construct the full directory. */
667 if (dirname[1] == '\0')
668 dirname = home_dir;
669 else
671 char *newp;
672 size_t home_len = strlen (home_dir);
673 newp = (char *) __alloca (home_len + dirlen);
674 # ifdef HAVE_MEMPCPY
675 mempcpy (mempcpy (newp, home_dir, home_len),
676 &dirname[1], dirlen);
677 # else
678 memcpy (newp, home_dir, home_len);
679 memcpy (&newp[home_len], &dirname[1], dirlen);
680 # endif
681 dirname = newp;
684 # if !defined _AMIGA && !defined WINDOWS32
685 else
687 char *end_name = strchr (dirname, '/');
688 const char *user_name;
689 const char *home_dir;
691 if (end_name == NULL)
692 user_name = dirname + 1;
693 else
695 char *newp;
696 newp = (char *) __alloca (end_name - dirname);
697 # ifdef HAVE_MEMPCPY
698 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
699 = '\0';
700 # else
701 memcpy (newp, dirname + 1, end_name - dirname);
702 newp[end_name - dirname - 1] = '\0';
703 # endif
704 user_name = newp;
707 /* Look up specific user's home directory. */
709 struct passwd *p;
710 # if defined HAVE_GETPWNAM_R || defined _LIBC
711 size_t buflen = sysconf (_SC_GETPW_R_SIZE_MAX);
712 char *pwtmpbuf;
713 struct passwd pwbuf;
715 if (buflen == -1)
716 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
717 moderate value. */
718 buflen = 1024;
719 pwtmpbuf = (char *) __alloca (buflen);
721 if (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) >= 0)
722 home_dir = p->pw_dir;
723 else
724 home_dir = NULL;
725 # else
726 p = getpwnam (user_name);
727 if (p != NULL)
728 home_dir = p->pw_dir;
729 else
730 home_dir = NULL;
731 # endif
733 /* If we found a home directory use this. */
734 if (home_dir != NULL)
736 char *newp;
737 size_t home_len = strlen (home_dir);
738 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
739 newp = (char *) __alloca (home_len + rest_len + 1);
740 # ifdef HAVE_MEMPCPY
741 *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
742 end_name, rest_len)) = '\0';
743 # else
744 memcpy (newp, home_dir, home_len);
745 memcpy (&newp[home_len], end_name, rest_len);
746 newp[home_len + rest_len] = '\0';
747 # endif
748 dirname = newp;
750 else
751 if (flags & GLOB_TILDE_CHECK)
752 /* We have to regard it as an error if we cannot find the
753 home directory. */
754 return GLOB_NOMATCH;
756 # endif /* Not Amiga && not WINDOWS32. */
758 #endif /* Not VMS. */
760 /* Now test whether we looked for "~" or "~NAME". In this case we
761 can give the answer now. */
762 if (filename == NULL)
764 struct stat st;
766 /* Return the directory if we don't check for error or if it exists. */
767 if ((flags & GLOB_NOCHECK)
768 || (((flags & GLOB_ALTDIRFUNC)
769 ? (*pglob->gl_stat) (dirname, &st)
770 : __stat (dirname, &st)) == 0
771 && S_ISDIR (st.st_mode)))
773 pglob->gl_pathv
774 = (char **) realloc (pglob->gl_pathv,
775 (pglob->gl_pathc +
776 ((flags & GLOB_DOOFFS) ?
777 pglob->gl_offs : 0) +
778 1 + 1) *
779 sizeof (char *));
780 if (pglob->gl_pathv == NULL)
781 return GLOB_NOSPACE;
783 if (flags & GLOB_DOOFFS)
784 while (pglob->gl_pathc < pglob->gl_offs)
785 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
787 #if defined HAVE_STRDUP || defined _LIBC
788 pglob->gl_pathv[pglob->gl_pathc] = strdup (dirname);
789 #else
791 size_t len = strlen (dirname) + 1;
792 char *dircopy = malloc (len);
793 if (dircopy != NULL)
794 pglob->gl_pathv[pglob->gl_pathc] = memcpy (dircopy, dirname,
795 len);
797 #endif
798 if (pglob->gl_pathv[pglob->gl_pathc] == NULL)
800 free (pglob->gl_pathv);
801 return GLOB_NOSPACE;
803 pglob->gl_pathv[++pglob->gl_pathc] = NULL;
804 pglob->gl_flags = flags;
806 return 0;
809 /* Not found. */
810 return GLOB_NOMATCH;
813 if (__glob_pattern_p (dirname, !(flags & GLOB_NOESCAPE)))
815 /* The directory name contains metacharacters, so we
816 have to glob for the directory, and then glob for
817 the pattern in each directory found. */
818 glob_t dirs;
819 register int i;
821 status = glob (dirname,
822 ((flags & (GLOB_ERR | GLOB_NOCHECK | GLOB_NOESCAPE))
823 | GLOB_NOSORT | GLOB_ONLYDIR),
824 errfunc, &dirs);
825 if (status != 0)
826 return status;
828 /* We have successfully globbed the preceding directory name.
829 For each name we found, call glob_in_dir on it and FILENAME,
830 appending the results to PGLOB. */
831 for (i = 0; i < dirs.gl_pathc; ++i)
833 int old_pathc;
835 #ifdef SHELL
837 /* Make globbing interruptible in the bash shell. */
838 extern int interrupt_state;
840 if (interrupt_state)
842 globfree (&dirs);
843 globfree (&files);
844 return GLOB_ABORTED;
847 #endif /* SHELL. */
849 old_pathc = pglob->gl_pathc;
850 status = glob_in_dir (filename, dirs.gl_pathv[i],
851 ((flags | GLOB_APPEND)
852 & ~(GLOB_NOCHECK | GLOB_ERR)),
853 errfunc, pglob);
854 if (status == GLOB_NOMATCH)
855 /* No matches in this directory. Try the next. */
856 continue;
858 if (status != 0)
860 globfree (&dirs);
861 globfree (pglob);
862 return status;
865 /* Stick the directory on the front of each name. */
866 if (prefix_array (dirs.gl_pathv[i],
867 &pglob->gl_pathv[old_pathc],
868 pglob->gl_pathc - old_pathc))
870 globfree (&dirs);
871 globfree (pglob);
872 return GLOB_NOSPACE;
876 flags |= GLOB_MAGCHAR;
878 /* We have ignored the GLOB_NOCHECK flag in the `glob_in_dir' calls.
879 But if we have not found any matching entry and thie GLOB_NOCHECK
880 flag was set we must return the list consisting of the disrectory
881 names followed by the filename. */
882 if (pglob->gl_pathc == oldcount)
883 /* No matches. */
884 if (flags & GLOB_NOCHECK)
886 size_t filename_len = strlen (filename) + 1;
887 char **new_pathv;
888 struct stat st;
890 /* This is an pessimistic guess about the size. */
891 pglob->gl_pathv
892 = (char **) realloc (pglob->gl_pathv,
893 (pglob->gl_pathc +
894 ((flags & GLOB_DOOFFS) ?
895 pglob->gl_offs : 0) +
896 dirs.gl_pathc + 1) *
897 sizeof (char *));
898 if (pglob->gl_pathv == NULL)
900 globfree (&dirs);
901 return GLOB_NOSPACE;
904 if (flags & GLOB_DOOFFS)
905 while (pglob->gl_pathc < pglob->gl_offs)
906 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
908 for (i = 0; i < dirs.gl_pathc; ++i)
910 const char *dir = dirs.gl_pathv[i];
911 size_t dir_len = strlen (dir);
913 /* First check whether this really is a directory. */
914 if (((flags & GLOB_ALTDIRFUNC)
915 ? (*pglob->gl_stat) (dir, &st) : __stat (dir, &st)) != 0
916 || !S_ISDIR (st.st_mode))
917 /* No directory, ignore this entry. */
918 continue;
920 pglob->gl_pathv[pglob->gl_pathc] = malloc (dir_len + 1
921 + filename_len);
922 if (pglob->gl_pathv[pglob->gl_pathc] == NULL)
924 globfree (&dirs);
925 globfree (pglob);
926 return GLOB_NOSPACE;
929 #ifdef HAVE_MEMPCPY
930 mempcpy (mempcpy (mempcpy (pglob->gl_pathv[pglob->gl_pathc],
931 dir, dir_len),
932 "/", 1),
933 filename, filename_len);
934 #else
935 memcpy (pglob->gl_pathv[pglob->gl_pathc], dir, dir_len);
936 pglob->gl_pathv[pglob->gl_pathc][dir_len] = '/';
937 memcpy (&pglob->gl_pathv[pglob->gl_pathc][dir_len + 1],
938 filename, filename_len);
939 #endif
940 ++pglob->gl_pathc;
943 pglob->gl_pathv[pglob->gl_pathc] = NULL;
944 pglob->gl_flags = flags;
946 /* Now we know how large the gl_pathv vector must be. */
947 new_pathv = (char **) realloc (pglob->gl_pathv,
948 ((pglob->gl_pathc + 1)
949 * sizeof (char *)));
950 if (new_pathv != NULL)
951 pglob->gl_pathv = new_pathv;
953 else
954 return GLOB_NOMATCH;
956 globfree (&dirs);
958 else
960 status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
961 if (status != 0)
962 return status;
964 if (dirlen > 0)
966 /* Stick the directory on the front of each name. */
967 int ignore = oldcount;
969 if ((flags & GLOB_DOOFFS) && ignore < pglob->gl_offs)
970 ignore = pglob->gl_offs;
972 if (prefix_array (dirname,
973 &pglob->gl_pathv[ignore],
974 pglob->gl_pathc - ignore))
976 globfree (pglob);
977 return GLOB_NOSPACE;
982 if (flags & GLOB_MARK)
984 /* Append slashes to directory names. */
985 int i;
986 struct stat st;
987 for (i = oldcount; i < pglob->gl_pathc; ++i)
988 if (((flags & GLOB_ALTDIRFUNC)
989 ? (*pglob->gl_stat) (pglob->gl_pathv[i], &st)
990 : __stat (pglob->gl_pathv[i], &st)) == 0
991 && S_ISDIR (st.st_mode))
993 size_t len = strlen (pglob->gl_pathv[i]) + 2;
994 char *new = realloc (pglob->gl_pathv[i], len);
995 if (new == NULL)
997 globfree (pglob);
998 return GLOB_NOSPACE;
1000 strcpy (&new[len - 2], "/");
1001 pglob->gl_pathv[i] = new;
1005 if (!(flags & GLOB_NOSORT))
1007 /* Sort the vector. */
1008 int non_sort = oldcount;
1010 if ((flags & GLOB_DOOFFS) && pglob->gl_offs > oldcount)
1011 non_sort = pglob->gl_offs;
1013 qsort ((__ptr_t) &pglob->gl_pathv[non_sort],
1014 pglob->gl_pathc - non_sort,
1015 sizeof (char *), collated_compare);
1018 return 0;
1022 /* Free storage allocated in PGLOB by a previous `glob' call. */
1023 void
1024 globfree (pglob)
1025 register glob_t *pglob;
1027 if (pglob->gl_pathv != NULL)
1029 register int i;
1030 for (i = 0; i < pglob->gl_pathc; ++i)
1031 if (pglob->gl_pathv[i] != NULL)
1032 free ((__ptr_t) pglob->gl_pathv[i]);
1033 free ((__ptr_t) pglob->gl_pathv);
1038 /* Do a collated comparison of A and B. */
1039 static int
1040 collated_compare (a, b)
1041 const __ptr_t a;
1042 const __ptr_t b;
1044 const char *const s1 = *(const char *const * const) a;
1045 const char *const s2 = *(const char *const * const) b;
1047 if (s1 == s2)
1048 return 0;
1049 if (s1 == NULL)
1050 return 1;
1051 if (s2 == NULL)
1052 return -1;
1053 return strcoll (s1, s2);
1057 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1058 elements in place. Return nonzero if out of memory, zero if successful.
1059 A slash is inserted between DIRNAME and each elt of ARRAY,
1060 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1061 static int
1062 prefix_array (dirname, array, n)
1063 const char *dirname;
1064 char **array;
1065 size_t n;
1067 register size_t i;
1068 size_t dirlen = strlen (dirname);
1069 #if defined __MSDOS__ || defined WINDOWS32
1070 int sep_char = '/';
1071 # define DIRSEP_CHAR sep_char
1072 #else
1073 # define DIRSEP_CHAR '/'
1074 #endif
1076 if (dirlen == 1 && dirname[0] == '/')
1077 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1078 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1079 dirlen = 0;
1080 #if defined __MSDOS__ || defined WINDOWS32
1081 else if (dirlen > 1)
1083 if (dirname[dirlen - 1] == '/')
1084 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1085 --dirlen;
1086 else if (dirname[dirlen - 1] == ':')
1088 /* DIRNAME is "d:". Use `:' instead of `/'. */
1089 --dirlen;
1090 sep_char = ':';
1093 #endif
1095 for (i = 0; i < n; ++i)
1097 size_t eltlen = strlen (array[i]) + 1;
1098 char *new = (char *) malloc (dirlen + 1 + eltlen);
1099 if (new == NULL)
1101 while (i > 0)
1102 free ((__ptr_t) array[--i]);
1103 return 1;
1106 #ifdef HAVE_MEMPCPY
1108 char *endp = (char *) mempcpy (new, dirname, dirlen);
1109 *endp++ = DIRSEP_CHAR;
1110 mempcpy (endp, array[i], eltlen);
1112 #else
1113 memcpy (new, dirname, dirlen);
1114 new[dirlen] = DIRSEP_CHAR;
1115 memcpy (&new[dirlen + 1], array[i], eltlen);
1116 #endif
1117 free ((__ptr_t) array[i]);
1118 array[i] = new;
1121 return 0;
1125 /* We must not compile this function twice. */
1126 #if !defined _LIBC || !defined NO_GLOB_PATTERN_P
1127 /* Return nonzero if PATTERN contains any metacharacters.
1128 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
1130 __glob_pattern_p (pattern, quote)
1131 const char *pattern;
1132 int quote;
1134 register const char *p;
1135 int open = 0;
1137 for (p = pattern; *p != '\0'; ++p)
1138 switch (*p)
1140 case '?':
1141 case '*':
1142 return 1;
1144 case '\\':
1145 if (quote && p[1] != '\0')
1146 ++p;
1147 break;
1149 case '[':
1150 open = 1;
1151 break;
1153 case ']':
1154 if (open)
1155 return 1;
1156 break;
1159 return 0;
1161 # ifdef _LIBC
1162 weak_alias (__glob_pattern_p, glob_pattern_p)
1163 # endif
1164 #endif
1167 /* Like `glob', but PATTERN is a final pathname component,
1168 and matches are searched for in DIRECTORY.
1169 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1170 The GLOB_APPEND flag is assumed to be set (always appends). */
1171 static int
1172 glob_in_dir (pattern, directory, flags, errfunc, pglob)
1173 const char *pattern;
1174 const char *directory;
1175 int flags;
1176 int (*errfunc) __P ((const char *, int));
1177 glob_t *pglob;
1179 __ptr_t stream = NULL;
1181 struct globlink
1183 struct globlink *next;
1184 char *name;
1186 struct globlink *names = NULL;
1187 size_t nfound;
1188 int meta;
1189 int save;
1191 meta = __glob_pattern_p (pattern, !(flags & GLOB_NOESCAPE));
1192 if (meta == 0)
1194 if (flags & (GLOB_NOCHECK|GLOB_NOMAGIC))
1195 /* We need not do any tests. The PATTERN contains no meta
1196 characters and we must not return an error therefore the
1197 result will always contain exactly one name. */
1198 flags |= GLOB_NOCHECK;
1199 else
1201 /* Since we use the normal file functions we can also use stat()
1202 to verify the file is there. */
1203 struct stat st;
1204 size_t patlen = strlen (pattern);
1205 size_t dirlen = strlen (directory);
1206 char *fullname = (char *) __alloca (dirlen + 1 + patlen + 1);
1208 # ifdef HAVE_MEMPCPY
1209 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1210 "/", 1),
1211 pattern, patlen + 1);
1212 # else
1213 memcpy (fullname, directory, dirlen);
1214 fullname[dirlen] = '/';
1215 memcpy (&fullname[dirlen + 1], pattern, patlen + 1);
1216 # endif
1217 if (((flags & GLOB_ALTDIRFUNC)
1218 ? (*pglob->gl_stat) (fullname, &st)
1219 : __stat (fullname, &st)) == 0)
1220 /* We found this file to be existing. Now tell the rest
1221 of the function to copy this name into the result. */
1222 flags |= GLOB_NOCHECK;
1225 nfound = 0;
1227 else
1229 if (pattern[0] == '\0')
1231 /* This is a special case for matching directories like in
1232 "*a/". */
1233 names = (struct globlink *) __alloca (sizeof (struct globlink));
1234 names->name = (char *) malloc (1);
1235 if (names->name == NULL)
1236 goto memory_error;
1237 names->name[0] = '\0';
1238 names->next = NULL;
1239 nfound = 1;
1240 meta = 0;
1242 else
1244 stream = ((flags & GLOB_ALTDIRFUNC)
1245 ? (*pglob->gl_opendir) (directory)
1246 : (__ptr_t) opendir (directory));
1247 if (stream == NULL)
1249 if ((errfunc != NULL && (*errfunc) (directory, errno))
1250 || (flags & GLOB_ERR))
1251 return GLOB_ABORTED;
1252 nfound = 0;
1253 meta = 0;
1255 else
1257 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1258 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1259 #if defined _AMIGA || defined VMS
1260 | FNM_CASEFOLD
1261 #endif
1263 nfound = 0;
1264 flags |= GLOB_MAGCHAR;
1266 while (1)
1268 const char *name;
1269 size_t len;
1270 struct dirent *d = ((flags & GLOB_ALTDIRFUNC)
1271 ? (*pglob->gl_readdir) (stream)
1272 : readdir ((DIR *) stream));
1273 if (d == NULL)
1274 break;
1275 if (! REAL_DIR_ENTRY (d))
1276 continue;
1278 #ifdef HAVE_D_TYPE
1279 /* If we shall match only directories use the information
1280 provided by the dirent call if possible. */
1281 if ((flags & GLOB_ONLYDIR)
1282 && d->d_type != DT_UNKNOWN && d->d_type != DT_DIR)
1283 continue;
1284 #endif
1286 name = d->d_name;
1288 if (fnmatch (pattern, name, fnm_flags) == 0)
1290 struct globlink *new = (struct globlink *)
1291 __alloca (sizeof (struct globlink));
1292 len = NAMLEN (d);
1293 new->name = (char *) malloc (len + 1);
1294 if (new->name == NULL)
1295 goto memory_error;
1296 #ifdef HAVE_MEMPCPY
1297 *((char *) mempcpy ((__ptr_t) new->name, name, len))
1298 = '\0';
1299 #else
1300 memcpy ((__ptr_t) new->name, name, len);
1301 new->name[len] = '\0';
1302 #endif
1303 new->next = names;
1304 names = new;
1305 ++nfound;
1312 if (nfound == 0 && (flags & GLOB_NOCHECK))
1314 size_t len = strlen (pattern);
1315 nfound = 1;
1316 names = (struct globlink *) __alloca (sizeof (struct globlink));
1317 names->next = NULL;
1318 names->name = (char *) malloc (len + 1);
1319 if (names->name == NULL)
1320 goto memory_error;
1321 #ifdef HAVE_MEMPCPY
1322 *((char *) mempcpy (names->name, pattern, len)) = '\0';
1323 #else
1324 memcpy (names->name, pattern, len);
1325 names->name[len] = '\0';
1326 #endif
1329 if (nfound != 0)
1331 pglob->gl_pathv
1332 = (char **) realloc (pglob->gl_pathv,
1333 (pglob->gl_pathc +
1334 ((flags & GLOB_DOOFFS) ? pglob->gl_offs : 0) +
1335 nfound + 1) *
1336 sizeof (char *));
1337 if (pglob->gl_pathv == NULL)
1338 goto memory_error;
1340 if (flags & GLOB_DOOFFS)
1341 while (pglob->gl_pathc < pglob->gl_offs)
1342 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
1344 for (; names != NULL; names = names->next)
1345 pglob->gl_pathv[pglob->gl_pathc++] = names->name;
1346 pglob->gl_pathv[pglob->gl_pathc] = NULL;
1348 pglob->gl_flags = flags;
1351 save = errno;
1352 if (stream != NULL)
1353 if (flags & GLOB_ALTDIRFUNC)
1354 (*pglob->gl_closedir) (stream);
1355 else
1356 closedir ((DIR *) stream);
1357 __set_errno (save);
1359 return nfound == 0 ? GLOB_NOMATCH : 0;
1361 memory_error:
1363 int save = errno;
1364 if (flags & GLOB_ALTDIRFUNC)
1365 (*pglob->gl_closedir) (stream);
1366 else
1367 closedir ((DIR *) stream);
1368 __set_errno (save);
1370 while (names != NULL)
1372 if (names->name != NULL)
1373 free ((__ptr_t) names->name);
1374 names = names->next;
1376 return GLOB_NOSPACE;
1379 #endif /* Not ELIDE_CODE. */