]> git.cameronkatri.com Git - mandoc.git/blob - apropos_db.c
Support -Ios='OpenBSD 5.1' to override uname(3) as the source of the
[mandoc.git] / apropos_db.c
1 /* $Id: apropos_db.c,v 1.32 2012/03/25 00:48:47 kristaps Exp $ */
2 /*
3 * Copyright (c) 2011, 2012 Kristaps Dzonsons <kristaps@bsd.lv>
4 * Copyright (c) 2011 Ingo Schwarze <schwarze@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18 #ifdef HAVE_CONFIG_H
19 #include "config.h"
20 #endif
21
22 #include <sys/param.h>
23
24 #include <assert.h>
25 #include <fcntl.h>
26 #include <regex.h>
27 #include <stdarg.h>
28 #include <stdint.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <unistd.h>
32
33 #if defined(__linux__)
34 # include <endian.h>
35 # include <db_185.h>
36 #elif defined(__APPLE__)
37 # include <libkern/OSByteOrder.h>
38 # include <db.h>
39 #else
40 # include <db.h>
41 #endif
42
43 #include "mandocdb.h"
44 #include "apropos_db.h"
45 #include "mandoc.h"
46
47 #define RESFREE(_x) \
48 do { \
49 free((_x)->file); \
50 free((_x)->cat); \
51 free((_x)->title); \
52 free((_x)->arch); \
53 free((_x)->desc); \
54 free((_x)->matches); \
55 } while (/*CONSTCOND*/0)
56
57 struct expr {
58 int regex; /* is regex? */
59 int index; /* index in match array */
60 uint64_t mask; /* type-mask */
61 int and; /* is rhs of logical AND? */
62 char *v; /* search value */
63 regex_t re; /* compiled re, if regex */
64 struct expr *next; /* next in sequence */
65 struct expr *subexpr;
66 };
67
68 struct type {
69 uint64_t mask;
70 const char *name;
71 };
72
73 struct rectree {
74 struct res *node; /* record array for dir tree */
75 int len; /* length of record array */
76 };
77
78 static const struct type types[] = {
79 { TYPE_An, "An" },
80 { TYPE_Ar, "Ar" },
81 { TYPE_At, "At" },
82 { TYPE_Bsx, "Bsx" },
83 { TYPE_Bx, "Bx" },
84 { TYPE_Cd, "Cd" },
85 { TYPE_Cm, "Cm" },
86 { TYPE_Dv, "Dv" },
87 { TYPE_Dx, "Dx" },
88 { TYPE_Em, "Em" },
89 { TYPE_Er, "Er" },
90 { TYPE_Ev, "Ev" },
91 { TYPE_Fa, "Fa" },
92 { TYPE_Fl, "Fl" },
93 { TYPE_Fn, "Fn" },
94 { TYPE_Fn, "Fo" },
95 { TYPE_Ft, "Ft" },
96 { TYPE_Fx, "Fx" },
97 { TYPE_Ic, "Ic" },
98 { TYPE_In, "In" },
99 { TYPE_Lb, "Lb" },
100 { TYPE_Li, "Li" },
101 { TYPE_Lk, "Lk" },
102 { TYPE_Ms, "Ms" },
103 { TYPE_Mt, "Mt" },
104 { TYPE_Nd, "Nd" },
105 { TYPE_Nm, "Nm" },
106 { TYPE_Nx, "Nx" },
107 { TYPE_Ox, "Ox" },
108 { TYPE_Pa, "Pa" },
109 { TYPE_Rs, "Rs" },
110 { TYPE_Sh, "Sh" },
111 { TYPE_Ss, "Ss" },
112 { TYPE_St, "St" },
113 { TYPE_Sy, "Sy" },
114 { TYPE_Tn, "Tn" },
115 { TYPE_Va, "Va" },
116 { TYPE_Va, "Vt" },
117 { TYPE_Xr, "Xr" },
118 { UINT64_MAX, "any" },
119 { 0, NULL }
120 };
121
122 static DB *btree_open(void);
123 static int btree_read(const DBT *, const DBT *,
124 const struct mchars *,
125 uint64_t *, recno_t *, char **);
126 static int expreval(const struct expr *, int *);
127 static void exprexec(const struct expr *,
128 const char *, uint64_t, struct res *);
129 static int exprmark(const struct expr *,
130 const char *, uint64_t, int *);
131 static struct expr *exprexpr(int, char *[], int *, int *, size_t *);
132 static struct expr *exprterm(char *, int);
133 static DB *index_open(void);
134 static int index_read(const DBT *, const DBT *, int,
135 const struct mchars *, struct res *);
136 static void norm_string(const char *,
137 const struct mchars *, char **);
138 static size_t norm_utf8(unsigned int, char[7]);
139 static int single_search(struct rectree *, const struct opts *,
140 const struct expr *, size_t terms,
141 struct mchars *, int);
142
143 /*
144 * Open the keyword mandoc-db database.
145 */
146 static DB *
147 btree_open(void)
148 {
149 BTREEINFO info;
150 DB *db;
151
152 memset(&info, 0, sizeof(BTREEINFO));
153 info.lorder = 4321;
154 info.flags = R_DUP;
155
156 db = dbopen(MANDOC_DB, O_RDONLY, 0, DB_BTREE, &info);
157 if (NULL != db)
158 return(db);
159
160 return(NULL);
161 }
162
163 /*
164 * Read a keyword from the database and normalise it.
165 * Return 0 if the database is insane, else 1.
166 */
167 static int
168 btree_read(const DBT *k, const DBT *v, const struct mchars *mc,
169 uint64_t *mask, recno_t *rec, char **buf)
170 {
171 uint64_t vbuf[2];
172
173 /* Are our sizes sane? */
174 if (k->size < 2 || sizeof(vbuf) != v->size)
175 return(0);
176
177 /* Is our string nil-terminated? */
178 if ('\0' != ((const char *)k->data)[(int)k->size - 1])
179 return(0);
180
181 norm_string((const char *)k->data, mc, buf);
182 memcpy(vbuf, v->data, v->size);
183 *mask = betoh64(vbuf[0]);
184 *rec = betoh64(vbuf[1]);
185 return(1);
186 }
187
188 /*
189 * Take a Unicode codepoint and produce its UTF-8 encoding.
190 * This isn't the best way to do this, but it works.
191 * The magic numbers are from the UTF-8 packaging.
192 * They're not as scary as they seem: read the UTF-8 spec for details.
193 */
194 static size_t
195 norm_utf8(unsigned int cp, char out[7])
196 {
197 int rc;
198
199 rc = 0;
200
201 if (cp <= 0x0000007F) {
202 rc = 1;
203 out[0] = (char)cp;
204 } else if (cp <= 0x000007FF) {
205 rc = 2;
206 out[0] = (cp >> 6 & 31) | 192;
207 out[1] = (cp & 63) | 128;
208 } else if (cp <= 0x0000FFFF) {
209 rc = 3;
210 out[0] = (cp >> 12 & 15) | 224;
211 out[1] = (cp >> 6 & 63) | 128;
212 out[2] = (cp & 63) | 128;
213 } else if (cp <= 0x001FFFFF) {
214 rc = 4;
215 out[0] = (cp >> 18 & 7) | 240;
216 out[1] = (cp >> 12 & 63) | 128;
217 out[2] = (cp >> 6 & 63) | 128;
218 out[3] = (cp & 63) | 128;
219 } else if (cp <= 0x03FFFFFF) {
220 rc = 5;
221 out[0] = (cp >> 24 & 3) | 248;
222 out[1] = (cp >> 18 & 63) | 128;
223 out[2] = (cp >> 12 & 63) | 128;
224 out[3] = (cp >> 6 & 63) | 128;
225 out[4] = (cp & 63) | 128;
226 } else if (cp <= 0x7FFFFFFF) {
227 rc = 6;
228 out[0] = (cp >> 30 & 1) | 252;
229 out[1] = (cp >> 24 & 63) | 128;
230 out[2] = (cp >> 18 & 63) | 128;
231 out[3] = (cp >> 12 & 63) | 128;
232 out[4] = (cp >> 6 & 63) | 128;
233 out[5] = (cp & 63) | 128;
234 } else
235 return(0);
236
237 out[rc] = '\0';
238 return((size_t)rc);
239 }
240
241 /*
242 * Normalise strings from the index and database.
243 * These strings are escaped as defined by mandoc_char(7) along with
244 * other goop in mandoc.h (e.g., soft hyphens).
245 * This function normalises these into a nice UTF-8 string.
246 * Returns 0 if the database is fucked.
247 */
248 static void
249 norm_string(const char *val, const struct mchars *mc, char **buf)
250 {
251 size_t sz, bsz;
252 char utfbuf[7];
253 const char *seq, *cpp;
254 int len, u, pos;
255 enum mandoc_esc esc;
256 static const char res[] = { '\\', '\t',
257 ASCII_NBRSP, ASCII_HYPH, '\0' };
258
259 /* Pre-allocate by the length of the input */
260
261 bsz = strlen(val) + 1;
262 *buf = mandoc_realloc(*buf, bsz);
263 pos = 0;
264
265 while ('\0' != *val) {
266 /*
267 * Halt on the first escape sequence.
268 * This also halts on the end of string, in which case
269 * we just copy, fallthrough, and exit the loop.
270 */
271 if ((sz = strcspn(val, res)) > 0) {
272 memcpy(&(*buf)[pos], val, sz);
273 pos += (int)sz;
274 val += (int)sz;
275 }
276
277 if (ASCII_HYPH == *val) {
278 (*buf)[pos++] = '-';
279 val++;
280 continue;
281 } else if ('\t' == *val || ASCII_NBRSP == *val) {
282 (*buf)[pos++] = ' ';
283 val++;
284 continue;
285 } else if ('\\' != *val)
286 break;
287
288 /* Read past the slash. */
289
290 val++;
291 u = 0;
292
293 /*
294 * Parse the escape sequence and see if it's a
295 * predefined character or special character.
296 */
297
298 esc = mandoc_escape(&val, &seq, &len);
299 if (ESCAPE_ERROR == esc)
300 break;
301
302 /*
303 * XXX - this just does UTF-8, but we need to know
304 * beforehand whether we should do text substitution.
305 */
306
307 switch (esc) {
308 case (ESCAPE_SPECIAL):
309 if (0 != (u = mchars_spec2cp(mc, seq, len)))
310 break;
311 /* FALLTHROUGH */
312 default:
313 continue;
314 }
315
316 /*
317 * If we have a Unicode codepoint, try to convert that
318 * to a UTF-8 byte string.
319 */
320
321 cpp = utfbuf;
322 if (0 == (sz = norm_utf8(u, utfbuf)))
323 continue;
324
325 /* Copy the rendered glyph into the stream. */
326
327 sz = strlen(cpp);
328 bsz += sz;
329
330 *buf = mandoc_realloc(*buf, bsz);
331
332 memcpy(&(*buf)[pos], cpp, sz);
333 pos += (int)sz;
334 }
335
336 (*buf)[pos] = '\0';
337 }
338
339 /*
340 * Open the filename-index mandoc-db database.
341 * Returns NULL if opening failed.
342 */
343 static DB *
344 index_open(void)
345 {
346 DB *db;
347
348 db = dbopen(MANDOC_IDX, O_RDONLY, 0, DB_RECNO, NULL);
349 if (NULL != db)
350 return(db);
351
352 return(NULL);
353 }
354
355 /*
356 * Safely unpack from an index file record into the structure.
357 * Returns 1 if an entry was unpacked, 0 if the database is insane.
358 */
359 static int
360 index_read(const DBT *key, const DBT *val, int index,
361 const struct mchars *mc, struct res *rec)
362 {
363 size_t left;
364 char *np, *cp;
365 char type;
366
367 #define INDEX_BREAD(_dst) \
368 do { \
369 if (NULL == (np = memchr(cp, '\0', left))) \
370 return(0); \
371 norm_string(cp, mc, &(_dst)); \
372 left -= (np - cp) + 1; \
373 cp = np + 1; \
374 } while (/* CONSTCOND */ 0)
375
376 if (0 == (left = val->size))
377 return(0);
378
379 cp = val->data;
380 assert(sizeof(recno_t) == key->size);
381 memcpy(&rec->rec, key->data, key->size);
382 rec->volume = index;
383
384 if ('d' == (type = *cp++))
385 rec->type = RESTYPE_MDOC;
386 else if ('a' == type)
387 rec->type = RESTYPE_MAN;
388 else if ('c' == type)
389 rec->type = RESTYPE_CAT;
390 else
391 return(0);
392
393 left--;
394 INDEX_BREAD(rec->file);
395 INDEX_BREAD(rec->cat);
396 INDEX_BREAD(rec->title);
397 INDEX_BREAD(rec->arch);
398 INDEX_BREAD(rec->desc);
399 return(1);
400 }
401
402 /*
403 * Search mandocdb databases in paths for expression "expr".
404 * Filter out by "opts".
405 * Call "res" with the results, which may be zero.
406 * Return 0 if there was a database error, else return 1.
407 */
408 int
409 apropos_search(int pathsz, char **paths, const struct opts *opts,
410 const struct expr *expr, size_t terms, void *arg,
411 size_t *sz, struct res **resp,
412 void (*res)(struct res *, size_t, void *))
413 {
414 struct rectree tree;
415 struct mchars *mc;
416 int i, rc;
417
418 memset(&tree, 0, sizeof(struct rectree));
419
420 rc = 0;
421 mc = mchars_alloc();
422 *sz = 0;
423 *resp = NULL;
424
425 /*
426 * Main loop. Change into the directory containing manpage
427 * databases. Run our expession over each database in the set.
428 */
429
430 for (i = 0; i < pathsz; i++) {
431 assert('/' == paths[i][0]);
432 if (chdir(paths[i]))
433 continue;
434 if (single_search(&tree, opts, expr, terms, mc, i))
435 continue;
436
437 resfree(tree.node, tree.len);
438 mchars_free(mc);
439 return(0);
440 }
441
442 (*res)(tree.node, tree.len, arg);
443 *sz = tree.len;
444 *resp = tree.node;
445 mchars_free(mc);
446 return(1);
447 }
448
449 static int
450 single_search(struct rectree *tree, const struct opts *opts,
451 const struct expr *expr, size_t terms,
452 struct mchars *mc, int vol)
453 {
454 int root, leaf, ch;
455 DBT key, val;
456 DB *btree, *idx;
457 char *buf;
458 struct res *rs;
459 struct res r;
460 uint64_t mask;
461 recno_t rec;
462
463 root = -1;
464 leaf = -1;
465 btree = NULL;
466 idx = NULL;
467 buf = NULL;
468 rs = tree->node;
469
470 memset(&r, 0, sizeof(struct res));
471
472 if (NULL == (btree = btree_open()))
473 return(1);
474
475 if (NULL == (idx = index_open())) {
476 (*btree->close)(btree);
477 return(1);
478 }
479
480 while (0 == (ch = (*btree->seq)(btree, &key, &val, R_NEXT))) {
481 if ( ! btree_read(&key, &val, mc, &mask, &rec, &buf))
482 break;
483
484 /*
485 * See if this keyword record matches any of the
486 * expressions we have stored.
487 */
488 if ( ! exprmark(expr, buf, mask, NULL))
489 continue;
490
491 /*
492 * O(log n) scan for prior records. Since a record
493 * number is unbounded, this has decent performance over
494 * a complex hash function.
495 */
496
497 for (leaf = root; leaf >= 0; )
498 if (rec > rs[leaf].rec &&
499 rs[leaf].rhs >= 0)
500 leaf = rs[leaf].rhs;
501 else if (rec < rs[leaf].rec &&
502 rs[leaf].lhs >= 0)
503 leaf = rs[leaf].lhs;
504 else
505 break;
506
507 /*
508 * If we find a record, see if it has already evaluated
509 * to true. If it has, great, just keep going. If not,
510 * try to evaluate it now and continue anyway.
511 */
512
513 if (leaf >= 0 && rs[leaf].rec == rec) {
514 if (0 == rs[leaf].matched)
515 exprexec(expr, buf, mask, &rs[leaf]);
516 continue;
517 }
518
519 /*
520 * We have a new file to examine.
521 * Extract the manpage's metadata from the index
522 * database, then begin partial evaluation.
523 */
524
525 key.data = &rec;
526 key.size = sizeof(recno_t);
527
528 if (0 != (*idx->get)(idx, &key, &val, 0))
529 break;
530
531 r.lhs = r.rhs = -1;
532 if ( ! index_read(&key, &val, vol, mc, &r))
533 break;
534
535 /* XXX: this should be elsewhere, I guess? */
536
537 if (opts->cat && strcasecmp(opts->cat, r.cat))
538 continue;
539
540 if (opts->arch && *r.arch)
541 if (strcasecmp(opts->arch, r.arch))
542 continue;
543
544 tree->node = rs = mandoc_realloc
545 (rs, (tree->len + 1) * sizeof(struct res));
546
547 memcpy(&rs[tree->len], &r, sizeof(struct res));
548 memset(&r, 0, sizeof(struct res));
549 rs[tree->len].matches =
550 mandoc_calloc(terms, sizeof(int));
551
552 exprexec(expr, buf, mask, &rs[tree->len]);
553
554 /* Append to our tree. */
555
556 if (leaf >= 0) {
557 if (rec > rs[leaf].rec)
558 rs[leaf].rhs = tree->len;
559 else
560 rs[leaf].lhs = tree->len;
561 } else
562 root = tree->len;
563
564 tree->len++;
565 }
566
567 (*btree->close)(btree);
568 (*idx->close)(idx);
569
570 free(buf);
571 RESFREE(&r);
572 return(1 == ch);
573 }
574
575 void
576 resfree(struct res *rec, size_t sz)
577 {
578 size_t i;
579
580 for (i = 0; i < sz; i++)
581 RESFREE(&rec[i]);
582 free(rec);
583 }
584
585 /*
586 * Compile a list of straight-up terms.
587 * The arguments are re-written into ~[[:<:]]term[[:>:]], or "term"
588 * surrounded by word boundaries, then pumped through exprterm().
589 * Terms are case-insensitive.
590 * This emulates whatis(1) behaviour.
591 */
592 struct expr *
593 termcomp(int argc, char *argv[], size_t *tt)
594 {
595 char *buf;
596 int pos;
597 struct expr *e, *next;
598 size_t sz;
599
600 buf = NULL;
601 e = NULL;
602 *tt = 0;
603
604 for (pos = argc - 1; pos >= 0; pos--) {
605 sz = strlen(argv[pos]) + 18;
606 buf = mandoc_realloc(buf, sz);
607 strlcpy(buf, "Nm~[[:<:]]", sz);
608 strlcat(buf, argv[pos], sz);
609 strlcat(buf, "[[:>:]]", sz);
610 if (NULL == (next = exprterm(buf, 0))) {
611 free(buf);
612 exprfree(e);
613 return(NULL);
614 }
615 next->next = e;
616 e = next;
617 (*tt)++;
618 }
619
620 free(buf);
621 return(e);
622 }
623
624 /*
625 * Compile a sequence of logical expressions.
626 * See apropos.1 for a grammar of this sequence.
627 */
628 struct expr *
629 exprcomp(int argc, char *argv[], size_t *tt)
630 {
631 int pos, lvl;
632 struct expr *e;
633
634 pos = lvl = 0;
635 *tt = 0;
636
637 e = exprexpr(argc, argv, &pos, &lvl, tt);
638
639 if (0 == lvl && pos >= argc)
640 return(e);
641
642 exprfree(e);
643 return(NULL);
644 }
645
646 /*
647 * Compile an array of tokens into an expression.
648 * An informal expression grammar is defined in apropos(1).
649 * Return NULL if we fail doing so. All memory will be cleaned up.
650 * Return the root of the expression sequence if alright.
651 */
652 static struct expr *
653 exprexpr(int argc, char *argv[], int *pos, int *lvl, size_t *tt)
654 {
655 struct expr *e, *first, *next;
656 int log;
657
658 first = next = NULL;
659
660 for ( ; *pos < argc; (*pos)++) {
661 e = next;
662
663 /*
664 * Close out a subexpression.
665 */
666
667 if (NULL != e && 0 == strcmp(")", argv[*pos])) {
668 if (--(*lvl) < 0)
669 goto err;
670 break;
671 }
672
673 /*
674 * Small note: if we're just starting, don't let "-a"
675 * and "-o" be considered logical operators: they're
676 * just tokens unless pairwise joining, in which case we
677 * record their existence (or assume "OR").
678 */
679 log = 0;
680
681 if (NULL != e && 0 == strcmp("-a", argv[*pos]))
682 log = 1;
683 else if (NULL != e && 0 == strcmp("-o", argv[*pos]))
684 log = 2;
685
686 if (log > 0 && ++(*pos) >= argc)
687 goto err;
688
689 /*
690 * Now we parse the term part. This can begin with
691 * "-i", in which case the expression is case
692 * insensitive.
693 */
694
695 if (0 == strcmp("(", argv[*pos])) {
696 ++(*pos);
697 ++(*lvl);
698 next = mandoc_calloc(1, sizeof(struct expr));
699 next->subexpr = exprexpr(argc, argv, pos, lvl, tt);
700 if (NULL == next->subexpr) {
701 free(next);
702 next = NULL;
703 }
704 } else if (0 == strcmp("-i", argv[*pos])) {
705 if (++(*pos) >= argc)
706 goto err;
707 next = exprterm(argv[*pos], 0);
708 } else
709 next = exprterm(argv[*pos], 1);
710
711 if (NULL == next)
712 goto err;
713
714 next->and = log == 1;
715 next->index = (int)(*tt)++;
716
717 /* Append to our chain of expressions. */
718
719 if (NULL == first) {
720 assert(NULL == e);
721 first = next;
722 } else {
723 assert(NULL != e);
724 e->next = next;
725 }
726 }
727
728 return(first);
729 err:
730 exprfree(first);
731 return(NULL);
732 }
733
734 /*
735 * Parse a terminal expression with the grammar as defined in
736 * apropos(1).
737 * Return NULL if we fail the parse.
738 */
739 static struct expr *
740 exprterm(char *buf, int cs)
741 {
742 struct expr e;
743 struct expr *p;
744 char *key;
745 int i;
746
747 memset(&e, 0, sizeof(struct expr));
748
749 /* Choose regex or substring match. */
750
751 if (NULL == (e.v = strpbrk(buf, "=~"))) {
752 e.regex = 0;
753 e.v = buf;
754 } else {
755 e.regex = '~' == *e.v;
756 *e.v++ = '\0';
757 }
758
759 /* Determine the record types to search for. */
760
761 e.mask = 0;
762 if (buf < e.v) {
763 while (NULL != (key = strsep(&buf, ","))) {
764 i = 0;
765 while (types[i].mask &&
766 strcmp(types[i].name, key))
767 i++;
768 e.mask |= types[i].mask;
769 }
770 }
771 if (0 == e.mask)
772 e.mask = TYPE_Nm | TYPE_Nd;
773
774 if (e.regex) {
775 i = REG_EXTENDED | REG_NOSUB | (cs ? 0 : REG_ICASE);
776 if (regcomp(&e.re, e.v, i))
777 return(NULL);
778 }
779
780 e.v = mandoc_strdup(e.v);
781
782 p = mandoc_calloc(1, sizeof(struct expr));
783 memcpy(p, &e, sizeof(struct expr));
784 return(p);
785 }
786
787 void
788 exprfree(struct expr *p)
789 {
790 struct expr *pp;
791
792 while (NULL != p) {
793 if (p->subexpr)
794 exprfree(p->subexpr);
795 if (p->regex)
796 regfree(&p->re);
797 free(p->v);
798 pp = p->next;
799 free(p);
800 p = pp;
801 }
802 }
803
804 static int
805 exprmark(const struct expr *p, const char *cp,
806 uint64_t mask, int *ms)
807 {
808
809 for ( ; p; p = p->next) {
810 if (p->subexpr) {
811 if (exprmark(p->subexpr, cp, mask, ms))
812 return(1);
813 continue;
814 } else if ( ! (mask & p->mask))
815 continue;
816
817 if (p->regex) {
818 if (regexec(&p->re, cp, 0, NULL, 0))
819 continue;
820 } else if (NULL == strcasestr(cp, p->v))
821 continue;
822
823 if (NULL == ms)
824 return(1);
825 else
826 ms[p->index] = 1;
827 }
828
829 return(0);
830 }
831
832 static int
833 expreval(const struct expr *p, int *ms)
834 {
835 int match;
836
837 /*
838 * AND has precedence over OR. Analysis is left-right, though
839 * it doesn't matter because there are no side-effects.
840 * Thus, step through pairwise ANDs and accumulate their Boolean
841 * evaluation. If we encounter a single true AND collection or
842 * standalone term, the whole expression is true (by definition
843 * of OR).
844 */
845
846 for (match = 0; p && ! match; p = p->next) {
847 /* Evaluate a subexpression, if applicable. */
848 if (p->subexpr && ! ms[p->index])
849 ms[p->index] = expreval(p->subexpr, ms);
850
851 match = ms[p->index];
852 for ( ; p->next && p->next->and; p = p->next) {
853 /* Evaluate a subexpression, if applicable. */
854 if (p->next->subexpr && ! ms[p->next->index])
855 ms[p->next->index] =
856 expreval(p->next->subexpr, ms);
857 match = match && ms[p->next->index];
858 }
859 }
860
861 return(match);
862 }
863
864 /*
865 * First, update the array of terms for which this expression evaluates
866 * to true.
867 * Second, logically evaluate all terms over the updated array of truth
868 * values.
869 * If this evaluates to true, mark the expression as satisfied.
870 */
871 static void
872 exprexec(const struct expr *e, const char *cp,
873 uint64_t mask, struct res *r)
874 {
875
876 assert(0 == r->matched);
877 exprmark(e, cp, mask, r->matches);
878 r->matched = expreval(e, r->matches);
879 }