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 "compat.h"
19 #include <sys/socket.h>
20 #include <sys/stat.h>
21 #include <sys/wait.h>
23 #include <assert.h>
24 #include <endian.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <inttypes.h>
28 #include <poll.h>
29 #include <pwd.h>
30 #include <regex.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <syslog.h>
36 #include <unistd.h>
38 #include "client.h"
39 #include "kami.h"
40 #include "kamid.h"
41 #include "log.h"
42 #include "script.h"
43 #include "utils.h"
45 #define DEBUG 0
47 #ifndef INFTIM
48 #define INFTIM -1
49 #endif
51 static const char *argv0;
53 static uint8_t *lastmsg;
55 static struct imsgbuf ibuf;
56 static int ibuf_inuse;
57 static int child_out = -1;
59 static struct procs procs = TAILQ_HEAD_INITIALIZER(procs);
60 static struct tests tests = TAILQ_HEAD_INITIALIZER(tests);
62 static int ntests;
64 static struct opstacks blocks = TAILQ_HEAD_INITIALIZER(blocks);
65 static struct opstacks args = TAILQ_HEAD_INITIALIZER(args);
67 #define STACK_HEIGHT 64
68 static struct value vstack[STACK_HEIGHT];
69 static int stackh;
71 static struct envs envs = TAILQ_HEAD_INITIALIZER(envs);
73 static struct value v_false = {.type = V_NUM, .v = {.num = 0}};
74 static struct value v_true = {.type = V_NUM, .v = {.num = 1}};
76 static uint8_t lasttag;
78 static int debug;
79 static int syntaxcheck;
81 static const char *filler;
83 static inline void
84 before_printing(void)
85 {
86 if (filler != NULL) {
87 printf("%s", filler);
88 filler = NULL;
89 }
90 }
92 static inline void
93 check_for_output(void)
94 {
95 static char buf[BUFSIZ];
96 struct pollfd pfd;
97 ssize_t r;
99 pfd.fd = child_out;
100 pfd.events = POLLIN;
101 if (poll(&pfd, 1, 0) == -1)
102 fatal("poll");
104 if (!(pfd.revents & POLLIN))
105 return;
107 for (;;) {
108 if ((r = read(child_out, buf, sizeof(buf))) == -1) {
109 if (errno == EAGAIN)
110 break;
111 fatal("read");
113 if (r == 0)
114 break;
115 before_printing();
116 fwrite(buf, 1, r, stdout);
120 static inline void
121 peekn(int depth, struct value *v)
123 if (depth > stackh)
124 errx(1, "can't peek the stack at %d: underflow",
125 depth);
126 memcpy(v, &vstack[stackh - depth], sizeof(*v));
128 #if DEBUG
129 printf("peeking(%d) ", depth); pp_val(v); printf("\n");
130 #endif
133 static inline void
134 popv(struct value *v)
136 if (stackh == 0)
137 errx(1, "can't pop the stack: underflow");
138 memcpy(v, &vstack[--stackh], sizeof(*v));
140 #if DEBUG
141 printf("popping "); pp_val(v); printf("\n");
142 #endif
145 static inline void
146 popvn(int n)
148 struct value v;
150 while (n-- > 0)
151 popv(&v);
154 static inline void
155 pushv(struct value *v)
157 if (stackh == STACK_HEIGHT)
158 errx(1, "can't push the stack: overflow");
160 #if DEBUG
161 printf("pushing "); pp_val(v); printf("\n");
162 #endif
164 memcpy(&vstack[stackh++], v, sizeof(*v));
167 static inline void
168 pushbool(int n)
170 pushv(n ? &v_true : &v_false);
173 static inline void
174 pushnum(int64_t n)
176 struct value v;
178 v.type = V_NUM;
179 v.v.num = n;
180 pushv(&v);
183 static inline struct opstack *
184 pushstack(struct opstacks *stack)
186 struct opstack *ops;
188 ops = xcalloc(1, sizeof(*ops));
189 TAILQ_INSERT_HEAD(stack, ops, entry);
190 return ops;
193 static inline struct opstack *
194 peek(struct opstacks *stack)
196 if (TAILQ_EMPTY(stack))
197 errx(1, "%s: args underflow", __func__);
199 return TAILQ_FIRST(stack);
202 static inline struct op *
203 finalize(struct opstacks *stack, int *argc)
205 struct opstack *ops;
206 struct op *op;
208 if (TAILQ_EMPTY(stack))
209 errx(1, "%s: args underflow", __func__);
211 ops = peek(stack);
212 TAILQ_REMOVE(&args, ops, entry);
213 op = ops->base.next;
215 if (argc != NULL)
216 *argc = ops->counter;
218 free(ops);
219 return op;
222 static inline void
223 push(struct opstacks *stack, struct op *op)
225 struct opstack *ops;
227 ops = peek(stack);
228 if (ops->last == NULL) {
229 ops->base.next = op;
230 ops->last = op;
231 } else {
232 ops->last->next = op;
233 ops->last = op;
236 ops->counter++;
239 static inline void
240 pushenv(void)
242 struct env *e;
244 e = xcalloc(1, sizeof(*e));
245 TAILQ_INSERT_HEAD(&envs, e, entry);
248 static inline struct env *
249 currentenv(void)
251 assert(!TAILQ_EMPTY(&envs));
252 return TAILQ_FIRST(&envs);
255 static void
256 popenv(void)
258 struct env *e;
259 struct binding *b, *tb;
261 e = currentenv();
262 TAILQ_REMOVE(&envs, e, entry);
264 TAILQ_FOREACH_SAFE(b, &e->bindings, entry, tb)
265 free(b);
267 free(e);
270 static inline int
271 setvar(char *sym, struct op *op)
273 struct binding *b;
274 struct env *e;
275 int ret, height;
277 height = stackh;
278 if ((ret = eval(op)) != EVAL_OK)
279 return ret;
281 if (stackh != height + 1) {
282 before_printing();
283 printf("trying to assign to `%s' a void value: ", sym);
284 pp_op(op);
285 printf("\n");
286 return EVAL_ERR;
289 b = xcalloc(1, sizeof(*b));
290 b->name = sym;
291 popv(&b->val);
293 e = TAILQ_FIRST(&envs);
294 TAILQ_INSERT_HEAD(&e->bindings, b, entry);
296 return EVAL_OK;
299 static inline void
300 setvar_raw(char *sym, struct op *op)
302 struct binding *b;
303 struct env *e;
305 b = xcalloc(1, sizeof(*b));
306 b->name = sym;
307 b->raw = op;
309 e = TAILQ_FIRST(&envs);
310 TAILQ_INSERT_HEAD(&e->bindings, b, entry);
313 static inline int
314 getvar(const char *sym, struct value *v)
316 struct env *e;
317 struct binding *b;
319 TAILQ_FOREACH(e, &envs, entry) {
320 TAILQ_FOREACH(b, &e->bindings, entry) {
321 if (!strcmp(sym, b->name)) {
322 memcpy(v, &b->val, sizeof(*v));
323 return EVAL_OK;
328 before_printing();
329 fprintf(stderr, "unbound variable %s\n", sym);
330 return EVAL_ERR;
333 static inline int
334 getvar_raw(const char *sym, struct op **raw)
336 struct env *e;
337 struct binding *b;
339 TAILQ_FOREACH(e, &envs, entry) {
340 TAILQ_FOREACH(b, &e->bindings, entry) {
341 if (!strcmp(sym, b->name)) {
342 *raw = b->raw;
343 return EVAL_OK;
348 return EVAL_ERR;
351 int
352 global_set(char *sym, struct op *op)
354 struct binding *b;
355 struct env *e;
357 /* TODO: check for duplicates */
359 if (op->type != OP_LITERAL &&
360 (op->type == OP_CAST && op->v.cast.expr->type != OP_LITERAL))
361 return 0;
363 b = xcalloc(1, sizeof(*b));
364 b->name = sym;
366 /* it's only a cast on a literal! */
367 if (op->type == OP_CAST) {
368 if (eval(op) != EVAL_OK) {
369 free(b);
370 return 0;
372 popv(&b->val);
373 } else
374 memcpy(&b->val, &op->v.literal, sizeof(b->val));
376 e = TAILQ_LAST(&envs, envs);
377 TAILQ_INSERT_HEAD(&e->bindings, b, entry);
379 return 1;
382 struct op *
383 newop(int type)
385 struct op *op;
387 op = xcalloc(1, sizeof(*op));
388 op->type = type;
390 return op;
393 void
394 free_op_rec(struct op *op)
396 struct op *n;
398 while (op != NULL) {
399 n = op->next;
400 free_op(op);
401 op = n;
405 void
406 free_op(struct op *op)
408 if (op == NULL)
409 return;
411 switch (op->type) {
412 case OP_REST:
413 case OP_LITERAL:
414 case OP_VARGS:
415 break;
416 case OP_ASSIGN:
417 free(op->v.assign.name);
418 free_op_rec(op->v.assign.expr);
419 break;
420 case OP_ASSERT:
421 free_op_rec(op->v.assert);
422 break;
423 case OP_FUNCALL:
424 free_op_rec(op->v.funcall.argv);
425 break;
426 case OP_VAR:
427 free(op->v.var);
428 break;
429 case OP_CAST:
430 free_op_rec(op->v.cast.expr);
431 break;
432 case OP_CMP_EQ:
433 case OP_CMP_LEQ:
434 free_op_rec(op->v.bin_cmp.a);
435 free_op_rec(op->v.bin_cmp.b);
436 break;
437 case OP_FACCESS:
438 free_op_rec(op->v.faccess.expr);
439 free(op->v.faccess.field);
440 break;
441 case OP_SFAIL:
442 free(op->v.sfail.msg);
443 free_op_rec(op->v.sfail.expr);
444 break;
445 default:
446 /* unreachable */
447 abort();
450 free(op);
453 struct op *
454 op_rest(void)
456 return newop(OP_REST);
459 struct op *
460 op_assign(char *sym, struct op *expr)
462 struct op *op;
464 op = newop(OP_ASSIGN);
465 op->v.assign.name = sym;
466 op->v.assign.expr = expr;
468 return op;
471 struct op *
472 op_assert(struct op *expr)
474 struct op *op;
476 op = newop(OP_ASSERT);
477 op->v.assert = expr;
479 return op;
482 struct op *
483 op_var(char *sym)
485 struct op *op;
487 op = newop(OP_VAR);
488 op->v.var = sym;
490 return op;
493 struct op *
494 op_lit_str(char *str)
496 struct op *op;
498 op = newop(OP_LITERAL);
499 op->v.literal.type = V_STR;
500 op->v.literal.v.str = str;
502 return op;
505 struct op *
506 op_lit_num(uint64_t n)
508 struct op *op;
510 op = newop(OP_LITERAL);
511 op->v.literal.type = V_NUM;
512 op->v.literal.v.num = n;
514 return op;
517 struct op *
518 op_cmp_eq(struct op *a, struct op *b)
520 struct op *op;
522 op = newop(OP_CMP_EQ);
523 op->v.bin_cmp.a = a;
524 op->v.bin_cmp.b = b;
526 return op;
529 struct op *
530 op_cmp_leq(struct op *a, struct op *b)
532 struct op *op;
534 op = newop(OP_CMP_LEQ);
535 op->v.bin_cmp.a = a;
536 op->v.bin_cmp.b = b;
538 return op;
541 struct op *
542 op_cast(struct op *expr, int totype)
544 struct op *op;
546 op = newop(OP_CAST);
547 op->v.cast.expr = expr;
548 op->v.cast.totype = totype;
550 return op;
553 struct op *
554 op_faccess(struct op *expr, char *field)
556 struct op *op;
558 op = newop(OP_FACCESS);
559 op->v.faccess.expr = expr;
560 op->v.faccess.field = field;
562 return op;
565 struct op *
566 op_sfail(struct op *expr, char *msg)
568 struct op *op;
570 op = newop(OP_SFAIL);
571 op->v.sfail.expr = expr;
572 op->v.sfail.msg = msg;
574 return op;
577 struct op *
578 op_vargs(void)
580 struct op *op;
582 op = newop(OP_VARGS);
584 return op;
587 void
588 ppf_val(FILE *f, struct value *val)
590 size_t i;
592 switch (val->type) {
593 case V_SYM:
594 fprintf(f, "%s", val->v.str);
595 break;
596 case V_STR:
597 fprintf(f, "\"%s\"", val->v.str);
598 break;
599 case V_NUM:
600 fprintf(f, "%"PRIi64, val->v.num);
601 break;
602 case V_U8:
603 fprintf(f, "%"PRIu8, val->v.u8);
604 break;
605 case V_U16:
606 fprintf(f, "%"PRIu16, val->v.u16);
607 break;
608 case V_U32:
609 fprintf(f, "%"PRIu32, val->v.u32);
610 break;
611 case V_MSG:
612 fprintf(f, "(");
613 for (i = 0; i < val->v.msg.len; ++i)
614 fprintf(f, "%x%s", val->v.msg.msg[i],
615 i == val->v.msg.len-1 ? "" : " ");
616 fprintf(f, ")");
617 break;
618 case V_QIDVEC:
619 fprintf(f, "qids[n=%zu]", val->v.qidvec.len);
620 break;
621 default:
622 fprintf(f, "<unknown value>");
623 break;
627 void
628 pp_val(struct value *val)
630 ppf_val(stdout, val);
633 const char *
634 val_type(struct value *v)
636 switch (v->type) {
637 case V_SYM: return "symbol";
638 case V_STR: return "string";
639 case V_NUM: return "number";
640 case V_MSG: return "message";
641 case V_QID: return "qid";
642 case V_U8: return "u8";
643 case V_U16: return "u16";
644 case V_U32: return "u32";
645 default: return "unknown";
649 int
650 val_trueish(struct value *a)
652 if (val_isnum(a))
653 return val_tonum(a);
654 return 1;
657 int
658 val_isnum(struct value *a)
660 return a->type == V_NUM
661 || a->type == V_U8
662 || a->type == V_U16
663 || a->type == V_U32;
666 int64_t
667 val_tonum(struct value *a)
669 switch (a->type) {
670 case V_NUM: return a->v.num;
671 case V_U8: return a->v.u8;
672 case V_U16: return a->v.u16;
673 case V_U32: return a->v.u32;
674 default:
675 before_printing();
676 fprintf(stderr, "%s: given value is not a number\n", __func__);
677 abort();
681 int
682 val_eq(struct value *a, struct value *b)
684 if (val_isnum(a) && val_isnum(b))
685 return val_tonum(a) == val_tonum(b);
687 if (a->type != b->type)
688 return 0;
690 switch (a->type) {
691 case V_STR:
692 case V_SYM:
693 return !strcmp(a->v.str, b->v.str);
696 return 0;
699 int
700 val_leq(struct value *a, struct value *b)
702 if (val_isnum(a) && val_isnum(b))
703 return val_tonum(a) <= val_tonum(b);
704 return 0;
707 static inline const char *
708 pp_totype(int totype)
710 /*
711 * Not all of these are valid cast type thought, including
712 * every possibility only to aid debugging.
713 */
714 switch (totype) {
715 case V_STR: return "str";
716 case V_SYM: return "sym";
717 case V_NUM: return "num";
718 case V_QID: return "qid";
719 case V_U8: return "u8";
720 case V_U16: return "u16";
721 case V_U32: return "u32";
722 default: return "unknown";
726 int
727 val_cast(struct value *a, int totype)
729 int64_t v;
731 #define NUMCAST(val, t, c, totype, max) do { \
732 if (val > max) { \
733 before_printing(); \
734 fprintf(stderr, "can't cast %"PRIu64 \
735 " to %s\n", val, pp_totype(totype)); \
736 return EVAL_ERR; \
737 } \
738 a->type = totype; \
739 a->v.t = (c)val; \
740 return EVAL_OK; \
741 } while (0)
743 if (a->type == totype)
744 return EVAL_OK;
746 if (!val_isnum(a)) {
747 before_printing();
748 fprintf(stderr, "can't cast ");
749 ppf_val(stderr, a);
750 fprintf(stderr, " to type %s\n", pp_totype(totype));
751 return EVAL_ERR;
754 v = a->v.num;
755 switch (totype) {
756 case V_U8: NUMCAST(v, u8, uint8_t, totype, UINT8_MAX);
757 case V_U16: NUMCAST(v, u16, uint16_t, totype, UINT16_MAX);
758 case V_U32: NUMCAST(v, u32, uint32_t, totype, UINT32_MAX);
759 default:
760 before_printing();
761 fprintf(stderr, "can't cast %"PRIu64" to %s\n",
762 v, pp_totype(totype));
763 return EVAL_ERR;
766 #undef NUMCAST
769 int
770 val_faccess(struct value *a, const char *field, struct value *ret)
772 uint8_t mtype;
773 uint16_t len;
774 const char *errstr;
776 #define MSGTYPE(m) *(m.msg + 4) /* skip the length */
778 switch (a->type) {
779 case V_QID:
780 /* TODO: add path. needs uint64_t values thought! */
781 if (!strcmp(field, "vers")) {
782 ret->type = V_U32;
783 memcpy(&ret->v.u32, a->v.qid+1, 4);
784 return EVAL_OK;
785 } else if (!strcmp(field, "type")) {
786 ret->type = V_U8;
787 ret->v.u8 = *a->v.qid;
788 return EVAL_OK;
790 break;
792 case V_MSG:
793 mtype = MSGTYPE(a->v.msg);
794 if (!strcmp(field, "type")) {
795 ret->type = V_U8;
796 ret->v.u8 = MSGTYPE(a->v.msg);
797 return EVAL_OK;
798 } else if (!strcmp(field, "tag")) {
799 ret->type = V_U16;
800 memcpy(&ret->v.u16, &a->v.msg.msg[5], 2);
801 ret->v.u16 = le16toh(ret->v.u16);
802 return EVAL_OK;
803 } else if (!strcmp(field, "msize") && mtype == Rversion) {
804 ret->type = V_U32;
805 memcpy(&ret->v.u32, &a->v.msg.msg[7], 4);
806 ret->v.u32 = le32toh(ret->v.u32);
807 return EVAL_OK;
808 } else if (!strcmp(field, "qid") && mtype == Rattach) {
809 ret->type = V_QID;
810 memcpy(&ret->v.qid, &a->v.msg.msg[7], QIDSIZE);
811 return EVAL_OK;
812 } else if (!strcmp(field, "nwqid") && mtype == Rwalk) {
813 ret->type = V_U16;
814 memcpy(&ret->v.u16, &a->v.msg.msg[7], 2);
815 ret->v.u16 = le16toh(ret->v.u16);
816 return EVAL_OK;
817 } else if (!strcmp(field, "wqid") && mtype == Rwalk) {
818 ret->type = V_QIDVEC;
819 ret->v.qidvec.start = &a->v.msg.msg[9];
820 memcpy(&len, &a->v.msg.msg[7], 2);
821 len = le16toh(len);
822 ret->v.qidvec.len = len;
823 return EVAL_OK;
825 break;
827 case V_QIDVEC:
828 len = strtonum(field, 0, MAXWELEM, &errstr);
829 if (errstr != NULL) {
830 before_printing();
831 printf("can't access qid #%s: %s\n", field, errstr);
832 return EVAL_ERR;
835 if (len >= a->v.qidvec.len) {
836 before_printing();
837 printf("can't access qid #%d: out-of-bound "
838 "(max %zu)\n", len, a->v.qidvec.len);
839 return EVAL_ERR;
842 ret->type = V_QID;
843 memcpy(&ret->v.qid, a->v.qidvec.start + len * QIDSIZE,
844 QIDSIZE);
846 return EVAL_OK;
848 default:
849 break;
852 before_printing();
853 printf("can't access field `%s' on type %s (", field, val_type(a));
854 pp_val(a);
855 printf(")\n");
856 return EVAL_ERR;
858 #undef MSGTYPE
861 void
862 pp_op(struct op *op)
864 struct op *aux;
866 switch (op->type) {
867 case OP_REST:
868 printf("...");
869 break;
870 case OP_ASSIGN:
871 printf("%s = ", op->v.assign.name);
872 pp_op(op->v.assign.expr);
873 break;
874 case OP_ASSERT:
875 printf("assert ");
876 pp_op(op->v.assert);
877 break;
878 case OP_FUNCALL:
879 printf("funcall %s(", op->v.funcall.proc->name);
880 for (aux = op->v.funcall.argv; aux != NULL; aux = aux->next) {
881 pp_op(aux);
882 if (aux->next != NULL)
883 printf(", ");
885 printf(")");
886 break;
887 case OP_LITERAL:
888 pp_val(&op->v.literal);
889 break;
890 case OP_VAR:
891 printf("%s", op->v.var);
892 break;
893 case OP_CAST:
894 pp_op(op->v.cast.expr);
895 printf(":");
896 switch (op->v.cast.totype) {
897 case V_U8: printf("u8"); break;
898 case V_U16: printf("u16"); break;
899 case V_U32: printf("u32"); break;
900 case V_STR: printf("str"); break;
901 default: printf("???"); break;
903 break;
904 case OP_CMP_EQ:
905 pp_op(op->v.bin_cmp.a);
906 printf(" == ");
907 pp_op(op->v.bin_cmp.b);
908 break;
909 case OP_CMP_LEQ:
910 pp_op(op->v.bin_cmp.a);
911 printf(" <= ");
912 pp_op(op->v.bin_cmp.b);
913 break;
914 case OP_FACCESS:
915 pp_op(op->v.faccess.expr);
916 printf(".%s", op->v.faccess.field);
917 break;
918 case OP_SFAIL:
919 printf("should-fail ");
920 pp_op(op->v.sfail.expr);
921 if (op->v.sfail.msg != NULL)
922 printf(": \"%s\"", op->v.sfail.msg);
923 break;
924 case OP_VARGS:
925 printf("vargs");
926 break;
927 default:
928 printf(" ???[%d] ", op->type);
932 void
933 pp_block(struct op *op)
935 while (op != NULL) {
936 printf("> ");
937 pp_op(op);
938 printf("\n");
940 op = op->next;
944 int
945 eval(struct op *op)
947 struct value a, b;
948 struct proc *proc;
949 struct op *t, *tnext;
950 int i, ret;
952 #if DEBUG
953 pp_op(op);
954 printf("\n");
955 #endif
957 switch (op->type) {
958 case OP_REST:
959 /*
960 * Try to load the rest argument. Note that it can be
961 * empty!
962 */
963 if ((ret = getvar_raw("...", &t)) == EVAL_OK)
964 if ((ret = eval(t)) != EVAL_OK)
965 return ret;
966 break;
968 case OP_ASSIGN:
969 ret = setvar(op->v.assign.name, op->v.assign.expr);
970 if (ret != EVAL_OK)
971 return ret;
972 break;
974 case OP_ASSERT:
975 if ((ret = eval(op->v.assert)) != EVAL_OK)
976 return ret;
977 popv(&a);
978 if (!val_trueish(&a)) {
979 before_printing();
980 printf("assertion failed: ");
981 pp_op(op->v.assert);
982 printf("\n");
983 return EVAL_ERR;
985 break;
987 case OP_FUNCALL:
988 /* assume airity matches */
990 proc = op->v.funcall.proc;
991 if (proc->nativefn != NULL) {
992 /*
993 * Push arguments on the stack for builtin
994 * functions. Counting the height of the
995 * stack is done to compute the correct number
996 * in the vararg case. argc only counts the
997 * "syntactical" arguments, i.e. foo(x, ...)
998 * has argc == 2, but at runtime argc may be
999 * 1, 2 or a greater number!
1002 i = stackh;
1003 t = op->v.funcall.argv;
1004 if (t != NULL && (ret = eval(t)) != EVAL_OK)
1005 return ret;
1006 i = stackh - i;
1008 assert(i >= 0);
1010 if ((ret = proc->nativefn(i))
1011 != EVAL_OK)
1012 return ret;
1013 } else {
1014 if (proc->body == NULL) {
1015 before_printing();
1016 printf("warn: calling the empty proc `%s'\n",
1017 proc->name);
1018 break;
1021 pushenv();
1023 for (t = op->v.funcall.argv, i = 0;
1024 t != NULL;
1025 t = t->next, i++) {
1027 * Push a pseudo variable `...' (and
1028 * don't evaluate it) in the vararg
1029 * case. A special case is when the
1030 * variable is itself `...'.
1032 if (proc->vararg && i == proc->minargs) {
1033 if (t->type != OP_REST)
1034 setvar_raw(xstrdup("..."), t);
1035 break;
1039 * The arguments are a linked list of
1040 * ops. Setvar will call eval that
1041 * will evaluate *all* the arguments.
1042 * The dance here that sets next to
1043 * NULL and then restores it is to
1044 * avoid this behaviour.
1046 tnext = t->next;
1047 t->next = NULL;
1048 ret = setvar(proc->args[i], t);
1049 t->next = tnext;
1051 if (ret != EVAL_OK)
1052 return ret;
1055 if ((ret = eval(proc->body)) != EVAL_OK)
1056 return ret;
1058 popenv();
1061 break;
1063 case OP_LITERAL:
1064 pushv(&op->v.literal);
1065 break;
1067 case OP_VAR:
1068 if ((ret = getvar(op->v.var, &a)) != EVAL_OK)
1069 return ret;
1070 pushv(&a);
1071 break;
1073 case OP_CAST:
1074 if ((ret = eval(op->v.cast.expr)) != EVAL_OK)
1075 return ret;
1076 popv(&a);
1077 if ((ret = val_cast(&a, op->v.cast.totype)) != EVAL_OK)
1078 return ret;
1079 pushv(&a);
1080 break;
1082 case OP_CMP_EQ:
1083 if ((ret = eval(op->v.bin_cmp.a)) != EVAL_OK)
1084 return ret;
1085 if ((ret = eval(op->v.bin_cmp.b)) != EVAL_OK)
1086 return ret;
1088 popv(&b);
1089 popv(&a);
1090 pushbool(val_eq(&a, &b));
1091 break;
1093 case OP_CMP_LEQ:
1094 if ((ret = eval(op->v.bin_cmp.a)) != EVAL_OK)
1095 return ret;
1096 if ((ret = eval(op->v.bin_cmp.b)) != EVAL_OK)
1097 return ret;
1099 popv(&b);
1100 popv(&a);
1101 pushbool(val_leq(&a, &b));
1102 break;
1104 case OP_FACCESS:
1105 if ((ret = eval(op->v.faccess.expr)) != EVAL_OK)
1106 return ret;
1107 popv(&a);
1108 if ((ret = val_faccess(&a, op->v.faccess.field, &b))
1109 != EVAL_OK)
1110 return ret;
1111 pushv(&b);
1112 break;
1114 case OP_SFAIL:
1115 if ((ret = eval(op->v.sfail.expr)) == EVAL_OK) {
1116 before_printing();
1117 printf("expecting failure");
1118 if (op->v.sfail.msg != NULL)
1119 printf(" \"%s\"", op->v.sfail.msg);
1120 printf("\n");
1121 printf("expression: ");
1122 pp_op(op->v.sfail.expr);
1123 printf("\n");
1124 return EVAL_ERR;
1126 if (ret == EVAL_SKIP)
1127 return ret;
1128 break;
1130 case OP_VARGS:
1131 if ((ret = getvar_raw("...", &t)) == EVAL_OK) {
1132 for (i = 0; t != NULL; t = t->next)
1133 i++;
1134 pushnum(i);
1135 } else
1136 pushnum(0);
1137 break;
1139 default:
1140 before_printing();
1141 fprintf(stderr, "invalid op, aborting.\n");
1142 abort();
1145 if (op->next)
1146 return eval(op->next);
1147 return EVAL_OK;
1150 void
1151 prepare_funcall(void)
1153 pushstack(&args);
1156 void
1157 push_arg(struct op *op)
1159 push(&args, op);
1162 struct op *
1163 op_funcall(struct proc *proc)
1165 struct op *op, *argv;
1166 int argc;
1168 argv = finalize(&args, &argc);
1170 op = newop(OP_FUNCALL);
1171 op->v.funcall.proc = proc;
1172 op->v.funcall.argv = argv;
1173 op->v.funcall.argc = argc;
1175 return op;
1178 void
1179 add_builtin_proc(const char *name, int (*fn)(int), int argc, int vararg)
1181 struct proc *proc;
1183 proc = xcalloc(1, sizeof(*proc));
1184 proc->name = xstrdup(name);
1185 proc->nativefn = fn;
1186 proc->minargs = argc;
1187 proc->vararg = vararg;
1189 TAILQ_INSERT_HEAD(&procs, proc, entry);
1192 void
1193 prepare_proc(void)
1195 pushstack(&args);
1198 int
1199 proc_setup_body(void)
1201 struct opstack *argv;
1202 struct op *op;
1203 int i;
1205 argv = peek(&args);
1206 for (i = 0, op = argv->base.next; op != NULL; i++) {
1208 * TODO: should free the whole list on error but..,
1209 * we're gonna exit real soon(tm)!
1211 if (op->type != OP_VAR && op->type != OP_REST)
1212 return 0;
1214 op = op->next;
1217 assert(i == argv->counter);
1218 pushstack(&blocks);
1219 return 1;
1222 void
1223 proc_done(char *name)
1225 struct proc *proc;
1226 struct op *op, *next, *argv, *body;
1227 int i, argc;
1229 argv = finalize(&args, &argc);
1230 body = finalize(&blocks, NULL);
1232 proc = xcalloc(1, sizeof(*proc));
1233 proc->name = name;
1234 proc->minargs = argc;
1236 for (i = 0, op = argv; op != NULL; ++i) {
1237 if (op->type == OP_REST) {
1238 proc->vararg = 1;
1239 proc->minargs = i;
1240 break;
1243 proc->args[i] = xstrdup(op->v.var);
1245 next = op->next;
1246 free_op(op);
1247 op = next;
1249 assert(i == argc || (proc->vararg && i == proc->minargs));
1251 proc->body = body;
1253 TAILQ_INSERT_HEAD(&procs, proc, entry);
1256 void
1257 block_push(struct op *op)
1259 push(&blocks, op);
1262 struct proc *
1263 proc_by_name(const char *name)
1265 struct proc *p;
1267 TAILQ_FOREACH(p, &procs, entry) {
1268 if (!strcmp(p->name, name))
1269 return p;
1272 return NULL;
1275 void
1276 prepare_test(void)
1278 pushstack(&blocks);
1281 void
1282 test_done(int shouldfail, char *name, char *dir)
1284 struct test *test;
1286 test = xcalloc(1, sizeof(*test));
1287 test->shouldfail = shouldfail;
1288 test->name = name;
1289 test->dir = dir;
1290 test->body = finalize(&blocks, NULL);
1292 if (TAILQ_EMPTY(&tests))
1293 TAILQ_INSERT_HEAD(&tests, test, entry);
1294 else
1295 TAILQ_INSERT_TAIL(&tests, test, entry);
1297 ntests++;
1300 static int
1301 builtin_print(int argc)
1303 struct value v;
1304 int i;
1306 before_printing();
1308 for (i = argc; i > 0; --i) {
1309 peekn(i, &v);
1310 if (v.type == V_STR)
1311 printf("%s", v.v.str);
1312 else
1313 pp_val(&v);
1314 printf(" ");
1317 printf("\n");
1319 popvn(argc);
1321 return EVAL_OK;
1324 static int
1325 builtin_debug(int argc)
1327 if (debug)
1328 return builtin_print(argc);
1330 popvn(argc);
1331 return EVAL_OK;
1334 static int
1335 builtin_skip(int argc)
1337 return EVAL_SKIP;
1340 static int
1341 builtin_iota(int argc)
1343 struct value v;
1345 v.type = V_U16;
1346 if ((v.v.u16 = ++lasttag) == 255)
1347 v.v.u16 = ++lasttag;
1349 pushv(&v);
1350 return EVAL_OK;
1353 static int
1354 builtin_send(int argc)
1356 struct ibuf *buf;
1357 struct value v;
1358 uint32_t len;
1359 uint16_t slen;
1360 int i;
1362 check_for_output();
1365 * Compute the length of the packet. 4 is for the initial
1366 * length field
1368 len = 4;
1370 for (i = argc; i > 0; --i) {
1371 peekn(i, &v);
1372 switch (v.type) {
1373 case V_STR:
1374 len += 2; /* count */
1375 len += strlen(v.v.str);
1376 break;
1378 case V_U8:
1379 len += 1;
1380 break;
1382 case V_U16:
1383 len += 2;
1384 break;
1386 case V_U32:
1387 len += 4;
1388 break;
1390 default:
1391 before_printing();
1392 printf("%s: can't serialize ", __func__);
1393 pp_val(&v);
1394 printf("\n");
1395 return EVAL_ERR;
1399 if (len > UINT16_MAX) {
1400 before_printing();
1401 printf("%s: message size too long: got %d when max is %d\n",
1402 __func__, len, UINT16_MAX);
1403 return EVAL_ERR;
1406 if ((buf = imsg_create(&ibuf, IMSG_BUF, 0, 0, len)) == NULL)
1407 fatal("imsg_create(%d)", len);
1409 len = htole32(len);
1410 imsg_add(buf, &len, sizeof(len));
1412 for (i = argc; i > 0; --i) {
1413 peekn(i, &v);
1414 switch (v.type) {
1415 case V_STR:
1416 slen = strlen(v.v.str);
1417 slen = htole16(slen);
1418 imsg_add(buf, &slen, sizeof(slen));
1419 imsg_add(buf, v.v.str, strlen(v.v.str));
1420 break;
1422 case V_U8:
1423 imsg_add(buf, &v.v.u8, 1);
1424 break;
1426 case V_U16:
1427 v.v.u16 = htole16(v.v.u16);
1428 imsg_add(buf, &v.v.u16, 2);
1429 break;
1431 case V_U32:
1432 v.v.u32 = htole32(v.v.u32);
1433 imsg_add(buf, &v.v.u32, 4);
1434 break;
1438 imsg_close(&ibuf, buf);
1440 if (imsg_flush(&ibuf) == -1) {
1441 i = errno;
1442 before_printing();
1443 printf("%s: imsg_flush failed: %s\n", __func__, strerror(i));
1444 return EVAL_ERR;
1447 check_for_output();
1448 return EVAL_OK;
1451 static int
1452 builtin_recv(int argc)
1454 struct pollfd pfd;
1455 struct value v;
1456 struct imsg imsg;
1457 ssize_t n, datalen;
1458 int serrno;
1460 if (lastmsg != NULL) {
1461 free(lastmsg);
1462 lastmsg = NULL;
1465 pfd.fd = ibuf.fd;
1466 pfd.events = POLLIN;
1467 if (poll(&pfd, 1, INFTIM) == -1) {
1468 serrno = errno;
1469 before_printing();
1470 printf("%s: poll failed: %s\n", __func__, strerror(serrno));
1471 return EVAL_ERR;
1474 again:
1475 if ((n = imsg_read(&ibuf)) == -1) {
1476 if (errno == EAGAIN)
1477 goto again;
1478 fatal("imsg_read");
1480 if (n == 0) {
1481 disconnect:
1482 before_printing();
1483 printf("child disconnected\n");
1484 return EVAL_ERR;
1487 nextmessage:
1488 check_for_output();
1490 /* read only one message */
1491 if ((n = imsg_get(&ibuf, &imsg)) == -1)
1492 fatal("imsg_get");
1493 if (n == 0)
1494 goto disconnect;
1496 datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
1497 switch (imsg.hdr.type) {
1498 case IMSG_BUF:
1499 v.type = V_MSG;
1500 if ((v.v.msg.msg = malloc(datalen)) == NULL)
1501 fatal("malloc");
1502 memcpy(v.v.msg.msg, imsg.data, datalen);
1503 v.v.msg.len = datalen;
1504 pushv(&v);
1505 imsg_free(&imsg);
1506 return EVAL_OK;
1508 case IMSG_CLOSE:
1509 before_printing();
1510 printf("subprocess closed the connection\n");
1511 imsg_free(&imsg);
1512 return EVAL_ERR;
1514 case IMSG_MSIZE:
1515 imsg_free(&imsg);
1516 goto nextmessage;
1518 default:
1519 before_printing();
1520 printf("got unknown message from subprocess: %d\n",
1521 imsg.hdr.type);
1522 imsg_free(&imsg);
1523 return EVAL_ERR;
1527 static pid_t
1528 spawn_client_proc(void)
1530 const char *argv[4];
1531 int p[2], out[2], argc = 0;
1532 pid_t pid;
1534 if (child_out != -1)
1535 close(child_out);
1537 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1538 PF_UNSPEC, p) == -1)
1539 fatal("socketpair");
1541 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1542 PF_UNSPEC, out) == -1)
1543 fatal("socketpair");
1545 switch (pid = fork()) {
1546 case -1:
1547 fatal("cannot fork");
1548 case 0:
1549 break;
1550 default:
1551 close(p[1]);
1552 close(out[1]);
1553 child_out = out[0];
1554 if (ibuf_inuse) {
1555 msgbuf_clear(&ibuf.w);
1556 close(ibuf.fd);
1558 imsg_init(&ibuf, p[0]);
1559 ibuf_inuse = 1;
1560 return pid;
1563 close(p[0]);
1564 close(out[0]);
1566 if (dup2(out[1], 1) == -1 ||
1567 dup2(out[1], 2) == -1)
1568 fatal("dup2");
1570 if (p[1] != 3) {
1571 if (dup2(p[1], 3) == -1)
1572 fatal("cannot setup imsg fd");
1573 } else if (fcntl(F_SETFD, 0) == -1)
1574 fatal("cannot setup imsg fd");
1576 argv[argc++] = argv0;
1577 argv[argc++] = "-Tc";
1579 #if DEBUG
1580 argv[argc++] = "-v";
1581 #endif
1583 argv[argc++] = NULL;
1585 execvp(argv0, (char *const *)argv);
1586 fatal("execvp");
1589 static void
1590 prepare_child_for_test(struct test *t)
1592 struct passwd *pw;
1593 struct stat sb;
1595 if (stat(t->dir, &sb) == -1)
1596 fatal("stat(\"%s\")", t->dir);
1598 if ((pw = getpwuid(sb.st_uid)) == NULL)
1599 fatal("getpwuid(%d)", sb.st_uid);
1601 imsg_compose(&ibuf, IMSG_AUTH, 0, 0, -1,
1602 pw->pw_name, strlen(pw->pw_name)+1);
1603 imsg_compose(&ibuf, IMSG_AUTH_DIR, 0, 0, -1,
1604 t->dir, strlen(t->dir)+1);
1606 if (imsg_flush(&ibuf) == -1)
1607 fatal("imsg_flush");
1610 static int
1611 run_test(struct test *t)
1613 pid_t pid;
1614 int ret;
1616 #if DEBUG
1617 before_printing();
1618 puts("=====================");
1619 pp_block(t->body);
1620 puts("=====================");
1621 #endif
1623 if (stackh != 0)
1624 popvn(stackh);
1626 if (t->body == NULL) {
1627 before_printing();
1628 printf("no instructions, skipping...\n");
1629 return EVAL_SKIP;
1632 pid = spawn_client_proc();
1633 prepare_child_for_test(t);
1634 ret = eval(t->body);
1636 imsg_compose(&ibuf, IMSG_CONN_GONE, 0, 0, -1, NULL, 0);
1637 imsg_flush(&ibuf);
1639 while (waitpid(pid, NULL, 0) != pid)
1640 ; /* nop */
1642 check_for_output();
1644 if (t->shouldfail) {
1645 if (ret == EVAL_OK) {
1646 before_printing();
1647 printf("test was expected to fail\n");
1648 return EVAL_ERR;
1649 } else if (ret == EVAL_ERR)
1650 return EVAL_OK;
1653 return ret;
1656 int
1657 main(int argc, char **argv)
1659 struct test *t;
1660 int ch, i, r, passed = 0, failed = 0, skipped = 0;
1661 int runclient = 0;
1662 const char *pat = NULL;
1663 regex_t reg;
1665 assert(argv0 = argv[0]);
1667 signal(SIGPIPE, SIG_IGN);
1669 log_init(1, LOG_DAEMON);
1670 log_setverbose(1);
1672 /* prepare the global env */
1673 pushenv();
1675 add_builtin_proc("print", builtin_print, 1, 1);
1676 add_builtin_proc("debug", builtin_debug, 1, 1);
1677 add_builtin_proc("skip", builtin_skip, 0, 0);
1678 add_builtin_proc("iota", builtin_iota, 0, 0);
1679 add_builtin_proc("send", builtin_send, 2, 1);
1680 add_builtin_proc("recv", builtin_recv, 0, 0);
1682 while ((ch = getopt(argc, argv, "nT:vx:")) != -1) {
1683 switch (ch) {
1684 case 'n':
1685 syntaxcheck = 1;
1686 break;
1687 case 'T':
1688 assert(*optarg == 'c');
1689 runclient = 1;
1690 break;
1691 case 'v':
1692 debug = 1;
1693 break;
1694 case 'x':
1695 pat = optarg;
1696 break;
1697 default:
1698 fprintf(stderr, "Usage: %s [-nv] [files...]\n",
1699 *argv);
1700 exit(1);
1703 argc -= optind;
1704 argv += optind;
1706 if (runclient)
1707 client(1, debug);
1709 if (pat == NULL)
1710 pat = ".*";
1712 if (regcomp(&reg, pat, REG_ICASE | REG_NOSUB) != 0)
1713 fatalx("invalid regexp: %s", pat);
1715 for (i = 0; i < argc; ++i)
1716 loadfile(argv[i]);
1718 if (syntaxcheck) {
1719 fprintf(stderr, "files OK\n");
1720 return 0;
1723 /* Check for root privileges. */
1724 if (geteuid())
1725 fatalx("need root privileges");
1727 i = 0;
1728 TAILQ_FOREACH(t, &tests, entry) {
1729 if (regexec(&reg, t->name, 0, NULL, 0) != 0)
1730 continue;
1732 printf("===> [%d/%d] running test \"%s\"... ", i+1, ntests,
1733 t->name);
1734 fflush(stdout);
1736 filler = "\n";
1737 r = run_test(t);
1738 if (filler == NULL)
1739 printf("=> test ");
1741 switch (r) {
1742 case EVAL_OK:
1743 printf("passed\n");
1744 passed++;
1745 break;
1746 case EVAL_ERR:
1747 failed++;
1748 printf("failed\n");
1749 break;
1750 case EVAL_SKIP:
1751 printf("skipped\n");
1752 skipped++;
1753 break;
1756 if (filler == NULL)
1757 printf("\n");
1758 i++;
1761 printf("\n");
1762 printf("%d/%d passed (%d skipped and %d failed)\n",
1763 passed, i, skipped, failed);
1765 popenv();
1766 free(lastmsg);
1767 regfree(&reg);
1769 return failed != 0;