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 <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 int verbose;
49 static const char *argv0;
50 static const char *dir;
51 static uid_t uid;
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 const struct value v_false = {.type = V_NUM, .v = {.num = 0}};
74 static const 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(const 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, const 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(const 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)
1284 struct test *test;
1286 test = xcalloc(1, sizeof(*test));
1287 test->shouldfail = shouldfail;
1288 test->name = name;
1289 test->body = finalize(&blocks, NULL);
1291 TAILQ_INSERT_TAIL(&tests, test, entry);
1293 ntests++;
1296 static int
1297 builtin_print(int argc)
1299 struct value v;
1300 int i;
1302 before_printing();
1304 for (i = argc; i > 0; --i) {
1305 peekn(i, &v);
1306 if (v.type == V_STR)
1307 printf("%s", v.v.str);
1308 else
1309 pp_val(&v);
1310 printf(" ");
1313 printf("\n");
1315 popvn(argc);
1317 return EVAL_OK;
1320 static int
1321 builtin_debug(int argc)
1323 if (debug)
1324 return builtin_print(argc);
1326 popvn(argc);
1327 return EVAL_OK;
1330 static int
1331 builtin_skip(int argc)
1333 return EVAL_SKIP;
1336 static int
1337 builtin_iota(int argc)
1339 struct value v;
1341 v.type = V_U16;
1342 if ((v.v.u16 = ++lasttag) == 255)
1343 v.v.u16 = ++lasttag;
1345 pushv(&v);
1346 return EVAL_OK;
1349 static int
1350 builtin_send(int argc)
1352 struct ibuf *buf;
1353 struct value v;
1354 uint32_t len;
1355 uint16_t slen;
1356 int i;
1358 check_for_output();
1361 * Compute the length of the packet. 4 is for the initial
1362 * length field
1364 len = 4;
1366 for (i = argc; i > 0; --i) {
1367 peekn(i, &v);
1368 switch (v.type) {
1369 case V_STR:
1370 len += 2; /* count */
1371 len += strlen(v.v.str);
1372 break;
1374 case V_U8:
1375 len += 1;
1376 break;
1378 case V_U16:
1379 len += 2;
1380 break;
1382 case V_U32:
1383 len += 4;
1384 break;
1386 default:
1387 before_printing();
1388 printf("%s: can't serialize ", __func__);
1389 pp_val(&v);
1390 printf("\n");
1391 return EVAL_ERR;
1395 if (len > UINT16_MAX) {
1396 before_printing();
1397 printf("%s: message size too long: got %d when max is %d\n",
1398 __func__, len, UINT16_MAX);
1399 return EVAL_ERR;
1402 if ((buf = imsg_create(&ibuf, IMSG_BUF, 0, 0, len)) == NULL)
1403 fatal("imsg_create(%d)", len);
1405 len = htole32(len);
1406 imsg_add(buf, &len, sizeof(len));
1408 for (i = argc; i > 0; --i) {
1409 peekn(i, &v);
1410 switch (v.type) {
1411 case V_STR:
1412 slen = strlen(v.v.str);
1413 slen = htole16(slen);
1414 imsg_add(buf, &slen, sizeof(slen));
1415 imsg_add(buf, v.v.str, strlen(v.v.str));
1416 break;
1418 case V_U8:
1419 imsg_add(buf, &v.v.u8, 1);
1420 break;
1422 case V_U16:
1423 v.v.u16 = htole16(v.v.u16);
1424 imsg_add(buf, &v.v.u16, 2);
1425 break;
1427 case V_U32:
1428 v.v.u32 = htole32(v.v.u32);
1429 imsg_add(buf, &v.v.u32, 4);
1430 break;
1434 imsg_close(&ibuf, buf);
1436 if (imsg_flush(&ibuf) == -1) {
1437 i = errno;
1438 before_printing();
1439 printf("%s: imsg_flush failed: %s\n", __func__, strerror(i));
1440 return EVAL_ERR;
1443 check_for_output();
1444 return EVAL_OK;
1447 static int
1448 builtin_recv(int argc)
1450 struct pollfd pfd;
1451 struct value v;
1452 struct imsg imsg;
1453 ssize_t n, datalen;
1454 int serrno, want_more = 0;
1456 if (lastmsg != NULL) {
1457 free(lastmsg);
1458 lastmsg = NULL;
1461 pfd.fd = ibuf.fd;
1462 pfd.events = POLLIN;
1463 again:
1464 if (poll(&pfd, 1, INFTIM) == -1) {
1465 serrno = errno;
1466 before_printing();
1467 printf("%s: poll failed: %s\n", __func__, strerror(serrno));
1468 return EVAL_ERR;
1471 if ((n = imsg_read(&ibuf)) == -1) {
1472 if (errno == EAGAIN)
1473 goto again;
1474 fatal("imsg_read");
1476 if (n == 0) {
1477 before_printing();
1478 printf("child disconnected\n");
1479 return EVAL_ERR;
1482 check_for_output();
1484 for (;;) {
1485 if ((n = imsg_get(&ibuf, &imsg)) == -1)
1486 fatal("imsg_get");
1487 if (n == 0)
1488 break;
1490 want_more = 0;
1491 datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
1492 switch (imsg.hdr.type) {
1493 case IMSG_BUF:
1494 v.type = V_MSG;
1495 if ((v.v.msg.msg = malloc(datalen)) == NULL)
1496 fatal("malloc");
1497 memcpy(v.v.msg.msg, imsg.data, datalen);
1498 v.v.msg.len = datalen;
1499 pushv(&v);
1500 imsg_free(&imsg);
1501 return EVAL_OK;
1503 case IMSG_CLOSE:
1504 before_printing();
1505 printf("subprocess closed the connection\n");
1506 imsg_free(&imsg);
1507 return EVAL_ERR;
1509 case IMSG_MSIZE:
1510 imsg_free(&imsg);
1511 want_more = 1;
1512 break;
1514 default:
1515 before_printing();
1516 printf("got unknown message from subprocess: %d\n",
1517 imsg.hdr.type);
1518 imsg_free(&imsg);
1519 return EVAL_ERR;
1523 if (want_more)
1524 goto again;
1526 fatalx("reached the end of %s\n", __func__);
1529 static pid_t
1530 spawn_client_proc(void)
1532 const char *argv[4];
1533 int p[2], out[2], argc = 0;
1534 pid_t pid;
1536 if (child_out != -1)
1537 close(child_out);
1539 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1540 PF_UNSPEC, p) == -1)
1541 fatal("socketpair");
1543 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1544 PF_UNSPEC, out) == -1)
1545 fatal("socketpair");
1547 switch (pid = fork()) {
1548 case -1:
1549 fatal("cannot fork");
1550 case 0:
1551 break;
1552 default:
1553 close(p[1]);
1554 close(out[1]);
1555 child_out = out[0];
1556 if (ibuf_inuse) {
1557 msgbuf_clear(&ibuf.w);
1558 close(ibuf.fd);
1560 imsg_init(&ibuf, p[0]);
1561 ibuf_inuse = 1;
1562 return pid;
1565 close(p[0]);
1566 close(out[0]);
1568 if (dup2(out[1], 1) == -1 ||
1569 dup2(out[1], 2) == -1)
1570 fatal("dup2");
1572 if (p[1] != 3) {
1573 if (dup2(p[1], 3) == -1)
1574 fatal("cannot setup imsg fd");
1575 } else if (fcntl(F_SETFD, 0) == -1)
1576 fatal("cannot setup imsg fd");
1578 argv[argc++] = argv0;
1579 argv[argc++] = "-Tc";
1581 #if DEBUG
1582 argv[argc++] = "-v";
1583 #endif
1585 argv[argc++] = NULL;
1587 execvp(argv0, (char *const *)argv);
1588 fatal("execvp");
1591 static void
1592 prepare_child_for_test(struct test *t)
1594 struct passwd *pw;
1595 struct kd_auth_proc rauth;
1597 if ((pw = getpwuid(uid)) == NULL)
1598 fatal("getpwuid(%d)", uid);
1600 memset(&rauth, 0, sizeof(rauth));
1601 strlcpy(rauth.uname, pw->pw_name, sizeof(rauth.uname));
1602 strlcpy(rauth.dir, dir, sizeof(rauth.dir));
1604 imsg_compose(&ibuf, IMSG_AUTH, 0, 0, -1,
1605 &rauth, sizeof(rauth));
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 stat sb;
1661 struct test *t;
1662 int ch, i, r, passed = 0, failed = 0, skipped = 0;
1663 int runclient = 0;
1664 const char *pat = NULL;
1665 regex_t reg;
1667 assert(argv0 = 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;