kconfig: support append assignment operator
[carl9170fw.git] / config / preprocess.c
1 // SPDX-License-Identifier: GPL-2.0
2 //
3 // Copyright (C) 2018 Masahiro Yamada <yamada.masahiro@socionext.com>
4
5 #include <stdarg.h>
6 #include <stdbool.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10
11 #include "list.h"
12
13 #define ARRAY_SIZE(arr)         (sizeof(arr) / sizeof((arr)[0]))
14
15 static char *expand_string_with_args(const char *in, int argc, char *argv[]);
16
17 static void __attribute__((noreturn)) pperror(const char *format, ...)
18 {
19         va_list ap;
20
21         fprintf(stderr, "%s:%d: ", current_file->name, yylineno);
22         va_start(ap, format);
23         vfprintf(stderr, format, ap);
24         va_end(ap);
25         fprintf(stderr, "\n");
26
27         exit(1);
28 }
29
30 /*
31  * Environment variables
32  */
33 static LIST_HEAD(env_list);
34
35 struct env {
36         char *name;
37         char *value;
38         struct list_head node;
39 };
40
41 static void env_add(const char *name, const char *value)
42 {
43         struct env *e;
44
45         e = xmalloc(sizeof(*e));
46         e->name = xstrdup(name);
47         e->value = xstrdup(value);
48
49         list_add_tail(&e->node, &env_list);
50 }
51
52 static void env_del(struct env *e)
53 {
54         list_del(&e->node);
55         free(e->name);
56         free(e->value);
57         free(e);
58 }
59
60 /* The returned pointer must be freed when done */
61 static char *env_expand(const char *name)
62 {
63         struct env *e;
64         const char *value;
65
66         if (!*name)
67                 return NULL;
68
69         list_for_each_entry(e, &env_list, node) {
70                 if (!strcmp(name, e->name))
71                         return xstrdup(e->value);
72         }
73
74         value = getenv(name);
75         if (!value)
76                 return NULL;
77
78         /*
79          * We need to remember all referenced environment variables.
80          * They will be written out to include/config/auto.conf.cmd
81          */
82         env_add(name, value);
83
84         return xstrdup(value);
85 }
86
87 void env_write_dep(FILE *f, const char *autoconfig_name)
88 {
89         struct env *e, *tmp;
90
91         list_for_each_entry_safe(e, tmp, &env_list, node) {
92                 fprintf(f, "ifneq \"$(%s)\" \"%s\"\n", e->name, e->value);
93                 fprintf(f, "%s: FORCE\n", autoconfig_name);
94                 fprintf(f, "endif\n");
95                 env_del(e);
96         }
97 }
98
99 /*
100  * Built-in functions
101  */
102 struct function {
103         const char *name;
104         unsigned int min_args;
105         unsigned int max_args;
106         char *(*func)(int argc, char *argv[]);
107 };
108
109 static char *do_shell(int argc, char *argv[])
110 {
111         FILE *p;
112         char buf[256];
113         char *cmd;
114         size_t nread;
115         int i;
116
117         cmd = argv[0];
118
119         p = popen(cmd, "r");
120         if (!p) {
121                 perror(cmd);
122                 exit(1);
123         }
124
125         nread = fread(buf, 1, sizeof(buf), p);
126         if (nread == sizeof(buf))
127                 nread--;
128
129         /* remove trailing new lines */
130         while (buf[nread - 1] == '\n')
131                 nread--;
132
133         buf[nread] = 0;
134
135         /* replace a new line with a space */
136         for (i = 0; i < nread; i++) {
137                 if (buf[i] == '\n')
138                         buf[i] = ' ';
139         }
140
141         if (pclose(p) == -1) {
142                 perror(cmd);
143                 exit(1);
144         }
145
146         return xstrdup(buf);
147 }
148
149 static const struct function function_table[] = {
150         /* Name         MIN     MAX     Function */
151         { "shell",      1,      1,      do_shell },
152 };
153
154 #define FUNCTION_MAX_ARGS               16
155
156 static char *function_expand(const char *name, int argc, char *argv[])
157 {
158         const struct function *f;
159         int i;
160
161         for (i = 0; i < ARRAY_SIZE(function_table); i++) {
162                 f = &function_table[i];
163                 if (strcmp(f->name, name))
164                         continue;
165
166                 if (argc < f->min_args)
167                         pperror("too few function arguments passed to '%s'",
168                                 name);
169
170                 if (argc > f->max_args)
171                         pperror("too many function arguments passed to '%s'",
172                                 name);
173
174                 return f->func(argc, argv);
175         }
176
177         return NULL;
178 }
179
180 /*
181  * Variables (and user-defined functions)
182  */
183 static LIST_HEAD(variable_list);
184
185 struct variable {
186         char *name;
187         char *value;
188         enum variable_flavor flavor;
189         struct list_head node;
190 };
191
192 static struct variable *variable_lookup(const char *name)
193 {
194         struct variable *v;
195
196         list_for_each_entry(v, &variable_list, node) {
197                 if (!strcmp(name, v->name))
198                         return v;
199         }
200
201         return NULL;
202 }
203
204 static char *variable_expand(const char *name, int argc, char *argv[])
205 {
206         struct variable *v;
207         char *res;
208
209         v = variable_lookup(name);
210         if (!v)
211                 return NULL;
212
213         if (v->flavor == VAR_RECURSIVE)
214                 res = expand_string_with_args(v->value, argc, argv);
215         else
216                 res = xstrdup(v->value);
217
218         return res;
219 }
220
221 void variable_add(const char *name, const char *value,
222                   enum variable_flavor flavor)
223 {
224         struct variable *v;
225         char *new_value;
226         bool append = false;
227
228         v = variable_lookup(name);
229         if (v) {
230                 /* For defined variables, += inherits the existing flavor */
231                 if (flavor == VAR_APPEND) {
232                         flavor = v->flavor;
233                         append = true;
234                 } else {
235                         free(v->value);
236                 }
237         } else {
238                 /* For undefined variables, += assumes the recursive flavor */
239                 if (flavor == VAR_APPEND)
240                         flavor = VAR_RECURSIVE;
241
242                 v = xmalloc(sizeof(*v));
243                 v->name = xstrdup(name);
244                 list_add_tail(&v->node, &variable_list);
245         }
246
247         v->flavor = flavor;
248
249         if (flavor == VAR_SIMPLE)
250                 new_value = expand_string(value);
251         else
252                 new_value = xstrdup(value);
253
254         if (append) {
255                 v->value = xrealloc(v->value,
256                                     strlen(v->value) + strlen(new_value) + 2);
257                 strcat(v->value, " ");
258                 strcat(v->value, new_value);
259                 free(new_value);
260         } else {
261                 v->value = new_value;
262         }
263 }
264
265 static void variable_del(struct variable *v)
266 {
267         list_del(&v->node);
268         free(v->name);
269         free(v->value);
270         free(v);
271 }
272
273 void variable_all_del(void)
274 {
275         struct variable *v, *tmp;
276
277         list_for_each_entry_safe(v, tmp, &variable_list, node)
278                 variable_del(v);
279 }
280
281 /*
282  * Evaluate a clause with arguments.  argc/argv are arguments from the upper
283  * function call.
284  *
285  * Returned string must be freed when done
286  */
287 static char *eval_clause(const char *str, size_t len, int argc, char *argv[])
288 {
289         char *tmp, *name, *res, *endptr, *prev, *p;
290         int new_argc = 0;
291         char *new_argv[FUNCTION_MAX_ARGS];
292         int nest = 0;
293         int i;
294         unsigned long n;
295
296         tmp = xstrndup(str, len);
297
298         /*
299          * If variable name is '1', '2', etc.  It is generally an argument
300          * from a user-function call (i.e. local-scope variable).  If not
301          * available, then look-up global-scope variables.
302          */
303         n = strtoul(tmp, &endptr, 10);
304         if (!*endptr && n > 0 && n <= argc) {
305                 res = xstrdup(argv[n - 1]);
306                 goto free_tmp;
307         }
308
309         prev = p = tmp;
310
311         /*
312          * Split into tokens
313          * The function name and arguments are separated by a comma.
314          * For example, if the function call is like this:
315          *   $(foo,$(x),$(y))
316          *
317          * The input string for this helper should be:
318          *   foo,$(x),$(y)
319          *
320          * and split into:
321          *   new_argv[0] = 'foo'
322          *   new_argv[1] = '$(x)'
323          *   new_argv[2] = '$(y)'
324          */
325         while (*p) {
326                 if (nest == 0 && *p == ',') {
327                         *p = 0;
328                         if (new_argc >= FUNCTION_MAX_ARGS)
329                                 pperror("too many function arguments");
330                         new_argv[new_argc++] = prev;
331                         prev = p + 1;
332                 } else if (*p == '(') {
333                         nest++;
334                 } else if (*p == ')') {
335                         nest--;
336                 }
337
338                 p++;
339         }
340         new_argv[new_argc++] = prev;
341
342         /*
343          * Shift arguments
344          * new_argv[0] represents a function name or a variable name.  Put it
345          * into 'name', then shift the rest of the arguments.  This simplifies
346          * 'const' handling.
347          */
348         name = expand_string_with_args(new_argv[0], argc, argv);
349         new_argc--;
350         for (i = 0; i < new_argc; i++)
351                 new_argv[i] = expand_string_with_args(new_argv[i + 1],
352                                                       argc, argv);
353
354         /* Search for variables */
355         res = variable_expand(name, new_argc, new_argv);
356         if (res)
357                 goto free;
358
359         /* Look for built-in functions */
360         res = function_expand(name, new_argc, new_argv);
361         if (res)
362                 goto free;
363
364         /* Last, try environment variable */
365         if (new_argc == 0) {
366                 res = env_expand(name);
367                 if (res)
368                         goto free;
369         }
370
371         res = xstrdup("");
372 free:
373         for (i = 0; i < new_argc; i++)
374                 free(new_argv[i]);
375         free(name);
376 free_tmp:
377         free(tmp);
378
379         return res;
380 }
381
382 /*
383  * Expand a string that follows '$'
384  *
385  * For example, if the input string is
386  *     ($(FOO)$($(BAR)))$(BAZ)
387  * this helper evaluates
388  *     $($(FOO)$($(BAR)))
389  * and returns a new string containing the expansion (note that the string is
390  * recursively expanded), also advancing 'str' to point to the next character
391  * after the corresponding closing parenthesis, in this case, *str will be
392  *     $(BAR)
393  */
394 static char *expand_dollar_with_args(const char **str, int argc, char *argv[])
395 {
396         const char *p = *str;
397         const char *q;
398         int nest = 0;
399
400         /*
401          * In Kconfig, variable/function references always start with "$(".
402          * Neither single-letter variables as in $A nor curly braces as in ${CC}
403          * are supported.  '$' not followed by '(' loses its special meaning.
404          */
405         if (*p != '(') {
406                 *str = p;
407                 return xstrdup("$");
408         }
409
410         p++;
411         q = p;
412         while (*q) {
413                 if (*q == '(') {
414                         nest++;
415                 } else if (*q == ')') {
416                         if (nest-- == 0)
417                                 break;
418                 }
419                 q++;
420         }
421
422         if (!*q)
423                 pperror("unterminated reference to '%s': missing ')'", p);
424
425         /* Advance 'str' to after the expanded initial portion of the string */
426         *str = q + 1;
427
428         return eval_clause(p, q - p, argc, argv);
429 }
430
431 char *expand_dollar(const char **str)
432 {
433         return expand_dollar_with_args(str, 0, NULL);
434 }
435
436 static char *__expand_string(const char **str, bool (*is_end)(char c),
437                              int argc, char *argv[])
438 {
439         const char *in, *p;
440         char *expansion, *out;
441         size_t in_len, out_len;
442
443         out = xmalloc(1);
444         *out = 0;
445         out_len = 1;
446
447         p = in = *str;
448
449         while (1) {
450                 if (*p == '$') {
451                         in_len = p - in;
452                         p++;
453                         expansion = expand_dollar_with_args(&p, argc, argv);
454                         out_len += in_len + strlen(expansion);
455                         out = xrealloc(out, out_len);
456                         strncat(out, in, in_len);
457                         strcat(out, expansion);
458                         free(expansion);
459                         in = p;
460                         continue;
461                 }
462
463                 if (is_end(*p))
464                         break;
465
466                 p++;
467         }
468
469         in_len = p - in;
470         out_len += in_len;
471         out = xrealloc(out, out_len);
472         strncat(out, in, in_len);
473
474         /* Advance 'str' to the end character */
475         *str = p;
476
477         return out;
478 }
479
480 static bool is_end_of_str(char c)
481 {
482         return !c;
483 }
484
485 /*
486  * Expand variables and functions in the given string.  Undefined variables
487  * expand to an empty string.
488  * The returned string must be freed when done.
489  */
490 static char *expand_string_with_args(const char *in, int argc, char *argv[])
491 {
492         return __expand_string(&in, is_end_of_str, argc, argv);
493 }
494
495 char *expand_string(const char *in)
496 {
497         return expand_string_with_args(in, 0, NULL);
498 }
499
500 static bool is_end_of_token(char c)
501 {
502         /* Why are '.' and '/' valid characters for symbols? */
503         return !(isalnum(c) || c == '_' || c == '-' || c == '.' || c == '/');
504 }
505
506 /*
507  * Expand variables in a token.  The parsing stops when a token separater
508  * (in most cases, it is a whitespace) is encountered.  'str' is updated to
509  * point to the next character.
510  *
511  * The returned string must be freed when done.
512  */
513 char *expand_one_token(const char **str)
514 {
515         return __expand_string(str, is_end_of_token, 0, NULL);
516 }