2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
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.
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.
19 #include <sys/socket.h>
48 static const char *argv0;
50 static uint8_t *lastmsg;
52 static struct imsgbuf ibuf;
53 static int ibuf_inuse;
55 static struct procs procs = TAILQ_HEAD_INITIALIZER(procs);
56 static struct tests tests = TAILQ_HEAD_INITIALIZER(tests);
60 static struct opstacks blocks = TAILQ_HEAD_INITIALIZER(blocks);
61 static struct opstacks args = TAILQ_HEAD_INITIALIZER(args);
63 #define STACK_HEIGHT 64
64 static struct value vstack[STACK_HEIGHT];
67 static struct envs envs = TAILQ_HEAD_INITIALIZER(envs);
69 static struct value v_false = {.type = V_NUM, .v = {.num = 0}};
70 static struct value v_true = {.type = V_NUM, .v = {.num = 1}};
72 static uint8_t lasttag;
75 static int syntaxcheck;
77 static const char *filler;
89 peekn(int depth, struct value *v)
92 errx(1, "can't peek the stack at %d: underflow",
94 memcpy(v, &vstack[stackh - depth], sizeof(*v));
97 printf("peeking(%d) ", depth); pp_val(v); printf("\n");
102 popv(struct value *v)
105 errx(1, "can't pop the stack: underflow");
106 memcpy(v, &vstack[--stackh], sizeof(*v));
109 printf("popping "); pp_val(v); printf("\n");
123 pushv(struct value *v)
125 if (stackh == STACK_HEIGHT)
126 errx(1, "can't push the stack: overflow");
129 printf("pushing "); pp_val(v); printf("\n");
132 memcpy(&vstack[stackh++], v, sizeof(*v));
138 pushv(n ? &v_true : &v_false);
141 static inline struct opstack *
142 pushstack(struct opstacks *stack)
146 ops = xcalloc(1, sizeof(*ops));
147 TAILQ_INSERT_HEAD(stack, ops, entry);
151 static inline struct opstack *
152 peek(struct opstacks *stack)
154 if (TAILQ_EMPTY(stack))
155 errx(1, "%s: args underflow", __func__);
157 return TAILQ_FIRST(stack);
160 static inline struct op *
161 finalize(struct opstacks *stack, int *argc)
166 if (TAILQ_EMPTY(stack))
167 errx(1, "%s: args underflow", __func__);
170 TAILQ_REMOVE(&args, ops, entry);
174 *argc = ops->counter;
181 push(struct opstacks *stack, struct op *op)
186 if (ops->last == NULL) {
190 ops->last->next = op;
202 e = xcalloc(1, sizeof(*e));
203 TAILQ_INSERT_HEAD(&envs, e, entry);
206 static inline struct env *
209 assert(!TAILQ_EMPTY(&envs));
210 return TAILQ_FIRST(&envs);
217 struct binding *b, *tb;
220 TAILQ_REMOVE(&envs, e, entry);
222 TAILQ_FOREACH_SAFE(b, &e->bindings, entry, tb) {
224 switch (b->val.type) {
237 setvar(char *sym, struct op *op)
244 if ((ret = eval(op)) != EVAL_OK)
247 if (stackh != height + 1) {
249 printf("trying to assign to `%s' a void value: ", sym);
255 b = xcalloc(1, sizeof(*b));
259 e = TAILQ_FIRST(&envs);
260 TAILQ_INSERT_HEAD(&e->bindings, b, entry);
266 setvar_raw(char *sym, struct op *op)
271 b = xcalloc(1, sizeof(*b));
275 e = TAILQ_FIRST(&envs);
276 TAILQ_INSERT_HEAD(&e->bindings, b, entry);
280 getvar(const char *sym, struct value *v)
285 TAILQ_FOREACH(e, &envs, entry) {
286 TAILQ_FOREACH(b, &e->bindings, entry) {
287 if (!strcmp(sym, b->name)) {
288 memcpy(v, &b->val, sizeof(*v));
295 fprintf(stderr, "unbound variable %s\n", sym);
300 getvar_raw(const char *sym, struct op **raw)
305 TAILQ_FOREACH(e, &envs, entry) {
306 TAILQ_FOREACH(b, &e->bindings, entry) {
307 if (!strcmp(sym, b->name)) {
315 fprintf(stderr, "no rest argument `...'\n");
320 global_set(char *sym, struct op *op)
325 /* TODO: check for duplicates */
327 if (op->type != OP_LITERAL &&
328 (op->type == OP_CAST && op->v.cast.expr->type != OP_LITERAL))
331 b = xcalloc(1, sizeof(*b));
334 /* it's only a cast on a literal! */
335 if (op->type == OP_CAST) {
336 if (eval(op) != EVAL_OK) {
342 memcpy(&b->val, &op->v.literal, sizeof(b->val));
344 e = TAILQ_LAST(&envs, envs);
345 TAILQ_INSERT_HEAD(&e->bindings, b, entry);
355 op = xcalloc(1, sizeof(*op));
362 free_op(struct op *op)
364 /* TODO: probably more... */
371 return newop(OP_REST);
375 op_assign(char *sym, struct op *expr)
379 op = newop(OP_ASSIGN);
380 op->v.assign.name = sym;
381 op->v.assign.expr = expr;
387 op_assert(struct op *expr)
391 op = newop(OP_ASSERT);
409 op_lit_str(char *str)
413 op = newop(OP_LITERAL);
414 op->v.literal.type = V_STR;
415 op->v.literal.v.str = str;
421 op_lit_num(uint64_t n)
425 op = newop(OP_LITERAL);
426 op->v.literal.type = V_NUM;
427 op->v.literal.v.num = n;
433 op_cmp_eq(struct op *a, struct op *b)
437 op = newop(OP_CMP_EQ);
445 op_cast(struct op *expr, int totype)
450 op->v.cast.expr = expr;
451 op->v.cast.totype = totype;
457 op_faccess(struct op *expr, char *field)
461 op = newop(OP_FACCESS);
462 op->v.faccess.expr = expr;
463 op->v.faccess.field = field;
469 op_sfail(struct op *expr, char *msg)
473 op = newop(OP_SFAIL);
474 op->v.sfail.expr = expr;
475 op->v.sfail.msg = msg;
481 ppf_val(FILE *f, struct value *val)
487 fprintf(f, "%s", val->v.str);
490 fprintf(f, "\"%s\"", val->v.str);
493 fprintf(f, "%"PRIi64, val->v.num);
496 fprintf(f, "%"PRIu8, val->v.u8);
499 fprintf(f, "%"PRIu16, val->v.u16);
502 fprintf(f, "%"PRIu32, val->v.u32);
506 for (i = 0; i < val->v.msg.len; ++i)
507 fprintf(f, "%x%s", val->v.msg.msg[i],
508 i == val->v.msg.len-1 ? "" : " ");
512 fprintf(f, "<unknown value>");
518 pp_val(struct value *val)
520 ppf_val(stdout, val);
524 val_type(struct value *v)
527 case V_SYM: return "symbol";
528 case V_STR: return "string";
529 case V_NUM: return "number";
530 case V_MSG: return "message";
531 case V_QID: return "qid";
532 case V_U8: return "u8";
533 case V_U16: return "u16";
534 case V_U32: return "u32";
535 default: return "unknown";
540 val_trueish(struct value *a)
542 return a->type == V_NUM && a->v.num;
546 val_isnum(struct value *a)
548 return a->type == V_NUM
554 static inline int64_t
555 val_tonum(struct value *a)
558 case V_NUM: return a->v.num;
559 case V_U8: return a->v.u8;
560 case V_U16: return a->v.u16;
561 case V_U32: return a->v.u32;
564 fprintf(stderr, "%s: given value is not a number\n", __func__);
570 val_eq(struct value *a, struct value *b)
572 if (val_isnum(a) && val_isnum(b))
573 return val_tonum(a) == val_tonum(b);
575 if (a->type != b->type)
581 return !strcmp(a->v.str, b->v.str);
587 static inline const char *
588 pp_totype(int totype)
591 * Not all of these are valid cast type thought, including
592 * every possibility only to aid debugging.
595 case V_STR: return "str";
596 case V_SYM: return "sym";
597 case V_NUM: return "num";
598 case V_QID: return "qid";
599 case V_U8: return "u8";
600 case V_U16: return "u16";
601 case V_U32: return "u32";
602 default: return "unknown";
607 val_cast(struct value *a, int totype)
611 #define NUMCAST(val, t, c, totype, max) do { \
614 fprintf(stderr, "can't cast %"PRIu64 \
615 " to %s\n", val, pp_totype(totype)); \
625 fprintf(stderr, "can't cast ");
627 fprintf(stderr, " to type %s\n", pp_totype(totype));
633 case V_U8: NUMCAST(v, u8, uint8_t, totype, UINT8_MAX);
634 case V_U16: NUMCAST(v, u16, uint16_t, totype, UINT16_MAX);
635 case V_U32: NUMCAST(v, u32, uint32_t, totype, UINT32_MAX);
638 fprintf(stderr, "can't cast %"PRIu64" to %s\n",
639 v, pp_totype(totype));
647 val_faccess(struct value *a, const char *field, struct value *ret)
651 /* TODO: add path. needs uint64_t values thought! */
652 if (!strcmp(field, "vers")) {
654 memcpy(&ret->v.u32, a->v.qid+1, 4);
656 } else if (!strcmp(field, "type")) {
658 ret->v.u8 = *a->v.qid;
663 if (!strcmp(field, "type")) {
665 ret->v.u8 = *(a->v.msg.msg + 4); /* skip the length */
674 printf("can't access field `%s' on type %s (", field, val_type(a));
690 printf("%s = ", op->v.assign.name);
691 pp_op(op->v.assign.expr);
698 printf("funcall %s(", op->v.funcall.proc->name);
699 for (aux = op->v.funcall.argv; aux != NULL; aux = aux->next) {
701 if (aux->next != NULL)
707 pp_val(&op->v.literal);
710 printf("%s", op->v.var);
713 pp_op(op->v.cast.expr);
715 switch (op->v.cast.totype) {
716 case V_U8: printf("u8"); break;
717 case V_U16: printf("u16"); break;
718 case V_U32: printf("u32"); break;
719 case V_STR: printf("str"); break;
720 default: printf("???"); break;
724 pp_op(op->v.cmp_eq.a);
726 pp_op(op->v.cmp_eq.b);
729 pp_op(op->v.faccess.expr);
730 printf(".%s", op->v.faccess.field);
733 printf("should-fail ");
734 pp_op(op->v.sfail.expr);
735 if (op->v.sfail.msg != NULL)
736 printf(": \"%s\"", op->v.sfail.msg);
739 printf(" ???[%d] ", op->type);
744 pp_block(struct op *op)
770 if ((ret = getvar_raw("...", &t)) != EVAL_OK)
772 if ((ret = eval(t)) != EVAL_OK)
777 ret = setvar(op->v.assign.name, op->v.assign.expr);
783 if ((ret = eval(op->v.assert)) != EVAL_OK)
786 if (!val_trueish(&a)) {
788 printf("assertion failed: ");
796 /* assume airity matches */
798 proc = op->v.funcall.proc;
799 if (proc->nativefn != NULL) {
801 * Push arguments on the stack for builtin
802 * functions. Counting the height of the
803 * stack is done to compute the correct number
804 * in the vararg case. argc only counts the
805 * "syntactical" arguments, i.e. foo(x, ...)
806 * has argc == 2, but at runtime argc may be
807 * 1, 2 or a greater number!
811 t = op->v.funcall.argv;
812 if (t != NULL && (ret = eval(t)) != EVAL_OK)
818 if ((ret = proc->nativefn(i))
822 if (proc->body == NULL) {
824 printf("warn: calling the empty proc `%s'\n",
831 for (t = op->v.funcall.argv, i = 0;
835 * Push a pseudo variable `...' (and
836 * don't evaluate it) in the vararg
837 * case. A special case is when the
838 * variable is itself `...'.
840 if (proc->vararg && i == proc->minargs) {
841 if (t->type != OP_REST)
842 setvar_raw(xstrdup("..."), t);
846 if ((ret = setvar(proc->args[i], t))
851 if ((ret = eval(proc->body)) != EVAL_OK)
860 pushv(&op->v.literal);
864 if ((ret = getvar(op->v.var, &a)) != EVAL_OK)
870 if ((ret = eval(op->v.cast.expr)) != EVAL_OK)
873 if ((ret = val_cast(&a, op->v.cast.totype)) != EVAL_OK)
879 if ((ret = eval(op->v.cmp_eq.a)) != EVAL_OK)
881 if ((ret = eval(op->v.cmp_eq.b)) != EVAL_OK)
886 pushbool(val_eq(&a, &b));
891 if ((ret = eval(op->v.faccess.expr)) != EVAL_OK)
894 if ((ret = val_faccess(&a, op->v.faccess.field, &b))
901 if ((ret = eval(op->v.sfail.expr)) == EVAL_OK) {
903 printf("expecting failure");
904 if (op->v.sfail.msg != NULL)
905 printf(" \"%s\"", op->v.sfail.msg);
907 printf("expression: ");
908 pp_op(op->v.sfail.expr);
912 if (ret == EVAL_SKIP)
918 fprintf(stderr, "invalid op, aborting.\n");
923 return eval(op->next);
928 prepare_funcall(void)
934 push_arg(struct op *op)
940 op_funcall(struct proc *proc)
942 struct op *op, *argv;
945 argv = finalize(&args, &argc);
947 op = newop(OP_FUNCALL);
948 op->v.funcall.proc = proc;
949 op->v.funcall.argv = argv;
950 op->v.funcall.argc = argc;
956 add_builtin_proc(const char *name, int (*fn)(int), int argc, int vararg)
960 proc = xcalloc(1, sizeof(*proc));
961 proc->name = xstrdup(name);
963 proc->minargs = argc;
964 proc->vararg = vararg;
966 TAILQ_INSERT_HEAD(&procs, proc, entry);
976 proc_setup_body(void)
978 struct opstack *argv;
983 for (i = 0, op = argv->base.next; op != NULL; i++) {
985 * TODO: should free the whole list on error but..,
986 * we're gonna exit real soon(tm)!
988 if (op->type != OP_VAR && op->type != OP_REST)
994 assert(i == argv->counter);
1000 proc_done(char *name)
1003 struct op *op, *next, *argv, *body;
1006 argv = finalize(&args, &argc);
1007 body = finalize(&blocks, NULL);
1009 proc = xcalloc(1, sizeof(*proc));
1011 proc->minargs = argc;
1013 for (i = 0, op = argv; op != NULL; ++i) {
1014 if (op->type == OP_REST) {
1020 proc->args[i] = xstrdup(op->v.var);
1026 assert(i == argc || (proc->vararg && i == proc->minargs));
1030 TAILQ_INSERT_HEAD(&procs, proc, entry);
1034 block_push(struct op *op)
1040 proc_by_name(const char *name)
1044 TAILQ_FOREACH(p, &procs, entry) {
1045 if (!strcmp(p->name, name))
1059 test_done(int shouldfail, char *name, char *dir)
1063 test = xcalloc(1, sizeof(*test));
1064 test->shouldfail = shouldfail;
1067 test->body = finalize(&blocks, NULL);
1069 if (TAILQ_EMPTY(&tests))
1070 TAILQ_INSERT_HEAD(&tests, test, entry);
1072 TAILQ_INSERT_TAIL(&tests, test, entry);
1078 builtin_print(int argc)
1085 for (i = argc; i > 0; --i) {
1087 if (v.type == V_STR)
1088 printf("%s", v.v.str);
1102 builtin_debug(int argc)
1105 return builtin_print(argc);
1112 builtin_skip(int argc)
1118 builtin_iota(int argc)
1123 if ((v.v.u8 = ++lasttag) == 255)
1131 builtin_send(int argc)
1140 * Compute the length of the packet. 4 is for the initial
1145 for (i = argc; i > 0; --i) {
1149 len += 2; /* count */
1150 len += strlen(v.v.str);
1167 printf("%s: can't serialize ", __func__);
1174 if (len > UINT16_MAX) {
1176 printf("%s: message size too long: got %d when max is %d\n",
1177 __func__, len, UINT16_MAX);
1181 if ((buf = imsg_create(&ibuf, IMSG_BUF, 0, 0, len)) == NULL)
1182 fatal("imsg_create(%d)", len);
1185 imsg_add(buf, &len, sizeof(len));
1187 for (i = argc; i > 0; --i) {
1191 slen = strlen(v.v.str);
1192 slen = htole16(slen);
1193 imsg_add(buf, &slen, sizeof(slen));
1194 imsg_add(buf, v.v.str, strlen(v.v.str));
1198 imsg_add(buf, &v.v.u8, 1);
1202 v.v.u16 = htole16(v.v.u16);
1203 imsg_add(buf, &v.v.u16, 2);
1207 v.v.u32 = htole32(v.v.u32);
1208 imsg_add(buf, &v.v.u32, 4);
1213 imsg_close(&ibuf, buf);
1215 if (imsg_flush(&ibuf) == -1) {
1218 printf("%s: imsg_flush failed: %s\n", __func__, strerror(i));
1226 builtin_recv(int argc)
1234 if (lastmsg != NULL) {
1240 pfd.events = POLLIN;
1241 if (poll(&pfd, 1, INFTIM) == -1) {
1244 printf("%s: poll failed: %s\n", __func__, strerror(serrno));
1249 if ((n = imsg_read(&ibuf)) == -1) {
1250 if (errno == EAGAIN)
1257 printf("child disconnected\n");
1262 /* read only one message */
1263 if ((n = imsg_get(&ibuf, &imsg)) == -1)
1268 datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
1269 switch (imsg.hdr.type) {
1272 if ((v.v.msg.msg = malloc(datalen)) == NULL)
1274 memcpy(v.v.msg.msg, imsg.data, datalen);
1275 v.v.msg.len = datalen;
1282 printf("subprocess closed the connection\n");
1292 printf("got unknown message from subprocess: %d\n",
1300 spawn_client_proc(void)
1302 const char *argv[4];
1306 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1307 PF_UNSPEC, p) == -1)
1308 fatal("socketpair");
1310 switch (pid = fork()) {
1312 fatal("cannot fork");
1318 msgbuf_clear(&ibuf.w);
1321 imsg_init(&ibuf, p[0]);
1329 if (dup2(p[1], 3) == -1)
1330 fatal("cannot setup imsg fd");
1331 } else if (fcntl(F_SETFD, 0) == -1)
1332 fatal("cannot setup imsg fd");
1334 argv[argc++] = argv0;
1335 argv[argc++] = "-Tc";
1338 argv[argc++] = "-v";
1341 argv[argc++] = NULL;
1343 execvp(argv0, (char *const *)argv);
1348 prepare_child_for_test(struct test *t)
1353 if (stat(t->dir, &sb) == -1)
1354 fatal("stat(\"%s\")", t->dir);
1356 if ((pw = getpwuid(sb.st_uid)) == NULL)
1357 fatal("getpwuid(%d)", sb.st_uid);
1359 imsg_compose(&ibuf, IMSG_AUTH, 0, 0, -1,
1360 pw->pw_name, strlen(pw->pw_name)+1);
1361 imsg_compose(&ibuf, IMSG_AUTH_DIR, 0, 0, -1,
1362 t->dir, strlen(t->dir)+1);
1364 if (imsg_flush(&ibuf) == -1)
1365 fatal("imsg_flush");
1369 run_test(struct test *t)
1376 puts("=====================");
1378 puts("=====================");
1381 if (t->body == NULL) {
1383 printf("no instructions, skipping...\n");
1387 pid = spawn_client_proc();
1388 prepare_child_for_test(t);
1389 ret = eval(t->body);
1391 imsg_compose(&ibuf, IMSG_CONN_GONE, 0, 0, -1, NULL, 0);
1394 while (waitpid(pid, NULL, 0) != pid)
1397 if (t->shouldfail) {
1398 if (ret == EVAL_OK) {
1400 printf("test was expected to fail\n");
1402 } else if (ret == EVAL_ERR)
1410 main(int argc, char **argv)
1414 int ch, i, r, passed = 0, failed = 0, skipped = 0;
1417 assert(argv0 = argv[0]);
1419 signal(SIGPIPE, SIG_IGN);
1421 log_init(1, LOG_DAEMON);
1424 /* prepare the global env */
1427 add_builtin_proc("print", builtin_print, 1, 1);
1428 add_builtin_proc("debug", builtin_debug, 1, 1);
1429 add_builtin_proc("skip", builtin_skip, 0, 0);
1430 add_builtin_proc("iota", builtin_iota, 0, 0);
1431 add_builtin_proc("send", builtin_send, 2, 1);
1432 add_builtin_proc("recv", builtin_recv, 0, 0);
1434 while ((ch = getopt(argc, argv, "nT:v")) != -1) {
1440 assert(*optarg == 'c');
1447 fprintf(stderr, "Usage: %s [-nv] [files...]\n",
1458 for (i = 0; i < argc; ++i)
1462 fprintf(stderr, "files OK\n");
1466 /* Check for root privileges. */
1468 fatalx("need root privileges");
1471 TAILQ_FOREACH(t, &tests, entry) {
1472 printf("===> [%d/%d] running test \"%s\"... ", i, ntests,
1491 printf("skipped\n");
1501 printf("passed: %d/%d\n", passed, i);
1502 printf("failed: %d\n", failed);
1503 printf("skipped: %d\n", skipped);