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