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