2 #include <linux/module.h>
3 #include "libcfs/linux/glob.h"
6 * glob_match - Shell-style pattern matching, like !fnmatch(pat, str, 0)
7 * @pat: Shell-style pattern to match, e.g. "*.[ch]".
8 * @str: String to match. The pattern must match the entire string.
10 * Perform shell-style glob matching, returning true (1) if the match
11 * succeeds, or false (0) if it fails. Equivalent to !fnmatch(@pat, @str, 0).
13 * Pattern metacharacters are ?, *, [ and \.
14 * (And, inside character classes, !, - and ].)
16 * This is small and simple implementation intended for device blacklists
17 * where a string is matched against a number of patterns. Thus, it
18 * does not preprocess the patterns. It is non-recursive, and run-time
19 * is at most quadratic: strlen(@str)*strlen(@pat).
21 * An example of the worst case is glob_match("*aaaaa", "aaaaaaaaaa");
22 * it takes 6 passes over the pattern before matching the string.
24 * Like !fnmatch(@pat, @str, 0) and unlike the shell, this does NOT
25 * treat / or leading . specially; it isn't actually used for pathnames.
27 * Note that according to glob(7) (and unlike bash), character classes
28 * are complemented by a leading !; this does not support the regex-style
31 * An opening bracket without a matching close is matched literally.
33 bool __pure glob_match(char const *pat, char const *str)
36 * Backtrack to previous * on mismatch and retry starting one
37 * character later in the string. Because * matches all characters
38 * (no exception for /), it can be easily proved that there's
39 * never a need to backtrack multiple levels.
41 char const *back_pat = NULL, *back_str = back_str;
44 * Loop over each token (character or class) in pat, matching
45 * it against the remaining unmatched tail of str. Return false
46 * on mismatch, or true after matching the trailing nul bytes.
49 unsigned char c = *str++;
50 unsigned char d = *pat++;
53 case '?': /* Wildcard: anything but nul */
57 case '*': /* Any-length wildcard */
58 if (*pat == '\0') /* Optimize trailing * case */
61 back_str = --str; /* Allow zero-length match */
63 case '[': { /* Character class */
64 bool match = false, inverted = (*pat == '!');
65 char const *class = pat + inverted;
66 unsigned char a = *class++;
69 * Iterate over each span in the character class.
70 * A span is either a single character a, or a
71 * range a-b. The first span may begin with ']'.
76 if (a == '\0') /* Malformed */
79 if (class[0] == '-' && class[1] != ']') {
86 /* Any special action if a > b? */
88 match |= (a <= c && c <= b);
89 } while ((a = *class++) != ']');
91 if (match == inverted)
99 default: /* Literal character */
107 if (c == '\0' || !back_pat)
108 return false; /* No point continuing */
109 /* Try again from last *, one character later in str. */
116 EXPORT_SYMBOL(glob_match);
117 #endif /* ! HAVE_GLOB */