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); }
167 | cexpr '<' '=' cexpr { $$ = op_cmp_leq($1, $4); }
170 expr : literal | funcall | varref | check | cast | faccess | vargs ;
172 vargs : VARGS { $$ = op_vargs(); } ;
174 cast : expr ':' U8 { $$ = op_cast($1, V_U8); }
175 | expr ':' U16 { $$ = op_cast($1, V_U16); }
176 | expr ':' U32 { $$ = op_cast($1, V_U32); }
177 | expr ':' STR { $$ = op_cast($1, V_STR); }
180 faccess : varref '.' SYMBOL { $$ = op_faccess($1, $3); }
181 | faccess '.' SYMBOL { $$ = op_faccess($1, $3); }
184 procname: SYMBOL {
185 if (($$ = proc_by_name($1)) == NULL) {
186 yyerror("unknown proc %s", $1);
187 free($1);
188 YYERROR;
190 free($1);
194 funcall : procname {
195 prepare_funcall();
196 } '(' args optcomma ')' {
197 struct proc *proc;
198 int argc;
200 $$ = op_funcall($1);
201 proc = $$->v.funcall.proc;
202 argc = $$->v.funcall.argc;
204 if (argc != proc->minargs && !proc->vararg) {
205 yyerror("invalid arity for `%s': want %d arguments "
206 "but %d given.", $1->name, proc->minargs, argc);
207 /* TODO: recursively free $$ */
208 YYERROR;
211 if (argc < proc->minargs && proc->vararg) {
212 yyerror("invalid arity for `%s': want at least %d "
213 "arguments but %d given.", $1->name, proc->minargs,
214 argc);
215 /* TODO: recursively free $$ */
216 YYERROR;
221 optcomma: /* empty */ | ',' ;
223 dots : '.' '.' '.' ;
225 args : /* empty */
226 | args ',' expr { push_arg($3); }
227 | args ',' dots { push_arg(op_rest()); }
228 | expr { push_arg($1); }
229 | dots { push_arg(op_rest()); }
232 proc : PROC SYMBOL {
233 prepare_proc();
234 } '(' args ')' {
235 if (!proc_setup_body()) {
236 yyerror("invalid argument in proc `%s' definition",
237 $2);
238 free($2);
239 YYERROR;
241 } '{' optnl block '}' {
242 proc_done($2);
246 block : /* empty */
247 | block var nl { block_push($2); }
248 | block funcall nl { block_push($2); }
249 | block assert nl
250 | block sfail nl { block_push($2); }
253 sfail : SHOULD_FAIL expr { $$ = op_sfail($2, NULL); }
254 | SHOULD_FAIL expr ':' STRING { $$ = op_sfail($2, $4); }
257 assert : ASSERT asserti
258 | ASSERT '(' optnl massert ')'
261 massert : asserti nl | massert asserti nl ;
263 asserti : check { block_push(op_assert($1)); }
266 test : TESTING STRING DIR STRING {
267 prepare_test();
268 } testopt '{' optnl block '}' {
269 test_done(shouldfail, $2, $4);
270 shouldfail = 0;
274 testopt : /* empty */
275 | SHOULD_FAIL { shouldfail = 1; }
278 %%
280 struct keywords {
281 const char *k_name;
282 int k_val;
283 };
285 int
286 yyerror(const char *fmt, ...)
288 va_list ap;
289 char *msg;
291 file->errors++;
292 va_start(ap, fmt);
293 if (vasprintf(&msg, fmt, ap) == -1)
294 fatalx("yyerror vasprintf");
295 va_end(ap);
296 logit(LOG_CRIT, "%s:%d: %s", file->name, yylval.lineno, msg);
297 free(msg);
298 return 0;
301 int
302 kw_cmp(const void *k, const void *e)
304 return strcmp(k, ((const struct keywords *)e)->k_name);
307 int
308 lookup(char *s)
310 /* This has to be sorted always. */
311 static const struct keywords keywords[] = {
312 {"assert", ASSERT},
313 {"const", CONST},
314 {"dir", DIR},
315 {"include", INCLUDE},
316 {"proc", PROC},
317 {"repeat", REPEAT},
318 {"should-fail", SHOULD_FAIL},
319 {"str", STR},
320 {"testing", TESTING},
321 {"u16", U16},
322 {"u32", U32},
323 {"u8", U8},
324 {"vargs", VARGS},
325 };
326 const struct keywords *p;
328 p = bsearch(s, keywords, sizeof(keywords)/sizeof(keywords[0]),
329 sizeof(keywords[0]), kw_cmp);
331 if (p)
332 return p->k_val;
333 else
334 return SYMBOL;
337 #define START_EXPAND 1
338 #define DONE_EXPAND 2
340 static int expanding;
342 int
343 igetc(void)
345 int c;
347 while (1) {
348 if (file->ungetpos > 0)
349 c = file->ungetbuf[--file->ungetpos];
350 else
351 c = getc(file->stream);
353 if (c == START_EXPAND)
354 expanding = 1;
355 else if (c == DONE_EXPAND)
356 expanding = 0;
357 else
358 break;
360 return c;
363 int
364 lgetc(int quotec)
366 int c, next;
368 if (quotec) {
369 if ((c = igetc()) == EOF) {
370 yyerror("reached end of file while parsing "
371 "quoted string");
372 if (file == topfile || popfile() == EOF)
373 return EOF;
374 return quotec;
376 return c;
379 while ((c = igetc()) == '\\') {
380 next = igetc();
381 if (next != '\n') {
382 c = next;
383 break;
385 yylval.lineno = file->lineno;
386 file->lineno++;
389 if (c == EOF) {
390 /*
391 * Fake EOL when hit EOF for the first time. This gets line
392 * count right if last line in included file is syntactically
393 * invalid and has no newline.
394 */
395 if (file->eof_reached == 0) {
396 file->eof_reached = 1;
397 return '\n';
399 while (c == EOF) {
400 if (file == topfile || popfile() == EOF)
401 return EOF;
402 c = igetc();
405 return c;
408 void
409 lungetc(int c)
411 if (c == EOF)
412 return;
414 if (file->ungetpos >= file->ungetsize) {
415 void *p = reallocarray(file->ungetbuf, file->ungetsize, 2);
416 if (p == NULL)
417 err(1, "lungetc");
418 file->ungetbuf = p;
419 file->ungetsize *= 2;
421 file->ungetbuf[file->ungetpos++] = c;
424 int
425 findeol(void)
427 int c;
429 /* Skip to either EOF or the first real EOL. */
430 while (1) {
431 c = lgetc(0);
432 if (c == '\n') {
433 file->lineno++;
434 break;
436 if (c == EOF)
437 break;
439 return ERROR;
443 #if 0
444 int my_yylex(void);
446 int
447 yylex(void)
449 int x;
451 switch (x = my_yylex()) {
452 case ASSERT: puts("assert"); break;
453 case CONST: puts("const"); break;
454 case DIR: puts("dir"); break;
455 case ERROR: puts("error"); break;
456 case INCLUDE: puts("include"); break;
457 case PROC: puts("proc"); break;
458 case REPEAT: puts("repeat"); break;
459 case STR: puts(":str"); break;
460 case TESTING: puts("testing"); break;
461 case U8: puts(":u8"); break;
462 case U16: puts(":u16"); break;
463 case U32: puts(":u32"); break;
465 case STRING: printf("string \"%s\"\n", yylval.v.str); break;
466 case SYMBOL: printf("symbol %s\n", yylval.v.str); break;
467 case NUMBER: printf("number %"PRIu64"\n", yylval.v.num); break;
469 default:
470 printf("character ");
471 if (x == '\n')
472 printf("\\n");
473 else
474 printf("%c", x);
475 printf(" [0x%x]", x);
476 printf("\n");
477 break;
480 return x;
483 int
484 my_yylex(void)
485 #else
486 int
487 yylex(void)
488 #endif
490 unsigned char buf[8096];
491 unsigned char *p;
492 int quotec, next, c;
493 int token;
495 p = buf;
496 while ((c = lgetc(0)) == ' ' || c == '\t' || c == '\f')
497 ; /* nop */
499 yylval.lineno = file->lineno;
500 if (c == '#')
501 while ((c = lgetc(0)) != '\n' && c != EOF)
502 ; /* nop */
504 switch (c) {
505 case ':':
506 return c;
507 break;
508 case '\'':
509 case '\"':
510 quotec = c;
511 while (1) {
512 if ((c = lgetc(quotec)) == EOF)
513 return 0;
514 if (c == '\n') {
515 file->lineno++;
516 continue;
517 } else if (c == '\\') {
518 if ((next = lgetc(quotec)) == EOF)
519 return 0;
520 if (next == quotec || next == ' ' ||
521 next == '\t')
522 c = next;
523 else if (next == '\n') {
524 file->lineno++;
525 continue;
526 } else
527 lungetc(next);
528 } else if (c == quotec) {
529 *p = '\0';
530 break;
531 } else if (c == '\0') {
532 yyerror("syntax error");
533 return findeol();
536 if (p + 1 >= buf + sizeof(buf) - 1) {
537 yyerror("string too long");
538 return findeol();
541 *p++ = c;
544 yylval.v.str = xstrdup(buf);
545 return STRING;
548 #define allowed_to_end_number(x) \
549 (isspace(x) || x == ')' || x == ',' || x == '/' || x == '}' \
550 || x == '=' || x == ':')
552 if (c == '-' || isdigit(c)) {
553 do {
554 *p++ = c;
555 if ((size_t)(p-buf) >= sizeof(buf)) {
556 yyerror("string too long");
557 return findeol();
559 } while ((c = lgetc(0)) != EOF && (isdigit(c) || c == 'x'));
560 lungetc(c);
561 if (p == buf + 1 && buf[0] == '-')
562 goto nodigits;
563 if (c == EOF || allowed_to_end_number(c)) {
564 char *ep;
566 *p = '\0';
567 errno = 0;
568 yylval.v.num = strtoll(buf, &ep, 0);
569 if (*ep != '\0' || (errno == ERANGE &&
570 (yylval.v.num == LONG_MAX ||
571 yylval.v.num == LONG_MIN))) {
572 yyerror("\"%s\" invalid number or out of range",
573 buf);
574 return findeol();
577 return NUMBER;
578 } else {
579 nodigits:
580 while (p > buf + 1)
581 lungetc(*--p);
582 c = *--p;
583 if (c == '-')
584 return c;
588 #define allowed_in_symbol(x) \
589 (isalnum(x) || (ispunct(x) && x != '(' && x != ')' && \
590 x != '{' && x != '}' && \
591 x != '!' && x != '=' && \
592 x != '#' && x != ',' && \
593 x != '.' && x != ':'))
595 if (isalnum(c) || c == ':' || c == '_') {
596 do {
597 *p++ = c;
598 if ((size_t)(p-buf) >= sizeof(buf)) {
599 yyerror("string too long");
600 return findeol();
602 } while ((c = lgetc(0)) != EOF && (allowed_in_symbol(c)));
603 lungetc(c);
604 *p = '\0';
605 if ((token = lookup(buf)) == SYMBOL)
606 yylval.v.str = xstrdup(buf);
607 return token;
610 if (c == '\n') {
611 yylval.lineno = file->lineno;
612 file->lineno++;
614 if (c == EOF)
615 return 0;
616 return c;
619 struct file *
620 pushfile(const char *name)
622 struct file *nfile;
624 if ((nfile = calloc(1, sizeof(struct file))) == NULL) {
625 log_warn("calloc");
626 return NULL;
628 if ((nfile->name = strdup(name)) == NULL) {
629 log_warn("strdup");
630 free(nfile);
631 return NULL;
633 if ((nfile->stream = fopen(nfile->name, "r")) == NULL) {
634 log_warn("%s", nfile->name);
635 free(nfile->name);
636 free(nfile);
637 return NULL;
639 nfile->lineno = TAILQ_EMPTY(&files) ? 1 : 0;
640 nfile->ungetsize = 16;
641 nfile->ungetbuf = malloc(nfile->ungetsize);
642 if (nfile->ungetbuf == NULL) {
643 log_warn("malloc");
644 fclose(nfile->stream);
645 free(nfile->name);
646 free(nfile);
647 return NULL;
649 TAILQ_INSERT_TAIL(&files, nfile, entry);
650 return nfile;
653 int
654 popfile(void)
656 struct file *prev;
658 if ((prev = TAILQ_PREV(file, files, entry)) != NULL)
659 prev->errors += file->errors;
661 TAILQ_REMOVE(&files, file, entry);
662 fclose(file->stream);
663 free(file->name);
664 free(file->ungetbuf);
665 free(file);
666 file = prev;
667 return file ? 0 : EOF;
670 void
671 loadfile(const char *path)
673 int errors;
675 file = pushfile(path);
676 if (file == NULL)
677 err(1, "pushfile");
678 topfile = file;
680 yyparse();
681 errors = file->errors;
682 popfile();
684 if (errors)
685 errx(1, "can't load %s because of errors", path);