Blob


1 /*
2 * Copyright (c) 2021, 2022 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 "compat.h"
28 #include <ctype.h>
29 #include <errno.h>
30 #include <inttypes.h>
31 #include <limits.h>
32 #include <limits.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <syslog.h>
38 #include "log.h"
39 #include "kami.h"
40 #include "utils.h"
42 #include "script.h"
44 TAILQ_HEAD(files, file) files = TAILQ_HEAD_INITIALIZER(files);
45 static struct file {
46 TAILQ_ENTRY(file) entry;
47 FILE *stream;
48 char *name;
49 size_t ungetpos;
50 size_t ungetsize;
51 u_char *ungetbuf;
52 int eof_reached;
53 int lineno;
54 int errors;
55 } *file, *topfile;
56 struct file *pushfile(const char *);
57 int popfile(void);
58 int yyparse(void);
59 int yylex(void);
60 int yyerror(const char *, ...)
61 __attribute__((__format__ (printf, 1, 2)))
62 __attribute__((__nonnull__ (1)));
63 int kw_cmp(const void *, const void *);
64 int lookup(char *);
65 int igetc(void);
66 int lgetc(int);
67 void lungetc(int);
68 int findeol(void);
70 static int shouldfail;
72 typedef struct {
73 union {
74 struct op *op;
75 struct proc *proc;
76 char *str;
77 int64_t num;
78 } v;
79 int lineno;
80 } YYSTYPE;
82 %}
84 /*
85 * for bison:
86 * %define parse.error verbose
87 */
89 %token ASSERT
90 %token CONST
91 %token ERROR
92 %token INCLUDE
93 %token PROC
94 %token REPEAT
95 %token SHOULD_FAIL STR
96 %token TESTING
97 %token U8 U16 U32
98 %token VARGS
100 %token <v.str> STRING SYMBOL
101 %token <v.num> NUMBER
103 %type <v.op> cast cexpr check expr faccess funcall
104 %type <v.op> literal sfail var varref vargs
106 %type <v.proc> procname
108 %%
110 program : /* empty */
111 | program '\n'
112 | program include '\n'
113 | program const '\n'
114 | program proc '\n'
115 | program test '\n'
118 optnl : '\n' optnl /* zero or more newlines */
119 | /*empty*/
122 nl : '\n' optnl ;
124 include : INCLUDE STRING {
125 struct file *nfile;
127 if ((nfile = pushfile($2)) == NULL) {
128 yyerror("failed to include file %s", $2);
129 free($2);
130 YYERROR;
132 free($2);
134 file = nfile;
135 lungetc('\n');
139 const : CONST consti
140 | CONST '(' optnl mconst ')'
143 mconst : consti nl | mconst consti nl ;
145 consti : SYMBOL '=' expr {
146 if (!global_set($1, $3)) {
147 yyerror("can't set %s: illegal expression", $1);
148 free($1);
149 free_op($3);
150 YYERROR;
155 var : SYMBOL '=' expr { $$ = op_assign($1, $3); } ;
156 varref : SYMBOL { $$ = op_var($1); } ;
157 literal : STRING { $$ = op_lit_str($1); }
158 | NUMBER { $$ = op_lit_num($1); } ;
160 /*
161 * `expr '=' '=' expr` is ambiguous. furthermore, we're not
162 * interested in checking all the possibilities here.
163 */
164 cexpr : literal | varref | funcall | faccess ;
165 check : cexpr '=' '=' cexpr { $$ = op_cmp_eq($1, $4); }
166 | cexpr '<' '=' cexpr { $$ = op_cmp_leq($1, $4); }
169 expr : literal | funcall | varref | check | cast | faccess | vargs ;
171 vargs : VARGS { $$ = op_vargs(); } ;
173 cast : expr ':' U8 { $$ = op_cast($1, V_U8); }
174 | expr ':' U16 { $$ = op_cast($1, V_U16); }
175 | expr ':' U32 { $$ = op_cast($1, V_U32); }
176 | expr ':' STR { $$ = op_cast($1, V_STR); }
179 faccess : varref '.' SYMBOL { $$ = op_faccess($1, $3); }
180 | faccess '.' SYMBOL { $$ = op_faccess($1, $3); }
183 procname: SYMBOL {
184 if (($$ = proc_by_name($1)) == NULL) {
185 yyerror("unknown proc %s", $1);
186 free($1);
187 YYERROR;
189 free($1);
193 funcall : procname {
194 prepare_funcall();
195 } '(' args optcomma ')' {
196 struct proc *proc;
197 int argc;
199 $$ = op_funcall($1);
200 proc = $$->v.funcall.proc;
201 argc = $$->v.funcall.argc;
203 if (argc != proc->minargs && !proc->vararg) {
204 yyerror("invalid arity for `%s': want %d arguments "
205 "but %d given.", $1->name, proc->minargs, argc);
206 /* TODO: recursively free $$ */
207 YYERROR;
210 if (argc < proc->minargs && proc->vararg) {
211 yyerror("invalid arity for `%s': want at least %d "
212 "arguments but %d given.", $1->name, proc->minargs,
213 argc);
214 /* TODO: recursively free $$ */
215 YYERROR;
220 optcomma: /* empty */ | ',' ;
222 dots : '.' '.' '.' ;
224 args : /* empty */
225 | args ',' expr { push_arg($3); }
226 | args ',' dots { push_arg(op_rest()); }
227 | expr { push_arg($1); }
228 | dots { push_arg(op_rest()); }
231 proc : PROC SYMBOL {
232 prepare_proc();
233 } '(' args ')' {
234 if (!proc_setup_body()) {
235 yyerror("invalid argument in proc `%s' definition",
236 $2);
237 free($2);
238 YYERROR;
240 } '{' optnl block '}' {
241 proc_done($2);
245 block : /* empty */
246 | block var nl { block_push($2); }
247 | block funcall nl { block_push($2); }
248 | block assert nl
249 | block sfail nl { block_push($2); }
252 sfail : SHOULD_FAIL expr { $$ = op_sfail($2, NULL); }
253 | SHOULD_FAIL expr ':' STRING { $$ = op_sfail($2, $4); }
256 assert : ASSERT asserti
257 | ASSERT '(' optnl massert ')'
260 massert : asserti nl | massert asserti nl ;
262 asserti : check { block_push(op_assert($1)); }
265 test : TESTING STRING {
266 prepare_test();
267 } testopt '{' optnl block '}' {
268 test_done(shouldfail, $2);
269 shouldfail = 0;
273 testopt : /* empty */
274 | SHOULD_FAIL { shouldfail = 1; }
277 %%
279 struct keywords {
280 const char *k_name;
281 int k_val;
282 };
284 int
285 yyerror(const char *fmt, ...)
287 va_list ap;
288 char *msg;
290 file->errors++;
291 va_start(ap, fmt);
292 if (vasprintf(&msg, fmt, ap) == -1)
293 fatalx("yyerror vasprintf");
294 va_end(ap);
295 logit(LOG_CRIT, "%s:%d: %s", file->name, yylval.lineno, msg);
296 free(msg);
297 return 0;
300 int
301 kw_cmp(const void *k, const void *e)
303 return strcmp(k, ((const struct keywords *)e)->k_name);
306 int
307 lookup(char *s)
309 /* This has to be sorted always. */
310 static const struct keywords keywords[] = {
311 {"assert", ASSERT},
312 {"const", CONST},
313 {"include", INCLUDE},
314 {"proc", PROC},
315 {"repeat", REPEAT},
316 {"should-fail", SHOULD_FAIL},
317 {"str", STR},
318 {"testing", TESTING},
319 {"u16", U16},
320 {"u32", U32},
321 {"u8", U8},
322 {"vargs", VARGS},
323 };
324 const struct keywords *p;
326 p = bsearch(s, keywords, sizeof(keywords)/sizeof(keywords[0]),
327 sizeof(keywords[0]), kw_cmp);
329 if (p)
330 return p->k_val;
331 else
332 return SYMBOL;
335 #define START_EXPAND 1
336 #define DONE_EXPAND 2
338 static int expanding;
340 int
341 igetc(void)
343 int c;
345 while (1) {
346 if (file->ungetpos > 0)
347 c = file->ungetbuf[--file->ungetpos];
348 else
349 c = getc(file->stream);
351 if (c == START_EXPAND)
352 expanding = 1;
353 else if (c == DONE_EXPAND)
354 expanding = 0;
355 else
356 break;
358 return c;
361 int
362 lgetc(int quotec)
364 int c, next;
366 if (quotec) {
367 if ((c = igetc()) == EOF) {
368 yyerror("reached end of file while parsing "
369 "quoted string");
370 if (file == topfile || popfile() == EOF)
371 return EOF;
372 return quotec;
374 return c;
377 while ((c = igetc()) == '\\') {
378 next = igetc();
379 if (next != '\n') {
380 c = next;
381 break;
383 yylval.lineno = file->lineno;
384 file->lineno++;
387 if (c == EOF) {
388 /*
389 * Fake EOL when hit EOF for the first time. This gets line
390 * count right if last line in included file is syntactically
391 * invalid and has no newline.
392 */
393 if (file->eof_reached == 0) {
394 file->eof_reached = 1;
395 return '\n';
397 while (c == EOF) {
398 if (file == topfile || popfile() == EOF)
399 return EOF;
400 c = igetc();
403 return c;
406 void
407 lungetc(int c)
409 if (c == EOF)
410 return;
412 if (file->ungetpos >= file->ungetsize) {
413 void *p = reallocarray(file->ungetbuf, file->ungetsize, 2);
414 if (p == NULL)
415 err(1, "lungetc");
416 file->ungetbuf = p;
417 file->ungetsize *= 2;
419 file->ungetbuf[file->ungetpos++] = c;
422 int
423 findeol(void)
425 int c;
427 /* Skip to either EOF or the first real EOL. */
428 while (1) {
429 c = lgetc(0);
430 if (c == '\n') {
431 file->lineno++;
432 break;
434 if (c == EOF)
435 break;
437 return ERROR;
441 #if 0
442 int my_yylex(void);
444 int
445 yylex(void)
447 int x;
449 switch (x = my_yylex()) {
450 case ASSERT: puts("assert"); break;
451 case CONST: puts("const"); break;
452 case ERROR: puts("error"); break;
453 case INCLUDE: puts("include"); break;
454 case PROC: puts("proc"); break;
455 case REPEAT: puts("repeat"); break;
456 case STR: puts(":str"); break;
457 case TESTING: puts("testing"); break;
458 case U8: puts(":u8"); break;
459 case U16: puts(":u16"); break;
460 case U32: puts(":u32"); break;
462 case STRING: printf("string \"%s\"\n", yylval.v.str); break;
463 case SYMBOL: printf("symbol %s\n", yylval.v.str); break;
464 case NUMBER: printf("number %"PRIu64"\n", yylval.v.num); break;
466 default:
467 printf("character ");
468 if (x == '\n')
469 printf("\\n");
470 else
471 printf("%c", x);
472 printf(" [0x%x]", x);
473 printf("\n");
474 break;
477 return x;
480 int
481 my_yylex(void)
482 #else
483 int
484 yylex(void)
485 #endif
487 unsigned char buf[8096];
488 unsigned char *p;
489 int quotec, next, c;
490 int token;
492 p = buf;
493 while ((c = lgetc(0)) == ' ' || c == '\t' || c == '\f')
494 ; /* nop */
496 yylval.lineno = file->lineno;
497 if (c == '#')
498 while ((c = lgetc(0)) != '\n' && c != EOF)
499 ; /* nop */
501 switch (c) {
502 case ':':
503 return c;
504 break;
505 case '\'':
506 case '\"':
507 quotec = c;
508 while (1) {
509 if ((c = lgetc(quotec)) == EOF)
510 return 0;
511 if (c == '\n') {
512 file->lineno++;
513 continue;
514 } else if (c == '\\') {
515 if ((next = lgetc(quotec)) == EOF)
516 return 0;
517 if (next == quotec || next == ' ' ||
518 next == '\t')
519 c = next;
520 else if (next == '\n') {
521 file->lineno++;
522 continue;
523 } else
524 lungetc(next);
525 } else if (c == quotec) {
526 *p = '\0';
527 break;
528 } else if (c == '\0') {
529 yyerror("syntax error");
530 return findeol();
533 if (p + 1 >= buf + sizeof(buf) - 1) {
534 yyerror("string too long");
535 return findeol();
538 *p++ = c;
541 yylval.v.str = xstrdup(buf);
542 return STRING;
545 #define allowed_to_end_number(x) \
546 (isspace(x) || x == ')' || x == ',' || x == '/' || x == '}' \
547 || x == '=' || x == ':')
549 if (c == '-' || isdigit(c)) {
550 do {
551 *p++ = c;
552 if ((size_t)(p-buf) >= sizeof(buf)) {
553 yyerror("string too long");
554 return findeol();
556 } while ((c = lgetc(0)) != EOF && (isdigit(c) || c == 'x'));
557 lungetc(c);
558 if (p == buf + 1 && buf[0] == '-')
559 goto nodigits;
560 if (c == EOF || allowed_to_end_number(c)) {
561 char *ep;
563 *p = '\0';
564 errno = 0;
565 yylval.v.num = strtoll(buf, &ep, 0);
566 if (*ep != '\0' || (errno == ERANGE &&
567 (yylval.v.num == LONG_MAX ||
568 yylval.v.num == LONG_MIN))) {
569 yyerror("\"%s\" invalid number or out of range",
570 buf);
571 return findeol();
574 return NUMBER;
575 } else {
576 nodigits:
577 while (p > buf + 1)
578 lungetc(*--p);
579 c = *--p;
580 if (c == '-')
581 return c;
585 #define allowed_in_symbol(x) \
586 (isalnum(x) || (ispunct(x) && x != '(' && x != ')' && \
587 x != '{' && x != '}' && \
588 x != '!' && x != '=' && \
589 x != '#' && x != ',' && \
590 x != '.' && x != ':'))
592 if (isalnum(c) || c == ':' || c == '_') {
593 do {
594 *p++ = c;
595 if ((size_t)(p-buf) >= sizeof(buf)) {
596 yyerror("string too long");
597 return findeol();
599 } while ((c = lgetc(0)) != EOF && (allowed_in_symbol(c)));
600 lungetc(c);
601 *p = '\0';
602 if ((token = lookup(buf)) == SYMBOL)
603 yylval.v.str = xstrdup(buf);
604 return token;
607 if (c == '\n') {
608 yylval.lineno = file->lineno;
609 file->lineno++;
611 if (c == EOF)
612 return 0;
613 return c;
616 struct file *
617 pushfile(const char *name)
619 struct file *nfile;
621 if ((nfile = calloc(1, sizeof(struct file))) == NULL) {
622 log_warn("calloc");
623 return NULL;
625 if ((nfile->name = strdup(name)) == NULL) {
626 log_warn("strdup");
627 free(nfile);
628 return NULL;
630 if ((nfile->stream = fopen(nfile->name, "r")) == NULL) {
631 log_warn("%s", nfile->name);
632 free(nfile->name);
633 free(nfile);
634 return NULL;
636 nfile->lineno = TAILQ_EMPTY(&files) ? 1 : 0;
637 nfile->ungetsize = 16;
638 nfile->ungetbuf = malloc(nfile->ungetsize);
639 if (nfile->ungetbuf == NULL) {
640 log_warn("malloc");
641 fclose(nfile->stream);
642 free(nfile->name);
643 free(nfile);
644 return NULL;
646 TAILQ_INSERT_TAIL(&files, nfile, entry);
647 return nfile;
650 int
651 popfile(void)
653 struct file *prev;
655 if ((prev = TAILQ_PREV(file, files, entry)) != NULL)
656 prev->errors += file->errors;
658 TAILQ_REMOVE(&files, file, entry);
659 fclose(file->stream);
660 free(file->name);
661 free(file->ungetbuf);
662 free(file);
663 file = prev;
664 return file ? 0 : EOF;
667 void
668 loadfile(const char *path)
670 int errors;
672 file = pushfile(path);
673 if (file == NULL)
674 err(1, "pushfile");
675 topfile = file;
677 yyparse();
678 errors = file->errors;
679 popfile();
681 if (errors)
682 errx(1, "can't load %s because of errors", path);