xref: /linux-6.15/scripts/kconfig/preprocess.c (revision 1175c025)
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  * Variables (and user-defined functions)
182  */
183 static LIST_HEAD(variable_list);
184 
185 struct variable {
186 	char *name;
187 	char *value;
188 	enum variable_flavor flavor;
189 	struct list_head node;
190 };
191 
192 static struct variable *variable_lookup(const char *name)
193 {
194 	struct variable *v;
195 
196 	list_for_each_entry(v, &variable_list, node) {
197 		if (!strcmp(name, v->name))
198 			return v;
199 	}
200 
201 	return NULL;
202 }
203 
204 static char *variable_expand(const char *name, int argc, char *argv[])
205 {
206 	struct variable *v;
207 	char *res;
208 
209 	v = variable_lookup(name);
210 	if (!v)
211 		return NULL;
212 
213 	if (v->flavor == VAR_RECURSIVE)
214 		res = expand_string_with_args(v->value, argc, argv);
215 	else
216 		res = xstrdup(v->value);
217 
218 	return res;
219 }
220 
221 void variable_add(const char *name, const char *value,
222 		  enum variable_flavor flavor)
223 {
224 	struct variable *v;
225 
226 	v = variable_lookup(name);
227 	if (v) {
228 		free(v->value);
229 	} else {
230 		v = xmalloc(sizeof(*v));
231 		v->name = xstrdup(name);
232 		list_add_tail(&v->node, &variable_list);
233 	}
234 
235 	v->flavor = flavor;
236 
237 	if (flavor == VAR_SIMPLE)
238 		v->value = expand_string(value);
239 	else
240 		v->value = xstrdup(value);
241 }
242 
243 static void variable_del(struct variable *v)
244 {
245 	list_del(&v->node);
246 	free(v->name);
247 	free(v->value);
248 	free(v);
249 }
250 
251 void variable_all_del(void)
252 {
253 	struct variable *v, *tmp;
254 
255 	list_for_each_entry_safe(v, tmp, &variable_list, node)
256 		variable_del(v);
257 }
258 
259 /*
260  * Evaluate a clause with arguments.  argc/argv are arguments from the upper
261  * function call.
262  *
263  * Returned string must be freed when done
264  */
265 static char *eval_clause(const char *str, size_t len, int argc, char *argv[])
266 {
267 	char *tmp, *name, *res, *endptr, *prev, *p;
268 	int new_argc = 0;
269 	char *new_argv[FUNCTION_MAX_ARGS];
270 	int nest = 0;
271 	int i;
272 	unsigned long n;
273 
274 	tmp = xstrndup(str, len);
275 
276 	/*
277 	 * If variable name is '1', '2', etc.  It is generally an argument
278 	 * from a user-function call (i.e. local-scope variable).  If not
279 	 * available, then look-up global-scope variables.
280 	 */
281 	n = strtoul(tmp, &endptr, 10);
282 	if (!*endptr && n > 0 && n <= argc) {
283 		res = xstrdup(argv[n - 1]);
284 		goto free_tmp;
285 	}
286 
287 	prev = p = tmp;
288 
289 	/*
290 	 * Split into tokens
291 	 * The function name and arguments are separated by a comma.
292 	 * For example, if the function call is like this:
293 	 *   $(foo,$(x),$(y))
294 	 *
295 	 * The input string for this helper should be:
296 	 *   foo,$(x),$(y)
297 	 *
298 	 * and split into:
299 	 *   new_argv[0] = 'foo'
300 	 *   new_argv[1] = '$(x)'
301 	 *   new_argv[2] = '$(y)'
302 	 */
303 	while (*p) {
304 		if (nest == 0 && *p == ',') {
305 			*p = 0;
306 			if (new_argc >= FUNCTION_MAX_ARGS)
307 				pperror("too many function arguments");
308 			new_argv[new_argc++] = prev;
309 			prev = p + 1;
310 		} else if (*p == '(') {
311 			nest++;
312 		} else if (*p == ')') {
313 			nest--;
314 		}
315 
316 		p++;
317 	}
318 	new_argv[new_argc++] = prev;
319 
320 	/*
321 	 * Shift arguments
322 	 * new_argv[0] represents a function name or a variable name.  Put it
323 	 * into 'name', then shift the rest of the arguments.  This simplifies
324 	 * 'const' handling.
325 	 */
326 	name = expand_string_with_args(new_argv[0], argc, argv);
327 	new_argc--;
328 	for (i = 0; i < new_argc; i++)
329 		new_argv[i] = expand_string_with_args(new_argv[i + 1],
330 						      argc, argv);
331 
332 	/* Search for variables */
333 	res = variable_expand(name, new_argc, new_argv);
334 	if (res)
335 		goto free;
336 
337 	/* Look for built-in functions */
338 	res = function_expand(name, new_argc, new_argv);
339 	if (res)
340 		goto free;
341 
342 	/* Last, try environment variable */
343 	if (new_argc == 0) {
344 		res = env_expand(name);
345 		if (res)
346 			goto free;
347 	}
348 
349 	res = xstrdup("");
350 free:
351 	for (i = 0; i < new_argc; i++)
352 		free(new_argv[i]);
353 	free(name);
354 free_tmp:
355 	free(tmp);
356 
357 	return res;
358 }
359 
360 /*
361  * Expand a string that follows '$'
362  *
363  * For example, if the input string is
364  *     ($(FOO)$($(BAR)))$(BAZ)
365  * this helper evaluates
366  *     $($(FOO)$($(BAR)))
367  * and returns a new string containing the expansion (note that the string is
368  * recursively expanded), also advancing 'str' to point to the next character
369  * after the corresponding closing parenthesis, in this case, *str will be
370  *     $(BAR)
371  */
372 static char *expand_dollar_with_args(const char **str, int argc, char *argv[])
373 {
374 	const char *p = *str;
375 	const char *q;
376 	int nest = 0;
377 
378 	/*
379 	 * In Kconfig, variable/function references always start with "$(".
380 	 * Neither single-letter variables as in $A nor curly braces as in ${CC}
381 	 * are supported.  '$' not followed by '(' loses its special meaning.
382 	 */
383 	if (*p != '(') {
384 		*str = p;
385 		return xstrdup("$");
386 	}
387 
388 	p++;
389 	q = p;
390 	while (*q) {
391 		if (*q == '(') {
392 			nest++;
393 		} else if (*q == ')') {
394 			if (nest-- == 0)
395 				break;
396 		}
397 		q++;
398 	}
399 
400 	if (!*q)
401 		pperror("unterminated reference to '%s': missing ')'", p);
402 
403 	/* Advance 'str' to after the expanded initial portion of the string */
404 	*str = q + 1;
405 
406 	return eval_clause(p, q - p, argc, argv);
407 }
408 
409 char *expand_dollar(const char **str)
410 {
411 	return expand_dollar_with_args(str, 0, NULL);
412 }
413 
414 static char *__expand_string(const char **str, bool (*is_end)(char c),
415 			     int argc, char *argv[])
416 {
417 	const char *in, *p;
418 	char *expansion, *out;
419 	size_t in_len, out_len;
420 
421 	out = xmalloc(1);
422 	*out = 0;
423 	out_len = 1;
424 
425 	p = in = *str;
426 
427 	while (1) {
428 		if (*p == '$') {
429 			in_len = p - in;
430 			p++;
431 			expansion = expand_dollar_with_args(&p, argc, argv);
432 			out_len += in_len + strlen(expansion);
433 			out = xrealloc(out, out_len);
434 			strncat(out, in, in_len);
435 			strcat(out, expansion);
436 			free(expansion);
437 			in = p;
438 			continue;
439 		}
440 
441 		if (is_end(*p))
442 			break;
443 
444 		p++;
445 	}
446 
447 	in_len = p - in;
448 	out_len += in_len;
449 	out = xrealloc(out, out_len);
450 	strncat(out, in, in_len);
451 
452 	/* Advance 'str' to the end character */
453 	*str = p;
454 
455 	return out;
456 }
457 
458 static bool is_end_of_str(char c)
459 {
460 	return !c;
461 }
462 
463 /*
464  * Expand variables and functions in the given string.  Undefined variables
465  * expand to an empty string.
466  * The returned string must be freed when done.
467  */
468 static char *expand_string_with_args(const char *in, int argc, char *argv[])
469 {
470 	return __expand_string(&in, is_end_of_str, argc, argv);
471 }
472 
473 char *expand_string(const char *in)
474 {
475 	return expand_string_with_args(in, 0, NULL);
476 }
477 
478 static bool is_end_of_token(char c)
479 {
480 	/* Why are '.' and '/' valid characters for symbols? */
481 	return !(isalnum(c) || c == '_' || c == '-' || c == '.' || c == '/');
482 }
483 
484 /*
485  * Expand variables in a token.  The parsing stops when a token separater
486  * (in most cases, it is a whitespace) is encountered.  'str' is updated to
487  * point to the next character.
488  *
489  * The returned string must be freed when done.
490  */
491 char *expand_one_token(const char **str)
492 {
493 	return __expand_string(str, is_end_of_token, 0, NULL);
494 }
495