1/* Copyright (C) 1991-2016 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3
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.
8
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.
13
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/>. */
17
18#ifdef HAVE_CONFIG_H
19# include <config.h>
20#endif
21
22#include <glob.h>
23
24#include <errno.h>
25#include <sys/types.h>
26#include <sys/stat.h>
27#include <stdbool.h>
28#include <stddef.h>
29#include <stdint.h>
30
31/* Outcomment the following line for production quality code. */
32/* #define NDEBUG 1 */
33#include <assert.h>
34
35#include <stdio.h> /* Needed on stupid SunOS for assert. */
36
37#if !defined _LIBC || !defined GLOB_ONLY_P
38#if defined HAVE_UNISTD_H || defined _LIBC
39# include <unistd.h>
40# ifndef POSIX
41# ifdef _POSIX_VERSION
42# define POSIX
43# endif
44# endif
45#endif
46
47#include <pwd.h>
48
49#if defined HAVE_STDINT_H || defined _LIBC
50# include <stdint.h>
51#elif !defined UINTPTR_MAX
52# define UINTPTR_MAX (~((size_t) 0))
53#endif
54
55#include <errno.h>
56#ifndef __set_errno
57# define __set_errno(val) errno = (val)
58#endif
59
60#if defined HAVE_DIRENT_H || defined __GNU_LIBRARY__
61# include <dirent.h>
62#else
63# define dirent direct
64# ifdef HAVE_SYS_NDIR_H
65# include <sys/ndir.h>
66# endif
67# ifdef HAVE_SYS_DIR_H
68# include <sys/dir.h>
69# endif
70# ifdef HAVE_NDIR_H
71# include <ndir.h>
72# endif
73# ifdef HAVE_VMSDIR_H
74# include "vmsdir.h"
75# endif /* HAVE_VMSDIR_H */
76#endif
77
78#include <stdlib.h>
79#include <string.h>
80#include <alloca.h>
81
82#ifdef _LIBC
83# undef strdup
84# define strdup(str) __strdup (str)
85# define sysconf(id) __sysconf (id)
86# define closedir(dir) __closedir (dir)
87# define opendir(name) __opendir (name)
88# define readdir(str) __readdir64 (str)
89# define getpwnam_r(name, bufp, buf, len, res) \
90 __getpwnam_r (name, bufp, buf, len, res)
91# ifndef __stat64
92# define __stat64(fname, buf) __xstat64 (_STAT_VER, fname, buf)
93# endif
94# define struct_stat64 struct stat64
95#else /* !_LIBC */
96# include "getlogin_r.h"
97# include "mempcpy.h"
98# include "stat-macros.h"
99# include "strdup.h"
100# define __stat64(fname, buf) stat (fname, buf)
101# define struct_stat64 struct stat
102# define __stat(fname, buf) stat (fname, buf)
103# define __alloca alloca
104# define __readdir readdir
105# define __readdir64 readdir64
106# define __glob_pattern_p glob_pattern_p
107#endif /* _LIBC */
108
109#include <fnmatch.h>
110
111#ifdef _SC_GETPW_R_SIZE_MAX
112# define GETPW_R_SIZE_MAX() sysconf (_SC_GETPW_R_SIZE_MAX)
113#else
114# define GETPW_R_SIZE_MAX() (-1)
115#endif
116#ifdef _SC_LOGIN_NAME_MAX
117# define GET_LOGIN_NAME_MAX() sysconf (_SC_LOGIN_NAME_MAX)
118#else
119# define GET_LOGIN_NAME_MAX() (-1)
120#endif
121
122static const char *next_brace_sub (const char *begin, int flags) __THROWNL;
123
124/* A representation of a directory entry which does not depend on the
125 layout of struct dirent, or the size of ino_t. */
126struct readdir_result
127{
128 const char *name;
129# if defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE
130 uint8_t type;
131# endif
132 bool skip_entry;
133};
134
135# if defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE
136/* Initializer based on the d_type member of struct dirent. */
137# define D_TYPE_TO_RESULT(source) (source)->d_type,
138
139/* True if the directory entry D might be a symbolic link. */
140static bool
141readdir_result_might_be_symlink (struct readdir_result d)
142{
143 return d.type == DT_UNKNOWN || d.type == DT_LNK;
144}
145
146/* True if the directory entry D might be a directory. */
147static bool
148readdir_result_might_be_dir (struct readdir_result d)
149{
150 return d.type == DT_DIR || readdir_result_might_be_symlink (d);
151}
152# else /* defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE */
153# define D_TYPE_TO_RESULT(source)
154
155/* If we do not have type information, symbolic links and directories
156 are always a possibility. */
157
158static bool
159readdir_result_might_be_symlink (struct readdir_result d)
160{
161 return true;
162}
163
164static bool
165readdir_result_might_be_dir (struct readdir_result d)
166{
167 return true;
168}
169
170# endif /* defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE */
171
172# if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
173/* Initializer for skip_entry. POSIX does not require that the d_ino
174 field be present, and some systems do not provide it. */
175# define D_INO_TO_RESULT(source) false,
176# else
177# define D_INO_TO_RESULT(source) (source)->d_ino == 0,
178# endif
179
180/* Construct an initializer for a struct readdir_result object from a
181 struct dirent *. No copy of the name is made. */
182#define READDIR_RESULT_INITIALIZER(source) \
183 { \
184 source->d_name, \
185 D_TYPE_TO_RESULT (source) \
186 D_INO_TO_RESULT (source) \
187 }
188
189#endif /* !defined _LIBC || !defined GLOB_ONLY_P */
190
191/* Call gl_readdir on STREAM. This macro can be overridden to reduce
192 type safety if an old interface version needs to be supported. */
193#ifndef GL_READDIR
194# define GL_READDIR(pglob, stream) ((pglob)->gl_readdir (stream))
195#endif
196
197/* Extract name and type from directory entry. No copy of the name is
198 made. If SOURCE is NULL, result name is NULL. Keep in sync with
199 convert_dirent64 below. */
200static struct readdir_result
201convert_dirent (const struct dirent *source)
202{
203 if (source == NULL)
204 {
205 struct readdir_result result = { NULL, };
206 return result;
207 }
208 struct readdir_result result = READDIR_RESULT_INITIALIZER (source);
209 return result;
210}
211
212#ifndef COMPILE_GLOB64
213/* Like convert_dirent, but works on struct dirent64 instead. Keep in
214 sync with convert_dirent above. */
215static struct readdir_result
216convert_dirent64 (const struct dirent64 *source)
217{
218 if (source == NULL)
219 {
220 struct readdir_result result = { NULL, };
221 return result;
222 }
223 struct readdir_result result = READDIR_RESULT_INITIALIZER (source);
224 return result;
225}
226#endif
227
228
229#ifndef attribute_hidden
230# define attribute_hidden
231#endif
232
233static int glob_in_dir (const char *pattern, const char *directory,
234 int flags, int (*errfunc) (const char *, int),
235 glob_t *pglob, size_t alloca_used);
236extern int __glob_pattern_type (const char *pattern, int quote)
237 attribute_hidden;
238
239#if !defined _LIBC || !defined GLOB_ONLY_P
240static int prefix_array (const char *prefix, char **array, size_t n) __THROWNL;
241static int collated_compare (const void *, const void *) __THROWNL;
242
243
244/* Find the end of the sub-pattern in a brace expression. */
245static const char *
246next_brace_sub (const char *cp, int flags)
247{
248 size_t depth = 0;
249 while (*cp != '\0')
250 if ((flags & GLOB_NOESCAPE) == 0 && *cp == '\\')
251 {
252 if (*++cp == '\0')
253 break;
254 ++cp;
255 }
256 else
257 {
258 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
259 break;
260
261 if (*cp++ == '{')
262 depth++;
263 }
264
265 return *cp != '\0' ? cp : NULL;
266}
267
268#endif /* !defined _LIBC || !defined GLOB_ONLY_P */
269
270/* Do glob searching for PATTERN, placing results in PGLOB.
271 The bits defined above may be set in FLAGS.
272 If a directory cannot be opened or read and ERRFUNC is not nil,
273 it is called with the pathname that caused the error, and the
274 `errno' value from the failing call; if it returns non-zero
275 `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
276 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
277 Otherwise, `glob' returns zero. */
278int
279#ifdef GLOB_ATTRIBUTE
280GLOB_ATTRIBUTE
281#endif
282glob (const char *pattern, int flags, int (*errfunc) (const char *, int),
283 glob_t *pglob)
284{
285 const char *filename;
286 char *dirname = NULL;
287 size_t dirlen;
288 int status;
289 size_t oldcount;
290 int meta;
291 int dirname_modified;
292 int malloc_dirname = 0;
293 glob_t dirs;
294 int retval = 0;
295#ifdef _LIBC
296 size_t alloca_used = 0;
297#endif
298
299 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
300 {
301 __set_errno (EINVAL);
302 return -1;
303 }
304
305 /* POSIX requires all slashes to be matched. This means that with
306 a trailing slash we must match only directories. */
307 if (pattern[0] && pattern[strlen (pattern) - 1] == '/')
308 flags |= GLOB_ONLYDIR;
309
310 if (!(flags & GLOB_DOOFFS))
311 /* Have to do this so `globfree' knows where to start freeing. It
312 also makes all the code that uses gl_offs simpler. */
313 pglob->gl_offs = 0;
314
315 if (flags & GLOB_BRACE)
316 {
317 const char *begin;
318
319 if (flags & GLOB_NOESCAPE)
320 begin = strchr (pattern, '{');
321 else
322 {
323 begin = pattern;
324 while (1)
325 {
326 if (*begin == '\0')
327 {
328 begin = NULL;
329 break;
330 }
331
332 if (*begin == '\\' && begin[1] != '\0')
333 ++begin;
334 else if (*begin == '{')
335 break;
336
337 ++begin;
338 }
339 }
340
341 if (begin != NULL)
342 {
343 /* Allocate working buffer large enough for our work. Note that
344 we have at least an opening and closing brace. */
345 size_t firstc;
346 char *alt_start;
347 const char *p;
348 const char *next;
349 const char *rest;
350 size_t rest_len;
351 char *onealt;
352 size_t pattern_len = strlen (pattern) - 1;
353#ifdef _LIBC
354 int alloca_onealt = __libc_use_alloca (alloca_used + pattern_len);
355 if (alloca_onealt)
356 onealt = alloca_account (pattern_len, alloca_used);
357 else
358#endif
359 {
360 onealt = (char *) malloc (pattern_len);
361 if (onealt == NULL)
362 {
363 if (!(flags & GLOB_APPEND))
364 {
365 pglob->gl_pathc = 0;
366 pglob->gl_pathv = NULL;
367 }
368 return GLOB_NOSPACE;
369 }
370 }
371
372 /* We know the prefix for all sub-patterns. */
373 alt_start = mempcpy (onealt, pattern, begin - pattern);
374
375 /* Find the first sub-pattern and at the same time find the
376 rest after the closing brace. */
377 next = next_brace_sub (begin + 1, flags);
378 if (next == NULL)
379 {
380 /* It is an illegal expression. */
381 illegal_brace:
382#ifdef _LIBC
383 if (__glibc_unlikely (!alloca_onealt))
384#endif
385 free (onealt);
386 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
387 }
388
389 /* Now find the end of the whole brace expression. */
390 rest = next;
391 while (*rest != '}')
392 {
393 rest = next_brace_sub (rest + 1, flags);
394 if (rest == NULL)
395 /* It is an illegal expression. */
396 goto illegal_brace;
397 }
398 /* Please note that we now can be sure the brace expression
399 is well-formed. */
400 rest_len = strlen (++rest) + 1;
401
402 /* We have a brace expression. BEGIN points to the opening {,
403 NEXT points past the terminator of the first element, and END
404 points past the final }. We will accumulate result names from
405 recursive runs for each brace alternative in the buffer using
406 GLOB_APPEND. */
407
408 if (!(flags & GLOB_APPEND))
409 {
410 /* This call is to set a new vector, so clear out the
411 vector so we can append to it. */
412 pglob->gl_pathc = 0;
413 pglob->gl_pathv = NULL;
414 }
415 firstc = pglob->gl_pathc;
416
417 p = begin + 1;
418 while (1)
419 {
420 int result;
421
422 /* Construct the new glob expression. */
423 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
424
425 result = glob (onealt,
426 ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))
427 | GLOB_APPEND), errfunc, pglob);
428
429 /* If we got an error, return it. */
430 if (result && result != GLOB_NOMATCH)
431 {
432#ifdef _LIBC
433 if (__glibc_unlikely (!alloca_onealt))
434#endif
435 free (onealt);
436 if (!(flags & GLOB_APPEND))
437 {
438 globfree (pglob);
439 pglob->gl_pathc = 0;
440 }
441 return result;
442 }
443
444 if (*next == '}')
445 /* We saw the last entry. */
446 break;
447
448 p = next + 1;
449 next = next_brace_sub (p, flags);
450 assert (next != NULL);
451 }
452
453#ifdef _LIBC
454 if (__glibc_unlikely (!alloca_onealt))
455#endif
456 free (onealt);
457
458 if (pglob->gl_pathc != firstc)
459 /* We found some entries. */
460 return 0;
461 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
462 return GLOB_NOMATCH;
463 }
464 }
465
466 if (!(flags & GLOB_APPEND))
467 {
468 pglob->gl_pathc = 0;
469 if (!(flags & GLOB_DOOFFS))
470 pglob->gl_pathv = NULL;
471 else
472 {
473 size_t i;
474
475 if (pglob->gl_offs >= ~((size_t) 0) / sizeof (char *))
476 return GLOB_NOSPACE;
477
478 pglob->gl_pathv = (char **) malloc ((pglob->gl_offs + 1)
479 * sizeof (char *));
480 if (pglob->gl_pathv == NULL)
481 return GLOB_NOSPACE;
482
483 for (i = 0; i <= pglob->gl_offs; ++i)
484 pglob->gl_pathv[i] = NULL;
485 }
486 }
487
488 oldcount = pglob->gl_pathc + pglob->gl_offs;
489
490 /* Find the filename. */
491 filename = strrchr (pattern, '/');
492#if defined __MSDOS__ || defined WINDOWS32
493 /* The case of "d:pattern". Since `:' is not allowed in
494 file names, we can safely assume that wherever it
495 happens in pattern, it signals the filename part. This
496 is so we could some day support patterns like "[a-z]:foo". */
497 if (filename == NULL)
498 filename = strchr (pattern, ':');
499#endif /* __MSDOS__ || WINDOWS32 */
500 dirname_modified = 0;
501 if (filename == NULL)
502 {
503 /* This can mean two things: a simple name or "~name". The latter
504 case is nothing but a notation for a directory. */
505 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
506 {
507 dirname = (char *) pattern;
508 dirlen = strlen (pattern);
509
510 /* Set FILENAME to NULL as a special flag. This is ugly but
511 other solutions would require much more code. We test for
512 this special case below. */
513 filename = NULL;
514 }
515 else
516 {
517 if (__glibc_unlikely (pattern[0] == '\0'))
518 {
519 dirs.gl_pathv = NULL;
520 goto no_matches;
521 }
522
523 filename = pattern;
524#ifdef _AMIGA
525 dirname = (char *) "";
526#else
527 dirname = (char *) ".";
528#endif
529 dirlen = 0;
530 }
531 }
532 else if (filename == pattern
533 || (filename == pattern + 1 && pattern[0] == '\\'
534 && (flags & GLOB_NOESCAPE) == 0))
535 {
536 /* "/pattern" or "\\/pattern". */
537 dirname = (char *) "/";
538 dirlen = 1;
539 ++filename;
540 }
541 else
542 {
543 char *newp;
544 dirlen = filename - pattern;
545#if defined __MSDOS__ || defined WINDOWS32
546 if (*filename == ':'
547 || (filename > pattern + 1 && filename[-1] == ':'))
548 {
549 char *drive_spec;
550
551 ++dirlen;
552 drive_spec = (char *) __alloca (dirlen + 1);
553 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
554 /* For now, disallow wildcards in the drive spec, to
555 prevent infinite recursion in glob. */
556 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
557 return GLOB_NOMATCH;
558 /* If this is "d:pattern", we need to copy `:' to DIRNAME
559 as well. If it's "d:/pattern", don't remove the slash
560 from "d:/", since "d:" and "d:/" are not the same.*/
561 }
562#endif
563#ifdef _LIBC
564 if (__libc_use_alloca (alloca_used + dirlen + 1))
565 newp = alloca_account (dirlen + 1, alloca_used);
566 else
567#endif
568 {
569 newp = malloc (dirlen + 1);
570 if (newp == NULL)
571 return GLOB_NOSPACE;
572 malloc_dirname = 1;
573 }
574 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
575 dirname = newp;
576 ++filename;
577
578 if (filename[0] == '\0'
579#if defined __MSDOS__ || defined WINDOWS32
580 && dirname[dirlen - 1] != ':'
581 && (dirlen < 3 || dirname[dirlen - 2] != ':'
582 || dirname[dirlen - 1] != '/')
583#endif
584 && dirlen > 1)
585 /* "pattern/". Expand "pattern", appending slashes. */
586 {
587 int orig_flags = flags;
588 if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\')
589 {
590 /* "pattern\\/". Remove the final backslash if it hasn't
591 been quoted. */
592 char *p = (char *) &dirname[dirlen - 1];
593
594 while (p > dirname && p[-1] == '\\') --p;
595 if ((&dirname[dirlen] - p) & 1)
596 {
597 *(char *) &dirname[--dirlen] = '\0';
598 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
599 }
600 }
601 int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
602 if (val == 0)
603 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
604 | (flags & GLOB_MARK));
605 else if (val == GLOB_NOMATCH && flags != orig_flags)
606 {
607 /* Make sure globfree (&dirs); is a nop. */
608 dirs.gl_pathv = NULL;
609 flags = orig_flags;
610 oldcount = pglob->gl_pathc + pglob->gl_offs;
611 goto no_matches;
612 }
613 retval = val;
614 goto out;
615 }
616 }
617
618#ifndef VMS
619 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
620 {
621 if (dirname[1] == '\0' || dirname[1] == '/'
622 || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\'
623 && (dirname[2] == '\0' || dirname[2] == '/')))
624 {
625 /* Look up home directory. */
626 char *home_dir = getenv ("HOME");
627 int malloc_home_dir = 0;
628# ifdef _AMIGA
629 if (home_dir == NULL || home_dir[0] == '\0')
630 home_dir = "SYS:";
631# else
632# ifdef WINDOWS32
633 if (home_dir == NULL || home_dir[0] == '\0')
634 home_dir = "c:/users/default"; /* poor default */
635# else
636 if (home_dir == NULL || home_dir[0] == '\0')
637 {
638 int success;
639 char *name;
640 size_t buflen = GET_LOGIN_NAME_MAX () + 1;
641
642 if (buflen == 0)
643 /* `sysconf' does not support _SC_LOGIN_NAME_MAX. Try
644 a moderate value. */
645 buflen = 20;
646 name = alloca_account (buflen, alloca_used);
647
648 success = __getlogin_r (name, buflen) == 0;
649 if (success)
650 {
651 struct passwd *p;
652# if defined HAVE_GETPWNAM_R || defined _LIBC
653 long int pwbuflen = GETPW_R_SIZE_MAX ();
654 char *pwtmpbuf;
655 struct passwd pwbuf;
656 int malloc_pwtmpbuf = 0;
657 int save = errno;
658
659# ifndef _LIBC
660 if (pwbuflen == -1)
661 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.
662 Try a moderate value. */
663 pwbuflen = 1024;
664# endif
665 if (__libc_use_alloca (alloca_used + pwbuflen))
666 pwtmpbuf = alloca_account (pwbuflen, alloca_used);
667 else
668 {
669 pwtmpbuf = malloc (pwbuflen);
670 if (pwtmpbuf == NULL)
671 {
672 retval = GLOB_NOSPACE;
673 goto out;
674 }
675 malloc_pwtmpbuf = 1;
676 }
677
678 while (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
679 != 0)
680 {
681 if (errno != ERANGE)
682 {
683 p = NULL;
684 break;
685 }
686
687 if (!malloc_pwtmpbuf
688 && __libc_use_alloca (alloca_used
689 + 2 * pwbuflen))
690 pwtmpbuf = extend_alloca_account (pwtmpbuf, pwbuflen,
691 2 * pwbuflen,
692 alloca_used);
693 else
694 {
695 char *newp = realloc (malloc_pwtmpbuf
696 ? pwtmpbuf : NULL,
697 2 * pwbuflen);
698 if (newp == NULL)
699 {
700 if (__glibc_unlikely (malloc_pwtmpbuf))
701 free (pwtmpbuf);
702 retval = GLOB_NOSPACE;
703 goto out;
704 }
705 pwtmpbuf = newp;
706 pwbuflen = 2 * pwbuflen;
707 malloc_pwtmpbuf = 1;
708 }
709 __set_errno (save);
710 }
711# else
712 p = getpwnam (name);
713# endif
714 if (p != NULL)
715 {
716 if (!malloc_pwtmpbuf)
717 home_dir = p->pw_dir;
718 else
719 {
720 size_t home_dir_len = strlen (p->pw_dir) + 1;
721 if (__libc_use_alloca (alloca_used + home_dir_len))
722 home_dir = alloca_account (home_dir_len,
723 alloca_used);
724 else
725 {
726 home_dir = malloc (home_dir_len);
727 if (home_dir == NULL)
728 {
729 free (pwtmpbuf);
730 retval = GLOB_NOSPACE;
731 goto out;
732 }
733 malloc_home_dir = 1;
734 }
735 memcpy (home_dir, p->pw_dir, home_dir_len);
736
737 free (pwtmpbuf);
738 }
739 }
740 }
741 }
742 if (home_dir == NULL || home_dir[0] == '\0')
743 {
744 if (flags & GLOB_TILDE_CHECK)
745 {
746 if (__glibc_unlikely (malloc_home_dir))
747 free (home_dir);
748 retval = GLOB_NOMATCH;
749 goto out;
750 }
751 else
752 home_dir = (char *) "~"; /* No luck. */
753 }
754# endif /* WINDOWS32 */
755# endif
756 /* Now construct the full directory. */
757 if (dirname[1] == '\0')
758 {
759 if (__glibc_unlikely (malloc_dirname))
760 free (dirname);
761
762 dirname = home_dir;
763 dirlen = strlen (dirname);
764 malloc_dirname = malloc_home_dir;
765 }
766 else
767 {
768 char *newp;
769 size_t home_len = strlen (home_dir);
770 int use_alloca = __libc_use_alloca (alloca_used
771 + home_len + dirlen);
772 if (use_alloca)
773 newp = alloca_account (home_len + dirlen, alloca_used);
774 else
775 {
776 newp = malloc (home_len + dirlen);
777 if (newp == NULL)
778 {
779 if (__glibc_unlikely (malloc_home_dir))
780 free (home_dir);
781 retval = GLOB_NOSPACE;
782 goto out;
783 }
784 }
785
786 mempcpy (mempcpy (newp, home_dir, home_len),
787 &dirname[1], dirlen);
788
789 if (__glibc_unlikely (malloc_dirname))
790 free (dirname);
791
792 dirname = newp;
793 dirlen += home_len - 1;
794 malloc_dirname = !use_alloca;
795 }
796 dirname_modified = 1;
797 }
798# if !defined _AMIGA && !defined WINDOWS32
799 else
800 {
801 char *end_name = strchr (dirname, '/');
802 char *user_name;
803 int malloc_user_name = 0;
804 char *unescape = NULL;
805
806 if (!(flags & GLOB_NOESCAPE))
807 {
808 if (end_name == NULL)
809 {
810 unescape = strchr (dirname, '\\');
811 if (unescape)
812 end_name = strchr (unescape, '\0');
813 }
814 else
815 unescape = memchr (dirname, '\\', end_name - dirname);
816 }
817 if (end_name == NULL)
818 user_name = dirname + 1;
819 else
820 {
821 char *newp;
822 if (__libc_use_alloca (alloca_used + (end_name - dirname)))
823 newp = alloca_account (end_name - dirname, alloca_used);
824 else
825 {
826 newp = malloc (end_name - dirname);
827 if (newp == NULL)
828 {
829 retval = GLOB_NOSPACE;
830 goto out;
831 }
832 malloc_user_name = 1;
833 }
834 if (unescape != NULL)
835 {
836 char *p = mempcpy (newp, dirname + 1,
837 unescape - dirname - 1);
838 char *q = unescape;
839 while (*q != '\0')
840 {
841 if (*q == '\\')
842 {
843 if (q[1] == '\0')
844 {
845 /* "~fo\\o\\" unescape to user_name "foo\\",
846 but "~fo\\o\\/" unescape to user_name
847 "foo". */
848 if (filename == NULL)
849 *p++ = '\\';
850 break;
851 }
852 ++q;
853 }
854 *p++ = *q++;
855 }
856 *p = '\0';
857 }
858 else
859 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
860 = '\0';
861 user_name = newp;
862 }
863
864 /* Look up specific user's home directory. */
865 {
866 struct passwd *p;
867# if defined HAVE_GETPWNAM_R || defined _LIBC
868 long int buflen = GETPW_R_SIZE_MAX ();
869 char *pwtmpbuf;
870 int malloc_pwtmpbuf = 0;
871 struct passwd pwbuf;
872 int save = errno;
873
874# ifndef _LIBC
875 if (buflen == -1)
876 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
877 moderate value. */
878 buflen = 1024;
879# endif
880 if (__libc_use_alloca (alloca_used + buflen))
881 pwtmpbuf = alloca_account (buflen, alloca_used);
882 else
883 {
884 pwtmpbuf = malloc (buflen);
885 if (pwtmpbuf == NULL)
886 {
887 nomem_getpw:
888 if (__glibc_unlikely (malloc_user_name))
889 free (user_name);
890 retval = GLOB_NOSPACE;
891 goto out;
892 }
893 malloc_pwtmpbuf = 1;
894 }
895
896 while (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) != 0)
897 {
898 if (errno != ERANGE)
899 {
900 p = NULL;
901 break;
902 }
903 if (!malloc_pwtmpbuf
904 && __libc_use_alloca (alloca_used + 2 * buflen))
905 pwtmpbuf = extend_alloca_account (pwtmpbuf, buflen,
906 2 * buflen, alloca_used);
907 else
908 {
909 char *newp = realloc (malloc_pwtmpbuf ? pwtmpbuf : NULL,
910 2 * buflen);
911 if (newp == NULL)
912 {
913 if (__glibc_unlikely (malloc_pwtmpbuf))
914 free (pwtmpbuf);
915 goto nomem_getpw;
916 }
917 pwtmpbuf = newp;
918 malloc_pwtmpbuf = 1;
919 }
920 __set_errno (save);
921 }
922# else
923 p = getpwnam (user_name);
924# endif
925
926 if (__glibc_unlikely (malloc_user_name))
927 free (user_name);
928
929 /* If we found a home directory use this. */
930 if (p != NULL)
931 {
932 size_t home_len = strlen (p->pw_dir);
933 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
934
935 if (__glibc_unlikely (malloc_dirname))
936 free (dirname);
937 malloc_dirname = 0;
938
939 if (__libc_use_alloca (alloca_used + home_len + rest_len + 1))
940 dirname = alloca_account (home_len + rest_len + 1,
941 alloca_used);
942 else
943 {
944 dirname = malloc (home_len + rest_len + 1);
945 if (dirname == NULL)
946 {
947 if (__glibc_unlikely (malloc_pwtmpbuf))
948 free (pwtmpbuf);
949 retval = GLOB_NOSPACE;
950 goto out;
951 }
952 malloc_dirname = 1;
953 }
954 *((char *) mempcpy (mempcpy (dirname, p->pw_dir, home_len),
955 end_name, rest_len)) = '\0';
956
957 dirlen = home_len + rest_len;
958 dirname_modified = 1;
959
960 if (__glibc_unlikely (malloc_pwtmpbuf))
961 free (pwtmpbuf);
962 }
963 else
964 {
965 if (__glibc_unlikely (malloc_pwtmpbuf))
966 free (pwtmpbuf);
967
968 if (flags & GLOB_TILDE_CHECK)
969 /* We have to regard it as an error if we cannot find the
970 home directory. */
971 return GLOB_NOMATCH;
972 }
973 }
974 }
975# endif /* Not Amiga && not WINDOWS32. */
976 }
977#endif /* Not VMS. */
978
979 /* Now test whether we looked for "~" or "~NAME". In this case we
980 can give the answer now. */
981 if (filename == NULL)
982 {
983 struct stat st;
984 struct_stat64 st64;
985
986 /* Return the directory if we don't check for error or if it exists. */
987 if ((flags & GLOB_NOCHECK)
988 || (((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
989 ? ((*pglob->gl_stat) (dirname, &st) == 0
990 && S_ISDIR (st.st_mode))
991 : (__stat64 (dirname, &st64) == 0 && S_ISDIR (st64.st_mode)))))
992 {
993 size_t newcount = pglob->gl_pathc + pglob->gl_offs;
994 char **new_gl_pathv;
995
996 if (newcount > UINTPTR_MAX - (1 + 1)
997 || newcount + 1 + 1 > ~((size_t) 0) / sizeof (char *))
998 {
999 nospace:
1000 free (pglob->gl_pathv);
1001 pglob->gl_pathv = NULL;
1002 pglob->gl_pathc = 0;
1003 return GLOB_NOSPACE;
1004 }
1005
1006 new_gl_pathv
1007 = (char **) realloc (pglob->gl_pathv,
1008 (newcount + 1 + 1) * sizeof (char *));
1009 if (new_gl_pathv == NULL)
1010 goto nospace;
1011 pglob->gl_pathv = new_gl_pathv;
1012
1013 if (flags & GLOB_MARK)
1014 {
1015 char *p;
1016 pglob->gl_pathv[newcount] = malloc (dirlen + 2);
1017 if (pglob->gl_pathv[newcount] == NULL)
1018 goto nospace;
1019 p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);
1020 p[0] = '/';
1021 p[1] = '\0';
1022 }
1023 else
1024 {
1025 pglob->gl_pathv[newcount] = strdup (dirname);
1026 if (pglob->gl_pathv[newcount] == NULL)
1027 goto nospace;
1028 }
1029 pglob->gl_pathv[++newcount] = NULL;
1030 ++pglob->gl_pathc;
1031 pglob->gl_flags = flags;
1032
1033 return 0;
1034 }
1035
1036 /* Not found. */
1037 return GLOB_NOMATCH;
1038 }
1039
1040 meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));
1041 /* meta is 1 if correct glob pattern containing metacharacters.
1042 If meta has bit (1 << 2) set, it means there was an unterminated
1043 [ which we handle the same, using fnmatch. Broken unterminated
1044 pattern bracket expressions ought to be rare enough that it is
1045 not worth special casing them, fnmatch will do the right thing. */
1046 if (meta & 5)
1047 {
1048 /* The directory name contains metacharacters, so we
1049 have to glob for the directory, and then glob for
1050 the pattern in each directory found. */
1051 size_t i;
1052
1053 if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\')
1054 {
1055 /* "foo\\/bar". Remove the final backslash from dirname
1056 if it has not been quoted. */
1057 char *p = (char *) &dirname[dirlen - 1];
1058
1059 while (p > dirname && p[-1] == '\\') --p;
1060 if ((&dirname[dirlen] - p) & 1)
1061 *(char *) &dirname[--dirlen] = '\0';
1062 }
1063
1064 if (__glibc_unlikely ((flags & GLOB_ALTDIRFUNC) != 0))
1065 {
1066 /* Use the alternative access functions also in the recursive
1067 call. */
1068 dirs.gl_opendir = pglob->gl_opendir;
1069 dirs.gl_readdir = pglob->gl_readdir;
1070 dirs.gl_closedir = pglob->gl_closedir;
1071 dirs.gl_stat = pglob->gl_stat;
1072 dirs.gl_lstat = pglob->gl_lstat;
1073 }
1074
1075 status = glob (dirname,
1076 ((flags & (GLOB_ERR | GLOB_NOESCAPE
1077 | GLOB_ALTDIRFUNC))
1078 | GLOB_NOSORT | GLOB_ONLYDIR),
1079 errfunc, &dirs);
1080 if (status != 0)
1081 {
1082 if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH)
1083 return status;
1084 goto no_matches;
1085 }
1086
1087 /* We have successfully globbed the preceding directory name.
1088 For each name we found, call glob_in_dir on it and FILENAME,
1089 appending the results to PGLOB. */
1090 for (i = 0; i < dirs.gl_pathc; ++i)
1091 {
1092 size_t old_pathc;
1093
1094#ifdef SHELL
1095 {
1096 /* Make globbing interruptible in the bash shell. */
1097 extern int interrupt_state;
1098
1099 if (interrupt_state)
1100 {
1101 globfree (&dirs);
1102 return GLOB_ABORTED;
1103 }
1104 }
1105#endif /* SHELL. */
1106
1107 old_pathc = pglob->gl_pathc;
1108 status = glob_in_dir (filename, dirs.gl_pathv[i],
1109 ((flags | GLOB_APPEND)
1110 & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),
1111 errfunc, pglob, alloca_used);
1112 if (status == GLOB_NOMATCH)
1113 /* No matches in this directory. Try the next. */
1114 continue;
1115
1116 if (status != 0)
1117 {
1118 globfree (&dirs);
1119 globfree (pglob);
1120 pglob->gl_pathc = 0;
1121 return status;
1122 }
1123
1124 /* Stick the directory on the front of each name. */
1125 if (prefix_array (dirs.gl_pathv[i],
1126 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
1127 pglob->gl_pathc - old_pathc))
1128 {
1129 globfree (&dirs);
1130 globfree (pglob);
1131 pglob->gl_pathc = 0;
1132 return GLOB_NOSPACE;
1133 }
1134 }
1135
1136 flags |= GLOB_MAGCHAR;
1137
1138 /* We have ignored the GLOB_NOCHECK flag in the `glob_in_dir' calls.
1139 But if we have not found any matching entry and the GLOB_NOCHECK
1140 flag was set we must return the input pattern itself. */
1141 if (pglob->gl_pathc + pglob->gl_offs == oldcount)
1142 {
1143 no_matches:
1144 /* No matches. */
1145 if (flags & GLOB_NOCHECK)
1146 {
1147 size_t newcount = pglob->gl_pathc + pglob->gl_offs;
1148 char **new_gl_pathv;
1149
1150 if (newcount > UINTPTR_MAX - 2
1151 || newcount + 2 > ~((size_t) 0) / sizeof (char *))
1152 {
1153 nospace2:
1154 globfree (&dirs);
1155 return GLOB_NOSPACE;
1156 }
1157
1158 new_gl_pathv = (char **) realloc (pglob->gl_pathv,
1159 (newcount + 2)
1160 * sizeof (char *));
1161 if (new_gl_pathv == NULL)
1162 goto nospace2;
1163 pglob->gl_pathv = new_gl_pathv;
1164
1165 pglob->gl_pathv[newcount] = __strdup (pattern);
1166 if (pglob->gl_pathv[newcount] == NULL)
1167 {
1168 globfree (&dirs);
1169 globfree (pglob);
1170 pglob->gl_pathc = 0;
1171 return GLOB_NOSPACE;
1172 }
1173
1174 ++pglob->gl_pathc;
1175 ++newcount;
1176
1177 pglob->gl_pathv[newcount] = NULL;
1178 pglob->gl_flags = flags;
1179 }
1180 else
1181 {
1182 globfree (&dirs);
1183 return GLOB_NOMATCH;
1184 }
1185 }
1186
1187 globfree (&dirs);
1188 }
1189 else
1190 {
1191 size_t old_pathc = pglob->gl_pathc;
1192 int orig_flags = flags;
1193
1194 if (meta & 2)
1195 {
1196 char *p = strchr (dirname, '\\'), *q;
1197 /* We need to unescape the dirname string. It is certainly
1198 allocated by alloca, as otherwise filename would be NULL
1199 or dirname wouldn't contain backslashes. */
1200 q = p;
1201 do
1202 {
1203 if (*p == '\\')
1204 {
1205 *q = *++p;
1206 --dirlen;
1207 }
1208 else
1209 *q = *p;
1210 ++q;
1211 }
1212 while (*p++ != '\0');
1213 dirname_modified = 1;
1214 }
1215 if (dirname_modified)
1216 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
1217 status = glob_in_dir (filename, dirname, flags, errfunc, pglob,
1218 alloca_used);
1219 if (status != 0)
1220 {
1221 if (status == GLOB_NOMATCH && flags != orig_flags
1222 && pglob->gl_pathc + pglob->gl_offs == oldcount)
1223 {
1224 /* Make sure globfree (&dirs); is a nop. */
1225 dirs.gl_pathv = NULL;
1226 flags = orig_flags;
1227 goto no_matches;
1228 }
1229 return status;
1230 }
1231
1232 if (dirlen > 0)
1233 {
1234 /* Stick the directory on the front of each name. */
1235 if (prefix_array (dirname,
1236 &pglob->gl_pathv[old_pathc + pglob->gl_offs],
1237 pglob->gl_pathc - old_pathc))
1238 {
1239 globfree (pglob);
1240 pglob->gl_pathc = 0;
1241 return GLOB_NOSPACE;
1242 }
1243 }
1244 }
1245
1246 if (flags & GLOB_MARK)
1247 {
1248 /* Append slashes to directory names. */
1249 size_t i;
1250 struct stat st;
1251 struct_stat64 st64;
1252
1253 for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)
1254 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1255 ? ((*pglob->gl_stat) (pglob->gl_pathv[i], &st) == 0
1256 && S_ISDIR (st.st_mode))
1257 : (__stat64 (pglob->gl_pathv[i], &st64) == 0
1258 && S_ISDIR (st64.st_mode))))
1259 {
1260 size_t len = strlen (pglob->gl_pathv[i]) + 2;
1261 char *new = realloc (pglob->gl_pathv[i], len);
1262 if (new == NULL)
1263 {
1264 globfree (pglob);
1265 pglob->gl_pathc = 0;
1266 return GLOB_NOSPACE;
1267 }
1268 strcpy (&new[len - 2], "/");
1269 pglob->gl_pathv[i] = new;
1270 }
1271 }
1272
1273 if (!(flags & GLOB_NOSORT))
1274 {
1275 /* Sort the vector. */
1276 qsort (&pglob->gl_pathv[oldcount],
1277 pglob->gl_pathc + pglob->gl_offs - oldcount,
1278 sizeof (char *), collated_compare);
1279 }
1280
1281 out:
1282 if (__glibc_unlikely (malloc_dirname))
1283 free (dirname);
1284
1285 return retval;
1286}
1287#if defined _LIBC && !defined glob
1288libc_hidden_def (glob)
1289#endif
1290
1291
1292#if !defined _LIBC || !defined GLOB_ONLY_P
1293
1294/* Free storage allocated in PGLOB by a previous `glob' call. */
1295void
1296globfree (glob_t *pglob)
1297{
1298 if (pglob->gl_pathv != NULL)
1299 {
1300 size_t i;
1301 for (i = 0; i < pglob->gl_pathc; ++i)
1302 free (pglob->gl_pathv[pglob->gl_offs + i]);
1303 free (pglob->gl_pathv);
1304 pglob->gl_pathv = NULL;
1305 }
1306}
1307#if defined _LIBC && !defined globfree
1308libc_hidden_def (globfree)
1309#endif
1310
1311
1312/* Do a collated comparison of A and B. */
1313static int
1314collated_compare (const void *a, const void *b)
1315{
1316 const char *const s1 = *(const char *const * const) a;
1317 const char *const s2 = *(const char *const * const) b;
1318
1319 if (s1 == s2)
1320 return 0;
1321 if (s1 == NULL)
1322 return 1;
1323 if (s2 == NULL)
1324 return -1;
1325 return strcoll (s1, s2);
1326}
1327
1328
1329/* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1330 elements in place. Return nonzero if out of memory, zero if successful.
1331 A slash is inserted between DIRNAME and each elt of ARRAY,
1332 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1333static int
1334prefix_array (const char *dirname, char **array, size_t n)
1335{
1336 size_t i;
1337 size_t dirlen = strlen (dirname);
1338#if defined __MSDOS__ || defined WINDOWS32
1339 int sep_char = '/';
1340# define DIRSEP_CHAR sep_char
1341#else
1342# define DIRSEP_CHAR '/'
1343#endif
1344
1345 if (dirlen == 1 && dirname[0] == '/')
1346 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1347 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1348 dirlen = 0;
1349#if defined __MSDOS__ || defined WINDOWS32
1350 else if (dirlen > 1)
1351 {
1352 if (dirname[dirlen - 1] == '/' && dirname[dirlen - 2] == ':')
1353 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1354 --dirlen;
1355 else if (dirname[dirlen - 1] == ':')
1356 {
1357 /* DIRNAME is "d:". Use `:' instead of `/'. */
1358 --dirlen;
1359 sep_char = ':';
1360 }
1361 }
1362#endif
1363
1364 for (i = 0; i < n; ++i)
1365 {
1366 size_t eltlen = strlen (array[i]) + 1;
1367 char *new = (char *) malloc (dirlen + 1 + eltlen);
1368 if (new == NULL)
1369 {
1370 while (i > 0)
1371 free (array[--i]);
1372 return 1;
1373 }
1374
1375 {
1376 char *endp = mempcpy (new, dirname, dirlen);
1377 *endp++ = DIRSEP_CHAR;
1378 mempcpy (endp, array[i], eltlen);
1379 }
1380 free (array[i]);
1381 array[i] = new;
1382 }
1383
1384 return 0;
1385}
1386
1387
1388/* We must not compile this function twice. */
1389#if !defined _LIBC || !defined NO_GLOB_PATTERN_P
1390int
1391__glob_pattern_type (const char *pattern, int quote)
1392{
1393 const char *p;
1394 int ret = 0;
1395
1396 for (p = pattern; *p != '\0'; ++p)
1397 switch (*p)
1398 {
1399 case '?':
1400 case '*':
1401 return 1;
1402
1403 case '\\':
1404 if (quote)
1405 {
1406 if (p[1] != '\0')
1407 ++p;
1408 ret |= 2;
1409 }
1410 break;
1411
1412 case '[':
1413 ret |= 4;
1414 break;
1415
1416 case ']':
1417 if (ret & 4)
1418 return 1;
1419 break;
1420 }
1421
1422 return ret;
1423}
1424
1425/* Return nonzero if PATTERN contains any metacharacters.
1426 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
1427int
1428__glob_pattern_p (const char *pattern, int quote)
1429{
1430 return __glob_pattern_type (pattern, quote) == 1;
1431}
1432# ifdef _LIBC
1433weak_alias (__glob_pattern_p, glob_pattern_p)
1434# endif
1435#endif
1436
1437#endif /* !GLOB_ONLY_P */
1438
1439
1440/* We put this in a separate function mainly to allow the memory
1441 allocated with alloca to be recycled. */
1442#if !defined _LIBC || !defined GLOB_ONLY_P
1443static int
1444__attribute_noinline__
1445link_exists2_p (const char *dir, size_t dirlen, const char *fname,
1446 glob_t *pglob
1447# ifndef _LIBC
1448 , int flags
1449# endif
1450 )
1451{
1452 size_t fnamelen = strlen (fname);
1453 char *fullname = (char *) __alloca (dirlen + 1 + fnamelen + 1);
1454 struct stat st;
1455# ifndef _LIBC
1456 struct_stat64 st64;
1457# endif
1458
1459 mempcpy (mempcpy (mempcpy (fullname, dir, dirlen), "/", 1),
1460 fname, fnamelen + 1);
1461
1462# ifdef _LIBC
1463 return (*pglob->gl_stat) (fullname, &st) == 0;
1464# else
1465 return ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1466 ? (*pglob->gl_stat) (fullname, &st)
1467 : __stat64 (fullname, &st64)) == 0);
1468# endif
1469}
1470# ifdef _LIBC
1471# define link_exists_p(dfd, dirname, dirnamelen, fname, pglob, flags) \
1472 (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0) \
1473 ? link_exists2_p (dirname, dirnamelen, fname, pglob) \
1474 : ({ struct stat64 st64; \
1475 __fxstatat64 (_STAT_VER, dfd, fname, &st64, 0) == 0; }))
1476# else
1477# define link_exists_p(dfd, dirname, dirnamelen, fname, pglob, flags) \
1478 link_exists2_p (dirname, dirnamelen, fname, pglob, flags)
1479# endif
1480#endif
1481
1482
1483/* Like `glob', but PATTERN is a final pathname component,
1484 and matches are searched for in DIRECTORY.
1485 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1486 The GLOB_APPEND flag is assumed to be set (always appends). */
1487static int
1488glob_in_dir (const char *pattern, const char *directory, int flags,
1489 int (*errfunc) (const char *, int),
1490 glob_t *pglob, size_t alloca_used)
1491{
1492 size_t dirlen = strlen (directory);
1493 void *stream = NULL;
1494 struct globnames
1495 {
1496 struct globnames *next;
1497 size_t count;
1498 char *name[64];
1499 };
1500#define INITIAL_COUNT sizeof (init_names.name) / sizeof (init_names.name[0])
1501 struct globnames init_names;
1502 struct globnames *names = &init_names;
1503 struct globnames *names_alloca = &init_names;
1504 size_t nfound = 0;
1505 size_t cur = 0;
1506 int meta;
1507 int save;
1508
1509 alloca_used += sizeof (init_names);
1510
1511 init_names.next = NULL;
1512 init_names.count = INITIAL_COUNT;
1513
1514 meta = __glob_pattern_type (pattern, !(flags & GLOB_NOESCAPE));
1515 if (meta == 0 && (flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
1516 {
1517 /* We need not do any tests. The PATTERN contains no meta
1518 characters and we must not return an error therefore the
1519 result will always contain exactly one name. */
1520 flags |= GLOB_NOCHECK;
1521 }
1522 else if (meta == 0)
1523 {
1524 /* Since we use the normal file functions we can also use stat()
1525 to verify the file is there. */
1526 union
1527 {
1528 struct stat st;
1529 struct_stat64 st64;
1530 } ust;
1531 size_t patlen = strlen (pattern);
1532 int alloca_fullname = __libc_use_alloca (alloca_used
1533 + dirlen + 1 + patlen + 1);
1534 char *fullname;
1535 if (alloca_fullname)
1536 fullname = alloca_account (dirlen + 1 + patlen + 1, alloca_used);
1537 else
1538 {
1539 fullname = malloc (dirlen + 1 + patlen + 1);
1540 if (fullname == NULL)
1541 return GLOB_NOSPACE;
1542 }
1543
1544 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1545 "/", 1),
1546 pattern, patlen + 1);
1547 if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1548 ? (*pglob->gl_stat) (fullname, &ust.st)
1549 : __stat64 (fullname, &ust.st64)) == 0)
1550 /* We found this file to be existing. Now tell the rest
1551 of the function to copy this name into the result. */
1552 flags |= GLOB_NOCHECK;
1553
1554 if (__glibc_unlikely (!alloca_fullname))
1555 free (fullname);
1556 }
1557 else
1558 {
1559 stream = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1560 ? (*pglob->gl_opendir) (directory)
1561 : opendir (directory));
1562 if (stream == NULL)
1563 {
1564 if (errno != ENOTDIR
1565 && ((errfunc != NULL && (*errfunc) (directory, errno))
1566 || (flags & GLOB_ERR)))
1567 return GLOB_ABORTED;
1568 }
1569 else
1570 {
1571#ifdef _LIBC
1572 int dfd = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1573 ? -1 : dirfd ((DIR *) stream));
1574#endif
1575 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1576 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1577#if defined _AMIGA || defined VMS
1578 | FNM_CASEFOLD
1579#endif
1580 );
1581 flags |= GLOB_MAGCHAR;
1582
1583 while (1)
1584 {
1585 struct readdir_result d;
1586 {
1587 if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1588 d = convert_dirent (GL_READDIR (pglob, stream));
1589 else
1590 {
1591#ifdef COMPILE_GLOB64
1592 d = convert_dirent (__readdir (stream));
1593#else
1594 d = convert_dirent64 (__readdir64 (stream));
1595#endif
1596 }
1597 }
1598 if (d.name == NULL)
1599 break;
1600 if (d.skip_entry)
1601 continue;
1602
1603 /* If we shall match only directories use the information
1604 provided by the dirent call if possible. */
1605 if ((flags & GLOB_ONLYDIR) && !readdir_result_might_be_dir (d))
1606 continue;
1607
1608 if (fnmatch (pattern, d.name, fnm_flags) == 0)
1609 {
1610 /* If the file we found is a symlink we have to
1611 make sure the target file exists. */
1612 if (!readdir_result_might_be_symlink (d)
1613 || link_exists_p (dfd, directory, dirlen, d.name,
1614 pglob, flags))
1615 {
1616 if (cur == names->count)
1617 {
1618 struct globnames *newnames;
1619 size_t count = names->count * 2;
1620 size_t size = (sizeof (struct globnames)
1621 + ((count - INITIAL_COUNT)
1622 * sizeof (char *)));
1623 if (__libc_use_alloca (alloca_used + size))
1624 newnames = names_alloca
1625 = alloca_account (size, alloca_used);
1626 else if ((newnames = malloc (size))
1627 == NULL)
1628 goto memory_error;
1629 newnames->count = count;
1630 newnames->next = names;
1631 names = newnames;
1632 cur = 0;
1633 }
1634 names->name[cur] = strdup (d.name);
1635 if (names->name[cur] == NULL)
1636 goto memory_error;
1637 ++cur;
1638 ++nfound;
1639 }
1640 }
1641 }
1642 }
1643 }
1644
1645 if (nfound == 0 && (flags & GLOB_NOCHECK))
1646 {
1647 size_t len = strlen (pattern);
1648 nfound = 1;
1649 names->name[cur] = (char *) malloc (len + 1);
1650 if (names->name[cur] == NULL)
1651 goto memory_error;
1652 *((char *) mempcpy (names->name[cur++], pattern, len)) = '\0';
1653 }
1654
1655 int result = GLOB_NOMATCH;
1656 if (nfound != 0)
1657 {
1658 result = 0;
1659
1660 if (pglob->gl_pathc > UINTPTR_MAX - pglob->gl_offs
1661 || pglob->gl_pathc + pglob->gl_offs > UINTPTR_MAX - nfound
1662 || pglob->gl_pathc + pglob->gl_offs + nfound > UINTPTR_MAX - 1
1663 || (pglob->gl_pathc + pglob->gl_offs + nfound + 1
1664 > UINTPTR_MAX / sizeof (char *)))
1665 goto memory_error;
1666
1667 char **new_gl_pathv;
1668 new_gl_pathv
1669 = (char **) realloc (pglob->gl_pathv,
1670 (pglob->gl_pathc + pglob->gl_offs + nfound + 1)
1671 * sizeof (char *));
1672 if (new_gl_pathv == NULL)
1673 {
1674 memory_error:
1675 while (1)
1676 {
1677 struct globnames *old = names;
1678 for (size_t i = 0; i < cur; ++i)
1679 free (names->name[i]);
1680 names = names->next;
1681 /* NB: we will not leak memory here if we exit without
1682 freeing the current block assigned to OLD. At least
1683 the very first block is always allocated on the stack
1684 and this is the block assigned to OLD here. */
1685 if (names == NULL)
1686 {
1687 assert (old == &init_names);
1688 break;
1689 }
1690 cur = names->count;
1691 if (old == names_alloca)
1692 names_alloca = names;
1693 else
1694 free (old);
1695 }
1696 result = GLOB_NOSPACE;
1697 }
1698 else
1699 {
1700 while (1)
1701 {
1702 struct globnames *old = names;
1703 for (size_t i = 0; i < cur; ++i)
1704 new_gl_pathv[pglob->gl_offs + pglob->gl_pathc++]
1705 = names->name[i];
1706 names = names->next;
1707 /* NB: we will not leak memory here if we exit without
1708 freeing the current block assigned to OLD. At least
1709 the very first block is always allocated on the stack
1710 and this is the block assigned to OLD here. */
1711 if (names == NULL)
1712 {
1713 assert (old == &init_names);
1714 break;
1715 }
1716 cur = names->count;
1717 if (old == names_alloca)
1718 names_alloca = names;
1719 else
1720 free (old);
1721 }
1722
1723 pglob->gl_pathv = new_gl_pathv;
1724
1725 pglob->gl_pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
1726
1727 pglob->gl_flags = flags;
1728 }
1729 }
1730
1731 if (stream != NULL)
1732 {
1733 save = errno;
1734 if (__glibc_unlikely (flags & GLOB_ALTDIRFUNC))
1735 (*pglob->gl_closedir) (stream);
1736 else
1737 closedir (stream);
1738 __set_errno (save);
1739 }
1740
1741 return result;
1742}
1743