home *** CD-ROM | disk | FTP | other *** search
/ Monster Media 1994 #1 / monster.zip / monster / OS2 / MAN11A.ZIP / src / glob.c < prev    next >
C/C++ Source or Header  |  1991-08-24  |  16KB  |  681 lines

  1. /* File-name wildcard pattern matching for GNU.
  2.    Copyright (C) 1985, 1988, 1989, 1990, 1991 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 1, or (at your option)
  7.    any later version.
  8.  
  9.    This program 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
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* To whomever it may concern: I have never seen the code which most
  19.    Unix programs use to perform this function.  I wrote this from scratch
  20.    based on specifications for the pattern matching.  --RMS.  */
  21.  
  22. #ifdef SHELL
  23. #include "config.h"
  24. #endif /* SHELL */
  25.  
  26. #include <sys/types.h>
  27.  
  28. #if defined (USGr3) && !defined (DIRENT)
  29. #define DIRENT
  30. #endif /* USGr3 */
  31. #if defined (Xenix) && !defined (SYSNDIR)
  32. #define SYSNDIR
  33. #endif /* Xenix */
  34.  
  35. #if defined (POSIX) || defined (DIRENT) || defined (__GNU_LIBRARY__)
  36. #include <dirent.h>
  37. #define direct dirent
  38. #define D_NAMLEN(d) strlen((d)->d_name)
  39. #else /* not POSIX or DIRENT or __GNU_LIBRARY__ */
  40. #define D_NAMLEN(d) ((d)->d_namlen)
  41. #ifdef USG
  42. #if defined (SYSNDIR)
  43. #include <sys/ndir.h>
  44. #else /* SYSNDIR */
  45. #include "ndir.h"
  46. #endif /* not SYSNDIR */
  47. #else /* not USG */
  48. #include <sys/dir.h>
  49. #endif /* USG */
  50. #endif /* POSIX or DIRENT or __GNU_LIBRARY__ */
  51.  
  52. #if defined (_POSIX_SOURCE)
  53. /* Posix does not require that the d_ino field be present, and some
  54.    systems do not provide it. */
  55. #define REAL_DIR_ENTRY(dp) 1
  56. #else
  57. #define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
  58. #endif /* _POSIX_SOURCE */
  59.  
  60. #if defined (STDC_HEADERS) || defined (__GNU_LIBRARY__)
  61. #include <stdlib.h>
  62. #include <string.h>
  63. #define STDC_STRINGS
  64. #else /* STDC_HEADERS or __GNU_LIBRARY__ */
  65.  
  66. #if defined (USG)
  67. #include <string.h>
  68. #ifndef POSIX
  69. #include <memory.h>
  70. #endif /* POSIX */
  71. #define STDC_STRINGS
  72. #else /* not USG */
  73. #ifdef NeXT
  74. #include <string.h>
  75. #else /* NeXT */
  76. #include <strings.h>
  77. #endif /* NeXT */
  78. /* Declaring bcopy causes errors on systems whose declarations are different.
  79.    If the declaration is omitted, everything works fine.  */
  80. #endif /* not USG */
  81.  
  82. extern char *malloc ();
  83. extern char *realloc ();
  84. extern void free ();
  85.  
  86. #ifndef NULL
  87. #define NULL 0
  88. #endif
  89. #endif    /* Not STDC_HEADERS or __GNU_LIBRARY__.  */
  90.  
  91. #ifdef STDC_STRINGS
  92. #define bcopy(s, d, n) memcpy ((d), (s), (n))
  93. #define index strchr
  94. #define rindex strrchr
  95. #endif /* STDC_STRINGS */
  96.  
  97. #ifndef    alloca
  98. #ifdef __GNUC__
  99. #define alloca __builtin_alloca
  100. #else /* Not GCC.  */
  101. #ifdef sparc
  102. #include <alloca.h>
  103. #else /* Not sparc.  */
  104. extern char *alloca ();
  105. #endif /* sparc.  */
  106. #endif /* GCC.  */
  107. #endif
  108.  
  109. /* Nonzero if '*' and '?' do not match an initial '.' for glob_filename.  */
  110. int noglob_dot_filenames = 1;
  111.  
  112. static int glob_match_after_star ();
  113.  
  114. /* Return nonzero if PATTERN has any special globbing chars in it.  */
  115.  
  116. int
  117. glob_pattern_p (pattern)
  118.      char *pattern;
  119. {
  120.   register char *p = pattern;
  121.   register char c;
  122.   int open = 0;
  123.  
  124.   while ((c = *p++) != '\0')
  125.     switch (c)
  126.       {
  127.       case '?':
  128.       case '*':
  129.     return 1;
  130.  
  131.       case '[':        /* Only accept an open brace if there is a close */
  132.     open++;        /* brace to match it.  Bracket expressions must be */
  133.     continue;    /* complete, according to Posix.2 */
  134.       case ']':
  135.     if (open)
  136.       return 1;
  137.     continue;      
  138.  
  139.       case '\\':
  140.     if (*p++ == '\0')
  141.       return 0;
  142.       }
  143.  
  144.   return 0;
  145. }
  146.  
  147.  
  148. /* Match the pattern PATTERN against the string TEXT;
  149.    return 1 if it matches, 0 otherwise.
  150.  
  151.    A match means the entire string TEXT is used up in matching.
  152.  
  153.    In the pattern string, `*' matches any sequence of characters,
  154.    `?' matches any character, [SET] matches any character in the specified set,
  155.    [!SET] matches any character not in the specified set.
  156.  
  157.    A set is composed of characters or ranges; a range looks like
  158.    character hyphen character (as in 0-9 or A-Z).
  159.    [0-9a-zA-Z_] is the set of characters allowed in C identifiers.
  160.    Any other character in the pattern must be matched exactly.
  161.  
  162.    To suppress the special syntactic significance of any of `[]*?!-\',
  163.    and match the character exactly, precede it with a `\'.
  164.  
  165.    If DOT_SPECIAL is nonzero,
  166.    `*' and `?' do not match `.' at the beginning of TEXT.  */
  167.  
  168. int
  169. glob_match (pattern, text, dot_special)
  170.      char *pattern, *text;
  171.      int dot_special;
  172. {
  173.   register char *p = pattern, *t = text;
  174.   register char c;
  175.  
  176.   while ((c = *p++) != '\0')
  177.     switch (c)
  178.       {
  179.       case '?':
  180.     if (*t == '\0' || (dot_special && t == text && *t == '.'))
  181.       return 0;
  182.     else
  183.       ++t;
  184.     break;
  185.  
  186.       case '\\':
  187.     if (*p++ != *t++)
  188.       return 0;
  189.     break;
  190.  
  191.       case '*':
  192.     if (dot_special && t == text && *t == '.')
  193.       return 0;
  194.     return glob_match_after_star (p, t);
  195.  
  196.       case '[':
  197.     {
  198.       register char c1 = *t++;
  199.       int invert;
  200.  
  201.       if (c1 == '\0')
  202.         return 0;
  203.  
  204.       invert = (*p == '!');
  205.  
  206.       if (invert)
  207.         p++;
  208.  
  209.       c = *p++;
  210.       while (1)
  211.         {
  212.           register char cstart = c, cend = c;
  213.  
  214.           if (c == '\\')
  215.         {
  216.           cstart = *p++;
  217.           cend = cstart;
  218.         }
  219.  
  220.           if (cstart == '\0')
  221.         return 0;    /* Missing ']'. */
  222.  
  223.           c = *p++;
  224.  
  225.           if (c == '-')
  226.         {
  227.           cend = *p++;
  228.           if (cend == '\\')
  229.             cend = *p++;
  230.           if (cend == '\0')
  231.             return 0;
  232.           c = *p++;
  233.         }
  234.           if (c1 >= cstart && c1 <= cend)
  235.         goto match;
  236.           if (c == ']')
  237.         break;
  238.         }
  239.       if (!invert)
  240.         return 0;
  241.       break;
  242.  
  243.     match:
  244.       /* Skip the rest of the [...] construct that already matched.  */
  245.       while (c != ']')
  246.         {
  247.           if (c == '\0')
  248.         return 0;
  249.           c = *p++;
  250.           if (c == '\0')
  251.         return 0;
  252.           if (c == '\\')
  253.         p++;
  254.         }
  255.       if (invert)
  256.         return 0;
  257.       break;
  258.     }
  259.  
  260.       default:
  261.     if (c != *t++)
  262.       return 0;
  263.       }
  264.  
  265.   return *t == '\0';
  266. }
  267.  
  268. /* Like glob_match, but match PATTERN against any final segment of TEXT.  */
  269.  
  270. static int
  271. glob_match_after_star (pattern, text)
  272.      char *pattern, *text;
  273. {
  274.   register char *p = pattern, *t = text;
  275.   register char c, c1;
  276.  
  277.   while ((c = *p++) == '?' || c == '*')
  278.     if (c == '?' && *t++ == '\0')
  279.       return 0;
  280.  
  281.   if (c == '\0')
  282.     return 1;
  283.  
  284.   if (c == '\\')
  285.     c1 = *p;
  286.   else
  287.     c1 = c;
  288.  
  289.   --p;
  290.   while (1)
  291.     {
  292.       if ((c == '[' || *t == c1) && glob_match (p, t, 0))
  293.     return 1;
  294.       if (*t++ == '\0')
  295.     return 0;
  296.     }
  297. }
  298.  
  299. /* Return a vector of names of files in directory DIR
  300.    whose names match glob pattern PAT.
  301.    The names are not in any particular order.
  302.    Wildcards at the beginning of PAT do not match an initial period
  303.    if noglob_dot_filenames is nonzero.
  304.  
  305.    The vector is terminated by an element that is a null pointer.
  306.  
  307.    To free the space allocated, first free the vector's elements,
  308.    then free the vector.
  309.  
  310.    Return NULL if cannot get enough memory to hold the pointer
  311.    and the names.
  312.  
  313.    Return -1 if cannot access directory DIR.
  314.    Look in errno for more information.  */
  315.  
  316. char **
  317. glob_vector (pat, dir)
  318.      char *pat;
  319.      char *dir;
  320. {
  321.   struct globval
  322.   {
  323.     struct globval *next;
  324.     char *name;
  325.   };
  326.  
  327.   DIR *d;
  328.   register struct direct *dp;
  329.   struct globval *lastlink;
  330.   register struct globval *nextlink;
  331.   register char *nextname;
  332.   unsigned int count;
  333.   int lose;
  334.   register char **name_vector;
  335.   register unsigned int i;
  336. #ifdef ALLOCA_MISSING
  337.   struct globval *templink;
  338. #endif
  339.  
  340.   d = opendir (dir);
  341.   if (d == NULL)
  342.     return (char **) -1;
  343.  
  344.   lastlink = NULL;
  345.   count = 0;
  346.   lose = 0;
  347.  
  348.   /* Scan the directory, finding all names that match.
  349.      For each name that matches, allocate a struct globval
  350.      on the stack and store the name in it.
  351.      Chain those structs together; lastlink is the front of the chain.  */
  352.   while (1)
  353.     {
  354. #if defined (SHELL)
  355.       /* Make globbing interruptible in the bash shell. */
  356.       extern int interrupt_state;
  357.  
  358.       if (interrupt_state)
  359.     {
  360.       closedir (d);
  361.       lose = 1;
  362.       goto lost;
  363.     }
  364. #endif /* SHELL */
  365.       
  366.       dp = readdir (d);
  367.       if (dp == NULL)
  368.     break;
  369.       if (REAL_DIR_ENTRY (dp)
  370.       && glob_match (pat, dp->d_name, noglob_dot_filenames))
  371.     {
  372. #ifdef ALLOCA_MISSING      
  373.       nextlink = (struct globval *) malloc (sizeof (struct globval));
  374. #else
  375.       nextlink = (struct globval *) alloca (sizeof (struct globval));
  376. #endif
  377.       nextlink->next = lastlink;
  378.       i = D_NAMLEN (dp) + 1;
  379.       nextname = (char *) malloc (i);
  380.       if (nextname == NULL)
  381.         {
  382.           lose = 1;
  383.           break;
  384.         }
  385.       lastlink = nextlink;
  386.       nextlink->name = nextname;
  387.       bcopy (dp->d_name, nextname, i);
  388.       count++;
  389.     }
  390.     }
  391.   closedir (d);
  392.  
  393.   if (!lose)
  394.     {
  395.       name_vector = (char **) malloc ((count + 1) * sizeof (char *));
  396.       lose |= name_vector == NULL;
  397.     }
  398.  
  399.   /* Have we run out of memory?  */
  400. #ifdef    SHELL
  401.  lost:
  402. #endif
  403.   if (lose)
  404.     {
  405.       /* Here free the strings we have got.  */
  406.       while (lastlink)
  407.     {
  408.       free (lastlink->name);
  409. #ifdef ALLOCA_MISSING
  410.       templink = lastlink->next;
  411.       free ((char *) lastlink);
  412.       lastlink = templink;
  413. #else
  414.       lastlink = lastlink->next;
  415. #endif
  416.     }
  417.       return NULL;
  418.     }
  419.  
  420.   /* Copy the name pointers from the linked list into the vector.  */
  421.   for (i = 0; i < count; ++i)
  422.     {
  423.       name_vector[i] = lastlink->name;
  424. #ifdef ALLOCA_MISSING
  425.       templink = lastlink->next;
  426.       free ((char *) lastlink);
  427.       lastlink = templink;
  428. #else
  429.       lastlink = lastlink->next;
  430. #endif
  431.     }
  432.  
  433.   name_vector[count] = NULL;
  434.   return name_vector;
  435. }
  436.  
  437. /* Return a new array, replacing ARRAY, which is the concatenation
  438.    of each string in ARRAY to DIR.
  439.    Return NULL if out of memory.  */
  440.  
  441. static char **
  442. glob_dir_to_array (dir, array)
  443.      char *dir, **array;
  444. {
  445.   register unsigned int i, l;
  446.   int add_slash = 0;
  447.   char **result;
  448.  
  449.   l = strlen (dir);
  450.   if (l == 0)
  451.     return array;
  452.  
  453.   if (dir[l - 1] != '/')
  454.     add_slash++;
  455.  
  456.   for (i = 0; array[i] != NULL; i++)
  457.     ;
  458.  
  459.   result = (char **) malloc ((i + 1) * sizeof (char *));
  460.   if (result == NULL)
  461.     return NULL;
  462.  
  463.   for (i = 0; array[i] != NULL; i++)
  464.     {
  465.       result[i] = (char *) malloc (1 + l + add_slash + strlen (array[i]));
  466.       if (result[i] == NULL)
  467.     return NULL;
  468.       strcpy (result[i], dir);
  469.       if (add_slash)
  470.     result[i][l] = '/';
  471.       strcpy (result[i] + l + add_slash, array[i]);
  472.     }
  473.   result[i] = NULL;
  474.  
  475.   /* Free the input array.  */
  476.   for (i = 0; array[i] != NULL; i++)
  477.     free (array[i]);
  478.   free ((char *) array);
  479.   return result;
  480. }
  481.  
  482. /* Do globbing on PATHNAME.  Return an array of pathnames that match,
  483.    marking the end of the array with a null-pointer as an element.
  484.    If no pathnames match, then the array is empty (first element is null).
  485.    If there isn't enough memory, then return NULL.
  486.    If a file system error occurs, return -1; `errno' has the error code.
  487.  
  488.    Wildcards at the beginning of PAT, or following a slash,
  489.    do not match an initial period if noglob_dot_filenames is nonzero.  */
  490.  
  491. char **
  492. glob_filename (pathname)
  493.      char *pathname;
  494. {
  495.   char **result;
  496.   unsigned int result_size;
  497.   char *directory_name, *filename;
  498.   unsigned int directory_len;
  499.  
  500.   result = (char **) malloc (sizeof (char *));
  501.   result_size = 1;
  502.   if (result == NULL)
  503.     return NULL;
  504.  
  505.   result[0] = NULL;
  506.  
  507.   /* Find the filename.  */
  508.   filename = rindex (pathname, '/');
  509.   if (filename == NULL)
  510.     {
  511.       filename = pathname;
  512.       directory_name = "";
  513.       directory_len = 0;
  514.     }
  515.   else
  516.     {
  517.       directory_len = (filename - pathname) + 1;
  518. #ifdef ALLOCA_MISSING
  519.       directory_name = (char *) malloc (directory_len + 1);
  520. #else
  521.       directory_name = (char *) alloca (directory_len + 1);
  522. #endif
  523.       bcopy (pathname, directory_name, directory_len);
  524.       directory_name[directory_len] = '\0';
  525.       ++filename;
  526.     }
  527.  
  528.   /* If directory_name contains globbing characters, then we
  529.      have to expand the previous levels.  Just recurse. */
  530.   if (glob_pattern_p (directory_name))
  531.     {
  532.       char **directories;
  533.       register unsigned int i;
  534.  
  535.       if (directory_name[directory_len - 1] == '/')
  536.     directory_name[directory_len - 1] = '\0';
  537.  
  538.       directories = glob_filename (directory_name);
  539. #ifdef ALLOCA_MISSING
  540.       free ((char *) directory_name);
  541. #endif
  542.       if (directories == NULL)
  543.     goto memory_error;
  544.       else if (directories == (char **) -1)
  545.     return (char **) -1;
  546.       else if (*directories == NULL)
  547.     {
  548.       free ((char *) directories);
  549.       return (char **) -1;
  550.     }
  551.  
  552.       /* We have successfully globbed the preceding directory name.
  553.      For each name in DIRECTORIES, call glob_vector on it and
  554.      FILENAME.  Concatenate the results together.  */
  555.       for (i = 0; directories[i] != NULL; i++)
  556.     {
  557.       char **temp_results = glob_vector (filename, directories[i]);
  558.       if (temp_results == NULL)
  559.         goto memory_error;
  560.       else if (temp_results == (char **) -1)
  561.         /* This filename is probably not a directory.  Ignore it.  */
  562.         ;
  563.       else
  564.         {
  565.           char **array = glob_dir_to_array (directories[i], temp_results);
  566.           register unsigned int l;
  567.  
  568.           l = 0;
  569.           while (array[l] != NULL)
  570.         ++l;
  571.  
  572.           result = (char **) realloc (result,
  573.                       (result_size + l) * sizeof (char *));
  574.           if (result == NULL)
  575.         goto memory_error;
  576.  
  577.           for (l = 0; array[l] != NULL; ++l)
  578.         result[result_size++ - 1] = array[l];
  579.           result[result_size - 1] = NULL;
  580.           free ((char *) array);
  581.         }
  582.     }
  583.       /* Free the directories.  */
  584.       for (i = 0; directories[i] != NULL; i++)
  585.     free (directories[i]);
  586.       free ((char *) directories);
  587.  
  588.       return result;
  589.     }
  590.  
  591.   /* If there is only a directory name, return it. */
  592.   if (*filename == '\0')
  593.     {
  594.       result = (char **) realloc ((char *) result, 2 * sizeof (char *));
  595.       if (result != NULL)
  596.     {
  597.       result[0] = (char *) malloc (directory_len + 1);
  598.       if (result[0] == NULL)
  599.         {
  600. #ifdef ALLOCA_MISSING
  601.           free ((char *) directory_name);
  602. #endif
  603.           goto memory_error;
  604.         }
  605.       bcopy (directory_name, result[0], directory_len + 1);
  606.       result[1] = NULL;
  607.     }
  608. #ifdef ALLOCA_MISSING
  609.       free ((char *) directory_name);
  610. #endif
  611.       return result;
  612.     }
  613.   else
  614.     {
  615.       /* Otherwise, just return what glob_vector
  616.      returns appended to the directory name. */
  617.       char **temp_results = glob_vector (filename,
  618.                      (directory_len == 0
  619.                       ? "." : directory_name));
  620.  
  621.       if (temp_results == NULL || temp_results == (char **) -1)
  622.     {
  623. #ifdef NO_ALLOCA
  624.       free ((char *) directory_name);
  625. #endif
  626.       return temp_results;
  627.     }
  628.  
  629.       temp_results = glob_dir_to_array (directory_name, temp_results);
  630. #ifdef NO_ALLOCA
  631.       free ((char *) directory_name);
  632. #endif
  633.       return temp_results;
  634.     }
  635.  
  636.   /* We get to memory error if the program has run out of memory, or
  637.      if this is the shell, and we have been interrupted. */
  638.  memory_error:
  639.   if (result != NULL)
  640.     {
  641.       register unsigned int i;
  642.       for (i = 0; result[i] != NULL; ++i)
  643.     free (result[i]);
  644.       free ((char *) result);
  645.     }
  646. #if defined (SHELL)
  647.   {
  648.     extern int interrupt_state;
  649.  
  650.     if (interrupt_state)
  651.       throw_to_top_level ();
  652.   }
  653. #endif /* SHELL */
  654.   return NULL;
  655. }
  656.  
  657. #ifdef TEST
  658.  
  659. main (argc, argv)
  660.      int argc;
  661.      char **argv;
  662. {
  663.   char **value;
  664.   int i, optind;
  665.  
  666.   for (optind = 1; optind < argc; optind++)
  667.     {
  668.       value = glob_filename (argv[optind]);
  669.       if (value == NULL)
  670.     puts ("virtual memory exhausted");
  671.       else if (value == (char **) -1)
  672.     perror (argv[optind]);
  673.       else
  674.     for (i = 0; value[i] != NULL; i++)
  675.       puts (value[i]);
  676.     }
  677.   exit (0);
  678. }
  679.  
  680. #endif /* TEST */
  681.