2 * ircd_match_t.c - test cases for irc glob matching
8 #include <errno.h> /* errno */
9 #include <fcntl.h> /* O_RDONLY */
12 #include <sys/mman.h> /* mmap(), munmap() */
13 #include <unistd.h> /* sysconf() */
15 #if !defined(MAP_ANONYMOUS)
16 # if defined(MAP_ANON)
17 # define MAP_ANONYMOUS MAP_ANON
19 # error I do not know how to request an anonymous mmap from your OS.
25 const char *should_match;
26 const char *shouldnt_match;
29 const struct match_test match_tests[] = {
34 "a\0pizza\0abe\0brack\0",
38 "*PeacefuL*\0pizza\0???\0" },
43 "abc\0fooabc\0ababc\0",
50 "dark\\s|de!pimp\0joe\\[mama\0" },
54 int test_match(const char glob[], const char name[])
56 static unsigned int page_size;
63 /* If we have not yet set up our test mappings, do so. */
68 page_size = sysconf(_SC_PAGE_SIZE);
69 if (page_size == 0 || page_size == (unsigned int)-1)
71 fprintf(stderr, "sysconf(_SC_PAGE_SIZE) failed: %s\n", strerror(errno));
74 dev_zero_fd = open("/dev/zero", O_RDONLY);
75 /* If dev_zero_fd == -1 (failed), we may still be able to mmap anonymously. */
76 pages = mmap(NULL, 4 * page_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, dev_zero_fd, 0);
77 if (pages == MAP_FAILED)
79 /* Try using fd == -1 for MAP_ANONYMOUS, which BSD systems require. */
80 pages = mmap(NULL, 4 * page_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
82 if (pages == MAP_FAILED)
84 fprintf(stderr, "Unable to map pages: %s\n", strerror(errno));
92 res = munmap(pages + page_size * 1, page_size);
95 fprintf(stderr, "Unable to unmap page 2/4: %s\n", strerror(errno));
96 /* Dysfunctional OSes */
98 munmap(pages + page_size * 3, page_size);
101 fprintf(stderr, "Unable to unmap page 4/4: %s\n", strerror(errno));
105 /* Copy the strings to the end of their respective pages. */
106 length = strlen(glob) + 1;
107 test_glob = pages + page_size * 1 - length;
108 memcpy(test_glob, glob, length);
109 length = strlen(name) + 1;
110 test_name = pages + page_size * 3 - length;
111 memcpy(test_name, name, length);
113 /* Perform the test. */
114 return match(test_glob, test_name);
117 void do_match_test(const struct match_test *test)
119 const char *candidate;
120 unsigned int matched, not_matched;
123 for (candidate = test->should_match, matched = 0;
125 candidate += strlen(candidate) + 1, ++matched) {
126 res = test_match(test->glob, candidate);
128 fprintf(stderr, "\"%s\" failed to match \"%s\".\n", test->glob, candidate);
133 for (candidate = test->shouldnt_match, not_matched = 0;
135 candidate += strlen(candidate) + 1, ++not_matched) {
136 res = test_match(test->glob, candidate);
138 fprintf(stderr, "\"%s\" incorrectly matched \"%s\".\n", test->glob, candidate);
143 printf("Passed: %s (%u matches, %u non-matches)\n",
144 test->glob, matched, not_matched);
147 int main(int argc, char *argv[])
149 const struct match_test *match;
150 for (match = match_tests; match->glob; ++match)
151 do_match_test(match);