xref: /linux-6.15/scripts/kconfig/preprocess.c (revision a702a617)
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_error_if(int argc, char *argv[])
110 {
111 	if (!strcmp(argv[0], "y"))
112 		pperror("%s", argv[1]);
113 
114 	return NULL;
115 }
116 
117 static char *do_filename(int argc, char *argv[])
118 {
119 	return xstrdup(current_file->name);
120 }
121 
122 static char *do_info(int argc, char *argv[])
123 {
124 	printf("%s\n", argv[0]);
125 
126 	return xstrdup("");
127 }
128 
129 static char *do_lineno(int argc, char *argv[])
130 {
131 	char buf[16];
132 
133 	sprintf(buf, "%d", yylineno);
134 
135 	return xstrdup(buf);
136 }
137 
138 static char *do_shell(int argc, char *argv[])
139 {
140 	FILE *p;
141 	char buf[256];
142 	char *cmd;
143 	size_t nread;
144 	int i;
145 
146 	cmd = argv[0];
147 
148 	p = popen(cmd, "r");
149 	if (!p) {
150 		perror(cmd);
151 		exit(1);
152 	}
153 
154 	nread = fread(buf, 1, sizeof(buf), p);
155 	if (nread == sizeof(buf))
156 		nread--;
157 
158 	/* remove trailing new lines */
159 	while (buf[nread - 1] == '\n')
160 		nread--;
161 
162 	buf[nread] = 0;
163 
164 	/* replace a new line with a space */
165 	for (i = 0; i < nread; i++) {
166 		if (buf[i] == '\n')
167 			buf[i] = ' ';
168 	}
169 
170 	if (pclose(p) == -1) {
171 		perror(cmd);
172 		exit(1);
173 	}
174 
175 	return xstrdup(buf);
176 }
177 
178 static char *do_warning_if(int argc, char *argv[])
179 {
180 	if (!strcmp(argv[0], "y"))
181 		fprintf(stderr, "%s:%d: %s\n",
182 			current_file->name, yylineno, argv[1]);
183 
184 	return xstrdup("");
185 }
186 
187 static const struct function function_table[] = {
188 	/* Name		MIN	MAX	Function */
189 	{ "error-if",	2,	2,	do_error_if },
190 	{ "filename",	0,	0,	do_filename },
191 	{ "info",	1,	1,	do_info },
192 	{ "lineno",	0,	0,	do_lineno },
193 	{ "shell",	1,	1,	do_shell },
194 	{ "warning-if",	2,	2,	do_warning_if },
195 };
196 
197 #define FUNCTION_MAX_ARGS		16
198 
199 static char *function_expand(const char *name, int argc, char *argv[])
200 {
201 	const struct function *f;
202 	int i;
203 
204 	for (i = 0; i < ARRAY_SIZE(function_table); i++) {
205 		f = &function_table[i];
206 		if (strcmp(f->name, name))
207 			continue;
208 
209 		if (argc < f->min_args)
210 			pperror("too few function arguments passed to '%s'",
211 				name);
212 
213 		if (argc > f->max_args)
214 			pperror("too many function arguments passed to '%s'",
215 				name);
216 
217 		return f->func(argc, argv);
218 	}
219 
220 	return NULL;
221 }
222 
223 /*
224  * Variables (and user-defined functions)
225  */
226 static LIST_HEAD(variable_list);
227 
228 struct variable {
229 	char *name;
230 	char *value;
231 	enum variable_flavor flavor;
232 	struct list_head node;
233 };
234 
235 static struct variable *variable_lookup(const char *name)
236 {
237 	struct variable *v;
238 
239 	list_for_each_entry(v, &variable_list, node) {
240 		if (!strcmp(name, v->name))
241 			return v;
242 	}
243 
244 	return NULL;
245 }
246 
247 static char *variable_expand(const char *name, int argc, char *argv[])
248 {
249 	struct variable *v;
250 	char *res;
251 
252 	v = variable_lookup(name);
253 	if (!v)
254 		return NULL;
255 
256 	if (v->flavor == VAR_RECURSIVE)
257 		res = expand_string_with_args(v->value, argc, argv);
258 	else
259 		res = xstrdup(v->value);
260 
261 	return res;
262 }
263 
264 void variable_add(const char *name, const char *value,
265 		  enum variable_flavor flavor)
266 {
267 	struct variable *v;
268 	char *new_value;
269 	bool append = false;
270 
271 	v = variable_lookup(name);
272 	if (v) {
273 		/* For defined variables, += inherits the existing flavor */
274 		if (flavor == VAR_APPEND) {
275 			flavor = v->flavor;
276 			append = true;
277 		} else {
278 			free(v->value);
279 		}
280 	} else {
281 		/* For undefined variables, += assumes the recursive flavor */
282 		if (flavor == VAR_APPEND)
283 			flavor = VAR_RECURSIVE;
284 
285 		v = xmalloc(sizeof(*v));
286 		v->name = xstrdup(name);
287 		list_add_tail(&v->node, &variable_list);
288 	}
289 
290 	v->flavor = flavor;
291 
292 	if (flavor == VAR_SIMPLE)
293 		new_value = expand_string(value);
294 	else
295 		new_value = xstrdup(value);
296 
297 	if (append) {
298 		v->value = xrealloc(v->value,
299 				    strlen(v->value) + strlen(new_value) + 2);
300 		strcat(v->value, " ");
301 		strcat(v->value, new_value);
302 		free(new_value);
303 	} else {
304 		v->value = new_value;
305 	}
306 }
307 
308 static void variable_del(struct variable *v)
309 {
310 	list_del(&v->node);
311 	free(v->name);
312 	free(v->value);
313 	free(v);
314 }
315 
316 void variable_all_del(void)
317 {
318 	struct variable *v, *tmp;
319 
320 	list_for_each_entry_safe(v, tmp, &variable_list, node)
321 		variable_del(v);
322 }
323 
324 /*
325  * Evaluate a clause with arguments.  argc/argv are arguments from the upper
326  * function call.
327  *
328  * Returned string must be freed when done
329  */
330 static char *eval_clause(const char *str, size_t len, int argc, char *argv[])
331 {
332 	char *tmp, *name, *res, *endptr, *prev, *p;
333 	int new_argc = 0;
334 	char *new_argv[FUNCTION_MAX_ARGS];
335 	int nest = 0;
336 	int i;
337 	unsigned long n;
338 
339 	tmp = xstrndup(str, len);
340 
341 	/*
342 	 * If variable name is '1', '2', etc.  It is generally an argument
343 	 * from a user-function call (i.e. local-scope variable).  If not
344 	 * available, then look-up global-scope variables.
345 	 */
346 	n = strtoul(tmp, &endptr, 10);
347 	if (!*endptr && n > 0 && n <= argc) {
348 		res = xstrdup(argv[n - 1]);
349 		goto free_tmp;
350 	}
351 
352 	prev = p = tmp;
353 
354 	/*
355 	 * Split into tokens
356 	 * The function name and arguments are separated by a comma.
357 	 * For example, if the function call is like this:
358 	 *   $(foo,$(x),$(y))
359 	 *
360 	 * The input string for this helper should be:
361 	 *   foo,$(x),$(y)
362 	 *
363 	 * and split into:
364 	 *   new_argv[0] = 'foo'
365 	 *   new_argv[1] = '$(x)'
366 	 *   new_argv[2] = '$(y)'
367 	 */
368 	while (*p) {
369 		if (nest == 0 && *p == ',') {
370 			*p = 0;
371 			if (new_argc >= FUNCTION_MAX_ARGS)
372 				pperror("too many function arguments");
373 			new_argv[new_argc++] = prev;
374 			prev = p + 1;
375 		} else if (*p == '(') {
376 			nest++;
377 		} else if (*p == ')') {
378 			nest--;
379 		}
380 
381 		p++;
382 	}
383 	new_argv[new_argc++] = prev;
384 
385 	/*
386 	 * Shift arguments
387 	 * new_argv[0] represents a function name or a variable name.  Put it
388 	 * into 'name', then shift the rest of the arguments.  This simplifies
389 	 * 'const' handling.
390 	 */
391 	name = expand_string_with_args(new_argv[0], argc, argv);
392 	new_argc--;
393 	for (i = 0; i < new_argc; i++)
394 		new_argv[i] = expand_string_with_args(new_argv[i + 1],
395 						      argc, argv);
396 
397 	/* Search for variables */
398 	res = variable_expand(name, new_argc, new_argv);
399 	if (res)
400 		goto free;
401 
402 	/* Look for built-in functions */
403 	res = function_expand(name, new_argc, new_argv);
404 	if (res)
405 		goto free;
406 
407 	/* Last, try environment variable */
408 	if (new_argc == 0) {
409 		res = env_expand(name);
410 		if (res)
411 			goto free;
412 	}
413 
414 	res = xstrdup("");
415 free:
416 	for (i = 0; i < new_argc; i++)
417 		free(new_argv[i]);
418 	free(name);
419 free_tmp:
420 	free(tmp);
421 
422 	return res;
423 }
424 
425 /*
426  * Expand a string that follows '$'
427  *
428  * For example, if the input string is
429  *     ($(FOO)$($(BAR)))$(BAZ)
430  * this helper evaluates
431  *     $($(FOO)$($(BAR)))
432  * and returns a new string containing the expansion (note that the string is
433  * recursively expanded), also advancing 'str' to point to the next character
434  * after the corresponding closing parenthesis, in this case, *str will be
435  *     $(BAR)
436  */
437 static char *expand_dollar_with_args(const char **str, int argc, char *argv[])
438 {
439 	const char *p = *str;
440 	const char *q;
441 	int nest = 0;
442 
443 	/*
444 	 * In Kconfig, variable/function references always start with "$(".
445 	 * Neither single-letter variables as in $A nor curly braces as in ${CC}
446 	 * are supported.  '$' not followed by '(' loses its special meaning.
447 	 */
448 	if (*p != '(') {
449 		*str = p;
450 		return xstrdup("$");
451 	}
452 
453 	p++;
454 	q = p;
455 	while (*q) {
456 		if (*q == '(') {
457 			nest++;
458 		} else if (*q == ')') {
459 			if (nest-- == 0)
460 				break;
461 		}
462 		q++;
463 	}
464 
465 	if (!*q)
466 		pperror("unterminated reference to '%s': missing ')'", p);
467 
468 	/* Advance 'str' to after the expanded initial portion of the string */
469 	*str = q + 1;
470 
471 	return eval_clause(p, q - p, argc, argv);
472 }
473 
474 char *expand_dollar(const char **str)
475 {
476 	return expand_dollar_with_args(str, 0, NULL);
477 }
478 
479 static char *__expand_string(const char **str, bool (*is_end)(char c),
480 			     int argc, char *argv[])
481 {
482 	const char *in, *p;
483 	char *expansion, *out;
484 	size_t in_len, out_len;
485 
486 	out = xmalloc(1);
487 	*out = 0;
488 	out_len = 1;
489 
490 	p = in = *str;
491 
492 	while (1) {
493 		if (*p == '$') {
494 			in_len = p - in;
495 			p++;
496 			expansion = expand_dollar_with_args(&p, argc, argv);
497 			out_len += in_len + strlen(expansion);
498 			out = xrealloc(out, out_len);
499 			strncat(out, in, in_len);
500 			strcat(out, expansion);
501 			free(expansion);
502 			in = p;
503 			continue;
504 		}
505 
506 		if (is_end(*p))
507 			break;
508 
509 		p++;
510 	}
511 
512 	in_len = p - in;
513 	out_len += in_len;
514 	out = xrealloc(out, out_len);
515 	strncat(out, in, in_len);
516 
517 	/* Advance 'str' to the end character */
518 	*str = p;
519 
520 	return out;
521 }
522 
523 static bool is_end_of_str(char c)
524 {
525 	return !c;
526 }
527 
528 /*
529  * Expand variables and functions in the given string.  Undefined variables
530  * expand to an empty string.
531  * The returned string must be freed when done.
532  */
533 static char *expand_string_with_args(const char *in, int argc, char *argv[])
534 {
535 	return __expand_string(&in, is_end_of_str, argc, argv);
536 }
537 
538 char *expand_string(const char *in)
539 {
540 	return expand_string_with_args(in, 0, NULL);
541 }
542 
543 static bool is_end_of_token(char c)
544 {
545 	/* Why are '.' and '/' valid characters for symbols? */
546 	return !(isalnum(c) || c == '_' || c == '-' || c == '.' || c == '/');
547 }
548 
549 /*
550  * Expand variables in a token.  The parsing stops when a token separater
551  * (in most cases, it is a whitespace) is encountered.  'str' is updated to
552  * point to the next character.
553  *
554  * The returned string must be freed when done.
555  */
556 char *expand_one_token(const char **str)
557 {
558 	return __expand_string(str, is_end_of_token, 0, NULL);
559 }
560