xref: /aosp_15_r20/external/coreboot/util/kconfig/confdata.c (revision b9411a12aaaa7e1e6a6fb7c5e057f44ee179a49c)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2002 Roman Zippel <[email protected]>
4  */
5 
6 #include <sys/mman.h>
7 #include <sys/stat.h>
8 #include <sys/types.h>
9 #include <ctype.h>
10 #include <errno.h>
11 #include <fcntl.h>
12 #include <limits.h>
13 #include <stdarg.h>
14 #include <stdbool.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <time.h>
19 #include <unistd.h>
20 
21 #include "lkc.h"
22 
23 /* return true if 'path' exists, false otherwise */
is_present(const char * path)24 static bool is_present(const char *path)
25 {
26 	struct stat st;
27 
28 	return !stat(path, &st);
29 }
30 
31 /* return true if 'path' exists and it is a directory, false otherwise */
is_dir(const char * path)32 static bool is_dir(const char *path)
33 {
34 	struct stat st;
35 
36 	if (stat(path, &st))
37 		return false;
38 
39 	return S_ISDIR(st.st_mode);
40 }
41 
42 /* return true if the given two files are the same, false otherwise */
is_same(const char * file1,const char * file2)43 static bool is_same(const char *file1, const char *file2)
44 {
45 	int fd1, fd2;
46 	struct stat st1, st2;
47 	void *map1, *map2;
48 	bool ret = false;
49 
50 	fd1 = open(file1, O_RDONLY);
51 	if (fd1 < 0)
52 		return ret;
53 
54 	fd2 = open(file2, O_RDONLY);
55 	if (fd2 < 0)
56 		goto close1;
57 
58 	ret = fstat(fd1, &st1);
59 	if (ret)
60 		goto close2;
61 	ret = fstat(fd2, &st2);
62 	if (ret)
63 		goto close2;
64 
65 	if (st1.st_size != st2.st_size)
66 		goto close2;
67 
68 	map1 = mmap(NULL, st1.st_size, PROT_READ, MAP_PRIVATE, fd1, 0);
69 	if (map1 == MAP_FAILED)
70 		goto close2;
71 
72 	map2 = mmap(NULL, st2.st_size, PROT_READ, MAP_PRIVATE, fd2, 0);
73 	if (map2 == MAP_FAILED)
74 		goto close2;
75 
76 	if (bcmp(map1, map2, st1.st_size))
77 		goto close2;
78 
79 	ret = true;
80 close2:
81 	close(fd2);
82 close1:
83 	close(fd1);
84 
85 	return ret;
86 }
87 
88 /*
89  * Create the parent directory of the given path.
90  *
91  * For example, if 'include/config/auto.conf' is given, create 'include/config'.
92  */
make_parent_dir(const char * path)93 static int make_parent_dir(const char *path)
94 {
95 	char tmp[PATH_MAX + 1];
96 	char *p;
97 
98 	strncpy(tmp, path, sizeof(tmp));
99 	tmp[sizeof(tmp) - 1] = 0;
100 
101 	/* Remove the base name. Just return if nothing is left */
102 	p = strrchr(tmp, '/');
103 	if (!p)
104 		return 0;
105 	*(p + 1) = 0;
106 
107 	/* Just in case it is an absolute path */
108 	p = tmp;
109 	while (*p == '/')
110 		p++;
111 
112 	while ((p = strchr(p, '/'))) {
113 		*p = 0;
114 
115 		/* skip if the directory exists */
116 		if (!is_dir(tmp) && mkdir(tmp, 0755))
117 			return -1;
118 
119 		*p = '/';
120 		while (*p == '/')
121 			p++;
122 	}
123 
124 	return 0;
125 }
126 
127 static char depfile_path[PATH_MAX];
128 static size_t depfile_prefix_len;
129 
130 /* touch depfile for symbol 'name' */
conf_touch_dep(const char * name)131 static int conf_touch_dep(const char *name)
132 {
133 	int fd;
134 
135 	/* check overflow: prefix + name + '\0' must fit in buffer. */
136 	if (depfile_prefix_len + strlen(name) + 1 > sizeof(depfile_path))
137 		return -1;
138 
139 	strcpy(depfile_path + depfile_prefix_len, name);
140 
141 	fd = open(depfile_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
142 	if (fd == -1)
143 		return -1;
144 	close(fd);
145 
146 	return 0;
147 }
148 
149 static void conf_warning(const char *fmt, ...)
150 	__attribute__ ((format (printf, 1, 2)));
151 
152 static void conf_message(const char *fmt, ...)
153 	__attribute__ ((format (printf, 1, 2)));
154 
155 static const char *conf_filename;
156 static int conf_lineno, conf_warnings;
157 
conf_errors(void)158 bool conf_errors(void)
159 {
160 	if (conf_warnings)
161 		return getenv("KCONFIG_WERROR");
162 	return false;
163 }
164 
165 #ifdef __MINGW32__
166 #define mkdir(_n,_p) mkdir((_n))
167 #endif
168 
conf_warning(const char * fmt,...)169 static void conf_warning(const char *fmt, ...)
170 {
171 	va_list ap;
172 	va_start(ap, fmt);
173 	fprintf(stderr, "%s:%d:warning: ", conf_filename, conf_lineno);
174 	vfprintf(stderr, fmt, ap);
175 	fprintf(stderr, "\n");
176 	va_end(ap);
177 	conf_warnings++;
178 }
179 
conf_notice(const char * fmt,...)180 static void conf_notice(const char *fmt, ...)
181 {
182 	va_list ap;
183 	va_start(ap, fmt);
184 	fprintf(stderr, "%s:%d:notice: ", conf_filename, conf_lineno);
185 	vfprintf(stderr, fmt, ap);
186 	fprintf(stderr, "\n");
187 	va_end(ap);
188 }
189 
conf_default_message_callback(const char * s)190 static void conf_default_message_callback(const char *s)
191 {
192 	printf("#\n# ");
193 	printf("%s", s);
194 	printf("\n#\n");
195 }
196 
197 static void (*conf_message_callback)(const char *s) =
198 	conf_default_message_callback;
conf_set_message_callback(void (* fn)(const char * s))199 void conf_set_message_callback(void (*fn)(const char *s))
200 {
201 	conf_message_callback = fn;
202 }
203 
conf_message(const char * fmt,...)204 static void conf_message(const char *fmt, ...)
205 {
206 	va_list ap;
207 	char buf[4096];
208 
209 	if (!conf_message_callback)
210 		return;
211 
212 	va_start(ap, fmt);
213 
214 	vsnprintf(buf, sizeof(buf), fmt, ap);
215 	conf_message_callback(buf);
216 	va_end(ap);
217 }
218 
conf_get_configname(void)219 const char *conf_get_configname(void)
220 {
221 	char *name = getenv("KCONFIG_CONFIG");
222 
223 	return name ? name : ".config";
224 }
225 
conf_get_autoconfig_name(void)226 static const char *conf_get_autoconfig_name(void)
227 {
228 	char *name = getenv("KCONFIG_AUTOCONFIG");
229 
230 	return name ? name : "include/config/auto.conf";
231 }
232 
conf_get_autoheader_name(void)233 static const char *conf_get_autoheader_name(void)
234 {
235 	char *name = getenv("KCONFIG_AUTOHEADER");
236 
237 	return name ? name : "include/generated/autoconf.h";
238 }
239 
conf_get_rustccfg_name(void)240 static const char *conf_get_rustccfg_name(void)
241 {
242 	char *name = getenv("KCONFIG_RUSTCCFG");
243 
244 	return name ? name : "include/generated/rustc_cfg";
245 }
246 
conf_get_autobase_name(void)247 static const char *conf_get_autobase_name(void)
248 {
249 	char *name = getenv("KCONFIG_SPLITCONFIG");
250 
251 	return name ? name : "include/config/";
252 }
253 
conf_set_sym_val(struct symbol * sym,int def,int def_flags,char * p)254 static int conf_set_sym_val(struct symbol *sym, int def, int def_flags, char *p)
255 {
256 	char *p2;
257 
258 	switch (sym->type) {
259 	case S_TRISTATE:
260 		if (p[0] == 'm') {
261 			sym->def[def].tri = mod;
262 			sym->flags |= def_flags;
263 			break;
264 		}
265 		/* fall through */
266 	case S_BOOLEAN:
267 		if (p[0] == 'y') {
268 			sym->def[def].tri = yes;
269 			sym->flags |= def_flags;
270 			break;
271 		}
272 		if (p[0] == 'n') {
273 			sym->def[def].tri = no;
274 			sym->flags |= def_flags;
275 			break;
276 		}
277 		if (def != S_DEF_AUTO)
278 			conf_warning("symbol value '%s' invalid for %s",
279 				     p, sym->name);
280 		return 1;
281 	case S_STRING:
282 		/* No escaping for S_DEF_AUTO (include/config/auto.conf) */
283 		if (def != S_DEF_AUTO) {
284 			if (*p++ != '"')
285 				break;
286 			for (p2 = p; (p2 = strpbrk(p2, "\"\\")); p2++) {
287 				if (*p2 == '"') {
288 					*p2 = 0;
289 					break;
290 				}
291 				memmove(p2, p2 + 1, strlen(p2));
292 			}
293 			if (!p2) {
294 				conf_warning("invalid string found");
295 				return 1;
296 			}
297 		}
298 		/* fall through */
299 	case S_INT:
300 	case S_HEX:
301 		if (sym_string_valid(sym, p)) {
302 			sym->def[def].val = xstrdup(p);
303 			sym->flags |= def_flags;
304 		} else {
305 			if (def != S_DEF_AUTO)
306 				conf_warning("symbol value '%s' invalid for %s",
307 					     p, sym->name);
308 			return 1;
309 		}
310 		break;
311 	default:
312 		;
313 	}
314 	return 0;
315 }
316 
317 #define LINE_GROWTH 16
add_byte(int c,char ** lineptr,size_t slen,size_t * n)318 static int add_byte(int c, char **lineptr, size_t slen, size_t *n)
319 {
320 	size_t new_size = slen + 1;
321 
322 	if (new_size > *n) {
323 		new_size += LINE_GROWTH - 1;
324 		new_size *= 2;
325 		*lineptr = xrealloc(*lineptr, new_size);
326 		*n = new_size;
327 	}
328 
329 	(*lineptr)[slen] = c;
330 
331 	return 0;
332 }
333 
compat_getline(char ** lineptr,size_t * n,FILE * stream)334 static ssize_t compat_getline(char **lineptr, size_t *n, FILE *stream)
335 {
336 	char *line = *lineptr;
337 	size_t slen = 0;
338 
339 	for (;;) {
340 		int c = getc(stream);
341 
342 		switch (c) {
343 		case '\n':
344 			if (add_byte(c, &line, slen, n) < 0)
345 				goto e_out;
346 			slen++;
347 			/* fall through */
348 		case EOF:
349 			if (add_byte('\0', &line, slen, n) < 0)
350 				goto e_out;
351 			*lineptr = line;
352 			if (slen == 0)
353 				return -1;
354 			return slen;
355 		default:
356 			if (add_byte(c, &line, slen, n) < 0)
357 				goto e_out;
358 			slen++;
359 		}
360 	}
361 
362 e_out:
363 	line[slen-1] = '\0';
364 	*lineptr = line;
365 	return -1;
366 }
367 
368 /* like getline(), but the newline character is stripped away */
getline_stripped(char ** lineptr,size_t * n,FILE * stream)369 static ssize_t getline_stripped(char **lineptr, size_t *n, FILE *stream)
370 {
371 	ssize_t len;
372 
373 	len = compat_getline(lineptr, n, stream);
374 
375 	if (len > 0 && (*lineptr)[len - 1] == '\n') {
376 		len--;
377 		(*lineptr)[len] = '\0';
378 
379 		if (len > 0 && (*lineptr)[len - 1] == '\r') {
380 			len--;
381 			(*lineptr)[len] = '\0';
382 		}
383 	}
384 
385 	return len;
386 }
387 
conf_read_simple(const char * name,int def)388 int conf_read_simple(const char *name, int def)
389 {
390 	FILE *in = NULL;
391 	char   *line = NULL;
392 	size_t  line_asize = 0;
393 	char *p, *val;
394 	struct symbol *sym;
395 	int i, def_flags;
396 	const char *warn_unknown, *sym_name;
397 
398 	warn_unknown = getenv("KCONFIG_WARN_UNKNOWN_SYMBOLS");
399 	if (name) {
400 		in = zconf_fopen(name);
401 	} else {
402 		char *env;
403 
404 		name = conf_get_configname();
405 		in = zconf_fopen(name);
406 		if (in)
407 			goto load;
408 		conf_set_changed(true);
409 
410 		env = getenv("KCONFIG_DEFCONFIG_LIST");
411 		if (!env)
412 			return 1;
413 
414 		while (1) {
415 			bool is_last;
416 
417 			while (isspace(*env))
418 				env++;
419 
420 			if (!*env)
421 				break;
422 
423 			p = env;
424 			while (*p && !isspace(*p))
425 				p++;
426 
427 			is_last = (*p == '\0');
428 
429 			*p = '\0';
430 
431 			in = zconf_fopen(env);
432 			if (in) {
433 				conf_message("using defaults found in %s",
434 					     env);
435 				goto load;
436 			}
437 
438 			if (is_last)
439 				break;
440 
441 			env = p + 1;
442 		}
443 	}
444 	if (!in)
445 		return 1;
446 
447 load:
448 	conf_filename = name;
449 	conf_lineno = 0;
450 	conf_warnings = 0;
451 
452 	def_flags = SYMBOL_DEF << def;
453 	for_all_symbols(i, sym) {
454 		sym->flags |= SYMBOL_CHANGED;
455 		sym->flags &= ~(def_flags|SYMBOL_VALID);
456 		if (sym_is_choice(sym))
457 			sym->flags |= def_flags;
458 		switch (sym->type) {
459 		case S_INT:
460 		case S_HEX:
461 		case S_STRING:
462 			free(sym->def[def].val);
463 			/* fall through */
464 		default:
465 			sym->def[def].val = NULL;
466 			sym->def[def].tri = no;
467 		}
468 	}
469 
470 	while (getline_stripped(&line, &line_asize, in) != -1) {
471 		conf_lineno++;
472 
473 		if (!line[0]) /* blank line */
474 			continue;
475 
476 		if (line[0] == '#') {
477 			if (line[1] != ' ')
478 				continue;
479 			p = line + 2;
480 			if (memcmp(p, CONFIG_, strlen(CONFIG_)))
481 				continue;
482 			sym_name = p + strlen(CONFIG_);
483 			p = strchr(sym_name, ' ');
484 			if (!p)
485 				continue;
486 			*p++ = 0;
487 			if (strcmp(p, "is not set"))
488 				continue;
489 
490 			val = "n";
491 		} else {
492 			if (memcmp(line, CONFIG_, strlen(CONFIG_))) {
493 				conf_warning("unexpected data: %s", line);
494 				continue;
495 			}
496 
497 			sym_name = line + strlen(CONFIG_);
498 			p = strchr(sym_name, '=');
499 			if (!p) {
500 				conf_warning("unexpected data: %s", line);
501 				continue;
502 			}
503 			*p = 0;
504 			val = p + 1;
505 		}
506 
507 		sym = sym_find(sym_name);
508 		if (!sym) {
509 			if (def == S_DEF_AUTO) {
510 				/*
511 				 * Reading from include/config/auto.conf.
512 				 * If CONFIG_FOO previously existed in auto.conf
513 				 * but it is missing now, include/config/FOO
514 				 * must be touched.
515 				 */
516 				conf_touch_dep(sym_name);
517 			} else {
518 				if (warn_unknown)
519 					conf_warning("unknown symbol: %s", sym_name);
520 
521 				conf_set_changed(true);
522 			}
523 			continue;
524 		}
525 
526 		if (sym->flags & def_flags)
527 			conf_notice("override: reassigning to symbol %s", sym->name);
528 
529 		if (conf_set_sym_val(sym, def, def_flags, val))
530 			continue;
531 
532 		if (sym && sym_is_choice_value(sym)) {
533 			struct symbol *cs = prop_get_symbol(sym_get_choice_prop(sym));
534 			switch (sym->def[def].tri) {
535 			case no:
536 				break;
537 			case mod:
538 				if (cs->def[def].tri == yes) {
539 					conf_warning("%s creates inconsistent choice state", sym->name);
540 					cs->flags &= ~def_flags;
541 				}
542 				break;
543 			case yes:
544 				if (cs->def[def].tri != no)
545 					conf_notice("override: %s changes choice state", sym->name);
546 				cs->def[def].val = sym;
547 				break;
548 			}
549 			cs->def[def].tri = EXPR_OR(cs->def[def].tri, sym->def[def].tri);
550 		}
551 	}
552 	free(line);
553 	fclose(in);
554 
555 	return 0;
556 }
557 
conf_read(const char * name)558 int conf_read(const char *name)
559 {
560 	struct symbol *sym;
561 	int conf_unsaved = 0;
562 	int i;
563 
564 	conf_set_changed(false);
565 
566 	if (conf_read_simple(name, S_DEF_USER)) {
567 		sym_calc_value(modules_sym);
568 		return 1;
569 	}
570 
571 	sym_calc_value(modules_sym);
572 
573 	for_all_symbols(i, sym) {
574 		sym_calc_value(sym);
575 		if (sym_is_choice(sym) || (sym->flags & SYMBOL_NO_WRITE))
576 			continue;
577 		if (sym_has_value(sym) && (sym->flags & SYMBOL_WRITE)) {
578 			/* check that calculated value agrees with saved value */
579 			switch (sym->type) {
580 			case S_BOOLEAN:
581 			case S_TRISTATE:
582 				if (sym->def[S_DEF_USER].tri == sym_get_tristate_value(sym))
583 					continue;
584 				break;
585 			default:
586 				if (!strcmp(sym->curr.val, sym->def[S_DEF_USER].val))
587 					continue;
588 				break;
589 			}
590 		} else if (!sym_has_value(sym) && !(sym->flags & SYMBOL_WRITE))
591 			/* no previous value and not saved */
592 			continue;
593 		conf_unsaved++;
594 		/* maybe print value in verbose mode... */
595 	}
596 
597 	for_all_symbols(i, sym) {
598 		if (sym_has_value(sym) && !sym_is_choice_value(sym)) {
599 			/* Reset values of generates values, so they'll appear
600 			 * as new, if they should become visible, but that
601 			 * doesn't quite work if the Kconfig and the saved
602 			 * configuration disagree.
603 			 */
604 			if (sym->visible == no && !conf_unsaved)
605 				sym->flags &= ~SYMBOL_DEF_USER;
606 			switch (sym->type) {
607 			case S_STRING:
608 			case S_INT:
609 			case S_HEX:
610 				/* Reset a string value if it's out of range */
611 				if (sym_string_within_range(sym, sym->def[S_DEF_USER].val))
612 					break;
613 				sym->flags &= ~SYMBOL_VALID;
614 				conf_unsaved++;
615 				break;
616 			default:
617 				break;
618 			}
619 		}
620 	}
621 
622 	if (conf_warnings || conf_unsaved)
623 		conf_set_changed(true);
624 
625 	return 0;
626 }
627 
628 struct comment_style {
629 	const char *decoration;
630 	const char *prefix;
631 	const char *postfix;
632 };
633 
634 static const struct comment_style comment_style_pound = {
635 	.decoration = "#",
636 	.prefix = "#",
637 	.postfix = "#",
638 };
639 
640 static const struct comment_style comment_style_c = {
641 	.decoration = " *",
642 	.prefix = "/*",
643 	.postfix = " */",
644 };
645 
conf_write_heading(FILE * fp,const struct comment_style * cs)646 static void conf_write_heading(FILE *fp, const struct comment_style *cs)
647 {
648 	if (!cs)
649 		return;
650 
651 	fprintf(fp, "%s\n", cs->prefix);
652 
653 	fprintf(fp, "%s Automatically generated file; DO NOT EDIT.\n",
654 		cs->decoration);
655 
656 	fprintf(fp, "%s %s\n", cs->decoration, rootmenu.prompt->text);
657 
658 	fprintf(fp, "%s\n", cs->postfix);
659 }
660 
661 /* The returned pointer must be freed on the caller side */
escape_string_value(const char * in)662 static char *escape_string_value(const char *in)
663 {
664 	const char *p;
665 	char *out;
666 	size_t len;
667 
668 	len = strlen(in) + strlen("\"\"") + 1;
669 
670 	p = in;
671 	while (1) {
672 		p += strcspn(p, "\"\\");
673 
674 		if (p[0] == '\0')
675 			break;
676 
677 		len++;
678 		p++;
679 	}
680 
681 	out = xmalloc(len);
682 	out[0] = '\0';
683 
684 	strcat(out, "\"");
685 
686 	p = in;
687 	while (1) {
688 		len = strcspn(p, "\"\\");
689 		strncat(out, p, len);
690 		p += len;
691 
692 		if (p[0] == '\0')
693 			break;
694 
695 		strcat(out, "\\");
696 		strncat(out, p++, 1);
697 	}
698 
699 	strcat(out, "\"");
700 
701 	return out;
702 }
703 
704 enum output_n { OUTPUT_N, OUTPUT_N_AS_UNSET, OUTPUT_N_NONE };
705 
__print_symbol(FILE * fp,struct symbol * sym,enum output_n output_n,bool escape_string)706 static void __print_symbol(FILE *fp, struct symbol *sym, enum output_n output_n,
707 			   bool escape_string)
708 {
709 	const char *val;
710 	char *escaped = NULL;
711 
712 	if (sym->type == S_UNKNOWN)
713 		return;
714 
715 	val = sym_get_string_value(sym);
716 
717 	if ((sym->type == S_BOOLEAN || sym->type == S_TRISTATE) &&
718 	    output_n != OUTPUT_N && *val == 'n') {
719 		if (output_n == OUTPUT_N_AS_UNSET)
720 			fprintf(fp, "# %s%s is not set\n", CONFIG_, sym->name);
721 		return;
722 	}
723 
724 	if (sym->type == S_STRING && escape_string) {
725 		escaped = escape_string_value(val);
726 		val = escaped;
727 	}
728 
729 	fprintf(fp, "%s%s=%s\n", CONFIG_, sym->name, val);
730 
731 	free(escaped);
732 }
733 
print_symbol_for_dotconfig(FILE * fp,struct symbol * sym)734 static void print_symbol_for_dotconfig(FILE *fp, struct symbol *sym)
735 {
736 	__print_symbol(fp, sym, OUTPUT_N_AS_UNSET, true);
737 }
738 
print_symbol_for_autoconf(FILE * fp,struct symbol * sym)739 static void print_symbol_for_autoconf(FILE *fp, struct symbol *sym)
740 {
741 	int print_negatives = getenv("KCONFIG_NEGATIVES") != NULL;
742 	enum output_n out = OUTPUT_N_NONE;
743 	if (print_negatives) {
744 		out = OUTPUT_N;
745 	}
746 	__print_symbol(fp, sym, out, false);
747 }
748 
print_symbol_for_listconfig(struct symbol * sym)749 void print_symbol_for_listconfig(struct symbol *sym)
750 {
751 	__print_symbol(stdout, sym, OUTPUT_N, true);
752 }
753 
print_symbol_for_c(FILE * fp,struct symbol * sym)754 static void print_symbol_for_c(FILE *fp, struct symbol *sym)
755 {
756 	const char *val;
757 	const char *sym_suffix = "";
758 	const char *val_prefix = "";
759 	char *escaped = NULL;
760 
761 	if (sym->type == S_UNKNOWN)
762 		return;
763 
764 	val = sym_get_string_value(sym);
765 
766 	switch (sym->type) {
767 	case S_BOOLEAN:
768 	case S_TRISTATE:
769 		switch (*val) {
770 		case 'n':
771 			if (getenv("KCONFIG_NEGATIVES") != NULL) {
772 				val = "0";
773 				break;
774 			}
775 			return;
776 		case 'm':
777 			sym_suffix = "_MODULE";
778 			/* fall through */
779 		default:
780 			val = "1";
781 		}
782 		break;
783 	case S_HEX:
784 		if (val[0] != '0' || (val[1] != 'x' && val[1] != 'X'))
785 			val_prefix = "0x";
786 		/* fall through */
787 	case S_INT:
788 		if (val[0] == '\0') {
789 			val = "0";
790 			val_prefix = "";
791 		}
792 		break;
793 	case S_STRING:
794 		escaped = escape_string_value(val);
795 		val = escaped;
796 	default:
797 		break;
798 	}
799 
800 	fprintf(fp, "#define %s%s%s %s%s\n", CONFIG_, sym->name, sym_suffix,
801 		val_prefix, val);
802 
803 	free(escaped);
804 }
805 
print_symbol_for_rustccfg(FILE * fp,struct symbol * sym)806 static void print_symbol_for_rustccfg(FILE *fp, struct symbol *sym)
807 {
808 	const char *val;
809 	const char *val_prefix = "";
810 	char *val_prefixed = NULL;
811 	size_t val_prefixed_len;
812 	char *escaped = NULL;
813 
814 	if (sym->type == S_UNKNOWN)
815 		return;
816 
817 	val = sym_get_string_value(sym);
818 
819 	switch (sym->type) {
820 	case S_BOOLEAN:
821 	case S_TRISTATE:
822 		/*
823 		 * We do not care about disabled ones, i.e. no need for
824 		 * what otherwise are "comments" in other printers.
825 		 */
826 		if (*val == 'n')
827 			return;
828 
829 		/*
830 		 * To have similar functionality to the C macro `IS_ENABLED()`
831 		 * we provide an empty `--cfg CONFIG_X` here in both `y`
832 		 * and `m` cases.
833 		 *
834 		 * Then, the common `fprintf()` below will also give us
835 		 * a `--cfg CONFIG_X="y"` or `--cfg CONFIG_X="m"`, which can
836 		 * be used as the equivalent of `IS_BUILTIN()`/`IS_MODULE()`.
837 		 */
838 		fprintf(fp, "--cfg=%s%s\n", CONFIG_, sym->name);
839 		break;
840 	case S_HEX:
841 		if (val[0] != '0' || (val[1] != 'x' && val[1] != 'X'))
842 			val_prefix = "0x";
843 		break;
844 	default:
845 		break;
846 	}
847 
848 	if (strlen(val_prefix) > 0) {
849 		val_prefixed_len = strlen(val) + strlen(val_prefix) + 1;
850 		val_prefixed = xmalloc(val_prefixed_len);
851 		snprintf(val_prefixed, val_prefixed_len, "%s%s", val_prefix, val);
852 		val = val_prefixed;
853 	}
854 
855 	/* All values get escaped: the `--cfg` option only takes strings */
856 	escaped = escape_string_value(val);
857 	val = escaped;
858 
859 	fprintf(fp, "--cfg=%s%s=%s\n", CONFIG_, sym->name, val);
860 
861 	free(escaped);
862 	free(val_prefixed);
863 }
864 
865 /*
866  * Write out a minimal config.
867  * All values that has default values are skipped as this is redundant.
868  */
conf_write_defconfig(const char * filename)869 int conf_write_defconfig(const char *filename)
870 {
871 	struct symbol *sym;
872 	struct menu *menu;
873 	FILE *out;
874 
875 	out = fopen(filename, "w");
876 	if (!out)
877 		return 1;
878 
879 	sym_clear_all_valid();
880 
881 	/* Traverse all menus to find all relevant symbols */
882 	menu = rootmenu.list;
883 
884 	while (menu != NULL)
885 	{
886 		sym = menu->sym;
887 		if (sym == NULL) {
888 			if (!menu_is_visible(menu))
889 				goto next_menu;
890 		} else if (!sym_is_choice(sym)) {
891 			sym_calc_value(sym);
892 			if (!(sym->flags & SYMBOL_WRITE))
893 				goto next_menu;
894 			sym->flags &= ~SYMBOL_WRITE;
895 			/* If we cannot change the symbol - skip */
896 			if (!sym_is_changeable(sym))
897 				goto next_menu;
898 			/* If symbol equals to default value - skip */
899 			if (strcmp(sym_get_string_value(sym), sym_get_string_default(sym)) == 0)
900 				goto next_menu;
901 
902 			/*
903 			 * If symbol is a choice value and equals to the
904 			 * default for a choice - skip.
905 			 * But only if value is bool and equal to "y" and
906 			 * choice is not "optional".
907 			 * (If choice is "optional" then all values can be "n")
908 			 */
909 			if (sym_is_choice_value(sym)) {
910 				struct symbol *cs;
911 				struct symbol *ds;
912 
913 				cs = prop_get_symbol(sym_get_choice_prop(sym));
914 				ds = sym_choice_default(cs);
915 				if (!sym_is_optional(cs) && sym == ds) {
916 					if ((sym->type == S_BOOLEAN) &&
917 					    sym_get_tristate_value(sym) == yes)
918 						goto next_menu;
919 				}
920 			}
921 			print_symbol_for_dotconfig(out, sym);
922 		}
923 next_menu:
924 		if (menu->list != NULL) {
925 			menu = menu->list;
926 		}
927 		else if (menu->next != NULL) {
928 			menu = menu->next;
929 		} else {
930 			while ((menu = menu->parent)) {
931 				if (menu->next != NULL) {
932 					menu = menu->next;
933 					break;
934 				}
935 			}
936 		}
937 	}
938 	fclose(out);
939 	return 0;
940 }
941 
conf_write(const char * name)942 int conf_write(const char *name)
943 {
944 	FILE *out;
945 	struct symbol *sym;
946 	struct menu *menu;
947 	const char *str;
948 	char tmpname[PATH_MAX + 1], oldname[PATH_MAX + 1];
949 	char *env;
950 	int i;
951 	bool need_newline = false;
952 
953 	if (!name)
954 		name = conf_get_configname();
955 
956 	if (!*name) {
957 		fprintf(stderr, "config name is empty\n");
958 		return -1;
959 	}
960 
961 	if (is_dir(name)) {
962 		fprintf(stderr, "%s: Is a directory\n", name);
963 		return -1;
964 	}
965 
966 	if (make_parent_dir(name))
967 		return -1;
968 
969 	env = getenv("KCONFIG_OVERWRITECONFIG");
970 	if (env && *env) {
971 		*tmpname = 0;
972 		out = fopen(name, "w");
973 	} else {
974 		snprintf(tmpname, sizeof(tmpname), "%s.%d.tmp",
975 			 name, (int)getpid());
976 		out = fopen(tmpname, "w");
977 	}
978 	if (!out)
979 		return 1;
980 
981 	conf_write_heading(out, &comment_style_pound);
982 
983 	if (!conf_get_changed())
984 		sym_clear_all_valid();
985 
986 	menu = rootmenu.list;
987 	while (menu) {
988 		sym = menu->sym;
989 		if (!sym) {
990 			if (!menu_is_visible(menu))
991 				goto next;
992 			str = menu_get_prompt(menu);
993 			fprintf(out, "\n"
994 				     "#\n"
995 				     "# %s\n"
996 				     "#\n", str);
997 			need_newline = false;
998 		} else if (!(sym->flags & SYMBOL_CHOICE) &&
999 			   !(sym->flags & SYMBOL_WRITTEN)) {
1000 			sym_calc_value(sym);
1001 			if (!(sym->flags & SYMBOL_WRITE))
1002 				goto next;
1003 			if (need_newline) {
1004 				fprintf(out, "\n");
1005 				need_newline = false;
1006 			}
1007 			sym->flags |= SYMBOL_WRITTEN;
1008 			print_symbol_for_dotconfig(out, sym);
1009 		}
1010 
1011 next:
1012 		if (menu->list) {
1013 			menu = menu->list;
1014 			continue;
1015 		}
1016 
1017 end_check:
1018 		if (!menu->sym && menu_is_visible(menu) && menu != &rootmenu &&
1019 		    menu->prompt->type == P_MENU) {
1020 			fprintf(out, "# end of %s\n", menu_get_prompt(menu));
1021 			need_newline = true;
1022 		}
1023 
1024 		if (menu->next) {
1025 			menu = menu->next;
1026 		} else {
1027 			menu = menu->parent;
1028 			if (menu)
1029 				goto end_check;
1030 		}
1031 	}
1032 	fclose(out);
1033 
1034 	for_all_symbols(i, sym)
1035 		sym->flags &= ~SYMBOL_WRITTEN;
1036 
1037 	if (*tmpname) {
1038 		if (is_same(name, tmpname)) {
1039 			conf_message("No change to %s", name);
1040 			unlink(tmpname);
1041 			conf_set_changed(false);
1042 			return 0;
1043 		}
1044 
1045 		snprintf(oldname, sizeof(oldname), "%s.old", name);
1046 		rename(name, oldname);
1047 		if (rename(tmpname, name))
1048 			return 1;
1049 	}
1050 
1051 	conf_message("configuration written to %s", name);
1052 
1053 	conf_set_changed(false);
1054 
1055 	return 0;
1056 }
1057 
1058 /* write a dependency file as used by kbuild to track dependencies */
conf_write_autoconf_cmd(const char * autoconf_name)1059 static int conf_write_autoconf_cmd(const char *autoconf_name)
1060 {
1061 	char name[PATH_MAX], tmp[PATH_MAX];
1062 	struct file *file;
1063 	FILE *out;
1064 	int ret;
1065 
1066 	ret = snprintf(name, sizeof(name), "%s.cmd", autoconf_name);
1067 	if (ret >= sizeof(name)) /* check truncation */
1068 		return -1;
1069 
1070 	if (make_parent_dir(name))
1071 		return -1;
1072 
1073 	ret = snprintf(tmp, sizeof(tmp), "%s.cmd.tmp", autoconf_name);
1074 	if (ret >= sizeof(tmp)) /* check truncation */
1075 		return -1;
1076 
1077 	out = fopen(tmp, "w");
1078 	if (!out) {
1079 		perror("fopen");
1080 		return -1;
1081 	}
1082 
1083 	fprintf(out, "deps_config := \\\n");
1084 	for (file = file_list; file; file = file->next)
1085 		fprintf(out, "\t%s \\\n", file->name);
1086 
1087 	fprintf(out, "\n%s: $(deps_config)\n\n", autoconf_name);
1088 
1089 	env_write_dep(out, autoconf_name);
1090 
1091 	fprintf(out, "\n$(deps_config): ;\n");
1092 
1093 	fflush(out);
1094 	ret = ferror(out); /* error check for all fprintf() calls */
1095 	fclose(out);
1096 	if (ret)
1097 		return -1;
1098 
1099 	if (rename(tmp, name)) {
1100 		perror("rename");
1101 		return -1;
1102 	}
1103 
1104 	return 0;
1105 }
1106 
conf_touch_deps(void)1107 static int conf_touch_deps(void)
1108 {
1109 	const char *name;
1110 	struct symbol *sym;
1111 	int res, i;
1112 
1113 	/*
1114 	 * Upstream Kconfig sets depfile_path based on the directory
1115 	 * prefix of the autoconfig path, but coreboot overrides this
1116 	 * using the KCONFIG_SPLITCONFIG environment variable
1117 	 */
1118 	strcpy(depfile_path, conf_get_autobase_name());
1119 	depfile_prefix_len = strlen(depfile_path);
1120 
1121 	name = conf_get_autoconfig_name();
1122 	conf_read_simple(name, S_DEF_AUTO);
1123 	sym_calc_value(modules_sym);
1124 
1125 	for_all_symbols(i, sym) {
1126 		sym_calc_value(sym);
1127 		if ((sym->flags & SYMBOL_NO_WRITE) || !sym->name)
1128 			continue;
1129 		if (sym->flags & SYMBOL_WRITE) {
1130 			if (sym->flags & SYMBOL_DEF_AUTO) {
1131 				/*
1132 				 * symbol has old and new value,
1133 				 * so compare them...
1134 				 */
1135 				switch (sym->type) {
1136 				case S_BOOLEAN:
1137 				case S_TRISTATE:
1138 					if (sym_get_tristate_value(sym) ==
1139 					    sym->def[S_DEF_AUTO].tri)
1140 						continue;
1141 					break;
1142 				case S_STRING:
1143 				case S_HEX:
1144 				case S_INT:
1145 					if (!strcmp(sym_get_string_value(sym),
1146 						    sym->def[S_DEF_AUTO].val))
1147 						continue;
1148 					break;
1149 				default:
1150 					break;
1151 				}
1152 			} else {
1153 				/*
1154 				 * If there is no old value, only 'no' (unset)
1155 				 * is allowed as new value.
1156 				 */
1157 				switch (sym->type) {
1158 				case S_BOOLEAN:
1159 				case S_TRISTATE:
1160 					if (sym_get_tristate_value(sym) == no)
1161 						continue;
1162 					break;
1163 				default:
1164 					break;
1165 				}
1166 			}
1167 		} else if (!(sym->flags & SYMBOL_DEF_AUTO))
1168 			/* There is neither an old nor a new value. */
1169 			continue;
1170 		/* else
1171 		 *	There is an old value, but no new value ('no' (unset)
1172 		 *	isn't saved in auto.conf, so the old value is always
1173 		 *	different from 'no').
1174 		 */
1175 
1176 		res = conf_touch_dep(sym->name);
1177 		if (res)
1178 			return res;
1179 	}
1180 
1181 	return 0;
1182 }
1183 
__conf_write_autoconf(const char * filename,void (* print_symbol)(FILE *,struct symbol *),const struct comment_style * comment_style)1184 static int __conf_write_autoconf(const char *filename,
1185 				 void (*print_symbol)(FILE *, struct symbol *),
1186 				 const struct comment_style *comment_style)
1187 {
1188 	char tmp[PATH_MAX];
1189 	FILE *file;
1190 	struct symbol *sym;
1191 	int ret, i;
1192 
1193 	if (make_parent_dir(filename))
1194 		return -1;
1195 
1196 	ret = snprintf(tmp, sizeof(tmp), "%s.tmp", filename);
1197 	if (ret >= sizeof(tmp)) /* check truncation */
1198 		return -1;
1199 
1200 	file = fopen(tmp, "w");
1201 	if (!file) {
1202 		perror("fopen");
1203 		return -1;
1204 	}
1205 
1206 	conf_write_heading(file, comment_style);
1207 
1208 	int print_negatives = getenv("KCONFIG_NEGATIVES") != NULL;
1209 	for_all_symbols(i, sym)
1210 		if (((sym->flags & SYMBOL_WRITE) || (print_negatives && sym->type != S_STRING)) && sym->name)
1211 			print_symbol(file, sym);
1212 
1213 	fflush(file);
1214 	/* check possible errors in conf_write_heading() and print_symbol() */
1215 	ret = ferror(file);
1216 	fclose(file);
1217 	if (ret)
1218 		return -1;
1219 
1220 	if (rename(tmp, filename)) {
1221 		perror("rename");
1222 		return -1;
1223 	}
1224 
1225 	return 0;
1226 }
1227 
conf_write_autoconf(int overwrite)1228 int conf_write_autoconf(int overwrite)
1229 {
1230 	struct symbol *sym;
1231 	const char *autoconf_name = conf_get_autoconfig_name();
1232 	int ret, i;
1233 
1234 	if (!overwrite && is_present(autoconf_name))
1235 		return 0;
1236 
1237 	ret = conf_write_autoconf_cmd(autoconf_name);
1238 	if (ret)
1239 		return -1;
1240 
1241 	if (conf_touch_deps())
1242 		return 1;
1243 
1244 	for_all_symbols(i, sym)
1245 		sym_calc_value(sym);
1246 
1247 	ret = __conf_write_autoconf(conf_get_autoheader_name(),
1248 				    print_symbol_for_c,
1249 				    &comment_style_c);
1250 	if (ret)
1251 		return ret;
1252 
1253 	ret = __conf_write_autoconf(conf_get_rustccfg_name(),
1254 				    print_symbol_for_rustccfg,
1255 				    NULL);
1256 	if (ret)
1257 		return ret;
1258 
1259 	/*
1260 	 * Create include/config/auto.conf. This must be the last step because
1261 	 * Kbuild has a dependency on auto.conf and this marks the successful
1262 	 * completion of the previous steps.
1263 	 */
1264 	ret = __conf_write_autoconf(conf_get_autoconfig_name(),
1265 				    print_symbol_for_autoconf,
1266 				    &comment_style_pound);
1267 	if (ret)
1268 		return ret;
1269 
1270 	return 0;
1271 }
1272 
1273 static bool conf_changed;
1274 static void (*conf_changed_callback)(void);
1275 
conf_set_changed(bool val)1276 void conf_set_changed(bool val)
1277 {
1278 	bool changed = conf_changed != val;
1279 
1280 	conf_changed = val;
1281 
1282 	if (conf_changed_callback && changed)
1283 		conf_changed_callback();
1284 }
1285 
conf_get_changed(void)1286 bool conf_get_changed(void)
1287 {
1288 	return conf_changed;
1289 }
1290 
conf_set_changed_callback(void (* fn)(void))1291 void conf_set_changed_callback(void (*fn)(void))
1292 {
1293 	conf_changed_callback = fn;
1294 }
1295 
set_all_choice_values(struct symbol * csym)1296 void set_all_choice_values(struct symbol *csym)
1297 {
1298 	struct property *prop;
1299 	struct symbol *sym;
1300 	struct expr *e;
1301 
1302 	prop = sym_get_choice_prop(csym);
1303 
1304 	/*
1305 	 * Set all non-assinged choice values to no
1306 	 */
1307 	expr_list_for_each_sym(prop->expr, e, sym) {
1308 		if (!sym_has_value(sym))
1309 			sym->def[S_DEF_USER].tri = no;
1310 	}
1311 	csym->flags |= SYMBOL_DEF_USER;
1312 	/* clear VALID to get value calculated */
1313 	csym->flags &= ~(SYMBOL_VALID | SYMBOL_NEED_SET_CHOICE_VALUES);
1314 }
1315