Blob


1 /*
2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
3 * Copyright (c) 2018 Florian Obser <florian@openbsd.org>
4 * Copyright (c) 2004, 2005 Esben Norby <norby@openbsd.org>
5 * Copyright (c) 2004 Ryan McBride <mcbride@openbsd.org>
6 * Copyright (c) 2002, 2003, 2004 Henning Brauer <henning@openbsd.org>
7 * Copyright (c) 2001 Markus Friedl. All rights reserved.
8 * Copyright (c) 2001 Daniel Hartmeier. All rights reserved.
9 * Copyright (c) 2001 Theo de Raadt. All rights reserved.
10 *
11 * Permission to use, copy, modify, and distribute this software for any
12 * purpose with or without fee is hereby granted, provided that the above
13 * copyright notice and this permission notice appear in all copies.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
16 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
17 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
18 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
20 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
21 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22 */
24 %{
26 #include <sys/queue.h>
28 #include <ctype.h>
29 #include <err.h>
30 #include <errno.h>
31 #include <event.h>
32 #include <inttypes.h>
33 #include <limits.h>
34 #include <limits.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <syslog.h>
40 #include "log.h"
41 #include "kami.h"
42 #include "utils.h"
44 #include "script.h"
46 TAILQ_HEAD(files, file) files = TAILQ_HEAD_INITIALIZER(files);
47 static struct file {
48 TAILQ_ENTRY(file) entry;
49 FILE *stream;
50 char *name;
51 size_t ungetpos;
52 size_t ungetsize;
53 u_char *ungetbuf;
54 int eof_reached;
55 int lineno;
56 int errors;
57 } *file, *topfile;
58 struct file *pushfile(const char *);
59 int popfile(void);
60 int yyparse(void);
61 int yylex(void);
62 int yyerror(const char *, ...)
63 __attribute__((__format__ (printf, 1, 2)))
64 __attribute__((__nonnull__ (1)));
65 int kw_cmp(const void *, const void *);
66 int lookup(char *);
67 int igetc(void);
68 int lgetc(int);
69 void lungetc(int);
70 int findeol(void);
72 static int shouldfail;
74 typedef struct {
75 union {
76 struct op *op;
77 struct proc *proc;
78 char *str;
79 int64_t num;
80 } v;
81 int lineno;
82 } YYSTYPE;
84 %}
86 /*
87 * for bison:
88 * %define parse.error verbose
89 */
91 %token ASSERT
92 %token CONST
93 %token DIR
94 %token ERROR
95 %token INCLUDE
96 %token PROC
97 %token REPEAT
98 %token SHOULD_FAIL STR
99 %token TESTING
100 %token U8 U16 U32
101 %token VARGS
103 %token <v.str> STRING SYMBOL
104 %token <v.num> NUMBER
106 %type <v.op> cast cexpr check expr faccess funcall
107 %type <v.op> literal sfail var varref vargs
109 %type <v.proc> procname
111 %%
113 program : /* empty */
114 | program '\n'
115 | program include '\n'
116 | program const '\n'
117 | program proc '\n'
118 | program test '\n'
121 optnl : '\n' optnl /* zero or more newlines */
122 | /*empty*/
125 nl : '\n' optnl ;
127 include : INCLUDE STRING {
128 struct file *nfile;
130 if ((nfile = pushfile($2)) == NULL) {
131 yyerror("failed to include file %s", $2);
132 free($2);
133 YYERROR;
135 free($2);
137 file = nfile;
138 lungetc('\n');
142 const : CONST consti
143 | CONST '(' optnl mconst ')'
146 mconst : consti nl | mconst consti nl ;
148 consti : SYMBOL '=' expr {
149 if (!global_set($1, $3)) {
150 yyerror("can't set %s: illegal expression", $1);
151 free($1);
152 free_op($3);
153 YYERROR;
158 var : SYMBOL '=' expr { $$ = op_assign($1, $3); } ;
159 varref : SYMBOL { $$ = op_var($1); } ;
160 literal : STRING { $$ = op_lit_str($1); }
161 | NUMBER { $$ = op_lit_num($1); } ;
163 /*
164 * `expr '=' '=' expr` is ambiguous. furthermore, we're not
165 * interested in checking all the possibilities here.
166 */
167 cexpr : literal | varref | funcall | faccess ;
168 check : cexpr '=' '=' cexpr { $$ = op_cmp_eq($1, $4); }
169 | cexpr '<' '=' cexpr { $$ = op_cmp_leq($1, $4); }
172 expr : literal | funcall | varref | check | cast | faccess | vargs ;
174 vargs : VARGS { $$ = op_vargs(); } ;
176 cast : expr ':' U8 { $$ = op_cast($1, V_U8); }
177 | expr ':' U16 { $$ = op_cast($1, V_U16); }
178 | expr ':' U32 { $$ = op_cast($1, V_U32); }
179 | expr ':' STR { $$ = op_cast($1, V_STR); }
182 faccess : varref '.' SYMBOL { $$ = op_faccess($1, $3); }
183 | faccess '.' SYMBOL { $$ = op_faccess($1, $3); }
186 procname: SYMBOL {
187 if (($$ = proc_by_name($1)) == NULL) {
188 yyerror("unknown proc %s", $1);
189 free($1);
190 YYERROR;
192 free($1);
196 funcall : procname {
197 prepare_funcall();
198 } '(' args optcomma ')' {
199 struct proc *proc;
200 int argc;
202 $$ = op_funcall($1);
203 proc = $$->v.funcall.proc;
204 argc = $$->v.funcall.argc;
206 if (argc != proc->minargs && !proc->vararg) {
207 yyerror("invalid arity for `%s': want %d arguments "
208 "but %d given.", $1->name, proc->minargs, argc);
209 /* TODO: recursively free $$ */
210 YYERROR;
213 if (argc < proc->minargs && proc->vararg) {
214 yyerror("invalid arity for `%s': want at least %d "
215 "arguments but %d given.", $1->name, proc->minargs,
216 argc);
217 /* TODO: recursively free $$ */
218 YYERROR;
223 optcomma: /* empty */ | ',' ;
225 dots : '.' '.' '.' ;
227 args : /* empty */
228 | args ',' expr { push_arg($3); }
229 | args ',' dots { push_arg(op_rest()); }
230 | expr { push_arg($1); }
231 | dots { push_arg(op_rest()); }
234 proc : PROC SYMBOL {
235 prepare_proc();
236 } '(' args ')' {
237 if (!proc_setup_body()) {
238 yyerror("invalid argument in proc `%s' definition",
239 $2);
240 free($2);
241 YYERROR;
243 } '{' optnl block '}' {
244 proc_done($2);
248 block : /* empty */
249 | block var nl { block_push($2); }
250 | block funcall nl { block_push($2); }
251 | block assert nl
252 | block sfail nl { block_push($2); }
255 sfail : SHOULD_FAIL expr { $$ = op_sfail($2, NULL); }
256 | SHOULD_FAIL expr ':' STRING { $$ = op_sfail($2, $4); }
259 assert : ASSERT asserti
260 | ASSERT '(' optnl massert ')'
263 massert : asserti nl | massert asserti nl ;
265 asserti : check { block_push(op_assert($1)); }
268 test : TESTING STRING DIR STRING {
269 prepare_test();
270 } testopt '{' optnl block '}' {
271 test_done(shouldfail, $2, $4);
272 shouldfail = 0;
276 testopt : /* empty */
277 | SHOULD_FAIL { shouldfail = 1; }
280 %%
282 struct keywords {
283 const char *k_name;
284 int k_val;
285 };
287 int
288 yyerror(const char *fmt, ...)
290 va_list ap;
291 char *msg;
293 file->errors++;
294 va_start(ap, fmt);
295 if (vasprintf(&msg, fmt, ap) == -1)
296 fatalx("yyerror vasprintf");
297 va_end(ap);
298 logit(LOG_CRIT, "%s:%d: %s", file->name, yylval.lineno, msg);
299 free(msg);
300 return 0;
303 int
304 kw_cmp(const void *k, const void *e)
306 return strcmp(k, ((const struct keywords *)e)->k_name);
309 int
310 lookup(char *s)
312 /* This has to be sorted always. */
313 static const struct keywords keywords[] = {
314 {"assert", ASSERT},
315 {"const", CONST},
316 {"dir", DIR},
317 {"include", INCLUDE},
318 {"proc", PROC},
319 {"repeat", REPEAT},
320 {"should-fail", SHOULD_FAIL},
321 {"str", STR},
322 {"testing", TESTING},
323 {"u16", U16},
324 {"u32", U32},
325 {"u8", U8},
326 {"vargs", VARGS},
327 };
328 const struct keywords *p;
330 p = bsearch(s, keywords, sizeof(keywords)/sizeof(keywords[0]),
331 sizeof(keywords[0]), kw_cmp);
333 if (p)
334 return p->k_val;
335 else
336 return SYMBOL;
339 #define START_EXPAND 1
340 #define DONE_EXPAND 2
342 static int expanding;
344 int
345 igetc(void)
347 int c;
349 while (1) {
350 if (file->ungetpos > 0)
351 c = file->ungetbuf[--file->ungetpos];
352 else
353 c = getc(file->stream);
355 if (c == START_EXPAND)
356 expanding = 1;
357 else if (c == DONE_EXPAND)
358 expanding = 0;
359 else
360 break;
362 return c;
365 int
366 lgetc(int quotec)
368 int c, next;
370 if (quotec) {
371 if ((c = igetc()) == EOF) {
372 yyerror("reached end of file while parsing "
373 "quoted string");
374 if (file == topfile || popfile() == EOF)
375 return EOF;
376 return quotec;
378 return c;
381 while ((c = igetc()) == '\\') {
382 next = igetc();
383 if (next != '\n') {
384 c = next;
385 break;
387 yylval.lineno = file->lineno;
388 file->lineno++;
391 if (c == EOF) {
392 /*
393 * Fake EOL when hit EOF for the first time. This gets line
394 * count right if last line in included file is syntactically
395 * invalid and has no newline.
396 */
397 if (file->eof_reached == 0) {
398 file->eof_reached = 1;
399 return '\n';
401 while (c == EOF) {
402 if (file == topfile || popfile() == EOF)
403 return EOF;
404 c = igetc();
407 return c;
410 void
411 lungetc(int c)
413 if (c == EOF)
414 return;
416 if (file->ungetpos >= file->ungetsize) {
417 void *p = reallocarray(file->ungetbuf, file->ungetsize, 2);
418 if (p == NULL)
419 err(1, "lungetc");
420 file->ungetbuf = p;
421 file->ungetsize *= 2;
423 file->ungetbuf[file->ungetpos++] = c;
426 int
427 findeol(void)
429 int c;
431 /* Skip to either EOF or the first real EOL. */
432 while (1) {
433 c = lgetc(0);
434 if (c == '\n') {
435 file->lineno++;
436 break;
438 if (c == EOF)
439 break;
441 return ERROR;
445 #if 0
446 int my_yylex(void);
448 int
449 yylex(void)
451 int x;
453 switch (x = my_yylex()) {
454 case ASSERT: puts("assert"); break;
455 case CONST: puts("const"); break;
456 case DIR: puts("dir"); break;
457 case ERROR: puts("error"); break;
458 case INCLUDE: puts("include"); break;
459 case PROC: puts("proc"); break;
460 case REPEAT: puts("repeat"); break;
461 case STR: puts(":str"); break;
462 case TESTING: puts("testing"); break;
463 case U8: puts(":u8"); break;
464 case U16: puts(":u16"); break;
465 case U32: puts(":u32"); break;
467 case STRING: printf("string \"%s\"\n", yylval.v.str); break;
468 case SYMBOL: printf("symbol %s\n", yylval.v.str); break;
469 case NUMBER: printf("number %"PRIu64"\n", yylval.v.num); break;
471 default:
472 printf("character ");
473 if (x == '\n')
474 printf("\\n");
475 else
476 printf("%c", x);
477 printf(" [0x%x]", x);
478 printf("\n");
479 break;
482 return x;
485 int
486 my_yylex(void)
487 #else
488 int
489 yylex(void)
490 #endif
492 unsigned char buf[8096];
493 unsigned char *p;
494 int quotec, next, c;
495 int token;
497 p = buf;
498 while ((c = lgetc(0)) == ' ' || c == '\t' || c == '\f')
499 ; /* nop */
501 yylval.lineno = file->lineno;
502 if (c == '#')
503 while ((c = lgetc(0)) != '\n' && c != EOF)
504 ; /* nop */
506 switch (c) {
507 case ':':
508 return c;
509 break;
510 case '\'':
511 case '\"':
512 quotec = c;
513 while (1) {
514 if ((c = lgetc(quotec)) == EOF)
515 return 0;
516 if (c == '\n') {
517 file->lineno++;
518 continue;
519 } else if (c == '\\') {
520 if ((next = lgetc(quotec)) == EOF)
521 return 0;
522 if (next == quotec || next == ' ' ||
523 next == '\t')
524 c = next;
525 else if (next == '\n') {
526 file->lineno++;
527 continue;
528 } else
529 lungetc(next);
530 } else if (c == quotec) {
531 *p = '\0';
532 break;
533 } else if (c == '\0') {
534 yyerror("syntax error");
535 return findeol();
538 if (p + 1 >= buf + sizeof(buf) - 1) {
539 yyerror("string too long");
540 return findeol();
543 *p++ = c;
546 yylval.v.str = xstrdup(buf);
547 return STRING;
550 #define allowed_to_end_number(x) \
551 (isspace(x) || x == ')' || x == ',' || x == '/' || x == '}' \
552 || x == '=' || x == ':')
554 if (c == '-' || isdigit(c)) {
555 do {
556 *p++ = c;
557 if ((size_t)(p-buf) >= sizeof(buf)) {
558 yyerror("string too long");
559 return findeol();
561 } while ((c = lgetc(0)) != EOF && (isdigit(c) || c == 'x'));
562 lungetc(c);
563 if (p == buf + 1 && buf[0] == '-')
564 goto nodigits;
565 if (c == EOF || allowed_to_end_number(c)) {
566 char *ep;
568 *p = '\0';
569 errno = 0;
570 yylval.v.num = strtoll(buf, &ep, 0);
571 if (*ep != '\0' || (errno == ERANGE &&
572 (yylval.v.num == LONG_MAX ||
573 yylval.v.num == LONG_MIN))) {
574 yyerror("\"%s\" invalid number or out of range",
575 buf);
576 return findeol();
579 return NUMBER;
580 } else {
581 nodigits:
582 while (p > buf + 1)
583 lungetc(*--p);
584 c = *--p;
585 if (c == '-')
586 return c;
590 #define allowed_in_symbol(x) \
591 (isalnum(x) || (ispunct(x) && x != '(' && x != ')' && \
592 x != '{' && x != '}' && \
593 x != '!' && x != '=' && \
594 x != '#' && x != ',' && \
595 x != '.' && x != ':'))
597 if (isalnum(c) || c == ':' || c == '_') {
598 do {
599 *p++ = c;
600 if ((size_t)(p-buf) >= sizeof(buf)) {
601 yyerror("string too long");
602 return findeol();
604 } while ((c = lgetc(0)) != EOF && (allowed_in_symbol(c)));
605 lungetc(c);
606 *p = '\0';
607 if ((token = lookup(buf)) == SYMBOL)
608 yylval.v.str = xstrdup(buf);
609 return token;
612 if (c == '\n') {
613 yylval.lineno = file->lineno;
614 file->lineno++;
616 if (c == EOF)
617 return 0;
618 return c;
621 struct file *
622 pushfile(const char *name)
624 struct file *nfile;
626 if ((nfile = calloc(1, sizeof(struct file))) == NULL) {
627 log_warn("calloc");
628 return NULL;
630 if ((nfile->name = strdup(name)) == NULL) {
631 log_warn("strdup");
632 free(nfile);
633 return NULL;
635 if ((nfile->stream = fopen(nfile->name, "r")) == NULL) {
636 log_warn("%s", nfile->name);
637 free(nfile->name);
638 free(nfile);
639 return NULL;
641 nfile->lineno = TAILQ_EMPTY(&files) ? 1 : 0;
642 nfile->ungetsize = 16;
643 nfile->ungetbuf = malloc(nfile->ungetsize);
644 if (nfile->ungetbuf == NULL) {
645 log_warn("malloc");
646 fclose(nfile->stream);
647 free(nfile->name);
648 free(nfile);
649 return NULL;
651 TAILQ_INSERT_TAIL(&files, nfile, entry);
652 return nfile;
655 int
656 popfile(void)
658 struct file *prev;
660 if ((prev = TAILQ_PREV(file, files, entry)) != NULL)
661 prev->errors += file->errors;
663 TAILQ_REMOVE(&files, file, entry);
664 fclose(file->stream);
665 free(file->name);
666 free(file->ungetbuf);
667 free(file);
668 file = prev;
669 return file ? 0 : EOF;
672 void
673 loadfile(const char *path)
675 int errors;
677 file = pushfile(path);
678 if (file == NULL)
679 err(1, "pushfile");
680 topfile = file;
682 yyparse();
683 errors = file->errors;
684 popfile();
686 if (errors)
687 errx(1, "can't load %s because of errors", path);