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 <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 "log.h"
39 #include "script.h"
40 #include "utils.h"
42 #define DEBUG 0
44 #ifndef INFTIM
45 #define INFTIM -1
46 #endif
48 static const char *argv0;
50 static uint8_t *lastmsg;
52 static struct imsgbuf ibuf;
53 static int ibuf_inuse;
54 static int child_out = -1;
56 static struct procs procs = TAILQ_HEAD_INITIALIZER(procs);
57 static struct tests tests = TAILQ_HEAD_INITIALIZER(tests);
59 static int ntests;
61 static struct opstacks blocks = TAILQ_HEAD_INITIALIZER(blocks);
62 static struct opstacks args = TAILQ_HEAD_INITIALIZER(args);
64 #define STACK_HEIGHT 64
65 static struct value vstack[STACK_HEIGHT];
66 static int stackh;
68 static struct envs envs = TAILQ_HEAD_INITIALIZER(envs);
70 static struct value v_false = {.type = V_NUM, .v = {.num = 0}};
71 static struct value v_true = {.type = V_NUM, .v = {.num = 1}};
73 static uint8_t lasttag;
75 static int debug;
76 static int syntaxcheck;
78 static const char *filler;
80 static inline void
81 before_printing(void)
82 {
83 if (filler != NULL) {
84 printf("%s", filler);
85 filler = NULL;
86 }
87 }
89 static inline void
90 check_for_output(void)
91 {
92 static char buf[BUFSIZ];
93 struct pollfd pfd;
94 ssize_t r;
96 pfd.fd = child_out;
97 pfd.events = POLLIN;
98 if (poll(&pfd, 1, 0) == -1)
99 fatal("poll");
101 if (!(pfd.revents & POLLIN))
102 return;
104 for (;;) {
105 if ((r = read(child_out, buf, sizeof(buf))) == -1) {
106 if (errno == EAGAIN)
107 break;
108 fatal("read");
110 if (r == 0)
111 break;
112 before_printing();
113 fwrite(buf, 1, r, stdout);
117 static inline void
118 peekn(int depth, struct value *v)
120 if (depth > stackh)
121 errx(1, "can't peek the stack at %d: underflow",
122 depth);
123 memcpy(v, &vstack[stackh - depth], sizeof(*v));
125 #if DEBUG
126 printf("peeking(%d) ", depth); pp_val(v); printf("\n");
127 #endif
130 static inline void
131 popv(struct value *v)
133 if (stackh == 0)
134 errx(1, "can't pop the stack: underflow");
135 memcpy(v, &vstack[--stackh], sizeof(*v));
137 #if DEBUG
138 printf("popping "); pp_val(v); printf("\n");
139 #endif
142 static inline void
143 popvn(int n)
145 struct value v;
147 while (n-- > 0)
148 popv(&v);
151 static inline void
152 pushv(struct value *v)
154 if (stackh == STACK_HEIGHT)
155 errx(1, "can't push the stack: overflow");
157 #if DEBUG
158 printf("pushing "); pp_val(v); printf("\n");
159 #endif
161 memcpy(&vstack[stackh++], v, sizeof(*v));
164 static inline void
165 pushbool(int n)
167 pushv(n ? &v_true : &v_false);
170 static inline void
171 pushnum(int64_t n)
173 struct value v;
175 v.type = V_NUM;
176 v.v.num = n;
177 pushv(&v);
180 static inline struct opstack *
181 pushstack(struct opstacks *stack)
183 struct opstack *ops;
185 ops = xcalloc(1, sizeof(*ops));
186 TAILQ_INSERT_HEAD(stack, ops, entry);
187 return ops;
190 static inline struct opstack *
191 peek(struct opstacks *stack)
193 if (TAILQ_EMPTY(stack))
194 errx(1, "%s: args underflow", __func__);
196 return TAILQ_FIRST(stack);
199 static inline struct op *
200 finalize(struct opstacks *stack, int *argc)
202 struct opstack *ops;
203 struct op *op;
205 if (TAILQ_EMPTY(stack))
206 errx(1, "%s: args underflow", __func__);
208 ops = peek(stack);
209 TAILQ_REMOVE(&args, ops, entry);
210 op = ops->base.next;
212 if (argc != NULL)
213 *argc = ops->counter;
215 free(ops);
216 return op;
219 static inline void
220 push(struct opstacks *stack, struct op *op)
222 struct opstack *ops;
224 ops = peek(stack);
225 if (ops->last == NULL) {
226 ops->base.next = op;
227 ops->last = op;
228 } else {
229 ops->last->next = op;
230 ops->last = op;
233 ops->counter++;
236 static inline void
237 pushenv(void)
239 struct env *e;
241 e = xcalloc(1, sizeof(*e));
242 TAILQ_INSERT_HEAD(&envs, e, entry);
245 static inline struct env *
246 currentenv(void)
248 assert(!TAILQ_EMPTY(&envs));
249 return TAILQ_FIRST(&envs);
252 static void
253 popenv(void)
255 struct env *e;
256 struct binding *b, *tb;
258 e = currentenv();
259 TAILQ_REMOVE(&envs, e, entry);
261 TAILQ_FOREACH_SAFE(b, &e->bindings, entry, tb)
262 free(b);
264 free(e);
267 static inline int
268 setvar(char *sym, struct op *op)
270 struct binding *b;
271 struct env *e;
272 int ret, height;
274 height = stackh;
275 if ((ret = eval(op)) != EVAL_OK)
276 return ret;
278 if (stackh != height + 1) {
279 before_printing();
280 printf("trying to assign to `%s' a void value: ", sym);
281 pp_op(op);
282 printf("\n");
283 return EVAL_ERR;
286 b = xcalloc(1, sizeof(*b));
287 b->name = sym;
288 popv(&b->val);
290 e = TAILQ_FIRST(&envs);
291 TAILQ_INSERT_HEAD(&e->bindings, b, entry);
293 return EVAL_OK;
296 static inline void
297 setvar_raw(char *sym, struct op *op)
299 struct binding *b;
300 struct env *e;
302 b = xcalloc(1, sizeof(*b));
303 b->name = sym;
304 b->raw = op;
306 e = TAILQ_FIRST(&envs);
307 TAILQ_INSERT_HEAD(&e->bindings, b, entry);
310 static inline int
311 getvar(const char *sym, struct value *v)
313 struct env *e;
314 struct binding *b;
316 TAILQ_FOREACH(e, &envs, entry) {
317 TAILQ_FOREACH(b, &e->bindings, entry) {
318 if (!strcmp(sym, b->name)) {
319 memcpy(v, &b->val, sizeof(*v));
320 return EVAL_OK;
325 before_printing();
326 fprintf(stderr, "unbound variable %s\n", sym);
327 return EVAL_ERR;
330 static inline int
331 getvar_raw(const char *sym, struct op **raw)
333 struct env *e;
334 struct binding *b;
336 TAILQ_FOREACH(e, &envs, entry) {
337 TAILQ_FOREACH(b, &e->bindings, entry) {
338 if (!strcmp(sym, b->name)) {
339 *raw = b->raw;
340 return EVAL_OK;
345 return EVAL_ERR;
348 int
349 global_set(char *sym, struct op *op)
351 struct binding *b;
352 struct env *e;
354 /* TODO: check for duplicates */
356 if (op->type != OP_LITERAL &&
357 (op->type == OP_CAST && op->v.cast.expr->type != OP_LITERAL))
358 return 0;
360 b = xcalloc(1, sizeof(*b));
361 b->name = sym;
363 /* it's only a cast on a literal! */
364 if (op->type == OP_CAST) {
365 if (eval(op) != EVAL_OK) {
366 free(b);
367 return 0;
369 popv(&b->val);
370 } else
371 memcpy(&b->val, &op->v.literal, sizeof(b->val));
373 e = TAILQ_LAST(&envs, envs);
374 TAILQ_INSERT_HEAD(&e->bindings, b, entry);
376 return 1;
379 struct op *
380 newop(int type)
382 struct op *op;
384 op = xcalloc(1, sizeof(*op));
385 op->type = type;
387 return op;
390 void
391 free_op_rec(struct op *op)
393 struct op *n;
395 while (op != NULL) {
396 n = op->next;
397 free_op(op);
398 op = n;
402 void
403 free_op(struct op *op)
405 if (op == NULL)
406 return;
408 switch (op->type) {
409 case OP_REST:
410 case OP_LITERAL:
411 case OP_VARGS:
412 break;
413 case OP_ASSIGN:
414 free(op->v.assign.name);
415 free_op_rec(op->v.assign.expr);
416 break;
417 case OP_ASSERT:
418 free_op_rec(op->v.assert);
419 break;
420 case OP_FUNCALL:
421 free_op_rec(op->v.funcall.argv);
422 break;
423 case OP_VAR:
424 free(op->v.var);
425 break;
426 case OP_CAST:
427 free_op_rec(op->v.cast.expr);
428 break;
429 case OP_CMP_EQ:
430 free_op_rec(op->v.cmp_eq.a);
431 free_op_rec(op->v.cmp_eq.b);
432 break;
433 case OP_FACCESS:
434 free_op_rec(op->v.faccess.expr);
435 free(op->v.faccess.field);
436 break;
437 case OP_SFAIL:
438 free(op->v.sfail.msg);
439 free_op_rec(op->v.sfail.expr);
440 break;
441 default:
442 /* unreachable */
443 abort();
446 free(op);
449 struct op *
450 op_rest(void)
452 return newop(OP_REST);
455 struct op *
456 op_assign(char *sym, struct op *expr)
458 struct op *op;
460 op = newop(OP_ASSIGN);
461 op->v.assign.name = sym;
462 op->v.assign.expr = expr;
464 return op;
467 struct op *
468 op_assert(struct op *expr)
470 struct op *op;
472 op = newop(OP_ASSERT);
473 op->v.assert = expr;
475 return op;
478 struct op *
479 op_var(char *sym)
481 struct op *op;
483 op = newop(OP_VAR);
484 op->v.var = sym;
486 return op;
489 struct op *
490 op_lit_str(char *str)
492 struct op *op;
494 op = newop(OP_LITERAL);
495 op->v.literal.type = V_STR;
496 op->v.literal.v.str = str;
498 return op;
501 struct op *
502 op_lit_num(uint64_t n)
504 struct op *op;
506 op = newop(OP_LITERAL);
507 op->v.literal.type = V_NUM;
508 op->v.literal.v.num = n;
510 return op;
513 struct op *
514 op_cmp_eq(struct op *a, struct op *b)
516 struct op *op;
518 op = newop(OP_CMP_EQ);
519 op->v.cmp_eq.a = a;
520 op->v.cmp_eq.b = b;
522 return op;
525 struct op *
526 op_cast(struct op *expr, int totype)
528 struct op *op;
530 op = newop(OP_CAST);
531 op->v.cast.expr = expr;
532 op->v.cast.totype = totype;
534 return op;
537 struct op *
538 op_faccess(struct op *expr, char *field)
540 struct op *op;
542 op = newop(OP_FACCESS);
543 op->v.faccess.expr = expr;
544 op->v.faccess.field = field;
546 return op;
549 struct op *
550 op_sfail(struct op *expr, char *msg)
552 struct op *op;
554 op = newop(OP_SFAIL);
555 op->v.sfail.expr = expr;
556 op->v.sfail.msg = msg;
558 return op;
561 struct op *
562 op_vargs(void)
564 struct op *op;
566 op = newop(OP_VARGS);
568 return op;
571 void
572 ppf_val(FILE *f, struct value *val)
574 size_t i;
576 switch (val->type) {
577 case V_SYM:
578 fprintf(f, "%s", val->v.str);
579 break;
580 case V_STR:
581 fprintf(f, "\"%s\"", val->v.str);
582 break;
583 case V_NUM:
584 fprintf(f, "%"PRIi64, val->v.num);
585 break;
586 case V_U8:
587 fprintf(f, "%"PRIu8, val->v.u8);
588 break;
589 case V_U16:
590 fprintf(f, "%"PRIu16, val->v.u16);
591 break;
592 case V_U32:
593 fprintf(f, "%"PRIu32, val->v.u32);
594 break;
595 case V_MSG:
596 fprintf(f, "(");
597 for (i = 0; i < val->v.msg.len; ++i)
598 fprintf(f, "%x%s", val->v.msg.msg[i],
599 i == val->v.msg.len-1 ? "" : " ");
600 fprintf(f, ")");
601 break;
602 case V_QIDVEC:
603 fprintf(f, "qids[n=%zu]", val->v.qidvec.len);
604 break;
605 default:
606 fprintf(f, "<unknown value>");
607 break;
611 void
612 pp_val(struct value *val)
614 ppf_val(stdout, val);
617 const char *
618 val_type(struct value *v)
620 switch (v->type) {
621 case V_SYM: return "symbol";
622 case V_STR: return "string";
623 case V_NUM: return "number";
624 case V_MSG: return "message";
625 case V_QID: return "qid";
626 case V_U8: return "u8";
627 case V_U16: return "u16";
628 case V_U32: return "u32";
629 default: return "unknown";
633 int
634 val_trueish(struct value *a)
636 if (val_isnum(a))
637 return val_tonum(a);
638 return 1;
641 int
642 val_isnum(struct value *a)
644 return a->type == V_NUM
645 || a->type == V_U8
646 || a->type == V_U16
647 || a->type == V_U32;
650 int64_t
651 val_tonum(struct value *a)
653 switch (a->type) {
654 case V_NUM: return a->v.num;
655 case V_U8: return a->v.u8;
656 case V_U16: return a->v.u16;
657 case V_U32: return a->v.u32;
658 default:
659 before_printing();
660 fprintf(stderr, "%s: given value is not a number\n", __func__);
661 abort();
665 int
666 val_eq(struct value *a, struct value *b)
668 if (val_isnum(a) && val_isnum(b))
669 return val_tonum(a) == val_tonum(b);
671 if (a->type != b->type)
672 return 0;
674 switch (a->type) {
675 case V_STR:
676 case V_SYM:
677 return !strcmp(a->v.str, b->v.str);
680 return 0;
683 static inline const char *
684 pp_totype(int totype)
686 /*
687 * Not all of these are valid cast type thought, including
688 * every possibility only to aid debugging.
689 */
690 switch (totype) {
691 case V_STR: return "str";
692 case V_SYM: return "sym";
693 case V_NUM: return "num";
694 case V_QID: return "qid";
695 case V_U8: return "u8";
696 case V_U16: return "u16";
697 case V_U32: return "u32";
698 default: return "unknown";
702 int
703 val_cast(struct value *a, int totype)
705 int64_t v;
707 #define NUMCAST(val, t, c, totype, max) do { \
708 if (val > max) { \
709 before_printing(); \
710 fprintf(stderr, "can't cast %"PRIu64 \
711 " to %s\n", val, pp_totype(totype)); \
712 return EVAL_ERR; \
713 } \
714 a->type = totype; \
715 a->v.t = (c)val; \
716 return EVAL_OK; \
717 } while (0)
719 if (a->type == totype)
720 return EVAL_OK;
722 if (!val_isnum(a)) {
723 before_printing();
724 fprintf(stderr, "can't cast ");
725 ppf_val(stderr, a);
726 fprintf(stderr, " to type %s\n", pp_totype(totype));
727 return EVAL_ERR;
730 v = a->v.num;
731 switch (totype) {
732 case V_U8: NUMCAST(v, u8, uint8_t, totype, UINT8_MAX);
733 case V_U16: NUMCAST(v, u16, uint16_t, totype, UINT16_MAX);
734 case V_U32: NUMCAST(v, u32, uint32_t, totype, UINT32_MAX);
735 default:
736 before_printing();
737 fprintf(stderr, "can't cast %"PRIu64" to %s\n",
738 v, pp_totype(totype));
739 return EVAL_ERR;
742 #undef NUMCAST
745 int
746 val_faccess(struct value *a, const char *field, struct value *ret)
748 uint8_t mtype;
749 uint16_t len;
750 const char *errstr;
752 #define MSGTYPE(m) *(m.msg + 4) /* skip the length */
754 switch (a->type) {
755 case V_QID:
756 /* TODO: add path. needs uint64_t values thought! */
757 if (!strcmp(field, "vers")) {
758 ret->type = V_U32;
759 memcpy(&ret->v.u32, a->v.qid+1, 4);
760 return EVAL_OK;
761 } else if (!strcmp(field, "type")) {
762 ret->type = V_U8;
763 ret->v.u8 = *a->v.qid;
764 return EVAL_OK;
766 break;
768 case V_MSG:
769 mtype = MSGTYPE(a->v.msg);
770 if (!strcmp(field, "type")) {
771 ret->type = V_U8;
772 ret->v.u8 = MSGTYPE(a->v.msg);
773 return EVAL_OK;
774 } else if (!strcmp(field, "tag")) {
775 ret->type = V_U16;
776 memcpy(&ret->v.u16, &a->v.msg.msg[5], 2);
777 ret->v.u16 = le16toh(ret->v.u16);
778 return EVAL_OK;
779 } else if (!strcmp(field, "msize") && mtype == Rversion) {
780 ret->type = V_U32;
781 memcpy(&ret->v.u32, &a->v.msg.msg[7], 4);
782 ret->v.u32 = le32toh(ret->v.u32);
783 return EVAL_OK;
784 } else if (!strcmp(field, "qid") && mtype == Rattach) {
785 ret->type = V_QID;
786 memcpy(&ret->v.qid, &a->v.msg.msg[7], QIDSIZE);
787 return EVAL_OK;
788 } else if (!strcmp(field, "nwqid") && mtype == Rwalk) {
789 ret->type = V_U16;
790 memcpy(&ret->v.u16, &a->v.msg.msg[7], 2);
791 ret->v.u16 = le16toh(ret->v.u16);
792 return EVAL_OK;
793 } else if (!strcmp(field, "wqid") && mtype == Rwalk) {
794 ret->type = V_QIDVEC;
795 ret->v.qidvec.start = &a->v.msg.msg[9];
796 memcpy(&len, &a->v.msg.msg[7], 2);
797 len = le16toh(len);
798 ret->v.qidvec.len = len;
799 return EVAL_OK;
801 break;
803 case V_QIDVEC:
804 len = strtonum(field, 0, MAXWELEM, &errstr);
805 if (errstr != NULL) {
806 before_printing();
807 printf("can't access qid #%s: %s\n", field, errstr);
808 return EVAL_ERR;
811 if (len >= a->v.qidvec.len) {
812 before_printing();
813 printf("can't access qid #%d: out-of-bound "
814 "(max %zu)\n", len, a->v.qidvec.len);
815 return EVAL_ERR;
818 ret->type = V_QID;
819 memcpy(&ret->v.qid, a->v.qidvec.start + len * QIDSIZE,
820 QIDSIZE);
822 return EVAL_OK;
824 default:
825 break;
828 before_printing();
829 printf("can't access field `%s' on type %s (", field, val_type(a));
830 pp_val(a);
831 printf(")\n");
832 return EVAL_ERR;
834 #undef MSGTYPE
837 void
838 pp_op(struct op *op)
840 struct op *aux;
842 switch (op->type) {
843 case OP_REST:
844 printf("...");
845 break;
846 case OP_ASSIGN:
847 printf("%s = ", op->v.assign.name);
848 pp_op(op->v.assign.expr);
849 break;
850 case OP_ASSERT:
851 printf("assert ");
852 pp_op(op->v.assert);
853 break;
854 case OP_FUNCALL:
855 printf("funcall %s(", op->v.funcall.proc->name);
856 for (aux = op->v.funcall.argv; aux != NULL; aux = aux->next) {
857 pp_op(aux);
858 if (aux->next != NULL)
859 printf(", ");
861 printf(")");
862 break;
863 case OP_LITERAL:
864 pp_val(&op->v.literal);
865 break;
866 case OP_VAR:
867 printf("%s", op->v.var);
868 break;
869 case OP_CAST:
870 pp_op(op->v.cast.expr);
871 printf(":");
872 switch (op->v.cast.totype) {
873 case V_U8: printf("u8"); break;
874 case V_U16: printf("u16"); break;
875 case V_U32: printf("u32"); break;
876 case V_STR: printf("str"); break;
877 default: printf("???"); break;
879 break;
880 case OP_CMP_EQ:
881 pp_op(op->v.cmp_eq.a);
882 printf(" == ");
883 pp_op(op->v.cmp_eq.b);
884 break;
885 case OP_FACCESS:
886 pp_op(op->v.faccess.expr);
887 printf(".%s", op->v.faccess.field);
888 break;
889 case OP_SFAIL:
890 printf("should-fail ");
891 pp_op(op->v.sfail.expr);
892 if (op->v.sfail.msg != NULL)
893 printf(": \"%s\"", op->v.sfail.msg);
894 break;
895 case OP_VARGS:
896 printf("vargs");
897 break;
898 default:
899 printf(" ???[%d] ", op->type);
903 void
904 pp_block(struct op *op)
906 while (op != NULL) {
907 printf("> ");
908 pp_op(op);
909 printf("\n");
911 op = op->next;
915 int
916 eval(struct op *op)
918 struct value a, b;
919 struct proc *proc;
920 struct op *t, *tnext;
921 int i, ret;
923 #if DEBUG
924 pp_op(op);
925 printf("\n");
926 #endif
928 switch (op->type) {
929 case OP_REST:
930 /*
931 * Try to load the rest argument. Note that it can be
932 * empty!
933 */
934 if ((ret = getvar_raw("...", &t)) == EVAL_OK)
935 if ((ret = eval(t)) != EVAL_OK)
936 return ret;
937 break;
939 case OP_ASSIGN:
940 ret = setvar(op->v.assign.name, op->v.assign.expr);
941 if (ret != EVAL_OK)
942 return ret;
943 break;
945 case OP_ASSERT:
946 if ((ret = eval(op->v.assert)) != EVAL_OK)
947 return ret;
948 popv(&a);
949 if (!val_trueish(&a)) {
950 before_printing();
951 printf("assertion failed: ");
952 pp_op(op->v.assert);
953 printf("\n");
954 return EVAL_ERR;
956 break;
958 case OP_FUNCALL:
959 /* assume airity matches */
961 proc = op->v.funcall.proc;
962 if (proc->nativefn != NULL) {
963 /*
964 * Push arguments on the stack for builtin
965 * functions. Counting the height of the
966 * stack is done to compute the correct number
967 * in the vararg case. argc only counts the
968 * "syntactical" arguments, i.e. foo(x, ...)
969 * has argc == 2, but at runtime argc may be
970 * 1, 2 or a greater number!
971 */
973 i = stackh;
974 t = op->v.funcall.argv;
975 if (t != NULL && (ret = eval(t)) != EVAL_OK)
976 return ret;
977 i = stackh - i;
979 assert(i >= 0);
981 if ((ret = proc->nativefn(i))
982 != EVAL_OK)
983 return ret;
984 } else {
985 if (proc->body == NULL) {
986 before_printing();
987 printf("warn: calling the empty proc `%s'\n",
988 proc->name);
989 break;
992 pushenv();
994 for (t = op->v.funcall.argv, i = 0;
995 t != NULL;
996 t = t->next, i++) {
997 /*
998 * Push a pseudo variable `...' (and
999 * don't evaluate it) in the vararg
1000 * case. A special case is when the
1001 * variable is itself `...'.
1003 if (proc->vararg && i == proc->minargs) {
1004 if (t->type != OP_REST)
1005 setvar_raw(xstrdup("..."), t);
1006 break;
1010 * The arguments are a linked list of
1011 * ops. Setvar will call eval that
1012 * will evaluate *all* the arguments.
1013 * The dance here that sets next to
1014 * NULL and then restores it is to
1015 * avoid this behaviour.
1017 tnext = t->next;
1018 t->next = NULL;
1019 ret = setvar(proc->args[i], t);
1020 t->next = tnext;
1022 if (ret != EVAL_OK)
1023 return ret;
1026 if ((ret = eval(proc->body)) != EVAL_OK)
1027 return ret;
1029 popenv();
1032 break;
1034 case OP_LITERAL:
1035 pushv(&op->v.literal);
1036 break;
1038 case OP_VAR:
1039 if ((ret = getvar(op->v.var, &a)) != EVAL_OK)
1040 return ret;
1041 pushv(&a);
1042 break;
1044 case OP_CAST:
1045 if ((ret = eval(op->v.cast.expr)) != EVAL_OK)
1046 return ret;
1047 popv(&a);
1048 if ((ret = val_cast(&a, op->v.cast.totype)) != EVAL_OK)
1049 return ret;
1050 pushv(&a);
1051 break;
1053 case OP_CMP_EQ:
1054 if ((ret = eval(op->v.cmp_eq.a)) != EVAL_OK)
1055 return ret;
1056 if ((ret = eval(op->v.cmp_eq.b)) != EVAL_OK)
1057 return ret;
1059 popv(&b);
1060 popv(&a);
1061 pushbool(val_eq(&a, &b));
1063 break;
1065 case OP_FACCESS:
1066 if ((ret = eval(op->v.faccess.expr)) != EVAL_OK)
1067 return ret;
1068 popv(&a);
1069 if ((ret = val_faccess(&a, op->v.faccess.field, &b))
1070 != EVAL_OK)
1071 return ret;
1072 pushv(&b);
1073 break;
1075 case OP_SFAIL:
1076 if ((ret = eval(op->v.sfail.expr)) == EVAL_OK) {
1077 before_printing();
1078 printf("expecting failure");
1079 if (op->v.sfail.msg != NULL)
1080 printf(" \"%s\"", op->v.sfail.msg);
1081 printf("\n");
1082 printf("expression: ");
1083 pp_op(op->v.sfail.expr);
1084 printf("\n");
1085 return EVAL_ERR;
1087 if (ret == EVAL_SKIP)
1088 return ret;
1089 break;
1091 case OP_VARGS:
1092 if ((ret = getvar_raw("...", &t)) == EVAL_OK) {
1093 for (i = 0; t != NULL; t = t->next)
1094 i++;
1095 pushnum(i);
1096 } else
1097 pushnum(0);
1098 break;
1100 default:
1101 before_printing();
1102 fprintf(stderr, "invalid op, aborting.\n");
1103 abort();
1106 if (op->next)
1107 return eval(op->next);
1108 return EVAL_OK;
1111 void
1112 prepare_funcall(void)
1114 pushstack(&args);
1117 void
1118 push_arg(struct op *op)
1120 push(&args, op);
1123 struct op *
1124 op_funcall(struct proc *proc)
1126 struct op *op, *argv;
1127 int argc;
1129 argv = finalize(&args, &argc);
1131 op = newop(OP_FUNCALL);
1132 op->v.funcall.proc = proc;
1133 op->v.funcall.argv = argv;
1134 op->v.funcall.argc = argc;
1136 return op;
1139 void
1140 add_builtin_proc(const char *name, int (*fn)(int), int argc, int vararg)
1142 struct proc *proc;
1144 proc = xcalloc(1, sizeof(*proc));
1145 proc->name = xstrdup(name);
1146 proc->nativefn = fn;
1147 proc->minargs = argc;
1148 proc->vararg = vararg;
1150 TAILQ_INSERT_HEAD(&procs, proc, entry);
1153 void
1154 prepare_proc(void)
1156 pushstack(&args);
1159 int
1160 proc_setup_body(void)
1162 struct opstack *argv;
1163 struct op *op;
1164 int i;
1166 argv = peek(&args);
1167 for (i = 0, op = argv->base.next; op != NULL; i++) {
1169 * TODO: should free the whole list on error but..,
1170 * we're gonna exit real soon(tm)!
1172 if (op->type != OP_VAR && op->type != OP_REST)
1173 return 0;
1175 op = op->next;
1178 assert(i == argv->counter);
1179 pushstack(&blocks);
1180 return 1;
1183 void
1184 proc_done(char *name)
1186 struct proc *proc;
1187 struct op *op, *next, *argv, *body;
1188 int i, argc;
1190 argv = finalize(&args, &argc);
1191 body = finalize(&blocks, NULL);
1193 proc = xcalloc(1, sizeof(*proc));
1194 proc->name = name;
1195 proc->minargs = argc;
1197 for (i = 0, op = argv; op != NULL; ++i) {
1198 if (op->type == OP_REST) {
1199 proc->vararg = 1;
1200 proc->minargs = i;
1201 break;
1204 proc->args[i] = xstrdup(op->v.var);
1206 next = op->next;
1207 free_op(op);
1208 op = next;
1210 assert(i == argc || (proc->vararg && i == proc->minargs));
1212 proc->body = body;
1214 TAILQ_INSERT_HEAD(&procs, proc, entry);
1217 void
1218 block_push(struct op *op)
1220 push(&blocks, op);
1223 struct proc *
1224 proc_by_name(const char *name)
1226 struct proc *p;
1228 TAILQ_FOREACH(p, &procs, entry) {
1229 if (!strcmp(p->name, name))
1230 return p;
1233 return NULL;
1236 void
1237 prepare_test(void)
1239 pushstack(&blocks);
1242 void
1243 test_done(int shouldfail, char *name, char *dir)
1245 struct test *test;
1247 test = xcalloc(1, sizeof(*test));
1248 test->shouldfail = shouldfail;
1249 test->name = name;
1250 test->dir = dir;
1251 test->body = finalize(&blocks, NULL);
1253 if (TAILQ_EMPTY(&tests))
1254 TAILQ_INSERT_HEAD(&tests, test, entry);
1255 else
1256 TAILQ_INSERT_TAIL(&tests, test, entry);
1258 ntests++;
1261 static int
1262 builtin_print(int argc)
1264 struct value v;
1265 int i;
1267 before_printing();
1269 for (i = argc; i > 0; --i) {
1270 peekn(i, &v);
1271 if (v.type == V_STR)
1272 printf("%s", v.v.str);
1273 else
1274 pp_val(&v);
1275 printf(" ");
1278 printf("\n");
1280 popvn(argc);
1282 return EVAL_OK;
1285 static int
1286 builtin_debug(int argc)
1288 if (debug)
1289 return builtin_print(argc);
1291 popvn(argc);
1292 return EVAL_OK;
1295 static int
1296 builtin_skip(int argc)
1298 return EVAL_SKIP;
1301 static int
1302 builtin_iota(int argc)
1304 struct value v;
1306 v.type = V_U16;
1307 if ((v.v.u16 = ++lasttag) == 255)
1308 v.v.u16 = ++lasttag;
1310 pushv(&v);
1311 return EVAL_OK;
1314 static int
1315 builtin_send(int argc)
1317 struct ibuf *buf;
1318 struct value v;
1319 uint32_t len;
1320 uint16_t slen;
1321 int i;
1323 check_for_output();
1326 * Compute the length of the packet. 4 is for the initial
1327 * length field
1329 len = 4;
1331 for (i = argc; i > 0; --i) {
1332 peekn(i, &v);
1333 switch (v.type) {
1334 case V_STR:
1335 len += 2; /* count */
1336 len += strlen(v.v.str);
1337 break;
1339 case V_U8:
1340 len += 1;
1341 break;
1343 case V_U16:
1344 len += 2;
1345 break;
1347 case V_U32:
1348 len += 4;
1349 break;
1351 default:
1352 before_printing();
1353 printf("%s: can't serialize ", __func__);
1354 pp_val(&v);
1355 printf("\n");
1356 return EVAL_ERR;
1360 if (len > UINT16_MAX) {
1361 before_printing();
1362 printf("%s: message size too long: got %d when max is %d\n",
1363 __func__, len, UINT16_MAX);
1364 return EVAL_ERR;
1367 if ((buf = imsg_create(&ibuf, IMSG_BUF, 0, 0, len)) == NULL)
1368 fatal("imsg_create(%d)", len);
1370 len = htole32(len);
1371 imsg_add(buf, &len, sizeof(len));
1373 for (i = argc; i > 0; --i) {
1374 peekn(i, &v);
1375 switch (v.type) {
1376 case V_STR:
1377 slen = strlen(v.v.str);
1378 slen = htole16(slen);
1379 imsg_add(buf, &slen, sizeof(slen));
1380 imsg_add(buf, v.v.str, strlen(v.v.str));
1381 break;
1383 case V_U8:
1384 imsg_add(buf, &v.v.u8, 1);
1385 break;
1387 case V_U16:
1388 v.v.u16 = htole16(v.v.u16);
1389 imsg_add(buf, &v.v.u16, 2);
1390 break;
1392 case V_U32:
1393 v.v.u32 = htole32(v.v.u32);
1394 imsg_add(buf, &v.v.u32, 4);
1395 break;
1399 imsg_close(&ibuf, buf);
1401 if (imsg_flush(&ibuf) == -1) {
1402 i = errno;
1403 before_printing();
1404 printf("%s: imsg_flush failed: %s\n", __func__, strerror(i));
1405 return EVAL_ERR;
1408 check_for_output();
1409 return EVAL_OK;
1412 static int
1413 builtin_recv(int argc)
1415 struct pollfd pfd;
1416 struct value v;
1417 struct imsg imsg;
1418 ssize_t n, datalen;
1419 int serrno;
1421 if (lastmsg != NULL) {
1422 free(lastmsg);
1423 lastmsg = NULL;
1426 pfd.fd = ibuf.fd;
1427 pfd.events = POLLIN;
1428 if (poll(&pfd, 1, INFTIM) == -1) {
1429 serrno = errno;
1430 before_printing();
1431 printf("%s: poll failed: %s\n", __func__, strerror(serrno));
1432 return EVAL_ERR;
1435 again:
1436 if ((n = imsg_read(&ibuf)) == -1) {
1437 if (errno == EAGAIN)
1438 goto again;
1439 fatal("imsg_read");
1441 if (n == 0) {
1442 disconnect:
1443 before_printing();
1444 printf("child disconnected\n");
1445 return EVAL_ERR;
1448 nextmessage:
1449 check_for_output();
1451 /* read only one message */
1452 if ((n = imsg_get(&ibuf, &imsg)) == -1)
1453 fatal("imsg_get");
1454 if (n == 0)
1455 goto disconnect;
1457 datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
1458 switch (imsg.hdr.type) {
1459 case IMSG_BUF:
1460 v.type = V_MSG;
1461 if ((v.v.msg.msg = malloc(datalen)) == NULL)
1462 fatal("malloc");
1463 memcpy(v.v.msg.msg, imsg.data, datalen);
1464 v.v.msg.len = datalen;
1465 pushv(&v);
1466 imsg_free(&imsg);
1467 return EVAL_OK;
1469 case IMSG_CLOSE:
1470 before_printing();
1471 printf("subprocess closed the connection\n");
1472 imsg_free(&imsg);
1473 return EVAL_ERR;
1475 case IMSG_MSIZE:
1476 imsg_free(&imsg);
1477 goto nextmessage;
1479 default:
1480 before_printing();
1481 printf("got unknown message from subprocess: %d\n",
1482 imsg.hdr.type);
1483 imsg_free(&imsg);
1484 return EVAL_ERR;
1488 static pid_t
1489 spawn_client_proc(void)
1491 const char *argv[4];
1492 int p[2], out[2], argc = 0;
1493 pid_t pid;
1495 if (child_out != -1)
1496 close(child_out);
1498 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1499 PF_UNSPEC, p) == -1)
1500 fatal("socketpair");
1502 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1503 PF_UNSPEC, out) == -1)
1504 fatal("socketpair");
1506 switch (pid = fork()) {
1507 case -1:
1508 fatal("cannot fork");
1509 case 0:
1510 break;
1511 default:
1512 close(p[1]);
1513 close(out[1]);
1514 child_out = out[0];
1515 if (ibuf_inuse) {
1516 msgbuf_clear(&ibuf.w);
1517 close(ibuf.fd);
1519 imsg_init(&ibuf, p[0]);
1520 ibuf_inuse = 1;
1521 return pid;
1524 close(p[0]);
1525 close(out[0]);
1527 if (dup2(out[1], 1) == -1 ||
1528 dup2(out[1], 2) == -1)
1529 fatal("dup2");
1531 if (p[1] != 3) {
1532 if (dup2(p[1], 3) == -1)
1533 fatal("cannot setup imsg fd");
1534 } else if (fcntl(F_SETFD, 0) == -1)
1535 fatal("cannot setup imsg fd");
1537 argv[argc++] = argv0;
1538 argv[argc++] = "-Tc";
1540 #if DEBUG
1541 argv[argc++] = "-v";
1542 #endif
1544 argv[argc++] = NULL;
1546 execvp(argv0, (char *const *)argv);
1547 fatal("execvp");
1550 static void
1551 prepare_child_for_test(struct test *t)
1553 struct passwd *pw;
1554 struct stat sb;
1556 if (stat(t->dir, &sb) == -1)
1557 fatal("stat(\"%s\")", t->dir);
1559 if ((pw = getpwuid(sb.st_uid)) == NULL)
1560 fatal("getpwuid(%d)", sb.st_uid);
1562 imsg_compose(&ibuf, IMSG_AUTH, 0, 0, -1,
1563 pw->pw_name, strlen(pw->pw_name)+1);
1564 imsg_compose(&ibuf, IMSG_AUTH_DIR, 0, 0, -1,
1565 t->dir, strlen(t->dir)+1);
1567 if (imsg_flush(&ibuf) == -1)
1568 fatal("imsg_flush");
1571 static int
1572 run_test(struct test *t)
1574 pid_t pid;
1575 int ret;
1577 #if DEBUG
1578 before_printing();
1579 puts("=====================");
1580 pp_block(t->body);
1581 puts("=====================");
1582 #endif
1584 if (stackh != 0)
1585 popvn(stackh);
1587 if (t->body == NULL) {
1588 before_printing();
1589 printf("no instructions, skipping...\n");
1590 return EVAL_SKIP;
1593 pid = spawn_client_proc();
1594 prepare_child_for_test(t);
1595 ret = eval(t->body);
1597 imsg_compose(&ibuf, IMSG_CONN_GONE, 0, 0, -1, NULL, 0);
1598 imsg_flush(&ibuf);
1600 while (waitpid(pid, NULL, 0) != pid)
1601 ; /* nop */
1603 check_for_output();
1605 if (t->shouldfail) {
1606 if (ret == EVAL_OK) {
1607 before_printing();
1608 printf("test was expected to fail\n");
1609 return EVAL_ERR;
1610 } else if (ret == EVAL_ERR)
1611 return EVAL_OK;
1614 return ret;
1617 int
1618 main(int argc, char **argv)
1620 struct test *t;
1621 int ch, i, r, passed = 0, failed = 0, skipped = 0;
1622 int runclient = 0;
1624 assert(argv0 = argv[0]);
1626 signal(SIGPIPE, SIG_IGN);
1628 log_init(1, LOG_DAEMON);
1629 log_setverbose(1);
1631 /* prepare the global env */
1632 pushenv();
1634 add_builtin_proc("print", builtin_print, 1, 1);
1635 add_builtin_proc("debug", builtin_debug, 1, 1);
1636 add_builtin_proc("skip", builtin_skip, 0, 0);
1637 add_builtin_proc("iota", builtin_iota, 0, 0);
1638 add_builtin_proc("send", builtin_send, 2, 1);
1639 add_builtin_proc("recv", builtin_recv, 0, 0);
1641 while ((ch = getopt(argc, argv, "nT:v")) != -1) {
1642 switch (ch) {
1643 case 'n':
1644 syntaxcheck = 1;
1645 break;
1646 case 'T':
1647 assert(*optarg == 'c');
1648 runclient = 1;
1649 break;
1650 case 'v':
1651 debug = 1;
1652 break;
1653 default:
1654 fprintf(stderr, "Usage: %s [-nv] [files...]\n",
1655 *argv);
1656 exit(1);
1659 argc -= optind;
1660 argv += optind;
1662 if (runclient)
1663 client(1, debug);
1665 for (i = 0; i < argc; ++i)
1666 loadfile(argv[i]);
1668 if (syntaxcheck) {
1669 fprintf(stderr, "files OK\n");
1670 return 0;
1673 /* Check for root privileges. */
1674 if (geteuid())
1675 fatalx("need root privileges");
1677 i = 0;
1678 TAILQ_FOREACH(t, &tests, entry) {
1679 printf("===> [%d/%d] running test \"%s\"... ", i+1, ntests,
1680 t->name);
1681 fflush(stdout);
1683 filler = "\n";
1684 r = run_test(t);
1685 if (filler == NULL)
1686 printf("=> test ");
1688 switch (r) {
1689 case EVAL_OK:
1690 printf("passed\n");
1691 passed++;
1692 break;
1693 case EVAL_ERR:
1694 failed++;
1695 printf("failed\n");
1696 break;
1697 case EVAL_SKIP:
1698 printf("skipped\n");
1699 skipped++;
1700 break;
1703 if (filler == NULL)
1704 printf("\n");
1705 i++;
1708 printf("\n");
1709 printf("passed %d/%d (%d skipped and %d failed)\n",
1710 passed, i, skipped, failed);
1712 popenv();
1713 free(lastmsg);
1715 return failed != 0;