Update.
[glibc.git] / sysdeps / generic / glob.c
blobc41d03f8b2ca162b15cc8aa6b0001f9f2b2e7413
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 # ifndef __stat
257 # define __stat(fname, buf) __xstat (_STAT_VER, fname, buf)
258 # endif
259 #endif
261 #if !(defined STDC_HEADERS || defined __GNU_LIBRARY__)
262 # undef size_t
263 # define size_t unsigned int
264 #endif
266 /* Some system header files erroneously define these.
267 We want our own definitions from <fnmatch.h> to take precedence. */
268 #ifndef __GNU_LIBRARY__
269 # undef FNM_PATHNAME
270 # undef FNM_NOESCAPE
271 # undef FNM_PERIOD
272 #endif
273 #include <fnmatch.h>
275 /* Some system header files erroneously define these.
276 We want our own definitions from <glob.h> to take precedence. */
277 #ifndef __GNU_LIBRARY__
278 # undef GLOB_ERR
279 # undef GLOB_MARK
280 # undef GLOB_NOSORT
281 # undef GLOB_DOOFFS
282 # undef GLOB_NOCHECK
283 # undef GLOB_APPEND
284 # undef GLOB_NOESCAPE
285 # undef GLOB_PERIOD
286 #endif
287 #include <glob.h>
289 static
290 #if __GNUC__ - 0 >= 2
291 inline
292 #endif
293 const char *next_brace_sub __P ((const char *begin));
294 static int glob_in_dir __P ((const char *pattern, const char *directory,
295 int flags,
296 int (*errfunc) (const char *, int),
297 glob_t *pglob));
298 static int prefix_array __P ((const char *prefix, char **array, size_t n));
299 static int collated_compare __P ((const __ptr_t, const __ptr_t));
302 /* Find the end of the sub-pattern in a brace expression. We define
303 this as an inline function if the compiler permits. */
304 static
305 #if __GNUC__ - 0 >= 2
306 inline
307 #endif
308 const char *
309 next_brace_sub (begin)
310 const char *begin;
312 unsigned int depth = 0;
313 const char *cp = begin;
315 while (1)
317 if (depth == 0)
319 if (*cp != ',' && *cp != '}' && *cp != '\0')
321 if (*cp == '{')
322 ++depth;
323 ++cp;
324 continue;
327 else
329 while (*cp != '\0' && (*cp != '}' || depth > 0))
331 if (*cp == '}')
332 --depth;
333 ++cp;
335 if (*cp == '\0')
336 /* An incorrectly terminated brace expression. */
337 return NULL;
339 continue;
341 break;
344 return cp;
347 /* Do glob searching for PATTERN, placing results in PGLOB.
348 The bits defined above may be set in FLAGS.
349 If a directory cannot be opened or read and ERRFUNC is not nil,
350 it is called with the pathname that caused the error, and the
351 `errno' value from the failing call; if it returns non-zero
352 `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
353 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
354 Otherwise, `glob' returns zero. */
356 glob (pattern, flags, errfunc, pglob)
357 const char *pattern;
358 int flags;
359 int (*errfunc) __P ((const char *, int));
360 glob_t *pglob;
362 const char *filename;
363 const char *dirname;
364 size_t dirlen;
365 int status;
366 int oldcount;
368 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
370 __set_errno (EINVAL);
371 return -1;
374 if (flags & GLOB_BRACE)
376 const char *begin = strchr (pattern, '{');
377 if (begin != NULL)
379 /* Allocate working buffer large enough for our work. Note that
380 we have at least an opening and closing brace. */
381 int firstc;
382 char *alt_start;
383 const char *p;
384 const char *next;
385 const char *rest;
386 size_t rest_len;
387 #ifdef __GNUC__
388 char onealt[strlen (pattern) - 1];
389 #else
390 char *onealt = (char *) malloc (strlen (pattern) - 1);
391 if (onealt == NULL)
393 if (!(flags & GLOB_APPEND))
394 globfree (pglob);
395 return GLOB_NOSPACE;
397 #endif
399 /* We know the prefix for all sub-patterns. */
400 #ifdef HAVE_MEMPCPY
401 alt_start = mempcpy (onealt, pattern, begin - pattern);
402 #else
403 memcpy (onealt, pattern, begin - pattern);
404 alt_start = &onealt[begin - pattern];
405 #endif
407 /* Find the first sub-pattern and at the same time find the
408 rest after the closing brace. */
409 next = next_brace_sub (begin + 1);
410 if (next == NULL)
412 /* It is an illegal expression. */
413 #ifndef __GNUC__
414 free (onealt);
415 #endif
416 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
419 /* Now find the end of the whole brace expression. */
420 rest = next;
421 while (*rest != '}')
423 rest = next_brace_sub (rest + 1);
424 if (rest == NULL)
426 /* It is an illegal expression. */
427 #ifndef __GNUC__
428 free (onealt);
429 #endif
430 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
433 /* Please note that we now can be sure the brace expression
434 is well-formed. */
435 rest_len = strlen (++rest) + 1;
437 /* We have a brace expression. BEGIN points to the opening {,
438 NEXT points past the terminator of the first element, and END
439 points past the final }. We will accumulate result names from
440 recursive runs for each brace alternative in the buffer using
441 GLOB_APPEND. */
443 if (!(flags & GLOB_APPEND))
445 /* This call is to set a new vector, so clear out the
446 vector so we can append to it. */
447 pglob->gl_pathc = 0;
448 pglob->gl_pathv = NULL;
450 firstc = pglob->gl_pathc;
452 p = begin + 1;
453 while (1)
455 int result;
457 /* Construct the new glob expression. */
458 #ifdef HAVE_MEMPCPY
459 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
460 #else
461 memcpy (alt_start, p, next - p);
462 memcpy (&alt_start[next - p], rest, rest_len);
463 #endif
465 result = glob (onealt,
466 ((flags & ~(GLOB_NOCHECK|GLOB_NOMAGIC))
467 | GLOB_APPEND), errfunc, pglob);
469 /* If we got an error, return it. */
470 if (result && result != GLOB_NOMATCH)
472 #ifndef __GNUC__
473 free (onealt);
474 #endif
475 if (!(flags & GLOB_APPEND))
476 globfree (pglob);
477 return result;
480 if (*next == '}')
481 /* We saw the last entry. */
482 break;
484 p = next + 1;
485 next = next_brace_sub (p);
486 assert (next != NULL);
489 #ifndef __GNUC__
490 free (onealt);
491 #endif
493 if (pglob->gl_pathc != firstc)
494 /* We found some entries. */
495 return 0;
496 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
497 return GLOB_NOMATCH;
501 /* Find the filename. */
502 filename = strrchr (pattern, '/');
503 #if defined __MSDOS__ || defined WINDOWS32
504 /* The case of "d:pattern". Since `:' is not allowed in
505 file names, we can safely assume that wherever it
506 happens in pattern, it signals the filename part. This
507 is so we could some day support patterns like "[a-z]:foo". */
508 if (filename == NULL)
509 filename = strchr (pattern, ':');
510 #endif /* __MSDOS__ || WINDOWS32 */
511 if (filename == NULL)
513 /* This can mean two things: a simple name or "~name". The later
514 case is nothing but a notation for a directory. */
515 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
517 dirname = pattern;
518 dirlen = strlen (pattern);
520 /* Set FILENAME to NULL as a special flag. This is ugly but
521 other solutions would require much more code. We test for
522 this special case below. */
523 filename = NULL;
525 else
527 filename = pattern;
528 #ifdef _AMIGA
529 dirname = "";
530 #else
531 dirname = ".";
532 #endif
533 dirlen = 0;
536 else if (filename == pattern)
538 /* "/pattern". */
539 dirname = "/";
540 dirlen = 1;
541 ++filename;
543 else
545 char *newp;
546 dirlen = filename - pattern;
547 #if defined __MSDOS__ || defined WINDOWS32
548 if (*filename == ':'
549 || (filename > pattern + 1 && filename[-1] == ':'))
551 char *drive_spec;
553 ++dirlen;
554 drive_spec = (char *) __alloca (dirlen + 1);
555 #ifdef HAVE_MEMPCPY
556 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
557 #else
558 memcpy (drive_spec, pattern, dirlen);
559 drive_spec[dirlen] = '\0';
560 #endif
561 /* For now, disallow wildcards in the drive spec, to
562 prevent infinite recursion in glob. */
563 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
564 return GLOB_NOMATCH;
565 /* If this is "d:pattern", we need to copy `:' to DIRNAME
566 as well. If it's "d:/pattern", don't remove the slash
567 from "d:/", since "d:" and "d:/" are not the same.*/
569 #endif
570 newp = (char *) __alloca (dirlen + 1);
571 #ifdef HAVE_MEMPCPY
572 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
573 #else
574 memcpy (newp, pattern, dirlen);
575 newp[dirlen] = '\0';
576 #endif
577 dirname = newp;
578 ++filename;
580 if (filename[0] == '\0'
581 #if defined __MSDOS__ || defined WINDOWS32
582 && dirname[dirlen - 1] != ':'
583 && (dirlen < 3 || dirname[dirlen - 2] != ':'
584 || dirname[dirlen - 1] != '/')
585 #endif
586 && dirlen > 1)
587 /* "pattern/". Expand "pattern", appending slashes. */
589 int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
590 if (val == 0)
591 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
592 | (flags & GLOB_MARK));
593 return val;
597 if (!(flags & GLOB_APPEND))
599 pglob->gl_pathc = 0;
600 pglob->gl_pathv = NULL;
603 oldcount = pglob->gl_pathc;
605 #ifndef VMS
606 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
608 if (dirname[1] == '\0' || dirname[1] == '/')
610 /* Look up home directory. */
611 const char *home_dir = getenv ("HOME");
612 # ifdef _AMIGA
613 if (home_dir == NULL || home_dir[0] == '\0')
614 home_dir = "SYS:";
615 # else
616 # ifdef WINDOWS32
617 if (home_dir == NULL || home_dir[0] == '\0')
618 home_dir = "c:/users/default"; /* poor default */
619 # else
620 if (home_dir == NULL || home_dir[0] == '\0')
622 int success;
623 char *name;
624 # if defined HAVE_GETLOGIN_R || defined _LIBC
625 size_t buflen = sysconf (_SC_LOGIN_NAME_MAX) + 1;
627 if (buflen == 0)
628 /* `sysconf' does not support _SC_LOGIN_NAME_MAX. Try
629 a moderate value. */
630 buflen = 20;
631 name = (char *) __alloca (buflen);
633 success = getlogin_r (name, buflen) >= 0;
634 # else
635 success = (name = getlogin ()) != NULL;
636 # endif
637 if (success)
639 struct passwd *p;
640 # if defined HAVE_GETPWNAM_R || defined _LIBC
641 size_t pwbuflen = sysconf (_SC_GETPW_R_SIZE_MAX);
642 char *pwtmpbuf;
643 struct passwd pwbuf;
645 if (pwbuflen == -1)
646 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.
647 Try a moderate value. */
648 pwbuflen = 1024;
649 pwtmpbuf = (char *) __alloca (pwbuflen);
651 success = (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
652 >= 0);
653 # else
654 p = getpwnam (name);
655 success = p != NULL;
656 # endif
657 if (success)
658 home_dir = p->pw_dir;
661 if (home_dir == NULL || home_dir[0] == '\0')
662 if (flags & GLOB_TILDE_CHECK)
663 return GLOB_NOMATCH;
664 else
665 home_dir = "~"; /* No luck. */
666 # endif /* WINDOWS32 */
667 # endif
668 /* Now construct the full directory. */
669 if (dirname[1] == '\0')
670 dirname = home_dir;
671 else
673 char *newp;
674 size_t home_len = strlen (home_dir);
675 newp = (char *) __alloca (home_len + dirlen);
676 # ifdef HAVE_MEMPCPY
677 mempcpy (mempcpy (newp, home_dir, home_len),
678 &dirname[1], dirlen);
679 # else
680 memcpy (newp, home_dir, home_len);
681 memcpy (&newp[home_len], &dirname[1], dirlen);
682 # endif
683 dirname = newp;
686 # if !defined _AMIGA && !defined WINDOWS32
687 else
689 char *end_name = strchr (dirname, '/');
690 const char *user_name;
691 const char *home_dir;
693 if (end_name == NULL)
694 user_name = dirname + 1;
695 else
697 char *newp;
698 newp = (char *) __alloca (end_name - dirname);
699 # ifdef HAVE_MEMPCPY
700 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
701 = '\0';
702 # else
703 memcpy (newp, dirname + 1, end_name - dirname);
704 newp[end_name - dirname - 1] = '\0';
705 # endif
706 user_name = newp;
709 /* Look up specific user's home directory. */
711 struct passwd *p;
712 # if defined HAVE_GETPWNAM_R || defined _LIBC
713 size_t buflen = sysconf (_SC_GETPW_R_SIZE_MAX);
714 char *pwtmpbuf;
715 struct passwd pwbuf;
717 if (buflen == -1)
718 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
719 moderate value. */
720 buflen = 1024;
721 pwtmpbuf = (char *) __alloca (buflen);
723 if (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) >= 0)
724 home_dir = p->pw_dir;
725 else
726 home_dir = NULL;
727 # else
728 p = getpwnam (user_name);
729 if (p != NULL)
730 home_dir = p->pw_dir;
731 else
732 home_dir = NULL;
733 # endif
735 /* If we found a home directory use this. */
736 if (home_dir != NULL)
738 char *newp;
739 size_t home_len = strlen (home_dir);
740 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
741 newp = (char *) __alloca (home_len + rest_len + 1);
742 # ifdef HAVE_MEMPCPY
743 *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
744 end_name, rest_len)) = '\0';
745 # else
746 memcpy (newp, home_dir, home_len);
747 memcpy (&newp[home_len], end_name, rest_len);
748 newp[home_len + rest_len] = '\0';
749 # endif
750 dirname = newp;
752 else
753 if (flags & GLOB_TILDE_CHECK)
754 /* We have to regard it as an error if we cannot find the
755 home directory. */
756 return GLOB_NOMATCH;
758 # endif /* Not Amiga && not WINDOWS32. */
760 #endif /* Not VMS. */
762 /* Now test whether we looked for "~" or "~NAME". In this case we
763 can give the answer now. */
764 if (filename == NULL)
766 struct stat st;
768 /* Return the directory if we don't check for error or if it exists. */
769 if ((flags & GLOB_NOCHECK)
770 || (((flags & GLOB_ALTDIRFUNC)
771 ? (*pglob->gl_stat) (dirname, &st)
772 : __stat (dirname, &st)) == 0
773 && S_ISDIR (st.st_mode)))
775 pglob->gl_pathv
776 = (char **) realloc (pglob->gl_pathv,
777 (pglob->gl_pathc +
778 ((flags & GLOB_DOOFFS) ?
779 pglob->gl_offs : 0) +
780 1 + 1) *
781 sizeof (char *));
782 if (pglob->gl_pathv == NULL)
783 return GLOB_NOSPACE;
785 if (flags & GLOB_DOOFFS)
786 while (pglob->gl_pathc < pglob->gl_offs)
787 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
789 #if defined HAVE_STRDUP || defined _LIBC
790 pglob->gl_pathv[pglob->gl_pathc] = strdup (dirname);
791 #else
793 size_t len = strlen (dirname) + 1;
794 char *dircopy = malloc (len);
795 if (dircopy != NULL)
796 pglob->gl_pathv[pglob->gl_pathc] = memcpy (dircopy, dirname,
797 len);
799 #endif
800 if (pglob->gl_pathv[pglob->gl_pathc] == NULL)
802 free (pglob->gl_pathv);
803 return GLOB_NOSPACE;
805 pglob->gl_pathv[++pglob->gl_pathc] = NULL;
806 pglob->gl_flags = flags;
808 return 0;
811 /* Not found. */
812 return GLOB_NOMATCH;
815 if (__glob_pattern_p (dirname, !(flags & GLOB_NOESCAPE)))
817 /* The directory name contains metacharacters, so we
818 have to glob for the directory, and then glob for
819 the pattern in each directory found. */
820 glob_t dirs;
821 register int i;
823 status = glob (dirname,
824 ((flags & (GLOB_ERR | GLOB_NOCHECK | GLOB_NOESCAPE))
825 | GLOB_NOSORT | GLOB_ONLYDIR),
826 errfunc, &dirs);
827 if (status != 0)
828 return status;
830 /* We have successfully globbed the preceding directory name.
831 For each name we found, call glob_in_dir on it and FILENAME,
832 appending the results to PGLOB. */
833 for (i = 0; i < dirs.gl_pathc; ++i)
835 int old_pathc;
837 #ifdef SHELL
839 /* Make globbing interruptible in the bash shell. */
840 extern int interrupt_state;
842 if (interrupt_state)
844 globfree (&dirs);
845 globfree (&files);
846 return GLOB_ABORTED;
849 #endif /* SHELL. */
851 old_pathc = pglob->gl_pathc;
852 status = glob_in_dir (filename, dirs.gl_pathv[i],
853 ((flags | GLOB_APPEND)
854 & ~(GLOB_NOCHECK | GLOB_ERR)),
855 errfunc, pglob);
856 if (status == GLOB_NOMATCH)
857 /* No matches in this directory. Try the next. */
858 continue;
860 if (status != 0)
862 globfree (&dirs);
863 globfree (pglob);
864 return status;
867 /* Stick the directory on the front of each name. */
868 if (prefix_array (dirs.gl_pathv[i],
869 &pglob->gl_pathv[old_pathc],
870 pglob->gl_pathc - old_pathc))
872 globfree (&dirs);
873 globfree (pglob);
874 return GLOB_NOSPACE;
878 flags |= GLOB_MAGCHAR;
880 /* We have ignored the GLOB_NOCHECK flag in the `glob_in_dir' calls.
881 But if we have not found any matching entry and thie GLOB_NOCHECK
882 flag was set we must return the list consisting of the disrectory
883 names followed by the filename. */
884 if (pglob->gl_pathc == oldcount)
885 /* No matches. */
886 if (flags & GLOB_NOCHECK)
888 size_t filename_len = strlen (filename) + 1;
889 char **new_pathv;
890 struct stat st;
892 /* This is an pessimistic guess about the size. */
893 pglob->gl_pathv
894 = (char **) realloc (pglob->gl_pathv,
895 (pglob->gl_pathc +
896 ((flags & GLOB_DOOFFS) ?
897 pglob->gl_offs : 0) +
898 dirs.gl_pathc + 1) *
899 sizeof (char *));
900 if (pglob->gl_pathv == NULL)
902 globfree (&dirs);
903 return GLOB_NOSPACE;
906 if (flags & GLOB_DOOFFS)
907 while (pglob->gl_pathc < pglob->gl_offs)
908 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
910 for (i = 0; i < dirs.gl_pathc; ++i)
912 const char *dir = dirs.gl_pathv[i];
913 size_t dir_len = strlen (dir);
915 /* First check whether this really is a directory. */
916 if (((flags & GLOB_ALTDIRFUNC)
917 ? (*pglob->gl_stat) (dir, &st) : __stat (dir, &st)) != 0
918 || !S_ISDIR (st.st_mode))
919 /* No directory, ignore this entry. */
920 continue;
922 pglob->gl_pathv[pglob->gl_pathc] = malloc (dir_len + 1
923 + filename_len);
924 if (pglob->gl_pathv[pglob->gl_pathc] == NULL)
926 globfree (&dirs);
927 globfree (pglob);
928 return GLOB_NOSPACE;
931 #ifdef HAVE_MEMPCPY
932 mempcpy (mempcpy (mempcpy (pglob->gl_pathv[pglob->gl_pathc],
933 dir, dir_len),
934 "/", 1),
935 filename, filename_len);
936 #else
937 memcpy (pglob->gl_pathv[pglob->gl_pathc], dir, dir_len);
938 pglob->gl_pathv[pglob->gl_pathc][dir_len] = '/';
939 memcpy (&pglob->gl_pathv[pglob->gl_pathc][dir_len + 1],
940 filename, filename_len);
941 #endif
942 ++pglob->gl_pathc;
945 pglob->gl_pathv[pglob->gl_pathc] = NULL;
946 pglob->gl_flags = flags;
948 /* Now we know how large the gl_pathv vector must be. */
949 new_pathv = (char **) realloc (pglob->gl_pathv,
950 ((pglob->gl_pathc + 1)
951 * sizeof (char *)));
952 if (new_pathv != NULL)
953 pglob->gl_pathv = new_pathv;
955 else
956 return GLOB_NOMATCH;
958 globfree (&dirs);
960 else
962 status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
963 if (status != 0)
964 return status;
966 if (dirlen > 0)
968 /* Stick the directory on the front of each name. */
969 int ignore = oldcount;
971 if ((flags & GLOB_DOOFFS) && ignore < pglob->gl_offs)
972 ignore = pglob->gl_offs;
974 if (prefix_array (dirname,
975 &pglob->gl_pathv[ignore],
976 pglob->gl_pathc - ignore))
978 globfree (pglob);
979 return GLOB_NOSPACE;
984 if (flags & GLOB_MARK)
986 /* Append slashes to directory names. */
987 int i;
988 struct stat st;
989 for (i = oldcount; i < pglob->gl_pathc; ++i)
990 if (((flags & GLOB_ALTDIRFUNC)
991 ? (*pglob->gl_stat) (pglob->gl_pathv[i], &st)
992 : __stat (pglob->gl_pathv[i], &st)) == 0
993 && S_ISDIR (st.st_mode))
995 size_t len = strlen (pglob->gl_pathv[i]) + 2;
996 char *new = realloc (pglob->gl_pathv[i], len);
997 if (new == NULL)
999 globfree (pglob);
1000 return GLOB_NOSPACE;
1002 strcpy (&new[len - 2], "/");
1003 pglob->gl_pathv[i] = new;
1007 if (!(flags & GLOB_NOSORT))
1009 /* Sort the vector. */
1010 int non_sort = oldcount;
1012 if ((flags & GLOB_DOOFFS) && pglob->gl_offs > oldcount)
1013 non_sort = pglob->gl_offs;
1015 qsort ((__ptr_t) &pglob->gl_pathv[non_sort],
1016 pglob->gl_pathc - non_sort,
1017 sizeof (char *), collated_compare);
1020 return 0;
1024 /* Free storage allocated in PGLOB by a previous `glob' call. */
1025 void
1026 globfree (pglob)
1027 register glob_t *pglob;
1029 if (pglob->gl_pathv != NULL)
1031 register int i;
1032 for (i = 0; i < pglob->gl_pathc; ++i)
1033 if (pglob->gl_pathv[i] != NULL)
1034 free ((__ptr_t) pglob->gl_pathv[i]);
1035 free ((__ptr_t) pglob->gl_pathv);
1040 /* Do a collated comparison of A and B. */
1041 static int
1042 collated_compare (a, b)
1043 const __ptr_t a;
1044 const __ptr_t b;
1046 const char *const s1 = *(const char *const * const) a;
1047 const char *const s2 = *(const char *const * const) b;
1049 if (s1 == s2)
1050 return 0;
1051 if (s1 == NULL)
1052 return 1;
1053 if (s2 == NULL)
1054 return -1;
1055 return strcoll (s1, s2);
1059 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1060 elements in place. Return nonzero if out of memory, zero if successful.
1061 A slash is inserted between DIRNAME and each elt of ARRAY,
1062 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1063 static int
1064 prefix_array (dirname, array, n)
1065 const char *dirname;
1066 char **array;
1067 size_t n;
1069 register size_t i;
1070 size_t dirlen = strlen (dirname);
1071 #if defined __MSDOS__ || defined WINDOWS32
1072 int sep_char = '/';
1073 # define DIRSEP_CHAR sep_char
1074 #else
1075 # define DIRSEP_CHAR '/'
1076 #endif
1078 if (dirlen == 1 && dirname[0] == '/')
1079 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1080 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1081 dirlen = 0;
1082 #if defined __MSDOS__ || defined WINDOWS32
1083 else if (dirlen > 1)
1085 if (dirname[dirlen - 1] == '/')
1086 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1087 --dirlen;
1088 else if (dirname[dirlen - 1] == ':')
1090 /* DIRNAME is "d:". Use `:' instead of `/'. */
1091 --dirlen;
1092 sep_char = ':';
1095 #endif
1097 for (i = 0; i < n; ++i)
1099 size_t eltlen = strlen (array[i]) + 1;
1100 char *new = (char *) malloc (dirlen + 1 + eltlen);
1101 if (new == NULL)
1103 while (i > 0)
1104 free ((__ptr_t) array[--i]);
1105 return 1;
1108 #ifdef HAVE_MEMPCPY
1110 char *endp = (char *) mempcpy (new, dirname, dirlen);
1111 *endp++ = DIRSEP_CHAR;
1112 mempcpy (endp, array[i], eltlen);
1114 #else
1115 memcpy (new, dirname, dirlen);
1116 new[dirlen] = DIRSEP_CHAR;
1117 memcpy (&new[dirlen + 1], array[i], eltlen);
1118 #endif
1119 free ((__ptr_t) array[i]);
1120 array[i] = new;
1123 return 0;
1127 /* We must not compile this function twice. */
1128 #if !defined _LIBC || !defined NO_GLOB_PATTERN_P
1129 /* Return nonzero if PATTERN contains any metacharacters.
1130 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
1132 __glob_pattern_p (pattern, quote)
1133 const char *pattern;
1134 int quote;
1136 register const char *p;
1137 int open = 0;
1139 for (p = pattern; *p != '\0'; ++p)
1140 switch (*p)
1142 case '?':
1143 case '*':
1144 return 1;
1146 case '\\':
1147 if (quote && p[1] != '\0')
1148 ++p;
1149 break;
1151 case '[':
1152 open = 1;
1153 break;
1155 case ']':
1156 if (open)
1157 return 1;
1158 break;
1161 return 0;
1163 # ifdef _LIBC
1164 weak_alias (__glob_pattern_p, glob_pattern_p)
1165 # endif
1166 #endif
1169 /* Like `glob', but PATTERN is a final pathname component,
1170 and matches are searched for in DIRECTORY.
1171 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1172 The GLOB_APPEND flag is assumed to be set (always appends). */
1173 static int
1174 glob_in_dir (pattern, directory, flags, errfunc, pglob)
1175 const char *pattern;
1176 const char *directory;
1177 int flags;
1178 int (*errfunc) __P ((const char *, int));
1179 glob_t *pglob;
1181 __ptr_t stream = NULL;
1183 struct globlink
1185 struct globlink *next;
1186 char *name;
1188 struct globlink *names = NULL;
1189 size_t nfound;
1190 int meta;
1191 int save;
1193 meta = __glob_pattern_p (pattern, !(flags & GLOB_NOESCAPE));
1194 if (meta == 0)
1196 if (flags & (GLOB_NOCHECK|GLOB_NOMAGIC))
1197 /* We need not do any tests. The PATTERN contains no meta
1198 characters and we must not return an error therefore the
1199 result will always contain exactly one name. */
1200 flags |= GLOB_NOCHECK;
1201 else
1203 /* Since we use the normal file functions we can also use stat()
1204 to verify the file is there. */
1205 struct stat st;
1206 size_t patlen = strlen (pattern);
1207 size_t dirlen = strlen (directory);
1208 char *fullname = (char *) __alloca (dirlen + 1 + patlen + 1);
1210 # ifdef HAVE_MEMPCPY
1211 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1212 "/", 1),
1213 pattern, patlen + 1);
1214 # else
1215 memcpy (fullname, directory, dirlen);
1216 fullname[dirlen] = '/';
1217 memcpy (&fullname[dirlen + 1], pattern, patlen + 1);
1218 # endif
1219 if (((flags & GLOB_ALTDIRFUNC)
1220 ? (*pglob->gl_stat) (fullname, &st)
1221 : __stat (fullname, &st)) == 0)
1222 /* We found this file to be existing. Now tell the rest
1223 of the function to copy this name into the result. */
1224 flags |= GLOB_NOCHECK;
1227 nfound = 0;
1229 else
1231 if (pattern[0] == '\0')
1233 /* This is a special case for matching directories like in
1234 "*a/". */
1235 names = (struct globlink *) __alloca (sizeof (struct globlink));
1236 names->name = (char *) malloc (1);
1237 if (names->name == NULL)
1238 goto memory_error;
1239 names->name[0] = '\0';
1240 names->next = NULL;
1241 nfound = 1;
1242 meta = 0;
1244 else
1246 stream = ((flags & GLOB_ALTDIRFUNC)
1247 ? (*pglob->gl_opendir) (directory)
1248 : (__ptr_t) opendir (directory));
1249 if (stream == NULL)
1251 if ((errfunc != NULL && (*errfunc) (directory, errno))
1252 || (flags & GLOB_ERR))
1253 return GLOB_ABORTED;
1254 nfound = 0;
1255 meta = 0;
1257 else
1259 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1260 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1261 #if defined _AMIGA || defined VMS
1262 | FNM_CASEFOLD
1263 #endif
1265 nfound = 0;
1266 flags |= GLOB_MAGCHAR;
1268 while (1)
1270 const char *name;
1271 size_t len;
1272 struct dirent *d = ((flags & GLOB_ALTDIRFUNC)
1273 ? (*pglob->gl_readdir) (stream)
1274 : readdir ((DIR *) stream));
1275 if (d == NULL)
1276 break;
1277 if (! REAL_DIR_ENTRY (d))
1278 continue;
1280 #ifdef HAVE_D_TYPE
1281 /* If we shall match only directories use the information
1282 provided by the dirent call if possible. */
1283 if ((flags & GLOB_ONLYDIR)
1284 && d->d_type != DT_UNKNOWN && d->d_type != DT_DIR)
1285 continue;
1286 #endif
1288 name = d->d_name;
1290 if (fnmatch (pattern, name, fnm_flags) == 0)
1292 struct globlink *new = (struct globlink *)
1293 __alloca (sizeof (struct globlink));
1294 len = NAMLEN (d);
1295 new->name = (char *) malloc (len + 1);
1296 if (new->name == NULL)
1297 goto memory_error;
1298 #ifdef HAVE_MEMPCPY
1299 *((char *) mempcpy ((__ptr_t) new->name, name, len))
1300 = '\0';
1301 #else
1302 memcpy ((__ptr_t) new->name, name, len);
1303 new->name[len] = '\0';
1304 #endif
1305 new->next = names;
1306 names = new;
1307 ++nfound;
1314 if (nfound == 0 && (flags & GLOB_NOCHECK))
1316 size_t len = strlen (pattern);
1317 nfound = 1;
1318 names = (struct globlink *) __alloca (sizeof (struct globlink));
1319 names->next = NULL;
1320 names->name = (char *) malloc (len + 1);
1321 if (names->name == NULL)
1322 goto memory_error;
1323 #ifdef HAVE_MEMPCPY
1324 *((char *) mempcpy (names->name, pattern, len)) = '\0';
1325 #else
1326 memcpy (names->name, pattern, len);
1327 names->name[len] = '\0';
1328 #endif
1331 if (nfound != 0)
1333 pglob->gl_pathv
1334 = (char **) realloc (pglob->gl_pathv,
1335 (pglob->gl_pathc +
1336 ((flags & GLOB_DOOFFS) ? pglob->gl_offs : 0) +
1337 nfound + 1) *
1338 sizeof (char *));
1339 if (pglob->gl_pathv == NULL)
1340 goto memory_error;
1342 if (flags & GLOB_DOOFFS)
1343 while (pglob->gl_pathc < pglob->gl_offs)
1344 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
1346 for (; names != NULL; names = names->next)
1347 pglob->gl_pathv[pglob->gl_pathc++] = names->name;
1348 pglob->gl_pathv[pglob->gl_pathc] = NULL;
1350 pglob->gl_flags = flags;
1353 save = errno;
1354 if (stream != NULL)
1355 if (flags & GLOB_ALTDIRFUNC)
1356 (*pglob->gl_closedir) (stream);
1357 else
1358 closedir ((DIR *) stream);
1359 __set_errno (save);
1361 return nfound == 0 ? GLOB_NOMATCH : 0;
1363 memory_error:
1365 int save = errno;
1366 if (flags & GLOB_ALTDIRFUNC)
1367 (*pglob->gl_closedir) (stream);
1368 else
1369 closedir ((DIR *) stream);
1370 __set_errno (save);
1372 while (names != NULL)
1374 if (names->name != NULL)
1375 free ((__ptr_t) names->name);
1376 names = names->next;
1378 return GLOB_NOSPACE;
1381 #endif /* Not ELIDE_CODE. */