xref: /aosp_15_r20/external/coreboot/util/bincfg/bincfg.l (revision b9411a12aaaa7e1e6a6fb7c5e057f44ee179a49c)
1 /* bincfg - Compiler/Decompiler for data blobs with specs */
2 /* SPDX-License-Identifier: GPL-3.0-or-later */
3 
4 %{
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include "bincfg.tab.h"
9 
10 extern struct blob binary;
11 
parsehex(char * s)12 unsigned int parsehex (char *s)
13 {
14 	unsigned int i, nib, retval = 0;
15 	unsigned int nibs = strlen(s) - 2;
16 
17 	for (i = 2; i < nibs + 2; i++) {
18 		if (s[i] >= '0' && s[i] <= '9') {
19 			nib = s[i] - '0';
20 		} else if (s[i] >= 'a' && s[i] <= 'f') {
21 			nib = s[i] - 'a' + 10;
22 		} else if (s[i] >= 'A' && s[i] <= 'F') {
23 			nib = s[i] - 'A' + 10;
24 		} else {
25 			return 0;
26 		}
27 		retval |= nib << (((nibs - 1) - (i - 2)) * 4);
28 	}
29 	return retval;
30 }
31 
stripquotes(char * string)32 char* stripquotes (char *string)
33 {
34 	char *stripped;
35 	unsigned int len = strlen(string);
36 	if (len >= 2 && string[0] == '"' && string[len - 1] == '"') {
37 		stripped = (char *) malloc (len - 1);
38 		if (stripped == NULL) {
39 			printf("Out of memory\n");
40 			exit(1);
41 		}
42 		snprintf (stripped, len - 1, "%s", string + 1);
43 		return stripped;
44 	}
45 	return NULL;
46 }
47 
48 %}
49 
50 %option noyywrap
51 %option nounput
52 
53 DIGIT [0-9]
54 INT [-]?{DIGIT}|[-]?[1-9]{DIGIT}+
55 FRAC [.]{DIGIT}+
56 EXP [eE][+-]?{DIGIT}+
57 NUMBER {INT}|{INT}{FRAC}|{INT}{EXP}|{INT}{FRAC}{EXP}
58 HEX [0][x][0-9a-fA-F]+
59 STRING ["][^"]*["]
60 COMMENT [#][^\n]*$
61 
62 %%
63 
64 {STRING} {
65     yylval.str = stripquotes(yytext);
66     return name;
67 };
68 
69 {NUMBER} {
70     yylval.u32 = atoi(yytext);
71     return val;
72 };
73 
74 {HEX} {
75     yylval.u32 = parsehex(yytext);
76     return val;
77 };
78 
79 \{ {
80     return '{';
81 };
82 
83 \} {
84     return '}';
85 };
86 
87 \[ {
88     return '[';
89 };
90 
91 \] {
92     return ']';
93 };
94 
95 , {
96     return ',';
97 };
98 
99 : {
100     return ':';
101 };
102 
103 = {
104     return '=';
105 };
106 
107 [ \t\n]+ /* ignore whitespace */;
108 
109 {COMMENT} /* ignore comments */
110 
111 \% {
112     return '%';
113 };
114 
115 <<EOF>> { return eof; };
116 
117 %%
118 
119 void set_input_string(char* in) {
120 	yy_scan_string(in);
121 }
122