sys_socket: Add support for OpenVMS.
[gnulib.git] / lib / glob.c
blob3b3194ade2b3d192e047209a904f007773913282
1 /* Copyright (C) 1991-2017 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 <http://www.gnu.org/licenses/>. */
18 #ifndef _LIBC
19 /* Don't use __attribute__ __nonnull__ in this compilation unit. Otherwise gcc
20 optimizes away the pattern == NULL || pglob == NULL tests below. */
21 # define _GL_ARG_NONNULL(params)
22 # include <config.h>
23 #endif
25 #include <glob.h>
27 #include <errno.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <stdbool.h>
31 #include <stddef.h>
32 #include <stdint.h>
34 /* Outcomment the following line for production quality code. */
35 /* #define NDEBUG 1 */
36 #include <assert.h>
38 #include <stdio.h> /* Needed on stupid SunOS for assert. */
40 #ifndef GLOB_ONLY_P
42 #include <unistd.h>
43 #if !defined POSIX && defined _POSIX_VERSION
44 # define POSIX
45 #endif
47 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
48 # define WINDOWS32
49 #endif
51 #ifndef WINDOWS32
52 # include <pwd.h>
53 #endif
55 #include <errno.h>
56 #ifndef __set_errno
57 # define __set_errno(val) errno = (val)
58 #endif
60 #include <dirent.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <alloca.h>
65 #ifdef _LIBC
66 # undef strdup
67 # define strdup(str) __strdup (str)
68 # define sysconf(id) __sysconf (id)
69 # define closedir(dir) __closedir (dir)
70 # define opendir(name) __opendir (name)
71 # define readdir(str) __readdir64 (str)
72 # define getpwnam_r(name, bufp, buf, len, res) \
73 __getpwnam_r (name, bufp, buf, len, res)
74 # ifndef __stat64
75 # define __stat64(fname, buf) __xstat64 (_STAT_VER, fname, buf)
76 # endif
77 # define struct_stat64 struct stat64
78 #else /* !_LIBC */
79 # define __getlogin_r(buf, len) getlogin_r (buf, len)
80 # define __stat64(fname, buf) stat (fname, buf)
81 # define __fxstatat64(_, d, f, st, flag) fstatat (d, f, st, flag)
82 # define struct_stat64 struct stat
83 # ifndef __MVS__
84 # define __alloca alloca
85 # endif
86 # define __readdir readdir
87 # define __glob_pattern_p glob_pattern_p
88 # define COMPILE_GLOB64
89 #endif /* _LIBC */
91 #include <fnmatch.h>
93 #include "flexmember.h"
95 #ifdef _SC_GETPW_R_SIZE_MAX
96 # define GETPW_R_SIZE_MAX() sysconf (_SC_GETPW_R_SIZE_MAX)
97 #else
98 # define GETPW_R_SIZE_MAX() (-1)
99 #endif
100 #ifdef _SC_LOGIN_NAME_MAX
101 # define GET_LOGIN_NAME_MAX() sysconf (_SC_LOGIN_NAME_MAX)
102 #else
103 # define GET_LOGIN_NAME_MAX() (-1)
104 #endif
106 static const char *next_brace_sub (const char *begin, int flags) __THROWNL;
108 /* A representation of a directory entry which does not depend on the
109 layout of struct dirent, or the size of ino_t. */
110 struct readdir_result
112 const char *name;
113 # if defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE
114 uint8_t type;
115 # endif
116 bool skip_entry;
119 # if defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE
120 /* Initializer based on the d_type member of struct dirent. */
121 # define D_TYPE_TO_RESULT(source) (source)->d_type,
123 /* True if the directory entry D might be a symbolic link. */
124 static bool
125 readdir_result_might_be_symlink (struct readdir_result d)
127 return d.type == DT_UNKNOWN || d.type == DT_LNK;
130 /* True if the directory entry D might be a directory. */
131 static bool
132 readdir_result_might_be_dir (struct readdir_result d)
134 return d.type == DT_DIR || readdir_result_might_be_symlink (d);
136 # else /* defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE */
137 # define D_TYPE_TO_RESULT(source)
139 /* If we do not have type information, symbolic links and directories
140 are always a possibility. */
142 static bool
143 readdir_result_might_be_symlink (struct readdir_result d)
145 return true;
148 static bool
149 readdir_result_might_be_dir (struct readdir_result d)
151 return true;
154 # endif /* defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE */
156 # if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
157 /* Initializer for skip_entry. POSIX does not require that the d_ino
158 field be present, and some systems do not provide it. */
159 # define D_INO_TO_RESULT(source) false,
160 # else
161 # define D_INO_TO_RESULT(source) (source)->d_ino == 0,
162 # endif
164 /* Construct an initializer for a struct readdir_result object from a
165 struct dirent *. No copy of the name is made. */
166 #define READDIR_RESULT_INITIALIZER(source) \
168 source->d_name, \
169 D_TYPE_TO_RESULT (source) \
170 D_INO_TO_RESULT (source) \
173 #endif /* !defined GLOB_ONLY_P */
175 /* Call gl_readdir on STREAM. This macro can be overridden to reduce
176 type safety if an old interface version needs to be supported. */
177 #ifndef GL_READDIR
178 # define GL_READDIR(pglob, stream) ((pglob)->gl_readdir (stream))
179 #endif
181 /* Extract name and type from directory entry. No copy of the name is
182 made. If SOURCE is NULL, result name is NULL. Keep in sync with
183 convert_dirent64 below. */
184 static struct readdir_result
185 convert_dirent (const struct dirent *source)
187 if (source == NULL)
189 struct readdir_result result = { NULL, };
190 return result;
192 else
194 struct readdir_result result = READDIR_RESULT_INITIALIZER (source);
195 return result;
199 #ifndef COMPILE_GLOB64
200 /* Like convert_dirent, but works on struct dirent64 instead. Keep in
201 sync with convert_dirent above. */
202 static struct readdir_result
203 convert_dirent64 (const struct dirent64 *source)
205 if (source == NULL)
207 struct readdir_result result = { NULL, };
208 return result;
210 else
212 struct readdir_result result = READDIR_RESULT_INITIALIZER (source);
213 return result;
216 #endif
219 #ifndef attribute_hidden
220 # define attribute_hidden
221 #endif
223 #ifndef __attribute_noinline__
224 # if __GNUC__ < 3 || (__GNUC__ == 3 && __GNUC_MINOR__ < 1)
225 # define __attribute_noinline__ /* Ignore */
226 #else
227 # define __attribute_noinline__ __attribute__ ((__noinline__))
228 # endif
229 #endif
231 #ifndef __glibc_unlikely
232 # define __glibc_unlikely(expr) __builtin_expect (expr, 0)
233 #endif
235 #ifndef _LIBC
236 /* The results of opendir() in this file are not used with dirfd and fchdir,
237 and we do not leak fds to any single-threaded code that could use stdio,
238 therefore save some unnecessary recursion in fchdir.c and opendir_safer.c.
239 FIXME - if the kernel ever adds support for multi-thread safety for
240 avoiding standard fds, then we should use opendir_safer. */
241 # ifdef GNULIB_defined_opendir
242 # undef opendir
243 # endif
244 # ifdef GNULIB_defined_closedir
245 # undef closedir
246 # endif
248 /* Just use malloc. */
249 # define __libc_use_alloca(n) false
250 # define alloca_account(len, avar) ((void) (len), (void) (avar), (void *) 0)
251 # define extend_alloca_account(buf, len, newlen, avar) \
252 ((void) (buf), (void) (len), (void) (newlen), (void) (avar), (void *) 0)
253 #endif
255 /* Set *R = A + B. Return true if the answer is mathematically
256 incorrect due to overflow; in this case, *R is the low order
257 bits of the correct answer.. */
259 static bool
260 size_add_wrapv (size_t a, size_t b, size_t *r)
262 #if 5 <= __GNUC__
263 return __builtin_add_overflow (a, b, r);
264 #else
265 *r = a + b;
266 return *r < a;
267 #endif
270 static bool
271 glob_use_alloca (size_t alloca_used, size_t len)
273 size_t size;
274 return (!size_add_wrapv (alloca_used, len, &size)
275 && __libc_use_alloca (size));
278 static int glob_in_dir (const char *pattern, const char *directory,
279 int flags, int (*errfunc) (const char *, int),
280 glob_t *pglob, size_t alloca_used);
281 extern int __glob_pattern_type (const char *pattern, int quote)
282 attribute_hidden;
284 #ifndef GLOB_ONLY_P
285 static int prefix_array (const char *prefix, char **array, size_t n) __THROWNL;
286 static int collated_compare (const void *, const void *) __THROWNL;
289 /* Find the end of the sub-pattern in a brace expression. */
290 static const char *
291 next_brace_sub (const char *cp, int flags)
293 size_t depth = 0;
294 while (*cp != '\0')
295 if ((flags & GLOB_NOESCAPE) == 0 && *cp == '\\')
297 if (*++cp == '\0')
298 break;
299 ++cp;
301 else
303 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
304 break;
306 if (*cp++ == '{')
307 depth++;
310 return *cp != '\0' ? cp : NULL;
313 #endif /* !defined GLOB_ONLY_P */
315 /* Do glob searching for PATTERN, placing results in PGLOB.
316 The bits defined above may be set in FLAGS.
317 If a directory cannot be opened or read and ERRFUNC is not nil,
318 it is called with the pathname that caused the error, and the
319 'errno' value from the failing call; if it returns non-zero
320 'glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
321 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
322 Otherwise, 'glob' returns zero. */
324 #ifdef GLOB_ATTRIBUTE
325 GLOB_ATTRIBUTE
326 #endif
327 glob (const char *pattern, int flags, int (*errfunc) (const char *, int),
328 glob_t *pglob)
330 const char *filename;
331 char *dirname = NULL;
332 size_t dirlen;
333 int status;
334 size_t oldcount;
335 int meta;
336 int dirname_modified;
337 int malloc_dirname = 0;
338 glob_t dirs;
339 int retval = 0;
340 size_t alloca_used = 0;
342 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
344 __set_errno (EINVAL);
345 return -1;
348 /* POSIX requires all slashes to be matched. This means that with
349 a trailing slash we must match only directories. */
350 if (pattern[0] && pattern[strlen (pattern) - 1] == '/')
351 flags |= GLOB_ONLYDIR;
353 if (!(flags & GLOB_DOOFFS))
354 /* Have to do this so 'globfree' knows where to start freeing. It
355 also makes all the code that uses gl_offs simpler. */
356 pglob->gl_offs = 0;
358 if (flags & GLOB_BRACE)
360 const char *begin;
362 if (flags & GLOB_NOESCAPE)
363 begin = strchr (pattern, '{');
364 else
366 begin = pattern;
367 while (1)
369 if (*begin == '\0')
371 begin = NULL;
372 break;
375 if (*begin == '\\' && begin[1] != '\0')
376 ++begin;
377 else if (*begin == '{')
378 break;
380 ++begin;
384 if (begin != NULL)
386 /* Allocate working buffer large enough for our work. Note that
387 we have at least an opening and closing brace. */
388 size_t firstc;
389 char *alt_start;
390 const char *p;
391 const char *next;
392 const char *rest;
393 size_t rest_len;
394 char *onealt;
395 size_t pattern_len = strlen (pattern) - 1;
396 int alloca_onealt = glob_use_alloca (alloca_used, pattern_len);
397 if (alloca_onealt)
398 onealt = alloca_account (pattern_len, alloca_used);
399 else
401 onealt = malloc (pattern_len);
402 if (onealt == NULL)
404 if (!(flags & GLOB_APPEND))
406 pglob->gl_pathc = 0;
407 pglob->gl_pathv = NULL;
409 return GLOB_NOSPACE;
413 /* We know the prefix for all sub-patterns. */
414 alt_start = mempcpy (onealt, pattern, begin - pattern);
416 /* Find the first sub-pattern and at the same time find the
417 rest after the closing brace. */
418 next = next_brace_sub (begin + 1, flags);
419 if (next == NULL)
421 /* It is an invalid expression. */
422 illegal_brace:
423 if (__glibc_unlikely (!alloca_onealt))
424 free (onealt);
425 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
428 /* Now find the end of the whole brace expression. */
429 rest = next;
430 while (*rest != '}')
432 rest = next_brace_sub (rest + 1, flags);
433 if (rest == NULL)
434 /* It is an illegal expression. */
435 goto illegal_brace;
437 /* Please note that we now can be sure the brace expression
438 is well-formed. */
439 rest_len = strlen (++rest) + 1;
441 /* We have a brace expression. BEGIN points to the opening {,
442 NEXT points past the terminator of the first element, and END
443 points past the final }. We will accumulate result names from
444 recursive runs for each brace alternative in the buffer using
445 GLOB_APPEND. */
447 if (!(flags & GLOB_APPEND))
449 /* This call is to set a new vector, so clear out the
450 vector so we can append to it. */
451 pglob->gl_pathc = 0;
452 pglob->gl_pathv = NULL;
454 firstc = pglob->gl_pathc;
456 p = begin + 1;
457 while (1)
459 int result;
461 /* Construct the new glob expression. */
462 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
464 result = glob (onealt,
465 ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))
466 | GLOB_APPEND), errfunc, pglob);
468 /* If we got an error, return it. */
469 if (result && result != GLOB_NOMATCH)
471 if (__glibc_unlikely (!alloca_onealt))
472 free (onealt);
473 if (!(flags & GLOB_APPEND))
475 globfree (pglob);
476 pglob->gl_pathc = 0;
478 return result;
481 if (*next == '}')
482 /* We saw the last entry. */
483 break;
485 p = next + 1;
486 next = next_brace_sub (p, flags);
487 assert (next != NULL);
490 if (__glibc_unlikely (!alloca_onealt))
491 free (onealt);
493 if (pglob->gl_pathc != firstc)
494 /* We found some entries. */
495 return 0;
496 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
497 return GLOB_NOMATCH;
501 if (!(flags & GLOB_APPEND))
503 pglob->gl_pathc = 0;
504 if (!(flags & GLOB_DOOFFS))
505 pglob->gl_pathv = NULL;
506 else
508 size_t i;
510 if (pglob->gl_offs >= SIZE_MAX / sizeof (char *))
511 return GLOB_NOSPACE;
513 pglob->gl_pathv = malloc ((pglob->gl_offs + 1) * sizeof (char *));
514 if (pglob->gl_pathv == NULL)
515 return GLOB_NOSPACE;
517 for (i = 0; i <= pglob->gl_offs; ++i)
518 pglob->gl_pathv[i] = NULL;
522 oldcount = pglob->gl_pathc + pglob->gl_offs;
524 /* Find the filename. */
525 filename = strrchr (pattern, '/');
526 #if defined __MSDOS__ || defined WINDOWS32
527 /* The case of "d:pattern". Since ':' is not allowed in
528 file names, we can safely assume that wherever it
529 happens in pattern, it signals the filename part. This
530 is so we could some day support patterns like "[a-z]:foo". */
531 if (filename == NULL)
532 filename = strchr (pattern, ':');
533 #endif /* __MSDOS__ || WINDOWS32 */
534 dirname_modified = 0;
535 if (filename == NULL)
537 /* This can mean two things: a simple name or "~name". The latter
538 case is nothing but a notation for a directory. */
539 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
541 dirname = (char *) pattern;
542 dirlen = strlen (pattern);
544 /* Set FILENAME to NULL as a special flag. This is ugly but
545 other solutions would require much more code. We test for
546 this special case below. */
547 filename = NULL;
549 else
551 if (__glibc_unlikely (pattern[0] == '\0'))
553 dirs.gl_pathv = NULL;
554 goto no_matches;
557 filename = pattern;
558 #ifdef _AMIGA
559 dirname = (char *) "";
560 #else
561 dirname = (char *) ".";
562 #endif
563 dirlen = 0;
566 else if (filename == pattern
567 || (filename == pattern + 1 && pattern[0] == '\\'
568 && (flags & GLOB_NOESCAPE) == 0))
570 /* "/pattern" or "\\/pattern". */
571 dirname = (char *) "/";
572 dirlen = 1;
573 ++filename;
575 else
577 char *newp;
578 dirlen = filename - pattern;
579 #if defined __MSDOS__ || defined WINDOWS32
580 if (*filename == ':'
581 || (filename > pattern + 1 && filename[-1] == ':'))
583 char *drive_spec;
585 ++dirlen;
586 drive_spec = __alloca (dirlen + 1);
587 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
588 /* For now, disallow wildcards in the drive spec, to
589 prevent infinite recursion in glob. */
590 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
591 return GLOB_NOMATCH;
592 /* If this is "d:pattern", we need to copy ':' to DIRNAME
593 as well. If it's "d:/pattern", don't remove the slash
594 from "d:/", since "d:" and "d:/" are not the same.*/
596 #endif
597 if (glob_use_alloca (alloca_used, dirlen + 1))
598 newp = alloca_account (dirlen + 1, alloca_used);
599 else
601 newp = malloc (dirlen + 1);
602 if (newp == NULL)
603 return GLOB_NOSPACE;
604 malloc_dirname = 1;
606 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
607 dirname = newp;
608 ++filename;
610 if (filename[0] == '\0'
611 #if defined __MSDOS__ || defined WINDOWS32
612 && dirname[dirlen - 1] != ':'
613 && (dirlen < 3 || dirname[dirlen - 2] != ':'
614 || dirname[dirlen - 1] != '/')
615 #endif
616 && dirlen > 1)
617 /* "pattern/". Expand "pattern", appending slashes. */
619 int orig_flags = flags;
620 int val;
621 if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\')
623 /* "pattern\\/". Remove the final backslash if it hasn't
624 been quoted. */
625 char *p = (char *) &dirname[dirlen - 1];
627 while (p > dirname && p[-1] == '\\') --p;
628 if ((&dirname[dirlen] - p) & 1)
630 *(char *) &dirname[--dirlen] = '\0';
631 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
634 val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
635 if (val == 0)
636 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
637 | (flags & GLOB_MARK));
638 else if (val == GLOB_NOMATCH && flags != orig_flags)
640 /* Make sure globfree (&dirs); is a nop. */
641 dirs.gl_pathv = NULL;
642 flags = orig_flags;
643 oldcount = pglob->gl_pathc + pglob->gl_offs;
644 goto no_matches;
646 retval = val;
647 goto out;
651 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
653 if (dirname[1] == '\0' || dirname[1] == '/'
654 || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\'
655 && (dirname[2] == '\0' || dirname[2] == '/')))
657 /* Look up home directory. */
658 char *home_dir = getenv ("HOME");
659 int malloc_home_dir = 0;
660 # ifdef _AMIGA
661 if (home_dir == NULL || home_dir[0] == '\0')
662 home_dir = "SYS:";
663 # else
664 # ifdef WINDOWS32
665 /* Windows NT defines HOMEDRIVE and HOMEPATH. But give preference
666 to HOME, because the user can change HOME. */
667 if (home_dir == NULL || home_dir[0] == '\0')
669 const char *home_drive = getenv ("HOMEDRIVE");
670 const char *home_path = getenv ("HOMEPATH");
672 if (home_drive != NULL && home_path != NULL)
674 size_t home_drive_len = strlen (home_drive);
675 size_t home_path_len = strlen (home_path);
676 char *mem = alloca (home_drive_len + home_path_len + 1);
678 memcpy (mem, home_drive, home_drive_len);
679 memcpy (mem + home_drive_len, home_path, home_path_len + 1);
680 home_dir = mem;
682 else
683 home_dir = "c:/users/default"; /* poor default */
685 # else
686 if (home_dir == NULL || home_dir[0] == '\0')
688 int success;
689 char *name;
690 int malloc_name = 0;
691 size_t buflen = GET_LOGIN_NAME_MAX () + 1;
693 if (buflen == 0)
694 /* 'sysconf' does not support _SC_LOGIN_NAME_MAX. Try
695 a moderate value. */
696 buflen = 20;
697 if (glob_use_alloca (alloca_used, buflen))
698 name = alloca_account (buflen, alloca_used);
699 else
701 name = malloc (buflen);
702 if (name == NULL)
704 retval = GLOB_NOSPACE;
705 goto out;
707 malloc_name = 1;
710 success = __getlogin_r (name, buflen) == 0;
711 if (success)
713 struct passwd *p;
714 char *malloc_pwtmpbuf = NULL;
715 char *pwtmpbuf;
716 # if defined HAVE_GETPWNAM_R || defined _LIBC
717 long int pwbuflenmax = GETPW_R_SIZE_MAX ();
718 size_t pwbuflen = pwbuflenmax;
719 struct passwd pwbuf;
720 int save = errno;
722 # ifndef _LIBC
723 if (! (0 < pwbuflenmax && pwbuflenmax <= SIZE_MAX))
724 /* Perhaps 'sysconf' does not support _SC_GETPW_R_SIZE_MAX.
725 Try a moderate value. */
726 pwbuflen = 1024;
727 # endif
728 if (glob_use_alloca (alloca_used, pwbuflen))
729 pwtmpbuf = alloca_account (pwbuflen, alloca_used);
730 else
732 pwtmpbuf = malloc (pwbuflen);
733 if (pwtmpbuf == NULL)
735 if (__glibc_unlikely (malloc_name))
736 free (name);
737 retval = GLOB_NOSPACE;
738 goto out;
740 malloc_pwtmpbuf = pwtmpbuf;
743 while (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
744 != 0)
746 size_t newlen;
747 bool v;
748 if (errno != ERANGE)
750 p = NULL;
751 break;
753 v = size_add_wrapv (pwbuflen, pwbuflen, &newlen);
754 if (!v && malloc_pwtmpbuf == NULL
755 && glob_use_alloca (alloca_used, newlen))
756 pwtmpbuf = extend_alloca_account (pwtmpbuf, pwbuflen,
757 newlen, alloca_used);
758 else
760 char *newp = (v ? NULL
761 : realloc (malloc_pwtmpbuf, newlen));
762 if (newp == NULL)
764 free (malloc_pwtmpbuf);
765 if (__glibc_unlikely (malloc_name))
766 free (name);
767 retval = GLOB_NOSPACE;
768 goto out;
770 malloc_pwtmpbuf = pwtmpbuf = newp;
772 pwbuflen = newlen;
773 __set_errno (save);
775 # else
776 p = getpwnam (name);
777 # endif
778 if (__glibc_unlikely (malloc_name))
779 free (name);
780 if (p != NULL)
782 if (malloc_pwtmpbuf == NULL)
783 home_dir = p->pw_dir;
784 else
786 size_t home_dir_len = strlen (p->pw_dir) + 1;
787 if (glob_use_alloca (alloca_used, home_dir_len))
788 home_dir = alloca_account (home_dir_len,
789 alloca_used);
790 else
792 home_dir = malloc (home_dir_len);
793 if (home_dir == NULL)
795 free (pwtmpbuf);
796 retval = GLOB_NOSPACE;
797 goto out;
799 malloc_home_dir = 1;
801 memcpy (home_dir, p->pw_dir, home_dir_len);
804 free (malloc_pwtmpbuf);
806 else
808 if (__glibc_unlikely (malloc_name))
809 free (name);
812 if (home_dir == NULL || home_dir[0] == '\0')
814 if (__glibc_unlikely (malloc_home_dir))
815 free (home_dir);
816 if (flags & GLOB_TILDE_CHECK)
818 retval = GLOB_NOMATCH;
819 goto out;
821 else
823 home_dir = (char *) "~"; /* No luck. */
824 malloc_home_dir = 0;
827 # endif /* WINDOWS32 */
828 # endif
829 /* Now construct the full directory. */
830 if (dirname[1] == '\0')
832 if (__glibc_unlikely (malloc_dirname))
833 free (dirname);
835 dirname = home_dir;
836 dirlen = strlen (dirname);
837 malloc_dirname = malloc_home_dir;
839 else
841 char *newp;
842 size_t home_len = strlen (home_dir);
843 int use_alloca = glob_use_alloca (alloca_used, home_len + dirlen);
844 if (use_alloca)
845 newp = alloca_account (home_len + dirlen, alloca_used);
846 else
848 newp = malloc (home_len + dirlen);
849 if (newp == NULL)
851 if (__glibc_unlikely (malloc_home_dir))
852 free (home_dir);
853 retval = GLOB_NOSPACE;
854 goto out;
858 mempcpy (mempcpy (newp, home_dir, home_len),
859 &dirname[1], dirlen);
861 if (__glibc_unlikely (malloc_dirname))
862 free (dirname);
864 dirname = newp;
865 dirlen += home_len - 1;
866 malloc_dirname = !use_alloca;
868 if (__glibc_unlikely (malloc_home_dir))
869 free (home_dir);
871 dirname_modified = 1;
873 # if !defined _AMIGA && !defined WINDOWS32
874 else
876 char *end_name = strchr (dirname, '/');
877 char *user_name;
878 int malloc_user_name = 0;
879 char *unescape = NULL;
881 if (!(flags & GLOB_NOESCAPE))
883 if (end_name == NULL)
885 unescape = strchr (dirname, '\\');
886 if (unescape)
887 end_name = strchr (unescape, '\0');
889 else
890 unescape = memchr (dirname, '\\', end_name - dirname);
892 if (end_name == NULL)
893 user_name = dirname + 1;
894 else
896 char *newp;
897 if (glob_use_alloca (alloca_used, end_name - dirname))
898 newp = alloca_account (end_name - dirname, alloca_used);
899 else
901 newp = malloc (end_name - dirname);
902 if (newp == NULL)
904 retval = GLOB_NOSPACE;
905 goto out;
907 malloc_user_name = 1;
909 if (unescape != NULL)
911 char *p = mempcpy (newp, dirname + 1,
912 unescape - dirname - 1);
913 char *q = unescape;
914 while (*q != '\0')
916 if (*q == '\\')
918 if (q[1] == '\0')
920 /* "~fo\\o\\" unescape to user_name "foo\\",
921 but "~fo\\o\\/" unescape to user_name
922 "foo". */
923 if (filename == NULL)
924 *p++ = '\\';
925 break;
927 ++q;
929 *p++ = *q++;
931 *p = '\0';
933 else
934 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
935 = '\0';
936 user_name = newp;
939 /* Look up specific user's home directory. */
941 struct passwd *p;
942 char *malloc_pwtmpbuf = NULL;
943 # if defined HAVE_GETPWNAM_R || defined _LIBC
944 long int buflenmax = GETPW_R_SIZE_MAX ();
945 size_t buflen = buflenmax;
946 char *pwtmpbuf;
947 struct passwd pwbuf;
948 int save = errno;
950 # ifndef _LIBC
951 if (! (0 <= buflenmax && buflenmax <= SIZE_MAX))
952 /* Perhaps 'sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
953 moderate value. */
954 buflen = 1024;
955 # endif
956 if (glob_use_alloca (alloca_used, buflen))
957 pwtmpbuf = alloca_account (buflen, alloca_used);
958 else
960 pwtmpbuf = malloc (buflen);
961 if (pwtmpbuf == NULL)
963 nomem_getpw:
964 if (__glibc_unlikely (malloc_user_name))
965 free (user_name);
966 retval = GLOB_NOSPACE;
967 goto out;
969 malloc_pwtmpbuf = pwtmpbuf;
972 while (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) != 0)
974 size_t newlen;
975 bool v;
976 if (errno != ERANGE)
978 p = NULL;
979 break;
981 v = size_add_wrapv (buflen, buflen, &newlen);
982 if (!v && malloc_pwtmpbuf == NULL
983 && glob_use_alloca (alloca_used, newlen))
984 pwtmpbuf = extend_alloca_account (pwtmpbuf, buflen,
985 newlen, alloca_used);
986 else
988 char *newp = v ? NULL : realloc (malloc_pwtmpbuf, newlen);
989 if (newp == NULL)
991 free (malloc_pwtmpbuf);
992 goto nomem_getpw;
994 malloc_pwtmpbuf = pwtmpbuf = newp;
996 __set_errno (save);
998 # else
999 p = getpwnam (user_name);
1000 # endif
1002 if (__glibc_unlikely (malloc_user_name))
1003 free (user_name);
1005 /* If we found a home directory use this. */
1006 if (p != NULL)
1008 size_t home_len = strlen (p->pw_dir);
1009 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
1011 if (__glibc_unlikely (malloc_dirname))
1012 free (dirname);
1013 malloc_dirname = 0;
1015 if (glob_use_alloca (alloca_used, home_len + rest_len + 1))
1016 dirname = alloca_account (home_len + rest_len + 1,
1017 alloca_used);
1018 else
1020 dirname = malloc (home_len + rest_len + 1);
1021 if (dirname == NULL)
1023 free (malloc_pwtmpbuf);
1024 retval = GLOB_NOSPACE;
1025 goto out;
1027 malloc_dirname = 1;
1029 *((char *) mempcpy (mempcpy (dirname, p->pw_dir, home_len),
1030 end_name, rest_len)) = '\0';
1032 dirlen = home_len + rest_len;
1033 dirname_modified = 1;
1035 free (malloc_pwtmpbuf);
1037 else
1039 free (malloc_pwtmpbuf);
1041 if (flags & GLOB_TILDE_CHECK)
1043 /* We have to regard it as an error if we cannot find the
1044 home directory. */
1045 retval = GLOB_NOMATCH;
1046 goto out;
1051 # endif /* Not Amiga && not WINDOWS32. */
1054 /* Now test whether we looked for "~" or "~NAME". In this case we
1055 can give the answer now. */
1056 if (filename == NULL)
1058 struct stat st;
1059 struct_stat64 st64;
1061 /* Return the directory if we don't check for error or if it exists. */
1062 if ((flags & GLOB_NOCHECK)
1063 || (((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1064 ? ((*pglob->gl_stat) (dirname, &st) == 0
1065 && S_ISDIR (st.st_mode))
1066 : (__stat64 (dirname, &st64) == 0 && S_ISDIR (st64.st_mode)))))
1068 size_t newcount = pglob->gl_pathc + pglob->gl_offs;
1069 char **new_gl_pathv;
1071 if (newcount > SIZE_MAX / sizeof (char *) - 2)
1073 nospace:
1074 free (pglob->gl_pathv);
1075 pglob->gl_pathv = NULL;
1076 pglob->gl_pathc = 0;
1077 retval = GLOB_NOSPACE;
1078 goto out;
1081 new_gl_pathv = realloc (pglob->gl_pathv,
1082 (newcount + 2) * sizeof (char *));
1083 if (new_gl_pathv == NULL)
1084 goto nospace;
1085 pglob->gl_pathv = new_gl_pathv;
1087 if (flags & GLOB_MARK)
1089 char *p;
1090 pglob->gl_pathv[newcount] = malloc (dirlen + 2);
1091 if (pglob->gl_pathv[newcount] == NULL)
1092 goto nospace;
1093 p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);
1094 p[0] = '/';
1095 p[1] = '\0';
1096 if (__glibc_unlikely (malloc_dirname))
1097 free (dirname);
1099 else
1101 if (__glibc_unlikely (malloc_dirname))
1102 pglob->gl_pathv[newcount] = dirname;
1103 else
1105 pglob->gl_pathv[newcount] = strdup (dirname);
1106 if (pglob->gl_pathv[newcount] == NULL)
1107 goto nospace;
1110 pglob->gl_pathv[++newcount] = NULL;
1111 ++pglob->gl_pathc;
1112 pglob->gl_flags = flags;
1114 return 0;
1117 /* Not found. */
1118 retval = GLOB_NOMATCH;
1119 goto out;
1122 meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));
1123 /* meta is 1 if correct glob pattern containing metacharacters.
1124 If meta has bit (1 << 2) set, it means there was an unterminated
1125 [ which we handle the same, using fnmatch. Broken unterminated
1126 pattern bracket expressions ought to be rare enough that it is
1127 not worth special casing them, fnmatch will do the right thing. */
1128 if (meta & 5)
1130 /* The directory name contains metacharacters, so we
1131 have to glob for the directory, and then glob for
1132 the pattern in each directory found. */
1133 size_t i;
1135 if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\')
1137 /* "foo\\/bar". Remove the final backslash from dirname
1138 if it has not been quoted. */
1139 char *p = (char *) &dirname[dirlen - 1];
1141 while (p > dirname && p[-1] == '\\') --p;
1142 if ((&dirname[dirlen] - p) & 1)
1143 *(char *) &dirname[--dirlen] = '\0';
1146 if (__glibc_unlikely ((flags & GLOB_ALTDIRFUNC) != 0))
1148 /* Use the alternative access functions also in the recursive
1149 call. */
1150 dirs.gl_opendir = pglob->gl_opendir;
1151 dirs.gl_readdir = pglob->gl_readdir;
1152 dirs.gl_closedir = pglob->gl_closedir;
1153 dirs.gl_stat = pglob->gl_stat;
1154 dirs.gl_lstat = pglob->gl_lstat;
1157 status = glob (dirname,
1158 ((flags & (GLOB_ERR | GLOB_NOESCAPE
1159 | GLOB_ALTDIRFUNC))
1160 | GLOB_NOSORT | GLOB_ONLYDIR),
1161 errfunc, &dirs);
1162 if (status != 0)
1164 if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH)
1166 retval = status;
1167 goto out;
1169 goto no_matches;
1172 /* We have successfully globbed the preceding directory name.
1173 For each name we found, call glob_in_dir on it and FILENAME,
1174 appending the results to PGLOB. */
1175 for (i = 0; i < dirs.gl_pathc; ++i)
1177 size_t old_pathc;
1179 #ifdef SHELL
1181 /* Make globbing interruptible in the bash shell. */
1182 extern int interrupt_state;
1184 if (interrupt_state)
1186 globfree (&dirs);
1187 retval = GLOB_ABORTED;
1188 goto out;
1191 #endif /* SHELL. */
1193 old_pathc = pglob->gl_pathc;
1194 status = glob_in_dir (filename, dirs.gl_pathv[i],
1195 ((flags | GLOB_APPEND)
1196 & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),
1197 errfunc, pglob, alloca_used);
1198 if (status == GLOB_NOMATCH)
1199 /* No matches in this directory. Try the next. */
1200 continue;
1202 if (status != 0)
1204 globfree (&dirs);
1205 globfree (pglob);
1206 pglob->gl_pathc = 0;
1207 retval = status;
1208 goto out;
1211 /* Stick the directory on the front of each name. */
1212 if (prefix_array (dirs.gl_pathv[i],
1213 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
1214 pglob->gl_pathc - old_pathc))
1216 globfree (&dirs);
1217 globfree (pglob);
1218 pglob->gl_pathc = 0;
1219 retval = GLOB_NOSPACE;
1220 goto out;
1224 flags |= GLOB_MAGCHAR;
1226 /* We have ignored the GLOB_NOCHECK flag in the 'glob_in_dir' calls.
1227 But if we have not found any matching entry and the GLOB_NOCHECK
1228 flag was set we must return the input pattern itself. */
1229 if (pglob->gl_pathc + pglob->gl_offs == oldcount)
1231 no_matches:
1232 /* No matches. */
1233 if (flags & GLOB_NOCHECK)
1235 size_t newcount = pglob->gl_pathc + pglob->gl_offs;
1236 char **new_gl_pathv;
1238 if (newcount > SIZE_MAX / sizeof (char *) - 2)
1240 nospace2:
1241 globfree (&dirs);
1242 retval = GLOB_NOSPACE;
1243 goto out;
1246 new_gl_pathv = realloc (pglob->gl_pathv,
1247 (newcount + 2) * sizeof (char *));
1248 if (new_gl_pathv == NULL)
1249 goto nospace2;
1250 pglob->gl_pathv = new_gl_pathv;
1252 pglob->gl_pathv[newcount] = strdup (pattern);
1253 if (pglob->gl_pathv[newcount] == NULL)
1255 globfree (&dirs);
1256 globfree (pglob);
1257 pglob->gl_pathc = 0;
1258 retval = GLOB_NOSPACE;
1259 goto out;
1262 ++pglob->gl_pathc;
1263 ++newcount;
1265 pglob->gl_pathv[newcount] = NULL;
1266 pglob->gl_flags = flags;
1268 else
1270 globfree (&dirs);
1271 retval = GLOB_NOMATCH;
1272 goto out;
1276 globfree (&dirs);
1278 else
1280 size_t old_pathc = pglob->gl_pathc;
1281 int orig_flags = flags;
1283 if (meta & 2)
1285 char *p = strchr (dirname, '\\'), *q;
1286 /* We need to unescape the dirname string. It is certainly
1287 allocated by alloca, as otherwise filename would be NULL
1288 or dirname wouldn't contain backslashes. */
1289 q = p;
1292 if (*p == '\\')
1294 *q = *++p;
1295 --dirlen;
1297 else
1298 *q = *p;
1299 ++q;
1301 while (*p++ != '\0');
1302 dirname_modified = 1;
1304 if (dirname_modified)
1305 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
1306 status = glob_in_dir (filename, dirname, flags, errfunc, pglob,
1307 alloca_used);
1308 if (status != 0)
1310 if (status == GLOB_NOMATCH && flags != orig_flags
1311 && pglob->gl_pathc + pglob->gl_offs == oldcount)
1313 /* Make sure globfree (&dirs); is a nop. */
1314 dirs.gl_pathv = NULL;
1315 flags = orig_flags;
1316 goto no_matches;
1318 retval = status;
1319 goto out;
1322 if (dirlen > 0)
1324 /* Stick the directory on the front of each name. */
1325 if (prefix_array (dirname,
1326 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
1327 pglob->gl_pathc - old_pathc))
1329 globfree (pglob);
1330 pglob->gl_pathc = 0;
1331 retval = GLOB_NOSPACE;
1332 goto out;
1337 if (flags & GLOB_MARK)
1339 /* Append slashes to directory names. */
1340 size_t i;
1341 struct stat st;
1342 struct_stat64 st64;
1344 for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)
1345 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1346 ? ((*pglob->gl_stat) (pglob->gl_pathv[i], &st) == 0
1347 && S_ISDIR (st.st_mode))
1348 : (__stat64 (pglob->gl_pathv[i], &st64) == 0
1349 && S_ISDIR (st64.st_mode))))
1351 size_t len = strlen (pglob->gl_pathv[i]) + 2;
1352 char *new = realloc (pglob->gl_pathv[i], len);
1353 if (new == NULL)
1355 globfree (pglob);
1356 pglob->gl_pathc = 0;
1357 retval = GLOB_NOSPACE;
1358 goto out;
1360 strcpy (&new[len - 2], "/");
1361 pglob->gl_pathv[i] = new;
1365 if (!(flags & GLOB_NOSORT))
1367 /* Sort the vector. */
1368 qsort (&pglob->gl_pathv[oldcount],
1369 pglob->gl_pathc + pglob->gl_offs - oldcount,
1370 sizeof (char *), collated_compare);
1373 out:
1374 if (__glibc_unlikely (malloc_dirname))
1375 free (dirname);
1377 return retval;
1379 #if defined _LIBC && !defined glob
1380 libc_hidden_def (glob)
1381 #endif
1384 #ifndef GLOB_ONLY_P
1386 /* Free storage allocated in PGLOB by a previous 'glob' call. */
1387 void
1388 globfree (glob_t *pglob)
1390 if (pglob->gl_pathv != NULL)
1392 size_t i;
1393 for (i = 0; i < pglob->gl_pathc; ++i)
1394 free (pglob->gl_pathv[pglob->gl_offs + i]);
1395 free (pglob->gl_pathv);
1396 pglob->gl_pathv = NULL;
1399 #if defined _LIBC && !defined globfree
1400 libc_hidden_def (globfree)
1401 #endif
1404 /* Do a collated comparison of A and B. */
1405 static int
1406 collated_compare (const void *a, const void *b)
1408 char *const *ps1 = a; char *s1 = *ps1;
1409 char *const *ps2 = b; char *s2 = *ps2;
1411 if (s1 == s2)
1412 return 0;
1413 if (s1 == NULL)
1414 return 1;
1415 if (s2 == NULL)
1416 return -1;
1417 return strcoll (s1, s2);
1421 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1422 elements in place. Return nonzero if out of memory, zero if successful.
1423 A slash is inserted between DIRNAME and each elt of ARRAY,
1424 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1425 static int
1426 prefix_array (const char *dirname, char **array, size_t n)
1428 size_t i;
1429 size_t dirlen = strlen (dirname);
1430 #if defined __MSDOS__ || defined WINDOWS32
1431 int sep_char = '/';
1432 # define DIRSEP_CHAR sep_char
1433 #else
1434 # define DIRSEP_CHAR '/'
1435 #endif
1437 if (dirlen == 1 && dirname[0] == '/')
1438 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1439 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1440 dirlen = 0;
1441 #if defined __MSDOS__ || defined WINDOWS32
1442 else if (dirlen > 1)
1444 if (dirname[dirlen - 1] == '/' && dirname[dirlen - 2] == ':')
1445 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1446 --dirlen;
1447 else if (dirname[dirlen - 1] == ':')
1449 /* DIRNAME is "d:". Use ':' instead of '/'. */
1450 --dirlen;
1451 sep_char = ':';
1454 #endif
1456 for (i = 0; i < n; ++i)
1458 size_t eltlen = strlen (array[i]) + 1;
1459 char *new = malloc (dirlen + 1 + eltlen);
1460 if (new == NULL)
1462 while (i > 0)
1463 free (array[--i]);
1464 return 1;
1468 char *endp = mempcpy (new, dirname, dirlen);
1469 *endp++ = DIRSEP_CHAR;
1470 mempcpy (endp, array[i], eltlen);
1472 free (array[i]);
1473 array[i] = new;
1476 return 0;
1480 /* We must not compile this function twice. */
1481 #ifndef NO_GLOB_PATTERN_P
1483 __glob_pattern_type (const char *pattern, int quote)
1485 const char *p;
1486 int ret = 0;
1488 for (p = pattern; *p != '\0'; ++p)
1489 switch (*p)
1491 case '?':
1492 case '*':
1493 return 1;
1495 case '\\':
1496 if (quote)
1498 if (p[1] != '\0')
1499 ++p;
1500 ret |= 2;
1502 break;
1504 case '[':
1505 ret |= 4;
1506 break;
1508 case ']':
1509 if (ret & 4)
1510 return 1;
1511 break;
1514 return ret;
1517 /* Return nonzero if PATTERN contains any metacharacters.
1518 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
1520 __glob_pattern_p (const char *pattern, int quote)
1522 return __glob_pattern_type (pattern, quote) == 1;
1524 # ifdef _LIBC
1525 weak_alias (__glob_pattern_p, glob_pattern_p)
1526 # endif
1527 #endif
1530 /* We put this in a separate function mainly to allow the memory
1531 allocated with alloca to be recycled. */
1532 static int
1533 __attribute_noinline__
1534 link_exists2_p (const char *dir, size_t dirlen, const char *fname,
1535 glob_t *pglob
1536 # if !defined _LIBC && !HAVE_FSTATAT
1537 , int flags
1538 # endif
1541 size_t fnamelen = strlen (fname);
1542 char *fullname = __alloca (dirlen + 1 + fnamelen + 1);
1543 struct stat st;
1545 mempcpy (mempcpy (mempcpy (fullname, dir, dirlen), "/", 1),
1546 fname, fnamelen + 1);
1548 # if !defined _LIBC && !HAVE_FSTATAT
1549 if (__builtin_expect ((flags & GLOB_ALTDIRFUNC) == 0, 1))
1551 struct_stat64 st64;
1552 return __stat64 (fullname, &st64) == 0;
1554 # endif
1555 return (*pglob->gl_stat) (fullname, &st) == 0;
1558 /* Return true if DIR/FNAME exists. */
1559 static int
1560 link_exists_p (int dfd, const char *dir, size_t dirlen, const char *fname,
1561 glob_t *pglob, int flags)
1563 # if defined _LIBC || HAVE_FSTATAT
1564 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1565 return link_exists2_p (dir, dirlen, fname, pglob);
1566 else
1568 /* dfd cannot be -1 here, because dirfd never returns -1 on
1569 glibc, or on hosts that have fstatat. */
1570 struct_stat64 st64;
1571 return __fxstatat64 (_STAT_VER, dfd, fname, &st64, 0) == 0;
1573 # else
1574 return link_exists2_p (dir, dirlen, fname, pglob, flags);
1575 # endif
1577 #endif /* !defined GLOB_ONLY_P */
1580 /* Like 'glob', but PATTERN is a final pathname component,
1581 and matches are searched for in DIRECTORY.
1582 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1583 The GLOB_APPEND flag is assumed to be set (always appends). */
1584 static int
1585 glob_in_dir (const char *pattern, const char *directory, int flags,
1586 int (*errfunc) (const char *, int),
1587 glob_t *pglob, size_t alloca_used)
1589 size_t dirlen = strlen (directory);
1590 void *stream = NULL;
1591 struct globnames
1593 struct globnames *next;
1594 size_t count;
1595 char *name[64];
1597 struct globnames init_names;
1598 struct globnames *names = &init_names;
1599 struct globnames *names_alloca = &init_names;
1600 size_t nfound = 0;
1601 size_t cur = 0;
1602 int meta;
1603 int save;
1604 int result;
1606 alloca_used += sizeof (init_names);
1608 init_names.next = NULL;
1609 init_names.count = sizeof init_names.name / sizeof init_names.name[0];
1611 meta = __glob_pattern_type (pattern, !(flags & GLOB_NOESCAPE));
1612 if (meta == 0 && (flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
1614 /* We need not do any tests. The PATTERN contains no meta
1615 characters and we must not return an error therefore the
1616 result will always contain exactly one name. */
1617 flags |= GLOB_NOCHECK;
1619 else if (meta == 0)
1621 /* Since we use the normal file functions we can also use stat()
1622 to verify the file is there. */
1623 union
1625 struct stat st;
1626 struct_stat64 st64;
1627 } ust;
1628 size_t patlen = strlen (pattern);
1629 size_t fullsize;
1630 bool alloca_fullname
1631 = (! size_add_wrapv (dirlen + 1, patlen + 1, &fullsize)
1632 && glob_use_alloca (alloca_used, fullsize));
1633 char *fullname;
1634 if (alloca_fullname)
1635 fullname = alloca_account (fullsize, alloca_used);
1636 else
1638 fullname = malloc (fullsize);
1639 if (fullname == NULL)
1640 return GLOB_NOSPACE;
1643 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1644 "/", 1),
1645 pattern, patlen + 1);
1646 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1647 ? (*pglob->gl_stat) (fullname, &ust.st)
1648 : __stat64 (fullname, &ust.st64)) == 0)
1649 /* We found this file to be existing. Now tell the rest
1650 of the function to copy this name into the result. */
1651 flags |= GLOB_NOCHECK;
1653 if (__glibc_unlikely (!alloca_fullname))
1654 free (fullname);
1656 else
1658 stream = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1659 ? (*pglob->gl_opendir) (directory)
1660 : opendir (directory));
1661 if (stream == NULL)
1663 if (errno != ENOTDIR
1664 && ((errfunc != NULL && (*errfunc) (directory, errno))
1665 || (flags & GLOB_ERR)))
1666 return GLOB_ABORTED;
1668 else
1670 int dfd = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1671 ? -1 : dirfd ((DIR *) stream));
1672 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1673 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1674 #if defined _AMIGA || defined VMS
1675 | FNM_CASEFOLD
1676 #endif
1678 flags |= GLOB_MAGCHAR;
1680 while (1)
1682 struct readdir_result d;
1684 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1685 d = convert_dirent (GL_READDIR (pglob, stream));
1686 else
1688 #ifdef COMPILE_GLOB64
1689 d = convert_dirent (__readdir (stream));
1690 #else
1691 d = convert_dirent64 (__readdir64 (stream));
1692 #endif
1695 if (d.name == NULL)
1696 break;
1697 if (d.skip_entry)
1698 continue;
1700 /* If we shall match only directories use the information
1701 provided by the dirent call if possible. */
1702 if ((flags & GLOB_ONLYDIR) && !readdir_result_might_be_dir (d))
1703 continue;
1705 if (fnmatch (pattern, d.name, fnm_flags) == 0)
1707 /* If the file we found is a symlink we have to
1708 make sure the target file exists. */
1709 if (!readdir_result_might_be_symlink (d)
1710 || link_exists_p (dfd, directory, dirlen, d.name,
1711 pglob, flags))
1713 if (cur == names->count)
1715 struct globnames *newnames;
1716 size_t count = names->count * 2;
1717 size_t nameoff = offsetof (struct globnames, name);
1718 size_t size = FLEXSIZEOF (struct globnames, name,
1719 count * sizeof (char *));
1720 if ((SIZE_MAX - nameoff) / 2 / sizeof (char *)
1721 < names->count)
1722 goto memory_error;
1723 if (glob_use_alloca (alloca_used, size))
1724 newnames = names_alloca
1725 = alloca_account (size, alloca_used);
1726 else if ((newnames = malloc (size))
1727 == NULL)
1728 goto memory_error;
1729 newnames->count = count;
1730 newnames->next = names;
1731 names = newnames;
1732 cur = 0;
1734 names->name[cur] = strdup (d.name);
1735 if (names->name[cur] == NULL)
1736 goto memory_error;
1737 ++cur;
1738 ++nfound;
1739 if (SIZE_MAX - pglob->gl_offs <= nfound)
1740 goto memory_error;
1747 if (nfound == 0 && (flags & GLOB_NOCHECK))
1749 size_t len = strlen (pattern);
1750 nfound = 1;
1751 names->name[cur] = malloc (len + 1);
1752 if (names->name[cur] == NULL)
1753 goto memory_error;
1754 *((char *) mempcpy (names->name[cur++], pattern, len)) = '\0';
1757 result = GLOB_NOMATCH;
1758 if (nfound != 0)
1760 char **new_gl_pathv;
1761 result = 0;
1763 if (SIZE_MAX / sizeof (char *) - pglob->gl_pathc
1764 < pglob->gl_offs + nfound + 1)
1765 goto memory_error;
1767 new_gl_pathv
1768 = realloc (pglob->gl_pathv,
1769 (pglob->gl_pathc + pglob->gl_offs + nfound + 1)
1770 * sizeof (char *));
1772 if (new_gl_pathv == NULL)
1774 memory_error:
1775 while (1)
1777 struct globnames *old = names;
1778 size_t i;
1779 for (i = 0; i < cur; ++i)
1780 free (names->name[i]);
1781 names = names->next;
1782 /* NB: we will not leak memory here if we exit without
1783 freeing the current block assigned to OLD. At least
1784 the very first block is always allocated on the stack
1785 and this is the block assigned to OLD here. */
1786 if (names == NULL)
1788 assert (old == &init_names);
1789 break;
1791 cur = names->count;
1792 if (old == names_alloca)
1793 names_alloca = names;
1794 else
1795 free (old);
1797 result = GLOB_NOSPACE;
1799 else
1801 while (1)
1803 struct globnames *old = names;
1804 size_t i;
1805 for (i = 0; i < cur; ++i)
1806 new_gl_pathv[pglob->gl_offs + pglob->gl_pathc++]
1807 = names->name[i];
1808 names = names->next;
1809 /* NB: we will not leak memory here if we exit without
1810 freeing the current block assigned to OLD. At least
1811 the very first block is always allocated on the stack
1812 and this is the block assigned to OLD here. */
1813 if (names == NULL)
1815 assert (old == &init_names);
1816 break;
1818 cur = names->count;
1819 if (old == names_alloca)
1820 names_alloca = names;
1821 else
1822 free (old);
1825 pglob->gl_pathv = new_gl_pathv;
1827 pglob->gl_pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
1829 pglob->gl_flags = flags;
1833 if (stream != NULL)
1835 save = errno;
1836 if (__glibc_unlikely (flags & GLOB_ALTDIRFUNC))
1837 (*pglob->gl_closedir) (stream);
1838 else
1839 closedir (stream);
1840 __set_errno (save);
1843 return result;