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 "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 "kamid.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 DIR
92 %token ERROR
93 %token INCLUDE
94 %token PROC
95 %token REPEAT
96 %token SHOULD_FAIL STR
97 %token TESTING
98 %token U8 U16 U32
99 %token VARGS
101 %token <v.str> STRING SYMBOL
102 %token <v.num> NUMBER
104 %type <v.op> cast cexpr check expr faccess funcall
105 %type <v.op> literal sfail var varref vargs
107 %type <v.proc> procname
109 %%
111 program : /* empty */
112 | program '\n'
113 | program include '\n'
114 | program const '\n'
115 | program proc '\n'
116 | program test '\n'
119 optnl : '\n' optnl /* zero or more newlines */
120 | /*empty*/
123 nl : '\n' optnl ;
125 include : INCLUDE STRING {
126 struct file *nfile;
128 if ((nfile = pushfile($2)) == NULL) {
129 yyerror("failed to include file %s", $2);
130 free($2);
131 YYERROR;
133 free($2);
135 file = nfile;
136 lungetc('\n');
140 const : CONST consti
141 | CONST '(' optnl mconst ')'
144 mconst : consti nl | mconst consti nl ;
146 consti : SYMBOL '=' expr {
147 if (!global_set($1, $3)) {
148 yyerror("can't set %s: illegal expression", $1);
149 free($1);
150 free_op($3);
151 YYERROR;
156 var : SYMBOL '=' expr { $$ = op_assign($1, $3); } ;
157 varref : SYMBOL { $$ = op_var($1); } ;
158 literal : STRING { $$ = op_lit_str($1); }
159 | NUMBER { $$ = op_lit_num($1); } ;
161 /*
162 * `expr '=' '=' expr` is ambiguous. furthermore, we're not
163 * interested in checking all the possibilities here.
164 */
165 cexpr : literal | varref | funcall | faccess ;
166 check : cexpr '=' '=' cexpr { $$ = op_cmp_eq($1, $4); } ;
168 expr : literal | funcall | varref | check | cast | faccess | vargs ;
170 vargs : VARGS { $$ = op_vargs(); } ;
172 cast : expr ':' U8 { $$ = op_cast($1, V_U8); }
173 | expr ':' U16 { $$ = op_cast($1, V_U16); }
174 | expr ':' U32 { $$ = op_cast($1, V_U32); }
175 | expr ':' STR { $$ = op_cast($1, V_STR); }
178 faccess : varref '.' SYMBOL { $$ = op_faccess($1, $3); }
179 | faccess '.' SYMBOL { $$ = op_faccess($1, $3); }
182 procname: SYMBOL {
183 if (($$ = proc_by_name($1)) == NULL) {
184 yyerror("unknown proc %s", $1);
185 free($1);
186 YYERROR;
188 free($1);
192 funcall : procname {
193 prepare_funcall();
194 } '(' args optcomma ')' {
195 struct proc *proc;
196 int argc;
198 $$ = op_funcall($1);
199 proc = $$->v.funcall.proc;
200 argc = $$->v.funcall.argc;
202 if (argc != proc->minargs && !proc->vararg) {
203 yyerror("invalid arity for `%s': want %d arguments "
204 "but %d given.", $1->name, proc->minargs, argc);
205 /* TODO: recursively free $$ */
206 YYERROR;
209 if (argc < proc->minargs && proc->vararg) {
210 yyerror("invalid arity for `%s': want at least %d "
211 "arguments but %d given.", $1->name, proc->minargs,
212 argc);
213 /* TODO: recursively free $$ */
214 YYERROR;
219 optcomma: /* empty */ | ',' ;
221 dots : '.' '.' '.' ;
223 args : /* empty */
224 | args ',' expr { push_arg($3); }
225 | args ',' dots { push_arg(op_rest()); }
226 | expr { push_arg($1); }
227 | dots { push_arg(op_rest()); }
230 proc : PROC SYMBOL {
231 prepare_proc();
232 } '(' args ')' {
233 if (!proc_setup_body()) {
234 yyerror("invalid argument in proc `%s' definition",
235 $2);
236 free($2);
237 YYERROR;
239 } '{' optnl block '}' {
240 proc_done($2);
244 block : /* empty */
245 | block var nl { block_push($2); }
246 | block funcall nl { block_push($2); }
247 | block assert nl
248 | block sfail nl { block_push($2); }
251 sfail : SHOULD_FAIL expr { $$ = op_sfail($2, NULL); }
252 | SHOULD_FAIL expr ':' STRING { $$ = op_sfail($2, $4); }
255 assert : ASSERT asserti
256 | ASSERT '(' optnl massert ')'
259 massert : asserti nl | massert asserti nl ;
261 asserti : check { block_push(op_assert($1)); }
264 test : TESTING STRING DIR STRING {
265 prepare_test();
266 } testopt '{' optnl block '}' {
267 test_done(shouldfail, $2, $4);
268 shouldfail = 0;
272 testopt : /* empty */
273 | SHOULD_FAIL { shouldfail = 1; }
276 %%
278 struct keywords {
279 const char *k_name;
280 int k_val;
281 };
283 int
284 yyerror(const char *fmt, ...)
286 va_list ap;
287 char *msg;
289 file->errors++;
290 va_start(ap, fmt);
291 if (vasprintf(&msg, fmt, ap) == -1)
292 fatalx("yyerror vasprintf");
293 va_end(ap);
294 logit(LOG_CRIT, "%s:%d: %s", file->name, yylval.lineno, msg);
295 free(msg);
296 return 0;
299 int
300 kw_cmp(const void *k, const void *e)
302 return strcmp(k, ((const struct keywords *)e)->k_name);
305 int
306 lookup(char *s)
308 /* This has to be sorted always. */
309 static const struct keywords keywords[] = {
310 {"assert", ASSERT},
311 {"const", CONST},
312 {"dir", DIR},
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 DIR: puts("dir"); break;
453 case ERROR: puts("error"); break;
454 case INCLUDE: puts("include"); break;
455 case PROC: puts("proc"); break;
456 case REPEAT: puts("repeat"); break;
457 case STR: puts(":str"); break;
458 case TESTING: puts("testing"); break;
459 case U8: puts(":u8"); break;
460 case U16: puts(":u16"); break;
461 case U32: puts(":u32"); break;
463 case STRING: printf("string \"%s\"\n", yylval.v.str); break;
464 case SYMBOL: printf("symbol %s\n", yylval.v.str); break;
465 case NUMBER: printf("number %"PRIu64"\n", yylval.v.num); break;
467 default:
468 printf("character ");
469 if (x == '\n')
470 printf("\\n");
471 else
472 printf("%c", x);
473 printf(" [0x%x]", x);
474 printf("\n");
475 break;
478 return x;
481 int
482 my_yylex(void)
483 #else
484 int
485 yylex(void)
486 #endif
488 unsigned char buf[8096];
489 unsigned char *p;
490 int quotec, next, c;
491 int token;
493 p = buf;
494 while ((c = lgetc(0)) == ' ' || c == '\t' || c == '\f')
495 ; /* nop */
497 yylval.lineno = file->lineno;
498 if (c == '#')
499 while ((c = lgetc(0)) != '\n' && c != EOF)
500 ; /* nop */
502 switch (c) {
503 case ':':
504 return c;
505 break;
506 case '\'':
507 case '\"':
508 quotec = c;
509 while (1) {
510 if ((c = lgetc(quotec)) == EOF)
511 return 0;
512 if (c == '\n') {
513 file->lineno++;
514 continue;
515 } else if (c == '\\') {
516 if ((next = lgetc(quotec)) == EOF)
517 return 0;
518 if (next == quotec || next == ' ' ||
519 next == '\t')
520 c = next;
521 else if (next == '\n') {
522 file->lineno++;
523 continue;
524 } else
525 lungetc(next);
526 } else if (c == quotec) {
527 *p = '\0';
528 break;
529 } else if (c == '\0') {
530 yyerror("syntax error");
531 return findeol();
534 if (p + 1 >= buf + sizeof(buf) - 1) {
535 yyerror("string too long");
536 return findeol();
539 *p++ = c;
542 yylval.v.str = xstrdup(buf);
543 return STRING;
546 #define allowed_to_end_number(x) \
547 (isspace(x) || x == ')' || x == ',' || x == '/' || x == '}' \
548 || x == '=' || x == ':')
550 if (c == '-' || isdigit(c)) {
551 do {
552 *p++ = c;
553 if ((size_t)(p-buf) >= sizeof(buf)) {
554 yyerror("string too long");
555 return findeol();
557 } while ((c = lgetc(0)) != EOF && (isdigit(c) || c == 'x'));
558 lungetc(c);
559 if (p == buf + 1 && buf[0] == '-')
560 goto nodigits;
561 if (c == EOF || allowed_to_end_number(c)) {
562 char *ep;
564 *p = '\0';
565 errno = 0;
566 yylval.v.num = strtoll(buf, &ep, 0);
567 if (*ep != '\0' || (errno == ERANGE &&
568 (yylval.v.num == LONG_MAX ||
569 yylval.v.num == LONG_MIN))) {
570 yyerror("\"%s\" invalid number or out of range",
571 buf);
572 return findeol();
575 return NUMBER;
576 } else {
577 nodigits:
578 while (p > buf + 1)
579 lungetc(*--p);
580 c = *--p;
581 if (c == '-')
582 return c;
586 #define allowed_in_symbol(x) \
587 (isalnum(x) || (ispunct(x) && x != '(' && x != ')' && \
588 x != '{' && x != '}' && \
589 x != '!' && x != '=' && \
590 x != '#' && x != ',' && \
591 x != '.' && x != ':'))
593 if (isalnum(c) || c == ':' || c == '_') {
594 do {
595 *p++ = c;
596 if ((size_t)(p-buf) >= sizeof(buf)) {
597 yyerror("string too long");
598 return findeol();
600 } while ((c = lgetc(0)) != EOF && (allowed_in_symbol(c)));
601 lungetc(c);
602 *p = '\0';
603 if ((token = lookup(buf)) == SYMBOL)
604 yylval.v.str = xstrdup(buf);
605 return token;
608 if (c == '\n') {
609 yylval.lineno = file->lineno;
610 file->lineno++;
612 if (c == EOF)
613 return 0;
614 return c;
617 struct file *
618 pushfile(const char *name)
620 struct file *nfile;
622 if ((nfile = calloc(1, sizeof(struct file))) == NULL) {
623 log_warn("calloc");
624 return NULL;
626 if ((nfile->name = strdup(name)) == NULL) {
627 log_warn("strdup");
628 free(nfile);
629 return NULL;
631 if ((nfile->stream = fopen(nfile->name, "r")) == NULL) {
632 log_warn("%s", nfile->name);
633 free(nfile->name);
634 free(nfile);
635 return NULL;
637 nfile->lineno = TAILQ_EMPTY(&files) ? 1 : 0;
638 nfile->ungetsize = 16;
639 nfile->ungetbuf = malloc(nfile->ungetsize);
640 if (nfile->ungetbuf == NULL) {
641 log_warn("malloc");
642 fclose(nfile->stream);
643 free(nfile->name);
644 free(nfile);
645 return NULL;
647 TAILQ_INSERT_TAIL(&files, nfile, entry);
648 return nfile;
651 int
652 popfile(void)
654 struct file *prev;
656 if ((prev = TAILQ_PREV(file, files, entry)) != NULL)
657 prev->errors += file->errors;
659 TAILQ_REMOVE(&files, file, entry);
660 fclose(file->stream);
661 free(file->name);
662 free(file->ungetbuf);
663 free(file);
664 file = prev;
665 return file ? 0 : EOF;
668 void
669 loadfile(const char *path)
671 int errors;
673 file = pushfile(path);
674 if (file == NULL)
675 err(1, "pushfile");
676 topfile = file;
678 yyparse();
679 errors = file->errors;
680 popfile();
682 if (errors)
683 errx(1, "can't load %s because of errors", path);