Tue Apr 2 21:27:01 1996 Andreas Schwab <schwab@issan.informatik.uni-dortmund.de>
[platform/upstream/glibc.git] / posix / glob.c
1 /* Copyright (C) 1991, 92, 93, 94, 95, 96 Free Software Foundation, Inc.
2
3 This library is free software; you can redistribute it and/or
4 modify it under the terms of the GNU Library General Public License as
5 published by the Free Software Foundation; either version 2 of the
6 License, or (at your option) any later version.
7
8 This library is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 Library General Public License for more details.
12
13 You should have received a copy of the GNU Library General Public
14 License along with this library; see the file COPYING.LIB.  If
15 not, write to the Free Software Foundation, Inc., 675 Mass Ave,
16 Cambridge, MA 02139, USA.  */
17
18 /* AIX requires this to be the first thing in the file.  */
19 #if defined (_AIX) && !defined (__GNUC__)
20  #pragma alloca
21 #endif
22
23 #ifdef  HAVE_CONFIG_H
24 #include <config.h>
25 #endif
26
27 /* Enable GNU extensions in glob.h.  */
28 #ifndef _GNU_SOURCE
29 #define _GNU_SOURCE     1
30 #endif
31
32 #include <errno.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35
36
37 /* Comment out all this code if we are using the GNU C Library, and are not
38    actually compiling the library itself.  This code is part of the GNU C
39    Library, but also included in many other GNU distributions.  Compiling
40    and linking in this code is a waste when using the GNU C library
41    (especially if it is a shared library).  Rather than having every GNU
42    program understand `configure --with-gnu-libc' and omit the object files,
43    it is simpler to just do this in the source for each such file.  */
44
45 #define GLOB_INTERFACE_VERSION 1
46 #if !defined (_LIBC) && defined (__GNU_LIBRARY__) && __GNU_LIBRARY__ > 1
47 #include <gnu-versions.h>
48 #if _GNU_GLOB_INTERFACE_VERSION == GLOB_INTERFACE_VERSION
49 #define ELIDE_CODE
50 #endif
51 #endif
52
53 #ifndef ELIDE_CODE
54
55 #ifdef  STDC_HEADERS
56 #include <stddef.h>
57 #endif
58
59 #ifdef  HAVE_UNISTD_H
60 #include <unistd.h>
61 #ifndef POSIX
62 #ifdef  _POSIX_VERSION
63 #define POSIX
64 #endif
65 #endif
66 #endif
67
68 #include <pwd.h>
69
70 #if !defined(__GNU_LIBRARY__) && !defined(STDC_HEADERS)
71 extern int errno;
72 #endif
73
74 #ifndef NULL
75 #define NULL    0
76 #endif
77
78
79 #if defined (HAVE_DIRENT_H) || defined (__GNU_LIBRARY__)
80 # include <dirent.h>
81 # define NAMLEN(dirent) strlen((dirent)->d_name)
82 #else
83 # define dirent direct
84 # define NAMLEN(dirent) (dirent)->d_namlen
85 # ifdef HAVE_SYS_NDIR_H
86 #  include <sys/ndir.h>
87 # endif
88 # ifdef HAVE_SYS_DIR_H
89 #  include <sys/dir.h>
90 # endif
91 # ifdef HAVE_NDIR_H
92 #  include <ndir.h>
93 # endif
94 #endif
95
96
97 /* In GNU systems, <dirent.h> defines this macro for us.  */
98 #ifdef _D_NAMLEN
99 #undef NAMLEN
100 #define NAMLEN(d) _D_NAMLEN(d)
101 #endif
102
103
104 #if defined (POSIX) && !defined (__GNU_LIBRARY__)
105 /* Posix does not require that the d_ino field be present, and some
106    systems do not provide it. */
107 #define REAL_DIR_ENTRY(dp) 1
108 #else
109 #define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
110 #endif /* POSIX */
111
112 #if     (defined (STDC_HEADERS) || defined (__GNU_LIBRARY__))
113 #include <stdlib.h>
114 #include <string.h>
115 #define ANSI_STRING
116 #else   /* No standard headers.  */
117
118 extern char *getenv ();
119
120 #ifdef HAVE_STRING_H
121 #include <string.h>
122 #define ANSI_STRING
123 #else
124 #include <strings.h>
125 #endif
126 #ifdef  HAVE_MEMORY_H
127 #include <memory.h>
128 #endif
129
130 extern char *malloc (), *realloc ();
131 extern void free ();
132
133 extern void qsort ();
134 extern void abort (), exit ();
135
136 #endif  /* Standard headers.  */
137
138 #ifndef ANSI_STRING
139
140 #ifndef bzero
141 extern void bzero ();
142 #endif
143 #ifndef bcopy
144 extern void bcopy ();
145 #endif
146
147 #define memcpy(d, s, n) bcopy ((s), (d), (n))
148 #define strrchr rindex
149 /* memset is only used for zero here, but let's be paranoid.  */
150 #define memset(s, better_be_zero, n) \
151   ((void) ((better_be_zero) == 0 ? (bzero((s), (n)), 0) : (abort(), 0)))
152 #endif  /* Not ANSI_STRING.  */
153
154 #ifndef HAVE_STRCOLL
155 #define strcoll strcmp
156 #endif
157
158
159 #ifndef __GNU_LIBRARY__
160 #ifdef  __GNUC__
161 __inline
162 #endif
163 static char *
164 my_realloc (p, n)
165      char *p;
166      unsigned int n;
167 {
168   /* These casts are the for sake of the broken Ultrix compiler,
169      which warns of illegal pointer combinations otherwise.  */
170   if (p == NULL)
171     return (char *) malloc (n);
172   return (char *) realloc (p, n);
173 }
174 #define realloc my_realloc
175 #endif
176
177
178 #if     !defined(__alloca) && !defined(__GNU_LIBRARY__)
179
180 #ifdef  __GNUC__
181 #undef  alloca
182 #define alloca(n)       __builtin_alloca (n)
183 #else   /* Not GCC.  */
184 #if     defined (sparc) || defined (HAVE_ALLOCA_H)
185 #include <alloca.h>
186 #else   /* Not sparc or HAVE_ALLOCA_H.  */
187 #ifndef _AIX
188 extern char *alloca ();
189 #endif  /* Not _AIX.  */
190 #endif  /* sparc or HAVE_ALLOCA_H.  */
191 #endif  /* GCC.  */
192
193 #define __alloca        alloca
194
195 #endif
196
197 #ifndef __GNU_LIBRARY__
198 #define __stat stat
199 #ifdef STAT_MACROS_BROKEN
200 #undef S_ISDIR
201 #endif
202 #ifndef S_ISDIR
203 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
204 #endif
205 #endif
206
207 #ifndef STDC_HEADERS
208 #undef  size_t
209 #define size_t  unsigned int
210 #endif
211
212 /* Some system header files erroneously define these.
213    We want our own definitions from <fnmatch.h> to take precedence.  */
214 #undef  FNM_PATHNAME
215 #undef  FNM_NOESCAPE
216 #undef  FNM_PERIOD
217 #include <fnmatch.h>
218
219 /* Some system header files erroneously define these.
220    We want our own definitions from <glob.h> to take precedence.  */
221 #undef  GLOB_ERR
222 #undef  GLOB_MARK
223 #undef  GLOB_NOSORT
224 #undef  GLOB_DOOFFS
225 #undef  GLOB_NOCHECK
226 #undef  GLOB_APPEND
227 #undef  GLOB_NOESCAPE
228 #undef  GLOB_PERIOD
229 #include <glob.h>
230 \f
231 static int glob_pattern_p __P ((const char *pattern, int quote));
232 static int glob_in_dir __P ((const char *pattern, const char *directory,
233                              int flags,
234                              int (*errfunc) __P ((const char *, int)),
235                              glob_t *pglob));
236 static int prefix_array __P ((const char *prefix, char **array, size_t n));
237 static int collated_compare __P ((const __ptr_t, const __ptr_t));
238
239 /* Do glob searching for PATTERN, placing results in PGLOB.
240    The bits defined above may be set in FLAGS.
241    If a directory cannot be opened or read and ERRFUNC is not nil,
242    it is called with the pathname that caused the error, and the
243    `errno' value from the failing call; if it returns non-zero
244    `glob' returns GLOB_ABEND; if it returns zero, the error is ignored.
245    If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
246    Otherwise, `glob' returns zero.  */
247 int
248 glob (pattern, flags, errfunc, pglob)
249      const char *pattern;
250      int flags;
251      int (*errfunc) __P ((const char *, int));
252      glob_t *pglob;
253 {
254   const char *filename;
255   char *dirname;
256   size_t dirlen;
257   int status;
258   int oldcount;
259
260   if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
261     {
262       errno = EINVAL;
263       return -1;
264     }
265
266   if (flags & GLOB_BRACE)
267     {
268       const char *begin = strchr (pattern, '{');
269       if (begin != NULL)
270         {
271           int firstc;
272           size_t restlen;
273           const char *p, *end, *next;
274           unsigned int depth = 0;
275
276           /* Find the end of the brace expression, by counting braces.
277              While we're at it, notice the first comma at top brace level.  */
278           end = begin + 1;
279           next = NULL;
280           while (1)
281             {
282               switch (*end++)
283                 {
284                 case ',':
285                   if (depth == 0 && next == NULL)
286                     next = end;
287                   continue;
288                 case '{':
289                   ++depth;
290                   continue;
291                 case '}':
292                   if (depth-- == 0)
293                     break;
294                   continue;
295                 case '\0':
296                   return glob (pattern, flags &~ GLOB_BRACE, errfunc, pglob);
297                 }
298               break;
299             }
300           restlen = strlen (end) + 1;
301           if (next == NULL)
302             next = end;
303
304           /* We have a brace expression.  BEGIN points to the opening {,
305              NEXT points past the terminator of the first element, and END
306              points past the final }.  We will accumulate result names from
307              recursive runs for each brace alternative in the buffer using
308              GLOB_APPEND.  */
309
310           if (!(flags & GLOB_APPEND))
311             {
312               /* This call is to set a new vector, so clear out the
313                  vector so we can append to it.  */
314               pglob->gl_pathc = 0;
315               pglob->gl_pathv = NULL;
316             }
317           firstc = pglob->gl_pathc;
318
319           /* In this loop P points to the beginning of the current element
320              and NEXT points past its terminator.  */
321           p = begin + 1;
322           while (1)
323             {
324               /* Construct a whole name that is one of the brace
325                  alternatives in a temporary buffer.  */
326               int result;
327               size_t bufsz = (begin - pattern) + (next - 1 - p) + restlen;
328 #ifdef __GNUC__
329               char onealt[bufsz];
330 #else
331               char *onealt = malloc (bufsz);
332               if (onealt == NULL)
333                 {
334                   if (!(flags & GLOB_APPEND))
335                     globfree (&pglob);
336                   return GLOB_NOSPACE;
337                 }
338 #endif
339               memcpy (onealt, pattern, begin - pattern);
340               memcpy (&onealt[begin - pattern], p, next - 1 - p);
341               memcpy (&onealt[(begin - pattern) + (next - 1 - p)],
342                       end, restlen);
343               result = glob (onealt,
344                              ((flags & ~(GLOB_NOCHECK|GLOB_NOMAGIC)) |
345                               GLOB_APPEND), errfunc, pglob);
346 #ifndef __GNUC__
347               free (onealt);
348 #endif
349
350               /* If we got an error, return it.  */
351               if (result && result != GLOB_NOMATCH)
352                 {
353                   if (!(flags & GLOB_APPEND))
354                     globfree (pglob);
355                   return result;
356                 }
357
358               /* Advance past this alternative and process the next.  */
359               p = next;
360               depth = 0;
361             scan:
362               switch (*p++)
363                 {
364                 case ',':
365                   if (depth == 0)
366                     {
367                       /* Found the next alternative.  Loop to glob it.  */
368                       next = p;
369                       continue;
370                     }
371                   goto scan;
372                 case '{':
373                   ++depth;
374                   goto scan;
375                 case '}':
376                   if (depth-- == 0)
377                     /* End of the brace expression.  Break out of the loop.  */
378                     break;
379                   goto scan;
380                 }
381             }
382
383           if (pglob->gl_pathc == firstc &&
384               !(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
385             return GLOB_NOMATCH;
386         }
387     }
388
389   /* Find the filename.  */
390   filename = strrchr (pattern, '/');
391   if (filename == NULL)
392     {
393       filename = pattern;
394       dirname = (char *) ".";
395       dirlen = 0;
396     }
397   else if (filename == pattern)
398     {
399       /* "/pattern".  */
400       dirname = (char *) "/";
401       dirlen = 1;
402       ++filename;
403     }
404   else
405     {
406       dirlen = filename - pattern;
407       dirname = (char *) __alloca (dirlen + 1);
408       memcpy (dirname, pattern, dirlen);
409       dirname[dirlen] = '\0';
410       ++filename;
411     }
412
413   if (filename[0] == '\0' && dirlen > 1)
414     /* "pattern/".  Expand "pattern", appending slashes.  */
415     {
416       int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
417       if (val == 0)
418         pglob->gl_flags = (pglob->gl_flags & ~GLOB_MARK) | (flags & GLOB_MARK);
419       return val;
420     }
421
422   if (!(flags & GLOB_APPEND))
423     {
424       pglob->gl_pathc = 0;
425       pglob->gl_pathv = NULL;
426     }
427
428   oldcount = pglob->gl_pathc;
429
430   if ((flags & GLOB_TILDE) && dirname[0] == '~')
431     {
432       if (dirname[1] == '\0')
433         {
434           /* Look up home directory.  */
435           dirname = getenv ("HOME");
436           if (dirname == NULL || dirname[0] == '\0')
437             {
438               extern char *getlogin __P ((void));
439               char *name = getlogin ();
440               if (name != NULL)
441                 {
442                   struct passwd *p = getpwnam (name);
443                   if (p != NULL)
444                     dirname = p->pw_dir;
445                 }
446             }
447           if (dirname == NULL || dirname[0] == '\0')
448             dirname = (char *) "~"; /* No luck.  */
449         }
450       else
451         {
452           /* Look up specific user's home directory.  */
453           struct passwd *p = getpwnam (dirname + 1);
454           if (p != NULL)
455             dirname = p->pw_dir;
456         }
457     }
458
459   if (glob_pattern_p (dirname, !(flags & GLOB_NOESCAPE)))
460     {
461       /* The directory name contains metacharacters, so we
462          have to glob for the directory, and then glob for
463          the pattern in each directory found.  */
464       glob_t dirs;
465       register int i;
466
467       status = glob (dirname,
468                      ((flags & (GLOB_ERR | GLOB_NOCHECK | GLOB_NOESCAPE)) |
469                       GLOB_NOSORT),
470                      errfunc, &dirs);
471       if (status != 0)
472         return status;
473
474       /* We have successfully globbed the preceding directory name.
475          For each name we found, call glob_in_dir on it and FILENAME,
476          appending the results to PGLOB.  */
477       for (i = 0; i < dirs.gl_pathc; ++i)
478         {
479           int oldcount;
480
481 #ifdef  SHELL
482           {
483             /* Make globbing interruptible in the bash shell. */
484             extern int interrupt_state;
485
486             if (interrupt_state)
487               {
488                 globfree (&dirs);
489                 globfree (&files);
490                 return GLOB_ABEND;
491               }
492           }
493 #endif /* SHELL.  */
494
495           oldcount = pglob->gl_pathc;
496           status = glob_in_dir (filename, dirs.gl_pathv[i],
497                                 (flags | GLOB_APPEND) & ~GLOB_NOCHECK,
498                                 errfunc, pglob);
499           if (status == GLOB_NOMATCH)
500             /* No matches in this directory.  Try the next.  */
501             continue;
502
503           if (status != 0)
504             {
505               globfree (&dirs);
506               globfree (pglob);
507               return status;
508             }
509
510           /* Stick the directory on the front of each name.  */
511           if (prefix_array (dirs.gl_pathv[i],
512                             &pglob->gl_pathv[oldcount],
513                             pglob->gl_pathc - oldcount))
514             {
515               globfree (&dirs);
516               globfree (pglob);
517               return GLOB_NOSPACE;
518             }
519         }
520
521       flags |= GLOB_MAGCHAR;
522
523       if (pglob->gl_pathc == oldcount)
524         /* No matches.  */
525         if (flags & GLOB_NOCHECK)
526           {
527             size_t len = strlen (pattern) + 1;
528             char *patcopy = (char *) malloc (len);
529             if (patcopy == NULL)
530               return GLOB_NOSPACE;
531             memcpy (patcopy, pattern, len);
532
533             pglob->gl_pathv
534               = (char **) realloc (pglob->gl_pathv,
535                                    (pglob->gl_pathc +
536                                     ((flags & GLOB_DOOFFS) ?
537                                      pglob->gl_offs : 0) +
538                                     1 + 1) *
539                                    sizeof (char *));
540             if (pglob->gl_pathv == NULL)
541               {
542                 free (patcopy);
543                 return GLOB_NOSPACE;
544               }
545
546             if (flags & GLOB_DOOFFS)
547               while (pglob->gl_pathc < pglob->gl_offs)
548                 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
549
550             pglob->gl_pathv[pglob->gl_pathc++] = patcopy;
551             pglob->gl_pathv[pglob->gl_pathc] = NULL;
552             pglob->gl_flags = flags;
553           }
554         else
555           return GLOB_NOMATCH;
556     }
557   else
558     {
559       status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
560       if (status != 0)
561         return status;
562
563       if (dirlen > 0)
564         {
565           /* Stick the directory on the front of each name.  */
566           if (prefix_array (dirname,
567                             &pglob->gl_pathv[oldcount],
568                             pglob->gl_pathc - oldcount))
569             {
570               globfree (pglob);
571               return GLOB_NOSPACE;
572             }
573         }
574     }
575
576   if (flags & GLOB_MARK)
577     {
578       /* Append slashes to directory names.  */
579       int i;
580       struct stat st;
581       for (i = oldcount; i < pglob->gl_pathc; ++i)
582         if (((flags & GLOB_ALTDIRFUNC) ?
583              (*pglob->gl_stat) (pglob->gl_pathv[i], &st) :
584              __stat (pglob->gl_pathv[i], &st)) == 0 &&
585             S_ISDIR (st.st_mode))
586           {
587             size_t len = strlen (pglob->gl_pathv[i]) + 2;
588             char *new = realloc (pglob->gl_pathv[i], len);
589             if (new == NULL)
590               {
591                 globfree (pglob);
592                 return GLOB_NOSPACE;
593               }
594             strcpy (&new[len - 2], "/");
595             pglob->gl_pathv[i] = new;
596           }
597     }
598
599   if (!(flags & GLOB_NOSORT))
600     /* Sort the vector.  */
601     qsort ((__ptr_t) &pglob->gl_pathv[oldcount],
602            pglob->gl_pathc - oldcount,
603            sizeof (char *), collated_compare);
604
605   return 0;
606 }
607
608
609 /* Free storage allocated in PGLOB by a previous `glob' call.  */
610 void
611 globfree (pglob)
612      register glob_t *pglob;
613 {
614   if (pglob->gl_pathv != NULL)
615     {
616       register int i;
617       for (i = 0; i < pglob->gl_pathc; ++i)
618         if (pglob->gl_pathv[i] != NULL)
619           free ((__ptr_t) pglob->gl_pathv[i]);
620       free ((__ptr_t) pglob->gl_pathv);
621     }
622 }
623
624
625 /* Do a collated comparison of A and B.  */
626 static int
627 collated_compare (a, b)
628      const __ptr_t a;
629      const __ptr_t b;
630 {
631   const char *const s1 = *(const char *const * const) a;
632   const char *const s2 = *(const char *const * const) b;
633
634   if (s1 == s2)
635     return 0;
636   if (s1 == NULL)
637     return 1;
638   if (s2 == NULL)
639     return -1;
640   return strcoll (s1, s2);
641 }
642
643
644 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
645    elements in place.  Return nonzero if out of memory, zero if successful.
646    A slash is inserted between DIRNAME and each elt of ARRAY,
647    unless DIRNAME is just "/".  Each old element of ARRAY is freed.  */
648 static int
649 prefix_array (dirname, array, n)
650      const char *dirname;
651      char **array;
652      size_t n;
653 {
654   register size_t i;
655   size_t dirlen = strlen (dirname);
656
657   if (dirlen == 1 && dirname[0] == '/')
658     /* DIRNAME is just "/", so normal prepending would get us "//foo".
659        We want "/foo" instead, so don't prepend any chars from DIRNAME.  */
660     dirlen = 0;
661
662   for (i = 0; i < n; ++i)
663     {
664       size_t eltlen = strlen (array[i]) + 1;
665       char *new = (char *) malloc (dirlen + 1 + eltlen);
666       if (new == NULL)
667         {
668           while (i > 0)
669             free ((__ptr_t) array[--i]);
670           return 1;
671         }
672
673       memcpy (new, dirname, dirlen);
674       new[dirlen] = '/';
675       memcpy (&new[dirlen + 1], array[i], eltlen);
676       free ((__ptr_t) array[i]);
677       array[i] = new;
678     }
679
680   return 0;
681 }
682
683
684 /* Return nonzero if PATTERN contains any metacharacters.
685    Metacharacters can be quoted with backslashes if QUOTE is nonzero.  */
686 static int
687 glob_pattern_p (pattern, quote)
688      const char *pattern;
689      int quote;
690 {
691   register const char *p;
692   int open = 0;
693
694   for (p = pattern; *p != '\0'; ++p)
695     switch (*p)
696       {
697       case '?':
698       case '*':
699         return 1;
700
701       case '\\':
702         if (quote && p[1] != '\0')
703           ++p;
704         break;
705
706       case '[':
707         open = 1;
708         break;
709
710       case ']':
711         if (open)
712           return 1;
713         break;
714       }
715
716   return 0;
717 }
718
719
720 /* Like `glob', but PATTERN is a final pathname component,
721    and matches are searched for in DIRECTORY.
722    The GLOB_NOSORT bit in FLAGS is ignored.  No sorting is ever done.
723    The GLOB_APPEND flag is assumed to be set (always appends).  */
724 static int
725 glob_in_dir (pattern, directory, flags, errfunc, pglob)
726      const char *pattern;
727      const char *directory;
728      int flags;
729      int (*errfunc) __P ((const char *, int));
730      glob_t *pglob;
731 {
732   __ptr_t stream;
733
734   struct globlink
735     {
736       struct globlink *next;
737       char *name;
738     };
739   struct globlink *names = NULL;
740   size_t nfound = 0;
741
742   if (!glob_pattern_p (pattern, !(flags & GLOB_NOESCAPE)))
743     {
744       stream = NULL;
745       flags |= GLOB_NOCHECK;
746     }
747   else
748     {
749       flags |= GLOB_MAGCHAR;
750
751       stream = ((flags & GLOB_ALTDIRFUNC) ?
752                 (*pglob->gl_opendir) (directory) :
753                 (__ptr_t) opendir (directory));
754       if (stream == NULL)
755         {
756           if ((errfunc != NULL && (*errfunc) (directory, errno)) ||
757               (flags & GLOB_ERR))
758             return GLOB_ABEND;
759         }
760       else
761         while (1)
762           {
763             const char *name;
764             size_t len;
765             struct dirent *d = ((flags & GLOB_ALTDIRFUNC) ?
766                                 (*pglob->gl_readdir) (stream) :
767                                 readdir ((DIR *) stream));
768             if (d == NULL)
769               break;
770             if (! REAL_DIR_ENTRY (d))
771               continue;
772
773             name = d->d_name;
774
775             if (fnmatch (pattern, name,
776                          (!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0) |
777                          ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)) == 0)
778               {
779                 struct globlink *new
780                   = (struct globlink *) __alloca (sizeof (struct globlink));
781                 len = NAMLEN (d);
782                 new->name
783                   = (char *) malloc (len + 1);
784                 if (new->name == NULL)
785                   goto memory_error;
786                 memcpy ((__ptr_t) new->name, name, len);
787                 new->name[len] = '\0';
788                 new->next = names;
789                 names = new;
790                 ++nfound;
791               }
792           }
793     }
794
795   if (nfound == 0 && (flags & GLOB_NOMAGIC) &&
796       ! glob_pattern_p (pattern, !(flags & GLOB_NOESCAPE)))
797     flags |= GLOB_NOCHECK;
798
799   if (nfound == 0 && (flags & GLOB_NOCHECK))
800     {
801       size_t len = strlen (pattern);
802       nfound = 1;
803       names = (struct globlink *) __alloca (sizeof (struct globlink));
804       names->next = NULL;
805       names->name = (char *) malloc (len + 1);
806       if (names->name == NULL)
807         goto memory_error;
808       memcpy (names->name, pattern, len);
809       names->name[len] = '\0';
810     }
811
812   pglob->gl_pathv
813     = (char **) realloc (pglob->gl_pathv,
814                          (pglob->gl_pathc +
815                           ((flags & GLOB_DOOFFS) ? pglob->gl_offs : 0) +
816                           nfound + 1) *
817                          sizeof (char *));
818   if (pglob->gl_pathv == NULL)
819     goto memory_error;
820
821   if (flags & GLOB_DOOFFS)
822     while (pglob->gl_pathc < pglob->gl_offs)
823       pglob->gl_pathv[pglob->gl_pathc++] = NULL;
824
825   for (; names != NULL; names = names->next)
826     pglob->gl_pathv[pglob->gl_pathc++] = names->name;
827   pglob->gl_pathv[pglob->gl_pathc] = NULL;
828
829   pglob->gl_flags = flags;
830
831   if (stream != NULL)
832     {
833       int save = errno;
834       if (flags & GLOB_ALTDIRFUNC)
835         (*pglob->gl_closedir) (stream);
836       else
837         closedir ((DIR *) stream);
838       errno = save;
839     }
840   return nfound == 0 ? GLOB_NOMATCH : 0;
841
842  memory_error:
843   {
844     int save = errno;
845     if (flags & GLOB_ALTDIRFUNC)
846       (*pglob->gl_closedir) (stream);
847     else
848       closedir ((DIR *) stream);
849     errno = save;
850   }
851   while (names != NULL)
852     {
853       if (names->name != NULL)
854         free ((__ptr_t) names->name);
855       names = names->next;
856     }
857   return GLOB_NOSPACE;
858 }
859
860 #endif  /* Not ELIDE_CODE.  */
861