Blob


1 /*
2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include "compat.h"
19 #include <sys/socket.h>
20 #include <sys/stat.h>
21 #include <sys/wait.h>
23 #include <assert.h>
24 #include <endian.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <inttypes.h>
28 #include <poll.h>
29 #include <pwd.h>
30 #include <regex.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <syslog.h>
36 #include <unistd.h>
38 #include "client.h"
39 #include "log.h"
40 #include "script.h"
41 #include "utils.h"
43 #define DEBUG 0
45 #ifndef INFTIM
46 #define INFTIM -1
47 #endif
49 static const char *argv0;
51 static uint8_t *lastmsg;
53 static struct imsgbuf ibuf;
54 static int ibuf_inuse;
55 static int child_out = -1;
57 static struct procs procs = TAILQ_HEAD_INITIALIZER(procs);
58 static struct tests tests = TAILQ_HEAD_INITIALIZER(tests);
60 static int ntests;
62 static struct opstacks blocks = TAILQ_HEAD_INITIALIZER(blocks);
63 static struct opstacks args = TAILQ_HEAD_INITIALIZER(args);
65 #define STACK_HEIGHT 64
66 static struct value vstack[STACK_HEIGHT];
67 static int stackh;
69 static struct envs envs = TAILQ_HEAD_INITIALIZER(envs);
71 static struct value v_false = {.type = V_NUM, .v = {.num = 0}};
72 static struct value v_true = {.type = V_NUM, .v = {.num = 1}};
74 static uint8_t lasttag;
76 static int debug;
77 static int syntaxcheck;
79 static const char *filler;
81 static inline void
82 before_printing(void)
83 {
84 if (filler != NULL) {
85 printf("%s", filler);
86 filler = NULL;
87 }
88 }
90 static inline void
91 check_for_output(void)
92 {
93 static char buf[BUFSIZ];
94 struct pollfd pfd;
95 ssize_t r;
97 pfd.fd = child_out;
98 pfd.events = POLLIN;
99 if (poll(&pfd, 1, 0) == -1)
100 fatal("poll");
102 if (!(pfd.revents & POLLIN))
103 return;
105 for (;;) {
106 if ((r = read(child_out, buf, sizeof(buf))) == -1) {
107 if (errno == EAGAIN)
108 break;
109 fatal("read");
111 if (r == 0)
112 break;
113 before_printing();
114 fwrite(buf, 1, r, stdout);
118 static inline void
119 peekn(int depth, struct value *v)
121 if (depth > stackh)
122 errx(1, "can't peek the stack at %d: underflow",
123 depth);
124 memcpy(v, &vstack[stackh - depth], sizeof(*v));
126 #if DEBUG
127 printf("peeking(%d) ", depth); pp_val(v); printf("\n");
128 #endif
131 static inline void
132 popv(struct value *v)
134 if (stackh == 0)
135 errx(1, "can't pop the stack: underflow");
136 memcpy(v, &vstack[--stackh], sizeof(*v));
138 #if DEBUG
139 printf("popping "); pp_val(v); printf("\n");
140 #endif
143 static inline void
144 popvn(int n)
146 struct value v;
148 while (n-- > 0)
149 popv(&v);
152 static inline void
153 pushv(struct value *v)
155 if (stackh == STACK_HEIGHT)
156 errx(1, "can't push the stack: overflow");
158 #if DEBUG
159 printf("pushing "); pp_val(v); printf("\n");
160 #endif
162 memcpy(&vstack[stackh++], v, sizeof(*v));
165 static inline void
166 pushbool(int n)
168 pushv(n ? &v_true : &v_false);
171 static inline void
172 pushnum(int64_t n)
174 struct value v;
176 v.type = V_NUM;
177 v.v.num = n;
178 pushv(&v);
181 static inline struct opstack *
182 pushstack(struct opstacks *stack)
184 struct opstack *ops;
186 ops = xcalloc(1, sizeof(*ops));
187 TAILQ_INSERT_HEAD(stack, ops, entry);
188 return ops;
191 static inline struct opstack *
192 peek(struct opstacks *stack)
194 if (TAILQ_EMPTY(stack))
195 errx(1, "%s: args underflow", __func__);
197 return TAILQ_FIRST(stack);
200 static inline struct op *
201 finalize(struct opstacks *stack, int *argc)
203 struct opstack *ops;
204 struct op *op;
206 if (TAILQ_EMPTY(stack))
207 errx(1, "%s: args underflow", __func__);
209 ops = peek(stack);
210 TAILQ_REMOVE(&args, ops, entry);
211 op = ops->base.next;
213 if (argc != NULL)
214 *argc = ops->counter;
216 free(ops);
217 return op;
220 static inline void
221 push(struct opstacks *stack, struct op *op)
223 struct opstack *ops;
225 ops = peek(stack);
226 if (ops->last == NULL) {
227 ops->base.next = op;
228 ops->last = op;
229 } else {
230 ops->last->next = op;
231 ops->last = op;
234 ops->counter++;
237 static inline void
238 pushenv(void)
240 struct env *e;
242 e = xcalloc(1, sizeof(*e));
243 TAILQ_INSERT_HEAD(&envs, e, entry);
246 static inline struct env *
247 currentenv(void)
249 assert(!TAILQ_EMPTY(&envs));
250 return TAILQ_FIRST(&envs);
253 static void
254 popenv(void)
256 struct env *e;
257 struct binding *b, *tb;
259 e = currentenv();
260 TAILQ_REMOVE(&envs, e, entry);
262 TAILQ_FOREACH_SAFE(b, &e->bindings, entry, tb)
263 free(b);
265 free(e);
268 static inline int
269 setvar(char *sym, struct op *op)
271 struct binding *b;
272 struct env *e;
273 int ret, height;
275 height = stackh;
276 if ((ret = eval(op)) != EVAL_OK)
277 return ret;
279 if (stackh != height + 1) {
280 before_printing();
281 printf("trying to assign to `%s' a void value: ", sym);
282 pp_op(op);
283 printf("\n");
284 return EVAL_ERR;
287 b = xcalloc(1, sizeof(*b));
288 b->name = sym;
289 popv(&b->val);
291 e = TAILQ_FIRST(&envs);
292 TAILQ_INSERT_HEAD(&e->bindings, b, entry);
294 return EVAL_OK;
297 static inline void
298 setvar_raw(char *sym, struct op *op)
300 struct binding *b;
301 struct env *e;
303 b = xcalloc(1, sizeof(*b));
304 b->name = sym;
305 b->raw = op;
307 e = TAILQ_FIRST(&envs);
308 TAILQ_INSERT_HEAD(&e->bindings, b, entry);
311 static inline int
312 getvar(const char *sym, struct value *v)
314 struct env *e;
315 struct binding *b;
317 TAILQ_FOREACH(e, &envs, entry) {
318 TAILQ_FOREACH(b, &e->bindings, entry) {
319 if (!strcmp(sym, b->name)) {
320 memcpy(v, &b->val, sizeof(*v));
321 return EVAL_OK;
326 before_printing();
327 fprintf(stderr, "unbound variable %s\n", sym);
328 return EVAL_ERR;
331 static inline int
332 getvar_raw(const char *sym, struct op **raw)
334 struct env *e;
335 struct binding *b;
337 TAILQ_FOREACH(e, &envs, entry) {
338 TAILQ_FOREACH(b, &e->bindings, entry) {
339 if (!strcmp(sym, b->name)) {
340 *raw = b->raw;
341 return EVAL_OK;
346 return EVAL_ERR;
349 int
350 global_set(char *sym, struct op *op)
352 struct binding *b;
353 struct env *e;
355 /* TODO: check for duplicates */
357 if (op->type != OP_LITERAL &&
358 (op->type == OP_CAST && op->v.cast.expr->type != OP_LITERAL))
359 return 0;
361 b = xcalloc(1, sizeof(*b));
362 b->name = sym;
364 /* it's only a cast on a literal! */
365 if (op->type == OP_CAST) {
366 if (eval(op) != EVAL_OK) {
367 free(b);
368 return 0;
370 popv(&b->val);
371 } else
372 memcpy(&b->val, &op->v.literal, sizeof(b->val));
374 e = TAILQ_LAST(&envs, envs);
375 TAILQ_INSERT_HEAD(&e->bindings, b, entry);
377 return 1;
380 struct op *
381 newop(int type)
383 struct op *op;
385 op = xcalloc(1, sizeof(*op));
386 op->type = type;
388 return op;
391 void
392 free_op_rec(struct op *op)
394 struct op *n;
396 while (op != NULL) {
397 n = op->next;
398 free_op(op);
399 op = n;
403 void
404 free_op(struct op *op)
406 if (op == NULL)
407 return;
409 switch (op->type) {
410 case OP_REST:
411 case OP_LITERAL:
412 case OP_VARGS:
413 break;
414 case OP_ASSIGN:
415 free(op->v.assign.name);
416 free_op_rec(op->v.assign.expr);
417 break;
418 case OP_ASSERT:
419 free_op_rec(op->v.assert);
420 break;
421 case OP_FUNCALL:
422 free_op_rec(op->v.funcall.argv);
423 break;
424 case OP_VAR:
425 free(op->v.var);
426 break;
427 case OP_CAST:
428 free_op_rec(op->v.cast.expr);
429 break;
430 case OP_CMP_EQ:
431 case OP_CMP_LEQ:
432 free_op_rec(op->v.bin_cmp.a);
433 free_op_rec(op->v.bin_cmp.b);
434 break;
435 case OP_FACCESS:
436 free_op_rec(op->v.faccess.expr);
437 free(op->v.faccess.field);
438 break;
439 case OP_SFAIL:
440 free(op->v.sfail.msg);
441 free_op_rec(op->v.sfail.expr);
442 break;
443 default:
444 /* unreachable */
445 abort();
448 free(op);
451 struct op *
452 op_rest(void)
454 return newop(OP_REST);
457 struct op *
458 op_assign(char *sym, struct op *expr)
460 struct op *op;
462 op = newop(OP_ASSIGN);
463 op->v.assign.name = sym;
464 op->v.assign.expr = expr;
466 return op;
469 struct op *
470 op_assert(struct op *expr)
472 struct op *op;
474 op = newop(OP_ASSERT);
475 op->v.assert = expr;
477 return op;
480 struct op *
481 op_var(char *sym)
483 struct op *op;
485 op = newop(OP_VAR);
486 op->v.var = sym;
488 return op;
491 struct op *
492 op_lit_str(char *str)
494 struct op *op;
496 op = newop(OP_LITERAL);
497 op->v.literal.type = V_STR;
498 op->v.literal.v.str = str;
500 return op;
503 struct op *
504 op_lit_num(uint64_t n)
506 struct op *op;
508 op = newop(OP_LITERAL);
509 op->v.literal.type = V_NUM;
510 op->v.literal.v.num = n;
512 return op;
515 struct op *
516 op_cmp_eq(struct op *a, struct op *b)
518 struct op *op;
520 op = newop(OP_CMP_EQ);
521 op->v.bin_cmp.a = a;
522 op->v.bin_cmp.b = b;
524 return op;
527 struct op *
528 op_cmp_leq(struct op *a, struct op *b)
530 struct op *op;
532 op = newop(OP_CMP_LEQ);
533 op->v.bin_cmp.a = a;
534 op->v.bin_cmp.b = b;
536 return op;
539 struct op *
540 op_cast(struct op *expr, int totype)
542 struct op *op;
544 op = newop(OP_CAST);
545 op->v.cast.expr = expr;
546 op->v.cast.totype = totype;
548 return op;
551 struct op *
552 op_faccess(struct op *expr, char *field)
554 struct op *op;
556 op = newop(OP_FACCESS);
557 op->v.faccess.expr = expr;
558 op->v.faccess.field = field;
560 return op;
563 struct op *
564 op_sfail(struct op *expr, char *msg)
566 struct op *op;
568 op = newop(OP_SFAIL);
569 op->v.sfail.expr = expr;
570 op->v.sfail.msg = msg;
572 return op;
575 struct op *
576 op_vargs(void)
578 struct op *op;
580 op = newop(OP_VARGS);
582 return op;
585 void
586 ppf_val(FILE *f, struct value *val)
588 size_t i;
590 switch (val->type) {
591 case V_SYM:
592 fprintf(f, "%s", val->v.str);
593 break;
594 case V_STR:
595 fprintf(f, "\"%s\"", val->v.str);
596 break;
597 case V_NUM:
598 fprintf(f, "%"PRIi64, val->v.num);
599 break;
600 case V_U8:
601 fprintf(f, "%"PRIu8, val->v.u8);
602 break;
603 case V_U16:
604 fprintf(f, "%"PRIu16, val->v.u16);
605 break;
606 case V_U32:
607 fprintf(f, "%"PRIu32, val->v.u32);
608 break;
609 case V_MSG:
610 fprintf(f, "(");
611 for (i = 0; i < val->v.msg.len; ++i)
612 fprintf(f, "%x%s", val->v.msg.msg[i],
613 i == val->v.msg.len-1 ? "" : " ");
614 fprintf(f, ")");
615 break;
616 case V_QIDVEC:
617 fprintf(f, "qids[n=%zu]", val->v.qidvec.len);
618 break;
619 default:
620 fprintf(f, "<unknown value>");
621 break;
625 void
626 pp_val(struct value *val)
628 ppf_val(stdout, val);
631 const char *
632 val_type(struct value *v)
634 switch (v->type) {
635 case V_SYM: return "symbol";
636 case V_STR: return "string";
637 case V_NUM: return "number";
638 case V_MSG: return "message";
639 case V_QID: return "qid";
640 case V_U8: return "u8";
641 case V_U16: return "u16";
642 case V_U32: return "u32";
643 default: return "unknown";
647 int
648 val_trueish(struct value *a)
650 if (val_isnum(a))
651 return val_tonum(a);
652 return 1;
655 int
656 val_isnum(struct value *a)
658 return a->type == V_NUM
659 || a->type == V_U8
660 || a->type == V_U16
661 || a->type == V_U32;
664 int64_t
665 val_tonum(struct value *a)
667 switch (a->type) {
668 case V_NUM: return a->v.num;
669 case V_U8: return a->v.u8;
670 case V_U16: return a->v.u16;
671 case V_U32: return a->v.u32;
672 default:
673 before_printing();
674 fprintf(stderr, "%s: given value is not a number\n", __func__);
675 abort();
679 int
680 val_eq(struct value *a, struct value *b)
682 if (val_isnum(a) && val_isnum(b))
683 return val_tonum(a) == val_tonum(b);
685 if (a->type != b->type)
686 return 0;
688 switch (a->type) {
689 case V_STR:
690 case V_SYM:
691 return !strcmp(a->v.str, b->v.str);
694 return 0;
697 int
698 val_leq(struct value *a, struct value *b)
700 if (val_isnum(a) && val_isnum(b))
701 return val_tonum(a) <= val_tonum(b);
702 return 0;
705 static inline const char *
706 pp_totype(int totype)
708 /*
709 * Not all of these are valid cast type thought, including
710 * every possibility only to aid debugging.
711 */
712 switch (totype) {
713 case V_STR: return "str";
714 case V_SYM: return "sym";
715 case V_NUM: return "num";
716 case V_QID: return "qid";
717 case V_U8: return "u8";
718 case V_U16: return "u16";
719 case V_U32: return "u32";
720 default: return "unknown";
724 int
725 val_cast(struct value *a, int totype)
727 int64_t v;
729 #define NUMCAST(val, t, c, totype, max) do { \
730 if (val > max) { \
731 before_printing(); \
732 fprintf(stderr, "can't cast %"PRIu64 \
733 " to %s\n", val, pp_totype(totype)); \
734 return EVAL_ERR; \
735 } \
736 a->type = totype; \
737 a->v.t = (c)val; \
738 return EVAL_OK; \
739 } while (0)
741 if (a->type == totype)
742 return EVAL_OK;
744 if (!val_isnum(a)) {
745 before_printing();
746 fprintf(stderr, "can't cast ");
747 ppf_val(stderr, a);
748 fprintf(stderr, " to type %s\n", pp_totype(totype));
749 return EVAL_ERR;
752 v = a->v.num;
753 switch (totype) {
754 case V_U8: NUMCAST(v, u8, uint8_t, totype, UINT8_MAX);
755 case V_U16: NUMCAST(v, u16, uint16_t, totype, UINT16_MAX);
756 case V_U32: NUMCAST(v, u32, uint32_t, totype, UINT32_MAX);
757 default:
758 before_printing();
759 fprintf(stderr, "can't cast %"PRIu64" to %s\n",
760 v, pp_totype(totype));
761 return EVAL_ERR;
764 #undef NUMCAST
767 int
768 val_faccess(struct value *a, const char *field, struct value *ret)
770 uint8_t mtype;
771 uint16_t len;
772 const char *errstr;
774 #define MSGTYPE(m) *(m.msg + 4) /* skip the length */
776 switch (a->type) {
777 case V_QID:
778 /* TODO: add path. needs uint64_t values thought! */
779 if (!strcmp(field, "vers")) {
780 ret->type = V_U32;
781 memcpy(&ret->v.u32, a->v.qid+1, 4);
782 return EVAL_OK;
783 } else if (!strcmp(field, "type")) {
784 ret->type = V_U8;
785 ret->v.u8 = *a->v.qid;
786 return EVAL_OK;
788 break;
790 case V_MSG:
791 mtype = MSGTYPE(a->v.msg);
792 if (!strcmp(field, "type")) {
793 ret->type = V_U8;
794 ret->v.u8 = MSGTYPE(a->v.msg);
795 return EVAL_OK;
796 } else if (!strcmp(field, "tag")) {
797 ret->type = V_U16;
798 memcpy(&ret->v.u16, &a->v.msg.msg[5], 2);
799 ret->v.u16 = le16toh(ret->v.u16);
800 return EVAL_OK;
801 } else if (!strcmp(field, "msize") && mtype == Rversion) {
802 ret->type = V_U32;
803 memcpy(&ret->v.u32, &a->v.msg.msg[7], 4);
804 ret->v.u32 = le32toh(ret->v.u32);
805 return EVAL_OK;
806 } else if (!strcmp(field, "qid") && mtype == Rattach) {
807 ret->type = V_QID;
808 memcpy(&ret->v.qid, &a->v.msg.msg[7], QIDSIZE);
809 return EVAL_OK;
810 } else if (!strcmp(field, "nwqid") && mtype == Rwalk) {
811 ret->type = V_U16;
812 memcpy(&ret->v.u16, &a->v.msg.msg[7], 2);
813 ret->v.u16 = le16toh(ret->v.u16);
814 return EVAL_OK;
815 } else if (!strcmp(field, "wqid") && mtype == Rwalk) {
816 ret->type = V_QIDVEC;
817 ret->v.qidvec.start = &a->v.msg.msg[9];
818 memcpy(&len, &a->v.msg.msg[7], 2);
819 len = le16toh(len);
820 ret->v.qidvec.len = len;
821 return EVAL_OK;
823 break;
825 case V_QIDVEC:
826 len = strtonum(field, 0, MAXWELEM, &errstr);
827 if (errstr != NULL) {
828 before_printing();
829 printf("can't access qid #%s: %s\n", field, errstr);
830 return EVAL_ERR;
833 if (len >= a->v.qidvec.len) {
834 before_printing();
835 printf("can't access qid #%d: out-of-bound "
836 "(max %zu)\n", len, a->v.qidvec.len);
837 return EVAL_ERR;
840 ret->type = V_QID;
841 memcpy(&ret->v.qid, a->v.qidvec.start + len * QIDSIZE,
842 QIDSIZE);
844 return EVAL_OK;
846 default:
847 break;
850 before_printing();
851 printf("can't access field `%s' on type %s (", field, val_type(a));
852 pp_val(a);
853 printf(")\n");
854 return EVAL_ERR;
856 #undef MSGTYPE
859 void
860 pp_op(struct op *op)
862 struct op *aux;
864 switch (op->type) {
865 case OP_REST:
866 printf("...");
867 break;
868 case OP_ASSIGN:
869 printf("%s = ", op->v.assign.name);
870 pp_op(op->v.assign.expr);
871 break;
872 case OP_ASSERT:
873 printf("assert ");
874 pp_op(op->v.assert);
875 break;
876 case OP_FUNCALL:
877 printf("funcall %s(", op->v.funcall.proc->name);
878 for (aux = op->v.funcall.argv; aux != NULL; aux = aux->next) {
879 pp_op(aux);
880 if (aux->next != NULL)
881 printf(", ");
883 printf(")");
884 break;
885 case OP_LITERAL:
886 pp_val(&op->v.literal);
887 break;
888 case OP_VAR:
889 printf("%s", op->v.var);
890 break;
891 case OP_CAST:
892 pp_op(op->v.cast.expr);
893 printf(":");
894 switch (op->v.cast.totype) {
895 case V_U8: printf("u8"); break;
896 case V_U16: printf("u16"); break;
897 case V_U32: printf("u32"); break;
898 case V_STR: printf("str"); break;
899 default: printf("???"); break;
901 break;
902 case OP_CMP_EQ:
903 pp_op(op->v.bin_cmp.a);
904 printf(" == ");
905 pp_op(op->v.bin_cmp.b);
906 break;
907 case OP_CMP_LEQ:
908 pp_op(op->v.bin_cmp.a);
909 printf(" <= ");
910 pp_op(op->v.bin_cmp.b);
911 break;
912 case OP_FACCESS:
913 pp_op(op->v.faccess.expr);
914 printf(".%s", op->v.faccess.field);
915 break;
916 case OP_SFAIL:
917 printf("should-fail ");
918 pp_op(op->v.sfail.expr);
919 if (op->v.sfail.msg != NULL)
920 printf(": \"%s\"", op->v.sfail.msg);
921 break;
922 case OP_VARGS:
923 printf("vargs");
924 break;
925 default:
926 printf(" ???[%d] ", op->type);
930 void
931 pp_block(struct op *op)
933 while (op != NULL) {
934 printf("> ");
935 pp_op(op);
936 printf("\n");
938 op = op->next;
942 int
943 eval(struct op *op)
945 struct value a, b;
946 struct proc *proc;
947 struct op *t, *tnext;
948 int i, ret;
950 #if DEBUG
951 pp_op(op);
952 printf("\n");
953 #endif
955 switch (op->type) {
956 case OP_REST:
957 /*
958 * Try to load the rest argument. Note that it can be
959 * empty!
960 */
961 if ((ret = getvar_raw("...", &t)) == EVAL_OK)
962 if ((ret = eval(t)) != EVAL_OK)
963 return ret;
964 break;
966 case OP_ASSIGN:
967 ret = setvar(op->v.assign.name, op->v.assign.expr);
968 if (ret != EVAL_OK)
969 return ret;
970 break;
972 case OP_ASSERT:
973 if ((ret = eval(op->v.assert)) != EVAL_OK)
974 return ret;
975 popv(&a);
976 if (!val_trueish(&a)) {
977 before_printing();
978 printf("assertion failed: ");
979 pp_op(op->v.assert);
980 printf("\n");
981 return EVAL_ERR;
983 break;
985 case OP_FUNCALL:
986 /* assume airity matches */
988 proc = op->v.funcall.proc;
989 if (proc->nativefn != NULL) {
990 /*
991 * Push arguments on the stack for builtin
992 * functions. Counting the height of the
993 * stack is done to compute the correct number
994 * in the vararg case. argc only counts the
995 * "syntactical" arguments, i.e. foo(x, ...)
996 * has argc == 2, but at runtime argc may be
997 * 1, 2 or a greater number!
998 */
1000 i = stackh;
1001 t = op->v.funcall.argv;
1002 if (t != NULL && (ret = eval(t)) != EVAL_OK)
1003 return ret;
1004 i = stackh - i;
1006 assert(i >= 0);
1008 if ((ret = proc->nativefn(i))
1009 != EVAL_OK)
1010 return ret;
1011 } else {
1012 if (proc->body == NULL) {
1013 before_printing();
1014 printf("warn: calling the empty proc `%s'\n",
1015 proc->name);
1016 break;
1019 pushenv();
1021 for (t = op->v.funcall.argv, i = 0;
1022 t != NULL;
1023 t = t->next, i++) {
1025 * Push a pseudo variable `...' (and
1026 * don't evaluate it) in the vararg
1027 * case. A special case is when the
1028 * variable is itself `...'.
1030 if (proc->vararg && i == proc->minargs) {
1031 if (t->type != OP_REST)
1032 setvar_raw(xstrdup("..."), t);
1033 break;
1037 * The arguments are a linked list of
1038 * ops. Setvar will call eval that
1039 * will evaluate *all* the arguments.
1040 * The dance here that sets next to
1041 * NULL and then restores it is to
1042 * avoid this behaviour.
1044 tnext = t->next;
1045 t->next = NULL;
1046 ret = setvar(proc->args[i], t);
1047 t->next = tnext;
1049 if (ret != EVAL_OK)
1050 return ret;
1053 if ((ret = eval(proc->body)) != EVAL_OK)
1054 return ret;
1056 popenv();
1059 break;
1061 case OP_LITERAL:
1062 pushv(&op->v.literal);
1063 break;
1065 case OP_VAR:
1066 if ((ret = getvar(op->v.var, &a)) != EVAL_OK)
1067 return ret;
1068 pushv(&a);
1069 break;
1071 case OP_CAST:
1072 if ((ret = eval(op->v.cast.expr)) != EVAL_OK)
1073 return ret;
1074 popv(&a);
1075 if ((ret = val_cast(&a, op->v.cast.totype)) != EVAL_OK)
1076 return ret;
1077 pushv(&a);
1078 break;
1080 case OP_CMP_EQ:
1081 if ((ret = eval(op->v.bin_cmp.a)) != EVAL_OK)
1082 return ret;
1083 if ((ret = eval(op->v.bin_cmp.b)) != EVAL_OK)
1084 return ret;
1086 popv(&b);
1087 popv(&a);
1088 pushbool(val_eq(&a, &b));
1089 break;
1091 case OP_CMP_LEQ:
1092 if ((ret = eval(op->v.bin_cmp.a)) != EVAL_OK)
1093 return ret;
1094 if ((ret = eval(op->v.bin_cmp.b)) != EVAL_OK)
1095 return ret;
1097 popv(&b);
1098 popv(&a);
1099 pushbool(val_leq(&a, &b));
1100 break;
1102 case OP_FACCESS:
1103 if ((ret = eval(op->v.faccess.expr)) != EVAL_OK)
1104 return ret;
1105 popv(&a);
1106 if ((ret = val_faccess(&a, op->v.faccess.field, &b))
1107 != EVAL_OK)
1108 return ret;
1109 pushv(&b);
1110 break;
1112 case OP_SFAIL:
1113 if ((ret = eval(op->v.sfail.expr)) == EVAL_OK) {
1114 before_printing();
1115 printf("expecting failure");
1116 if (op->v.sfail.msg != NULL)
1117 printf(" \"%s\"", op->v.sfail.msg);
1118 printf("\n");
1119 printf("expression: ");
1120 pp_op(op->v.sfail.expr);
1121 printf("\n");
1122 return EVAL_ERR;
1124 if (ret == EVAL_SKIP)
1125 return ret;
1126 break;
1128 case OP_VARGS:
1129 if ((ret = getvar_raw("...", &t)) == EVAL_OK) {
1130 for (i = 0; t != NULL; t = t->next)
1131 i++;
1132 pushnum(i);
1133 } else
1134 pushnum(0);
1135 break;
1137 default:
1138 before_printing();
1139 fprintf(stderr, "invalid op, aborting.\n");
1140 abort();
1143 if (op->next)
1144 return eval(op->next);
1145 return EVAL_OK;
1148 void
1149 prepare_funcall(void)
1151 pushstack(&args);
1154 void
1155 push_arg(struct op *op)
1157 push(&args, op);
1160 struct op *
1161 op_funcall(struct proc *proc)
1163 struct op *op, *argv;
1164 int argc;
1166 argv = finalize(&args, &argc);
1168 op = newop(OP_FUNCALL);
1169 op->v.funcall.proc = proc;
1170 op->v.funcall.argv = argv;
1171 op->v.funcall.argc = argc;
1173 return op;
1176 void
1177 add_builtin_proc(const char *name, int (*fn)(int), int argc, int vararg)
1179 struct proc *proc;
1181 proc = xcalloc(1, sizeof(*proc));
1182 proc->name = xstrdup(name);
1183 proc->nativefn = fn;
1184 proc->minargs = argc;
1185 proc->vararg = vararg;
1187 TAILQ_INSERT_HEAD(&procs, proc, entry);
1190 void
1191 prepare_proc(void)
1193 pushstack(&args);
1196 int
1197 proc_setup_body(void)
1199 struct opstack *argv;
1200 struct op *op;
1201 int i;
1203 argv = peek(&args);
1204 for (i = 0, op = argv->base.next; op != NULL; i++) {
1206 * TODO: should free the whole list on error but..,
1207 * we're gonna exit real soon(tm)!
1209 if (op->type != OP_VAR && op->type != OP_REST)
1210 return 0;
1212 op = op->next;
1215 assert(i == argv->counter);
1216 pushstack(&blocks);
1217 return 1;
1220 void
1221 proc_done(char *name)
1223 struct proc *proc;
1224 struct op *op, *next, *argv, *body;
1225 int i, argc;
1227 argv = finalize(&args, &argc);
1228 body = finalize(&blocks, NULL);
1230 proc = xcalloc(1, sizeof(*proc));
1231 proc->name = name;
1232 proc->minargs = argc;
1234 for (i = 0, op = argv; op != NULL; ++i) {
1235 if (op->type == OP_REST) {
1236 proc->vararg = 1;
1237 proc->minargs = i;
1238 break;
1241 proc->args[i] = xstrdup(op->v.var);
1243 next = op->next;
1244 free_op(op);
1245 op = next;
1247 assert(i == argc || (proc->vararg && i == proc->minargs));
1249 proc->body = body;
1251 TAILQ_INSERT_HEAD(&procs, proc, entry);
1254 void
1255 block_push(struct op *op)
1257 push(&blocks, op);
1260 struct proc *
1261 proc_by_name(const char *name)
1263 struct proc *p;
1265 TAILQ_FOREACH(p, &procs, entry) {
1266 if (!strcmp(p->name, name))
1267 return p;
1270 return NULL;
1273 void
1274 prepare_test(void)
1276 pushstack(&blocks);
1279 void
1280 test_done(int shouldfail, char *name, char *dir)
1282 struct test *test;
1284 test = xcalloc(1, sizeof(*test));
1285 test->shouldfail = shouldfail;
1286 test->name = name;
1287 test->dir = dir;
1288 test->body = finalize(&blocks, NULL);
1290 if (TAILQ_EMPTY(&tests))
1291 TAILQ_INSERT_HEAD(&tests, test, entry);
1292 else
1293 TAILQ_INSERT_TAIL(&tests, test, entry);
1295 ntests++;
1298 static int
1299 builtin_print(int argc)
1301 struct value v;
1302 int i;
1304 before_printing();
1306 for (i = argc; i > 0; --i) {
1307 peekn(i, &v);
1308 if (v.type == V_STR)
1309 printf("%s", v.v.str);
1310 else
1311 pp_val(&v);
1312 printf(" ");
1315 printf("\n");
1317 popvn(argc);
1319 return EVAL_OK;
1322 static int
1323 builtin_debug(int argc)
1325 if (debug)
1326 return builtin_print(argc);
1328 popvn(argc);
1329 return EVAL_OK;
1332 static int
1333 builtin_skip(int argc)
1335 return EVAL_SKIP;
1338 static int
1339 builtin_iota(int argc)
1341 struct value v;
1343 v.type = V_U16;
1344 if ((v.v.u16 = ++lasttag) == 255)
1345 v.v.u16 = ++lasttag;
1347 pushv(&v);
1348 return EVAL_OK;
1351 static int
1352 builtin_send(int argc)
1354 struct ibuf *buf;
1355 struct value v;
1356 uint32_t len;
1357 uint16_t slen;
1358 int i;
1360 check_for_output();
1363 * Compute the length of the packet. 4 is for the initial
1364 * length field
1366 len = 4;
1368 for (i = argc; i > 0; --i) {
1369 peekn(i, &v);
1370 switch (v.type) {
1371 case V_STR:
1372 len += 2; /* count */
1373 len += strlen(v.v.str);
1374 break;
1376 case V_U8:
1377 len += 1;
1378 break;
1380 case V_U16:
1381 len += 2;
1382 break;
1384 case V_U32:
1385 len += 4;
1386 break;
1388 default:
1389 before_printing();
1390 printf("%s: can't serialize ", __func__);
1391 pp_val(&v);
1392 printf("\n");
1393 return EVAL_ERR;
1397 if (len > UINT16_MAX) {
1398 before_printing();
1399 printf("%s: message size too long: got %d when max is %d\n",
1400 __func__, len, UINT16_MAX);
1401 return EVAL_ERR;
1404 if ((buf = imsg_create(&ibuf, IMSG_BUF, 0, 0, len)) == NULL)
1405 fatal("imsg_create(%d)", len);
1407 len = htole32(len);
1408 imsg_add(buf, &len, sizeof(len));
1410 for (i = argc; i > 0; --i) {
1411 peekn(i, &v);
1412 switch (v.type) {
1413 case V_STR:
1414 slen = strlen(v.v.str);
1415 slen = htole16(slen);
1416 imsg_add(buf, &slen, sizeof(slen));
1417 imsg_add(buf, v.v.str, strlen(v.v.str));
1418 break;
1420 case V_U8:
1421 imsg_add(buf, &v.v.u8, 1);
1422 break;
1424 case V_U16:
1425 v.v.u16 = htole16(v.v.u16);
1426 imsg_add(buf, &v.v.u16, 2);
1427 break;
1429 case V_U32:
1430 v.v.u32 = htole32(v.v.u32);
1431 imsg_add(buf, &v.v.u32, 4);
1432 break;
1436 imsg_close(&ibuf, buf);
1438 if (imsg_flush(&ibuf) == -1) {
1439 i = errno;
1440 before_printing();
1441 printf("%s: imsg_flush failed: %s\n", __func__, strerror(i));
1442 return EVAL_ERR;
1445 check_for_output();
1446 return EVAL_OK;
1449 static int
1450 builtin_recv(int argc)
1452 struct pollfd pfd;
1453 struct value v;
1454 struct imsg imsg;
1455 ssize_t n, datalen;
1456 int serrno;
1458 if (lastmsg != NULL) {
1459 free(lastmsg);
1460 lastmsg = NULL;
1463 pfd.fd = ibuf.fd;
1464 pfd.events = POLLIN;
1465 if (poll(&pfd, 1, INFTIM) == -1) {
1466 serrno = errno;
1467 before_printing();
1468 printf("%s: poll failed: %s\n", __func__, strerror(serrno));
1469 return EVAL_ERR;
1472 again:
1473 if ((n = imsg_read(&ibuf)) == -1) {
1474 if (errno == EAGAIN)
1475 goto again;
1476 fatal("imsg_read");
1478 if (n == 0) {
1479 disconnect:
1480 before_printing();
1481 printf("child disconnected\n");
1482 return EVAL_ERR;
1485 nextmessage:
1486 check_for_output();
1488 /* read only one message */
1489 if ((n = imsg_get(&ibuf, &imsg)) == -1)
1490 fatal("imsg_get");
1491 if (n == 0)
1492 goto disconnect;
1494 datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
1495 switch (imsg.hdr.type) {
1496 case IMSG_BUF:
1497 v.type = V_MSG;
1498 if ((v.v.msg.msg = malloc(datalen)) == NULL)
1499 fatal("malloc");
1500 memcpy(v.v.msg.msg, imsg.data, datalen);
1501 v.v.msg.len = datalen;
1502 pushv(&v);
1503 imsg_free(&imsg);
1504 return EVAL_OK;
1506 case IMSG_CLOSE:
1507 before_printing();
1508 printf("subprocess closed the connection\n");
1509 imsg_free(&imsg);
1510 return EVAL_ERR;
1512 case IMSG_MSIZE:
1513 imsg_free(&imsg);
1514 goto nextmessage;
1516 default:
1517 before_printing();
1518 printf("got unknown message from subprocess: %d\n",
1519 imsg.hdr.type);
1520 imsg_free(&imsg);
1521 return EVAL_ERR;
1525 static pid_t
1526 spawn_client_proc(void)
1528 const char *argv[4];
1529 int p[2], out[2], argc = 0;
1530 pid_t pid;
1532 if (child_out != -1)
1533 close(child_out);
1535 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1536 PF_UNSPEC, p) == -1)
1537 fatal("socketpair");
1539 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1540 PF_UNSPEC, out) == -1)
1541 fatal("socketpair");
1543 switch (pid = fork()) {
1544 case -1:
1545 fatal("cannot fork");
1546 case 0:
1547 break;
1548 default:
1549 close(p[1]);
1550 close(out[1]);
1551 child_out = out[0];
1552 if (ibuf_inuse) {
1553 msgbuf_clear(&ibuf.w);
1554 close(ibuf.fd);
1556 imsg_init(&ibuf, p[0]);
1557 ibuf_inuse = 1;
1558 return pid;
1561 close(p[0]);
1562 close(out[0]);
1564 if (dup2(out[1], 1) == -1 ||
1565 dup2(out[1], 2) == -1)
1566 fatal("dup2");
1568 if (p[1] != 3) {
1569 if (dup2(p[1], 3) == -1)
1570 fatal("cannot setup imsg fd");
1571 } else if (fcntl(F_SETFD, 0) == -1)
1572 fatal("cannot setup imsg fd");
1574 argv[argc++] = argv0;
1575 argv[argc++] = "-Tc";
1577 #if DEBUG
1578 argv[argc++] = "-v";
1579 #endif
1581 argv[argc++] = NULL;
1583 execvp(argv0, (char *const *)argv);
1584 fatal("execvp");
1587 static void
1588 prepare_child_for_test(struct test *t)
1590 struct passwd *pw;
1591 struct stat sb;
1593 if (stat(t->dir, &sb) == -1)
1594 fatal("stat(\"%s\")", t->dir);
1596 if ((pw = getpwuid(sb.st_uid)) == NULL)
1597 fatal("getpwuid(%d)", sb.st_uid);
1599 imsg_compose(&ibuf, IMSG_AUTH, 0, 0, -1,
1600 pw->pw_name, strlen(pw->pw_name)+1);
1601 imsg_compose(&ibuf, IMSG_AUTH_DIR, 0, 0, -1,
1602 t->dir, strlen(t->dir)+1);
1604 if (imsg_flush(&ibuf) == -1)
1605 fatal("imsg_flush");
1608 static int
1609 run_test(struct test *t)
1611 pid_t pid;
1612 int ret;
1614 #if DEBUG
1615 before_printing();
1616 puts("=====================");
1617 pp_block(t->body);
1618 puts("=====================");
1619 #endif
1621 if (stackh != 0)
1622 popvn(stackh);
1624 if (t->body == NULL) {
1625 before_printing();
1626 printf("no instructions, skipping...\n");
1627 return EVAL_SKIP;
1630 pid = spawn_client_proc();
1631 prepare_child_for_test(t);
1632 ret = eval(t->body);
1634 imsg_compose(&ibuf, IMSG_CONN_GONE, 0, 0, -1, NULL, 0);
1635 imsg_flush(&ibuf);
1637 while (waitpid(pid, NULL, 0) != pid)
1638 ; /* nop */
1640 check_for_output();
1642 if (t->shouldfail) {
1643 if (ret == EVAL_OK) {
1644 before_printing();
1645 printf("test was expected to fail\n");
1646 return EVAL_ERR;
1647 } else if (ret == EVAL_ERR)
1648 return EVAL_OK;
1651 return ret;
1654 int
1655 main(int argc, char **argv)
1657 struct test *t;
1658 int ch, i, r, passed = 0, failed = 0, skipped = 0;
1659 int runclient = 0;
1660 const char *pat = NULL;
1661 regex_t reg;
1663 assert(argv0 = argv[0]);
1665 signal(SIGPIPE, SIG_IGN);
1667 log_init(1, LOG_DAEMON);
1668 log_setverbose(1);
1670 /* prepare the global env */
1671 pushenv();
1673 add_builtin_proc("print", builtin_print, 1, 1);
1674 add_builtin_proc("debug", builtin_debug, 1, 1);
1675 add_builtin_proc("skip", builtin_skip, 0, 0);
1676 add_builtin_proc("iota", builtin_iota, 0, 0);
1677 add_builtin_proc("send", builtin_send, 2, 1);
1678 add_builtin_proc("recv", builtin_recv, 0, 0);
1680 while ((ch = getopt(argc, argv, "nT:vx:")) != -1) {
1681 switch (ch) {
1682 case 'n':
1683 syntaxcheck = 1;
1684 break;
1685 case 'T':
1686 assert(*optarg == 'c');
1687 runclient = 1;
1688 break;
1689 case 'v':
1690 debug = 1;
1691 break;
1692 case 'x':
1693 pat = optarg;
1694 break;
1695 default:
1696 fprintf(stderr, "Usage: %s [-nv] [files...]\n",
1697 *argv);
1698 exit(1);
1701 argc -= optind;
1702 argv += optind;
1704 if (runclient)
1705 client(1, debug);
1707 if (pat == NULL)
1708 pat = ".*";
1710 if (regcomp(&reg, pat, REG_BASIC | REG_ICASE | REG_NOSUB) != 0)
1711 fatalx("invalid regexp: %s", pat);
1713 for (i = 0; i < argc; ++i)
1714 loadfile(argv[i]);
1716 if (syntaxcheck) {
1717 fprintf(stderr, "files OK\n");
1718 return 0;
1721 /* Check for root privileges. */
1722 if (geteuid())
1723 fatalx("need root privileges");
1725 i = 0;
1726 TAILQ_FOREACH(t, &tests, entry) {
1727 if (regexec(&reg, t->name, 0, NULL, 0) != 0)
1728 continue;
1730 printf("===> [%d/%d] running test \"%s\"... ", i+1, ntests,
1731 t->name);
1732 fflush(stdout);
1734 filler = "\n";
1735 r = run_test(t);
1736 if (filler == NULL)
1737 printf("=> test ");
1739 switch (r) {
1740 case EVAL_OK:
1741 printf("passed\n");
1742 passed++;
1743 break;
1744 case EVAL_ERR:
1745 failed++;
1746 printf("failed\n");
1747 break;
1748 case EVAL_SKIP:
1749 printf("skipped\n");
1750 skipped++;
1751 break;
1754 if (filler == NULL)
1755 printf("\n");
1756 i++;
1759 printf("\n");
1760 printf("%d/%d passed (%d skipped and %d failed)\n",
1761 passed, i, skipped, failed);
1763 popenv();
1764 free(lastmsg);
1765 regfree(&reg);
1767 return failed != 0;