xref: /linux-6.15/scripts/kconfig/preprocess.c (revision 2fd5b09c)
1 // SPDX-License-Identifier: GPL-2.0
2 //
3 // Copyright (C) 2018 Masahiro Yamada <[email protected]>
4 
5 #include <stdarg.h>
6 #include <stdbool.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 
11 #include "list.h"
12 
13 #define ARRAY_SIZE(arr)		(sizeof(arr) / sizeof((arr)[0]))
14 
15 static char *expand_string_with_args(const char *in, int argc, char *argv[]);
16 
17 static void __attribute__((noreturn)) pperror(const char *format, ...)
18 {
19 	va_list ap;
20 
21 	fprintf(stderr, "%s:%d: ", current_file->name, yylineno);
22 	va_start(ap, format);
23 	vfprintf(stderr, format, ap);
24 	va_end(ap);
25 	fprintf(stderr, "\n");
26 
27 	exit(1);
28 }
29 
30 /*
31  * Environment variables
32  */
33 static LIST_HEAD(env_list);
34 
35 struct env {
36 	char *name;
37 	char *value;
38 	struct list_head node;
39 };
40 
41 static void env_add(const char *name, const char *value)
42 {
43 	struct env *e;
44 
45 	e = xmalloc(sizeof(*e));
46 	e->name = xstrdup(name);
47 	e->value = xstrdup(value);
48 
49 	list_add_tail(&e->node, &env_list);
50 }
51 
52 static void env_del(struct env *e)
53 {
54 	list_del(&e->node);
55 	free(e->name);
56 	free(e->value);
57 	free(e);
58 }
59 
60 /* The returned pointer must be freed when done */
61 static char *env_expand(const char *name)
62 {
63 	struct env *e;
64 	const char *value;
65 
66 	if (!*name)
67 		return NULL;
68 
69 	list_for_each_entry(e, &env_list, node) {
70 		if (!strcmp(name, e->name))
71 			return xstrdup(e->value);
72 	}
73 
74 	value = getenv(name);
75 	if (!value)
76 		return NULL;
77 
78 	/*
79 	 * We need to remember all referenced environment variables.
80 	 * They will be written out to include/config/auto.conf.cmd
81 	 */
82 	env_add(name, value);
83 
84 	return xstrdup(value);
85 }
86 
87 void env_write_dep(FILE *f, const char *autoconfig_name)
88 {
89 	struct env *e, *tmp;
90 
91 	list_for_each_entry_safe(e, tmp, &env_list, node) {
92 		fprintf(f, "ifneq \"$(%s)\" \"%s\"\n", e->name, e->value);
93 		fprintf(f, "%s: FORCE\n", autoconfig_name);
94 		fprintf(f, "endif\n");
95 		env_del(e);
96 	}
97 }
98 
99 /*
100  * Built-in functions
101  */
102 struct function {
103 	const char *name;
104 	unsigned int min_args;
105 	unsigned int max_args;
106 	char *(*func)(int argc, char *argv[]);
107 };
108 
109 static char *do_shell(int argc, char *argv[])
110 {
111 	FILE *p;
112 	char buf[256];
113 	char *cmd;
114 	size_t nread;
115 	int i;
116 
117 	cmd = argv[0];
118 
119 	p = popen(cmd, "r");
120 	if (!p) {
121 		perror(cmd);
122 		exit(1);
123 	}
124 
125 	nread = fread(buf, 1, sizeof(buf), p);
126 	if (nread == sizeof(buf))
127 		nread--;
128 
129 	/* remove trailing new lines */
130 	while (buf[nread - 1] == '\n')
131 		nread--;
132 
133 	buf[nread] = 0;
134 
135 	/* replace a new line with a space */
136 	for (i = 0; i < nread; i++) {
137 		if (buf[i] == '\n')
138 			buf[i] = ' ';
139 	}
140 
141 	if (pclose(p) == -1) {
142 		perror(cmd);
143 		exit(1);
144 	}
145 
146 	return xstrdup(buf);
147 }
148 
149 static const struct function function_table[] = {
150 	/* Name		MIN	MAX	Function */
151 	{ "shell",	1,	1,	do_shell },
152 };
153 
154 #define FUNCTION_MAX_ARGS		16
155 
156 static char *function_expand(const char *name, int argc, char *argv[])
157 {
158 	const struct function *f;
159 	int i;
160 
161 	for (i = 0; i < ARRAY_SIZE(function_table); i++) {
162 		f = &function_table[i];
163 		if (strcmp(f->name, name))
164 			continue;
165 
166 		if (argc < f->min_args)
167 			pperror("too few function arguments passed to '%s'",
168 				name);
169 
170 		if (argc > f->max_args)
171 			pperror("too many function arguments passed to '%s'",
172 				name);
173 
174 		return f->func(argc, argv);
175 	}
176 
177 	return NULL;
178 }
179 
180 /*
181  * Evaluate a clause with arguments.  argc/argv are arguments from the upper
182  * function call.
183  *
184  * Returned string must be freed when done
185  */
186 static char *eval_clause(const char *str, size_t len, int argc, char *argv[])
187 {
188 	char *tmp, *name, *res, *prev, *p;
189 	int new_argc = 0;
190 	char *new_argv[FUNCTION_MAX_ARGS];
191 	int nest = 0;
192 	int i;
193 
194 	tmp = xstrndup(str, len);
195 
196 	prev = p = tmp;
197 
198 	/*
199 	 * Split into tokens
200 	 * The function name and arguments are separated by a comma.
201 	 * For example, if the function call is like this:
202 	 *   $(foo,$(x),$(y))
203 	 *
204 	 * The input string for this helper should be:
205 	 *   foo,$(x),$(y)
206 	 *
207 	 * and split into:
208 	 *   new_argv[0] = 'foo'
209 	 *   new_argv[1] = '$(x)'
210 	 *   new_argv[2] = '$(y)'
211 	 */
212 	while (*p) {
213 		if (nest == 0 && *p == ',') {
214 			*p = 0;
215 			if (new_argc >= FUNCTION_MAX_ARGS)
216 				pperror("too many function arguments");
217 			new_argv[new_argc++] = prev;
218 			prev = p + 1;
219 		} else if (*p == '(') {
220 			nest++;
221 		} else if (*p == ')') {
222 			nest--;
223 		}
224 
225 		p++;
226 	}
227 	new_argv[new_argc++] = prev;
228 
229 	/*
230 	 * Shift arguments
231 	 * new_argv[0] represents a function name or a variable name.  Put it
232 	 * into 'name', then shift the rest of the arguments.  This simplifies
233 	 * 'const' handling.
234 	 */
235 	name = expand_string_with_args(new_argv[0], argc, argv);
236 	new_argc--;
237 	for (i = 0; i < new_argc; i++)
238 		new_argv[i] = expand_string_with_args(new_argv[i + 1],
239 						      argc, argv);
240 
241 	/* Look for built-in functions */
242 	res = function_expand(name, new_argc, new_argv);
243 	if (res)
244 		goto free;
245 
246 	/* Last, try environment variable */
247 	if (new_argc == 0) {
248 		res = env_expand(name);
249 		if (res)
250 			goto free;
251 	}
252 
253 	res = xstrdup("");
254 free:
255 	for (i = 0; i < new_argc; i++)
256 		free(new_argv[i]);
257 	free(name);
258 	free(tmp);
259 
260 	return res;
261 }
262 
263 /*
264  * Expand a string that follows '$'
265  *
266  * For example, if the input string is
267  *     ($(FOO)$($(BAR)))$(BAZ)
268  * this helper evaluates
269  *     $($(FOO)$($(BAR)))
270  * and returns a new string containing the expansion (note that the string is
271  * recursively expanded), also advancing 'str' to point to the next character
272  * after the corresponding closing parenthesis, in this case, *str will be
273  *     $(BAR)
274  */
275 static char *expand_dollar_with_args(const char **str, int argc, char *argv[])
276 {
277 	const char *p = *str;
278 	const char *q;
279 	int nest = 0;
280 
281 	/*
282 	 * In Kconfig, variable/function references always start with "$(".
283 	 * Neither single-letter variables as in $A nor curly braces as in ${CC}
284 	 * are supported.  '$' not followed by '(' loses its special meaning.
285 	 */
286 	if (*p != '(') {
287 		*str = p;
288 		return xstrdup("$");
289 	}
290 
291 	p++;
292 	q = p;
293 	while (*q) {
294 		if (*q == '(') {
295 			nest++;
296 		} else if (*q == ')') {
297 			if (nest-- == 0)
298 				break;
299 		}
300 		q++;
301 	}
302 
303 	if (!*q)
304 		pperror("unterminated reference to '%s': missing ')'", p);
305 
306 	/* Advance 'str' to after the expanded initial portion of the string */
307 	*str = q + 1;
308 
309 	return eval_clause(p, q - p, argc, argv);
310 }
311 
312 char *expand_dollar(const char **str)
313 {
314 	return expand_dollar_with_args(str, 0, NULL);
315 }
316 
317 static char *__expand_string(const char **str, bool (*is_end)(char c),
318 			     int argc, char *argv[])
319 {
320 	const char *in, *p;
321 	char *expansion, *out;
322 	size_t in_len, out_len;
323 
324 	out = xmalloc(1);
325 	*out = 0;
326 	out_len = 1;
327 
328 	p = in = *str;
329 
330 	while (1) {
331 		if (*p == '$') {
332 			in_len = p - in;
333 			p++;
334 			expansion = expand_dollar_with_args(&p, argc, argv);
335 			out_len += in_len + strlen(expansion);
336 			out = xrealloc(out, out_len);
337 			strncat(out, in, in_len);
338 			strcat(out, expansion);
339 			free(expansion);
340 			in = p;
341 			continue;
342 		}
343 
344 		if (is_end(*p))
345 			break;
346 
347 		p++;
348 	}
349 
350 	in_len = p - in;
351 	out_len += in_len;
352 	out = xrealloc(out, out_len);
353 	strncat(out, in, in_len);
354 
355 	/* Advance 'str' to the end character */
356 	*str = p;
357 
358 	return out;
359 }
360 
361 static bool is_end_of_str(char c)
362 {
363 	return !c;
364 }
365 
366 /*
367  * Expand variables and functions in the given string.  Undefined variables
368  * expand to an empty string.
369  * The returned string must be freed when done.
370  */
371 static char *expand_string_with_args(const char *in, int argc, char *argv[])
372 {
373 	return __expand_string(&in, is_end_of_str, argc, argv);
374 }
375 
376 char *expand_string(const char *in)
377 {
378 	return expand_string_with_args(in, 0, NULL);
379 }
380 
381 static bool is_end_of_token(char c)
382 {
383 	/* Why are '.' and '/' valid characters for symbols? */
384 	return !(isalnum(c) || c == '_' || c == '-' || c == '.' || c == '/');
385 }
386 
387 /*
388  * Expand variables in a token.  The parsing stops when a token separater
389  * (in most cases, it is a whitespace) is encountered.  'str' is updated to
390  * point to the next character.
391  *
392  * The returned string must be freed when done.
393  */
394 char *expand_one_token(const char **str)
395 {
396 	return __expand_string(str, is_end_of_token, 0, NULL);
397 }
398