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 free_op_rec(op->v.cmp_eq.a);
432 free_op_rec(op->v.cmp_eq.b);
433 break;
434 case OP_FACCESS:
435 free_op_rec(op->v.faccess.expr);
436 free(op->v.faccess.field);
437 break;
438 case OP_SFAIL:
439 free(op->v.sfail.msg);
440 free_op_rec(op->v.sfail.expr);
441 break;
442 default:
443 /* unreachable */
444 abort();
447 free(op);
450 struct op *
451 op_rest(void)
453 return newop(OP_REST);
456 struct op *
457 op_assign(char *sym, struct op *expr)
459 struct op *op;
461 op = newop(OP_ASSIGN);
462 op->v.assign.name = sym;
463 op->v.assign.expr = expr;
465 return op;
468 struct op *
469 op_assert(struct op *expr)
471 struct op *op;
473 op = newop(OP_ASSERT);
474 op->v.assert = expr;
476 return op;
479 struct op *
480 op_var(char *sym)
482 struct op *op;
484 op = newop(OP_VAR);
485 op->v.var = sym;
487 return op;
490 struct op *
491 op_lit_str(char *str)
493 struct op *op;
495 op = newop(OP_LITERAL);
496 op->v.literal.type = V_STR;
497 op->v.literal.v.str = str;
499 return op;
502 struct op *
503 op_lit_num(uint64_t n)
505 struct op *op;
507 op = newop(OP_LITERAL);
508 op->v.literal.type = V_NUM;
509 op->v.literal.v.num = n;
511 return op;
514 struct op *
515 op_cmp_eq(struct op *a, struct op *b)
517 struct op *op;
519 op = newop(OP_CMP_EQ);
520 op->v.cmp_eq.a = a;
521 op->v.cmp_eq.b = b;
523 return op;
526 struct op *
527 op_cast(struct op *expr, int totype)
529 struct op *op;
531 op = newop(OP_CAST);
532 op->v.cast.expr = expr;
533 op->v.cast.totype = totype;
535 return op;
538 struct op *
539 op_faccess(struct op *expr, char *field)
541 struct op *op;
543 op = newop(OP_FACCESS);
544 op->v.faccess.expr = expr;
545 op->v.faccess.field = field;
547 return op;
550 struct op *
551 op_sfail(struct op *expr, char *msg)
553 struct op *op;
555 op = newop(OP_SFAIL);
556 op->v.sfail.expr = expr;
557 op->v.sfail.msg = msg;
559 return op;
562 struct op *
563 op_vargs(void)
565 struct op *op;
567 op = newop(OP_VARGS);
569 return op;
572 void
573 ppf_val(FILE *f, struct value *val)
575 size_t i;
577 switch (val->type) {
578 case V_SYM:
579 fprintf(f, "%s", val->v.str);
580 break;
581 case V_STR:
582 fprintf(f, "\"%s\"", val->v.str);
583 break;
584 case V_NUM:
585 fprintf(f, "%"PRIi64, val->v.num);
586 break;
587 case V_U8:
588 fprintf(f, "%"PRIu8, val->v.u8);
589 break;
590 case V_U16:
591 fprintf(f, "%"PRIu16, val->v.u16);
592 break;
593 case V_U32:
594 fprintf(f, "%"PRIu32, val->v.u32);
595 break;
596 case V_MSG:
597 fprintf(f, "(");
598 for (i = 0; i < val->v.msg.len; ++i)
599 fprintf(f, "%x%s", val->v.msg.msg[i],
600 i == val->v.msg.len-1 ? "" : " ");
601 fprintf(f, ")");
602 break;
603 case V_QIDVEC:
604 fprintf(f, "qids[n=%zu]", val->v.qidvec.len);
605 break;
606 default:
607 fprintf(f, "<unknown value>");
608 break;
612 void
613 pp_val(struct value *val)
615 ppf_val(stdout, val);
618 const char *
619 val_type(struct value *v)
621 switch (v->type) {
622 case V_SYM: return "symbol";
623 case V_STR: return "string";
624 case V_NUM: return "number";
625 case V_MSG: return "message";
626 case V_QID: return "qid";
627 case V_U8: return "u8";
628 case V_U16: return "u16";
629 case V_U32: return "u32";
630 default: return "unknown";
634 int
635 val_trueish(struct value *a)
637 if (val_isnum(a))
638 return val_tonum(a);
639 return 1;
642 int
643 val_isnum(struct value *a)
645 return a->type == V_NUM
646 || a->type == V_U8
647 || a->type == V_U16
648 || a->type == V_U32;
651 int64_t
652 val_tonum(struct value *a)
654 switch (a->type) {
655 case V_NUM: return a->v.num;
656 case V_U8: return a->v.u8;
657 case V_U16: return a->v.u16;
658 case V_U32: return a->v.u32;
659 default:
660 before_printing();
661 fprintf(stderr, "%s: given value is not a number\n", __func__);
662 abort();
666 int
667 val_eq(struct value *a, struct value *b)
669 if (val_isnum(a) && val_isnum(b))
670 return val_tonum(a) == val_tonum(b);
672 if (a->type != b->type)
673 return 0;
675 switch (a->type) {
676 case V_STR:
677 case V_SYM:
678 return !strcmp(a->v.str, b->v.str);
681 return 0;
684 static inline const char *
685 pp_totype(int totype)
687 /*
688 * Not all of these are valid cast type thought, including
689 * every possibility only to aid debugging.
690 */
691 switch (totype) {
692 case V_STR: return "str";
693 case V_SYM: return "sym";
694 case V_NUM: return "num";
695 case V_QID: return "qid";
696 case V_U8: return "u8";
697 case V_U16: return "u16";
698 case V_U32: return "u32";
699 default: return "unknown";
703 int
704 val_cast(struct value *a, int totype)
706 int64_t v;
708 #define NUMCAST(val, t, c, totype, max) do { \
709 if (val > max) { \
710 before_printing(); \
711 fprintf(stderr, "can't cast %"PRIu64 \
712 " to %s\n", val, pp_totype(totype)); \
713 return EVAL_ERR; \
714 } \
715 a->type = totype; \
716 a->v.t = (c)val; \
717 return EVAL_OK; \
718 } while (0)
720 if (a->type == totype)
721 return EVAL_OK;
723 if (!val_isnum(a)) {
724 before_printing();
725 fprintf(stderr, "can't cast ");
726 ppf_val(stderr, a);
727 fprintf(stderr, " to type %s\n", pp_totype(totype));
728 return EVAL_ERR;
731 v = a->v.num;
732 switch (totype) {
733 case V_U8: NUMCAST(v, u8, uint8_t, totype, UINT8_MAX);
734 case V_U16: NUMCAST(v, u16, uint16_t, totype, UINT16_MAX);
735 case V_U32: NUMCAST(v, u32, uint32_t, totype, UINT32_MAX);
736 default:
737 before_printing();
738 fprintf(stderr, "can't cast %"PRIu64" to %s\n",
739 v, pp_totype(totype));
740 return EVAL_ERR;
743 #undef NUMCAST
746 int
747 val_faccess(struct value *a, const char *field, struct value *ret)
749 uint8_t mtype;
750 uint16_t len;
751 const char *errstr;
753 #define MSGTYPE(m) *(m.msg + 4) /* skip the length */
755 switch (a->type) {
756 case V_QID:
757 /* TODO: add path. needs uint64_t values thought! */
758 if (!strcmp(field, "vers")) {
759 ret->type = V_U32;
760 memcpy(&ret->v.u32, a->v.qid+1, 4);
761 return EVAL_OK;
762 } else if (!strcmp(field, "type")) {
763 ret->type = V_U8;
764 ret->v.u8 = *a->v.qid;
765 return EVAL_OK;
767 break;
769 case V_MSG:
770 mtype = MSGTYPE(a->v.msg);
771 if (!strcmp(field, "type")) {
772 ret->type = V_U8;
773 ret->v.u8 = MSGTYPE(a->v.msg);
774 return EVAL_OK;
775 } else if (!strcmp(field, "tag")) {
776 ret->type = V_U16;
777 memcpy(&ret->v.u16, &a->v.msg.msg[5], 2);
778 ret->v.u16 = le16toh(ret->v.u16);
779 return EVAL_OK;
780 } else if (!strcmp(field, "msize") && mtype == Rversion) {
781 ret->type = V_U32;
782 memcpy(&ret->v.u32, &a->v.msg.msg[7], 4);
783 ret->v.u32 = le32toh(ret->v.u32);
784 return EVAL_OK;
785 } else if (!strcmp(field, "qid") && mtype == Rattach) {
786 ret->type = V_QID;
787 memcpy(&ret->v.qid, &a->v.msg.msg[7], QIDSIZE);
788 return EVAL_OK;
789 } else if (!strcmp(field, "nwqid") && mtype == Rwalk) {
790 ret->type = V_U16;
791 memcpy(&ret->v.u16, &a->v.msg.msg[7], 2);
792 ret->v.u16 = le16toh(ret->v.u16);
793 return EVAL_OK;
794 } else if (!strcmp(field, "wqid") && mtype == Rwalk) {
795 ret->type = V_QIDVEC;
796 ret->v.qidvec.start = &a->v.msg.msg[9];
797 memcpy(&len, &a->v.msg.msg[7], 2);
798 len = le16toh(len);
799 ret->v.qidvec.len = len;
800 return EVAL_OK;
802 break;
804 case V_QIDVEC:
805 len = strtonum(field, 0, MAXWELEM, &errstr);
806 if (errstr != NULL) {
807 before_printing();
808 printf("can't access qid #%s: %s\n", field, errstr);
809 return EVAL_ERR;
812 if (len >= a->v.qidvec.len) {
813 before_printing();
814 printf("can't access qid #%d: out-of-bound "
815 "(max %zu)\n", len, a->v.qidvec.len);
816 return EVAL_ERR;
819 ret->type = V_QID;
820 memcpy(&ret->v.qid, a->v.qidvec.start + len * QIDSIZE,
821 QIDSIZE);
823 return EVAL_OK;
825 default:
826 break;
829 before_printing();
830 printf("can't access field `%s' on type %s (", field, val_type(a));
831 pp_val(a);
832 printf(")\n");
833 return EVAL_ERR;
835 #undef MSGTYPE
838 void
839 pp_op(struct op *op)
841 struct op *aux;
843 switch (op->type) {
844 case OP_REST:
845 printf("...");
846 break;
847 case OP_ASSIGN:
848 printf("%s = ", op->v.assign.name);
849 pp_op(op->v.assign.expr);
850 break;
851 case OP_ASSERT:
852 printf("assert ");
853 pp_op(op->v.assert);
854 break;
855 case OP_FUNCALL:
856 printf("funcall %s(", op->v.funcall.proc->name);
857 for (aux = op->v.funcall.argv; aux != NULL; aux = aux->next) {
858 pp_op(aux);
859 if (aux->next != NULL)
860 printf(", ");
862 printf(")");
863 break;
864 case OP_LITERAL:
865 pp_val(&op->v.literal);
866 break;
867 case OP_VAR:
868 printf("%s", op->v.var);
869 break;
870 case OP_CAST:
871 pp_op(op->v.cast.expr);
872 printf(":");
873 switch (op->v.cast.totype) {
874 case V_U8: printf("u8"); break;
875 case V_U16: printf("u16"); break;
876 case V_U32: printf("u32"); break;
877 case V_STR: printf("str"); break;
878 default: printf("???"); break;
880 break;
881 case OP_CMP_EQ:
882 pp_op(op->v.cmp_eq.a);
883 printf(" == ");
884 pp_op(op->v.cmp_eq.b);
885 break;
886 case OP_FACCESS:
887 pp_op(op->v.faccess.expr);
888 printf(".%s", op->v.faccess.field);
889 break;
890 case OP_SFAIL:
891 printf("should-fail ");
892 pp_op(op->v.sfail.expr);
893 if (op->v.sfail.msg != NULL)
894 printf(": \"%s\"", op->v.sfail.msg);
895 break;
896 case OP_VARGS:
897 printf("vargs");
898 break;
899 default:
900 printf(" ???[%d] ", op->type);
904 void
905 pp_block(struct op *op)
907 while (op != NULL) {
908 printf("> ");
909 pp_op(op);
910 printf("\n");
912 op = op->next;
916 int
917 eval(struct op *op)
919 struct value a, b;
920 struct proc *proc;
921 struct op *t, *tnext;
922 int i, ret;
924 #if DEBUG
925 pp_op(op);
926 printf("\n");
927 #endif
929 switch (op->type) {
930 case OP_REST:
931 /*
932 * Try to load the rest argument. Note that it can be
933 * empty!
934 */
935 if ((ret = getvar_raw("...", &t)) == EVAL_OK)
936 if ((ret = eval(t)) != EVAL_OK)
937 return ret;
938 break;
940 case OP_ASSIGN:
941 ret = setvar(op->v.assign.name, op->v.assign.expr);
942 if (ret != EVAL_OK)
943 return ret;
944 break;
946 case OP_ASSERT:
947 if ((ret = eval(op->v.assert)) != EVAL_OK)
948 return ret;
949 popv(&a);
950 if (!val_trueish(&a)) {
951 before_printing();
952 printf("assertion failed: ");
953 pp_op(op->v.assert);
954 printf("\n");
955 return EVAL_ERR;
957 break;
959 case OP_FUNCALL:
960 /* assume airity matches */
962 proc = op->v.funcall.proc;
963 if (proc->nativefn != NULL) {
964 /*
965 * Push arguments on the stack for builtin
966 * functions. Counting the height of the
967 * stack is done to compute the correct number
968 * in the vararg case. argc only counts the
969 * "syntactical" arguments, i.e. foo(x, ...)
970 * has argc == 2, but at runtime argc may be
971 * 1, 2 or a greater number!
972 */
974 i = stackh;
975 t = op->v.funcall.argv;
976 if (t != NULL && (ret = eval(t)) != EVAL_OK)
977 return ret;
978 i = stackh - i;
980 assert(i >= 0);
982 if ((ret = proc->nativefn(i))
983 != EVAL_OK)
984 return ret;
985 } else {
986 if (proc->body == NULL) {
987 before_printing();
988 printf("warn: calling the empty proc `%s'\n",
989 proc->name);
990 break;
993 pushenv();
995 for (t = op->v.funcall.argv, i = 0;
996 t != NULL;
997 t = t->next, i++) {
998 /*
999 * Push a pseudo variable `...' (and
1000 * don't evaluate it) in the vararg
1001 * case. A special case is when the
1002 * variable is itself `...'.
1004 if (proc->vararg && i == proc->minargs) {
1005 if (t->type != OP_REST)
1006 setvar_raw(xstrdup("..."), t);
1007 break;
1011 * The arguments are a linked list of
1012 * ops. Setvar will call eval that
1013 * will evaluate *all* the arguments.
1014 * The dance here that sets next to
1015 * NULL and then restores it is to
1016 * avoid this behaviour.
1018 tnext = t->next;
1019 t->next = NULL;
1020 ret = setvar(proc->args[i], t);
1021 t->next = tnext;
1023 if (ret != EVAL_OK)
1024 return ret;
1027 if ((ret = eval(proc->body)) != EVAL_OK)
1028 return ret;
1030 popenv();
1033 break;
1035 case OP_LITERAL:
1036 pushv(&op->v.literal);
1037 break;
1039 case OP_VAR:
1040 if ((ret = getvar(op->v.var, &a)) != EVAL_OK)
1041 return ret;
1042 pushv(&a);
1043 break;
1045 case OP_CAST:
1046 if ((ret = eval(op->v.cast.expr)) != EVAL_OK)
1047 return ret;
1048 popv(&a);
1049 if ((ret = val_cast(&a, op->v.cast.totype)) != EVAL_OK)
1050 return ret;
1051 pushv(&a);
1052 break;
1054 case OP_CMP_EQ:
1055 if ((ret = eval(op->v.cmp_eq.a)) != EVAL_OK)
1056 return ret;
1057 if ((ret = eval(op->v.cmp_eq.b)) != EVAL_OK)
1058 return ret;
1060 popv(&b);
1061 popv(&a);
1062 pushbool(val_eq(&a, &b));
1064 break;
1066 case OP_FACCESS:
1067 if ((ret = eval(op->v.faccess.expr)) != EVAL_OK)
1068 return ret;
1069 popv(&a);
1070 if ((ret = val_faccess(&a, op->v.faccess.field, &b))
1071 != EVAL_OK)
1072 return ret;
1073 pushv(&b);
1074 break;
1076 case OP_SFAIL:
1077 if ((ret = eval(op->v.sfail.expr)) == EVAL_OK) {
1078 before_printing();
1079 printf("expecting failure");
1080 if (op->v.sfail.msg != NULL)
1081 printf(" \"%s\"", op->v.sfail.msg);
1082 printf("\n");
1083 printf("expression: ");
1084 pp_op(op->v.sfail.expr);
1085 printf("\n");
1086 return EVAL_ERR;
1088 if (ret == EVAL_SKIP)
1089 return ret;
1090 break;
1092 case OP_VARGS:
1093 if ((ret = getvar_raw("...", &t)) == EVAL_OK) {
1094 for (i = 0; t != NULL; t = t->next)
1095 i++;
1096 pushnum(i);
1097 } else
1098 pushnum(0);
1099 break;
1101 default:
1102 before_printing();
1103 fprintf(stderr, "invalid op, aborting.\n");
1104 abort();
1107 if (op->next)
1108 return eval(op->next);
1109 return EVAL_OK;
1112 void
1113 prepare_funcall(void)
1115 pushstack(&args);
1118 void
1119 push_arg(struct op *op)
1121 push(&args, op);
1124 struct op *
1125 op_funcall(struct proc *proc)
1127 struct op *op, *argv;
1128 int argc;
1130 argv = finalize(&args, &argc);
1132 op = newop(OP_FUNCALL);
1133 op->v.funcall.proc = proc;
1134 op->v.funcall.argv = argv;
1135 op->v.funcall.argc = argc;
1137 return op;
1140 void
1141 add_builtin_proc(const char *name, int (*fn)(int), int argc, int vararg)
1143 struct proc *proc;
1145 proc = xcalloc(1, sizeof(*proc));
1146 proc->name = xstrdup(name);
1147 proc->nativefn = fn;
1148 proc->minargs = argc;
1149 proc->vararg = vararg;
1151 TAILQ_INSERT_HEAD(&procs, proc, entry);
1154 void
1155 prepare_proc(void)
1157 pushstack(&args);
1160 int
1161 proc_setup_body(void)
1163 struct opstack *argv;
1164 struct op *op;
1165 int i;
1167 argv = peek(&args);
1168 for (i = 0, op = argv->base.next; op != NULL; i++) {
1170 * TODO: should free the whole list on error but..,
1171 * we're gonna exit real soon(tm)!
1173 if (op->type != OP_VAR && op->type != OP_REST)
1174 return 0;
1176 op = op->next;
1179 assert(i == argv->counter);
1180 pushstack(&blocks);
1181 return 1;
1184 void
1185 proc_done(char *name)
1187 struct proc *proc;
1188 struct op *op, *next, *argv, *body;
1189 int i, argc;
1191 argv = finalize(&args, &argc);
1192 body = finalize(&blocks, NULL);
1194 proc = xcalloc(1, sizeof(*proc));
1195 proc->name = name;
1196 proc->minargs = argc;
1198 for (i = 0, op = argv; op != NULL; ++i) {
1199 if (op->type == OP_REST) {
1200 proc->vararg = 1;
1201 proc->minargs = i;
1202 break;
1205 proc->args[i] = xstrdup(op->v.var);
1207 next = op->next;
1208 free_op(op);
1209 op = next;
1211 assert(i == argc || (proc->vararg && i == proc->minargs));
1213 proc->body = body;
1215 TAILQ_INSERT_HEAD(&procs, proc, entry);
1218 void
1219 block_push(struct op *op)
1221 push(&blocks, op);
1224 struct proc *
1225 proc_by_name(const char *name)
1227 struct proc *p;
1229 TAILQ_FOREACH(p, &procs, entry) {
1230 if (!strcmp(p->name, name))
1231 return p;
1234 return NULL;
1237 void
1238 prepare_test(void)
1240 pushstack(&blocks);
1243 void
1244 test_done(int shouldfail, char *name, char *dir)
1246 struct test *test;
1248 test = xcalloc(1, sizeof(*test));
1249 test->shouldfail = shouldfail;
1250 test->name = name;
1251 test->dir = dir;
1252 test->body = finalize(&blocks, NULL);
1254 if (TAILQ_EMPTY(&tests))
1255 TAILQ_INSERT_HEAD(&tests, test, entry);
1256 else
1257 TAILQ_INSERT_TAIL(&tests, test, entry);
1259 ntests++;
1262 static int
1263 builtin_print(int argc)
1265 struct value v;
1266 int i;
1268 before_printing();
1270 for (i = argc; i > 0; --i) {
1271 peekn(i, &v);
1272 if (v.type == V_STR)
1273 printf("%s", v.v.str);
1274 else
1275 pp_val(&v);
1276 printf(" ");
1279 printf("\n");
1281 popvn(argc);
1283 return EVAL_OK;
1286 static int
1287 builtin_debug(int argc)
1289 if (debug)
1290 return builtin_print(argc);
1292 popvn(argc);
1293 return EVAL_OK;
1296 static int
1297 builtin_skip(int argc)
1299 return EVAL_SKIP;
1302 static int
1303 builtin_iota(int argc)
1305 struct value v;
1307 v.type = V_U16;
1308 if ((v.v.u16 = ++lasttag) == 255)
1309 v.v.u16 = ++lasttag;
1311 pushv(&v);
1312 return EVAL_OK;
1315 static int
1316 builtin_send(int argc)
1318 struct ibuf *buf;
1319 struct value v;
1320 uint32_t len;
1321 uint16_t slen;
1322 int i;
1324 check_for_output();
1327 * Compute the length of the packet. 4 is for the initial
1328 * length field
1330 len = 4;
1332 for (i = argc; i > 0; --i) {
1333 peekn(i, &v);
1334 switch (v.type) {
1335 case V_STR:
1336 len += 2; /* count */
1337 len += strlen(v.v.str);
1338 break;
1340 case V_U8:
1341 len += 1;
1342 break;
1344 case V_U16:
1345 len += 2;
1346 break;
1348 case V_U32:
1349 len += 4;
1350 break;
1352 default:
1353 before_printing();
1354 printf("%s: can't serialize ", __func__);
1355 pp_val(&v);
1356 printf("\n");
1357 return EVAL_ERR;
1361 if (len > UINT16_MAX) {
1362 before_printing();
1363 printf("%s: message size too long: got %d when max is %d\n",
1364 __func__, len, UINT16_MAX);
1365 return EVAL_ERR;
1368 if ((buf = imsg_create(&ibuf, IMSG_BUF, 0, 0, len)) == NULL)
1369 fatal("imsg_create(%d)", len);
1371 len = htole32(len);
1372 imsg_add(buf, &len, sizeof(len));
1374 for (i = argc; i > 0; --i) {
1375 peekn(i, &v);
1376 switch (v.type) {
1377 case V_STR:
1378 slen = strlen(v.v.str);
1379 slen = htole16(slen);
1380 imsg_add(buf, &slen, sizeof(slen));
1381 imsg_add(buf, v.v.str, strlen(v.v.str));
1382 break;
1384 case V_U8:
1385 imsg_add(buf, &v.v.u8, 1);
1386 break;
1388 case V_U16:
1389 v.v.u16 = htole16(v.v.u16);
1390 imsg_add(buf, &v.v.u16, 2);
1391 break;
1393 case V_U32:
1394 v.v.u32 = htole32(v.v.u32);
1395 imsg_add(buf, &v.v.u32, 4);
1396 break;
1400 imsg_close(&ibuf, buf);
1402 if (imsg_flush(&ibuf) == -1) {
1403 i = errno;
1404 before_printing();
1405 printf("%s: imsg_flush failed: %s\n", __func__, strerror(i));
1406 return EVAL_ERR;
1409 check_for_output();
1410 return EVAL_OK;
1413 static int
1414 builtin_recv(int argc)
1416 struct pollfd pfd;
1417 struct value v;
1418 struct imsg imsg;
1419 ssize_t n, datalen;
1420 int serrno;
1422 if (lastmsg != NULL) {
1423 free(lastmsg);
1424 lastmsg = NULL;
1427 pfd.fd = ibuf.fd;
1428 pfd.events = POLLIN;
1429 if (poll(&pfd, 1, INFTIM) == -1) {
1430 serrno = errno;
1431 before_printing();
1432 printf("%s: poll failed: %s\n", __func__, strerror(serrno));
1433 return EVAL_ERR;
1436 again:
1437 if ((n = imsg_read(&ibuf)) == -1) {
1438 if (errno == EAGAIN)
1439 goto again;
1440 fatal("imsg_read");
1442 if (n == 0) {
1443 disconnect:
1444 before_printing();
1445 printf("child disconnected\n");
1446 return EVAL_ERR;
1449 nextmessage:
1450 check_for_output();
1452 /* read only one message */
1453 if ((n = imsg_get(&ibuf, &imsg)) == -1)
1454 fatal("imsg_get");
1455 if (n == 0)
1456 goto disconnect;
1458 datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
1459 switch (imsg.hdr.type) {
1460 case IMSG_BUF:
1461 v.type = V_MSG;
1462 if ((v.v.msg.msg = malloc(datalen)) == NULL)
1463 fatal("malloc");
1464 memcpy(v.v.msg.msg, imsg.data, datalen);
1465 v.v.msg.len = datalen;
1466 pushv(&v);
1467 imsg_free(&imsg);
1468 return EVAL_OK;
1470 case IMSG_CLOSE:
1471 before_printing();
1472 printf("subprocess closed the connection\n");
1473 imsg_free(&imsg);
1474 return EVAL_ERR;
1476 case IMSG_MSIZE:
1477 imsg_free(&imsg);
1478 goto nextmessage;
1480 default:
1481 before_printing();
1482 printf("got unknown message from subprocess: %d\n",
1483 imsg.hdr.type);
1484 imsg_free(&imsg);
1485 return EVAL_ERR;
1489 static pid_t
1490 spawn_client_proc(void)
1492 const char *argv[4];
1493 int p[2], out[2], argc = 0;
1494 pid_t pid;
1496 if (child_out != -1)
1497 close(child_out);
1499 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1500 PF_UNSPEC, p) == -1)
1501 fatal("socketpair");
1503 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1504 PF_UNSPEC, out) == -1)
1505 fatal("socketpair");
1507 switch (pid = fork()) {
1508 case -1:
1509 fatal("cannot fork");
1510 case 0:
1511 break;
1512 default:
1513 close(p[1]);
1514 close(out[1]);
1515 child_out = out[0];
1516 if (ibuf_inuse) {
1517 msgbuf_clear(&ibuf.w);
1518 close(ibuf.fd);
1520 imsg_init(&ibuf, p[0]);
1521 ibuf_inuse = 1;
1522 return pid;
1525 close(p[0]);
1526 close(out[0]);
1528 if (dup2(out[1], 1) == -1 ||
1529 dup2(out[1], 2) == -1)
1530 fatal("dup2");
1532 if (p[1] != 3) {
1533 if (dup2(p[1], 3) == -1)
1534 fatal("cannot setup imsg fd");
1535 } else if (fcntl(F_SETFD, 0) == -1)
1536 fatal("cannot setup imsg fd");
1538 argv[argc++] = argv0;
1539 argv[argc++] = "-Tc";
1541 #if DEBUG
1542 argv[argc++] = "-v";
1543 #endif
1545 argv[argc++] = NULL;
1547 execvp(argv0, (char *const *)argv);
1548 fatal("execvp");
1551 static void
1552 prepare_child_for_test(struct test *t)
1554 struct passwd *pw;
1555 struct stat sb;
1557 if (stat(t->dir, &sb) == -1)
1558 fatal("stat(\"%s\")", t->dir);
1560 if ((pw = getpwuid(sb.st_uid)) == NULL)
1561 fatal("getpwuid(%d)", sb.st_uid);
1563 imsg_compose(&ibuf, IMSG_AUTH, 0, 0, -1,
1564 pw->pw_name, strlen(pw->pw_name)+1);
1565 imsg_compose(&ibuf, IMSG_AUTH_DIR, 0, 0, -1,
1566 t->dir, strlen(t->dir)+1);
1568 if (imsg_flush(&ibuf) == -1)
1569 fatal("imsg_flush");
1572 static int
1573 run_test(struct test *t)
1575 pid_t pid;
1576 int ret;
1578 #if DEBUG
1579 before_printing();
1580 puts("=====================");
1581 pp_block(t->body);
1582 puts("=====================");
1583 #endif
1585 if (stackh != 0)
1586 popvn(stackh);
1588 if (t->body == NULL) {
1589 before_printing();
1590 printf("no instructions, skipping...\n");
1591 return EVAL_SKIP;
1594 pid = spawn_client_proc();
1595 prepare_child_for_test(t);
1596 ret = eval(t->body);
1598 imsg_compose(&ibuf, IMSG_CONN_GONE, 0, 0, -1, NULL, 0);
1599 imsg_flush(&ibuf);
1601 while (waitpid(pid, NULL, 0) != pid)
1602 ; /* nop */
1604 check_for_output();
1606 if (t->shouldfail) {
1607 if (ret == EVAL_OK) {
1608 before_printing();
1609 printf("test was expected to fail\n");
1610 return EVAL_ERR;
1611 } else if (ret == EVAL_ERR)
1612 return EVAL_OK;
1615 return ret;
1618 int
1619 main(int argc, char **argv)
1621 struct test *t;
1622 int ch, i, r, passed = 0, failed = 0, skipped = 0;
1623 int runclient = 0;
1624 const char *pat = NULL;
1625 regex_t reg;
1627 assert(argv0 = argv[0]);
1629 signal(SIGPIPE, SIG_IGN);
1631 log_init(1, LOG_DAEMON);
1632 log_setverbose(1);
1634 /* prepare the global env */
1635 pushenv();
1637 add_builtin_proc("print", builtin_print, 1, 1);
1638 add_builtin_proc("debug", builtin_debug, 1, 1);
1639 add_builtin_proc("skip", builtin_skip, 0, 0);
1640 add_builtin_proc("iota", builtin_iota, 0, 0);
1641 add_builtin_proc("send", builtin_send, 2, 1);
1642 add_builtin_proc("recv", builtin_recv, 0, 0);
1644 while ((ch = getopt(argc, argv, "nT:vx:")) != -1) {
1645 switch (ch) {
1646 case 'n':
1647 syntaxcheck = 1;
1648 break;
1649 case 'T':
1650 assert(*optarg == 'c');
1651 runclient = 1;
1652 break;
1653 case 'v':
1654 debug = 1;
1655 break;
1656 case 'x':
1657 pat = optarg;
1658 break;
1659 default:
1660 fprintf(stderr, "Usage: %s [-nv] [files...]\n",
1661 *argv);
1662 exit(1);
1665 argc -= optind;
1666 argv += optind;
1668 if (runclient)
1669 client(1, debug);
1671 if (pat == NULL)
1672 pat = ".*";
1674 if (regcomp(&reg, pat, REG_BASIC | REG_ICASE | REG_NOSUB) != 0)
1675 fatalx("invalid regexp: %s", pat);
1677 for (i = 0; i < argc; ++i)
1678 loadfile(argv[i]);
1680 if (syntaxcheck) {
1681 fprintf(stderr, "files OK\n");
1682 return 0;
1685 /* Check for root privileges. */
1686 if (geteuid())
1687 fatalx("need root privileges");
1689 i = 0;
1690 TAILQ_FOREACH(t, &tests, entry) {
1691 if (regexec(&reg, t->name, 0, NULL, 0) != 0)
1692 continue;
1694 printf("===> [%d/%d] running test \"%s\"... ", i+1, ntests,
1695 t->name);
1696 fflush(stdout);
1698 filler = "\n";
1699 r = run_test(t);
1700 if (filler == NULL)
1701 printf("=> test ");
1703 switch (r) {
1704 case EVAL_OK:
1705 printf("passed\n");
1706 passed++;
1707 break;
1708 case EVAL_ERR:
1709 failed++;
1710 printf("failed\n");
1711 break;
1712 case EVAL_SKIP:
1713 printf("skipped\n");
1714 skipped++;
1715 break;
1718 if (filler == NULL)
1719 printf("\n");
1720 i++;
1723 printf("\n");
1724 printf("%d/%d passed (%d skipped and %d failed)\n",
1725 passed, i, skipped, failed);
1727 popenv();
1728 free(lastmsg);
1729 regfree(&reg);
1731 return failed != 0;