(glob): If GLOB_MARK set, stat names to find directories and append slashes to them...
[platform/upstream/glibc.git] / posix / glob.c
1 /* Copyright (C) 1991, 1992, 1993, 1994, 1995 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 #include <errno.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30
31
32 /* Comment out all this code if we are using the GNU C Library, and are not
33    actually compiling the library itself.  This code is part of the GNU C
34    Library, but also included in many other GNU distributions.  Compiling
35    and linking in this code is a waste when using the GNU C library
36    (especially if it is a shared library).  Rather than having every GNU
37    program understand `configure --with-gnu-libc' and omit the object files,
38    it is simpler to just do this in the source for each such file.  */
39
40 #if defined (_LIBC) || !defined (__GNU_LIBRARY__)
41
42
43 #ifdef  STDC_HEADERS
44 #include <stddef.h>
45 #endif
46
47 #ifdef  HAVE_UNISTD_H
48 #include <unistd.h>
49 #ifndef POSIX
50 #ifdef  _POSIX_VERSION
51 #define POSIX
52 #endif
53 #endif
54 #endif
55
56 #if !defined(__GNU_LIBRARY__) && !defined(STDC_HEADERS)
57 extern int errno;
58 #endif
59
60 #ifndef NULL
61 #define NULL    0
62 #endif
63
64
65 #if     defined (POSIX) || defined (HAVE_DIRENT_H) || defined (__GNU_LIBRARY__)
66 #include <dirent.h>
67 #ifndef __GNU_LIBRARY__
68 #define D_NAMLEN(d) strlen((d)->d_name)
69 #else   /* GNU C library.  */
70 #define D_NAMLEN(d) ((d)->d_namlen)
71 #endif  /* Not GNU C library.  */
72 #else   /* Not POSIX or HAVE_DIRENT_H.  */
73 #define direct dirent
74 #define D_NAMLEN(d) ((d)->d_namlen)
75 #ifdef  HAVE_SYS_NDIR_H
76 #include <sys/ndir.h>
77 #endif  /* HAVE_SYS_NDIR_H */
78 #ifdef  HAVE_SYS_DIR_H
79 #include <sys/dir.h>
80 #endif  /* HAVE_SYS_DIR_H */
81 #ifdef HAVE_NDIR_H
82 #include <ndir.h>
83 #endif  /* HAVE_NDIR_H */
84 #endif  /* POSIX or HAVE_DIRENT_H or __GNU_LIBRARY__.  */
85
86 #if defined (POSIX) && !defined (__GNU_LIBRARY__)
87 /* Posix does not require that the d_ino field be present, and some
88    systems do not provide it. */
89 #define REAL_DIR_ENTRY(dp) 1
90 #else
91 #define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
92 #endif /* POSIX */
93
94 #if     (defined (STDC_HEADERS) || defined (__GNU_LIBRARY__))
95 #include <stdlib.h>
96 #include <string.h>
97 #define ANSI_STRING
98 #else   /* No standard headers.  */
99
100 #ifdef HAVE_STRING_H
101 #include <string.h>
102 #define ANSI_STRING
103 #else
104 #include <strings.h>
105 #endif
106 #ifdef  HAVE_MEMORY_H
107 #include <memory.h>
108 #endif
109
110 extern char *malloc (), *realloc ();
111 extern void free ();
112
113 extern void qsort ();
114 extern void abort (), exit ();
115
116 #endif  /* Standard headers.  */
117
118 #ifndef ANSI_STRING
119
120 #ifndef bzero
121 extern void bzero ();
122 #endif
123 #ifndef bcopy
124 extern void bcopy ();
125 #endif
126
127 #define memcpy(d, s, n) bcopy ((s), (d), (n))
128 #define strrchr rindex
129 /* memset is only used for zero here, but let's be paranoid.  */
130 #define memset(s, better_be_zero, n) \
131   ((void) ((better_be_zero) == 0 ? (bzero((s), (n)), 0) : (abort(), 0)))
132 #endif  /* Not ANSI_STRING.  */
133
134 #ifndef HAVE_STRCOLL
135 #define strcoll strcmp
136 #endif
137
138
139 #ifndef __GNU_LIBRARY__
140 #ifdef  __GNUC__
141 __inline
142 #endif
143 static char *
144 my_realloc (p, n)
145      char *p;
146      unsigned int n;
147 {
148   /* These casts are the for sake of the broken Ultrix compiler,
149      which warns of illegal pointer combinations otherwise.  */
150   if (p == NULL)
151     return (char *) malloc (n);
152   return (char *) realloc (p, n);
153 }
154 #define realloc my_realloc
155 #endif
156
157
158 #if     !defined(__alloca) && !defined(__GNU_LIBRARY__)
159
160 #ifdef  __GNUC__
161 #undef  alloca
162 #define alloca(n)       __builtin_alloca (n)
163 #else   /* Not GCC.  */
164 #if     defined (sparc) || defined (HAVE_ALLOCA_H)
165 #include <alloca.h>
166 #else   /* Not sparc or HAVE_ALLOCA_H.  */
167 #ifndef _AIX
168 extern char *alloca ();
169 #endif  /* Not _AIX.  */
170 #endif  /* sparc or HAVE_ALLOCA_H.  */
171 #endif  /* GCC.  */
172
173 #define __alloca        alloca
174
175 #endif
176
177 #ifndef __GNU_LIBRARY__
178 #define __lstat lstat
179 #ifndef HAVE_LSTAT
180 #define lstat stat
181 #endif
182 #ifdef STAT_MACROS_BROKEN
183 #undef S_ISDIR
184 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
185 #endif
186 #endif
187
188 #ifndef STDC_HEADERS
189 #undef  size_t
190 #define size_t  unsigned int
191 #endif
192
193 /* Some system header files erroneously define these.
194    We want our own definitions from <fnmatch.h> to take precedence.  */
195 #undef  FNM_PATHNAME
196 #undef  FNM_NOESCAPE
197 #undef  FNM_PERIOD
198 #include <fnmatch.h>
199
200 /* Some system header files erroneously define these.
201    We want our own definitions from <glob.h> to take precedence.  */
202 #undef  GLOB_ERR
203 #undef  GLOB_MARK
204 #undef  GLOB_NOSORT
205 #undef  GLOB_DOOFFS
206 #undef  GLOB_NOCHECK
207 #undef  GLOB_APPEND
208 #undef  GLOB_NOESCAPE
209 #undef  GLOB_PERIOD
210 #include <glob.h>
211 \f
212 __ptr_t (*__glob_opendir_hook) __P ((const char *directory));
213 const char *(*__glob_readdir_hook) __P ((__ptr_t stream));
214 void (*__glob_closedir_hook) __P ((__ptr_t stream));
215
216 static int glob_pattern_p __P ((const char *pattern, int quote));
217 static int glob_in_dir __P ((const char *pattern, const char *directory,
218                              int flags,
219                              int (*errfunc) __P ((const char *, int)),
220                              glob_t *pglob));
221 static int prefix_array __P ((const char *prefix, char **array, size_t n));
222 static int collated_compare __P ((const __ptr_t, const __ptr_t));
223
224 /* Do glob searching for PATTERN, placing results in PGLOB.
225    The bits defined above may be set in FLAGS.
226    If a directory cannot be opened or read and ERRFUNC is not nil,
227    it is called with the pathname that caused the error, and the
228    `errno' value from the failing call; if it returns non-zero
229    `glob' returns GLOB_ABEND; if it returns zero, the error is ignored.
230    If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
231    Otherwise, `glob' returns zero.  */
232 int
233 glob (pattern, flags, errfunc, pglob)
234      const char *pattern;
235      int flags;
236      int (*errfunc) __P ((const char *, int));
237      glob_t *pglob;
238 {
239   const char *filename;
240   char *dirname;
241   size_t dirlen;
242   int status;
243   int oldcount;
244
245   if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
246     {
247       errno = EINVAL;
248       return -1;
249     }
250
251   /* Find the filename.  */
252   filename = strrchr (pattern, '/');
253   if (filename == NULL)
254     {
255       filename = pattern;
256       dirname = (char *) ".";
257       dirlen = 0;
258     }
259   else if (filename == pattern)
260     {
261       /* "/pattern".  */
262       dirname = (char *) "/";
263       dirlen = 1;
264       ++filename;
265     }
266   else
267     {
268       dirlen = filename - pattern;
269       dirname = (char *) __alloca (dirlen + 1);
270       memcpy (dirname, pattern, dirlen);
271       dirname[dirlen] = '\0';
272       ++filename;
273     }
274
275   if (filename[0] == '\0' && dirlen > 1)
276     /* "pattern/".  Expand "pattern", appending slashes.  */
277     {
278       int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
279       if (val == 0)
280         pglob->gl_flags = (pglob->gl_flags & ~GLOB_MARK) | (flags & GLOB_MARK);
281       return val;
282     }
283
284   if (!(flags & GLOB_APPEND))
285     {
286       pglob->gl_pathc = 0;
287       pglob->gl_pathv = NULL;
288     }
289
290   oldcount = pglob->gl_pathc;
291
292   if (glob_pattern_p (dirname, !(flags & GLOB_NOESCAPE)))
293     {
294       /* The directory name contains metacharacters, so we
295          have to glob for the directory, and then glob for
296          the pattern in each directory found.  */
297       glob_t dirs;
298       register int i;
299
300       status = glob (dirname,
301                      ((flags & (GLOB_ERR | GLOB_NOCHECK | GLOB_NOESCAPE)) |
302                       GLOB_NOSORT),
303                      errfunc, &dirs);
304       if (status != 0)
305         return status;
306
307       /* We have successfully globbed the preceding directory name.
308          For each name we found, call glob_in_dir on it and FILENAME,
309          appending the results to PGLOB.  */
310       for (i = 0; i < dirs.gl_pathc; ++i)
311         {
312           int oldcount;
313
314 #ifdef  SHELL
315           {
316             /* Make globbing interruptible in the bash shell. */
317             extern int interrupt_state;
318
319             if (interrupt_state)
320               {
321                 globfree (&dirs);
322                 globfree (&files);
323                 return GLOB_ABEND;
324               }
325           }
326 #endif /* SHELL.  */
327
328           oldcount = pglob->gl_pathc;
329           status = glob_in_dir (filename, dirs.gl_pathv[i],
330                                 (flags | GLOB_APPEND) & ~GLOB_NOCHECK,
331                                 errfunc, pglob);
332           if (status == GLOB_NOMATCH)
333             /* No matches in this directory.  Try the next.  */
334             continue;
335
336           if (status != 0)
337             {
338               globfree (&dirs);
339               globfree (pglob);
340               return status;
341             }
342
343           /* Stick the directory on the front of each name.  */
344           if (prefix_array (dirs.gl_pathv[i],
345                             &pglob->gl_pathv[oldcount],
346                             pglob->gl_pathc - oldcount))
347             {
348               globfree (&dirs);
349               globfree (pglob);
350               return GLOB_NOSPACE;
351             }
352         }
353
354       flags |= GLOB_MAGCHAR;
355
356       if (pglob->gl_pathc == oldcount)
357         /* No matches.  */
358         if (flags & GLOB_NOCHECK)
359           {
360             size_t len = strlen (pattern) + 1;
361             char *patcopy = (char *) malloc (len);
362             if (patcopy == NULL)
363               return GLOB_NOSPACE;
364             memcpy (patcopy, pattern, len);
365
366             pglob->gl_pathv
367               = (char **) realloc (pglob->gl_pathv,
368                                    (pglob->gl_pathc +
369                                     ((flags & GLOB_DOOFFS) ?
370                                      pglob->gl_offs : 0) +
371                                     1 + 1) *
372                                    sizeof (char *));
373             if (pglob->gl_pathv == NULL)
374               {
375                 free (patcopy);
376                 return GLOB_NOSPACE;
377               }
378
379             if (flags & GLOB_DOOFFS)
380               while (pglob->gl_pathc < pglob->gl_offs)
381                 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
382
383             pglob->gl_pathv[pglob->gl_pathc++] = patcopy;
384             pglob->gl_pathv[pglob->gl_pathc] = NULL;
385             pglob->gl_flags = flags;
386           }
387         else
388           return GLOB_NOMATCH;
389     }
390   else
391     {
392       status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
393       if (status != 0)
394         return status;
395
396       if (dirlen > 0)
397         {
398           /* Stick the directory on the front of each name.  */
399           if (prefix_array (dirname,
400                             &pglob->gl_pathv[oldcount],
401                             pglob->gl_pathc - oldcount))
402             {
403               globfree (pglob);
404               return GLOB_NOSPACE;
405             }
406         }
407     }
408
409   if (flags & GLOB_MARK)
410     {
411       /* Append slashes to directory names.  glob_in_dir has already
412          allocated the extra character for us.  */
413       int i;
414       struct stat st;
415       for (i = oldcount; i < pglob->gl_pathc; ++i)
416         if (__lstat (pglob->gl_pathv[i], &st) == 0 &&
417             S_ISDIR (st.st_mode))
418           strcat (pglob->gl_pathv[i], "/");
419     }
420
421   if (!(flags & GLOB_NOSORT))
422     /* Sort the vector.  */
423     qsort ((__ptr_t) &pglob->gl_pathv[oldcount],
424            pglob->gl_pathc - oldcount,
425            sizeof (char *), collated_compare);
426
427   return 0;
428 }
429
430
431 /* Free storage allocated in PGLOB by a previous `glob' call.  */
432 void
433 globfree (pglob)
434      register glob_t *pglob;
435 {
436   if (pglob->gl_pathv != NULL)
437     {
438       register int i;
439       for (i = 0; i < pglob->gl_pathc; ++i)
440         if (pglob->gl_pathv[i] != NULL)
441           free ((__ptr_t) pglob->gl_pathv[i]);
442       free ((__ptr_t) pglob->gl_pathv);
443     }
444 }
445
446
447 /* Do a collated comparison of A and B.  */
448 static int
449 collated_compare (a, b)
450      const __ptr_t a;
451      const __ptr_t b;
452 {
453   const char *const s1 = *(const char *const * const) a;
454   const char *const s2 = *(const char *const * const) b;
455
456   if (s1 == s2)
457     return 0;
458   if (s1 == NULL)
459     return 1;
460   if (s2 == NULL)
461     return -1;
462   return strcoll (s1, s2);
463 }
464
465
466 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
467    elements in place.  Return nonzero if out of memory, zero if successful.
468    A slash is inserted between DIRNAME and each elt of ARRAY,
469    unless DIRNAME is just "/".  Each old element of ARRAY is freed.  */
470 static int
471 prefix_array (dirname, array, n)
472      const char *dirname;
473      char **array;
474      size_t n;
475 {
476   register size_t i;
477   size_t dirlen = strlen (dirname);
478
479   if (dirlen == 1 && dirname[0] == '/')
480     /* DIRNAME is just "/", so normal prepending would get us "//foo".
481        We want "/foo" instead, so don't prepend any chars from DIRNAME.  */
482     dirlen = 0;
483
484   for (i = 0; i < n; ++i)
485     {
486       size_t eltlen = strlen (array[i]) + 1;
487       char *new = (char *) malloc (dirlen + 1 + eltlen);
488       if (new == NULL)
489         {
490           while (i > 0)
491             free ((__ptr_t) array[--i]);
492           return 1;
493         }
494
495       memcpy (new, dirname, dirlen);
496       new[dirlen] = '/';
497       memcpy (&new[dirlen + 1], array[i], eltlen);
498       free ((__ptr_t) array[i]);
499       array[i] = new;
500     }
501
502   return 0;
503 }
504
505
506 /* Return nonzero if PATTERN contains any metacharacters.
507    Metacharacters can be quoted with backslashes if QUOTE is nonzero.  */
508 static int
509 glob_pattern_p (pattern, quote)
510      const char *pattern;
511      int quote;
512 {
513   register const char *p;
514   int open = 0;
515
516   for (p = pattern; *p != '\0'; ++p)
517     switch (*p)
518       {
519       case '?':
520       case '*':
521         return 1;
522
523       case '\\':
524         if (quote)
525           ++p;
526         break;
527
528       case '[':
529         open = 1;
530         break;
531
532       case ']':
533         if (open)
534           return 1;
535         break;
536       }
537
538   return 0;
539 }
540
541
542 /* Like `glob', but PATTERN is a final pathname component,
543    and matches are searched for in DIRECTORY.
544    The GLOB_NOSORT bit in FLAGS is ignored.  No sorting is ever done.
545    The GLOB_APPEND flag is assumed to be set (always appends).  */
546 static int
547 glob_in_dir (pattern, directory, flags, errfunc, pglob)
548      const char *pattern;
549      const char *directory;
550      int flags;
551      int (*errfunc) __P ((const char *, int));
552      glob_t *pglob;
553 {
554   __ptr_t stream;
555
556   struct globlink
557     {
558       struct globlink *next;
559       char *name;
560     };
561   struct globlink *names = NULL;
562   size_t nfound = 0;
563
564   if (!glob_pattern_p (pattern, !(flags & GLOB_NOESCAPE)))
565     {
566       stream = NULL;
567       flags |= GLOB_NOCHECK;
568     }
569   else
570     {
571       flags |= GLOB_MAGCHAR;
572
573       stream = (__glob_opendir_hook ? (*__glob_opendir_hook) (directory)
574                 : (__ptr_t) opendir (directory));
575       if (stream == NULL)
576         {
577           if ((errfunc != NULL && (*errfunc) (directory, errno)) ||
578               (flags & GLOB_ERR))
579             return GLOB_ABEND;
580         }
581       else
582         while (1)
583           {
584             const char *name;
585             size_t len;
586
587             if (__glob_readdir_hook)
588               {
589                 name = (*__glob_readdir_hook) (stream);
590                 if (name == NULL)
591                   break;
592                 len = 0;
593               }
594             else
595               {
596                 struct dirent *d = readdir ((DIR *) stream);
597                 if (d == NULL)
598                   break;
599                 if (! REAL_DIR_ENTRY (d))
600                   continue;
601                 name = d->d_name;
602 #ifdef  HAVE_D_NAMLEN
603                 len = d->d_namlen;
604 #else
605                 len = 0;
606 #endif
607               }
608                 
609             if (fnmatch (pattern, name,
610                          (!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0) |
611                          ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)) == 0)
612               {
613                 struct globlink *new
614                   = (struct globlink *) __alloca (sizeof (struct globlink));
615                 if (len == 0)
616                   len = strlen (name);
617                 new->name
618                   = (char *) malloc (len + ((flags & GLOB_MARK) ? 1 : 0) + 1);
619                 if (new->name == NULL)
620                   goto memory_error;
621                 memcpy ((__ptr_t) new->name, name, len);
622                 new->name[len] = '\0';
623                 new->next = names;
624                 names = new;
625                 ++nfound;
626               }
627           }
628     }
629
630   if (nfound == 0 && (flags & GLOB_NOCHECK))
631     {
632       size_t len = strlen (pattern);
633       nfound = 1;
634       names = (struct globlink *) __alloca (sizeof (struct globlink));
635       names->next = NULL;
636       names->name = (char *) malloc (len + 1);
637       if (names->name == NULL)
638         goto memory_error;
639       memcpy (names->name, pattern, len);
640       names->name[len] = '\0';
641     }
642
643   pglob->gl_pathv
644     = (char **) realloc (pglob->gl_pathv,
645                          (pglob->gl_pathc +
646                           ((flags & GLOB_DOOFFS) ? pglob->gl_offs : 0) +
647                           nfound + 1) *
648                          sizeof (char *));
649   if (pglob->gl_pathv == NULL)
650     goto memory_error;
651
652   if (flags & GLOB_DOOFFS)
653     while (pglob->gl_pathc < pglob->gl_offs)
654       pglob->gl_pathv[pglob->gl_pathc++] = NULL;
655
656   for (; names != NULL; names = names->next)
657     pglob->gl_pathv[pglob->gl_pathc++] = names->name;
658   pglob->gl_pathv[pglob->gl_pathc] = NULL;
659
660   pglob->gl_flags = flags;
661
662   if (stream != NULL)
663     {
664       int save = errno;
665       if (__glob_closedir_hook)
666         (*__glob_closedir_hook) (stream);
667       else
668         (void) closedir ((DIR *) stream);
669       errno = save;
670     }
671   return nfound == 0 ? GLOB_NOMATCH : 0;
672
673  memory_error:
674   {
675     int save = errno;
676     if (__glob_closedir_hook)
677       (*__glob_closedir_hook) (stream);
678     else
679       (void) closedir ((DIR *) stream);
680     errno = save;
681   }
682   while (names != NULL)
683     {
684       if (names->name != NULL)
685         free ((__ptr_t) names->name);
686       names = names->next;
687     }
688   return GLOB_NOSPACE;
689 }
690
691 #endif  /* _LIBC or not __GNU_LIBRARY__.  */