Update.
[glibc.git] / sysdeps / generic / glob.c
blob9182c0585a26f86d45ca2b765f121613ef9b6fc7
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 #ifndef ANSI_STRING
160 # ifndef bzero
161 extern void bzero ();
162 # endif
163 # ifndef bcopy
164 extern void bcopy ();
165 # endif
167 # define memcpy(d, s, n) bcopy ((s), (d), (n))
168 # define strrchr rindex
169 /* memset is only used for zero here, but let's be paranoid. */
170 # define memset(s, better_be_zero, n) \
171 ((void) ((better_be_zero) == 0 ? (bzero((s), (n)), 0) : (abort(), 0)))
172 #endif /* Not ANSI_STRING. */
174 #if !defined HAVE_STRCOLL && !defined _LIBC
175 # define strcoll strcmp
176 #endif
178 #if !defined HAVE_MEMPCPY && __GLIBC__ - 0 == 2 && __GLIBC_MINOR__ >= 1
179 # define HAVE_MEMPCPY 1
180 # define mempcpy(Dest, Src, Len) __mempcpy (Dest, Src, Len)
181 #endif
184 #ifndef __GNU_LIBRARY__
185 # ifdef __GNUC__
186 __inline
187 # endif
188 # ifndef __SASC
189 # ifdef WINDOWS32
190 static void *
191 # else
192 static char *
193 # endif
194 my_realloc (p, n)
195 char *p;
196 unsigned int n;
198 /* These casts are the for sake of the broken Ultrix compiler,
199 which warns of illegal pointer combinations otherwise. */
200 if (p == NULL)
201 return (char *) malloc (n);
202 return (char *) realloc (p, n);
204 # define realloc my_realloc
205 # endif /* __SASC */
206 #endif /* __GNU_LIBRARY__ */
209 #if !defined __alloca && !defined __GNU_LIBRARY__
211 # ifdef __GNUC__
212 # undef alloca
213 # define alloca(n) __builtin_alloca (n)
214 # else /* Not GCC. */
215 # ifdef HAVE_ALLOCA_H
216 # include <alloca.h>
217 # else /* Not HAVE_ALLOCA_H. */
218 # ifndef _AIX
219 # ifdef WINDOWS32
220 # include <malloc.h>
221 # else
222 extern char *alloca ();
223 # endif /* WINDOWS32 */
224 # endif /* Not _AIX. */
225 # endif /* sparc or HAVE_ALLOCA_H. */
226 # endif /* GCC. */
228 # define __alloca alloca
230 #endif
232 #ifndef __GNU_LIBRARY__
233 # define __stat stat
234 # ifdef STAT_MACROS_BROKEN
235 # undef S_ISDIR
236 # endif
237 # ifndef S_ISDIR
238 # define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
239 # endif
240 #endif
242 #ifdef _LIBC
243 # define sysconf(id) __sysconf (id)
244 # define closedir(dir) __closedir (dir)
245 # define opendir(name) __opendir (name)
246 # define readdir(str) __readdir (str)
247 #endif
249 #if !(defined STDC_HEADERS || defined __GNU_LIBRARY__)
250 # undef size_t
251 # define size_t unsigned int
252 #endif
254 /* Some system header files erroneously define these.
255 We want our own definitions from <fnmatch.h> to take precedence. */
256 #ifndef __GNU_LIBRARY__
257 # undef FNM_PATHNAME
258 # undef FNM_NOESCAPE
259 # undef FNM_PERIOD
260 #endif
261 #include <fnmatch.h>
263 /* Some system header files erroneously define these.
264 We want our own definitions from <glob.h> to take precedence. */
265 #ifndef __GNU_LIBRARY__
266 # undef GLOB_ERR
267 # undef GLOB_MARK
268 # undef GLOB_NOSORT
269 # undef GLOB_DOOFFS
270 # undef GLOB_NOCHECK
271 # undef GLOB_APPEND
272 # undef GLOB_NOESCAPE
273 # undef GLOB_PERIOD
274 #endif
275 #include <glob.h>
277 static
278 #if __GNUC__ - 0 >= 2
279 inline
280 #endif
281 const char *next_brace_sub __P ((const char *begin));
282 static int glob_in_dir __P ((const char *pattern, const char *directory,
283 int flags,
284 int (*errfunc) __P ((const char *, int)),
285 glob_t *pglob));
286 static int prefix_array __P ((const char *prefix, char **array, size_t n));
287 static int collated_compare __P ((const __ptr_t, const __ptr_t));
290 /* Find the end of the sub-pattern in a brace expression. We define
291 this as an inline function if the compiler permits. */
292 static
293 #if __GNUC__ - 0 >= 2
294 inline
295 #endif
296 const char *
297 next_brace_sub (begin)
298 const char *begin;
300 unsigned int depth = 0;
301 const char *cp = begin;
303 while (1)
305 if (depth == 0)
307 if (*cp != ',' && *cp != '}' && *cp != '\0')
309 if (*cp == '{')
310 ++depth;
311 ++cp;
312 continue;
315 else
317 while (*cp != '\0' && (*cp != '}' || depth > 0))
319 if (*cp == '}')
320 --depth;
321 ++cp;
323 if (*cp == '\0')
324 /* An incorrectly terminated brace expression. */
325 return NULL;
327 continue;
329 break;
332 return cp;
335 /* Do glob searching for PATTERN, placing results in PGLOB.
336 The bits defined above may be set in FLAGS.
337 If a directory cannot be opened or read and ERRFUNC is not nil,
338 it is called with the pathname that caused the error, and the
339 `errno' value from the failing call; if it returns non-zero
340 `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
341 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
342 Otherwise, `glob' returns zero. */
344 glob (pattern, flags, errfunc, pglob)
345 const char *pattern;
346 int flags;
347 int (*errfunc) __P ((const char *, int));
348 glob_t *pglob;
350 const char *filename;
351 char *dirname;
352 size_t dirlen;
353 int status;
354 int oldcount;
356 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
358 __set_errno (EINVAL);
359 return -1;
362 if (flags & GLOB_BRACE)
364 const char *begin = strchr (pattern, '{');
365 if (begin != NULL)
367 /* Allocate working buffer large enough for our work. Note that
368 we have at least an opening and closing brace. */
369 int firstc;
370 char *alt_start;
371 const char *p;
372 const char *next;
373 const char *rest;
374 size_t rest_len;
375 #ifdef __GNUC__
376 char onealt[strlen (pattern) - 1];
377 #else
378 char *onealt = (char *) malloc (strlen (pattern) - 1);
379 if (onealt == NULL)
381 if (!(flags & GLOB_APPEND))
382 globfree (pglob);
383 return GLOB_NOSPACE;
385 #endif
387 /* We know the prefix for all sub-patterns. */
388 #ifdef HAVE_MEMPCPY
389 alt_start = mempcpy (onealt, pattern, begin - pattern);
390 #else
391 memcpy (onealt, pattern, begin - pattern);
392 alt_start = &onealt[begin - pattern];
393 #endif
395 /* Find the first sub-pattern and at the same time find the
396 rest after the closing brace. */
397 next = next_brace_sub (begin + 1);
398 if (next == NULL)
400 /* It is an illegal expression. */
401 #ifndef __GNUC__
402 free (onealt);
403 #endif
404 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
407 /* Now find the end of the whole brace expression. */
408 rest = next;
409 while (*rest != '}')
411 rest = next_brace_sub (rest + 1);
412 if (rest == NULL)
414 /* It is an illegal expression. */
415 #ifndef __GNUC__
416 free (onealt);
417 #endif
418 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
421 /* Please note that we now can be sure the brace expression
422 is well-formed. */
423 rest_len = strlen (++rest) + 1;
425 /* We have a brace expression. BEGIN points to the opening {,
426 NEXT points past the terminator of the first element, and END
427 points past the final }. We will accumulate result names from
428 recursive runs for each brace alternative in the buffer using
429 GLOB_APPEND. */
431 if (!(flags & GLOB_APPEND))
433 /* This call is to set a new vector, so clear out the
434 vector so we can append to it. */
435 pglob->gl_pathc = 0;
436 pglob->gl_pathv = NULL;
438 firstc = pglob->gl_pathc;
440 p = begin + 1;
441 while (1)
443 int result;
445 /* Construct the new glob expression. */
446 #ifdef HAVE_MEMPCPY
447 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
448 #else
449 memcpy (alt_start, p, next - p);
450 memcpy (&alt_start[next - p], rest, rest_len);
451 #endif
453 result = glob (onealt,
454 ((flags & ~(GLOB_NOCHECK|GLOB_NOMAGIC))
455 | GLOB_APPEND), errfunc, pglob);
457 /* If we got an error, return it. */
458 if (result && result != GLOB_NOMATCH)
460 #ifndef __GNUC__
461 free (onealt);
462 #endif
463 if (!(flags & GLOB_APPEND))
464 globfree (pglob);
465 return result;
468 if (*next == '}')
469 /* We saw the last entry. */
470 break;
472 p = next + 1;
473 next = next_brace_sub (p);
474 assert (next != NULL);
477 #ifndef __GNUC__
478 free (onealt);
479 #endif
481 if (pglob->gl_pathc != firstc)
482 /* We found some entries. */
483 return 0;
484 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
485 return GLOB_NOMATCH;
489 /* Find the filename. */
490 filename = strrchr (pattern, '/');
491 if (filename == NULL)
493 filename = pattern;
494 #ifdef _AMIGA
495 dirname = (char *) "";
496 #else
497 dirname = (char *) ".";
498 #endif
499 dirlen = 0;
501 else if (filename == pattern)
503 /* "/pattern". */
504 dirname = (char *) "/";
505 dirlen = 1;
506 ++filename;
508 else
510 dirlen = filename - pattern;
511 dirname = (char *) __alloca (dirlen + 1);
512 #ifdef HAVE_MEMPCPY
513 *((char *) mempcpy (dirname, pattern, dirlen)) = '\0';
514 #else
515 memcpy (dirname, pattern, dirlen);
516 dirname[dirlen] = '\0';
517 #endif
518 ++filename;
521 if (filename[0] == '\0' && dirlen > 1)
522 /* "pattern/". Expand "pattern", appending slashes. */
524 int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
525 if (val == 0)
526 pglob->gl_flags = (pglob->gl_flags & ~GLOB_MARK) | (flags & GLOB_MARK);
527 return val;
530 if (!(flags & GLOB_APPEND))
532 pglob->gl_pathc = 0;
533 pglob->gl_pathv = NULL;
536 oldcount = pglob->gl_pathc;
538 #ifndef VMS
539 if ((flags & GLOB_TILDE) && dirname[0] == '~')
541 if (dirname[1] == '\0' || dirname[1] == '/')
543 /* Look up home directory. */
544 char *home_dir = getenv ("HOME");
545 # ifdef _AMIGA
546 if (home_dir == NULL || home_dir[0] == '\0')
547 home_dir = "SYS:";
548 # else
549 # ifdef WINDOWS32
550 if (home_dir == NULL || home_dir[0] == '\0')
551 home_dir = "c:/users/default"; /* poor default */
552 # else
553 if (home_dir == NULL || home_dir[0] == '\0')
555 int success;
556 # if defined HAVE_GETLOGIN_R || defined _LIBC
557 extern int getlogin_r __P ((char *, size_t));
558 size_t buflen = sysconf (_SC_LOGIN_NAME_MAX) + 1;
559 char *name;
561 if (buflen == 0)
562 /* `sysconf' does not support _SC_LOGIN_NAME_MAX. Try
563 a moderate value. */
564 buflen = 16;
565 name = (char *) __alloca (buflen);
567 success = getlogin_r (name, buflen) >= 0;
568 # else
569 extern char *getlogin __P ((void));
570 char *name;
572 success = (name = getlogin ()) != NULL;
573 # endif
574 if (success)
576 # if defined HAVE_GETPWNAM_R || defined _LIBC
577 size_t pwbuflen = sysconf (_SC_GETPW_R_SIZE_MAX);
578 char *pwtmpbuf;
579 struct passwd pwbuf, *p;
581 pwtmpbuf = (char *) __alloca (pwbuflen);
583 success = (__getpwnam_r (name, &pwbuf, pwtmpbuf,
584 pwbuflen, &p) >= 0);
585 # else
586 struct passwd *p = getpwnam (name);
587 success = p != NULL;
588 # endif
589 if (success)
590 home_dir = p->pw_dir;
593 if (home_dir == NULL || home_dir[0] == '\0')
594 home_dir = (char *) "~"; /* No luck. */
595 # endif /* WINDOWS32 */
596 # endif
597 /* Now construct the full directory. */
598 if (dirname[1] == '\0')
599 dirname = home_dir;
600 else
602 char *newp;
603 size_t home_len = strlen (home_dir);
604 newp = (char *) __alloca (home_len + dirlen);
605 # ifdef HAVE_MEMPCPY
606 mempcpy (mempcpy (newp, home_dir, home_len),
607 &dirname[1], dirlen);
608 # else
609 memcpy (newp, home_dir, home_len);
610 memcpy (&newp[home_len], &dirname[1], dirlen);
611 # endif
612 dirname = newp;
615 # if !defined _AMIGA && !defined WINDOWS32
616 else
618 char *end_name = strchr (dirname, '/');
619 char *user_name;
620 char *home_dir;
622 if (end_name == NULL)
623 user_name = dirname + 1;
624 else
626 user_name = (char *) __alloca (end_name - dirname);
627 # ifdef HAVE_MEMPCPY
628 *((char *) mempcpy (user_name, dirname + 1, end_name - dirname))
629 = '\0';
630 # else
631 memcpy (user_name, dirname + 1, end_name - dirname);
632 user_name[end_name - dirname - 1] = '\0';
633 # endif
636 /* Look up specific user's home directory. */
638 # if defined HAVE_GETPWNAM_R || defined _LIBC
639 size_t buflen = sysconf (_SC_GETPW_R_SIZE_MAX);
640 char *pwtmpbuf = (char *) __alloca (buflen);
641 struct passwd pwbuf, *p;
642 if (__getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) >= 0)
643 home_dir = p->pw_dir;
644 else
645 home_dir = NULL;
646 # else
647 struct passwd *p = getpwnam (user_name);
648 if (p != NULL)
649 home_dir = p->pw_dir;
650 else
651 home_dir = NULL;
652 # endif
654 /* If we found a home directory use this. */
655 if (home_dir != NULL)
657 char *newp;
658 size_t home_len = strlen (home_dir);
659 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
660 newp = (char *) __alloca (home_len + rest_len + 1);
661 # ifdef HAVE_MEMPCPY
662 *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
663 end_name, rest_len)) = '\0';
664 # else
665 memcpy (newp, home_dir, home_len);
666 memcpy (&newp[home_len], end_name, rest_len);
667 newp[home_len + rest_len] = '\0';
668 # endif
669 dirname = newp;
672 # endif /* Not Amiga && not WINDOWS32. */
674 #endif /* Not VMS. */
676 if (__glob_pattern_p (dirname, !(flags & GLOB_NOESCAPE)))
678 /* The directory name contains metacharacters, so we
679 have to glob for the directory, and then glob for
680 the pattern in each directory found. */
681 glob_t dirs;
682 register int i;
684 status = glob (dirname,
685 ((flags & (GLOB_ERR | GLOB_NOCHECK | GLOB_NOESCAPE))
686 | GLOB_NOSORT | GLOB_ONLYDIR),
687 errfunc, &dirs);
688 if (status != 0)
689 return status;
691 /* We have successfully globbed the preceding directory name.
692 For each name we found, call glob_in_dir on it and FILENAME,
693 appending the results to PGLOB. */
694 for (i = 0; i < dirs.gl_pathc; ++i)
696 int oldcount;
698 #ifdef SHELL
700 /* Make globbing interruptible in the bash shell. */
701 extern int interrupt_state;
703 if (interrupt_state)
705 globfree (&dirs);
706 globfree (&files);
707 return GLOB_ABORTED;
710 #endif /* SHELL. */
712 oldcount = pglob->gl_pathc;
713 status = glob_in_dir (filename, dirs.gl_pathv[i],
714 ((flags | GLOB_APPEND)
715 & ~(GLOB_NOCHECK | GLOB_ERR)),
716 errfunc, pglob);
717 if (status == GLOB_NOMATCH)
718 /* No matches in this directory. Try the next. */
719 continue;
721 if (status != 0)
723 globfree (&dirs);
724 globfree (pglob);
725 return status;
728 /* Stick the directory on the front of each name. */
729 if (prefix_array (dirs.gl_pathv[i],
730 &pglob->gl_pathv[oldcount],
731 pglob->gl_pathc - oldcount))
733 globfree (&dirs);
734 globfree (pglob);
735 return GLOB_NOSPACE;
739 flags |= GLOB_MAGCHAR;
741 if (pglob->gl_pathc == oldcount)
742 /* No matches. */
743 if (flags & GLOB_NOCHECK)
745 size_t len = strlen (pattern) + 1;
746 char *patcopy = (char *) malloc (len);
747 if (patcopy == NULL)
748 return GLOB_NOSPACE;
749 memcpy (patcopy, pattern, len);
751 pglob->gl_pathv
752 = (char **) realloc (pglob->gl_pathv,
753 (pglob->gl_pathc +
754 ((flags & GLOB_DOOFFS) ?
755 pglob->gl_offs : 0) +
756 1 + 1) *
757 sizeof (char *));
758 if (pglob->gl_pathv == NULL)
760 free (patcopy);
761 return GLOB_NOSPACE;
764 if (flags & GLOB_DOOFFS)
765 while (pglob->gl_pathc < pglob->gl_offs)
766 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
768 pglob->gl_pathv[pglob->gl_pathc++] = patcopy;
769 pglob->gl_pathv[pglob->gl_pathc] = NULL;
770 pglob->gl_flags = flags;
772 else
773 return GLOB_NOMATCH;
775 else
777 status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
778 if (status != 0)
779 return status;
781 if (dirlen > 0)
783 /* Stick the directory on the front of each name. */
784 if (prefix_array (dirname,
785 &pglob->gl_pathv[oldcount],
786 pglob->gl_pathc - oldcount))
788 globfree (pglob);
789 return GLOB_NOSPACE;
794 if (flags & GLOB_MARK)
796 /* Append slashes to directory names. */
797 int i;
798 struct stat st;
799 for (i = oldcount; i < pglob->gl_pathc; ++i)
800 if (((flags & GLOB_ALTDIRFUNC)
801 ? (*pglob->gl_stat) (pglob->gl_pathv[i], &st)
802 : __stat (pglob->gl_pathv[i], &st)) == 0
803 && S_ISDIR (st.st_mode))
805 size_t len = strlen (pglob->gl_pathv[i]) + 2;
806 char *new = realloc (pglob->gl_pathv[i], len);
807 if (new == NULL)
809 globfree (pglob);
810 return GLOB_NOSPACE;
812 strcpy (&new[len - 2], "/");
813 pglob->gl_pathv[i] = new;
817 if (!(flags & GLOB_NOSORT))
818 /* Sort the vector. */
819 qsort ((__ptr_t) &pglob->gl_pathv[oldcount],
820 pglob->gl_pathc - oldcount,
821 sizeof (char *), collated_compare);
823 return 0;
827 /* Free storage allocated in PGLOB by a previous `glob' call. */
828 void
829 globfree (pglob)
830 register glob_t *pglob;
832 if (pglob->gl_pathv != NULL)
834 register int i;
835 for (i = 0; i < pglob->gl_pathc; ++i)
836 if (pglob->gl_pathv[i] != NULL)
837 free ((__ptr_t) pglob->gl_pathv[i]);
838 free ((__ptr_t) pglob->gl_pathv);
843 /* Do a collated comparison of A and B. */
844 static int
845 collated_compare (a, b)
846 const __ptr_t a;
847 const __ptr_t b;
849 const char *const s1 = *(const char *const * const) a;
850 const char *const s2 = *(const char *const * const) b;
852 if (s1 == s2)
853 return 0;
854 if (s1 == NULL)
855 return 1;
856 if (s2 == NULL)
857 return -1;
858 return strcoll (s1, s2);
862 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
863 elements in place. Return nonzero if out of memory, zero if successful.
864 A slash is inserted between DIRNAME and each elt of ARRAY,
865 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
866 static int
867 prefix_array (dirname, array, n)
868 const char *dirname;
869 char **array;
870 size_t n;
872 register size_t i;
873 size_t dirlen = strlen (dirname);
875 if (dirlen == 1 && dirname[0] == '/')
876 /* DIRNAME is just "/", so normal prepending would get us "//foo".
877 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
878 dirlen = 0;
880 for (i = 0; i < n; ++i)
882 size_t eltlen = strlen (array[i]) + 1;
883 char *new = (char *) malloc (dirlen + 1 + eltlen);
884 if (new == NULL)
886 while (i > 0)
887 free ((__ptr_t) array[--i]);
888 return 1;
891 #ifdef HAVE_MEMPCPY
893 char *endp = (char *) mempcpy (new, dirname, dirlen);
894 *endp++ = '/';
895 mempcpy (endp, array[i], eltlen);
897 #else
898 memcpy (new, dirname, dirlen);
899 new[dirlen] = '/';
900 memcpy (&new[dirlen + 1], array[i], eltlen);
901 #endif
902 free ((__ptr_t) array[i]);
903 array[i] = new;
906 return 0;
910 /* Return nonzero if PATTERN contains any metacharacters.
911 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
913 __glob_pattern_p (pattern, quote)
914 const char *pattern;
915 int quote;
917 register const char *p;
918 int open = 0;
920 for (p = pattern; *p != '\0'; ++p)
921 switch (*p)
923 case '?':
924 case '*':
925 return 1;
927 case '\\':
928 if (quote && p[1] != '\0')
929 ++p;
930 break;
932 case '[':
933 open = 1;
934 break;
936 case ']':
937 if (open)
938 return 1;
939 break;
942 return 0;
944 #ifdef _LIBC
945 weak_alias (__glob_pattern_p, glob_pattern_p)
946 #endif
949 /* Like `glob', but PATTERN is a final pathname component,
950 and matches are searched for in DIRECTORY.
951 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
952 The GLOB_APPEND flag is assumed to be set (always appends). */
953 static int
954 glob_in_dir (pattern, directory, flags, errfunc, pglob)
955 const char *pattern;
956 const char *directory;
957 int flags;
958 int (*errfunc) __P ((const char *, int));
959 glob_t *pglob;
961 __ptr_t stream = NULL;
963 struct globlink
965 struct globlink *next;
966 char *name;
968 struct globlink *names = NULL;
969 size_t nfound;
970 int meta;
971 int save;
973 meta = __glob_pattern_p (pattern, !(flags & GLOB_NOESCAPE));
974 if (meta == 0)
976 if (flags & (GLOB_NOCHECK|GLOB_NOMAGIC))
977 /* We need not do any tests. The PATTERN contains no meta
978 characters and we must not return an error therefore the
979 result will always contain exactly the one name. */
980 flags |= GLOB_NOCHECK;
981 else
983 /* Since we use the normal file functions we can also use stat()
984 to verify the file is there. */
985 struct stat st;
986 size_t patlen = strlen (pattern);
987 size_t dirlen = strlen (directory);
988 char *fullname = __alloca (dirlen + 1 + patlen + 1);
990 # ifdef HAVE_MEMPCPY
991 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
992 "/", 1),
993 pattern, patlen + 1);
994 # else
995 memcpy (fullname, directory, dirlen);
996 fullname[dirlen] = '/';
997 memcpy (&fullname[dirlen + 1], pattern, patlen + 1);
998 # endif
999 if (((flags & GLOB_ALTDIRFUNC)
1000 ? (*pglob->gl_stat) (fullname, &st)
1001 : __stat (fullname, &st)) == 0)
1002 /* We found this file to be existing. No tell the rest
1003 of the function to copy this name into the result. */
1004 flags |= GLOB_NOCHECK;
1007 nfound = 0;
1009 else
1011 if (pattern[0] == '\0')
1013 /* This is a special case for matching directories like in
1014 "*a/". */
1015 names = (struct globlink *) __alloca (sizeof (struct globlink));
1016 names->name = (char *) malloc (1);
1017 if (names->name == NULL)
1018 goto memory_error;
1019 names->name[0] = '\0';
1020 names->next = NULL;
1021 nfound = 1;
1022 meta = 0;
1024 else
1026 stream = ((flags & GLOB_ALTDIRFUNC)
1027 ? (*pglob->gl_opendir) (directory)
1028 : (__ptr_t) opendir (directory));
1029 if (stream == NULL)
1031 if ((errfunc != NULL && (*errfunc) (directory, errno))
1032 || (flags & GLOB_ERR))
1033 return GLOB_ABORTED;
1034 nfound = 0;
1035 meta = 0;
1037 else
1039 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1040 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1041 #if defined _AMIGA || defined VMS
1042 | FNM_CASEFOLD
1043 #endif
1045 nfound = 0;
1046 flags |= GLOB_MAGCHAR;
1048 while (1)
1050 const char *name;
1051 size_t len;
1052 struct dirent *d = ((flags & GLOB_ALTDIRFUNC)
1053 ? (*pglob->gl_readdir) (stream)
1054 : readdir ((DIR *) stream));
1055 if (d == NULL)
1056 break;
1057 if (! REAL_DIR_ENTRY (d))
1058 continue;
1060 #ifdef HAVE_D_TYPE
1061 /* If we shall match only directories use the information
1062 provided by the dirent call if possible. */
1063 if ((flags & GLOB_ONLYDIR)
1064 && d->d_type != DT_UNKNOWN && d->d_type != DT_DIR)
1065 continue;
1066 #endif
1068 name = d->d_name;
1070 if (fnmatch (pattern, name, fnm_flags) == 0)
1072 struct globlink *new = (struct globlink *)
1073 __alloca (sizeof (struct globlink));
1074 len = NAMLEN (d);
1075 new->name = (char *) malloc (len + 1);
1076 if (new->name == NULL)
1077 goto memory_error;
1078 #ifdef HAVE_MEMPCPY
1079 *((char *) mempcpy ((__ptr_t) new->name, name, len))
1080 = '\0';
1081 #else
1082 memcpy ((__ptr_t) new->name, name, len);
1083 new->name[len] = '\0';
1084 #endif
1085 new->next = names;
1086 names = new;
1087 ++nfound;
1094 if (nfound == 0 && (flags & GLOB_NOCHECK))
1096 size_t len = strlen (pattern);
1097 nfound = 1;
1098 names = (struct globlink *) __alloca (sizeof (struct globlink));
1099 names->next = NULL;
1100 names->name = (char *) malloc (len + 1);
1101 if (names->name == NULL)
1102 goto memory_error;
1103 #ifdef HAVE_MEMPCPY
1104 *((char *) mempcpy (names->name, pattern, len)) = '\0';
1105 #else
1106 memcpy (names->name, pattern, len);
1107 names->name[len] = '\0';
1108 #endif
1111 if (nfound != 0)
1113 pglob->gl_pathv
1114 = (char **) realloc (pglob->gl_pathv,
1115 (pglob->gl_pathc +
1116 ((flags & GLOB_DOOFFS) ? pglob->gl_offs : 0) +
1117 nfound + 1) *
1118 sizeof (char *));
1119 if (pglob->gl_pathv == NULL)
1120 goto memory_error;
1122 if (flags & GLOB_DOOFFS)
1123 while (pglob->gl_pathc < pglob->gl_offs)
1124 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
1126 for (; names != NULL; names = names->next)
1127 pglob->gl_pathv[pglob->gl_pathc++] = names->name;
1128 pglob->gl_pathv[pglob->gl_pathc] = NULL;
1130 pglob->gl_flags = flags;
1133 save = errno;
1134 if (stream != NULL)
1135 if (flags & GLOB_ALTDIRFUNC)
1136 (*pglob->gl_closedir) (stream);
1137 else
1138 closedir ((DIR *) stream);
1139 __set_errno (save);
1141 return nfound == 0 ? GLOB_NOMATCH : 0;
1143 memory_error:
1145 int save = errno;
1146 if (flags & GLOB_ALTDIRFUNC)
1147 (*pglob->gl_closedir) (stream);
1148 else
1149 closedir ((DIR *) stream);
1150 __set_errno (save);
1152 while (names != NULL)
1154 if (names->name != NULL)
1155 free ((__ptr_t) names->name);
1156 names = names->next;
1158 return GLOB_NOSPACE;
1161 #endif /* Not ELIDE_CODE. */