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 <inttypes.h>
30 #include <limits.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <syslog.h>
36 #include "log.h"
37 #include "kamid.h"
38 #include "utils.h"
40 #include "script.h"
42 TAILQ_HEAD(files, file) files = TAILQ_HEAD_INITIALIZER(files);
43 static struct file {
44 TAILQ_ENTRY(file) entry;
45 FILE *stream;
46 char *name;
47 size_t ungetpos;
48 size_t ungetsize;
49 u_char *ungetbuf;
50 int eof_reached;
51 int lineno;
52 int errors;
53 } *file, *topfile;
54 struct file *pushfile(const char *);
55 int popfile(void);
56 int yyparse(void);
57 int yylex(void);
58 int yyerror(const char *, ...)
59 __attribute__((__format__ (printf, 1, 2)))
60 __attribute__((__nonnull__ (1)));
61 int kw_cmp(const void *, const void *);
62 int lookup(char *);
63 int igetc(void);
64 int lgetc(int);
65 void lungetc(int);
66 int findeol(void);
68 typedef struct {
69 union {
70 struct op *op;
71 struct proc *proc;
72 char *str;
73 int64_t num;
74 } v;
75 int lineno;
76 } YYSTYPE;
78 %}
80 /*
81 * for bison:
82 * %define parse.error verbose
83 */
85 %token ASSERT
86 %token CONST
87 %token DIR
88 %token ERROR
89 %token INCLUDE
90 %token PROC
91 %token REPEAT
92 %token STR
93 %token TESTING
94 %token U8 U16 U32
96 %token <v.str> STRING SYMBOL
97 %token <v.num> NUMBER
99 %type <v.op> cast cexpr check expr funcall
100 %type <v.op> literal var varref
102 %type <v.proc> procname
104 %%
106 program : /* empty */
107 | program '\n'
108 | program include '\n'
109 | program const '\n'
110 | program proc '\n'
111 | program test '\n'
114 optnl : '\n' optnl /* zero or more newlines */
115 | /*empty*/
118 include : INCLUDE STRING {
119 struct file *nfile;
121 if ((nfile = pushfile($2)) == NULL) {
122 yyerror("failed to include file %s", $2);
123 free($2);
124 YYERROR;
126 free($2);
128 file = nfile;
129 lungetc('\n');
133 const : CONST SYMBOL '=' literal {
134 if (!global_set($2, $4)) {
135 yyerror("constant expression is not a literal");
136 free($2);
137 free_op($4);
138 YYERROR;
140 };
142 var : SYMBOL '=' expr { $$ = op_assign($1, $3); } ;
143 varref : SYMBOL { $$ = op_var($1); } ;
144 literal : STRING { $$ = op_lit_str($1); }
145 | NUMBER { $$ = op_lit_num($1); } ;
147 /*
148 * `expr '=' '=' expr` is ambiguous. furthermore, we're not
149 * interested in checking all the possibilities here.
150 */
151 cexpr : literal | varref | funcall ;
152 check : cexpr '=' '=' cexpr { $$ = op_cmp_eq($1, $4); } ;
154 expr : literal | funcall | varref | check | cast ;
156 cast : expr ':' U8 { $$ = op_cast($1, V_U8); }
157 | expr ':' U16 { $$ = op_cast($1, V_U16); }
158 | expr ':' U32 { $$ = op_cast($1, V_U32); }
159 | expr ':' STR { $$ = op_cast($1, V_STR); }
162 procname: SYMBOL {
163 if (($$ = proc_by_name($1)) == NULL) {
164 yyerror("unknown proc %s", $1);
165 free($1);
166 YYERROR;
168 free($1);
172 funcall : procname {
173 prepare_funcall();
174 } '(' args optcomma ')' {
175 $$ = op_funcall($1);
176 if ($$->v.funcall.argc != $$->v.funcall.proc->minargs) {
177 yyerror("invalid arity for `%s'",
178 $1->name);
179 /* TODO: recursively free $$ */
180 YYERROR;
185 optcomma: /* empty */ | ',' ;
187 args : /* empty */
188 | args ',' expr { push_arg($3); }
189 | expr { push_arg($1); }
192 proc : PROC SYMBOL {
193 prepare_proc();
194 } '(' args ')' {
195 if (!proc_setup_body()) {
196 yyerror("invalid argument in proc `%s' definition",
197 $2);
198 free($2);
199 YYERROR;
201 } '{' optnl block '}' {
202 proc_done($2);
206 block : /* empty */
207 | block var '\n' { block_push($2); }
208 | block funcall '\n' { block_push($2); }
209 | block assert '\n'
212 assert : ASSERT check { block_push(op_assert($2)); }
213 /* | ASSERT '(' optnl massert ')' */
216 massert : /* empty */
217 | massert ',' optnl check { block_push(op_assert($4)); }
218 | check { block_push(op_assert($1)); }
221 test : TESTING STRING DIR STRING {
222 prepare_test();
223 } '{' optnl block '}' {
224 test_done($2, $4);
228 %%
230 struct keywords {
231 const char *k_name;
232 int k_val;
233 };
235 int
236 yyerror(const char *fmt, ...)
238 va_list ap;
239 char *msg;
241 file->errors++;
242 va_start(ap, fmt);
243 if (vasprintf(&msg, fmt, ap) == -1)
244 fatalx("yyerror vasprintf");
245 va_end(ap);
246 logit(LOG_CRIT, "%s:%d: %s", file->name, yylval.lineno, msg);
247 free(msg);
248 return 0;
251 int
252 kw_cmp(const void *k, const void *e)
254 return strcmp(k, ((const struct keywords *)e)->k_name);
257 int
258 lookup(char *s)
260 /* This has to be sorted always. */
261 static const struct keywords keywords[] = {
262 {"assert", ASSERT},
263 {"const", CONST},
264 {"dir", DIR},
265 {"include", INCLUDE},
266 {"proc", PROC},
267 {"repeat", REPEAT},
268 {"str", STR},
269 {"testing", TESTING},
270 {"u16", U16},
271 {"u32", U32},
272 {"u8", U8},
273 };
274 const struct keywords *p;
276 p = bsearch(s, keywords, sizeof(keywords)/sizeof(keywords[0]),
277 sizeof(keywords[0]), kw_cmp);
279 if (p)
280 return p->k_val;
281 else
282 return SYMBOL;
285 #define START_EXPAND 1
286 #define DONE_EXPAND 2
288 static int expanding;
290 int
291 igetc(void)
293 int c;
295 while (1) {
296 if (file->ungetpos > 0)
297 c = file->ungetbuf[--file->ungetpos];
298 else
299 c = getc(file->stream);
301 if (c == START_EXPAND)
302 expanding = 1;
303 else if (c == DONE_EXPAND)
304 expanding = 0;
305 else
306 break;
308 return c;
311 int
312 lgetc(int quotec)
314 int c, next;
316 if (quotec) {
317 if ((c = igetc()) == EOF) {
318 yyerror("reached end of file while parsing "
319 "quoted string");
320 if (file == topfile || popfile() == EOF)
321 return EOF;
322 return quotec;
324 return c;
327 while ((c = igetc()) == '\\') {
328 next = igetc();
329 if (next != '\n') {
330 c = next;
331 break;
333 yylval.lineno = file->lineno;
334 file->lineno++;
337 if (c == EOF) {
338 /*
339 * Fake EOL when hit EOF for the first time. This gets line
340 * count right if last line in included file is syntactically
341 * invalid and has no newline.
342 */
343 if (file->eof_reached == 0) {
344 file->eof_reached = 1;
345 return '\n';
347 while (c == EOF) {
348 if (file == topfile || popfile() == EOF)
349 return EOF;
350 c = igetc();
353 return c;
356 void
357 lungetc(int c)
359 if (c == EOF)
360 return;
362 if (file->ungetpos >= file->ungetsize) {
363 void *p = reallocarray(file->ungetbuf, file->ungetsize, 2);
364 if (p == NULL)
365 err(1, "lungetc");
366 file->ungetbuf = p;
367 file->ungetsize *= 2;
369 file->ungetbuf[file->ungetpos++] = c;
372 int
373 findeol(void)
375 int c;
377 /* Skip to either EOF or the first real EOL. */
378 while (1) {
379 c = lgetc(0);
380 if (c == '\n') {
381 file->lineno++;
382 break;
384 if (c == EOF)
385 break;
387 return ERROR;
391 #if 0
392 int my_yylex(void);
394 int
395 yylex(void)
397 int x;
399 switch (x = my_yylex()) {
400 case ASSERT: puts("assert"); break;
401 case CONST: puts("const"); break;
402 case DIR: puts("dir"); break;
403 case ERROR: puts("error"); break;
404 case INCLUDE: puts("include"); break;
405 case PROC: puts("proc"); break;
406 case REPEAT: puts("repeat"); break;
407 case STR: puts(":str"); break;
408 case TESTING: puts("testing"); break;
409 case U8: puts(":u8"); break;
410 case U16: puts(":u16"); break;
411 case U32: puts(":u32"); break;
413 case STRING: printf("string \"%s\"\n", yylval.v.str); break;
414 case SYMBOL: printf("symbol %s\n", yylval.v.str); break;
415 case NUMBER: printf("number %"PRIu64"\n", yylval.v.num); break;
417 default:
418 printf("character ");
419 if (x == '\n')
420 printf("\\n");
421 else
422 printf("%c", x);
423 printf(" [0x%x]", x);
424 printf("\n");
425 break;
428 return x;
431 int
432 my_yylex(void)
433 #else
434 int
435 yylex(void)
436 #endif
438 unsigned char buf[8096];
439 unsigned char *p;
440 int quotec, next, c;
441 int token;
443 p = buf;
444 while ((c = lgetc(0)) == ' ' || c == '\t' || c == '\f')
445 ; /* nop */
447 yylval.lineno = file->lineno;
448 if (c == '#')
449 while ((c = lgetc(0)) != '\n' && c != EOF)
450 ; /* nop */
452 switch (c) {
453 case ':':
454 return c;
455 break;
456 case '\'':
457 case '\"':
458 quotec = c;
459 while (1) {
460 if ((c = lgetc(quotec)) == EOF)
461 return 0;
462 if (c == '\n') {
463 file->lineno++;
464 continue;
465 } else if (c == '\\') {
466 if ((next = lgetc(quotec)) == EOF)
467 return 0;
468 if (next == quotec || next == ' ' ||
469 next == '\t')
470 c = next;
471 else if (next == '\n') {
472 file->lineno++;
473 continue;
474 } else
475 lungetc(next);
476 } else if (c == quotec) {
477 *p = '\0';
478 break;
479 } else if (c == '\0') {
480 yyerror("syntax error");
481 return findeol();
484 if (p + 1 >= buf + sizeof(buf) - 1) {
485 yyerror("string too long");
486 return findeol();
489 *p++ = c;
492 yylval.v.str = xstrdup(buf);
493 return STRING;
496 #define allowed_to_end_number(x) \
497 (isspace(x) || x == ')' || x == ',' || x == '/' || x == '}' \
498 || x == '=' || x == ':')
500 if (c == '-' || isdigit(c)) {
501 do {
502 *p++ = c;
503 if ((size_t)(p-buf) >= sizeof(buf)) {
504 yyerror("string too long");
505 return findeol();
507 } while ((c = lgetc(0)) != EOF && isdigit(c));
508 lungetc(c);
509 if (p == buf + 1 && buf[0] == '-')
510 goto nodigits;
511 if (c == EOF || allowed_to_end_number(c)) {
512 const char *errstr = NULL;
514 *p = '\0';
515 yylval.v.num = strtonum(buf, INT64_MIN, INT64_MAX,
516 &errstr);
517 if (errstr) {
518 yyerror("\"%s\" invalid number: %s",
519 buf, errstr);
520 return findeol();
522 return NUMBER;
523 } else {
524 nodigits:
525 while (p > buf + 1)
526 lungetc(*--p);
527 c = *--p;
528 if (c == '-')
529 return c;
533 #define allowed_in_symbol(x) \
534 (isalnum(x) || (ispunct(x) && x != '(' && x != ')' && \
535 x != '{' && x != '}' && \
536 x != '!' && x != '=' && \
537 x != '#' && x != ','))
539 if (isalnum(c) || c == ':' || c == '_') {
540 do {
541 *p++ = c;
542 if ((size_t)(p-buf) >= sizeof(buf)) {
543 yyerror("string too long");
544 return findeol();
546 } while ((c = lgetc(0)) != EOF && (allowed_in_symbol(c)));
547 lungetc(c);
548 *p = '\0';
549 if ((token = lookup(buf)) == SYMBOL)
550 yylval.v.str = xstrdup(buf);
551 return token;
554 if (c == '\n') {
555 yylval.lineno = file->lineno;
556 file->lineno++;
558 if (c == EOF)
559 return 0;
560 return c;
563 struct file *
564 pushfile(const char *name)
566 struct file *nfile;
568 if ((nfile = calloc(1, sizeof(struct file))) == NULL) {
569 log_warn("calloc");
570 return NULL;
572 if ((nfile->name = strdup(name)) == NULL) {
573 log_warn("strdup");
574 free(nfile);
575 return NULL;
577 if ((nfile->stream = fopen(nfile->name, "r")) == NULL) {
578 log_warn("%s", nfile->name);
579 free(nfile->name);
580 free(nfile);
581 return NULL;
583 nfile->lineno = TAILQ_EMPTY(&files) ? 1 : 0;
584 nfile->ungetsize = 16;
585 nfile->ungetbuf = malloc(nfile->ungetsize);
586 if (nfile->ungetbuf == NULL) {
587 log_warn("malloc");
588 fclose(nfile->stream);
589 free(nfile->name);
590 free(nfile);
591 return NULL;
593 TAILQ_INSERT_TAIL(&files, nfile, entry);
594 return nfile;
597 int
598 popfile(void)
600 struct file *prev;
602 if ((prev = TAILQ_PREV(file, files, entry)) != NULL)
603 prev->errors += file->errors;
605 TAILQ_REMOVE(&files, file, entry);
606 fclose(file->stream);
607 free(file->name);
608 free(file->ungetbuf);
609 free(file);
610 file = prev;
611 return file ? 0 : EOF;
614 void
615 loadfile(const char *path)
617 int errors;
619 file = pushfile(path);
620 if (file == NULL)
621 err(1, "pushfile");
622 topfile = file;
624 yyparse();
625 errors = file->errors;
626 popfile();
628 if (errors)
629 errx(1, "can't load %s because of errors", path);