(next_brace_sub): Return NULL if braces don't match, fix {{a,b},c} globbing, clean up.
[glibc.git] / sysdeps / generic / glob.c
bloba17a4c45dfab24f2566bb33a88624d2b4e7f8468
1 /* Copyright (C) 1991-1999, 2000, 2001 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
9 The GNU C Library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public
15 License along with the GNU C Library; if not, write to the Free
16 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
17 02111-1307 USA. */
19 /* AIX requires this to be the first thing in the file. */
20 #if defined _AIX && !defined __GNUC__
21 #pragma alloca
22 #endif
24 #ifdef HAVE_CONFIG_H
25 # include <config.h>
26 #endif
28 /* Enable GNU extensions in glob.h. */
29 #ifndef _GNU_SOURCE
30 # define _GNU_SOURCE 1
31 #endif
33 #include <errno.h>
34 #include <sys/types.h>
35 #include <sys/stat.h>
37 /* Outcomment the following line for production quality code. */
38 /* #define NDEBUG 1 */
39 #include <assert.h>
41 #include <stdio.h> /* Needed on stupid SunOS for assert. */
44 /* Comment out all this code if we are using the GNU C Library, and are not
45 actually compiling the library itself. This code is part of the GNU C
46 Library, but also included in many other GNU distributions. Compiling
47 and linking in this code is a waste when using the GNU C library
48 (especially if it is a shared library). Rather than having every GNU
49 program understand `configure --with-gnu-libc' and omit the object files,
50 it is simpler to just do this in the source for each such file. */
52 #define GLOB_INTERFACE_VERSION 1
53 #if !defined _LIBC && defined __GNU_LIBRARY__ && __GNU_LIBRARY__ > 1
54 # include <gnu-versions.h>
55 # if _GNU_GLOB_INTERFACE_VERSION == GLOB_INTERFACE_VERSION
56 # define ELIDE_CODE
57 # endif
58 #endif
60 #ifndef ELIDE_CODE
61 #if !defined _LIBC || !defined GLOB_ONLY_P
63 #if defined STDC_HEADERS || defined __GNU_LIBRARY__
64 # include <stddef.h>
65 #endif
67 #if defined HAVE_UNISTD_H || defined _LIBC
68 # include <unistd.h>
69 # ifndef POSIX
70 # ifdef _POSIX_VERSION
71 # define POSIX
72 # endif
73 # endif
74 #endif
76 #if !defined _AMIGA && !defined VMS && !defined WINDOWS32
77 # include <pwd.h>
78 #endif
80 #if !defined __GNU_LIBRARY__ && !defined STDC_HEADERS
81 extern int errno;
82 #endif
83 #ifndef __set_errno
84 # define __set_errno(val) errno = (val)
85 #endif
87 #ifndef NULL
88 # define NULL 0
89 #endif
92 #if defined HAVE_DIRENT_H || defined __GNU_LIBRARY__
93 # include <dirent.h>
94 # define NAMLEN(dirent) strlen((dirent)->d_name)
95 #else
96 # define dirent direct
97 # define NAMLEN(dirent) (dirent)->d_namlen
98 # ifdef HAVE_SYS_NDIR_H
99 # include <sys/ndir.h>
100 # endif
101 # ifdef HAVE_SYS_DIR_H
102 # include <sys/dir.h>
103 # endif
104 # ifdef HAVE_NDIR_H
105 # include <ndir.h>
106 # endif
107 # ifdef HAVE_VMSDIR_H
108 # include "vmsdir.h"
109 # endif /* HAVE_VMSDIR_H */
110 #endif
113 /* In GNU systems, <dirent.h> defines this macro for us. */
114 #ifdef _D_NAMLEN
115 # undef NAMLEN
116 # define NAMLEN(d) _D_NAMLEN(d)
117 #endif
119 /* When used in the GNU libc the symbol _DIRENT_HAVE_D_TYPE is available
120 if the `d_type' member for `struct dirent' is available. */
121 #ifdef _DIRENT_HAVE_D_TYPE
122 # define HAVE_D_TYPE 1
123 #endif
125 #if _LIBC
126 # define HAVE_DIRENT64 1
127 #endif
129 /* If the system has the `struct dirent64' type we use it internally. */
130 #if defined HAVE_DIRENT64 && !defined COMPILE_GLOB64
131 # if defined HAVE_DIRENT_H || defined __GNU_LIBRARY__
132 # define CONVERT_D_NAMLEN(d64, d32)
133 # else
134 # define CONVERT_D_NAMLEN(d64, d32) \
135 (d64)->d_namlen = (d32)->d_namlen;
136 # endif
138 # if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
139 # define CONVERT_D_INO(d64, d32)
140 # else
141 # define CONVERT_D_INO(d64, d32) \
142 (d64)->d_ino = (d32)->d_ino;
143 # endif
145 # ifdef HAVE_D_TYPE
146 # define CONVERT_D_TYPE(d64, d32) \
147 (d64)->d_type = (d32)->d_type;
148 # else
149 # define CONVERT_D_TYPE(d64, d32)
150 # endif
152 # define CONVERT_DIRENT_DIRENT64(d64, d32) \
153 memcpy ((d64)->d_name, (d32)->d_name, NAMLEN (d32) + 1); \
154 CONVERT_D_NAMLEN (d64, d32) \
155 CONVERT_D_INO (d64, d32) \
156 CONVERT_D_TYPE (d64, d32)
157 #endif
160 #if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
161 /* Posix does not require that the d_ino field be present, and some
162 systems do not provide it. */
163 # define REAL_DIR_ENTRY(dp) 1
164 #else
165 # define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
166 #endif /* POSIX */
168 #if defined STDC_HEADERS || defined __GNU_LIBRARY__
169 # include <stdlib.h>
170 # include <string.h>
171 # define ANSI_STRING
172 #else /* No standard headers. */
174 extern char *getenv ();
176 # ifdef HAVE_STRING_H
177 # include <string.h>
178 # define ANSI_STRING
179 # else
180 # include <strings.h>
181 # endif
182 # ifdef HAVE_MEMORY_H
183 # include <memory.h>
184 # endif
186 extern char *malloc (), *realloc ();
187 extern void free ();
189 extern void qsort ();
190 extern void abort (), exit ();
192 #endif /* Standard headers. */
194 #ifndef ANSI_STRING
196 # ifndef bzero
197 extern void bzero ();
198 # endif
199 # ifndef bcopy
200 extern void bcopy ();
201 # endif
203 # define memcpy(d, s, n) bcopy ((s), (d), (n))
204 # define strrchr rindex
205 /* memset is only used for zero here, but let's be paranoid. */
206 # define memset(s, better_be_zero, n) \
207 ((void) ((better_be_zero) == 0 ? (bzero((s), (n)), 0) : (abort(), 0)))
208 #endif /* Not ANSI_STRING. */
210 #if !defined HAVE_STRCOLL && !defined _LIBC
211 # define strcoll strcmp
212 #endif
214 #if !defined HAVE_MEMPCPY && __GLIBC__ - 0 == 2 && __GLIBC_MINOR__ >= 1
215 # define HAVE_MEMPCPY 1
216 # undef mempcpy
217 # define mempcpy(Dest, Src, Len) __mempcpy (Dest, Src, Len)
218 #endif
220 #ifndef __GNU_LIBRARY__
221 # ifdef __GNUC__
222 __inline
223 # endif
224 # ifndef __SASC
225 # ifdef WINDOWS32
226 static void *
227 # else
228 static char *
229 # endif
230 my_realloc (p, n)
231 char *p;
232 unsigned int n;
234 /* These casts are the for sake of the broken Ultrix compiler,
235 which warns of illegal pointer combinations otherwise. */
236 if (p == NULL)
237 return (char *) malloc (n);
238 return (char *) realloc (p, n);
240 # define realloc my_realloc
241 # endif /* __SASC */
242 #endif /* __GNU_LIBRARY__ */
245 #if !defined __alloca && !defined __GNU_LIBRARY__
247 # ifdef __GNUC__
248 # undef alloca
249 # define alloca(n) __builtin_alloca (n)
250 # else /* Not GCC. */
251 # ifdef HAVE_ALLOCA_H
252 # include <alloca.h>
253 # else /* Not HAVE_ALLOCA_H. */
254 # ifndef _AIX
255 # ifdef WINDOWS32
256 # include <malloc.h>
257 # else
258 extern char *alloca ();
259 # endif /* WINDOWS32 */
260 # endif /* Not _AIX. */
261 # endif /* sparc or HAVE_ALLOCA_H. */
262 # endif /* GCC. */
264 # define __alloca alloca
266 #endif
268 #ifndef __GNU_LIBRARY__
269 # define __stat stat
270 # ifdef STAT_MACROS_BROKEN
271 # undef S_ISDIR
272 # endif
273 # ifndef S_ISDIR
274 # define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
275 # endif
276 #endif
278 #ifdef _LIBC
279 # undef strdup
280 # define strdup(str) __strdup (str)
281 # define sysconf(id) __sysconf (id)
282 # define closedir(dir) __closedir (dir)
283 # define opendir(name) __opendir (name)
284 # define readdir(str) __readdir64 (str)
285 # define getpwnam_r(name, bufp, buf, len, res) \
286 __getpwnam_r (name, bufp, buf, len, res)
287 # ifndef __stat64
288 # define __stat64(fname, buf) __xstat64 (_STAT_VER, fname, buf)
289 # endif
290 # define HAVE_STAT64 1
291 #endif
293 #ifndef HAVE_STAT64
294 # define __stat64(fname, buf) __stat (fname, buf)
295 /* This is the variable name we are using. */
296 # define st64 st
297 #endif
299 #if !(defined STDC_HEADERS || defined __GNU_LIBRARY__)
300 # undef size_t
301 # define size_t unsigned int
302 #endif
304 /* Some system header files erroneously define these.
305 We want our own definitions from <fnmatch.h> to take precedence. */
306 #ifndef __GNU_LIBRARY__
307 # undef FNM_PATHNAME
308 # undef FNM_NOESCAPE
309 # undef FNM_PERIOD
310 #endif
311 #include <fnmatch.h>
313 /* Some system header files erroneously define these.
314 We want our own definitions from <glob.h> to take precedence. */
315 #ifndef __GNU_LIBRARY__
316 # undef GLOB_ERR
317 # undef GLOB_MARK
318 # undef GLOB_NOSORT
319 # undef GLOB_DOOFFS
320 # undef GLOB_NOCHECK
321 # undef GLOB_APPEND
322 # undef GLOB_NOESCAPE
323 # undef GLOB_PERIOD
324 #endif
325 #include <glob.h>
327 #ifdef HAVE_GETLOGIN_R
328 extern int getlogin_r __P ((char *, size_t));
329 #else
330 extern char *getlogin __P ((void));
331 #endif
333 static
334 #if __GNUC__ - 0 >= 2
335 inline
336 #endif
337 const char *next_brace_sub __P ((const char *begin));
339 #endif /* GLOB_ONLY_P */
341 static int glob_in_dir __P ((const char *pattern, const char *directory,
342 int flags,
343 int (*errfunc) (const char *, int),
344 glob_t *pglob));
346 #if !defined _LIBC || !defined GLOB_ONLY_P
347 static int prefix_array __P ((const char *prefix, char **array, size_t n));
348 static int collated_compare __P ((const __ptr_t, const __ptr_t));
351 /* Find the end of the sub-pattern in a brace expression. We define
352 this as an inline function if the compiler permits. */
353 static
354 #if __GNUC__ - 0 >= 2
355 inline
356 #endif
357 const char *
358 next_brace_sub (cp)
359 const char *cp;
361 unsigned int depth = 0;
362 while (*cp != '\0' && (*cp != '}' || depth--) && (*cp != ',' || depth))
363 if (*cp++ == '{')
364 depth++;
365 return *cp != '\0' ? cp : NULL;
368 #endif /* !GLOB_ONLY_P */
370 /* Do glob searching for PATTERN, placing results in PGLOB.
371 The bits defined above may be set in FLAGS.
372 If a directory cannot be opened or read and ERRFUNC is not nil,
373 it is called with the pathname that caused the error, and the
374 `errno' value from the failing call; if it returns non-zero
375 `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
376 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
377 Otherwise, `glob' returns zero. */
379 glob (pattern, flags, errfunc, pglob)
380 const char *pattern;
381 int flags;
382 int (*errfunc) __P ((const char *, int));
383 glob_t *pglob;
385 const char *filename;
386 const char *dirname;
387 size_t dirlen;
388 int status;
389 size_t oldcount;
391 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
393 __set_errno (EINVAL);
394 return -1;
397 if (!(flags & GLOB_DOOFFS))
398 /* Have to do this so `globfree' knows where to start freeing. It
399 also makes all the code that uses gl_offs simpler. */
400 pglob->gl_offs = 0;
402 if (flags & GLOB_BRACE)
404 const char *begin = strchr (pattern, '{');
405 if (begin != NULL)
407 /* Allocate working buffer large enough for our work. Note that
408 we have at least an opening and closing brace. */
409 size_t firstc;
410 char *alt_start;
411 const char *p;
412 const char *next;
413 const char *rest;
414 size_t rest_len;
415 #ifdef __GNUC__
416 char onealt[strlen (pattern) - 1];
417 #else
418 char *onealt = (char *) malloc (strlen (pattern) - 1);
419 if (onealt == NULL)
421 if (!(flags & GLOB_APPEND))
422 globfree (pglob);
423 return GLOB_NOSPACE;
425 #endif
427 /* We know the prefix for all sub-patterns. */
428 #ifdef HAVE_MEMPCPY
429 alt_start = mempcpy (onealt, pattern, begin - pattern);
430 #else
431 memcpy (onealt, pattern, begin - pattern);
432 alt_start = &onealt[begin - pattern];
433 #endif
435 /* Find the first sub-pattern and at the same time find the
436 rest after the closing brace. */
437 next = next_brace_sub (begin + 1);
438 if (next == NULL)
440 /* It is an illegal expression. */
441 #ifndef __GNUC__
442 free (onealt);
443 #endif
444 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
447 /* Now find the end of the whole brace expression. */
448 rest = next;
449 while (*rest != '}')
451 rest = next_brace_sub (rest + 1);
452 if (rest == NULL)
454 /* It is an illegal expression. */
455 #ifndef __GNUC__
456 free (onealt);
457 #endif
458 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
461 /* Please note that we now can be sure the brace expression
462 is well-formed. */
463 rest_len = strlen (++rest) + 1;
465 /* We have a brace expression. BEGIN points to the opening {,
466 NEXT points past the terminator of the first element, and END
467 points past the final }. We will accumulate result names from
468 recursive runs for each brace alternative in the buffer using
469 GLOB_APPEND. */
471 if (!(flags & GLOB_APPEND))
473 /* This call is to set a new vector, so clear out the
474 vector so we can append to it. */
475 pglob->gl_pathc = 0;
476 pglob->gl_pathv = NULL;
478 firstc = pglob->gl_pathc;
480 p = begin + 1;
481 while (1)
483 int result;
485 /* Construct the new glob expression. */
486 #ifdef HAVE_MEMPCPY
487 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
488 #else
489 memcpy (alt_start, p, next - p);
490 memcpy (&alt_start[next - p], rest, rest_len);
491 #endif
493 result = glob (onealt,
494 ((flags & ~(GLOB_NOCHECK|GLOB_NOMAGIC))
495 | GLOB_APPEND), errfunc, pglob);
497 /* If we got an error, return it. */
498 if (result && result != GLOB_NOMATCH)
500 #ifndef __GNUC__
501 free (onealt);
502 #endif
503 if (!(flags & GLOB_APPEND))
504 globfree (pglob);
505 return result;
508 if (*next == '}')
509 /* We saw the last entry. */
510 break;
512 p = next + 1;
513 next = next_brace_sub (p);
514 assert (next != NULL);
517 #ifndef __GNUC__
518 free (onealt);
519 #endif
521 if (pglob->gl_pathc != firstc)
522 /* We found some entries. */
523 return 0;
524 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
525 return GLOB_NOMATCH;
529 /* Find the filename. */
530 filename = strrchr (pattern, '/');
531 #if defined __MSDOS__ || defined WINDOWS32
532 /* The case of "d:pattern". Since `:' is not allowed in
533 file names, we can safely assume that wherever it
534 happens in pattern, it signals the filename part. This
535 is so we could some day support patterns like "[a-z]:foo". */
536 if (filename == NULL)
537 filename = strchr (pattern, ':');
538 #endif /* __MSDOS__ || WINDOWS32 */
539 if (filename == NULL)
541 /* This can mean two things: a simple name or "~name". The latter
542 case is nothing but a notation for a directory. */
543 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
545 dirname = pattern;
546 dirlen = strlen (pattern);
548 /* Set FILENAME to NULL as a special flag. This is ugly but
549 other solutions would require much more code. We test for
550 this special case below. */
551 filename = NULL;
553 else
555 filename = pattern;
556 #ifdef _AMIGA
557 dirname = "";
558 #else
559 dirname = ".";
560 #endif
561 dirlen = 0;
564 else if (filename == pattern)
566 /* "/pattern". */
567 dirname = "/";
568 dirlen = 1;
569 ++filename;
571 else
573 char *newp;
574 dirlen = filename - pattern;
575 #if defined __MSDOS__ || defined WINDOWS32
576 if (*filename == ':'
577 || (filename > pattern + 1 && filename[-1] == ':'))
579 char *drive_spec;
581 ++dirlen;
582 drive_spec = (char *) __alloca (dirlen + 1);
583 #ifdef HAVE_MEMPCPY
584 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
585 #else
586 memcpy (drive_spec, pattern, dirlen);
587 drive_spec[dirlen] = '\0';
588 #endif
589 /* For now, disallow wildcards in the drive spec, to
590 prevent infinite recursion in glob. */
591 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
592 return GLOB_NOMATCH;
593 /* If this is "d:pattern", we need to copy `:' to DIRNAME
594 as well. If it's "d:/pattern", don't remove the slash
595 from "d:/", since "d:" and "d:/" are not the same.*/
597 #endif
598 newp = (char *) __alloca (dirlen + 1);
599 #ifdef HAVE_MEMPCPY
600 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
601 #else
602 memcpy (newp, pattern, dirlen);
603 newp[dirlen] = '\0';
604 #endif
605 dirname = newp;
606 ++filename;
608 if (filename[0] == '\0'
609 #if defined __MSDOS__ || defined WINDOWS32
610 && dirname[dirlen - 1] != ':'
611 && (dirlen < 3 || dirname[dirlen - 2] != ':'
612 || dirname[dirlen - 1] != '/')
613 #endif
614 && dirlen > 1)
615 /* "pattern/". Expand "pattern", appending slashes. */
617 int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
618 if (val == 0)
619 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
620 | (flags & GLOB_MARK));
621 return val;
625 if (!(flags & GLOB_APPEND))
627 pglob->gl_pathc = 0;
628 if (!(flags & GLOB_DOOFFS))
629 pglob->gl_pathv = NULL;
630 else
632 size_t i;
633 pglob->gl_pathv = (char **) malloc ((pglob->gl_offs + 1)
634 * sizeof (char *));
635 if (pglob->gl_pathv == NULL)
636 return GLOB_NOSPACE;
638 for (i = 0; i <= pglob->gl_offs; ++i)
639 pglob->gl_pathv[i] = NULL;
643 oldcount = pglob->gl_pathc + pglob->gl_offs;
645 #ifndef VMS
646 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
648 if (dirname[1] == '\0' || dirname[1] == '/')
650 /* Look up home directory. */
651 const char *home_dir = getenv ("HOME");
652 # ifdef _AMIGA
653 if (home_dir == NULL || home_dir[0] == '\0')
654 home_dir = "SYS:";
655 # else
656 # ifdef WINDOWS32
657 if (home_dir == NULL || home_dir[0] == '\0')
658 home_dir = "c:/users/default"; /* poor default */
659 # else
660 if (home_dir == NULL || home_dir[0] == '\0')
662 int success;
663 char *name;
664 # if defined HAVE_GETLOGIN_R || defined _LIBC
665 size_t buflen = sysconf (_SC_LOGIN_NAME_MAX) + 1;
667 if (buflen == 0)
668 /* `sysconf' does not support _SC_LOGIN_NAME_MAX. Try
669 a moderate value. */
670 buflen = 20;
671 name = (char *) __alloca (buflen);
673 success = getlogin_r (name, buflen) >= 0;
674 # else
675 success = (name = getlogin ()) != NULL;
676 # endif
677 if (success)
679 struct passwd *p;
680 # if defined HAVE_GETPWNAM_R || defined _LIBC
681 long int pwbuflen = sysconf (_SC_GETPW_R_SIZE_MAX);
682 char *pwtmpbuf;
683 struct passwd pwbuf;
684 int save = errno;
686 if (pwbuflen == -1)
687 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.
688 Try a moderate value. */
689 pwbuflen = 1024;
690 pwtmpbuf = (char *) __alloca (pwbuflen);
692 while (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
693 != 0)
695 if (errno != ERANGE)
697 p = NULL;
698 break;
700 pwbuflen *= 2;
701 pwtmpbuf = (char *) __alloca (pwbuflen);
702 __set_errno (save);
704 # else
705 p = getpwnam (name);
706 # endif
707 if (p != NULL)
708 home_dir = p->pw_dir;
711 if (home_dir == NULL || home_dir[0] == '\0')
713 if (flags & GLOB_TILDE_CHECK)
714 return GLOB_NOMATCH;
715 else
716 home_dir = "~"; /* No luck. */
718 # endif /* WINDOWS32 */
719 # endif
720 /* Now construct the full directory. */
721 if (dirname[1] == '\0')
722 dirname = home_dir;
723 else
725 char *newp;
726 size_t home_len = strlen (home_dir);
727 newp = (char *) __alloca (home_len + dirlen);
728 # ifdef HAVE_MEMPCPY
729 mempcpy (mempcpy (newp, home_dir, home_len),
730 &dirname[1], dirlen);
731 # else
732 memcpy (newp, home_dir, home_len);
733 memcpy (&newp[home_len], &dirname[1], dirlen);
734 # endif
735 dirname = newp;
738 # if !defined _AMIGA && !defined WINDOWS32
739 else
741 char *end_name = strchr (dirname, '/');
742 const char *user_name;
743 const char *home_dir;
745 if (end_name == NULL)
746 user_name = dirname + 1;
747 else
749 char *newp;
750 newp = (char *) __alloca (end_name - dirname);
751 # ifdef HAVE_MEMPCPY
752 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
753 = '\0';
754 # else
755 memcpy (newp, dirname + 1, end_name - dirname);
756 newp[end_name - dirname - 1] = '\0';
757 # endif
758 user_name = newp;
761 /* Look up specific user's home directory. */
763 struct passwd *p;
764 # if defined HAVE_GETPWNAM_R || defined _LIBC
765 long int buflen = sysconf (_SC_GETPW_R_SIZE_MAX);
766 char *pwtmpbuf;
767 struct passwd pwbuf;
768 int save = errno;
770 if (buflen == -1)
771 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
772 moderate value. */
773 buflen = 1024;
774 pwtmpbuf = (char *) __alloca (buflen);
776 while (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) != 0)
778 if (errno != ERANGE)
780 p = NULL;
781 break;
783 buflen *= 2;
784 pwtmpbuf = __alloca (buflen);
785 __set_errno (save);
787 # else
788 p = getpwnam (user_name);
789 # endif
790 if (p != NULL)
791 home_dir = p->pw_dir;
792 else
793 home_dir = NULL;
795 /* If we found a home directory use this. */
796 if (home_dir != NULL)
798 char *newp;
799 size_t home_len = strlen (home_dir);
800 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
801 newp = (char *) __alloca (home_len + rest_len + 1);
802 # ifdef HAVE_MEMPCPY
803 *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
804 end_name, rest_len)) = '\0';
805 # else
806 memcpy (newp, home_dir, home_len);
807 memcpy (&newp[home_len], end_name, rest_len);
808 newp[home_len + rest_len] = '\0';
809 # endif
810 dirname = newp;
812 else
813 if (flags & GLOB_TILDE_CHECK)
814 /* We have to regard it as an error if we cannot find the
815 home directory. */
816 return GLOB_NOMATCH;
818 # endif /* Not Amiga && not WINDOWS32. */
820 #endif /* Not VMS. */
822 /* Now test whether we looked for "~" or "~NAME". In this case we
823 can give the answer now. */
824 if (filename == NULL)
826 struct stat st;
827 #ifdef HAVE_STAT64
828 struct stat64 st64;
829 #endif
831 /* Return the directory if we don't check for error or if it exists. */
832 if ((flags & GLOB_NOCHECK)
833 || (((flags & GLOB_ALTDIRFUNC)
834 ? ((*pglob->gl_stat) (dirname, &st) == 0
835 && S_ISDIR (st.st_mode))
836 : (__stat64 (dirname, &st64) == 0 && S_ISDIR (st64.st_mode)))))
838 int newcount = pglob->gl_pathc + pglob->gl_offs;
840 pglob->gl_pathv
841 = (char **) realloc (pglob->gl_pathv,
842 (newcount + 1 + 1) * sizeof (char *));
843 if (pglob->gl_pathv == NULL)
844 return GLOB_NOSPACE;
846 #if defined HAVE_STRDUP || defined _LIBC
847 pglob->gl_pathv[newcount] = strdup (dirname);
848 #else
850 size_t len = strlen (dirname) + 1;
851 char *dircopy = malloc (len);
852 if (dircopy != NULL)
853 pglob->gl_pathv[newcount] = memcpy (dircopy, dirname, len);
855 #endif
856 if (pglob->gl_pathv[newcount] == NULL)
858 free (pglob->gl_pathv);
859 return GLOB_NOSPACE;
861 pglob->gl_pathv[++newcount] = NULL;
862 ++pglob->gl_pathc;
863 pglob->gl_flags = flags;
865 return 0;
868 /* Not found. */
869 return GLOB_NOMATCH;
872 if (__glob_pattern_p (dirname, !(flags & GLOB_NOESCAPE)))
874 /* The directory name contains metacharacters, so we
875 have to glob for the directory, and then glob for
876 the pattern in each directory found. */
877 glob_t dirs;
878 size_t i;
880 if ((flags & GLOB_ALTDIRFUNC) != 0)
882 /* Use the alternative access functions also in the recursive
883 call. */
884 dirs.gl_opendir = pglob->gl_opendir;
885 dirs.gl_readdir = pglob->gl_readdir;
886 dirs.gl_closedir = pglob->gl_closedir;
887 dirs.gl_stat = pglob->gl_stat;
888 dirs.gl_lstat = pglob->gl_lstat;
891 status = glob (dirname,
892 ((flags & (GLOB_ERR | GLOB_NOCHECK | GLOB_NOESCAPE
893 | GLOB_ALTDIRFUNC))
894 | GLOB_NOSORT | GLOB_ONLYDIR),
895 errfunc, &dirs);
896 if (status != 0)
897 return status;
899 /* We have successfully globbed the preceding directory name.
900 For each name we found, call glob_in_dir on it and FILENAME,
901 appending the results to PGLOB. */
902 for (i = 0; i < dirs.gl_pathc; ++i)
904 int old_pathc;
906 #ifdef SHELL
908 /* Make globbing interruptible in the bash shell. */
909 extern int interrupt_state;
911 if (interrupt_state)
913 globfree (&dirs);
914 return GLOB_ABORTED;
917 #endif /* SHELL. */
919 old_pathc = pglob->gl_pathc;
920 status = glob_in_dir (filename, dirs.gl_pathv[i],
921 ((flags | GLOB_APPEND) & ~GLOB_NOCHECK),
922 errfunc, pglob);
923 if (status == GLOB_NOMATCH)
924 /* No matches in this directory. Try the next. */
925 continue;
927 if (status != 0)
929 globfree (&dirs);
930 globfree (pglob);
931 return status;
934 /* Stick the directory on the front of each name. */
935 if (prefix_array (dirs.gl_pathv[i],
936 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
937 pglob->gl_pathc - old_pathc))
939 globfree (&dirs);
940 globfree (pglob);
941 return GLOB_NOSPACE;
945 flags |= GLOB_MAGCHAR;
947 /* We have ignored the GLOB_NOCHECK flag in the `glob_in_dir' calls.
948 But if we have not found any matching entry and the GLOB_NOCHECK
949 flag was set we must return the list consisting of the disrectory
950 names followed by the filename. */
951 if (pglob->gl_pathc + pglob->gl_offs == oldcount)
953 /* No matches. */
954 if (flags & GLOB_NOCHECK)
956 size_t filename_len = strlen (filename) + 1;
957 char **new_pathv;
958 int newcount = pglob->gl_pathc + pglob->gl_offs;
959 struct stat st;
960 #ifdef HAVE_STAT64
961 struct stat64 st64;
962 #endif
964 /* This is an pessimistic guess about the size. */
965 pglob->gl_pathv
966 = (char **) realloc (pglob->gl_pathv,
967 (newcount + dirs.gl_pathc + 1)
968 * sizeof (char *));
969 if (pglob->gl_pathv == NULL)
971 globfree (&dirs);
972 return GLOB_NOSPACE;
975 for (i = 0; i < dirs.gl_pathc; ++i)
977 const char *dir = dirs.gl_pathv[i];
978 size_t dir_len = strlen (dir);
980 /* First check whether this really is a directory. */
981 if (((flags & GLOB_ALTDIRFUNC)
982 ? ((*pglob->gl_stat) (dir, &st) != 0
983 || !S_ISDIR (st.st_mode))
984 : (__stat64 (dir, &st64) != 0
985 || !S_ISDIR (st64.st_mode))))
986 /* No directory, ignore this entry. */
987 continue;
989 pglob->gl_pathv[newcount] = malloc (dir_len + 1
990 + filename_len);
991 if (pglob->gl_pathv[newcount] == NULL)
993 globfree (&dirs);
994 globfree (pglob);
995 return GLOB_NOSPACE;
998 #ifdef HAVE_MEMPCPY
999 mempcpy (mempcpy (mempcpy (pglob->gl_pathv[newcount],
1000 dir, dir_len),
1001 "/", 1),
1002 filename, filename_len);
1003 #else
1004 memcpy (pglob->gl_pathv[newcount], dir, dir_len);
1005 pglob->gl_pathv[newcount][dir_len] = '/';
1006 memcpy (&pglob->gl_pathv[newcount][dir_len + 1],
1007 filename, filename_len);
1008 #endif
1009 ++pglob->gl_pathc;
1010 ++newcount;
1013 pglob->gl_pathv[newcount] = NULL;
1014 pglob->gl_flags = flags;
1016 /* Now we know how large the gl_pathv vector must be. */
1017 new_pathv = (char **) realloc (pglob->gl_pathv,
1018 ((newcount + 1)
1019 * sizeof (char *)));
1020 if (new_pathv != NULL)
1021 pglob->gl_pathv = new_pathv;
1023 else
1025 globfree (&dirs);
1026 return GLOB_NOMATCH;
1030 globfree (&dirs);
1032 else
1034 int old_pathc = pglob->gl_pathc;
1036 status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
1037 if (status != 0)
1038 return status;
1040 if (dirlen > 0)
1042 /* Stick the directory on the front of each name. */
1043 if (prefix_array (dirname,
1044 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
1045 pglob->gl_pathc - old_pathc))
1047 globfree (pglob);
1048 return GLOB_NOSPACE;
1053 if (flags & GLOB_MARK)
1055 /* Append slashes to directory names. */
1056 size_t i;
1057 struct stat st;
1058 #ifdef HAVE_STAT64
1059 struct stat64 st64;
1060 #endif
1062 for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)
1063 if (((flags & GLOB_ALTDIRFUNC)
1064 ? ((*pglob->gl_stat) (pglob->gl_pathv[i], &st) == 0
1065 && S_ISDIR (st.st_mode))
1066 : (__stat64 (pglob->gl_pathv[i], &st64) == 0
1067 && S_ISDIR (st64.st_mode))))
1069 size_t len = strlen (pglob->gl_pathv[i]) + 2;
1070 char *new = realloc (pglob->gl_pathv[i], len);
1071 if (new == NULL)
1073 globfree (pglob);
1074 return GLOB_NOSPACE;
1076 strcpy (&new[len - 2], "/");
1077 pglob->gl_pathv[i] = new;
1081 if (!(flags & GLOB_NOSORT))
1083 /* Sort the vector. */
1084 qsort ((__ptr_t) &pglob->gl_pathv[oldcount],
1085 pglob->gl_pathc + pglob->gl_offs - oldcount,
1086 sizeof (char *), collated_compare);
1089 return 0;
1093 #if !defined _LIBC || !defined GLOB_ONLY_P
1095 /* Free storage allocated in PGLOB by a previous `glob' call. */
1096 void
1097 globfree (pglob)
1098 register glob_t *pglob;
1100 if (pglob->gl_pathv != NULL)
1102 size_t i;
1103 for (i = 0; i < pglob->gl_pathc; ++i)
1104 if (pglob->gl_pathv[pglob->gl_offs + i] != NULL)
1105 free ((__ptr_t) pglob->gl_pathv[pglob->gl_offs + i]);
1106 free ((__ptr_t) pglob->gl_pathv);
1111 /* Do a collated comparison of A and B. */
1112 static int
1113 collated_compare (a, b)
1114 const __ptr_t a;
1115 const __ptr_t b;
1117 const char *const s1 = *(const char *const * const) a;
1118 const char *const s2 = *(const char *const * const) b;
1120 if (s1 == s2)
1121 return 0;
1122 if (s1 == NULL)
1123 return 1;
1124 if (s2 == NULL)
1125 return -1;
1126 return strcoll (s1, s2);
1130 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1131 elements in place. Return nonzero if out of memory, zero if successful.
1132 A slash is inserted between DIRNAME and each elt of ARRAY,
1133 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1134 static int
1135 prefix_array (dirname, array, n)
1136 const char *dirname;
1137 char **array;
1138 size_t n;
1140 register size_t i;
1141 size_t dirlen = strlen (dirname);
1142 #if defined __MSDOS__ || defined WINDOWS32
1143 int sep_char = '/';
1144 # define DIRSEP_CHAR sep_char
1145 #else
1146 # define DIRSEP_CHAR '/'
1147 #endif
1149 if (dirlen == 1 && dirname[0] == '/')
1150 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1151 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1152 dirlen = 0;
1153 #if defined __MSDOS__ || defined WINDOWS32
1154 else if (dirlen > 1)
1156 if (dirname[dirlen - 1] == '/' && dirname[dirlen - 2] == ':')
1157 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1158 --dirlen;
1159 else if (dirname[dirlen - 1] == ':')
1161 /* DIRNAME is "d:". Use `:' instead of `/'. */
1162 --dirlen;
1163 sep_char = ':';
1166 #endif
1168 for (i = 0; i < n; ++i)
1170 size_t eltlen = strlen (array[i]) + 1;
1171 char *new = (char *) malloc (dirlen + 1 + eltlen);
1172 if (new == NULL)
1174 while (i > 0)
1175 free ((__ptr_t) array[--i]);
1176 return 1;
1179 #ifdef HAVE_MEMPCPY
1181 char *endp = (char *) mempcpy (new, dirname, dirlen);
1182 *endp++ = DIRSEP_CHAR;
1183 mempcpy (endp, array[i], eltlen);
1185 #else
1186 memcpy (new, dirname, dirlen);
1187 new[dirlen] = DIRSEP_CHAR;
1188 memcpy (&new[dirlen + 1], array[i], eltlen);
1189 #endif
1190 free ((__ptr_t) array[i]);
1191 array[i] = new;
1194 return 0;
1198 /* We must not compile this function twice. */
1199 #if !defined _LIBC || !defined NO_GLOB_PATTERN_P
1200 /* Return nonzero if PATTERN contains any metacharacters.
1201 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
1203 __glob_pattern_p (pattern, quote)
1204 const char *pattern;
1205 int quote;
1207 register const char *p;
1208 int open = 0;
1210 for (p = pattern; *p != '\0'; ++p)
1211 switch (*p)
1213 case '?':
1214 case '*':
1215 return 1;
1217 case '\\':
1218 if (quote && p[1] != '\0')
1219 ++p;
1220 break;
1222 case '[':
1223 open = 1;
1224 break;
1226 case ']':
1227 if (open)
1228 return 1;
1229 break;
1232 return 0;
1234 # ifdef _LIBC
1235 weak_alias (__glob_pattern_p, glob_pattern_p)
1236 # endif
1237 #endif
1239 #endif /* !GLOB_ONLY_P */
1242 /* Like `glob', but PATTERN is a final pathname component,
1243 and matches are searched for in DIRECTORY.
1244 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1245 The GLOB_APPEND flag is assumed to be set (always appends). */
1246 static int
1247 glob_in_dir (pattern, directory, flags, errfunc, pglob)
1248 const char *pattern;
1249 const char *directory;
1250 int flags;
1251 int (*errfunc) __P ((const char *, int));
1252 glob_t *pglob;
1254 __ptr_t stream = NULL;
1255 struct globlink
1257 struct globlink *next;
1258 char *name;
1260 struct globlink *names = NULL;
1261 size_t nfound;
1262 int meta;
1263 int save;
1265 meta = __glob_pattern_p (pattern, !(flags & GLOB_NOESCAPE));
1266 if (meta == 0 && (flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
1268 /* We need not do any tests. The PATTERN contains no meta
1269 characters and we must not return an error therefore the
1270 result will always contain exactly one name. */
1271 flags |= GLOB_NOCHECK;
1272 nfound = 0;
1274 else if (meta == 0 &&
1275 ((flags & GLOB_NOESCAPE) || strchr(pattern, '\\') == NULL))
1277 /* Since we use the normal file functions we can also use stat()
1278 to verify the file is there. */
1279 struct stat st;
1280 # ifdef HAVE_STAT64
1281 struct stat64 st64;
1282 # endif
1283 size_t patlen = strlen (pattern);
1284 size_t dirlen = strlen (directory);
1285 char *fullname = (char *) __alloca (dirlen + 1 + patlen + 1);
1287 # ifdef HAVE_MEMPCPY
1288 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1289 "/", 1),
1290 pattern, patlen + 1);
1291 # else
1292 memcpy (fullname, directory, dirlen);
1293 fullname[dirlen] = '/';
1294 memcpy (&fullname[dirlen + 1], pattern, patlen + 1);
1295 # endif
1296 if (((flags & GLOB_ALTDIRFUNC)
1297 ? (*pglob->gl_stat) (fullname, &st)
1298 : __stat64 (fullname, &st64)) == 0)
1299 /* We found this file to be existing. Now tell the rest
1300 of the function to copy this name into the result. */
1301 flags |= GLOB_NOCHECK;
1303 nfound = 0;
1305 else
1307 if (pattern[0] == '\0')
1309 /* This is a special case for matching directories like in
1310 "*a/". */
1311 names = (struct globlink *) __alloca (sizeof (struct globlink));
1312 names->name = (char *) malloc (1);
1313 if (names->name == NULL)
1314 goto memory_error;
1315 names->name[0] = '\0';
1316 names->next = NULL;
1317 nfound = 1;
1318 meta = 0;
1320 else
1322 stream = ((flags & GLOB_ALTDIRFUNC)
1323 ? (*pglob->gl_opendir) (directory)
1324 : (__ptr_t) opendir (directory));
1325 if (stream == NULL)
1327 if (errno != ENOTDIR
1328 && ((errfunc != NULL && (*errfunc) (directory, errno))
1329 || (flags & GLOB_ERR)))
1330 return GLOB_ABORTED;
1331 nfound = 0;
1332 meta = 0;
1334 else
1336 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1337 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1338 #if defined _AMIGA || defined VMS
1339 | FNM_CASEFOLD
1340 #endif
1342 nfound = 0;
1343 flags |= GLOB_MAGCHAR;
1345 while (1)
1347 const char *name;
1348 size_t len;
1349 #if defined HAVE_DIRENT64 && !defined COMPILE_GLOB64
1350 struct dirent64 *d;
1351 struct dirent64 d64;
1353 if (flags & GLOB_ALTDIRFUNC)
1355 struct dirent *d32 = (*pglob->gl_readdir) (stream);
1356 if (d32 != NULL)
1358 CONVERT_DIRENT_DIRENT64 (&d64, d32);
1359 d = &d64;
1361 else
1362 d = NULL;
1364 else
1365 d = __readdir64 ((DIR *) stream);
1366 #else
1367 struct dirent *d = ((flags & GLOB_ALTDIRFUNC)
1368 ? ((struct dirent *)
1369 (*pglob->gl_readdir) (stream))
1370 : __readdir ((DIR *) stream));
1371 #endif
1372 if (d == NULL)
1373 break;
1374 if (! REAL_DIR_ENTRY (d))
1375 continue;
1377 #ifdef HAVE_D_TYPE
1378 /* If we shall match only directories use the information
1379 provided by the dirent call if possible. */
1380 if ((flags & GLOB_ONLYDIR)
1381 && d->d_type != DT_UNKNOWN && d->d_type != DT_DIR)
1382 continue;
1383 #endif
1385 name = d->d_name;
1387 if (fnmatch (pattern, name, fnm_flags) == 0)
1389 struct globlink *new = (struct globlink *)
1390 __alloca (sizeof (struct globlink));
1391 len = NAMLEN (d);
1392 new->name = (char *) malloc (len + 1);
1393 if (new->name == NULL)
1394 goto memory_error;
1395 #ifdef HAVE_MEMPCPY
1396 *((char *) mempcpy ((__ptr_t) new->name, name, len))
1397 = '\0';
1398 #else
1399 memcpy ((__ptr_t) new->name, name, len);
1400 new->name[len] = '\0';
1401 #endif
1402 new->next = names;
1403 names = new;
1404 ++nfound;
1411 if (nfound == 0 && (flags & GLOB_NOCHECK))
1413 size_t len = strlen (pattern);
1414 nfound = 1;
1415 names = (struct globlink *) __alloca (sizeof (struct globlink));
1416 names->next = NULL;
1417 names->name = (char *) malloc (len + 1);
1418 if (names->name == NULL)
1419 goto memory_error;
1420 #ifdef HAVE_MEMPCPY
1421 *((char *) mempcpy (names->name, pattern, len)) = '\0';
1422 #else
1423 memcpy (names->name, pattern, len);
1424 names->name[len] = '\0';
1425 #endif
1428 if (nfound != 0)
1430 pglob->gl_pathv
1431 = (char **) realloc (pglob->gl_pathv,
1432 (pglob->gl_pathc + pglob->gl_offs + nfound + 1)
1433 * sizeof (char *));
1434 if (pglob->gl_pathv == NULL)
1435 goto memory_error;
1437 for (; names != NULL; names = names->next)
1438 pglob->gl_pathv[pglob->gl_offs + pglob->gl_pathc++] = names->name;
1439 pglob->gl_pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
1441 pglob->gl_flags = flags;
1444 save = errno;
1445 if (stream != NULL)
1447 if (flags & GLOB_ALTDIRFUNC)
1448 (*pglob->gl_closedir) (stream);
1449 else
1450 closedir ((DIR *) stream);
1452 __set_errno (save);
1454 return nfound == 0 ? GLOB_NOMATCH : 0;
1456 memory_error:
1458 int save = errno;
1459 if (flags & GLOB_ALTDIRFUNC)
1460 (*pglob->gl_closedir) (stream);
1461 else
1462 closedir ((DIR *) stream);
1463 __set_errno (save);
1465 while (names != NULL)
1467 if (names->name != NULL)
1468 free ((__ptr_t) names->name);
1469 names = names->next;
1471 return GLOB_NOSPACE;
1474 #endif /* Not ELIDE_CODE. */