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 <fcntl.h>
31 #include <inttypes.h>
32 #include <libgen.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>
39 #include <unistd.h>
41 #include "log.h"
42 #include "kami.h"
43 #include "utils.h"
45 #include "script.h"
47 TAILQ_HEAD(files, file) files = TAILQ_HEAD_INITIALIZER(files);
48 static struct file {
49 TAILQ_ENTRY(file) entry;
50 FILE *stream;
51 char *name;
52 size_t ungetpos;
53 size_t ungetsize;
54 u_char *ungetbuf;
55 int eof_reached;
56 int lineno;
57 int errors;
58 } *file, *topfile;
59 struct file *pushfile(const char *);
60 int popfile(void);
61 int yyparse(void);
62 int yylex(void);
63 int yyerror(const char *, ...)
64 __attribute__((__format__ (printf, 1, 2)))
65 __attribute__((__nonnull__ (1)));
66 int kw_cmp(const void *, const void *);
67 int lookup(char *);
68 int igetc(void);
69 int lgetc(int);
70 void lungetc(int);
71 int findeol(void);
73 static int shouldfail;
75 typedef struct {
76 union {
77 struct op *op;
78 struct proc *proc;
79 char *str;
80 int64_t num;
81 } v;
82 int lineno;
83 } YYSTYPE;
85 %}
87 /*
88 * for bison:
89 * %define parse.error verbose
90 */
92 %token ASSERT
93 %token CONST
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 {
269 prepare_test();
270 } testopt '{' optnl block '}' {
271 test_done(shouldfail, $2);
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 {"include", INCLUDE},
317 {"proc", PROC},
318 {"repeat", REPEAT},
319 {"should-fail", SHOULD_FAIL},
320 {"str", STR},
321 {"testing", TESTING},
322 {"u16", U16},
323 {"u32", U32},
324 {"u8", U8},
325 {"vargs", VARGS},
326 };
327 const struct keywords *p;
329 p = bsearch(s, keywords, sizeof(keywords)/sizeof(keywords[0]),
330 sizeof(keywords[0]), kw_cmp);
332 if (p)
333 return p->k_val;
334 else
335 return SYMBOL;
338 #define START_EXPAND 1
339 #define DONE_EXPAND 2
341 static int expanding;
343 int
344 igetc(void)
346 int c;
348 while (1) {
349 if (file->ungetpos > 0)
350 c = file->ungetbuf[--file->ungetpos];
351 else
352 c = getc(file->stream);
354 if (c == START_EXPAND)
355 expanding = 1;
356 else if (c == DONE_EXPAND)
357 expanding = 0;
358 else
359 break;
361 return c;
364 int
365 lgetc(int quotec)
367 int c, next;
369 if (quotec) {
370 if ((c = igetc()) == EOF) {
371 yyerror("reached end of file while parsing "
372 "quoted string");
373 if (file == topfile || popfile() == EOF)
374 return EOF;
375 return quotec;
377 return c;
380 while ((c = igetc()) == '\\') {
381 next = igetc();
382 if (next != '\n') {
383 c = next;
384 break;
386 yylval.lineno = file->lineno;
387 file->lineno++;
390 if (c == EOF) {
391 /*
392 * Fake EOL when hit EOF for the first time. This gets line
393 * count right if last line in included file is syntactically
394 * invalid and has no newline.
395 */
396 if (file->eof_reached == 0) {
397 file->eof_reached = 1;
398 return '\n';
400 while (c == EOF) {
401 if (file == topfile || popfile() == EOF)
402 return EOF;
403 c = igetc();
406 return c;
409 void
410 lungetc(int c)
412 if (c == EOF)
413 return;
415 if (file->ungetpos >= file->ungetsize) {
416 void *p = reallocarray(file->ungetbuf, file->ungetsize, 2);
417 if (p == NULL)
418 err(1, "lungetc");
419 file->ungetbuf = p;
420 file->ungetsize *= 2;
422 file->ungetbuf[file->ungetpos++] = c;
425 int
426 findeol(void)
428 int c;
430 /* Skip to either EOF or the first real EOL. */
431 while (1) {
432 c = lgetc(0);
433 if (c == '\n') {
434 file->lineno++;
435 break;
437 if (c == EOF)
438 break;
440 return ERROR;
444 #if 0
445 int my_yylex(void);
447 int
448 yylex(void)
450 int x;
452 switch (x = my_yylex()) {
453 case ASSERT: puts("assert"); break;
454 case CONST: puts("const"); 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 pwdfd, errors;
674 char p[PATH_MAX], *dir;
676 /*
677 * Ugly workaround: we really need a smarter `include', one that
678 * is able to resolve path relatively from the currently processed
679 * file. The workaround consist to save the current directory,
680 * chdir(2) to the script dirname and then jump back by mean of
681 * fchdir.
682 */
684 if ((pwdfd = open(".", O_RDONLY|O_DIRECTORY)) == -1)
685 err(1, "can't open .");
686 strlcpy(p, path, sizeof(p));
687 dir = dirname(p);
688 if (chdir(dir) == -1)
689 err(1, "chdir %s", dir);
691 /* XXX: include the *basename* of the file after chdir */
692 strlcpy(p, path, sizeof(p));
693 file = pushfile(basename(p));
694 if (file == NULL)
695 err(1, "pushfile");
696 topfile = file;
698 yyparse();
699 errors = file->errors;
700 popfile();
702 fchdir(pwdfd);
703 close(pwdfd);
705 if (errors)
706 errx(1, "can't load %s because of errors", path);