Blob


1 /*
2 * Copyright (c) 2021, 2022 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 <errno.h>
25 #include <fcntl.h>
26 #include <inttypes.h>
27 #include <poll.h>
28 #include <pwd.h>
29 #include <regex.h>
30 #include <signal.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <syslog.h>
35 #include <unistd.h>
37 #include "client.h"
38 #include "kami.h"
39 #include "kamid.h"
40 #include "log.h"
41 #include "script.h"
42 #include "utils.h"
44 #define DEBUG 0
46 int verbose;
48 static const char *argv0;
49 static const char *dir;
50 static uid_t uid;
52 static uint8_t *lastmsg;
54 static struct imsgbuf ibuf;
55 static int ibuf_inuse;
56 static int child_out = -1;
58 static struct procs procs = TAILQ_HEAD_INITIALIZER(procs);
59 static struct tests tests = TAILQ_HEAD_INITIALIZER(tests);
61 static int ntests;
63 static struct opstacks blocks = TAILQ_HEAD_INITIALIZER(blocks);
64 static struct opstacks args = TAILQ_HEAD_INITIALIZER(args);
66 #define STACK_HEIGHT 64
67 static struct value vstack[STACK_HEIGHT];
68 static int stackh;
70 static struct envs envs = TAILQ_HEAD_INITIALIZER(envs);
72 static const struct value v_false = {.type = V_NUM, .v = {.num = 0}};
73 static const struct value v_true = {.type = V_NUM, .v = {.num = 1}};
75 static uint8_t lasttag;
77 static int debug;
78 static int syntaxcheck;
80 static const char *filler;
82 static inline void
83 before_printing(void)
84 {
85 if (filler != NULL) {
86 printf("%s", filler);
87 filler = NULL;
88 }
89 }
91 static inline void
92 check_for_output(void)
93 {
94 static char buf[BUFSIZ];
95 struct pollfd pfd;
96 ssize_t r;
98 pfd.fd = child_out;
99 pfd.events = POLLIN;
100 if (poll(&pfd, 1, 0) == -1)
101 fatal("poll");
103 if (!(pfd.revents & POLLIN))
104 return;
106 for (;;) {
107 if ((r = read(child_out, buf, sizeof(buf))) == -1) {
108 if (errno == EAGAIN)
109 break;
110 fatal("read");
112 if (r == 0)
113 break;
114 before_printing();
115 fwrite(buf, 1, r, stdout);
119 static inline void
120 peekn(int depth, struct value *v)
122 if (depth > stackh)
123 errx(1, "can't peek the stack at %d: underflow",
124 depth);
125 memcpy(v, &vstack[stackh - depth], sizeof(*v));
127 #if DEBUG
128 printf("peeking(%d) ", depth); pp_val(v); printf("\n");
129 #endif
132 static inline void
133 popv(struct value *v)
135 if (stackh == 0)
136 errx(1, "can't pop the stack: underflow");
137 memcpy(v, &vstack[--stackh], sizeof(*v));
139 #if DEBUG
140 printf("popping "); pp_val(v); printf("\n");
141 #endif
144 static inline void
145 popvn(int n)
147 struct value v;
149 while (n-- > 0)
150 popv(&v);
153 static inline void
154 pushv(const struct value *v)
156 if (stackh == STACK_HEIGHT)
157 errx(1, "can't push the stack: overflow");
159 #if DEBUG
160 printf("pushing "); pp_val(v); printf("\n");
161 #endif
163 memcpy(&vstack[stackh++], v, sizeof(*v));
166 static inline void
167 pushbool(int n)
169 pushv(n ? &v_true : &v_false);
172 static inline void
173 pushnum(int64_t n)
175 struct value v;
177 v.type = V_NUM;
178 v.v.num = n;
179 pushv(&v);
182 static inline struct opstack *
183 pushstack(struct opstacks *stack)
185 struct opstack *ops;
187 ops = xcalloc(1, sizeof(*ops));
188 TAILQ_INSERT_HEAD(stack, ops, entry);
189 return ops;
192 static inline struct opstack *
193 peek(struct opstacks *stack)
195 if (TAILQ_EMPTY(stack))
196 errx(1, "%s: args underflow", __func__);
198 return TAILQ_FIRST(stack);
201 static inline struct op *
202 finalize(struct opstacks *stack, int *argc)
204 struct opstack *ops;
205 struct op *op;
207 if (TAILQ_EMPTY(stack))
208 errx(1, "%s: args underflow", __func__);
210 ops = peek(stack);
211 TAILQ_REMOVE(&args, ops, entry);
212 op = ops->base.next;
214 if (argc != NULL)
215 *argc = ops->counter;
217 free(ops);
218 return op;
221 static inline void
222 push(struct opstacks *stack, struct op *op)
224 struct opstack *ops;
226 ops = peek(stack);
227 if (ops->last == NULL) {
228 ops->base.next = op;
229 ops->last = op;
230 } else {
231 ops->last->next = op;
232 ops->last = op;
235 ops->counter++;
238 static inline void
239 pushenv(void)
241 struct env *e;
243 e = xcalloc(1, sizeof(*e));
244 TAILQ_INSERT_HEAD(&envs, e, entry);
247 static inline struct env *
248 currentenv(void)
250 assert(!TAILQ_EMPTY(&envs));
251 return TAILQ_FIRST(&envs);
254 static void
255 popenv(void)
257 struct env *e;
258 struct binding *b, *tb;
260 e = currentenv();
261 TAILQ_REMOVE(&envs, e, entry);
263 TAILQ_FOREACH_SAFE(b, &e->bindings, entry, tb)
264 free(b);
266 free(e);
269 static inline int
270 setvar(char *sym, struct op *op)
272 struct binding *b;
273 struct env *e;
274 int ret, height;
276 height = stackh;
277 if ((ret = eval(op)) != EVAL_OK)
278 return ret;
280 if (stackh != height + 1) {
281 before_printing();
282 printf("trying to assign to `%s' a void value: ", sym);
283 pp_op(op);
284 printf("\n");
285 return EVAL_ERR;
288 b = xcalloc(1, sizeof(*b));
289 b->name = sym;
290 popv(&b->val);
292 e = TAILQ_FIRST(&envs);
293 TAILQ_INSERT_HEAD(&e->bindings, b, entry);
295 return EVAL_OK;
298 static inline void
299 setvar_raw(char *sym, struct op *op)
301 struct binding *b;
302 struct env *e;
304 b = xcalloc(1, sizeof(*b));
305 b->name = sym;
306 b->raw = op;
308 e = TAILQ_FIRST(&envs);
309 TAILQ_INSERT_HEAD(&e->bindings, b, entry);
312 static inline int
313 getvar(const char *sym, struct value *v)
315 struct env *e;
316 struct binding *b;
318 TAILQ_FOREACH(e, &envs, entry) {
319 TAILQ_FOREACH(b, &e->bindings, entry) {
320 if (!strcmp(sym, b->name)) {
321 memcpy(v, &b->val, sizeof(*v));
322 return EVAL_OK;
327 before_printing();
328 fprintf(stderr, "unbound variable %s\n", sym);
329 return EVAL_ERR;
332 static inline int
333 getvar_raw(const char *sym, struct op **raw)
335 struct env *e;
336 struct binding *b;
338 TAILQ_FOREACH(e, &envs, entry) {
339 TAILQ_FOREACH(b, &e->bindings, entry) {
340 if (!strcmp(sym, b->name)) {
341 *raw = b->raw;
342 return EVAL_OK;
347 return EVAL_ERR;
350 int
351 global_set(char *sym, struct op *op)
353 struct binding *b;
354 struct env *e;
356 /* TODO: check for duplicates */
358 if (op->type != OP_LITERAL &&
359 (op->type == OP_CAST && op->v.cast.expr->type != OP_LITERAL))
360 return 0;
362 b = xcalloc(1, sizeof(*b));
363 b->name = sym;
365 /* it's only a cast on a literal! */
366 if (op->type == OP_CAST) {
367 if (eval(op) != EVAL_OK) {
368 free(b);
369 return 0;
371 popv(&b->val);
372 } else
373 memcpy(&b->val, &op->v.literal, sizeof(b->val));
375 e = TAILQ_LAST(&envs, envs);
376 TAILQ_INSERT_HEAD(&e->bindings, b, entry);
378 return 1;
381 struct op *
382 newop(int type)
384 struct op *op;
386 op = xcalloc(1, sizeof(*op));
387 op->type = type;
389 return op;
392 void
393 free_op_rec(struct op *op)
395 struct op *n;
397 while (op != NULL) {
398 n = op->next;
399 free_op(op);
400 op = n;
404 void
405 free_op(struct op *op)
407 if (op == NULL)
408 return;
410 switch (op->type) {
411 case OP_REST:
412 case OP_LITERAL:
413 case OP_VARGS:
414 break;
415 case OP_ASSIGN:
416 free(op->v.assign.name);
417 free_op_rec(op->v.assign.expr);
418 break;
419 case OP_ASSERT:
420 free_op_rec(op->v.assert);
421 break;
422 case OP_FUNCALL:
423 free_op_rec(op->v.funcall.argv);
424 break;
425 case OP_VAR:
426 free(op->v.var);
427 break;
428 case OP_CAST:
429 free_op_rec(op->v.cast.expr);
430 break;
431 case OP_CMP_EQ:
432 case OP_CMP_LEQ:
433 free_op_rec(op->v.bin_cmp.a);
434 free_op_rec(op->v.bin_cmp.b);
435 break;
436 case OP_FACCESS:
437 free_op_rec(op->v.faccess.expr);
438 free(op->v.faccess.field);
439 break;
440 case OP_SFAIL:
441 free(op->v.sfail.msg);
442 free_op_rec(op->v.sfail.expr);
443 break;
444 default:
445 /* unreachable */
446 abort();
449 free(op);
452 struct op *
453 op_rest(void)
455 return newop(OP_REST);
458 struct op *
459 op_assign(char *sym, struct op *expr)
461 struct op *op;
463 op = newop(OP_ASSIGN);
464 op->v.assign.name = sym;
465 op->v.assign.expr = expr;
467 return op;
470 struct op *
471 op_assert(struct op *expr)
473 struct op *op;
475 op = newop(OP_ASSERT);
476 op->v.assert = expr;
478 return op;
481 struct op *
482 op_var(char *sym)
484 struct op *op;
486 op = newop(OP_VAR);
487 op->v.var = sym;
489 return op;
492 struct op *
493 op_lit_str(char *str)
495 struct op *op;
497 op = newop(OP_LITERAL);
498 op->v.literal.type = V_STR;
499 op->v.literal.v.str = str;
501 return op;
504 struct op *
505 op_lit_num(uint64_t n)
507 struct op *op;
509 op = newop(OP_LITERAL);
510 op->v.literal.type = V_NUM;
511 op->v.literal.v.num = n;
513 return op;
516 struct op *
517 op_cmp_eq(struct op *a, struct op *b)
519 struct op *op;
521 op = newop(OP_CMP_EQ);
522 op->v.bin_cmp.a = a;
523 op->v.bin_cmp.b = b;
525 return op;
528 struct op *
529 op_cmp_leq(struct op *a, struct op *b)
531 struct op *op;
533 op = newop(OP_CMP_LEQ);
534 op->v.bin_cmp.a = a;
535 op->v.bin_cmp.b = b;
537 return op;
540 struct op *
541 op_cast(struct op *expr, int totype)
543 struct op *op;
545 op = newop(OP_CAST);
546 op->v.cast.expr = expr;
547 op->v.cast.totype = totype;
549 return op;
552 struct op *
553 op_faccess(struct op *expr, char *field)
555 struct op *op;
557 op = newop(OP_FACCESS);
558 op->v.faccess.expr = expr;
559 op->v.faccess.field = field;
561 return op;
564 struct op *
565 op_sfail(struct op *expr, char *msg)
567 struct op *op;
569 op = newop(OP_SFAIL);
570 op->v.sfail.expr = expr;
571 op->v.sfail.msg = msg;
573 return op;
576 struct op *
577 op_vargs(void)
579 struct op *op;
581 op = newop(OP_VARGS);
583 return op;
586 void
587 ppf_val(FILE *f, const struct value *val)
589 size_t i;
591 switch (val->type) {
592 case V_SYM:
593 fprintf(f, "%s", val->v.str);
594 break;
595 case V_STR:
596 fprintf(f, "\"%s\"", val->v.str);
597 break;
598 case V_NUM:
599 fprintf(f, "%"PRIi64, val->v.num);
600 break;
601 case V_U8:
602 fprintf(f, "%"PRIu8, val->v.u8);
603 break;
604 case V_U16:
605 fprintf(f, "%"PRIu16, val->v.u16);
606 break;
607 case V_U32:
608 fprintf(f, "%"PRIu32, val->v.u32);
609 break;
610 case V_MSG:
611 fprintf(f, "(");
612 for (i = 0; i < val->v.msg.len; ++i)
613 fprintf(f, "%x%s", val->v.msg.msg[i],
614 i == val->v.msg.len-1 ? "" : " ");
615 fprintf(f, ")");
616 break;
617 case V_QIDVEC:
618 fprintf(f, "qids[n=%zu]", val->v.qidvec.len);
619 break;
620 default:
621 fprintf(f, "<unknown value>");
622 break;
626 void
627 pp_val(const struct value *val)
629 ppf_val(stdout, val);
632 const char *
633 val_type(struct value *v)
635 switch (v->type) {
636 case V_SYM: return "symbol";
637 case V_STR: return "string";
638 case V_NUM: return "number";
639 case V_MSG: return "message";
640 case V_QID: return "qid";
641 case V_U8: return "u8";
642 case V_U16: return "u16";
643 case V_U32: return "u32";
644 default: return "unknown";
648 int
649 val_trueish(struct value *a)
651 if (val_isnum(a))
652 return val_tonum(a);
653 return 1;
656 int
657 val_isnum(struct value *a)
659 return a->type == V_NUM
660 || a->type == V_U8
661 || a->type == V_U16
662 || a->type == V_U32;
665 int64_t
666 val_tonum(struct value *a)
668 switch (a->type) {
669 case V_NUM: return a->v.num;
670 case V_U8: return a->v.u8;
671 case V_U16: return a->v.u16;
672 case V_U32: return a->v.u32;
673 default:
674 before_printing();
675 fprintf(stderr, "%s: given value is not a number\n", __func__);
676 abort();
680 int
681 val_eq(struct value *a, struct value *b)
683 if (val_isnum(a) && val_isnum(b))
684 return val_tonum(a) == val_tonum(b);
686 if (a->type != b->type)
687 return 0;
689 switch (a->type) {
690 case V_STR:
691 case V_SYM:
692 return !strcmp(a->v.str, b->v.str);
695 return 0;
698 int
699 val_leq(struct value *a, struct value *b)
701 if (val_isnum(a) && val_isnum(b))
702 return val_tonum(a) <= val_tonum(b);
703 return 0;
706 static inline const char *
707 pp_totype(int totype)
709 /*
710 * Not all of these are valid cast type thought, including
711 * every possibility only to aid debugging.
712 */
713 switch (totype) {
714 case V_STR: return "str";
715 case V_SYM: return "sym";
716 case V_NUM: return "num";
717 case V_QID: return "qid";
718 case V_U8: return "u8";
719 case V_U16: return "u16";
720 case V_U32: return "u32";
721 default: return "unknown";
725 int
726 val_cast(struct value *a, int totype)
728 int64_t v;
730 #define NUMCAST(val, t, c, totype, max) do { \
731 if (val > max) { \
732 before_printing(); \
733 fprintf(stderr, "can't cast %"PRIu64 \
734 " to %s\n", val, pp_totype(totype)); \
735 return EVAL_ERR; \
736 } \
737 a->type = totype; \
738 a->v.t = (c)val; \
739 return EVAL_OK; \
740 } while (0)
742 if (a->type == totype)
743 return EVAL_OK;
745 if (!val_isnum(a)) {
746 before_printing();
747 fprintf(stderr, "can't cast ");
748 ppf_val(stderr, a);
749 fprintf(stderr, " to type %s\n", pp_totype(totype));
750 return EVAL_ERR;
753 v = a->v.num;
754 switch (totype) {
755 case V_U8: NUMCAST(v, u8, uint8_t, totype, UINT8_MAX);
756 case V_U16: NUMCAST(v, u16, uint16_t, totype, UINT16_MAX);
757 case V_U32: NUMCAST(v, u32, uint32_t, totype, UINT32_MAX);
758 default:
759 before_printing();
760 fprintf(stderr, "can't cast %"PRIu64" to %s\n",
761 v, pp_totype(totype));
762 return EVAL_ERR;
765 #undef NUMCAST
768 int
769 val_faccess(struct value *a, const char *field, struct value *ret)
771 uint8_t mtype;
772 uint16_t len;
773 const char *errstr;
775 #define MSGTYPE(m) *(m.msg + 4) /* skip the length */
777 switch (a->type) {
778 case V_QID:
779 /* TODO: add path. needs uint64_t values thought! */
780 if (!strcmp(field, "vers")) {
781 ret->type = V_U32;
782 memcpy(&ret->v.u32, a->v.qid+1, 4);
783 return EVAL_OK;
784 } else if (!strcmp(field, "type")) {
785 ret->type = V_U8;
786 ret->v.u8 = *a->v.qid;
787 return EVAL_OK;
789 break;
791 case V_MSG:
792 mtype = MSGTYPE(a->v.msg);
793 if (!strcmp(field, "type")) {
794 ret->type = V_U8;
795 ret->v.u8 = MSGTYPE(a->v.msg);
796 return EVAL_OK;
797 } else if (!strcmp(field, "tag")) {
798 ret->type = V_U16;
799 memcpy(&ret->v.u16, &a->v.msg.msg[5], 2);
800 ret->v.u16 = le16toh(ret->v.u16);
801 return EVAL_OK;
802 } else if (!strcmp(field, "msize") && mtype == Rversion) {
803 ret->type = V_U32;
804 memcpy(&ret->v.u32, &a->v.msg.msg[7], 4);
805 ret->v.u32 = le32toh(ret->v.u32);
806 return EVAL_OK;
807 } else if (!strcmp(field, "qid") && mtype == Rattach) {
808 ret->type = V_QID;
809 memcpy(&ret->v.qid, &a->v.msg.msg[7], QIDSIZE);
810 return EVAL_OK;
811 } else if (!strcmp(field, "nwqid") && mtype == Rwalk) {
812 ret->type = V_U16;
813 memcpy(&ret->v.u16, &a->v.msg.msg[7], 2);
814 ret->v.u16 = le16toh(ret->v.u16);
815 return EVAL_OK;
816 } else if (!strcmp(field, "wqid") && mtype == Rwalk) {
817 ret->type = V_QIDVEC;
818 ret->v.qidvec.start = &a->v.msg.msg[9];
819 memcpy(&len, &a->v.msg.msg[7], 2);
820 len = le16toh(len);
821 ret->v.qidvec.len = len;
822 return EVAL_OK;
824 break;
826 case V_QIDVEC:
827 len = strtonum(field, 0, MAXWELEM, &errstr);
828 if (errstr != NULL) {
829 before_printing();
830 printf("can't access qid #%s: %s\n", field, errstr);
831 return EVAL_ERR;
834 if (len >= a->v.qidvec.len) {
835 before_printing();
836 printf("can't access qid #%d: out-of-bound "
837 "(max %zu)\n", len, a->v.qidvec.len);
838 return EVAL_ERR;
841 ret->type = V_QID;
842 memcpy(&ret->v.qid, a->v.qidvec.start + len * QIDSIZE,
843 QIDSIZE);
845 return EVAL_OK;
847 default:
848 break;
851 before_printing();
852 printf("can't access field `%s' on type %s (", field, val_type(a));
853 pp_val(a);
854 printf(")\n");
855 return EVAL_ERR;
857 #undef MSGTYPE
860 void
861 pp_op(struct op *op)
863 struct op *aux;
865 switch (op->type) {
866 case OP_REST:
867 printf("...");
868 break;
869 case OP_ASSIGN:
870 printf("%s = ", op->v.assign.name);
871 pp_op(op->v.assign.expr);
872 break;
873 case OP_ASSERT:
874 printf("assert ");
875 pp_op(op->v.assert);
876 break;
877 case OP_FUNCALL:
878 printf("funcall %s(", op->v.funcall.proc->name);
879 for (aux = op->v.funcall.argv; aux != NULL; aux = aux->next) {
880 pp_op(aux);
881 if (aux->next != NULL)
882 printf(", ");
884 printf(")");
885 break;
886 case OP_LITERAL:
887 pp_val(&op->v.literal);
888 break;
889 case OP_VAR:
890 printf("%s", op->v.var);
891 break;
892 case OP_CAST:
893 pp_op(op->v.cast.expr);
894 printf(":");
895 switch (op->v.cast.totype) {
896 case V_U8: printf("u8"); break;
897 case V_U16: printf("u16"); break;
898 case V_U32: printf("u32"); break;
899 case V_STR: printf("str"); break;
900 default: printf("???"); break;
902 break;
903 case OP_CMP_EQ:
904 pp_op(op->v.bin_cmp.a);
905 printf(" == ");
906 pp_op(op->v.bin_cmp.b);
907 break;
908 case OP_CMP_LEQ:
909 pp_op(op->v.bin_cmp.a);
910 printf(" <= ");
911 pp_op(op->v.bin_cmp.b);
912 break;
913 case OP_FACCESS:
914 pp_op(op->v.faccess.expr);
915 printf(".%s", op->v.faccess.field);
916 break;
917 case OP_SFAIL:
918 printf("should-fail ");
919 pp_op(op->v.sfail.expr);
920 if (op->v.sfail.msg != NULL)
921 printf(": \"%s\"", op->v.sfail.msg);
922 break;
923 case OP_VARGS:
924 printf("vargs");
925 break;
926 default:
927 printf(" ???[%d] ", op->type);
931 void
932 pp_block(struct op *op)
934 while (op != NULL) {
935 printf("> ");
936 pp_op(op);
937 printf("\n");
939 op = op->next;
943 int
944 eval(struct op *op)
946 struct value a, b;
947 struct proc *proc;
948 struct op *t, *tnext;
949 int i, ret;
951 #if DEBUG
952 pp_op(op);
953 printf("\n");
954 #endif
956 switch (op->type) {
957 case OP_REST:
958 /*
959 * Try to load the rest argument. Note that it can be
960 * empty!
961 */
962 if ((ret = getvar_raw("...", &t)) == EVAL_OK)
963 if ((ret = eval(t)) != EVAL_OK)
964 return ret;
965 break;
967 case OP_ASSIGN:
968 ret = setvar(op->v.assign.name, op->v.assign.expr);
969 if (ret != EVAL_OK)
970 return ret;
971 break;
973 case OP_ASSERT:
974 if ((ret = eval(op->v.assert)) != EVAL_OK)
975 return ret;
976 popv(&a);
977 if (!val_trueish(&a)) {
978 before_printing();
979 printf("assertion failed: ");
980 pp_op(op->v.assert);
981 printf("\n");
982 return EVAL_ERR;
984 break;
986 case OP_FUNCALL:
987 /* assume airity matches */
989 proc = op->v.funcall.proc;
990 if (proc->nativefn != NULL) {
991 /*
992 * Push arguments on the stack for builtin
993 * functions. Counting the height of the
994 * stack is done to compute the correct number
995 * in the vararg case. argc only counts the
996 * "syntactical" arguments, i.e. foo(x, ...)
997 * has argc == 2, but at runtime argc may be
998 * 1, 2 or a greater number!
999 */
1001 i = stackh;
1002 t = op->v.funcall.argv;
1003 if (t != NULL && (ret = eval(t)) != EVAL_OK)
1004 return ret;
1005 i = stackh - i;
1007 assert(i >= 0);
1009 if ((ret = proc->nativefn(i))
1010 != EVAL_OK)
1011 return ret;
1012 } else {
1013 if (proc->body == NULL) {
1014 before_printing();
1015 printf("warn: calling the empty proc `%s'\n",
1016 proc->name);
1017 break;
1020 pushenv();
1022 for (t = op->v.funcall.argv, i = 0;
1023 t != NULL;
1024 t = t->next, i++) {
1026 * Push a pseudo variable `...' (and
1027 * don't evaluate it) in the vararg
1028 * case. A special case is when the
1029 * variable is itself `...'.
1031 if (proc->vararg && i == proc->minargs) {
1032 if (t->type != OP_REST)
1033 setvar_raw(xstrdup("..."), t);
1034 break;
1038 * The arguments are a linked list of
1039 * ops. Setvar will call eval that
1040 * will evaluate *all* the arguments.
1041 * The dance here that sets next to
1042 * NULL and then restores it is to
1043 * avoid this behaviour.
1045 tnext = t->next;
1046 t->next = NULL;
1047 ret = setvar(proc->args[i], t);
1048 t->next = tnext;
1050 if (ret != EVAL_OK)
1051 return ret;
1054 if ((ret = eval(proc->body)) != EVAL_OK)
1055 return ret;
1057 popenv();
1060 break;
1062 case OP_LITERAL:
1063 pushv(&op->v.literal);
1064 break;
1066 case OP_VAR:
1067 if ((ret = getvar(op->v.var, &a)) != EVAL_OK)
1068 return ret;
1069 pushv(&a);
1070 break;
1072 case OP_CAST:
1073 if ((ret = eval(op->v.cast.expr)) != EVAL_OK)
1074 return ret;
1075 popv(&a);
1076 if ((ret = val_cast(&a, op->v.cast.totype)) != EVAL_OK)
1077 return ret;
1078 pushv(&a);
1079 break;
1081 case OP_CMP_EQ:
1082 if ((ret = eval(op->v.bin_cmp.a)) != EVAL_OK)
1083 return ret;
1084 if ((ret = eval(op->v.bin_cmp.b)) != EVAL_OK)
1085 return ret;
1087 popv(&b);
1088 popv(&a);
1089 pushbool(val_eq(&a, &b));
1090 break;
1092 case OP_CMP_LEQ:
1093 if ((ret = eval(op->v.bin_cmp.a)) != EVAL_OK)
1094 return ret;
1095 if ((ret = eval(op->v.bin_cmp.b)) != EVAL_OK)
1096 return ret;
1098 popv(&b);
1099 popv(&a);
1100 pushbool(val_leq(&a, &b));
1101 break;
1103 case OP_FACCESS:
1104 if ((ret = eval(op->v.faccess.expr)) != EVAL_OK)
1105 return ret;
1106 popv(&a);
1107 if ((ret = val_faccess(&a, op->v.faccess.field, &b))
1108 != EVAL_OK)
1109 return ret;
1110 pushv(&b);
1111 break;
1113 case OP_SFAIL:
1114 if ((ret = eval(op->v.sfail.expr)) == EVAL_OK) {
1115 before_printing();
1116 printf("expecting failure");
1117 if (op->v.sfail.msg != NULL)
1118 printf(" \"%s\"", op->v.sfail.msg);
1119 printf("\n");
1120 printf("expression: ");
1121 pp_op(op->v.sfail.expr);
1122 printf("\n");
1123 return EVAL_ERR;
1125 if (ret == EVAL_SKIP)
1126 return ret;
1127 break;
1129 case OP_VARGS:
1130 if ((ret = getvar_raw("...", &t)) == EVAL_OK) {
1131 for (i = 0; t != NULL; t = t->next)
1132 i++;
1133 pushnum(i);
1134 } else
1135 pushnum(0);
1136 break;
1138 default:
1139 before_printing();
1140 fprintf(stderr, "invalid op, aborting.\n");
1141 abort();
1144 if (op->next)
1145 return eval(op->next);
1146 return EVAL_OK;
1149 void
1150 prepare_funcall(void)
1152 pushstack(&args);
1155 void
1156 push_arg(struct op *op)
1158 push(&args, op);
1161 struct op *
1162 op_funcall(struct proc *proc)
1164 struct op *op, *argv;
1165 int argc;
1167 argv = finalize(&args, &argc);
1169 op = newop(OP_FUNCALL);
1170 op->v.funcall.proc = proc;
1171 op->v.funcall.argv = argv;
1172 op->v.funcall.argc = argc;
1174 return op;
1177 void
1178 add_builtin_proc(const char *name, int (*fn)(int), int argc, int vararg)
1180 struct proc *proc;
1182 proc = xcalloc(1, sizeof(*proc));
1183 proc->name = xstrdup(name);
1184 proc->nativefn = fn;
1185 proc->minargs = argc;
1186 proc->vararg = vararg;
1188 TAILQ_INSERT_HEAD(&procs, proc, entry);
1191 void
1192 prepare_proc(void)
1194 pushstack(&args);
1197 int
1198 proc_setup_body(void)
1200 struct opstack *argv;
1201 struct op *op;
1202 int i;
1204 argv = peek(&args);
1205 for (i = 0, op = argv->base.next; op != NULL; i++) {
1207 * TODO: should free the whole list on error but..,
1208 * we're gonna exit real soon(tm)!
1210 if (op->type != OP_VAR && op->type != OP_REST)
1211 return 0;
1213 op = op->next;
1216 assert(i == argv->counter);
1217 pushstack(&blocks);
1218 return 1;
1221 void
1222 proc_done(char *name)
1224 struct proc *proc;
1225 struct op *op, *next, *argv, *body;
1226 int i, argc;
1228 argv = finalize(&args, &argc);
1229 body = finalize(&blocks, NULL);
1231 proc = xcalloc(1, sizeof(*proc));
1232 proc->name = name;
1233 proc->minargs = argc;
1235 for (i = 0, op = argv; op != NULL; ++i) {
1236 if (op->type == OP_REST) {
1237 proc->vararg = 1;
1238 proc->minargs = i;
1239 break;
1242 proc->args[i] = xstrdup(op->v.var);
1244 next = op->next;
1245 free_op(op);
1246 op = next;
1248 assert(i == argc || (proc->vararg && i == proc->minargs));
1250 proc->body = body;
1252 TAILQ_INSERT_HEAD(&procs, proc, entry);
1255 void
1256 block_push(struct op *op)
1258 push(&blocks, op);
1261 struct proc *
1262 proc_by_name(const char *name)
1264 struct proc *p;
1266 TAILQ_FOREACH(p, &procs, entry) {
1267 if (!strcmp(p->name, name))
1268 return p;
1271 return NULL;
1274 void
1275 prepare_test(void)
1277 pushstack(&blocks);
1280 void
1281 test_done(int shouldfail, char *name)
1283 struct test *test;
1285 test = xcalloc(1, sizeof(*test));
1286 test->shouldfail = shouldfail;
1287 test->name = name;
1288 test->body = finalize(&blocks, NULL);
1290 TAILQ_INSERT_TAIL(&tests, test, entry);
1292 ntests++;
1295 static int
1296 builtin_print(int argc)
1298 struct value v;
1299 int i;
1301 before_printing();
1303 for (i = argc; i > 0; --i) {
1304 peekn(i, &v);
1305 if (v.type == V_STR)
1306 printf("%s", v.v.str);
1307 else
1308 pp_val(&v);
1309 printf(" ");
1312 printf("\n");
1314 popvn(argc);
1316 return EVAL_OK;
1319 static int
1320 builtin_debug(int argc)
1322 if (debug)
1323 return builtin_print(argc);
1325 popvn(argc);
1326 return EVAL_OK;
1329 static int
1330 builtin_skip(int argc)
1332 return EVAL_SKIP;
1335 static int
1336 builtin_iota(int argc)
1338 struct value v;
1340 v.type = V_U16;
1341 if ((v.v.u16 = ++lasttag) == 255)
1342 v.v.u16 = ++lasttag;
1344 pushv(&v);
1345 return EVAL_OK;
1348 static int
1349 builtin_send(int argc)
1351 struct ibuf *buf;
1352 struct value v;
1353 uint32_t len;
1354 uint16_t slen;
1355 int i;
1357 check_for_output();
1360 * Compute the length of the packet. 4 is for the initial
1361 * length field
1363 len = 4;
1365 for (i = argc; i > 0; --i) {
1366 peekn(i, &v);
1367 switch (v.type) {
1368 case V_STR:
1369 len += 2; /* count */
1370 len += strlen(v.v.str);
1371 break;
1373 case V_U8:
1374 len += 1;
1375 break;
1377 case V_U16:
1378 len += 2;
1379 break;
1381 case V_U32:
1382 len += 4;
1383 break;
1385 default:
1386 before_printing();
1387 printf("%s: can't serialize ", __func__);
1388 pp_val(&v);
1389 printf("\n");
1390 return EVAL_ERR;
1394 if (len > UINT16_MAX) {
1395 before_printing();
1396 printf("%s: message size too long: got %d when max is %d\n",
1397 __func__, len, UINT16_MAX);
1398 return EVAL_ERR;
1401 if ((buf = imsg_create(&ibuf, IMSG_BUF, 0, 0, len)) == NULL)
1402 fatal("imsg_create(%d)", len);
1404 len = htole32(len);
1405 imsg_add(buf, &len, sizeof(len));
1407 for (i = argc; i > 0; --i) {
1408 peekn(i, &v);
1409 switch (v.type) {
1410 case V_STR:
1411 slen = strlen(v.v.str);
1412 slen = htole16(slen);
1413 imsg_add(buf, &slen, sizeof(slen));
1414 imsg_add(buf, v.v.str, strlen(v.v.str));
1415 break;
1417 case V_U8:
1418 imsg_add(buf, &v.v.u8, 1);
1419 break;
1421 case V_U16:
1422 v.v.u16 = htole16(v.v.u16);
1423 imsg_add(buf, &v.v.u16, 2);
1424 break;
1426 case V_U32:
1427 v.v.u32 = htole32(v.v.u32);
1428 imsg_add(buf, &v.v.u32, 4);
1429 break;
1433 imsg_close(&ibuf, buf);
1435 if (imsg_flush(&ibuf) == -1) {
1436 i = errno;
1437 before_printing();
1438 printf("%s: imsg_flush failed: %s\n", __func__, strerror(i));
1439 return EVAL_ERR;
1442 check_for_output();
1443 return EVAL_OK;
1446 static int
1447 builtin_recv(int argc)
1449 struct pollfd pfd;
1450 struct value v;
1451 struct imsg imsg;
1452 ssize_t n, datalen;
1453 int serrno, want_more = 0;
1455 if (lastmsg != NULL) {
1456 free(lastmsg);
1457 lastmsg = NULL;
1460 pfd.fd = ibuf.fd;
1461 pfd.events = POLLIN;
1462 again:
1463 if (poll(&pfd, 1, INFTIM) == -1) {
1464 serrno = errno;
1465 before_printing();
1466 printf("%s: poll failed: %s\n", __func__, strerror(serrno));
1467 return EVAL_ERR;
1470 if ((n = imsg_read(&ibuf)) == -1) {
1471 if (errno == EAGAIN)
1472 goto again;
1473 fatal("imsg_read");
1475 if (n == 0) {
1476 before_printing();
1477 printf("child disconnected\n");
1478 return EVAL_ERR;
1481 check_for_output();
1483 for (;;) {
1484 if ((n = imsg_get(&ibuf, &imsg)) == -1)
1485 fatal("imsg_get");
1486 if (n == 0)
1487 break;
1489 want_more = 0;
1490 datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
1491 switch (imsg.hdr.type) {
1492 case IMSG_BUF:
1493 v.type = V_MSG;
1494 if ((v.v.msg.msg = malloc(datalen)) == NULL)
1495 fatal("malloc");
1496 memcpy(v.v.msg.msg, imsg.data, datalen);
1497 v.v.msg.len = datalen;
1498 pushv(&v);
1499 imsg_free(&imsg);
1500 return EVAL_OK;
1502 case IMSG_CLOSE:
1503 before_printing();
1504 printf("subprocess closed the connection\n");
1505 imsg_free(&imsg);
1506 return EVAL_ERR;
1508 case IMSG_MSIZE:
1509 imsg_free(&imsg);
1510 want_more = 1;
1511 break;
1513 default:
1514 before_printing();
1515 printf("got unknown message from subprocess: %d\n",
1516 imsg.hdr.type);
1517 imsg_free(&imsg);
1518 return EVAL_ERR;
1522 if (want_more)
1523 goto again;
1525 fatalx("reached the end of %s\n", __func__);
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 kd_auth_proc rauth;
1596 if ((pw = getpwuid(uid)) == NULL)
1597 fatal("getpwuid(%d)", uid);
1599 memset(&rauth, 0, sizeof(rauth));
1600 strlcpy(rauth.uname, pw->pw_name, sizeof(rauth.uname));
1601 strlcpy(rauth.dir, dir, sizeof(rauth.dir));
1603 imsg_compose(&ibuf, IMSG_AUTH, 0, 0, -1,
1604 &rauth, sizeof(rauth));
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 stat sb;
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 if ((argv0 = argv[0]) == NULL)
1667 fatal("empty argv[0]");
1669 signal(SIGPIPE, SIG_IGN);
1671 log_init(1, LOG_DAEMON);
1672 log_setverbose(1);
1674 /* prepare the global env */
1675 pushenv();
1677 add_builtin_proc("print", builtin_print, 1, 1);
1678 add_builtin_proc("debug", builtin_debug, 1, 1);
1679 add_builtin_proc("skip", builtin_skip, 0, 0);
1680 add_builtin_proc("iota", builtin_iota, 0, 0);
1681 add_builtin_proc("send", builtin_send, 2, 1);
1682 add_builtin_proc("recv", builtin_recv, 0, 0);
1684 while ((ch = getopt(argc, argv, "nT:r:vx:")) != -1) {
1685 switch (ch) {
1686 case 'n':
1687 syntaxcheck = 1;
1688 break;
1689 case 'T':
1690 assert(*optarg == 'c');
1691 runclient = 1;
1692 break;
1693 case 'r':
1694 dir = optarg;
1695 break;
1696 case 'v':
1697 debug = 1;
1698 break;
1699 case 'x':
1700 pat = optarg;
1701 break;
1702 default:
1703 fprintf(stderr, "Usage: %s [-nv] [files...]\n",
1704 *argv);
1705 exit(1);
1708 argc -= optind;
1709 argv += optind;
1711 if (runclient)
1712 client(1, debug);
1714 if (dir == NULL)
1715 fatal("missing root test dir");
1717 if (stat(dir, &sb) == -1)
1718 fatal("stat(\"%s\")", dir);
1719 uid = sb.st_uid;
1721 if (pat == NULL)
1722 pat = ".*";
1724 if (regcomp(&reg, pat, REG_ICASE | REG_NOSUB) != 0)
1725 fatalx("invalid regexp: %s", pat);
1727 for (i = 0; i < argc; ++i)
1728 loadfile(argv[i]);
1730 if (syntaxcheck) {
1731 fprintf(stderr, "files OK\n");
1732 return 0;
1735 /* Check for root privileges. */
1736 if (geteuid())
1737 fatalx("need root privileges");
1739 i = 0;
1740 TAILQ_FOREACH(t, &tests, entry) {
1741 if (regexec(&reg, t->name, 0, NULL, 0) != 0)
1742 continue;
1744 printf("===> [%d/%d] running test \"%s\"... ", i+1, ntests,
1745 t->name);
1746 fflush(stdout);
1748 filler = "\n";
1749 r = run_test(t);
1750 if (filler == NULL)
1751 printf("=> test ");
1753 switch (r) {
1754 case EVAL_OK:
1755 printf("passed\n");
1756 passed++;
1757 break;
1758 case EVAL_ERR:
1759 failed++;
1760 printf("failed\n");
1761 break;
1762 case EVAL_SKIP:
1763 printf("skipped\n");
1764 skipped++;
1765 break;
1768 if (filler == NULL)
1769 printf("\n");
1770 i++;
1773 printf("\n");
1774 printf("%d/%d passed (%d skipped and %d failed)\n",
1775 passed, i, skipped, failed);
1777 popenv();
1778 free(lastmsg);
1779 regfree(&reg);
1781 return failed != 0;