Blob


1 /*
2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/socket.h>
19 #include <sys/stat.h>
20 #include <sys/wait.h>
22 #include <assert.h>
23 #include <endian.h>
24 #include <err.h>
25 #include <errno.h>
26 #include <event.h>
27 #include <fcntl.h>
28 #include <inttypes.h>
29 #include <poll.h>
30 #include <pwd.h>
31 #include <regex.h>
32 #include <signal.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <syslog.h>
37 #include <unistd.h>
39 #include "client.h"
40 #include "kami.h"
41 #include "kamid.h"
42 #include "log.h"
43 #include "script.h"
44 #include "utils.h"
46 #define DEBUG 0
48 #ifndef INFTIM
49 #define INFTIM -1
50 #endif
52 static const char *argv0;
54 static uint8_t *lastmsg;
56 static struct imsgbuf ibuf;
57 static int ibuf_inuse;
58 static int child_out = -1;
60 static struct procs procs = TAILQ_HEAD_INITIALIZER(procs);
61 static struct tests tests = TAILQ_HEAD_INITIALIZER(tests);
63 static int ntests;
65 static struct opstacks blocks = TAILQ_HEAD_INITIALIZER(blocks);
66 static struct opstacks args = TAILQ_HEAD_INITIALIZER(args);
68 #define STACK_HEIGHT 64
69 static struct value vstack[STACK_HEIGHT];
70 static int stackh;
72 static struct envs envs = TAILQ_HEAD_INITIALIZER(envs);
74 static struct value v_false = {.type = V_NUM, .v = {.num = 0}};
75 static struct value v_true = {.type = V_NUM, .v = {.num = 1}};
77 static uint8_t lasttag;
79 static int debug;
80 static int syntaxcheck;
82 static const char *filler;
84 static inline void
85 before_printing(void)
86 {
87 if (filler != NULL) {
88 printf("%s", filler);
89 filler = NULL;
90 }
91 }
93 static inline void
94 check_for_output(void)
95 {
96 static char buf[BUFSIZ];
97 struct pollfd pfd;
98 ssize_t r;
100 pfd.fd = child_out;
101 pfd.events = POLLIN;
102 if (poll(&pfd, 1, 0) == -1)
103 fatal("poll");
105 if (!(pfd.revents & POLLIN))
106 return;
108 for (;;) {
109 if ((r = read(child_out, buf, sizeof(buf))) == -1) {
110 if (errno == EAGAIN)
111 break;
112 fatal("read");
114 if (r == 0)
115 break;
116 before_printing();
117 fwrite(buf, 1, r, stdout);
121 static inline void
122 peekn(int depth, struct value *v)
124 if (depth > stackh)
125 errx(1, "can't peek the stack at %d: underflow",
126 depth);
127 memcpy(v, &vstack[stackh - depth], sizeof(*v));
129 #if DEBUG
130 printf("peeking(%d) ", depth); pp_val(v); printf("\n");
131 #endif
134 static inline void
135 popv(struct value *v)
137 if (stackh == 0)
138 errx(1, "can't pop the stack: underflow");
139 memcpy(v, &vstack[--stackh], sizeof(*v));
141 #if DEBUG
142 printf("popping "); pp_val(v); printf("\n");
143 #endif
146 static inline void
147 popvn(int n)
149 struct value v;
151 while (n-- > 0)
152 popv(&v);
155 static inline void
156 pushv(struct value *v)
158 if (stackh == STACK_HEIGHT)
159 errx(1, "can't push the stack: overflow");
161 #if DEBUG
162 printf("pushing "); pp_val(v); printf("\n");
163 #endif
165 memcpy(&vstack[stackh++], v, sizeof(*v));
168 static inline void
169 pushbool(int n)
171 pushv(n ? &v_true : &v_false);
174 static inline void
175 pushnum(int64_t n)
177 struct value v;
179 v.type = V_NUM;
180 v.v.num = n;
181 pushv(&v);
184 static inline struct opstack *
185 pushstack(struct opstacks *stack)
187 struct opstack *ops;
189 ops = xcalloc(1, sizeof(*ops));
190 TAILQ_INSERT_HEAD(stack, ops, entry);
191 return ops;
194 static inline struct opstack *
195 peek(struct opstacks *stack)
197 if (TAILQ_EMPTY(stack))
198 errx(1, "%s: args underflow", __func__);
200 return TAILQ_FIRST(stack);
203 static inline struct op *
204 finalize(struct opstacks *stack, int *argc)
206 struct opstack *ops;
207 struct op *op;
209 if (TAILQ_EMPTY(stack))
210 errx(1, "%s: args underflow", __func__);
212 ops = peek(stack);
213 TAILQ_REMOVE(&args, ops, entry);
214 op = ops->base.next;
216 if (argc != NULL)
217 *argc = ops->counter;
219 free(ops);
220 return op;
223 static inline void
224 push(struct opstacks *stack, struct op *op)
226 struct opstack *ops;
228 ops = peek(stack);
229 if (ops->last == NULL) {
230 ops->base.next = op;
231 ops->last = op;
232 } else {
233 ops->last->next = op;
234 ops->last = op;
237 ops->counter++;
240 static inline void
241 pushenv(void)
243 struct env *e;
245 e = xcalloc(1, sizeof(*e));
246 TAILQ_INSERT_HEAD(&envs, e, entry);
249 static inline struct env *
250 currentenv(void)
252 assert(!TAILQ_EMPTY(&envs));
253 return TAILQ_FIRST(&envs);
256 static void
257 popenv(void)
259 struct env *e;
260 struct binding *b, *tb;
262 e = currentenv();
263 TAILQ_REMOVE(&envs, e, entry);
265 TAILQ_FOREACH_SAFE(b, &e->bindings, entry, tb)
266 free(b);
268 free(e);
271 static inline int
272 setvar(char *sym, struct op *op)
274 struct binding *b;
275 struct env *e;
276 int ret, height;
278 height = stackh;
279 if ((ret = eval(op)) != EVAL_OK)
280 return ret;
282 if (stackh != height + 1) {
283 before_printing();
284 printf("trying to assign to `%s' a void value: ", sym);
285 pp_op(op);
286 printf("\n");
287 return EVAL_ERR;
290 b = xcalloc(1, sizeof(*b));
291 b->name = sym;
292 popv(&b->val);
294 e = TAILQ_FIRST(&envs);
295 TAILQ_INSERT_HEAD(&e->bindings, b, entry);
297 return EVAL_OK;
300 static inline void
301 setvar_raw(char *sym, struct op *op)
303 struct binding *b;
304 struct env *e;
306 b = xcalloc(1, sizeof(*b));
307 b->name = sym;
308 b->raw = op;
310 e = TAILQ_FIRST(&envs);
311 TAILQ_INSERT_HEAD(&e->bindings, b, entry);
314 static inline int
315 getvar(const char *sym, struct value *v)
317 struct env *e;
318 struct binding *b;
320 TAILQ_FOREACH(e, &envs, entry) {
321 TAILQ_FOREACH(b, &e->bindings, entry) {
322 if (!strcmp(sym, b->name)) {
323 memcpy(v, &b->val, sizeof(*v));
324 return EVAL_OK;
329 before_printing();
330 fprintf(stderr, "unbound variable %s\n", sym);
331 return EVAL_ERR;
334 static inline int
335 getvar_raw(const char *sym, struct op **raw)
337 struct env *e;
338 struct binding *b;
340 TAILQ_FOREACH(e, &envs, entry) {
341 TAILQ_FOREACH(b, &e->bindings, entry) {
342 if (!strcmp(sym, b->name)) {
343 *raw = b->raw;
344 return EVAL_OK;
349 return EVAL_ERR;
352 int
353 global_set(char *sym, struct op *op)
355 struct binding *b;
356 struct env *e;
358 /* TODO: check for duplicates */
360 if (op->type != OP_LITERAL &&
361 (op->type == OP_CAST && op->v.cast.expr->type != OP_LITERAL))
362 return 0;
364 b = xcalloc(1, sizeof(*b));
365 b->name = sym;
367 /* it's only a cast on a literal! */
368 if (op->type == OP_CAST) {
369 if (eval(op) != EVAL_OK) {
370 free(b);
371 return 0;
373 popv(&b->val);
374 } else
375 memcpy(&b->val, &op->v.literal, sizeof(b->val));
377 e = TAILQ_LAST(&envs, envs);
378 TAILQ_INSERT_HEAD(&e->bindings, b, entry);
380 return 1;
383 struct op *
384 newop(int type)
386 struct op *op;
388 op = xcalloc(1, sizeof(*op));
389 op->type = type;
391 return op;
394 void
395 free_op_rec(struct op *op)
397 struct op *n;
399 while (op != NULL) {
400 n = op->next;
401 free_op(op);
402 op = n;
406 void
407 free_op(struct op *op)
409 if (op == NULL)
410 return;
412 switch (op->type) {
413 case OP_REST:
414 case OP_LITERAL:
415 case OP_VARGS:
416 break;
417 case OP_ASSIGN:
418 free(op->v.assign.name);
419 free_op_rec(op->v.assign.expr);
420 break;
421 case OP_ASSERT:
422 free_op_rec(op->v.assert);
423 break;
424 case OP_FUNCALL:
425 free_op_rec(op->v.funcall.argv);
426 break;
427 case OP_VAR:
428 free(op->v.var);
429 break;
430 case OP_CAST:
431 free_op_rec(op->v.cast.expr);
432 break;
433 case OP_CMP_EQ:
434 case OP_CMP_LEQ:
435 free_op_rec(op->v.bin_cmp.a);
436 free_op_rec(op->v.bin_cmp.b);
437 break;
438 case OP_FACCESS:
439 free_op_rec(op->v.faccess.expr);
440 free(op->v.faccess.field);
441 break;
442 case OP_SFAIL:
443 free(op->v.sfail.msg);
444 free_op_rec(op->v.sfail.expr);
445 break;
446 default:
447 /* unreachable */
448 abort();
451 free(op);
454 struct op *
455 op_rest(void)
457 return newop(OP_REST);
460 struct op *
461 op_assign(char *sym, struct op *expr)
463 struct op *op;
465 op = newop(OP_ASSIGN);
466 op->v.assign.name = sym;
467 op->v.assign.expr = expr;
469 return op;
472 struct op *
473 op_assert(struct op *expr)
475 struct op *op;
477 op = newop(OP_ASSERT);
478 op->v.assert = expr;
480 return op;
483 struct op *
484 op_var(char *sym)
486 struct op *op;
488 op = newop(OP_VAR);
489 op->v.var = sym;
491 return op;
494 struct op *
495 op_lit_str(char *str)
497 struct op *op;
499 op = newop(OP_LITERAL);
500 op->v.literal.type = V_STR;
501 op->v.literal.v.str = str;
503 return op;
506 struct op *
507 op_lit_num(uint64_t n)
509 struct op *op;
511 op = newop(OP_LITERAL);
512 op->v.literal.type = V_NUM;
513 op->v.literal.v.num = n;
515 return op;
518 struct op *
519 op_cmp_eq(struct op *a, struct op *b)
521 struct op *op;
523 op = newop(OP_CMP_EQ);
524 op->v.bin_cmp.a = a;
525 op->v.bin_cmp.b = b;
527 return op;
530 struct op *
531 op_cmp_leq(struct op *a, struct op *b)
533 struct op *op;
535 op = newop(OP_CMP_LEQ);
536 op->v.bin_cmp.a = a;
537 op->v.bin_cmp.b = b;
539 return op;
542 struct op *
543 op_cast(struct op *expr, int totype)
545 struct op *op;
547 op = newop(OP_CAST);
548 op->v.cast.expr = expr;
549 op->v.cast.totype = totype;
551 return op;
554 struct op *
555 op_faccess(struct op *expr, char *field)
557 struct op *op;
559 op = newop(OP_FACCESS);
560 op->v.faccess.expr = expr;
561 op->v.faccess.field = field;
563 return op;
566 struct op *
567 op_sfail(struct op *expr, char *msg)
569 struct op *op;
571 op = newop(OP_SFAIL);
572 op->v.sfail.expr = expr;
573 op->v.sfail.msg = msg;
575 return op;
578 struct op *
579 op_vargs(void)
581 struct op *op;
583 op = newop(OP_VARGS);
585 return op;
588 void
589 ppf_val(FILE *f, struct value *val)
591 size_t i;
593 switch (val->type) {
594 case V_SYM:
595 fprintf(f, "%s", val->v.str);
596 break;
597 case V_STR:
598 fprintf(f, "\"%s\"", val->v.str);
599 break;
600 case V_NUM:
601 fprintf(f, "%"PRIi64, val->v.num);
602 break;
603 case V_U8:
604 fprintf(f, "%"PRIu8, val->v.u8);
605 break;
606 case V_U16:
607 fprintf(f, "%"PRIu16, val->v.u16);
608 break;
609 case V_U32:
610 fprintf(f, "%"PRIu32, val->v.u32);
611 break;
612 case V_MSG:
613 fprintf(f, "(");
614 for (i = 0; i < val->v.msg.len; ++i)
615 fprintf(f, "%x%s", val->v.msg.msg[i],
616 i == val->v.msg.len-1 ? "" : " ");
617 fprintf(f, ")");
618 break;
619 case V_QIDVEC:
620 fprintf(f, "qids[n=%zu]", val->v.qidvec.len);
621 break;
622 default:
623 fprintf(f, "<unknown value>");
624 break;
628 void
629 pp_val(struct value *val)
631 ppf_val(stdout, val);
634 const char *
635 val_type(struct value *v)
637 switch (v->type) {
638 case V_SYM: return "symbol";
639 case V_STR: return "string";
640 case V_NUM: return "number";
641 case V_MSG: return "message";
642 case V_QID: return "qid";
643 case V_U8: return "u8";
644 case V_U16: return "u16";
645 case V_U32: return "u32";
646 default: return "unknown";
650 int
651 val_trueish(struct value *a)
653 if (val_isnum(a))
654 return val_tonum(a);
655 return 1;
658 int
659 val_isnum(struct value *a)
661 return a->type == V_NUM
662 || a->type == V_U8
663 || a->type == V_U16
664 || a->type == V_U32;
667 int64_t
668 val_tonum(struct value *a)
670 switch (a->type) {
671 case V_NUM: return a->v.num;
672 case V_U8: return a->v.u8;
673 case V_U16: return a->v.u16;
674 case V_U32: return a->v.u32;
675 default:
676 before_printing();
677 fprintf(stderr, "%s: given value is not a number\n", __func__);
678 abort();
682 int
683 val_eq(struct value *a, struct value *b)
685 if (val_isnum(a) && val_isnum(b))
686 return val_tonum(a) == val_tonum(b);
688 if (a->type != b->type)
689 return 0;
691 switch (a->type) {
692 case V_STR:
693 case V_SYM:
694 return !strcmp(a->v.str, b->v.str);
697 return 0;
700 int
701 val_leq(struct value *a, struct value *b)
703 if (val_isnum(a) && val_isnum(b))
704 return val_tonum(a) <= val_tonum(b);
705 return 0;
708 static inline const char *
709 pp_totype(int totype)
711 /*
712 * Not all of these are valid cast type thought, including
713 * every possibility only to aid debugging.
714 */
715 switch (totype) {
716 case V_STR: return "str";
717 case V_SYM: return "sym";
718 case V_NUM: return "num";
719 case V_QID: return "qid";
720 case V_U8: return "u8";
721 case V_U16: return "u16";
722 case V_U32: return "u32";
723 default: return "unknown";
727 int
728 val_cast(struct value *a, int totype)
730 int64_t v;
732 #define NUMCAST(val, t, c, totype, max) do { \
733 if (val > max) { \
734 before_printing(); \
735 fprintf(stderr, "can't cast %"PRIu64 \
736 " to %s\n", val, pp_totype(totype)); \
737 return EVAL_ERR; \
738 } \
739 a->type = totype; \
740 a->v.t = (c)val; \
741 return EVAL_OK; \
742 } while (0)
744 if (a->type == totype)
745 return EVAL_OK;
747 if (!val_isnum(a)) {
748 before_printing();
749 fprintf(stderr, "can't cast ");
750 ppf_val(stderr, a);
751 fprintf(stderr, " to type %s\n", pp_totype(totype));
752 return EVAL_ERR;
755 v = a->v.num;
756 switch (totype) {
757 case V_U8: NUMCAST(v, u8, uint8_t, totype, UINT8_MAX);
758 case V_U16: NUMCAST(v, u16, uint16_t, totype, UINT16_MAX);
759 case V_U32: NUMCAST(v, u32, uint32_t, totype, UINT32_MAX);
760 default:
761 before_printing();
762 fprintf(stderr, "can't cast %"PRIu64" to %s\n",
763 v, pp_totype(totype));
764 return EVAL_ERR;
767 #undef NUMCAST
770 int
771 val_faccess(struct value *a, const char *field, struct value *ret)
773 uint8_t mtype;
774 uint16_t len;
775 const char *errstr;
777 #define MSGTYPE(m) *(m.msg + 4) /* skip the length */
779 switch (a->type) {
780 case V_QID:
781 /* TODO: add path. needs uint64_t values thought! */
782 if (!strcmp(field, "vers")) {
783 ret->type = V_U32;
784 memcpy(&ret->v.u32, a->v.qid+1, 4);
785 return EVAL_OK;
786 } else if (!strcmp(field, "type")) {
787 ret->type = V_U8;
788 ret->v.u8 = *a->v.qid;
789 return EVAL_OK;
791 break;
793 case V_MSG:
794 mtype = MSGTYPE(a->v.msg);
795 if (!strcmp(field, "type")) {
796 ret->type = V_U8;
797 ret->v.u8 = MSGTYPE(a->v.msg);
798 return EVAL_OK;
799 } else if (!strcmp(field, "tag")) {
800 ret->type = V_U16;
801 memcpy(&ret->v.u16, &a->v.msg.msg[5], 2);
802 ret->v.u16 = le16toh(ret->v.u16);
803 return EVAL_OK;
804 } else if (!strcmp(field, "msize") && mtype == Rversion) {
805 ret->type = V_U32;
806 memcpy(&ret->v.u32, &a->v.msg.msg[7], 4);
807 ret->v.u32 = le32toh(ret->v.u32);
808 return EVAL_OK;
809 } else if (!strcmp(field, "qid") && mtype == Rattach) {
810 ret->type = V_QID;
811 memcpy(&ret->v.qid, &a->v.msg.msg[7], QIDSIZE);
812 return EVAL_OK;
813 } else if (!strcmp(field, "nwqid") && mtype == Rwalk) {
814 ret->type = V_U16;
815 memcpy(&ret->v.u16, &a->v.msg.msg[7], 2);
816 ret->v.u16 = le16toh(ret->v.u16);
817 return EVAL_OK;
818 } else if (!strcmp(field, "wqid") && mtype == Rwalk) {
819 ret->type = V_QIDVEC;
820 ret->v.qidvec.start = &a->v.msg.msg[9];
821 memcpy(&len, &a->v.msg.msg[7], 2);
822 len = le16toh(len);
823 ret->v.qidvec.len = len;
824 return EVAL_OK;
826 break;
828 case V_QIDVEC:
829 len = strtonum(field, 0, MAXWELEM, &errstr);
830 if (errstr != NULL) {
831 before_printing();
832 printf("can't access qid #%s: %s\n", field, errstr);
833 return EVAL_ERR;
836 if (len >= a->v.qidvec.len) {
837 before_printing();
838 printf("can't access qid #%d: out-of-bound "
839 "(max %zu)\n", len, a->v.qidvec.len);
840 return EVAL_ERR;
843 ret->type = V_QID;
844 memcpy(&ret->v.qid, a->v.qidvec.start + len * QIDSIZE,
845 QIDSIZE);
847 return EVAL_OK;
849 default:
850 break;
853 before_printing();
854 printf("can't access field `%s' on type %s (", field, val_type(a));
855 pp_val(a);
856 printf(")\n");
857 return EVAL_ERR;
859 #undef MSGTYPE
862 void
863 pp_op(struct op *op)
865 struct op *aux;
867 switch (op->type) {
868 case OP_REST:
869 printf("...");
870 break;
871 case OP_ASSIGN:
872 printf("%s = ", op->v.assign.name);
873 pp_op(op->v.assign.expr);
874 break;
875 case OP_ASSERT:
876 printf("assert ");
877 pp_op(op->v.assert);
878 break;
879 case OP_FUNCALL:
880 printf("funcall %s(", op->v.funcall.proc->name);
881 for (aux = op->v.funcall.argv; aux != NULL; aux = aux->next) {
882 pp_op(aux);
883 if (aux->next != NULL)
884 printf(", ");
886 printf(")");
887 break;
888 case OP_LITERAL:
889 pp_val(&op->v.literal);
890 break;
891 case OP_VAR:
892 printf("%s", op->v.var);
893 break;
894 case OP_CAST:
895 pp_op(op->v.cast.expr);
896 printf(":");
897 switch (op->v.cast.totype) {
898 case V_U8: printf("u8"); break;
899 case V_U16: printf("u16"); break;
900 case V_U32: printf("u32"); break;
901 case V_STR: printf("str"); break;
902 default: printf("???"); break;
904 break;
905 case OP_CMP_EQ:
906 pp_op(op->v.bin_cmp.a);
907 printf(" == ");
908 pp_op(op->v.bin_cmp.b);
909 break;
910 case OP_CMP_LEQ:
911 pp_op(op->v.bin_cmp.a);
912 printf(" <= ");
913 pp_op(op->v.bin_cmp.b);
914 break;
915 case OP_FACCESS:
916 pp_op(op->v.faccess.expr);
917 printf(".%s", op->v.faccess.field);
918 break;
919 case OP_SFAIL:
920 printf("should-fail ");
921 pp_op(op->v.sfail.expr);
922 if (op->v.sfail.msg != NULL)
923 printf(": \"%s\"", op->v.sfail.msg);
924 break;
925 case OP_VARGS:
926 printf("vargs");
927 break;
928 default:
929 printf(" ???[%d] ", op->type);
933 void
934 pp_block(struct op *op)
936 while (op != NULL) {
937 printf("> ");
938 pp_op(op);
939 printf("\n");
941 op = op->next;
945 int
946 eval(struct op *op)
948 struct value a, b;
949 struct proc *proc;
950 struct op *t, *tnext;
951 int i, ret;
953 #if DEBUG
954 pp_op(op);
955 printf("\n");
956 #endif
958 switch (op->type) {
959 case OP_REST:
960 /*
961 * Try to load the rest argument. Note that it can be
962 * empty!
963 */
964 if ((ret = getvar_raw("...", &t)) == EVAL_OK)
965 if ((ret = eval(t)) != EVAL_OK)
966 return ret;
967 break;
969 case OP_ASSIGN:
970 ret = setvar(op->v.assign.name, op->v.assign.expr);
971 if (ret != EVAL_OK)
972 return ret;
973 break;
975 case OP_ASSERT:
976 if ((ret = eval(op->v.assert)) != EVAL_OK)
977 return ret;
978 popv(&a);
979 if (!val_trueish(&a)) {
980 before_printing();
981 printf("assertion failed: ");
982 pp_op(op->v.assert);
983 printf("\n");
984 return EVAL_ERR;
986 break;
988 case OP_FUNCALL:
989 /* assume airity matches */
991 proc = op->v.funcall.proc;
992 if (proc->nativefn != NULL) {
993 /*
994 * Push arguments on the stack for builtin
995 * functions. Counting the height of the
996 * stack is done to compute the correct number
997 * in the vararg case. argc only counts the
998 * "syntactical" arguments, i.e. foo(x, ...)
999 * has argc == 2, but at runtime argc may be
1000 * 1, 2 or a greater number!
1003 i = stackh;
1004 t = op->v.funcall.argv;
1005 if (t != NULL && (ret = eval(t)) != EVAL_OK)
1006 return ret;
1007 i = stackh - i;
1009 assert(i >= 0);
1011 if ((ret = proc->nativefn(i))
1012 != EVAL_OK)
1013 return ret;
1014 } else {
1015 if (proc->body == NULL) {
1016 before_printing();
1017 printf("warn: calling the empty proc `%s'\n",
1018 proc->name);
1019 break;
1022 pushenv();
1024 for (t = op->v.funcall.argv, i = 0;
1025 t != NULL;
1026 t = t->next, i++) {
1028 * Push a pseudo variable `...' (and
1029 * don't evaluate it) in the vararg
1030 * case. A special case is when the
1031 * variable is itself `...'.
1033 if (proc->vararg && i == proc->minargs) {
1034 if (t->type != OP_REST)
1035 setvar_raw(xstrdup("..."), t);
1036 break;
1040 * The arguments are a linked list of
1041 * ops. Setvar will call eval that
1042 * will evaluate *all* the arguments.
1043 * The dance here that sets next to
1044 * NULL and then restores it is to
1045 * avoid this behaviour.
1047 tnext = t->next;
1048 t->next = NULL;
1049 ret = setvar(proc->args[i], t);
1050 t->next = tnext;
1052 if (ret != EVAL_OK)
1053 return ret;
1056 if ((ret = eval(proc->body)) != EVAL_OK)
1057 return ret;
1059 popenv();
1062 break;
1064 case OP_LITERAL:
1065 pushv(&op->v.literal);
1066 break;
1068 case OP_VAR:
1069 if ((ret = getvar(op->v.var, &a)) != EVAL_OK)
1070 return ret;
1071 pushv(&a);
1072 break;
1074 case OP_CAST:
1075 if ((ret = eval(op->v.cast.expr)) != EVAL_OK)
1076 return ret;
1077 popv(&a);
1078 if ((ret = val_cast(&a, op->v.cast.totype)) != EVAL_OK)
1079 return ret;
1080 pushv(&a);
1081 break;
1083 case OP_CMP_EQ:
1084 if ((ret = eval(op->v.bin_cmp.a)) != EVAL_OK)
1085 return ret;
1086 if ((ret = eval(op->v.bin_cmp.b)) != EVAL_OK)
1087 return ret;
1089 popv(&b);
1090 popv(&a);
1091 pushbool(val_eq(&a, &b));
1092 break;
1094 case OP_CMP_LEQ:
1095 if ((ret = eval(op->v.bin_cmp.a)) != EVAL_OK)
1096 return ret;
1097 if ((ret = eval(op->v.bin_cmp.b)) != EVAL_OK)
1098 return ret;
1100 popv(&b);
1101 popv(&a);
1102 pushbool(val_leq(&a, &b));
1103 break;
1105 case OP_FACCESS:
1106 if ((ret = eval(op->v.faccess.expr)) != EVAL_OK)
1107 return ret;
1108 popv(&a);
1109 if ((ret = val_faccess(&a, op->v.faccess.field, &b))
1110 != EVAL_OK)
1111 return ret;
1112 pushv(&b);
1113 break;
1115 case OP_SFAIL:
1116 if ((ret = eval(op->v.sfail.expr)) == EVAL_OK) {
1117 before_printing();
1118 printf("expecting failure");
1119 if (op->v.sfail.msg != NULL)
1120 printf(" \"%s\"", op->v.sfail.msg);
1121 printf("\n");
1122 printf("expression: ");
1123 pp_op(op->v.sfail.expr);
1124 printf("\n");
1125 return EVAL_ERR;
1127 if (ret == EVAL_SKIP)
1128 return ret;
1129 break;
1131 case OP_VARGS:
1132 if ((ret = getvar_raw("...", &t)) == EVAL_OK) {
1133 for (i = 0; t != NULL; t = t->next)
1134 i++;
1135 pushnum(i);
1136 } else
1137 pushnum(0);
1138 break;
1140 default:
1141 before_printing();
1142 fprintf(stderr, "invalid op, aborting.\n");
1143 abort();
1146 if (op->next)
1147 return eval(op->next);
1148 return EVAL_OK;
1151 void
1152 prepare_funcall(void)
1154 pushstack(&args);
1157 void
1158 push_arg(struct op *op)
1160 push(&args, op);
1163 struct op *
1164 op_funcall(struct proc *proc)
1166 struct op *op, *argv;
1167 int argc;
1169 argv = finalize(&args, &argc);
1171 op = newop(OP_FUNCALL);
1172 op->v.funcall.proc = proc;
1173 op->v.funcall.argv = argv;
1174 op->v.funcall.argc = argc;
1176 return op;
1179 void
1180 add_builtin_proc(const char *name, int (*fn)(int), int argc, int vararg)
1182 struct proc *proc;
1184 proc = xcalloc(1, sizeof(*proc));
1185 proc->name = xstrdup(name);
1186 proc->nativefn = fn;
1187 proc->minargs = argc;
1188 proc->vararg = vararg;
1190 TAILQ_INSERT_HEAD(&procs, proc, entry);
1193 void
1194 prepare_proc(void)
1196 pushstack(&args);
1199 int
1200 proc_setup_body(void)
1202 struct opstack *argv;
1203 struct op *op;
1204 int i;
1206 argv = peek(&args);
1207 for (i = 0, op = argv->base.next; op != NULL; i++) {
1209 * TODO: should free the whole list on error but..,
1210 * we're gonna exit real soon(tm)!
1212 if (op->type != OP_VAR && op->type != OP_REST)
1213 return 0;
1215 op = op->next;
1218 assert(i == argv->counter);
1219 pushstack(&blocks);
1220 return 1;
1223 void
1224 proc_done(char *name)
1226 struct proc *proc;
1227 struct op *op, *next, *argv, *body;
1228 int i, argc;
1230 argv = finalize(&args, &argc);
1231 body = finalize(&blocks, NULL);
1233 proc = xcalloc(1, sizeof(*proc));
1234 proc->name = name;
1235 proc->minargs = argc;
1237 for (i = 0, op = argv; op != NULL; ++i) {
1238 if (op->type == OP_REST) {
1239 proc->vararg = 1;
1240 proc->minargs = i;
1241 break;
1244 proc->args[i] = xstrdup(op->v.var);
1246 next = op->next;
1247 free_op(op);
1248 op = next;
1250 assert(i == argc || (proc->vararg && i == proc->minargs));
1252 proc->body = body;
1254 TAILQ_INSERT_HEAD(&procs, proc, entry);
1257 void
1258 block_push(struct op *op)
1260 push(&blocks, op);
1263 struct proc *
1264 proc_by_name(const char *name)
1266 struct proc *p;
1268 TAILQ_FOREACH(p, &procs, entry) {
1269 if (!strcmp(p->name, name))
1270 return p;
1273 return NULL;
1276 void
1277 prepare_test(void)
1279 pushstack(&blocks);
1282 void
1283 test_done(int shouldfail, char *name, char *dir)
1285 struct test *test;
1287 test = xcalloc(1, sizeof(*test));
1288 test->shouldfail = shouldfail;
1289 test->name = name;
1290 test->dir = dir;
1291 test->body = finalize(&blocks, NULL);
1293 if (TAILQ_EMPTY(&tests))
1294 TAILQ_INSERT_HEAD(&tests, test, entry);
1295 else
1296 TAILQ_INSERT_TAIL(&tests, test, entry);
1298 ntests++;
1301 static int
1302 builtin_print(int argc)
1304 struct value v;
1305 int i;
1307 before_printing();
1309 for (i = argc; i > 0; --i) {
1310 peekn(i, &v);
1311 if (v.type == V_STR)
1312 printf("%s", v.v.str);
1313 else
1314 pp_val(&v);
1315 printf(" ");
1318 printf("\n");
1320 popvn(argc);
1322 return EVAL_OK;
1325 static int
1326 builtin_debug(int argc)
1328 if (debug)
1329 return builtin_print(argc);
1331 popvn(argc);
1332 return EVAL_OK;
1335 static int
1336 builtin_skip(int argc)
1338 return EVAL_SKIP;
1341 static int
1342 builtin_iota(int argc)
1344 struct value v;
1346 v.type = V_U16;
1347 if ((v.v.u16 = ++lasttag) == 255)
1348 v.v.u16 = ++lasttag;
1350 pushv(&v);
1351 return EVAL_OK;
1354 static int
1355 builtin_send(int argc)
1357 struct ibuf *buf;
1358 struct value v;
1359 uint32_t len;
1360 uint16_t slen;
1361 int i;
1363 check_for_output();
1366 * Compute the length of the packet. 4 is for the initial
1367 * length field
1369 len = 4;
1371 for (i = argc; i > 0; --i) {
1372 peekn(i, &v);
1373 switch (v.type) {
1374 case V_STR:
1375 len += 2; /* count */
1376 len += strlen(v.v.str);
1377 break;
1379 case V_U8:
1380 len += 1;
1381 break;
1383 case V_U16:
1384 len += 2;
1385 break;
1387 case V_U32:
1388 len += 4;
1389 break;
1391 default:
1392 before_printing();
1393 printf("%s: can't serialize ", __func__);
1394 pp_val(&v);
1395 printf("\n");
1396 return EVAL_ERR;
1400 if (len > UINT16_MAX) {
1401 before_printing();
1402 printf("%s: message size too long: got %d when max is %d\n",
1403 __func__, len, UINT16_MAX);
1404 return EVAL_ERR;
1407 if ((buf = imsg_create(&ibuf, IMSG_BUF, 0, 0, len)) == NULL)
1408 fatal("imsg_create(%d)", len);
1410 len = htole32(len);
1411 imsg_add(buf, &len, sizeof(len));
1413 for (i = argc; i > 0; --i) {
1414 peekn(i, &v);
1415 switch (v.type) {
1416 case V_STR:
1417 slen = strlen(v.v.str);
1418 slen = htole16(slen);
1419 imsg_add(buf, &slen, sizeof(slen));
1420 imsg_add(buf, v.v.str, strlen(v.v.str));
1421 break;
1423 case V_U8:
1424 imsg_add(buf, &v.v.u8, 1);
1425 break;
1427 case V_U16:
1428 v.v.u16 = htole16(v.v.u16);
1429 imsg_add(buf, &v.v.u16, 2);
1430 break;
1432 case V_U32:
1433 v.v.u32 = htole32(v.v.u32);
1434 imsg_add(buf, &v.v.u32, 4);
1435 break;
1439 imsg_close(&ibuf, buf);
1441 if (imsg_flush(&ibuf) == -1) {
1442 i = errno;
1443 before_printing();
1444 printf("%s: imsg_flush failed: %s\n", __func__, strerror(i));
1445 return EVAL_ERR;
1448 check_for_output();
1449 return EVAL_OK;
1452 static int
1453 builtin_recv(int argc)
1455 struct pollfd pfd;
1456 struct value v;
1457 struct imsg imsg;
1458 ssize_t n, datalen;
1459 int serrno;
1461 if (lastmsg != NULL) {
1462 free(lastmsg);
1463 lastmsg = NULL;
1466 pfd.fd = ibuf.fd;
1467 pfd.events = POLLIN;
1468 if (poll(&pfd, 1, INFTIM) == -1) {
1469 serrno = errno;
1470 before_printing();
1471 printf("%s: poll failed: %s\n", __func__, strerror(serrno));
1472 return EVAL_ERR;
1475 again:
1476 if ((n = imsg_read(&ibuf)) == -1) {
1477 if (errno == EAGAIN)
1478 goto again;
1479 fatal("imsg_read");
1481 if (n == 0) {
1482 disconnect:
1483 before_printing();
1484 printf("child disconnected\n");
1485 return EVAL_ERR;
1488 nextmessage:
1489 check_for_output();
1491 /* read only one message */
1492 if ((n = imsg_get(&ibuf, &imsg)) == -1)
1493 fatal("imsg_get");
1494 if (n == 0)
1495 goto disconnect;
1497 datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
1498 switch (imsg.hdr.type) {
1499 case IMSG_BUF:
1500 v.type = V_MSG;
1501 if ((v.v.msg.msg = malloc(datalen)) == NULL)
1502 fatal("malloc");
1503 memcpy(v.v.msg.msg, imsg.data, datalen);
1504 v.v.msg.len = datalen;
1505 pushv(&v);
1506 imsg_free(&imsg);
1507 return EVAL_OK;
1509 case IMSG_CLOSE:
1510 before_printing();
1511 printf("subprocess closed the connection\n");
1512 imsg_free(&imsg);
1513 return EVAL_ERR;
1515 case IMSG_MSIZE:
1516 imsg_free(&imsg);
1517 goto nextmessage;
1519 default:
1520 before_printing();
1521 printf("got unknown message from subprocess: %d\n",
1522 imsg.hdr.type);
1523 imsg_free(&imsg);
1524 return EVAL_ERR;
1528 static pid_t
1529 spawn_client_proc(void)
1531 const char *argv[4];
1532 int p[2], out[2], argc = 0;
1533 pid_t pid;
1535 if (child_out != -1)
1536 close(child_out);
1538 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1539 PF_UNSPEC, p) == -1)
1540 fatal("socketpair");
1542 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1543 PF_UNSPEC, out) == -1)
1544 fatal("socketpair");
1546 switch (pid = fork()) {
1547 case -1:
1548 fatal("cannot fork");
1549 case 0:
1550 break;
1551 default:
1552 close(p[1]);
1553 close(out[1]);
1554 child_out = out[0];
1555 if (ibuf_inuse) {
1556 msgbuf_clear(&ibuf.w);
1557 close(ibuf.fd);
1559 imsg_init(&ibuf, p[0]);
1560 ibuf_inuse = 1;
1561 return pid;
1564 close(p[0]);
1565 close(out[0]);
1567 if (dup2(out[1], 1) == -1 ||
1568 dup2(out[1], 2) == -1)
1569 fatal("dup2");
1571 if (p[1] != 3) {
1572 if (dup2(p[1], 3) == -1)
1573 fatal("cannot setup imsg fd");
1574 } else if (fcntl(F_SETFD, 0) == -1)
1575 fatal("cannot setup imsg fd");
1577 argv[argc++] = argv0;
1578 argv[argc++] = "-Tc";
1580 #if DEBUG
1581 argv[argc++] = "-v";
1582 #endif
1584 argv[argc++] = NULL;
1586 execvp(argv0, (char *const *)argv);
1587 fatal("execvp");
1590 static void
1591 prepare_child_for_test(struct test *t)
1593 struct passwd *pw;
1594 struct stat sb;
1596 if (stat(t->dir, &sb) == -1)
1597 fatal("stat(\"%s\")", t->dir);
1599 if ((pw = getpwuid(sb.st_uid)) == NULL)
1600 fatal("getpwuid(%d)", sb.st_uid);
1602 imsg_compose(&ibuf, IMSG_AUTH, 0, 0, -1,
1603 pw->pw_name, strlen(pw->pw_name)+1);
1604 imsg_compose(&ibuf, IMSG_AUTH_DIR, 0, 0, -1,
1605 t->dir, strlen(t->dir)+1);
1607 if (imsg_flush(&ibuf) == -1)
1608 fatal("imsg_flush");
1611 static int
1612 run_test(struct test *t)
1614 pid_t pid;
1615 int ret;
1617 #if DEBUG
1618 before_printing();
1619 puts("=====================");
1620 pp_block(t->body);
1621 puts("=====================");
1622 #endif
1624 if (stackh != 0)
1625 popvn(stackh);
1627 if (t->body == NULL) {
1628 before_printing();
1629 printf("no instructions, skipping...\n");
1630 return EVAL_SKIP;
1633 pid = spawn_client_proc();
1634 prepare_child_for_test(t);
1635 ret = eval(t->body);
1637 imsg_compose(&ibuf, IMSG_CONN_GONE, 0, 0, -1, NULL, 0);
1638 imsg_flush(&ibuf);
1640 while (waitpid(pid, NULL, 0) != pid)
1641 ; /* nop */
1643 check_for_output();
1645 if (t->shouldfail) {
1646 if (ret == EVAL_OK) {
1647 before_printing();
1648 printf("test was expected to fail\n");
1649 return EVAL_ERR;
1650 } else if (ret == EVAL_ERR)
1651 return EVAL_OK;
1654 return ret;
1657 int
1658 main(int argc, char **argv)
1660 struct test *t;
1661 int ch, i, r, passed = 0, failed = 0, skipped = 0;
1662 int runclient = 0;
1663 const char *pat = NULL;
1664 regex_t reg;
1666 assert(argv0 = argv[0]);
1668 signal(SIGPIPE, SIG_IGN);
1670 log_init(1, LOG_DAEMON);
1671 log_setverbose(1);
1673 /* prepare the global env */
1674 pushenv();
1676 add_builtin_proc("print", builtin_print, 1, 1);
1677 add_builtin_proc("debug", builtin_debug, 1, 1);
1678 add_builtin_proc("skip", builtin_skip, 0, 0);
1679 add_builtin_proc("iota", builtin_iota, 0, 0);
1680 add_builtin_proc("send", builtin_send, 2, 1);
1681 add_builtin_proc("recv", builtin_recv, 0, 0);
1683 while ((ch = getopt(argc, argv, "nT:vx:")) != -1) {
1684 switch (ch) {
1685 case 'n':
1686 syntaxcheck = 1;
1687 break;
1688 case 'T':
1689 assert(*optarg == 'c');
1690 runclient = 1;
1691 break;
1692 case 'v':
1693 debug = 1;
1694 break;
1695 case 'x':
1696 pat = optarg;
1697 break;
1698 default:
1699 fprintf(stderr, "Usage: %s [-nv] [files...]\n",
1700 *argv);
1701 exit(1);
1704 argc -= optind;
1705 argv += optind;
1707 if (runclient)
1708 client(1, debug);
1710 if (pat == NULL)
1711 pat = ".*";
1713 if (regcomp(&reg, pat, REG_BASIC | REG_ICASE | REG_NOSUB) != 0)
1714 fatalx("invalid regexp: %s", pat);
1716 for (i = 0; i < argc; ++i)
1717 loadfile(argv[i]);
1719 if (syntaxcheck) {
1720 fprintf(stderr, "files OK\n");
1721 return 0;
1724 /* Check for root privileges. */
1725 if (geteuid())
1726 fatalx("need root privileges");
1728 i = 0;
1729 TAILQ_FOREACH(t, &tests, entry) {
1730 if (regexec(&reg, t->name, 0, NULL, 0) != 0)
1731 continue;
1733 printf("===> [%d/%d] running test \"%s\"... ", i+1, ntests,
1734 t->name);
1735 fflush(stdout);
1737 filler = "\n";
1738 r = run_test(t);
1739 if (filler == NULL)
1740 printf("=> test ");
1742 switch (r) {
1743 case EVAL_OK:
1744 printf("passed\n");
1745 passed++;
1746 break;
1747 case EVAL_ERR:
1748 failed++;
1749 printf("failed\n");
1750 break;
1751 case EVAL_SKIP:
1752 printf("skipped\n");
1753 skipped++;
1754 break;
1757 if (filler == NULL)
1758 printf("\n");
1759 i++;
1762 printf("\n");
1763 printf("%d/%d passed (%d skipped and %d failed)\n",
1764 passed, i, skipped, failed);
1766 popenv();
1767 free(lastmsg);
1768 regfree(&reg);
1770 return failed != 0;