OSDN Git Service

hidden_def/hidden_proto: convert all users (I hope) termios split, add some missing...
[uclinux-h8/uClibc.git] / libc / misc / glob / 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 #include <features.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <errno.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <unistd.h>
25 #include <dirent.h>
26 #include <malloc.h>
27 #include <fnmatch.h>
28 #define _GNU_SOURCE
29 #include <glob.h>
30
31 libc_hidden_proto(memcpy)
32 libc_hidden_proto(strcat)
33 libc_hidden_proto(strcmp)
34 libc_hidden_proto(strlen)
35 libc_hidden_proto(strrchr)
36 libc_hidden_proto(strcoll)
37 libc_hidden_proto(opendir)
38 libc_hidden_proto(closedir)
39 libc_hidden_proto(fnmatch)
40 libc_hidden_proto(qsort)
41 libc_hidden_proto(lstat)
42
43 extern __ptr_t (*__glob_opendir_hook) __P ((const char *directory));
44 extern void (*__glob_closedir_hook) __P ((__ptr_t stream));
45 extern const char *(*__glob_readdir_hook) __P ((__ptr_t stream));
46
47
48 static int glob_in_dir __P ((const char *pattern, const char *directory,
49                              int flags,
50                              int (*errfunc) __P ((const char *, int)),
51                              glob_t *pglob));
52 static int prefix_array __P ((const char *prefix, char **array, size_t n,
53                               int add_slash));
54 static int collated_compare __P ((const __ptr_t, const __ptr_t));
55
56 #ifdef __GLOB64
57 extern int __glob_pattern_p(const char *pattern, int quote) attribute_hidden;
58 libc_hidden_proto(readdir64)
59 #define __readdir readdir64
60 #else
61 extern int __glob (__const char *__restrict __pattern, int __flags,
62                  int (*__errfunc) (__const char *, int),
63                  glob_t *__restrict __pglob) __THROW attribute_hidden;
64 extern void __globfree (glob_t *__pglob) __THROW attribute_hidden;
65 #define __readdir readdir
66 libc_hidden_proto(readdir)
67 /* Return nonzero if PATTERN contains any metacharacters.
68    Metacharacters can be quoted with backslashes if QUOTE is nonzero.  */
69 int attribute_hidden __glob_pattern_p(const char *pattern, int quote)
70 {
71     const char *p;
72     int open = 0;
73
74     for (p = pattern; *p != '\0'; ++p)
75         switch (*p)
76         {
77             case '?':
78             case '*':
79                 return 1;
80
81             case '\\':
82                 if (quote && p[1] != '\0')
83                     ++p;
84                 break;
85
86             case '[':
87                 open = 1;
88                 break;
89
90             case ']':
91                 if (open)
92                     return 1;
93                 break;
94         }
95
96     return 0;
97 }
98 strong_alias(__glob_pattern_p,glob_pattern_p)
99 #endif
100
101
102 /* Do glob searching for PATTERN, placing results in PGLOB.
103    The bits defined above may be set in FLAGS.
104    If a directory cannot be opened or read and ERRFUNC is not nil,
105    it is called with the pathname that caused the error, and the
106    `errno' value from the failing call; if it returns non-zero
107    `glob' returns GLOB_ABEND; if it returns zero, the error is ignored.
108    If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
109    Otherwise, `glob' returns zero.  */
110 int attribute_hidden
111 __glob (pattern, flags, errfunc, pglob)
112      const char *pattern;
113      int flags;
114      int (*errfunc) __P ((const char *, int));
115      glob_t *pglob;
116 {
117   const char *filename;
118   char *dirname;
119   size_t dirlen;
120   int status;
121   int oldcount;
122
123   if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
124     {
125       errno = EINVAL;
126       return -1;
127     }
128
129   /* Find the filename.  */
130   filename = strrchr (pattern, '/');
131   if (filename == NULL)
132     {
133       filename = pattern;
134       dirname = (char *) ".";
135       dirlen = 0;
136     }
137   else if (filename == pattern)
138     {
139       /* "/pattern".  */
140       dirname = (char *) "/";
141       dirlen = 1;
142       ++filename;
143     }
144   else
145     {
146       dirlen = filename - pattern;
147       dirname = (char *) alloca (dirlen + 1);
148       memcpy (dirname, pattern, dirlen);
149       dirname[dirlen] = '\0';
150       ++filename;
151     }
152
153   if (filename[0] == '\0' && dirlen > 1)
154     /* "pattern/".  Expand "pattern", appending slashes.  */
155     {
156       int val = __glob (dirname, flags | GLOB_MARK, errfunc, pglob);
157       if (val == 0)
158         pglob->gl_flags = (pglob->gl_flags & ~GLOB_MARK) | (flags & GLOB_MARK);
159       return val;
160     }
161
162   if (!(flags & GLOB_APPEND))
163     {
164       pglob->gl_pathc = 0;
165       pglob->gl_pathv = NULL;
166     }
167
168   oldcount = pglob->gl_pathc;
169
170   if (__glob_pattern_p (dirname, !(flags & GLOB_NOESCAPE)))
171     {
172       /* The directory name contains metacharacters, so we
173          have to glob for the directory, and then glob for
174          the pattern in each directory found.  */
175       glob_t dirs;
176       register int i;
177
178       status = __glob (dirname,
179                      ((flags & (GLOB_ERR | GLOB_NOCHECK | GLOB_NOESCAPE)) |
180                       GLOB_NOSORT),
181                      errfunc, &dirs);
182       if (status != 0)
183         return status;
184
185       /* We have successfully globbed the preceding directory name.
186          For each name we found, call glob_in_dir on it and FILENAME,
187          appending the results to PGLOB.  */
188       for (i = 0; i < dirs.gl_pathc; ++i)
189         {
190           int oldcount;
191
192 #ifdef  SHELL
193           {
194             /* Make globbing interruptible in the bash shell. */
195             extern int interrupt_state;
196
197             if (interrupt_state)
198               {
199                 __globfree (&dirs);
200                 __globfree (&files);
201                 return GLOB_ABEND;
202               }
203           }
204 #endif /* SHELL.  */
205
206           oldcount = pglob->gl_pathc;
207           status = glob_in_dir (filename, dirs.gl_pathv[i],
208                                 (flags | GLOB_APPEND) & ~GLOB_NOCHECK,
209                                 errfunc, pglob);
210           if (status == GLOB_NOMATCH)
211             /* No matches in this directory.  Try the next.  */
212             continue;
213
214           if (status != 0)
215             {
216               __globfree (&dirs);
217               __globfree (pglob);
218               return status;
219             }
220
221           /* Stick the directory on the front of each name.  */
222           if (prefix_array (dirs.gl_pathv[i],
223                             &pglob->gl_pathv[oldcount],
224                             pglob->gl_pathc - oldcount,
225                             flags & GLOB_MARK))
226             {
227               __globfree (&dirs);
228               __globfree (pglob);
229               return GLOB_NOSPACE;
230             }
231         }
232
233       flags |= GLOB_MAGCHAR;
234
235       if (pglob->gl_pathc == oldcount)
236       {
237         /* No matches.  */
238         if (flags & GLOB_NOCHECK)
239         {
240             size_t len = strlen (pattern) + 1;
241             char *patcopy = (char *) malloc (len);
242             if (patcopy == NULL)
243               return GLOB_NOSPACE;
244             memcpy (patcopy, pattern, len);
245
246             pglob->gl_pathv
247               = (char **) realloc (pglob->gl_pathv,
248                                    (pglob->gl_pathc +
249                                     ((flags & GLOB_DOOFFS) ?
250                                      pglob->gl_offs : 0) +
251                                     1 + 1) *
252                                    sizeof (char *));
253             if (pglob->gl_pathv == NULL)
254               {
255                 free (patcopy);
256                 return GLOB_NOSPACE;
257               }
258
259             if (flags & GLOB_DOOFFS)
260               while (pglob->gl_pathc < pglob->gl_offs)
261                 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
262
263             pglob->gl_pathv[pglob->gl_pathc++] = patcopy;
264             pglob->gl_pathv[pglob->gl_pathc] = NULL;
265             pglob->gl_flags = flags;
266         }
267         else 
268         {
269           return GLOB_NOMATCH;
270         }
271       }
272     }
273   else
274     {
275       status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
276       if (status != 0)
277         return status;
278
279       if (dirlen > 0)
280         {
281           /* Stick the directory on the front of each name.  */
282           if (prefix_array (dirname,
283                             &pglob->gl_pathv[oldcount],
284                             pglob->gl_pathc - oldcount,
285                             flags & GLOB_MARK))
286             {
287               __globfree (pglob);
288               return GLOB_NOSPACE;
289             }
290         }
291     }
292
293   if (flags & GLOB_MARK)
294     {
295       /* Append slashes to directory names.  glob_in_dir has already
296          allocated the extra character for us.  */
297       int i;
298       struct stat st;
299       for (i = oldcount; i < pglob->gl_pathc; ++i)
300         if (lstat (pglob->gl_pathv[i], &st) == 0 &&
301             S_ISDIR (st.st_mode))
302           strcat (pglob->gl_pathv[i], "/");
303     }
304
305   if (!(flags & GLOB_NOSORT))
306     /* Sort the vector.  */
307     qsort ((__ptr_t) &pglob->gl_pathv[oldcount],
308            pglob->gl_pathc - oldcount,
309            sizeof (char *), (__compar_fn_t)collated_compare);
310
311   return 0;
312 }
313 #ifdef __GLOB64
314 strong_alias(__glob64,glob64)
315 #else
316 strong_alias(__glob,glob)
317 #endif
318
319
320 /* Free storage allocated in PGLOB by a previous `glob' call.  */
321 void attribute_hidden
322 __globfree (pglob)
323      register glob_t *pglob;
324 {
325   if (pglob->gl_pathv != NULL)
326     {
327       register int i = pglob->gl_flags & GLOB_DOOFFS? pglob->gl_offs : 0;
328       for (; i < pglob->gl_pathc; ++i)
329         if (pglob->gl_pathv[i] != NULL)
330           free ((__ptr_t) pglob->gl_pathv[i]);
331       free ((__ptr_t) pglob->gl_pathv);
332     }
333 }
334 #ifdef __GLOB64
335 strong_alias(__globfree64,globfree64)
336 #else
337 strong_alias(__globfree,globfree)
338 #endif
339
340
341 /* Do a collated comparison of A and B.  */
342 static int
343 collated_compare (a, b)
344      const __ptr_t a;
345      const __ptr_t b;
346 {
347   const char *const s1 = *(const char *const *) a;
348   const char *const s2 = *(const char *const *) b;
349
350   if (s1 == s2)
351     return 0;
352   if (s1 == NULL)
353     return 1;
354   if (s2 == NULL)
355     return -1;
356   return strcoll (s1, s2);
357 }
358
359
360 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
361    elements in place.  Return nonzero if out of memory, zero if successful.
362    A slash is inserted between DIRNAME and each elt of ARRAY,
363    unless DIRNAME is just "/".  Each old element of ARRAY is freed.
364    If ADD_SLASH is non-zero, allocate one character more than
365    necessary, so that a slash can be appended later.  */
366 static int
367 prefix_array (dirname, array, n, add_slash)
368      const char *dirname;
369      char **array;
370      size_t n;
371      int add_slash;
372 {
373   register size_t i;
374   size_t dirlen = strlen (dirname);
375
376   if (dirlen == 1 && dirname[0] == '/')
377     /* DIRNAME is just "/", so normal prepending would get us "//foo".
378        We want "/foo" instead, so don't prepend any chars from DIRNAME.  */
379     dirlen = 0;
380
381   for (i = 0; i < n; ++i)
382     {
383       size_t eltlen = strlen (array[i]) + 1;
384       char *new = (char *) malloc (dirlen + 1 + eltlen + (add_slash ? 1 : 0));
385       if (new == NULL)
386         {
387           while (i > 0)
388             free ((__ptr_t) array[--i]);
389           return 1;
390         }
391
392       memcpy (new, dirname, dirlen);
393       new[dirlen] = '/';
394       memcpy (&new[dirlen + 1], array[i], eltlen);
395       free ((__ptr_t) array[i]);
396       array[i] = new;
397     }
398
399   return 0;
400 }
401
402
403 /* Like `glob', but PATTERN is a final pathname component,
404    and matches are searched for in DIRECTORY.
405    The GLOB_NOSORT bit in FLAGS is ignored.  No sorting is ever done.
406    The GLOB_APPEND flag is assumed to be set (always appends).  */
407 static int
408 glob_in_dir (pattern, directory, flags, errfunc, pglob)
409      const char *pattern;
410      const char *directory;
411      int flags;
412      int (*errfunc) __P ((const char *, int));
413      glob_t *pglob;
414 {
415   __ptr_t stream;
416
417   struct globlink
418     {
419       struct globlink *next;
420       char *name;
421     };
422   struct globlink *names = NULL;
423   size_t nfound = 0;
424   int meta;
425
426   stream = (__glob_opendir_hook ? (*__glob_opendir_hook) (directory)
427            : (__ptr_t) opendir (directory));
428   if (stream == NULL)
429     {
430       if ((errfunc != NULL && (*errfunc) (directory, errno)) ||
431           (flags & GLOB_ERR))
432         return GLOB_ABORTED;
433     }
434
435   meta = __glob_pattern_p (pattern, !(flags & GLOB_NOESCAPE));
436
437   if (meta)
438     flags |= GLOB_MAGCHAR;
439
440   while (1)
441     {
442       const char *name;
443       size_t len;
444
445       if (__glob_readdir_hook)
446         {
447           name = (*__glob_readdir_hook) (stream);
448           if (name == NULL)
449             break;
450           len = 0;
451         }
452       else
453         {
454           struct dirent *d = __readdir ((DIR *) stream);
455           if (d == NULL)
456             break;
457           if (! (d->d_ino != 0))
458             continue;
459           name = d->d_name;
460 #ifdef _DIRENT_HAVE_D_NAMLEN
461           len = d->d_namlen;
462 #else
463           len = 0;
464 #endif
465         }
466                 
467       if ((!meta && strcmp (pattern, name) == 0)
468           || fnmatch (pattern, name,
469                       (!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0) |
470                       ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)) == 0)
471         {
472           struct globlink *new
473             = (struct globlink *) alloca (sizeof (struct globlink));
474           if (len == 0)
475             len = strlen (name);
476           new->name
477             = (char *) malloc (len + ((flags & GLOB_MARK) ? 1 : 0) + 1);
478           if (new->name == NULL)
479             goto memory_error;
480           memcpy ((__ptr_t) new->name, name, len);
481           new->name[len] = '\0';
482           new->next = names;
483           names = new;
484           ++nfound;
485           if (!meta)
486             break;
487         }
488     }
489
490   if (nfound == 0 && (flags & GLOB_NOCHECK))
491     {
492       size_t len = strlen (pattern);
493       nfound = 1;
494       names = (struct globlink *) alloca (sizeof (struct globlink));
495       names->next = NULL;
496       names->name = (char *) malloc (len + (flags & GLOB_MARK ? 1 : 0) + 1);
497       if (names->name == NULL)
498         goto memory_error;
499       memcpy (names->name, pattern, len);
500       names->name[len] = '\0';
501     }
502
503   pglob->gl_pathv
504     = (char **) realloc (pglob->gl_pathv,
505                          (pglob->gl_pathc +
506                           ((flags & GLOB_DOOFFS) ? pglob->gl_offs : 0) +
507                           nfound + 1) *
508                          sizeof (char *));
509   if (pglob->gl_pathv == NULL)
510     goto memory_error;
511
512   if (flags & GLOB_DOOFFS)
513     while (pglob->gl_pathc < pglob->gl_offs)
514       pglob->gl_pathv[pglob->gl_pathc++] = NULL;
515
516   for (; names != NULL; names = names->next)
517     pglob->gl_pathv[pglob->gl_pathc++] = names->name;
518   pglob->gl_pathv[pglob->gl_pathc] = NULL;
519
520   pglob->gl_flags = flags;
521
522   {
523     int save = errno;
524     if (__glob_closedir_hook)
525       (*__glob_closedir_hook) (stream);
526     else
527       (void) closedir ((DIR *) stream);
528     errno = save;
529   }
530   return nfound == 0 ? GLOB_NOMATCH : 0;
531
532  memory_error:
533   {
534     int save = errno;
535     if (__glob_closedir_hook)
536       (*__glob_closedir_hook) (stream);
537     else
538       (void) closedir ((DIR *) stream);
539     errno = save;
540   }
541   while (names != NULL)
542     {
543       if (names->name != NULL)
544         free ((__ptr_t) names->name);
545       names = names->next;
546     }
547   return GLOB_NOSPACE;
548 }
549