exp2l: Work around a NetBSD 10.0/i386 bug.
[gnulib.git] / lib / glob.c
blobdc1a915c054adc436c481ab38ffbd3297a3982cf
1 /* Copyright (C) 1991-2024 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, see
16 <https://www.gnu.org/licenses/>. */
18 #ifndef _LIBC
20 /* Don't use __attribute__ __nonnull__ in this compilation unit. Otherwise gcc
21 optimizes away the pattern == NULL test below. */
22 # define _GL_ARG_NONNULL(params)
24 # include <libc-config.h>
26 #endif
28 #include <glob.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <stdckdint.h>
35 #include <stddef.h>
36 #include <stdint.h>
37 #include <assert.h>
38 #include <unistd.h>
40 #if defined _WIN32 && ! defined __CYGWIN__
41 # define WINDOWS32
42 #endif
44 #ifndef WINDOWS32
45 # include <pwd.h>
46 #endif
48 #include <errno.h>
49 #include <dirent.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <alloca.h>
54 #ifdef _LIBC
55 # undef strdup
56 # define strdup(str) __strdup (str)
57 # define sysconf(id) __sysconf (id)
58 # define closedir(dir) __closedir (dir)
59 # define opendir(name) __opendir (name)
60 # undef dirfd
61 # define dirfd(str) __dirfd (str)
62 # define readdir(str) __readdir64 (str)
63 # define getpwnam_r(name, bufp, buf, len, res) \
64 __getpwnam_r (name, bufp, buf, len, res)
65 # define FLEXIBLE_ARRAY_MEMBER
66 # ifndef struct_stat
67 # define struct_stat struct stat
68 # endif
69 # ifndef struct_stat64
70 # define struct_stat64 struct stat64
71 # endif
72 # ifndef GLOB_LSTAT
73 # define GLOB_LSTAT gl_lstat
74 # endif
75 # ifndef GLOB_FSTATAT64
76 # define GLOB_FSTATAT64 __fstatat64
77 # endif
78 # include <shlib-compat.h>
79 #else /* !_LIBC */
80 # define __glob glob
81 # define __getlogin_r(buf, len) getlogin_r (buf, len)
82 # define __fxstatat64(_, d, f, st, flag) fstatat (d, f, st, flag)
83 # ifndef __MVS__
84 # define __alloca alloca
85 # endif
86 # define __readdir readdir
87 # define COMPILE_GLOB64
88 # define struct_stat struct stat
89 # define struct_stat64 struct stat
90 # define GLOB_LSTAT gl_lstat
91 # define GLOB_FSTATAT64 fstatat
92 #endif /* _LIBC */
94 #include <fnmatch.h>
96 #include <flexmember.h>
97 #include <glob_internal.h>
98 #include <scratch_buffer.h>
100 static const char *next_brace_sub (const char *begin, int flags) __THROWNL;
102 /* The type of ((struct dirent *) 0)->d_type is 'unsigned char' on most
103 platforms, but 'unsigned int' in the mingw from mingw.org. */
104 typedef uint_fast32_t dirent_type;
106 #if !defined _LIBC && !defined HAVE_STRUCT_DIRENT_D_TYPE
107 /* Any distinct values will do here.
108 Undef any existing macros out of the way. */
109 # undef DT_UNKNOWN
110 # undef DT_DIR
111 # undef DT_LNK
112 # define DT_UNKNOWN 0
113 # define DT_DIR 1
114 # define DT_LNK 2
115 #endif
117 /* A representation of a directory entry which does not depend on the
118 layout of struct dirent, or the size of ino_t. */
119 struct readdir_result
121 const char *name;
122 #if defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE
123 dirent_type type;
124 #endif
127 /* Initialize and return type member of struct readdir_result. */
128 static dirent_type
129 readdir_result_type (struct readdir_result d)
131 #if defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE
132 # define D_TYPE_TO_RESULT(source) (source)->d_type,
133 return d.type;
134 #else
135 # define D_TYPE_TO_RESULT(source)
136 return DT_UNKNOWN;
137 #endif
140 /* Construct an initializer for a struct readdir_result object from a
141 struct dirent *. No copy of the name is made. */
142 #define READDIR_RESULT_INITIALIZER(source) \
144 source->d_name, \
145 D_TYPE_TO_RESULT (source) \
148 /* Call gl_readdir on STREAM. This macro can be overridden to reduce
149 type safety if an old interface version needs to be supported. */
150 #ifndef GL_READDIR
151 # define GL_READDIR(pglob, stream) ((pglob)->gl_readdir (stream))
152 #endif
154 /* Extract name and type from directory entry. No copy of the name is
155 made. If SOURCE is NULL, result name is NULL. Keep in sync with
156 convert_dirent64 below. */
157 static struct readdir_result
158 convert_dirent (const struct dirent *source)
160 if (source == NULL)
162 struct readdir_result result = { NULL, };
163 return result;
165 struct readdir_result result = READDIR_RESULT_INITIALIZER (source);
166 return result;
169 #ifndef COMPILE_GLOB64
170 /* Like convert_dirent, but works on struct dirent64 instead. Keep in
171 sync with convert_dirent above. */
172 static struct readdir_result
173 convert_dirent64 (const struct dirent64 *source)
175 if (source == NULL)
177 struct readdir_result result = { NULL, };
178 return result;
180 struct readdir_result result = READDIR_RESULT_INITIALIZER (source);
181 return result;
183 #endif
185 #ifndef _LIBC
186 /* The results of opendir() in this file are used with dirfd. But they are
187 not used with fchdir, and we do not leak fds to any single-threaded code
188 that could use stdio, therefore save some unnecessary recursion in
189 fchdir.c and opendir_safer.c. */
190 # ifndef GNULIB_defined_DIR
191 # ifdef GNULIB_defined_opendir
192 # undef opendir
193 # endif
194 # ifdef GNULIB_defined_closedir
195 # undef closedir
196 # endif
197 # endif
199 /* Just use malloc. */
200 # define __libc_use_alloca(n) false
201 # define alloca_account(len, avar) ((void) (len), (void) (avar), (void *) 0)
202 # define extend_alloca_account(buf, len, newlen, avar) \
203 ((void) (buf), (void) (len), (void) (newlen), (void) (avar), (void *) 0)
204 #endif
206 static int
207 glob_lstat (glob_t *pglob, int flags, const char *fullname)
209 /* Use on glob-lstat-compat.c to provide a compat symbol which does not
210 use lstat / gl_lstat. */
211 union
213 struct_stat st;
214 struct_stat64 st64;
215 } ust;
216 return (__glibc_unlikely (flags & GLOB_ALTDIRFUNC)
217 ? pglob->GLOB_LSTAT (fullname, &ust.st)
218 : GLOB_FSTATAT64 (AT_FDCWD, fullname, &ust.st64,
219 AT_SYMLINK_NOFOLLOW));
222 static bool
223 glob_use_alloca (size_t alloca_used, size_t len)
225 size_t size;
226 return (!ckd_add (&size, alloca_used, len)
227 && __libc_use_alloca (size));
230 static int glob_in_dir (const char *pattern, const char *directory,
231 int flags, int (*errfunc) (const char *, int),
232 glob_t *pglob, size_t alloca_used);
233 static int prefix_array (const char *prefix, char **array, size_t n) __THROWNL;
234 static int collated_compare (const void *, const void *) __THROWNL;
237 /* Return true if FILENAME is a directory or a symbolic link to a directory.
238 Use FLAGS and PGLOB to resolve the filename. */
239 static bool
240 is_dir (char const *filename, int flags, glob_t const *pglob)
242 struct_stat st;
243 struct_stat64 st64;
244 return (__glibc_unlikely (flags & GLOB_ALTDIRFUNC)
245 ? pglob->gl_stat (filename, &st) == 0 && S_ISDIR (st.st_mode)
246 : (GLOB_FSTATAT64 (AT_FDCWD, filename, &st64, 0) == 0
247 && S_ISDIR (st64.st_mode)));
250 /* Find the end of the sub-pattern in a brace expression. */
251 static const char *
252 next_brace_sub (const char *cp, int flags)
254 size_t depth = 0;
255 while (*cp != '\0')
256 if ((flags & GLOB_NOESCAPE) == 0 && *cp == '\\')
258 if (*++cp == '\0')
259 break;
260 ++cp;
262 else
264 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
265 break;
267 if (*cp++ == '{')
268 depth++;
271 return *cp != '\0' ? cp : NULL;
274 #ifndef GLOB_ATTRIBUTE
275 # define GLOB_ATTRIBUTE
276 #endif
278 /* Do glob searching for PATTERN, placing results in PGLOB.
279 The bits defined above may be set in FLAGS.
280 If a directory cannot be opened or read and ERRFUNC is not nil,
281 it is called with the pathname that caused the error, and the
282 'errno' value from the failing call; if it returns non-zero
283 'glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
284 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
285 Otherwise, 'glob' returns zero. */
287 GLOB_ATTRIBUTE
288 __glob (const char *pattern, int flags, int (*errfunc) (const char *, int),
289 glob_t *pglob)
291 const char *filename;
292 char *dirname = NULL;
293 size_t dirlen;
294 int status;
295 size_t oldcount;
296 int meta;
297 int dirname_modified;
298 int malloc_dirname = 0;
299 glob_t dirs;
300 int retval = 0;
301 size_t alloca_used = 0;
303 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
305 __set_errno (EINVAL);
306 return -1;
309 /* POSIX requires all slashes to be matched. This means that with
310 a trailing slash we must match only directories. */
311 if (pattern[0] && pattern[strlen (pattern) - 1] == '/')
312 flags |= GLOB_ONLYDIR;
314 if (!(flags & GLOB_DOOFFS))
315 /* Have to do this so 'globfree' knows where to start freeing. It
316 also makes all the code that uses gl_offs simpler. */
317 pglob->gl_offs = 0;
319 if (!(flags & GLOB_APPEND))
321 pglob->gl_pathc = 0;
322 if (!(flags & GLOB_DOOFFS))
323 pglob->gl_pathv = NULL;
324 else
326 size_t i;
328 if (pglob->gl_offs >= ~((size_t) 0) / sizeof (char *))
329 return GLOB_NOSPACE;
331 pglob->gl_pathv = (char **) malloc ((pglob->gl_offs + 1)
332 * sizeof (char *));
333 if (pglob->gl_pathv == NULL)
334 return GLOB_NOSPACE;
336 for (i = 0; i <= pglob->gl_offs; ++i)
337 pglob->gl_pathv[i] = NULL;
341 if (flags & GLOB_BRACE)
343 const char *begin;
345 if (flags & GLOB_NOESCAPE)
346 begin = strchr (pattern, '{');
347 else
349 begin = pattern;
350 while (1)
352 if (*begin == '\0')
354 begin = NULL;
355 break;
358 if (*begin == '\\' && begin[1] != '\0')
359 ++begin;
360 else if (*begin == '{')
361 break;
363 ++begin;
367 if (begin != NULL)
369 /* Allocate working buffer large enough for our work. Note that
370 we have at least an opening and closing brace. */
371 size_t firstc;
372 char *alt_start;
373 const char *p;
374 const char *next;
375 const char *rest;
376 size_t rest_len;
377 char *onealt;
378 size_t pattern_len = strlen (pattern) - 1;
379 int alloca_onealt = glob_use_alloca (alloca_used, pattern_len);
380 if (alloca_onealt)
381 onealt = alloca_account (pattern_len, alloca_used);
382 else
384 onealt = malloc (pattern_len);
385 if (onealt == NULL)
386 return GLOB_NOSPACE;
389 /* We know the prefix for all sub-patterns. */
390 alt_start = mempcpy (onealt, pattern, begin - pattern);
392 /* Find the first sub-pattern and at the same time find the
393 rest after the closing brace. */
394 next = next_brace_sub (begin + 1, flags);
395 if (next == NULL)
397 /* It is an invalid expression. */
398 illegal_brace:
399 if (__glibc_unlikely (!alloca_onealt))
400 free (onealt);
401 flags &= ~GLOB_BRACE;
402 goto no_brace;
405 /* Now find the end of the whole brace expression. */
406 rest = next;
407 while (*rest != '}')
409 rest = next_brace_sub (rest + 1, flags);
410 if (rest == NULL)
411 /* It is an illegal expression. */
412 goto illegal_brace;
414 /* Please note that we now can be sure the brace expression
415 is well-formed. */
416 rest_len = strlen (++rest) + 1;
418 /* We have a brace expression. BEGIN points to the opening {,
419 NEXT points past the terminator of the first element, and END
420 points past the final }. We will accumulate result names from
421 recursive runs for each brace alternative in the buffer using
422 GLOB_APPEND. */
423 firstc = pglob->gl_pathc;
425 p = begin + 1;
426 while (1)
428 int result;
430 /* Construct the new glob expression. */
431 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
433 result = __glob (onealt,
434 ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))
435 | GLOB_APPEND),
436 errfunc, pglob);
438 /* If we got an error, return it. */
439 if (result && result != GLOB_NOMATCH)
441 if (__glibc_unlikely (!alloca_onealt))
442 free (onealt);
443 if (!(flags & GLOB_APPEND))
445 globfree (pglob);
446 pglob->gl_pathc = 0;
448 return result;
451 if (*next == '}')
452 /* We saw the last entry. */
453 break;
455 p = next + 1;
456 next = next_brace_sub (p, flags);
457 assert (next != NULL);
460 if (__glibc_unlikely (!alloca_onealt))
461 free (onealt);
463 if (pglob->gl_pathc != firstc)
464 /* We found some entries. */
465 return 0;
466 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
467 return GLOB_NOMATCH;
471 no_brace:
472 oldcount = pglob->gl_pathc + pglob->gl_offs;
474 /* Find the filename. */
475 filename = strrchr (pattern, '/');
477 #if defined __MSDOS__ || defined WINDOWS32
478 /* The case of "d:pattern". Since ':' is not allowed in
479 file names, we can safely assume that wherever it
480 happens in pattern, it signals the filename part. This
481 is so we could some day support patterns like "[a-z]:foo". */
482 if (filename == NULL)
483 filename = strchr (pattern, ':');
484 #endif /* __MSDOS__ || WINDOWS32 */
486 dirname_modified = 0;
487 if (filename == NULL)
489 /* This can mean two things: a simple name or "~name". The latter
490 case is nothing but a notation for a directory. */
491 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
493 dirname = (char *) pattern;
494 dirlen = strlen (pattern);
496 /* Set FILENAME to NULL as a special flag. This is ugly but
497 other solutions would require much more code. We test for
498 this special case below. */
499 filename = NULL;
501 else
503 if (__glibc_unlikely (pattern[0] == '\0'))
505 dirs.gl_pathv = NULL;
506 goto no_matches;
509 filename = pattern;
510 dirname = (char *) ".";
511 dirlen = 0;
514 else if (filename == pattern
515 || (filename == pattern + 1 && pattern[0] == '\\'
516 && (flags & GLOB_NOESCAPE) == 0))
518 /* "/pattern" or "\\/pattern". */
519 dirname = (char *) "/";
520 dirlen = 1;
521 ++filename;
523 else
525 char *newp;
526 dirlen = filename - pattern;
527 #if defined __MSDOS__ || defined WINDOWS32
528 if (*filename == ':'
529 || (filename > pattern + 1 && filename[-1] == ':'))
531 char *drive_spec;
533 ++dirlen;
534 drive_spec = __alloca (dirlen + 1);
535 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
536 /* For now, disallow wildcards in the drive spec, to
537 prevent infinite recursion in glob. */
538 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
539 return GLOB_NOMATCH;
540 /* If this is "d:pattern", we need to copy ':' to DIRNAME
541 as well. If it's "d:/pattern", don't remove the slash
542 from "d:/", since "d:" and "d:/" are not the same.*/
544 #endif
546 if (glob_use_alloca (alloca_used, dirlen + 1))
547 newp = alloca_account (dirlen + 1, alloca_used);
548 else
550 newp = malloc (dirlen + 1);
551 if (newp == NULL)
552 return GLOB_NOSPACE;
553 malloc_dirname = 1;
555 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
556 dirname = newp;
557 ++filename;
559 #if defined __MSDOS__ || defined WINDOWS32
560 bool drive_root = (dirlen > 1
561 && (dirname[dirlen - 1] == ':'
562 || (dirlen > 2 && dirname[dirlen - 2] == ':'
563 && dirname[dirlen - 1] == '/')));
564 #else
565 bool drive_root = false;
566 #endif
568 if (filename[0] == '\0' && dirlen > 1 && !drive_root)
569 /* "pattern/". Expand "pattern", appending slashes. */
571 int orig_flags = flags;
572 if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\')
574 /* "pattern\\/". Remove the final backslash if it hasn't
575 been quoted. */
576 char *p = (char *) &dirname[dirlen - 1];
578 while (p > dirname && p[-1] == '\\') --p;
579 if ((&dirname[dirlen] - p) & 1)
581 *(char *) &dirname[--dirlen] = '\0';
582 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
585 int val = __glob (dirname, flags | GLOB_MARK, errfunc, pglob);
586 if (val == 0)
587 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
588 | (flags & GLOB_MARK));
589 else if (val == GLOB_NOMATCH && flags != orig_flags)
591 /* Make sure globfree (&dirs); is a nop. */
592 dirs.gl_pathv = NULL;
593 flags = orig_flags;
594 oldcount = pglob->gl_pathc + pglob->gl_offs;
595 goto no_matches;
597 retval = val;
598 goto out;
602 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
604 if (dirname[1] == '\0' || dirname[1] == '/'
605 || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\'
606 && (dirname[2] == '\0' || dirname[2] == '/')))
608 /* Look up home directory. */
609 char *home_dir = getenv ("HOME");
610 int malloc_home_dir = 0;
611 if (home_dir == NULL || home_dir[0] == '\0')
613 #ifdef WINDOWS32
614 /* Windows NT defines HOMEDRIVE and HOMEPATH. But give
615 preference to HOME, because the user can change HOME. */
616 const char *home_drive = getenv ("HOMEDRIVE");
617 const char *home_path = getenv ("HOMEPATH");
619 if (home_drive != NULL && home_path != NULL)
621 size_t home_drive_len = strlen (home_drive);
622 size_t home_path_len = strlen (home_path);
623 char *mem = alloca (home_drive_len + home_path_len + 1);
625 memcpy (mem, home_drive, home_drive_len);
626 memcpy (mem + home_drive_len, home_path, home_path_len + 1);
627 home_dir = mem;
629 else
630 home_dir = "c:/users/default"; /* poor default */
631 #else
632 int err;
633 struct passwd *p;
634 struct passwd pwbuf;
635 struct scratch_buffer s;
636 scratch_buffer_init (&s);
637 while (true)
639 p = NULL;
640 err = __getlogin_r (s.data, s.length);
641 if (err == 0)
643 # if defined HAVE_GETPWNAM_R || defined _LIBC
644 size_t ssize = strlen (s.data) + 1;
645 char *sdata = s.data;
646 err = getpwnam_r (sdata, &pwbuf, sdata + ssize,
647 s.length - ssize, &p);
648 # else
649 p = getpwnam (s.data);
650 if (p == NULL)
651 err = errno;
652 # endif
654 if (err != ERANGE)
655 break;
656 if (!scratch_buffer_grow (&s))
658 retval = GLOB_NOSPACE;
659 goto out;
662 if (err == 0)
664 home_dir = strdup (p->pw_dir);
665 malloc_home_dir = 1;
667 scratch_buffer_free (&s);
668 if (err == 0 && home_dir == NULL)
670 retval = GLOB_NOSPACE;
671 goto out;
673 #endif /* WINDOWS32 */
675 if (home_dir == NULL || home_dir[0] == '\0')
677 if (__glibc_unlikely (malloc_home_dir))
678 free (home_dir);
679 if (flags & GLOB_TILDE_CHECK)
681 retval = GLOB_NOMATCH;
682 goto out;
684 else
686 home_dir = (char *) "~"; /* No luck. */
687 malloc_home_dir = 0;
690 /* Now construct the full directory. */
691 if (dirname[1] == '\0')
693 if (__glibc_unlikely (malloc_dirname))
694 free (dirname);
696 dirname = home_dir;
697 dirlen = strlen (dirname);
698 malloc_dirname = malloc_home_dir;
700 else
702 char *newp;
703 size_t home_len = strlen (home_dir);
704 int use_alloca = glob_use_alloca (alloca_used, home_len + dirlen);
705 if (use_alloca)
706 newp = alloca_account (home_len + dirlen, alloca_used);
707 else
709 newp = malloc (home_len + dirlen);
710 if (newp == NULL)
712 if (__glibc_unlikely (malloc_home_dir))
713 free (home_dir);
714 retval = GLOB_NOSPACE;
715 goto out;
719 mempcpy (mempcpy (newp, home_dir, home_len),
720 &dirname[1], dirlen);
722 if (__glibc_unlikely (malloc_dirname))
723 free (dirname);
725 dirname = newp;
726 dirlen += home_len - 1;
727 malloc_dirname = !use_alloca;
729 if (__glibc_unlikely (malloc_home_dir))
730 free (home_dir);
732 dirname_modified = 1;
734 else
736 #ifndef WINDOWS32
737 /* Recognize ~user as a shorthand for the specified user's home
738 directory. */
739 char *end_name = strchr (dirname, '/');
740 char *user_name;
741 int malloc_user_name = 0;
742 char *unescape = NULL;
744 if (!(flags & GLOB_NOESCAPE))
746 if (end_name == NULL)
748 unescape = strchr (dirname, '\\');
749 if (unescape)
750 end_name = strchr (unescape, '\0');
752 else
753 unescape = memchr (dirname, '\\', end_name - dirname);
755 if (end_name == NULL)
756 user_name = dirname + 1;
757 else
759 char *newp;
760 if (glob_use_alloca (alloca_used, end_name - dirname))
761 newp = alloca_account (end_name - dirname, alloca_used);
762 else
764 newp = malloc (end_name - dirname);
765 if (newp == NULL)
767 retval = GLOB_NOSPACE;
768 goto out;
770 malloc_user_name = 1;
772 if (unescape != NULL)
774 char *p = mempcpy (newp, dirname + 1,
775 unescape - dirname - 1);
776 char *q = unescape;
777 while (q != end_name)
779 if (*q == '\\')
781 if (q + 1 == end_name)
783 /* "~fo\\o\\" unescape to user_name "foo\\",
784 but "~fo\\o\\/" unescape to user_name
785 "foo". */
786 if (filename == NULL)
787 *p++ = '\\';
788 break;
790 ++q;
792 *p++ = *q++;
794 *p = '\0';
796 else
797 *((char *) mempcpy (newp, dirname + 1, end_name - dirname - 1))
798 = '\0';
799 user_name = newp;
802 /* Look up specific user's home directory. */
804 struct passwd *p;
805 struct scratch_buffer pwtmpbuf;
806 scratch_buffer_init (&pwtmpbuf);
808 # if defined HAVE_GETPWNAM_R || defined _LIBC
809 struct passwd pwbuf;
811 while (getpwnam_r (user_name, &pwbuf,
812 pwtmpbuf.data, pwtmpbuf.length, &p)
813 == ERANGE)
815 if (!scratch_buffer_grow (&pwtmpbuf))
817 retval = GLOB_NOSPACE;
818 goto out;
821 # else
822 p = getpwnam (user_name);
823 # endif
825 if (__glibc_unlikely (malloc_user_name))
826 free (user_name);
828 /* If we found a home directory use this. */
829 if (p != NULL)
831 size_t home_len = strlen (p->pw_dir);
832 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
833 /* dirname contains end_name; we can't free it now. */
834 char *prev_dirname =
835 (__glibc_unlikely (malloc_dirname) ? dirname : NULL);
836 char *d;
838 malloc_dirname = 0;
840 if (glob_use_alloca (alloca_used, home_len + rest_len + 1))
841 dirname = alloca_account (home_len + rest_len + 1,
842 alloca_used);
843 else
845 dirname = malloc (home_len + rest_len + 1);
846 if (dirname == NULL)
848 free (prev_dirname);
849 scratch_buffer_free (&pwtmpbuf);
850 retval = GLOB_NOSPACE;
851 goto out;
853 malloc_dirname = 1;
855 d = mempcpy (dirname, p->pw_dir, home_len);
856 if (end_name != NULL)
857 d = mempcpy (d, end_name, rest_len);
858 *d = '\0';
860 free (prev_dirname);
862 dirlen = home_len + rest_len;
863 dirname_modified = 1;
865 else
867 if (flags & GLOB_TILDE_CHECK)
869 /* We have to regard it as an error if we cannot find the
870 home directory. */
871 retval = GLOB_NOMATCH;
872 goto out;
875 scratch_buffer_free (&pwtmpbuf);
877 #else /* WINDOWS32 */
878 /* On native Windows, access to a user's home directory
879 (via GetUserProfileDirectory) or to a user's environment
880 variables (via ExpandEnvironmentStringsForUser) requires
881 the credentials of the user. Therefore we cannot support
882 the ~user syntax on this platform.
883 Handling ~user specially (and treat it like plain ~) if
884 user is getenv ("USERNAME") would not be a good idea,
885 since it would make people think that ~user is supported
886 in general. */
887 if (flags & GLOB_TILDE_CHECK)
889 retval = GLOB_NOMATCH;
890 goto out;
892 #endif /* WINDOWS32 */
896 /* Now test whether we looked for "~" or "~NAME". In this case we
897 can give the answer now. */
898 if (filename == NULL)
900 size_t newcount = pglob->gl_pathc + pglob->gl_offs;
901 char **new_gl_pathv;
903 if (newcount > SIZE_MAX / sizeof (char *) - 2)
905 nospace:
906 free (pglob->gl_pathv);
907 pglob->gl_pathv = NULL;
908 pglob->gl_pathc = 0;
909 retval = GLOB_NOSPACE;
910 goto out;
913 new_gl_pathv = realloc (pglob->gl_pathv,
914 (newcount + 2) * sizeof (char *));
915 if (new_gl_pathv == NULL)
916 goto nospace;
917 pglob->gl_pathv = new_gl_pathv;
919 if (flags & GLOB_MARK && is_dir (dirname, flags, pglob))
921 char *p;
922 pglob->gl_pathv[newcount] = malloc (dirlen + 2);
923 if (pglob->gl_pathv[newcount] == NULL)
924 goto nospace;
925 p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);
926 p[0] = '/';
927 p[1] = '\0';
928 if (__glibc_unlikely (malloc_dirname))
929 free (dirname);
931 else
933 if (__glibc_unlikely (malloc_dirname))
934 pglob->gl_pathv[newcount] = dirname;
935 else
937 pglob->gl_pathv[newcount] = strdup (dirname);
938 if (pglob->gl_pathv[newcount] == NULL)
939 goto nospace;
942 pglob->gl_pathv[++newcount] = NULL;
943 ++pglob->gl_pathc;
944 pglob->gl_flags = flags;
946 return 0;
949 meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));
950 /* meta is 1 if correct glob pattern containing metacharacters.
951 If meta has bit (1 << 2) set, it means there was an unterminated
952 [ which we handle the same, using fnmatch. Broken unterminated
953 pattern bracket expressions ought to be rare enough that it is
954 not worth special casing them, fnmatch will do the right thing. */
955 if (meta & (GLOBPAT_SPECIAL | GLOBPAT_BRACKET))
957 /* The directory name contains metacharacters, so we
958 have to glob for the directory, and then glob for
959 the pattern in each directory found. */
960 size_t i;
962 if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\')
964 /* "foo\\/bar". Remove the final backslash from dirname
965 if it has not been quoted. */
966 char *p = (char *) &dirname[dirlen - 1];
968 while (p > dirname && p[-1] == '\\') --p;
969 if ((&dirname[dirlen] - p) & 1)
970 *(char *) &dirname[--dirlen] = '\0';
973 if (__glibc_unlikely ((flags & GLOB_ALTDIRFUNC) != 0))
975 /* Use the alternative access functions also in the recursive
976 call. */
977 dirs.gl_opendir = pglob->gl_opendir;
978 dirs.gl_readdir = pglob->gl_readdir;
979 dirs.gl_closedir = pglob->gl_closedir;
980 dirs.gl_stat = pglob->gl_stat;
981 dirs.gl_lstat = pglob->gl_lstat;
984 status = __glob (dirname,
985 ((flags & (GLOB_ERR | GLOB_NOESCAPE | GLOB_ALTDIRFUNC))
986 | GLOB_NOSORT | GLOB_ONLYDIR),
987 errfunc, &dirs);
988 if (status != 0)
990 if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH)
992 retval = status;
993 goto out;
995 goto no_matches;
998 /* We have successfully globbed the preceding directory name.
999 For each name we found, call glob_in_dir on it and FILENAME,
1000 appending the results to PGLOB. */
1001 for (i = 0; i < dirs.gl_pathc; ++i)
1003 size_t old_pathc;
1005 old_pathc = pglob->gl_pathc;
1006 status = glob_in_dir (filename, dirs.gl_pathv[i],
1007 ((flags | GLOB_APPEND)
1008 & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),
1009 errfunc, pglob, alloca_used);
1010 if (status == GLOB_NOMATCH)
1011 /* No matches in this directory. Try the next. */
1012 continue;
1014 if (status != 0)
1016 globfree (&dirs);
1017 globfree (pglob);
1018 pglob->gl_pathc = 0;
1019 retval = status;
1020 goto out;
1023 /* Stick the directory on the front of each name. */
1024 if (prefix_array (dirs.gl_pathv[i],
1025 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
1026 pglob->gl_pathc - old_pathc))
1028 globfree (&dirs);
1029 globfree (pglob);
1030 pglob->gl_pathc = 0;
1031 retval = GLOB_NOSPACE;
1032 goto out;
1036 flags |= GLOB_MAGCHAR;
1038 /* We have ignored the GLOB_NOCHECK flag in the 'glob_in_dir' calls.
1039 But if we have not found any matching entry and the GLOB_NOCHECK
1040 flag was set we must return the input pattern itself. */
1041 if (pglob->gl_pathc + pglob->gl_offs == oldcount)
1043 no_matches:
1044 /* No matches. */
1045 if (flags & GLOB_NOCHECK)
1047 size_t newcount = pglob->gl_pathc + pglob->gl_offs;
1048 char **new_gl_pathv;
1050 if (newcount > SIZE_MAX / sizeof (char *) - 2)
1052 nospace2:
1053 globfree (&dirs);
1054 retval = GLOB_NOSPACE;
1055 goto out;
1058 new_gl_pathv = realloc (pglob->gl_pathv,
1059 (newcount + 2) * sizeof (char *));
1060 if (new_gl_pathv == NULL)
1061 goto nospace2;
1062 pglob->gl_pathv = new_gl_pathv;
1064 pglob->gl_pathv[newcount] = strdup (pattern);
1065 if (pglob->gl_pathv[newcount] == NULL)
1067 globfree (&dirs);
1068 globfree (pglob);
1069 pglob->gl_pathc = 0;
1070 retval = GLOB_NOSPACE;
1071 goto out;
1074 ++pglob->gl_pathc;
1075 ++newcount;
1077 pglob->gl_pathv[newcount] = NULL;
1078 pglob->gl_flags = flags;
1080 else
1082 globfree (&dirs);
1083 retval = GLOB_NOMATCH;
1084 goto out;
1088 globfree (&dirs);
1090 else
1092 size_t old_pathc = pglob->gl_pathc;
1093 int orig_flags = flags;
1095 if (meta & GLOBPAT_BACKSLASH)
1097 char *p = strchr (dirname, '\\'), *q;
1098 /* We need to unescape the dirname string. It is certainly
1099 allocated by alloca, as otherwise filename would be NULL
1100 or dirname wouldn't contain backslashes. */
1101 q = p;
1104 if (*p == '\\')
1106 *q = *++p;
1107 --dirlen;
1109 else
1110 *q = *p;
1111 ++q;
1113 while (*p++ != '\0');
1114 dirname_modified = 1;
1116 if (dirname_modified)
1117 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
1118 status = glob_in_dir (filename, dirname, flags, errfunc, pglob,
1119 alloca_used);
1120 if (status != 0)
1122 if (status == GLOB_NOMATCH && flags != orig_flags
1123 && pglob->gl_pathc + pglob->gl_offs == oldcount)
1125 /* Make sure globfree (&dirs); is a nop. */
1126 dirs.gl_pathv = NULL;
1127 flags = orig_flags;
1128 goto no_matches;
1130 retval = status;
1131 goto out;
1134 if (dirlen > 0)
1136 /* Stick the directory on the front of each name. */
1137 if (prefix_array (dirname,
1138 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
1139 pglob->gl_pathc - old_pathc))
1141 globfree (pglob);
1142 pglob->gl_pathc = 0;
1143 retval = GLOB_NOSPACE;
1144 goto out;
1149 if (flags & GLOB_MARK)
1151 /* Append slashes to directory names. */
1152 size_t i;
1154 for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)
1155 if (is_dir (pglob->gl_pathv[i], flags, pglob))
1157 size_t len = strlen (pglob->gl_pathv[i]) + 2;
1158 char *new = realloc (pglob->gl_pathv[i], len);
1159 if (new == NULL)
1161 globfree (pglob);
1162 pglob->gl_pathc = 0;
1163 retval = GLOB_NOSPACE;
1164 goto out;
1166 strcpy (&new[len - 2], "/");
1167 pglob->gl_pathv[i] = new;
1171 if (!(flags & GLOB_NOSORT))
1173 /* Sort the vector. */
1174 qsort (&pglob->gl_pathv[oldcount],
1175 pglob->gl_pathc + pglob->gl_offs - oldcount,
1176 sizeof (char *), collated_compare);
1179 out:
1180 if (__glibc_unlikely (malloc_dirname))
1181 free (dirname);
1183 return retval;
1185 #if defined _LIBC && !defined __glob
1186 versioned_symbol (libc, __glob, glob, GLIBC_2_27);
1187 libc_hidden_ver (__glob, glob)
1188 #endif
1191 /* Do a collated comparison of A and B. */
1192 static int
1193 collated_compare (const void *a, const void *b)
1195 char *const *ps1 = a; char *s1 = *ps1;
1196 char *const *ps2 = b; char *s2 = *ps2;
1198 if (s1 == s2)
1199 return 0;
1200 if (s1 == NULL)
1201 return 1;
1202 if (s2 == NULL)
1203 return -1;
1204 return strcoll (s1, s2);
1208 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1209 elements in place. Return nonzero if out of memory, zero if successful.
1210 A slash is inserted between DIRNAME and each elt of ARRAY,
1211 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1212 static int
1213 prefix_array (const char *dirname, char **array, size_t n)
1215 size_t i;
1216 size_t dirlen = strlen (dirname);
1217 char dirsep_char = '/';
1219 if (dirlen == 1 && dirname[0] == '/')
1220 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1221 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1222 dirlen = 0;
1224 #if defined __MSDOS__ || defined WINDOWS32
1225 if (dirlen > 1)
1227 if (dirname[dirlen - 1] == '/' && dirname[dirlen - 2] == ':')
1228 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1229 --dirlen;
1230 else if (dirname[dirlen - 1] == ':')
1232 /* DIRNAME is "d:". Use ':' instead of '/'. */
1233 --dirlen;
1234 dirsep_char = ':';
1237 #endif
1239 for (i = 0; i < n; ++i)
1241 size_t eltlen = strlen (array[i]) + 1;
1242 char *new = malloc (dirlen + 1 + eltlen);
1243 if (new == NULL)
1245 while (i > 0)
1246 free (array[--i]);
1247 return 1;
1251 char *endp = mempcpy (new, dirname, dirlen);
1252 *endp++ = dirsep_char;
1253 mempcpy (endp, array[i], eltlen);
1255 free (array[i]);
1256 array[i] = new;
1259 return 0;
1262 /* Like 'glob', but PATTERN is a final pathname component,
1263 and matches are searched for in DIRECTORY.
1264 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1265 The GLOB_APPEND flag is assumed to be set (always appends). */
1266 static int
1267 glob_in_dir (const char *pattern, const char *directory, int flags,
1268 int (*errfunc) (const char *, int),
1269 glob_t *pglob, size_t alloca_used)
1271 size_t dirlen = strlen (directory);
1272 void *stream = NULL;
1273 struct scratch_buffer s;
1274 scratch_buffer_init (&s);
1275 # define GLOBNAMES_MEMBERS(nnames) \
1276 struct globnames *next; size_t count; char *name[nnames];
1277 struct globnames { GLOBNAMES_MEMBERS (FLEXIBLE_ARRAY_MEMBER) };
1278 struct { GLOBNAMES_MEMBERS (64) } init_names_buf;
1279 struct globnames *init_names = (struct globnames *) &init_names_buf;
1280 struct globnames *names = init_names;
1281 struct globnames *names_alloca = init_names;
1282 size_t nfound = 0;
1283 size_t cur = 0;
1284 int meta;
1285 int save;
1286 int result;
1288 alloca_used += sizeof init_names_buf;
1290 init_names->next = NULL;
1291 init_names->count = ((sizeof init_names_buf
1292 - offsetof (struct globnames, name))
1293 / sizeof init_names->name[0]);
1295 meta = __glob_pattern_type (pattern, !(flags & GLOB_NOESCAPE));
1296 if (meta == GLOBPAT_NONE && (flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
1298 /* We need not do any tests. The PATTERN contains no meta
1299 characters and we must not return an error therefore the
1300 result will always contain exactly one name. */
1301 flags |= GLOB_NOCHECK;
1303 else if (meta == GLOBPAT_NONE)
1305 size_t patlen = strlen (pattern);
1306 size_t fullsize;
1307 bool alloca_fullname
1308 = (!ckd_add (&fullsize, dirlen + 1, patlen + 1)
1309 && glob_use_alloca (alloca_used, fullsize));
1310 char *fullname;
1311 if (alloca_fullname)
1312 fullname = alloca_account (fullsize, alloca_used);
1313 else
1315 fullname = malloc (fullsize);
1316 if (fullname == NULL)
1317 return GLOB_NOSPACE;
1320 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1321 "/", 1),
1322 pattern, patlen + 1);
1323 if (glob_lstat (pglob, flags, fullname) == 0
1324 || errno == EOVERFLOW)
1325 /* We found this file to be existing. Now tell the rest
1326 of the function to copy this name into the result. */
1327 flags |= GLOB_NOCHECK;
1329 if (__glibc_unlikely (!alloca_fullname))
1330 free (fullname);
1332 else
1334 stream = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1335 ? (*pglob->gl_opendir) (directory)
1336 : opendir (directory));
1337 if (stream == NULL)
1339 if (errno != ENOTDIR
1340 && ((errfunc != NULL && (*errfunc) (directory, errno))
1341 || (flags & GLOB_ERR)))
1342 return GLOB_ABORTED;
1344 else
1346 DIR *dirp = stream;
1347 int dfd = dirfd (dirp);
1348 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1349 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0));
1350 flags |= GLOB_MAGCHAR;
1352 while (1)
1354 struct readdir_result d;
1356 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1357 d = convert_dirent (GL_READDIR (pglob, stream));
1358 else
1360 #ifdef COMPILE_GLOB64
1361 d = convert_dirent (__readdir (stream));
1362 #else
1363 d = convert_dirent64 (__readdir64 (stream));
1364 #endif
1367 if (d.name == NULL)
1368 break;
1370 /* If we shall match only directories use the information
1371 provided by the dirent call if possible. */
1372 if (flags & GLOB_ONLYDIR)
1373 switch (readdir_result_type (d))
1375 default: continue;
1376 case DT_DIR: break;
1377 case DT_LNK: case DT_UNKNOWN:
1378 /* The filesystem was too lazy to give us a hint,
1379 so we have to do it the hard way. */
1380 if (__glibc_unlikely (dfd < 0 || flags & GLOB_ALTDIRFUNC))
1382 size_t namelen = strlen (d.name);
1383 size_t need = dirlen + 1 + namelen + 1;
1384 if (s.length < need
1385 && !scratch_buffer_set_array_size (&s, need, 1))
1386 goto memory_error;
1387 char *p = mempcpy (s.data, directory, dirlen);
1388 *p = '/';
1389 p += p[-1] != '/';
1390 memcpy (p, d.name, namelen + 1);
1391 if (! is_dir (s.data, flags, pglob))
1392 continue;
1394 else
1396 struct_stat64 st64;
1397 if (! (GLOB_FSTATAT64 (dfd, d.name, &st64, 0) == 0
1398 && S_ISDIR (st64.st_mode)))
1399 continue;
1403 if (fnmatch (pattern, d.name, fnm_flags) == 0)
1405 if (cur == names->count)
1407 struct globnames *newnames;
1408 size_t count = names->count * 2;
1409 size_t nameoff = offsetof (struct globnames, name);
1410 size_t size = FLEXSIZEOF (struct globnames, name,
1411 count * sizeof (char *));
1412 if ((SIZE_MAX - nameoff) / 2 / sizeof (char *)
1413 < names->count)
1414 goto memory_error;
1415 if (glob_use_alloca (alloca_used, size))
1416 newnames = names_alloca
1417 = alloca_account (size, alloca_used);
1418 else if ((newnames = malloc (size))
1419 == NULL)
1420 goto memory_error;
1421 newnames->count = count;
1422 newnames->next = names;
1423 names = newnames;
1424 cur = 0;
1426 names->name[cur] = strdup (d.name);
1427 if (names->name[cur] == NULL)
1428 goto memory_error;
1429 ++cur;
1430 ++nfound;
1431 if (SIZE_MAX - pglob->gl_offs <= nfound)
1432 goto memory_error;
1438 if (nfound == 0 && (flags & GLOB_NOCHECK))
1440 size_t len = strlen (pattern);
1441 nfound = 1;
1442 names->name[cur] = malloc (len + 1);
1443 if (names->name[cur] == NULL)
1444 goto memory_error;
1445 *((char *) mempcpy (names->name[cur++], pattern, len)) = '\0';
1448 result = GLOB_NOMATCH;
1449 if (nfound != 0)
1451 char **new_gl_pathv;
1452 result = 0;
1454 if (SIZE_MAX / sizeof (char *) - pglob->gl_pathc
1455 < pglob->gl_offs + nfound + 1)
1456 goto memory_error;
1458 new_gl_pathv
1459 = realloc (pglob->gl_pathv,
1460 (pglob->gl_pathc + pglob->gl_offs + nfound + 1)
1461 * sizeof (char *));
1463 if (new_gl_pathv == NULL)
1465 memory_error:
1466 while (1)
1468 struct globnames *old = names;
1469 for (size_t i = 0; i < cur; ++i)
1470 free (names->name[i]);
1471 names = names->next;
1472 /* NB: we will not leak memory here if we exit without
1473 freeing the current block assigned to OLD. At least
1474 the very first block is always allocated on the stack
1475 and this is the block assigned to OLD here. */
1476 if (names == NULL)
1478 assert (old == init_names);
1479 break;
1481 cur = names->count;
1482 if (old == names_alloca)
1483 names_alloca = names;
1484 else
1485 free (old);
1487 result = GLOB_NOSPACE;
1489 else
1491 while (1)
1493 struct globnames *old = names;
1494 for (size_t i = 0; i < cur; ++i)
1495 new_gl_pathv[pglob->gl_offs + pglob->gl_pathc++]
1496 = names->name[i];
1497 names = names->next;
1498 /* NB: we will not leak memory here if we exit without
1499 freeing the current block assigned to OLD. At least
1500 the very first block is always allocated on the stack
1501 and this is the block assigned to OLD here. */
1502 if (names == NULL)
1504 assert (old == init_names);
1505 break;
1507 cur = names->count;
1508 if (old == names_alloca)
1509 names_alloca = names;
1510 else
1511 free (old);
1514 pglob->gl_pathv = new_gl_pathv;
1516 pglob->gl_pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
1518 pglob->gl_flags = flags;
1522 if (stream != NULL)
1524 save = errno;
1525 if (__glibc_unlikely (flags & GLOB_ALTDIRFUNC))
1526 (*pglob->gl_closedir) (stream);
1527 else
1528 closedir (stream);
1529 __set_errno (save);
1532 scratch_buffer_free (&s);
1533 return result;