OSDN Git Service

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