]> git.cameronkatri.com Git - mandoc.git/blob - apropos_db.c
In apropos_db.c, move all btree reading (and safety checks) into the
[mandoc.git] / apropos_db.c
1 /* $Id: apropos_db.c,v 1.17 2011/12/01 23:46:26 kristaps Exp $ */
2 /*
3 * Copyright (c) 2011 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 #include <assert.h>
19 #include <fcntl.h>
20 #include <regex.h>
21 #include <stdarg.h>
22 #include <stdint.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26
27 #include <arpa/inet.h>
28
29 #ifdef __linux__
30 # include <db_185.h>
31 #else
32 # include <db.h>
33 #endif
34
35 #include "mandocdb.h"
36 #include "apropos_db.h"
37 #include "mandoc.h"
38
39 struct rec {
40 struct res res; /* resulting record info */
41 /*
42 * Maintain a binary tree for checking the uniqueness of `rec'
43 * when adding elements to the results array.
44 * Since the results array is dynamic, use offset in the array
45 * instead of a pointer to the structure.
46 */
47 int lhs;
48 int rhs;
49 int matched; /* expression is true */
50 int *matches; /* partial truth evaluations */
51 };
52
53 struct expr {
54 int regex; /* is regex? */
55 int index; /* index in match array */
56 uint64_t mask; /* type-mask */
57 int and; /* is rhs of logical AND? */
58 char *v; /* search value */
59 regex_t re; /* compiled re, if regex */
60 struct expr *next; /* next in sequence */
61 struct expr *subexpr;
62 };
63
64 struct type {
65 uint64_t mask;
66 const char *name;
67 };
68
69 struct rectree {
70 struct rec *node; /* record array for dir tree */
71 int len; /* length of record array */
72 };
73
74 static const struct type types[] = {
75 { TYPE_An, "An" },
76 { TYPE_Ar, "Ar" },
77 { TYPE_At, "At" },
78 { TYPE_Bsx, "Bsx" },
79 { TYPE_Bx, "Bx" },
80 { TYPE_Cd, "Cd" },
81 { TYPE_Cm, "Cm" },
82 { TYPE_Dv, "Dv" },
83 { TYPE_Dx, "Dx" },
84 { TYPE_Em, "Em" },
85 { TYPE_Er, "Er" },
86 { TYPE_Ev, "Ev" },
87 { TYPE_Fa, "Fa" },
88 { TYPE_Fl, "Fl" },
89 { TYPE_Fn, "Fn" },
90 { TYPE_Fn, "Fo" },
91 { TYPE_Ft, "Ft" },
92 { TYPE_Fx, "Fx" },
93 { TYPE_Ic, "Ic" },
94 { TYPE_In, "In" },
95 { TYPE_Lb, "Lb" },
96 { TYPE_Li, "Li" },
97 { TYPE_Lk, "Lk" },
98 { TYPE_Ms, "Ms" },
99 { TYPE_Mt, "Mt" },
100 { TYPE_Nd, "Nd" },
101 { TYPE_Nm, "Nm" },
102 { TYPE_Nx, "Nx" },
103 { TYPE_Ox, "Ox" },
104 { TYPE_Pa, "Pa" },
105 { TYPE_Rs, "Rs" },
106 { TYPE_Sh, "Sh" },
107 { TYPE_Ss, "Ss" },
108 { TYPE_St, "St" },
109 { TYPE_Sy, "Sy" },
110 { TYPE_Tn, "Tn" },
111 { TYPE_Va, "Va" },
112 { TYPE_Va, "Vt" },
113 { TYPE_Xr, "Xr" },
114 { INT_MAX, "any" },
115 { 0, NULL }
116 };
117
118 static DB *btree_open(void);
119 static int btree_read(const DBT *, const DBT *,
120 const struct mchars *,
121 struct db_val *, char **);
122 static int expreval(const struct expr *, int *);
123 static void exprexec(const struct expr *,
124 const char *, uint64_t, struct rec *);
125 static int exprmark(const struct expr *,
126 const char *, uint64_t, int *);
127 static struct expr *exprexpr(int, char *[], int *, int *, size_t *);
128 static struct expr *exprterm(char *, int);
129 static DB *index_open(void);
130 static int index_read(const DBT *, const DBT *, int,
131 const struct mchars *, struct rec *);
132 static void norm_string(const char *,
133 const struct mchars *, char **);
134 static size_t norm_utf8(unsigned int, char[7]);
135 static void recfree(struct rec *);
136 static int single_search(struct rectree *, const struct opts *,
137 const struct expr *, size_t terms,
138 struct mchars *, int);
139
140 /*
141 * Open the keyword mandoc-db database.
142 */
143 static DB *
144 btree_open(void)
145 {
146 BTREEINFO info;
147 DB *db;
148
149 memset(&info, 0, sizeof(BTREEINFO));
150 info.flags = R_DUP;
151
152 db = dbopen(MANDOC_DB, O_RDONLY, 0, DB_BTREE, &info);
153 if (NULL != db)
154 return(db);
155
156 return(NULL);
157 }
158
159 /*
160 * Read a keyword from the database and normalise it.
161 * Return 0 if the database is insane, else 1.
162 */
163 static int
164 btree_read(const DBT *k, const DBT *v,
165 const struct mchars *mc,
166 struct db_val *dbv, char **buf)
167 {
168 const struct db_val *vp;
169
170 /* Are our sizes sane? */
171 if (k->size < 2 || sizeof(struct db_val) != v->size)
172 return(0);
173
174 /* Is our string nil-terminated? */
175 if ('\0' != ((const char *)k->data)[(int)k->size - 1])
176 return(0);
177
178 vp = v->data;
179 norm_string((const char *)k->data, mc, buf);
180 dbv->rec = ntohl(vp->rec);
181 dbv->mask = vp->mask;
182 return(1);
183 }
184
185 /*
186 * Take a Unicode codepoint and produce its UTF-8 encoding.
187 * This isn't the best way to do this, but it works.
188 * The magic numbers are from the UTF-8 packaging.
189 * They're not as scary as they seem: read the UTF-8 spec for details.
190 */
191 static size_t
192 norm_utf8(unsigned int cp, char out[7])
193 {
194 size_t rc;
195
196 rc = 0;
197
198 if (cp <= 0x0000007F) {
199 rc = 1;
200 out[0] = (char)cp;
201 } else if (cp <= 0x000007FF) {
202 rc = 2;
203 out[0] = (cp >> 6 & 31) | 192;
204 out[1] = (cp & 63) | 128;
205 } else if (cp <= 0x0000FFFF) {
206 rc = 3;
207 out[0] = (cp >> 12 & 15) | 224;
208 out[1] = (cp >> 6 & 63) | 128;
209 out[2] = (cp & 63) | 128;
210 } else if (cp <= 0x001FFFFF) {
211 rc = 4;
212 out[0] = (cp >> 18 & 7) | 240;
213 out[1] = (cp >> 12 & 63) | 128;
214 out[2] = (cp >> 6 & 63) | 128;
215 out[3] = (cp & 63) | 128;
216 } else if (cp <= 0x03FFFFFF) {
217 rc = 5;
218 out[0] = (cp >> 24 & 3) | 248;
219 out[1] = (cp >> 18 & 63) | 128;
220 out[2] = (cp >> 12 & 63) | 128;
221 out[3] = (cp >> 6 & 63) | 128;
222 out[4] = (cp & 63) | 128;
223 } else if (cp <= 0x7FFFFFFF) {
224 rc = 6;
225 out[0] = (cp >> 30 & 1) | 252;
226 out[1] = (cp >> 24 & 63) | 128;
227 out[2] = (cp >> 18 & 63) | 128;
228 out[3] = (cp >> 12 & 63) | 128;
229 out[4] = (cp >> 6 & 63) | 128;
230 out[5] = (cp & 63) | 128;
231 } else
232 return(0);
233
234 out[rc] = '\0';
235 return(rc);
236 }
237
238 /*
239 * Normalise strings from the index and database.
240 * These strings are escaped as defined by mandoc_char(7) along with
241 * other goop in mandoc.h (e.g., soft hyphens).
242 * This function normalises these into a nice UTF-8 string.
243 * Returns 0 if the database is fucked.
244 */
245 static void
246 norm_string(const char *val, const struct mchars *mc, char **buf)
247 {
248 size_t sz, bsz;
249 char utfbuf[7];
250 const char *seq, *cpp;
251 int len, u, pos;
252 enum mandoc_esc esc;
253 static const char res[] = { '\\', '\t',
254 ASCII_NBRSP, ASCII_HYPH, '\0' };
255
256 /* Pre-allocate by the length of the input */
257
258 bsz = strlen(val) + 1;
259 *buf = mandoc_realloc(*buf, bsz);
260 pos = 0;
261
262 while ('\0' != *val) {
263 /*
264 * Halt on the first escape sequence.
265 * This also halts on the end of string, in which case
266 * we just copy, fallthrough, and exit the loop.
267 */
268 if ((sz = strcspn(val, res)) > 0) {
269 memcpy(&(*buf)[pos], val, sz);
270 pos += (int)sz;
271 val += (int)sz;
272 }
273
274 if (ASCII_HYPH == *val) {
275 (*buf)[pos++] = '-';
276 val++;
277 continue;
278 } else if ('\t' == *val || ASCII_NBRSP == *val) {
279 (*buf)[pos++] = ' ';
280 val++;
281 continue;
282 } else if ('\\' != *val)
283 break;
284
285 /* Read past the slash. */
286
287 val++;
288 u = 0;
289
290 /*
291 * Parse the escape sequence and see if it's a
292 * predefined character or special character.
293 */
294
295 esc = mandoc_escape(&val, &seq, &len);
296 if (ESCAPE_ERROR == esc)
297 break;
298
299 /*
300 * XXX - this just does UTF-8, but we need to know
301 * beforehand whether we should do text substitution.
302 */
303
304 switch (esc) {
305 case (ESCAPE_SPECIAL):
306 if (0 != (u = mchars_spec2cp(mc, seq, len)))
307 break;
308 /* FALLTHROUGH */
309 default:
310 continue;
311 }
312
313 /*
314 * If we have a Unicode codepoint, try to convert that
315 * to a UTF-8 byte string.
316 */
317
318 cpp = utfbuf;
319 if (0 == (sz = norm_utf8(u, utfbuf)))
320 continue;
321
322 /* Copy the rendered glyph into the stream. */
323
324 sz = strlen(cpp);
325 bsz += sz;
326
327 *buf = mandoc_realloc(*buf, bsz);
328
329 memcpy(&(*buf)[pos], cpp, sz);
330 pos += (int)sz;
331 }
332
333 (*buf)[pos] = '\0';
334 }
335
336 /*
337 * Open the filename-index mandoc-db database.
338 * Returns NULL if opening failed.
339 */
340 static DB *
341 index_open(void)
342 {
343 DB *db;
344
345 db = dbopen(MANDOC_IDX, O_RDONLY, 0, DB_RECNO, NULL);
346 if (NULL != db)
347 return(db);
348
349 return(NULL);
350 }
351
352 /*
353 * Safely unpack from an index file record into the structure.
354 * Returns 1 if an entry was unpacked, 0 if the database is insane.
355 */
356 static int
357 index_read(const DBT *key, const DBT *val, int index,
358 const struct mchars *mc, struct rec *rec)
359 {
360 size_t left;
361 char *np, *cp;
362
363 #define INDEX_BREAD(_dst) \
364 do { \
365 if (NULL == (np = memchr(cp, '\0', left))) \
366 return(0); \
367 norm_string(cp, mc, &(_dst)); \
368 left -= (np - cp) + 1; \
369 cp = np + 1; \
370 } while (/* CONSTCOND */ 0)
371
372 left = val->size;
373 cp = (char *)val->data;
374
375 rec->res.rec = *(recno_t *)key->data;
376 rec->res.volume = index;
377
378 INDEX_BREAD(rec->res.type);
379 INDEX_BREAD(rec->res.file);
380 INDEX_BREAD(rec->res.cat);
381 INDEX_BREAD(rec->res.title);
382 INDEX_BREAD(rec->res.arch);
383 INDEX_BREAD(rec->res.desc);
384 return(1);
385 }
386
387 /*
388 * Search mandocdb databases in paths for expression "expr".
389 * Filter out by "opts".
390 * Call "res" with the results, which may be zero.
391 * Return 0 if there was a database error, else return 1.
392 */
393 int
394 apropos_search(int pathsz, char **paths, const struct opts *opts,
395 const struct expr *expr, size_t terms, void *arg,
396 void (*res)(struct res *, size_t, void *))
397 {
398 struct rectree tree;
399 struct mchars *mc;
400 struct res *ress;
401 int i, mlen, rc;
402
403 memset(&tree, 0, sizeof(struct rectree));
404
405 rc = 0;
406 mc = mchars_alloc();
407
408 /*
409 * Main loop. Change into the directory containing manpage
410 * databases. Run our expession over each database in the set.
411 */
412
413 for (i = 0; i < pathsz; i++) {
414 if (chdir(paths[i]))
415 continue;
416 if ( ! single_search(&tree, opts, expr, terms, mc, i))
417 goto out;
418 }
419
420 /*
421 * Count matching files, transfer to a "clean" array, then feed
422 * them to the output handler.
423 */
424
425 for (mlen = i = 0; i < tree.len; i++)
426 if (tree.node[i].matched)
427 mlen++;
428
429 ress = mandoc_malloc(mlen * sizeof(struct res));
430
431 for (mlen = i = 0; i < tree.len; i++)
432 if (tree.node[i].matched)
433 memcpy(&ress[mlen++], &tree.node[i].res,
434 sizeof(struct res));
435
436 (*res)(ress, mlen, arg);
437 free(ress);
438
439 rc = 1;
440 out:
441 for (i = 0; i < tree.len; i++)
442 recfree(&tree.node[i]);
443
444 free(tree.node);
445 mchars_free(mc);
446 return(rc);
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 rec *rs;
459 struct rec r;
460 struct db_val vb;
461
462 root = -1;
463 leaf = -1;
464 btree = NULL;
465 idx = NULL;
466 buf = NULL;
467 rs = tree->node;
468
469 memset(&r, 0, sizeof(struct rec));
470
471 if (NULL == (btree = btree_open()))
472 return(1);
473
474 if (NULL == (idx = index_open())) {
475 (*btree->close)(btree);
476 return(1);
477 }
478
479 while (0 == (ch = (*btree->seq)(btree, &key, &val, R_NEXT))) {
480 if ( ! btree_read(&key, &val, mc, &vb, &buf))
481 break;
482
483 /*
484 * See if this keyword record matches any of the
485 * expressions we have stored.
486 */
487 if ( ! exprmark(expr, buf, vb.mask, NULL))
488 continue;
489
490 /*
491 * O(log n) scan for prior records. Since a record
492 * number is unbounded, this has decent performance over
493 * a complex hash function.
494 */
495
496 for (leaf = root; leaf >= 0; )
497 if (vb.rec > rs[leaf].res.rec &&
498 rs[leaf].rhs >= 0)
499 leaf = rs[leaf].rhs;
500 else if (vb.rec < rs[leaf].res.rec &&
501 rs[leaf].lhs >= 0)
502 leaf = rs[leaf].lhs;
503 else
504 break;
505
506 /*
507 * If we find a record, see if it has already evaluated
508 * to true. If it has, great, just keep going. If not,
509 * try to evaluate it now and continue anyway.
510 */
511
512 if (leaf >= 0 && rs[leaf].res.rec == vb.rec) {
513 if (0 == rs[leaf].matched)
514 exprexec(expr, buf, vb.mask, &rs[leaf]);
515 continue;
516 }
517
518 /*
519 * We have a new file to examine.
520 * Extract the manpage's metadata from the index
521 * database, then begin partial evaluation.
522 */
523
524 key.data = &vb.rec;
525 key.size = sizeof(recno_t);
526
527 if (0 != (*idx->get)(idx, &key, &val, 0))
528 break;
529
530 r.lhs = r.rhs = -1;
531 if ( ! index_read(&key, &val, vol, mc, &r))
532 break;
533
534 /* XXX: this should be elsewhere, I guess? */
535
536 if (opts->cat && strcasecmp(opts->cat, r.res.cat))
537 continue;
538 if (opts->arch && strcasecmp(opts->arch, r.res.arch))
539 continue;
540
541 tree->node = rs = mandoc_realloc
542 (rs, (tree->len + 1) * sizeof(struct rec));
543
544 memcpy(&rs[tree->len], &r, sizeof(struct rec));
545 rs[tree->len].matches =
546 mandoc_calloc(terms, sizeof(int));
547
548 exprexec(expr, buf, vb.mask, &rs[tree->len]);
549
550 /* Append to our tree. */
551
552 if (leaf >= 0) {
553 if (vb.rec > rs[leaf].res.rec)
554 rs[leaf].rhs = tree->len;
555 else
556 rs[leaf].lhs = tree->len;
557 } else
558 root = tree->len;
559
560 memset(&r, 0, sizeof(struct rec));
561 tree->len++;
562 }
563
564 (*btree->close)(btree);
565 (*idx->close)(idx);
566
567 free(buf);
568 return(1 == ch);
569 }
570
571 static void
572 recfree(struct rec *rec)
573 {
574
575 free(rec->res.type);
576 free(rec->res.file);
577 free(rec->res.cat);
578 free(rec->res.title);
579 free(rec->res.arch);
580 free(rec->res.desc);
581
582 free(rec->matches);
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 rec *r)
874 {
875
876 assert(0 == r->matched);
877 exprmark(e, cp, mask, r->matches);
878 r->matched = expreval(e, r->matches);
879 }