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