Debian Codegraph @

lib/glob.c

raw
1 /* Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
2 2023 Free Software Foundation, Inc.
3
4 This library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Library General Public License as
6 published by the Free Software Foundation; either version 2 of the
7 License, or (at your option) any later version.
8
9 This 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 Library General Public License for more details.
13
14 You should have received a copy of the GNU Library General Public License
15 along with this library; see the file COPYING.LIB. If not, write to the Free
16 Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
17 USA. */
18
19 /* AIX requires this to be the first thing in the file. */
20 #if defined _AIX && !defined __GNUC__
21 #pragma alloca
22 #endif
23
24 #ifdef HAVE_CONFIG_H
25 # include <config.h>
26 #endif
27
28 /* Enable GNU extensions in glob.h. */
29 #ifndef _GNU_SOURCE
30 # define _GNU_SOURCE 1
31 #endif
32
33 #include <errno.h>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36
37 /* Outcomment the following line for production quality code. */
38 /* #define NDEBUG 1 */
39 #include <assert.h>
40
41 /* Comment out all this code if we are using the GNU C Library, and are not
42 actually compiling the library itself. This code is part of the GNU C
43 Library, but also included in many other GNU distributions. Compiling
44 and linking in this code is a waste when using the GNU C library
45 (especially if it is a shared library). Rather than having every GNU
46 program understand `configure --with-gnu-libc' and omit the object files,
47 it is simpler to just do this in the source for each such file. */
48
49 #define GLOB_INTERFACE_VERSION 1
50 #if defined _LIBC
51 # define ELIDE_CODE
52 #elif 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
58
59 #ifndef ELIDE_CODE
60
61 #if defined STDC_HEADERS || defined __GNU_LIBRARY__
62 # include <stddef.h>
63 #endif
64
65 #if defined HAVE_UNISTD_H
66 # include <unistd.h>
67 # ifndef POSIX
68 # ifdef _POSIX_VERSION
69 # define POSIX
70 # endif
71 # endif
72 #endif
73
74 #if !defined _AMIGA && !defined VMS && !defined WINDOWS32
75 # include <pwd.h>
76 #endif
77
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
84
85 #if defined HAVE_DIRENT_H || defined __GNU_LIBRARY__
86 # include <dirent.h>
87 # define NAMLEN(dirent) strlen((dirent)->d_name)
88 #else
89 # define dirent direct
90 # define NAMLEN(dirent) (dirent)->d_namlen
91 # ifdef HAVE_SYS_NDIR_H
92 # include <sys/ndir.h>
93 # endif
94 # ifdef HAVE_SYS_DIR_H
95 # include <sys/dir.h>
96 # endif
97 # ifdef HAVE_NDIR_H
98 # include <ndir.h>
99 # endif
100 # ifdef HAVE_VMSDIR_H
101 # include "vmsdir.h"
102 # endif /* HAVE_VMSDIR_H */
103 #endif
104
105 /* In GNU systems, <dirent.h> defines this macro for us. */
106 #ifdef _D_NAMLEN
107 # undef NAMLEN
108 # define NAMLEN(d) _D_NAMLEN(d)
109 #endif
110
111 /* When used in the GNU libc the symbol _DIRENT_HAVE_D_TYPE is available
112 if the `d_type' member for `struct dirent' is available. */
113 #if defined(_DIRENT_HAVE_D_TYPE) || defined(HAVE_STRUCT_DIRENT_D_TYPE)
114 # define HAVE_D_TYPE 1
115 #endif
116
117
118 #if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
119 /* Posix does not require that the d_ino field be present, and some
120 systems do not provide it. */
121 # define REAL_DIR_ENTRY(dp) 1
122 #else
123 # define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
124 #endif /* POSIX */
125
126 #include <stdlib.h>
127 #include <string.h>
128
129 #if !defined HAVE_STRCOLL
130 # define strcoll strcmp
131 #endif
132
133 #if !defined HAVE_MEMPCPY && __GLIBC__ - 0 == 2 && __GLIBC_MINOR__ >= 1
134 # define HAVE_MEMPCPY 1
135 # undef mempcpy
136 # define mempcpy(Dest, Src, Len) __mempcpy (Dest, Src, Len)
137 #endif
138
139 #if !defined __alloca && !defined __GNU_LIBRARY__
140
141 # ifdef __GNUC__
142 # undef alloca
143 # define alloca(n) __builtin_alloca (n)
144 # else /* Not GCC. */
145 # ifdef HAVE_ALLOCA_H
146 # include <alloca.h>
147 # else /* Not HAVE_ALLOCA_H. */
148 # ifndef _AIX
149 # ifdef WINDOWS32
150 # include <malloc.h>
151 # else
152 extern char *alloca ();
153 # endif /* WINDOWS32 */
154 # endif /* Not _AIX. */
155 # endif /* sparc or HAVE_ALLOCA_H. */
156 # endif /* GCC. */
157 #endif
158
159 #ifndef __GNU_LIBRARY__
160 # ifdef STAT_MACROS_BROKEN
161 # undef S_ISDIR
162 # endif
163 # ifndef S_ISDIR
164 # define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
165 # endif
166 #endif
167
168 /* Some system header files erroneously define these.
169 We want our own definitions from <fnmatch.h> to take precedence. */
170 #ifndef __GNU_LIBRARY__
171 # undef FNM_PATHNAME
172 # undef FNM_NOESCAPE
173 # undef FNM_PERIOD
174 #endif
175 #include <fnmatch.h>
176
177 /* Some system header files erroneously define these.
178 We want our own definitions from <glob.h> to take precedence. */
179 #ifndef __GNU_LIBRARY__
180 # undef GLOB_ERR
181 # undef GLOB_MARK
182 # undef GLOB_NOSORT
183 # undef GLOB_DOOFFS
184 # undef GLOB_NOCHECK
185 # undef GLOB_APPEND
186 # undef GLOB_NOESCAPE
187 # undef GLOB_PERIOD
188 #endif
189 #include <glob.h>
190
191 #if !defined __alloca
192 # define __alloca alloca
193 #endif
194
195 #ifdef HAVE_GETLOGIN_R
196 extern int getlogin_r (char *, size_t);
197 #else
198 extern char *getlogin (void);
199 #endif
200
201 static
202 #if __GNUC__ - 0 >= 2
203 inline
204 #endif
205 const char *next_brace_sub (const char *begin);
206 static int glob_in_dir (const char *pattern, const char *directory,
207 int flags,
208 int (*errfunc) (const char *, int),
209 glob_t *pglob);
210 static int prefix_array (const char *prefix, char **array, size_t n);
211 static int collated_compare (const void *, const void *);
212
213 #if !defined NO_GLOB_PATTERN_P
214 int __glob_pattern_p (const char *pattern, int quote);
215 #endif
216
217 /* Find the end of the sub-pattern in a brace expression. We define
218 this as an inline function if the compiler permits. */
219 static
220 #if __GNUC__ - 0 >= 2
221 inline
222 #endif
223 const char *
224 next_brace_sub (const char *begin)
225 {
226 unsigned int depth = 0;
227 const char *cp = begin;
228
229 while (1)
230 {
231 if (depth == 0)
232 {
233 if (*cp != ',' && *cp != '}' && *cp != '\0')
234 {
235 if (*cp == '{')
236 ++depth;
237 ++cp;
238 continue;
239 }
240 }
241 else
242 {
243 while (*cp != '\0' && (*cp != '}' || depth > 0))
244 {
245 if (*cp == '}')
246 --depth;
247 ++cp;
248 }
249 if (*cp == '\0')
250 /* An incorrectly terminated brace expression. */
251 return NULL;
252
253 continue;
254 }
255 break;
256 }
257
258 return cp;
259 }
260
261 /* Do glob searching for PATTERN, placing results in PGLOB.
262 The bits defined above may be set in FLAGS.
263 If a directory cannot be opened or read and ERRFUNC is not nil,
264 it is called with the pathname that caused the error, and the
265 `errno' value from the failing call; if it returns non-zero
266 `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
267 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
268 Otherwise, `glob' returns zero. */
269 int
270 glob (const char *pattern, int flags,
271 int (*errfunc) (const char *, int), glob_t *pglob)
272 {
273 const char *filename;
274 const char *dirname;
275 size_t dirlen;
276 int status;
277 size_t oldcount;
278
279 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
280 {
281 __set_errno (EINVAL);
282 return -1;
283 }
284
285 /* POSIX requires all slashes to be matched. This means that with
286 a trailing slash we must match only directories. */
287 if (pattern[0] && pattern[strlen (pattern) - 1] == '/')
288 flags |= GLOB_ONLYDIR;
289
290 if (flags & GLOB_BRACE)
291 {
292 const char *begin = strchr (pattern, '{');
293 if (begin != NULL)
294 {
295 /* Allocate working buffer large enough for our work. Note that
296 we have at least an opening and closing brace. */
297 size_t firstc;
298 char *alt_start;
299 const char *p;
300 const char *next;
301 const char *rest;
302 size_t rest_len;
303 #ifdef __GNUC__
304 char onealt[strlen (pattern) - 1];
305 #else
306 char *onealt = (char *) malloc (strlen (pattern) - 1);
307 if (onealt == NULL)
308 {
309 if (!(flags & GLOB_APPEND))
310 globfree (pglob);
311 return GLOB_NOSPACE;
312 }
313 #endif
314
315 /* We know the prefix for all sub-patterns. */
316 #ifdef HAVE_MEMPCPY
317 alt_start = mempcpy (onealt, pattern, begin - pattern);
318 #else
319 memcpy (onealt, pattern, begin - pattern);
320 alt_start = &onealt[begin - pattern];
321 #endif
322
323 /* Find the first sub-pattern and at the same time find the
324 rest after the closing brace. */
325 next = next_brace_sub (begin + 1);
326 if (next == NULL)
327 {
328 /* It is an illegal expression. */
329 #ifndef __GNUC__
330 free (onealt);
331 #endif
332 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
333 }
334
335 /* Now find the end of the whole brace expression. */
336 rest = next;
337 while (*rest != '}')
338 {
339 rest = next_brace_sub (rest + 1);
340 if (rest == NULL)
341 {
342 /* It is an illegal expression. */
343 #ifndef __GNUC__
344 free (onealt);
345 #endif
346 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
347 }
348 }
349 /* Please note that we now can be sure the brace expression
350 is well-formed. */
351 rest_len = strlen (++rest) + 1;
352
353 /* We have a brace expression. BEGIN points to the opening {,
354 NEXT points past the terminator of the first element, and END
355 points past the final }. We will accumulate result names from
356 recursive runs for each brace alternative in the buffer using
357 GLOB_APPEND. */
358
359 if (!(flags & GLOB_APPEND))
360 {
361 /* This call is to set a new vector, so clear out the
362 vector so we can append to it. */
363 pglob->gl_pathc = 0;
364 pglob->gl_pathv = NULL;
365 }
366 firstc = pglob->gl_pathc;
367
368 p = begin + 1;
369 while (1)
370 {
371 int result;
372
373 /* Construct the new glob expression. */
374 #ifdef HAVE_MEMPCPY
375 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
376 #else
377 memcpy (alt_start, p, next - p);
378 memcpy (&alt_start[next - p], rest, rest_len);
379 #endif
380
381 result = glob (onealt,
382 ((flags & ~(GLOB_NOCHECK|GLOB_NOMAGIC))
383 | GLOB_APPEND), errfunc, pglob);
384
385 /* If we got an error, return it. */
386 if (result && result != GLOB_NOMATCH)
387 {
388 #ifndef __GNUC__
389 free (onealt);
390 #endif
391 if (!(flags & GLOB_APPEND))
392 globfree (pglob);
393 return result;
394 }
395
396 if (*next == '}')
397 /* We saw the last entry. */
398 break;
399
400 p = next + 1;
401 next = next_brace_sub (p);
402 assert (next != NULL);
403 }
404
405 #ifndef __GNUC__
406 free (onealt);
407 #endif
408
409 if (pglob->gl_pathc != firstc)
410 /* We found some entries. */
411 return 0;
412 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
413 return GLOB_NOMATCH;
414 }
415 }
416
417 /* Find the filename. */
418 filename = strrchr (pattern, '/');
419 #if defined __MSDOS__ || defined WINDOWS32
420 /* The case of "d:pattern". Since `:' is not allowed in
421 file names, we can safely assume that wherever it
422 happens in pattern, it signals the filename part. This
423 is so we could some day support patterns like "[a-z]:foo". */
424 if (filename == NULL)
425 filename = strchr (pattern, ':');
426 #endif /* __MSDOS__ || WINDOWS32 */
427 if (filename == NULL)
428 {
429 /* This can mean two things: a simple name or "~name". The later
430 case is nothing but a notation for a directory. */
431 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
432 {
433 dirname = pattern;
434 dirlen = strlen (pattern);
435
436 /* Set FILENAME to NULL as a special flag. This is ugly but
437 other solutions would require much more code. We test for
438 this special case below. */
439 filename = NULL;
440 }
441 else
442 {
443 filename = pattern;
444 #ifdef _AMIGA
445 dirname = "";
446 #else
447 dirname = ".";
448 #endif
449 dirlen = 0;
450 }
451 }
452 else if (filename == pattern)
453 {
454 /* "/pattern". */
455 dirname = "/";
456 dirlen = 1;
457 ++filename;
458 }
459 else
460 {
461 char *newp;
462 dirlen = filename - pattern;
463 #if defined __MSDOS__ || defined WINDOWS32
464 if (*filename == ':'
465 || (filename > pattern + 1 && filename[-1] == ':'))
466 {
467 char *drive_spec;
468
469 ++dirlen;
470 drive_spec = (char *) __alloca (dirlen + 1);
471 #ifdef HAVE_MEMPCPY
472 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
473 #else
474 memcpy (drive_spec, pattern, dirlen);
475 drive_spec[dirlen] = '\0';
476 #endif
477 /* For now, disallow wildcards in the drive spec, to
478 prevent infinite recursion in glob. */
479 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
480 return GLOB_NOMATCH;
481 /* If this is "d:pattern", we need to copy `:' to DIRNAME
482 as well. If it's "d:/pattern", don't remove the slash
483 from "d:/", since "d:" and "d:/" are not the same.*/
484 }
485 #endif
486 newp = (char *) __alloca (dirlen + 1);
487 #ifdef HAVE_MEMPCPY
488 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
489 #else
490 memcpy (newp, pattern, dirlen);
491 newp[dirlen] = '\0';
492 #endif
493 dirname = newp;
494 ++filename;
495
496 if (filename[0] == '\0'
497 #if defined __MSDOS__ || defined WINDOWS32
498 && dirname[dirlen - 1] != ':'
499 && (dirlen < 3 || dirname[dirlen - 2] != ':'
500 || dirname[dirlen - 1] != '/')
501 #endif
502 && dirlen > 1)
503 /* "pattern/". Expand "pattern", appending slashes. */
504 {
505 int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
506 if (val == 0)
507 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
508 | (flags & GLOB_MARK));
509 return val;
510 }
511 }
512
513 if (!(flags & GLOB_APPEND))
514 {
515 pglob->gl_pathc = 0;
516 pglob->gl_pathv = NULL;
517 }
518
519 oldcount = pglob->gl_pathc;
520
521 #ifndef VMS
522 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
523 {
524 if (dirname[1] == '\0' || dirname[1] == '/')
525 {
526 /* Look up home directory. */
527 #ifdef VMS
528 /* This isn't obvious, RTLs of DECC and VAXC know about "HOME" */
529 const char *home_dir = getenv ("SYS$LOGIN");
530 #else
531 const char *home_dir = getenv ("HOME");
532 #endif
533 # ifdef _AMIGA
534 if (home_dir == NULL || home_dir[0] == '\0')
535 home_dir = "SYS:";
536 # else
537 # ifdef WINDOWS32
538 if (home_dir == NULL || home_dir[0] == '\0')
539 home_dir = "c:/users/default"; /* poor default */
540 # else
541 # ifdef VMS
542 /* Again, this isn't obvious, if "HOME" isn't known "SYS$LOGIN" should be set */
543 if (home_dir == NULL || home_dir[0] == '\0')
544 home_dir = "SYS$DISK:[]";
545 # else
546 if (home_dir == NULL || home_dir[0] == '\0')
547 {
548 int success;
549 char *name;
550 # if defined HAVE_GETLOGIN_R
551 size_t buflen = sysconf (_SC_LOGIN_NAME_MAX) + 1;
552
553 if (buflen == 0)
554 /* `sysconf' does not support _SC_LOGIN_NAME_MAX. Try
555 a moderate value. */
556 buflen = 20;
557 name = (char *) __alloca (buflen);
558
559 success = getlogin_r (name, buflen) >= 0;
560 # else
561 success = (name = getlogin ()) != NULL;
562 # endif
563 if (success)
564 {
565 struct passwd *p;
566 # if defined HAVE_GETPWNAM_R
567 size_t pwbuflen = sysconf (_SC_GETPW_R_SIZE_MAX);
568 char *pwtmpbuf;
569 struct passwd pwbuf;
570 int save = errno;
571
572 if (pwbuflen == -1)
573 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.
574 Try a moderate value. */
575 pwbuflen = 1024;
576 pwtmpbuf = (char *) __alloca (pwbuflen);
577
578 while (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
579 != 0)
580 {
581 if (errno != ERANGE)
582 {
583 p = NULL;
584 break;
585 }
586 pwbuflen *= 2;
587 pwtmpbuf = (char *) __alloca (pwbuflen);
588 __set_errno (save);
589 }
590 # else
591 p = getpwnam (name);
592 # endif
593 if (p != NULL)
594 home_dir = p->pw_dir;
595 }
596 }
597 if (home_dir == NULL || home_dir[0] == '\0')
598 {
599 if (flags & GLOB_TILDE_CHECK)
600 return GLOB_NOMATCH;
601 else
602 home_dir = "~"; /* No luck. */
603 }
604 # endif /* VMS */
605 # endif /* WINDOWS32 */
606 # endif
607 /* Now construct the full directory. */
608 if (dirname[1] == '\0')
609 dirname = home_dir;
610 else
611 {
612 char *newp;
613 size_t home_len = strlen (home_dir);
614 newp = (char *) __alloca (home_len + dirlen);
615 # ifdef HAVE_MEMPCPY
616 mempcpy (mempcpy (newp, home_dir, home_len),
617 &dirname[1], dirlen);
618 # else
619 memcpy (newp, home_dir, home_len);
620 memcpy (&newp[home_len], &dirname[1], dirlen);
621 # endif
622 dirname = newp;
623 }
624 }
625 # if !defined _AMIGA && !defined WINDOWS32 && !defined VMS
626 else
627 {
628 char *end_name = strchr (dirname, '/');
629 const char *user_name;
630 const char *home_dir;
631
632 if (end_name == NULL)
633 user_name = dirname + 1;
634 else
635 {
636 char *newp;
637 newp = (char *) __alloca (end_name - dirname);
638 # ifdef HAVE_MEMPCPY
639 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
640 = '\0';
641 # else
642 memcpy (newp, dirname + 1, end_name - dirname);
643 newp[end_name - dirname - 1] = '\0';
644 # endif
645 user_name = newp;
646 }
647
648 /* Look up specific user's home directory. */
649 {
650 struct passwd *p;
651 # if defined HAVE_GETPWNAM_R
652 size_t buflen = sysconf (_SC_GETPW_R_SIZE_MAX);
653 char *pwtmpbuf;
654 struct passwd pwbuf;
655 int save = errno;
656
657 if (buflen == -1)
658 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
659 moderate value. */
660 buflen = 1024;
661 pwtmpbuf = (char *) __alloca (buflen);
662
663 while (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) != 0)
664 {
665 if (errno != ERANGE)
666 {
667 p = NULL;
668 break;
669 }
670 buflen *= 2;
671 pwtmpbuf = __alloca (buflen);
672 __set_errno (save);
673 }
674 # else
675 p = getpwnam (user_name);
676 # endif
677 if (p != NULL)
678 home_dir = p->pw_dir;
679 else
680 home_dir = NULL;
681 }
682 /* If we found a home directory use this. */
683 if (home_dir != NULL)
684 {
685 char *newp;
686 size_t home_len = strlen (home_dir);
687 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
688 newp = (char *) __alloca (home_len + rest_len + 1);
689 # ifdef HAVE_MEMPCPY
690 *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
691 end_name, rest_len)) = '\0';
692 # else
693 memcpy (newp, home_dir, home_len);
694 memcpy (&newp[home_len], end_name, rest_len);
695 newp[home_len + rest_len] = '\0';
696 # endif
697 dirname = newp;
698 }
699 else
700 if (flags & GLOB_TILDE_CHECK)
701 /* We have to regard it as an error if we cannot find the
702 home directory. */
703 return GLOB_NOMATCH;
704 }
705 # endif /* Not Amiga && not WINDOWS32 && not VMS. */
706 }
707 #endif /* Not VMS. */
708
709 /* Now test whether we looked for "~" or "~NAME". In this case we
710 can give the answer now. */
711 if (filename == NULL)
712 {
713 struct stat st;
714
715 /* Return the directory if we don't check for error or if it exists. */
716 if ((flags & GLOB_NOCHECK)
717 || (((flags & GLOB_ALTDIRFUNC)
718 ? (*pglob->gl_stat) (dirname, &st)
719 : stat (dirname, &st)) == 0
720 && S_ISDIR (st.st_mode)))
721 {
722 pglob->gl_pathv
723 = (char **) realloc (pglob->gl_pathv,
724 (pglob->gl_pathc +
725 ((flags & GLOB_DOOFFS) ?
726 pglob->gl_offs : 0) +
727 1 + 1) *
728 sizeof (char *));
729 if (pglob->gl_pathv == NULL)
730 return GLOB_NOSPACE;
731
732 if (flags & GLOB_DOOFFS)
733 while (pglob->gl_pathc < pglob->gl_offs)
734 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
735
736 #if defined HAVE_STRDUP
737 pglob->gl_pathv[pglob->gl_pathc] = strdup (dirname);
738 #else
739 {
740 size_t len = strlen (dirname) + 1;
741 char *dircopy = malloc (len);
742 if (dircopy != NULL)
743 pglob->gl_pathv[pglob->gl_pathc] = memcpy (dircopy, dirname,
744 len);
745 }
746 #endif
747 if (pglob->gl_pathv[pglob->gl_pathc] == NULL)
748 {
749 free (pglob->gl_pathv);
750 return GLOB_NOSPACE;
751 }
752 pglob->gl_pathv[++pglob->gl_pathc] = NULL;
753 pglob->gl_flags = flags;
754
755 return 0;
756 }
757
758 /* Not found. */
759 return GLOB_NOMATCH;
760 }
761
762 if (__glob_pattern_p (dirname, !(flags & GLOB_NOESCAPE)))
763 {
764 /* The directory name contains metacharacters, so we
765 have to glob for the directory, and then glob for
766 the pattern in each directory found. */
767 glob_t dirs;
768 size_t i;
769
770 status = glob (dirname,
771 ((flags & (GLOB_ERR | GLOB_NOCHECK | GLOB_NOESCAPE))
772 | GLOB_NOSORT | GLOB_ONLYDIR),
773 errfunc, &dirs);
774 if (status != 0)
775 return status;
776
777 /* We have successfully globbed the preceding directory name.
778 For each name we found, call glob_in_dir on it and FILENAME,
779 appending the results to PGLOB. */
780 for (i = 0; i < dirs.gl_pathc; ++i)
781 {
782 size_t old_pathc;
783
784 #ifdef SHELL
785 {
786 /* Make globbing interruptible in the bash shell. */
787 extern int interrupt_state;
788
789 if (interrupt_state)
790 {
791 globfree (&dirs);
792 globfree (&files);
793 return GLOB_ABORTED;
794 }
795 }
796 #endif /* SHELL. */
797
798 old_pathc = pglob->gl_pathc;
799 status = glob_in_dir (filename, dirs.gl_pathv[i],
800 ((flags | GLOB_APPEND)
801 & ~(GLOB_NOCHECK | GLOB_ERR)),
802 errfunc, pglob);
803 if (status == GLOB_NOMATCH)
804 /* No matches in this directory. Try the next. */
805 continue;
806
807 if (status != 0)
808 {
809 globfree (&dirs);
810 globfree (pglob);
811 return status;
812 }
813
814 /* Stick the directory on the front of each name. */
815 if (prefix_array (dirs.gl_pathv[i],
816 &pglob->gl_pathv[old_pathc],
817 pglob->gl_pathc - old_pathc))
818 {
819 globfree (&dirs);
820 globfree (pglob);
821 return GLOB_NOSPACE;
822 }
823 }
824
825 flags |= GLOB_MAGCHAR;
826
827 /* We have ignored the GLOB_NOCHECK flag in the `glob_in_dir' calls.
828 But if we have not found any matching entry and thie GLOB_NOCHECK
829 flag was set we must return the list consisting of the disrectory
830 names followed by the filename. */
831 if (pglob->gl_pathc == oldcount)
832 {
833 /* No matches. */
834 if (flags & GLOB_NOCHECK)
835 {
836 size_t filename_len = strlen (filename) + 1;
837 char **new_pathv;
838 struct stat st;
839
840 /* This is an pessimistic guess about the size. */
841 pglob->gl_pathv
842 = (char **) realloc (pglob->gl_pathv,
843 (pglob->gl_pathc +
844 ((flags & GLOB_DOOFFS) ?
845 pglob->gl_offs : 0) +
846 dirs.gl_pathc + 1) *
847 sizeof (char *));
848 if (pglob->gl_pathv == NULL)
849 {
850 globfree (&dirs);
851 return GLOB_NOSPACE;
852 }
853
854 if (flags & GLOB_DOOFFS)
855 while (pglob->gl_pathc < pglob->gl_offs)
856 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
857
858 for (i = 0; i < dirs.gl_pathc; ++i)
859 {
860 const char *dir = dirs.gl_pathv[i];
861 size_t dir_len = strlen (dir);
862
863 /* First check whether this really is a directory. */
864 if (((flags & GLOB_ALTDIRFUNC)
865 ? (*pglob->gl_stat) (dir, &st) : stat (dir, &st)) != 0
866 || !S_ISDIR (st.st_mode))
867 /* No directory, ignore this entry. */
868 continue;
869
870 pglob->gl_pathv[pglob->gl_pathc] = malloc (dir_len + 1
871 + filename_len);
872 if (pglob->gl_pathv[pglob->gl_pathc] == NULL)
873 {
874 globfree (&dirs);
875 globfree (pglob);
876 return GLOB_NOSPACE;
877 }
878
879 #ifdef HAVE_MEMPCPY
880 mempcpy (mempcpy (mempcpy (pglob->gl_pathv[pglob->gl_pathc],
881 dir, dir_len),
882 "/", 1),
883 filename, filename_len);
884 #else
885 memcpy (pglob->gl_pathv[pglob->gl_pathc], dir, dir_len);
886 pglob->gl_pathv[pglob->gl_pathc][dir_len] = '/';
887 memcpy (&pglob->gl_pathv[pglob->gl_pathc][dir_len + 1],
888 filename, filename_len);
889 #endif
890 ++pglob->gl_pathc;
891 }
892
893 pglob->gl_pathv[pglob->gl_pathc] = NULL;
894 pglob->gl_flags = flags;
895
896 /* Now we know how large the gl_pathv vector must be. */
897 new_pathv = (char **) realloc (pglob->gl_pathv,
898 ((pglob->gl_pathc + 1)
899 * sizeof (char *)));
900 if (new_pathv != NULL)
901 pglob->gl_pathv = new_pathv;
902 }
903 else
904 return GLOB_NOMATCH;
905 }
906
907 globfree (&dirs);
908 }
909 else
910 {
911 status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
912 if (status != 0)
913 return status;
914
915 if (dirlen > 0)
916 {
917 /* Stick the directory on the front of each name. */
918 size_t ignore = oldcount;
919
920 if ((flags & GLOB_DOOFFS) && ignore < pglob->gl_offs)
921 ignore = pglob->gl_offs;
922
923 if (prefix_array (dirname,
924 &pglob->gl_pathv[ignore],
925 pglob->gl_pathc - ignore))
926 {
927 globfree (pglob);
928 return GLOB_NOSPACE;
929 }
930 }
931 }
932
933 if (flags & GLOB_MARK)
934 {
935 /* Append slashes to directory names. */
936 size_t i;
937 struct stat st;
938 for (i = oldcount; i < pglob->gl_pathc; ++i)
939 if (((flags & GLOB_ALTDIRFUNC)
940 ? (*pglob->gl_stat) (pglob->gl_pathv[i], &st)
941 : stat (pglob->gl_pathv[i], &st)) == 0
942 && S_ISDIR (st.st_mode))
943 {
944 size_t len = strlen (pglob->gl_pathv[i]) + 2;
945 char *new = realloc (pglob->gl_pathv[i], len);
946 if (new == NULL)
947 {
948 globfree (pglob);
949 return GLOB_NOSPACE;
950 }
951 strcpy (&new[len - 2], "/");
952 pglob->gl_pathv[i] = new;
953 }
954 }
955
956 if (!(flags & GLOB_NOSORT))
957 {
958 /* Sort the vector. */
959 size_t non_sort = oldcount;
960
961 if ((flags & GLOB_DOOFFS) && pglob->gl_offs > oldcount)
962 non_sort = pglob->gl_offs;
963
964 qsort ((void *) &pglob->gl_pathv[non_sort],
965 pglob->gl_pathc - non_sort,
966 sizeof (char *), collated_compare);
967 }
968
969 return 0;
970 }
971
972
973 /* Free storage allocated in PGLOB by a previous `glob' call. */
974 void
975 globfree (glob_t *pglob)
976 {
977 if (pglob->gl_pathv != NULL)
978 {
979 size_t i;
980 for (i = 0; i < pglob->gl_pathc; ++i)
981 if (pglob->gl_pathv[i] != NULL)
982 free (pglob->gl_pathv[i]);
983 free (pglob->gl_pathv);
984 }
985 }
986
987
988 /* Do a collated comparison of A and B. */
989 static int
990 collated_compare (const void *a, const void *b)
991 {
992 const char *const s1 = *(const char *const * const) a;
993 const char *const s2 = *(const char *const * const) b;
994
995 if (s1 == s2)
996 return 0;
997 if (s1 == NULL)
998 return 1;
999 if (s2 == NULL)
1000 return -1;
1001 return strcoll (s1, s2);
1002 }
1003
1004
1005 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1006 elements in place. Return nonzero if out of memory, zero if successful.
1007 A slash is inserted between DIRNAME and each elt of ARRAY,
1008 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1009 static int
1010 prefix_array (const char *dirname, char **array, size_t n)
1011 {
1012 size_t i;
1013 size_t dirlen = strlen (dirname);
1014 #if defined __MSDOS__ || defined WINDOWS32
1015 char sep_char = '/';
1016 # define DIRSEP_CHAR sep_char
1017 #else
1018 # define DIRSEP_CHAR '/'
1019 #endif
1020
1021 if (dirlen == 1 && dirname[0] == '/')
1022 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1023 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1024 dirlen = 0;
1025 #if defined __MSDOS__ || defined WINDOWS32
1026 else if (dirlen > 1)
1027 {
1028 if (dirname[dirlen - 1] == '/' && dirname[dirlen - 2] == ':')
1029 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1030 --dirlen;
1031 else if (dirname[dirlen - 1] == ':')
1032 {
1033 /* DIRNAME is "d:". Use `:' instead of `/'. */
1034 --dirlen;
1035 sep_char = ':';
1036 }
1037 }
1038 #endif
1039
1040 for (i = 0; i < n; ++i)
1041 {
1042 size_t eltlen = strlen (array[i]) + 1;
1043 char *new = (char *) malloc (dirlen + 1 + eltlen);
1044 if (new == NULL)
1045 {
1046 while (i > 0)
1047 free (array[--i]);
1048 return 1;
1049 }
1050
1051 #ifdef HAVE_MEMPCPY
1052 {
1053 char *endp = (char *) mempcpy (new, dirname, dirlen);
1054 *endp++ = DIRSEP_CHAR;
1055 mempcpy (endp, array[i], eltlen);
1056 }
1057 #else
1058 memcpy (new, dirname, dirlen);
1059 new[dirlen] = DIRSEP_CHAR;
1060 memcpy (&new[dirlen + 1], array[i], eltlen);
1061 #endif
1062 free (array[i]);
1063 array[i] = new;
1064 }
1065
1066 return 0;
1067 }
1068
1069
1070 /* We must not compile this function twice. */
1071 #if !defined NO_GLOB_PATTERN_P
1072 /* Return nonzero if PATTERN contains any metacharacters.
1073 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
1074 int
1075 __glob_pattern_p (const char *pattern, int quote)
1076 {
1077 const char *p;
1078 int open = 0;
1079
1080 for (p = pattern; *p != '\0'; ++p)
1081 switch (*p)
1082 {
1083 case '?':
1084 case '*':
1085 return 1;
1086
1087 case '\\':
1088 if (quote && p[1] != '\0')
1089 ++p;
1090 break;
1091
1092 case '[':
1093 open = 1;
1094 break;
1095
1096 case ']':
1097 if (open)
1098 return 1;
1099 break;
1100 }
1101
1102 return 0;
1103 }
1104 #endif
1105
1106
1107 /* Like `glob', but PATTERN is a final pathname component,
1108 and matches are searched for in DIRECTORY.
1109 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1110 The GLOB_APPEND flag is assumed to be set (always appends). */
1111 static int
1112 glob_in_dir (const char *pattern, const char *directory, int flags,
1113 int (*errfunc) (const char *, int), glob_t *pglob)
1114 {
1115 void *stream = NULL;
1116
1117 struct globlink
1118 {
1119 struct globlink *next;
1120 char *name;
1121 };
1122 struct globlink *names = NULL;
1123 size_t nfound;
1124 int meta;
1125 int save;
1126
1127 #ifdef VMS
1128 if (*directory == 0)
1129 directory = "[]";
1130 #endif
1131 meta = __glob_pattern_p (pattern, !(flags & GLOB_NOESCAPE));
1132 if (meta == 0)
1133 {
1134 if (flags & (GLOB_NOCHECK|GLOB_NOMAGIC))
1135 /* We need not do any tests. The PATTERN contains no meta
1136 characters and we must not return an error therefore the
1137 result will always contain exactly one name. */
1138 flags |= GLOB_NOCHECK;
1139 else
1140 {
1141 /* Since we use the normal file functions we can also use stat()
1142 to verify the file is there. */
1143 struct stat st;
1144 size_t patlen = strlen (pattern);
1145 size_t dirlen = strlen (directory);
1146 char *fullname = (char *) __alloca (dirlen + 1 + patlen + 1);
1147
1148 # ifdef HAVE_MEMPCPY
1149 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1150 "/", 1),
1151 pattern, patlen + 1);
1152 # else
1153 memcpy (fullname, directory, dirlen);
1154 fullname[dirlen] = '/';
1155 memcpy (&fullname[dirlen + 1], pattern, patlen + 1);
1156 # endif
1157 if (((flags & GLOB_ALTDIRFUNC)
1158 ? (*pglob->gl_stat) (fullname, &st)
1159 : stat (fullname, &st)) == 0)
1160 /* We found this file to be existing. Now tell the rest
1161 of the function to copy this name into the result. */
1162 flags |= GLOB_NOCHECK;
1163 }
1164
1165 nfound = 0;
1166 }
1167 else
1168 {
1169 if (pattern[0] == '\0')
1170 {
1171 /* This is a special case for matching directories like in
1172 "*a/". */
1173 names = (struct globlink *) __alloca (sizeof (struct globlink));
1174 names->name = (char *) malloc (1);
1175 if (names->name == NULL)
1176 goto memory_error;
1177 names->name[0] = '\0';
1178 names->next = NULL;
1179 nfound = 1;
1180 meta = 0;
1181 }
1182 else
1183 {
1184 stream = ((flags & GLOB_ALTDIRFUNC)
1185 ? (*pglob->gl_opendir) (directory)
1186 : (void *) opendir (directory));
1187 if (stream == NULL)
1188 {
1189 if (errno != ENOTDIR
1190 && ((errfunc != NULL && (*errfunc) (directory, errno))
1191 || (flags & GLOB_ERR)))
1192 return GLOB_ABORTED;
1193 nfound = 0;
1194 meta = 0;
1195 }
1196 else
1197 {
1198 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1199 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1200 #if defined HAVE_CASE_INSENSITIVE_FS
1201 | FNM_CASEFOLD
1202 #endif
1203 );
1204 nfound = 0;
1205 flags |= GLOB_MAGCHAR;
1206
1207 while (1)
1208 {
1209 const char *name;
1210 size_t len;
1211 struct dirent *d = ((flags & GLOB_ALTDIRFUNC)
1212 ? (*pglob->gl_readdir) (stream)
1213 : readdir ((DIR *) stream));
1214 if (d == NULL)
1215 break;
1216 if (! REAL_DIR_ENTRY (d))
1217 continue;
1218
1219 #ifdef HAVE_D_TYPE
1220 /* If we shall match only directories use the information
1221 provided by the dirent call if possible. */
1222 if ((flags & GLOB_ONLYDIR)
1223 && d->d_type != DT_UNKNOWN && d->d_type != DT_DIR && d->d_type != DT_LNK)
1224 continue;
1225 #endif
1226
1227 name = d->d_name;
1228
1229 if (fnmatch (pattern, name, fnm_flags) == 0)
1230 {
1231 struct globlink *new = (struct globlink *)
1232 __alloca (sizeof (struct globlink));
1233 len = NAMLEN (d);
1234 new->name = (char *) malloc (len + 1);
1235 if (new->name == NULL)
1236 goto memory_error;
1237 #ifdef HAVE_MEMPCPY
1238 *((char *) mempcpy (new->name, name, len)) = '\0';
1239 #else
1240 memcpy (new->name, name, len);
1241 new->name[len] = '\0';
1242 #endif
1243 new->next = names;
1244 names = new;
1245 ++nfound;
1246 }
1247 }
1248 }
1249 }
1250 }
1251
1252 if (nfound == 0 && (flags & GLOB_NOCHECK))
1253 {
1254 size_t len = strlen (pattern);
1255 nfound = 1;
1256 names = (struct globlink *) __alloca (sizeof (struct globlink));
1257 names->next = NULL;
1258 names->name = (char *) malloc (len + 1);
1259 if (names->name == NULL)
1260 goto memory_error;
1261 #ifdef HAVE_MEMPCPY
1262 *((char *) mempcpy (names->name, pattern, len)) = '\0';
1263 #else
1264 memcpy (names->name, pattern, len);
1265 names->name[len] = '\0';
1266 #endif
1267 }
1268
1269 if (nfound != 0)
1270 {
1271 pglob->gl_pathv
1272 = (char **) realloc (pglob->gl_pathv,
1273 (pglob->gl_pathc +
1274 ((flags & GLOB_DOOFFS) ? pglob->gl_offs : 0) +
1275 nfound + 1) *
1276 sizeof (char *));
1277 if (pglob->gl_pathv == NULL)
1278 goto memory_error;
1279
1280 if (flags & GLOB_DOOFFS)
1281 while (pglob->gl_pathc < pglob->gl_offs)
1282 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
1283
1284 for (; names != NULL; names = names->next)
1285 pglob->gl_pathv[pglob->gl_pathc++] = names->name;
1286 pglob->gl_pathv[pglob->gl_pathc] = NULL;
1287
1288 pglob->gl_flags = flags;
1289 }
1290
1291 save = errno;
1292 if (stream != NULL)
1293 {
1294 if (flags & GLOB_ALTDIRFUNC)
1295 (*pglob->gl_closedir) (stream);
1296 else
1297 closedir ((DIR *) stream);
1298 }
1299 __set_errno (save);
1300
1301 return nfound == 0 ? GLOB_NOMATCH : 0;
1302
1303 memory_error:
1304 {
1305 save = errno;
1306 if (flags & GLOB_ALTDIRFUNC)
1307 (*pglob->gl_closedir) (stream);
1308 else
1309 closedir ((DIR *) stream);
1310 __set_errno (save);
1311 }
1312 while (names != NULL)
1313 {
1314 if (names->name != NULL)
1315 free (names->name);
1316 names = names->next;
1317 }
1318 return GLOB_NOSPACE;
1319 }
1320
1321 #endif /* Not ELIDE_CODE. */