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