5ee58eeb9a7d954d8d5b849211835147a88da8dc
[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_error_if(int argc, char *argv[])
110 {
111         if (!strcmp(argv[0], "y"))
112                 pperror("%s", argv[1]);
113
114         return NULL;
115 }
116
117 static char *do_info(int argc, char *argv[])
118 {
119         printf("%s\n", argv[0]);
120
121         return xstrdup("");
122 }
123
124 static char *do_shell(int argc, char *argv[])
125 {
126         FILE *p;
127         char buf[256];
128         char *cmd;
129         size_t nread;
130         int i;
131
132         cmd = argv[0];
133
134         p = popen(cmd, "r");
135         if (!p) {
136                 perror(cmd);
137                 exit(1);
138         }
139
140         nread = fread(buf, 1, sizeof(buf), p);
141         if (nread == sizeof(buf))
142                 nread--;
143
144         /* remove trailing new lines */
145         while (buf[nread - 1] == '\n')
146                 nread--;
147
148         buf[nread] = 0;
149
150         /* replace a new line with a space */
151         for (i = 0; i < nread; i++) {
152                 if (buf[i] == '\n')
153                         buf[i] = ' ';
154         }
155
156         if (pclose(p) == -1) {
157                 perror(cmd);
158                 exit(1);
159         }
160
161         return xstrdup(buf);
162 }
163
164 static char *do_warning_if(int argc, char *argv[])
165 {
166         if (!strcmp(argv[0], "y"))
167                 fprintf(stderr, "%s:%d: %s\n",
168                         current_file->name, yylineno, argv[1]);
169
170         return xstrdup("");
171 }
172
173 static const struct function function_table[] = {
174         /* Name         MIN     MAX     Function */
175         { "error-if",   2,      2,      do_error_if },
176         { "info",       1,      1,      do_info },
177         { "shell",      1,      1,      do_shell },
178         { "warning-if", 2,      2,      do_warning_if },
179 };
180
181 #define FUNCTION_MAX_ARGS               16
182
183 static char *function_expand(const char *name, int argc, char *argv[])
184 {
185         const struct function *f;
186         int i;
187
188         for (i = 0; i < ARRAY_SIZE(function_table); i++) {
189                 f = &function_table[i];
190                 if (strcmp(f->name, name))
191                         continue;
192
193                 if (argc < f->min_args)
194                         pperror("too few function arguments passed to '%s'",
195                                 name);
196
197                 if (argc > f->max_args)
198                         pperror("too many function arguments passed to '%s'",
199                                 name);
200
201                 return f->func(argc, argv);
202         }
203
204         return NULL;
205 }
206
207 /*
208  * Variables (and user-defined functions)
209  */
210 static LIST_HEAD(variable_list);
211
212 struct variable {
213         char *name;
214         char *value;
215         enum variable_flavor flavor;
216         struct list_head node;
217 };
218
219 static struct variable *variable_lookup(const char *name)
220 {
221         struct variable *v;
222
223         list_for_each_entry(v, &variable_list, node) {
224                 if (!strcmp(name, v->name))
225                         return v;
226         }
227
228         return NULL;
229 }
230
231 static char *variable_expand(const char *name, int argc, char *argv[])
232 {
233         struct variable *v;
234         char *res;
235
236         v = variable_lookup(name);
237         if (!v)
238                 return NULL;
239
240         if (v->flavor == VAR_RECURSIVE)
241                 res = expand_string_with_args(v->value, argc, argv);
242         else
243                 res = xstrdup(v->value);
244
245         return res;
246 }
247
248 void variable_add(const char *name, const char *value,
249                   enum variable_flavor flavor)
250 {
251         struct variable *v;
252         char *new_value;
253         bool append = false;
254
255         v = variable_lookup(name);
256         if (v) {
257                 /* For defined variables, += inherits the existing flavor */
258                 if (flavor == VAR_APPEND) {
259                         flavor = v->flavor;
260                         append = true;
261                 } else {
262                         free(v->value);
263                 }
264         } else {
265                 /* For undefined variables, += assumes the recursive flavor */
266                 if (flavor == VAR_APPEND)
267                         flavor = VAR_RECURSIVE;
268
269                 v = xmalloc(sizeof(*v));
270                 v->name = xstrdup(name);
271                 list_add_tail(&v->node, &variable_list);
272         }
273
274         v->flavor = flavor;
275
276         if (flavor == VAR_SIMPLE)
277                 new_value = expand_string(value);
278         else
279                 new_value = xstrdup(value);
280
281         if (append) {
282                 v->value = xrealloc(v->value,
283                                     strlen(v->value) + strlen(new_value) + 2);
284                 strcat(v->value, " ");
285                 strcat(v->value, new_value);
286                 free(new_value);
287         } else {
288                 v->value = new_value;
289         }
290 }
291
292 static void variable_del(struct variable *v)
293 {
294         list_del(&v->node);
295         free(v->name);
296         free(v->value);
297         free(v);
298 }
299
300 void variable_all_del(void)
301 {
302         struct variable *v, *tmp;
303
304         list_for_each_entry_safe(v, tmp, &variable_list, node)
305                 variable_del(v);
306 }
307
308 /*
309  * Evaluate a clause with arguments.  argc/argv are arguments from the upper
310  * function call.
311  *
312  * Returned string must be freed when done
313  */
314 static char *eval_clause(const char *str, size_t len, int argc, char *argv[])
315 {
316         char *tmp, *name, *res, *endptr, *prev, *p;
317         int new_argc = 0;
318         char *new_argv[FUNCTION_MAX_ARGS];
319         int nest = 0;
320         int i;
321         unsigned long n;
322
323         tmp = xstrndup(str, len);
324
325         /*
326          * If variable name is '1', '2', etc.  It is generally an argument
327          * from a user-function call (i.e. local-scope variable).  If not
328          * available, then look-up global-scope variables.
329          */
330         n = strtoul(tmp, &endptr, 10);
331         if (!*endptr && n > 0 && n <= argc) {
332                 res = xstrdup(argv[n - 1]);
333                 goto free_tmp;
334         }
335
336         prev = p = tmp;
337
338         /*
339          * Split into tokens
340          * The function name and arguments are separated by a comma.
341          * For example, if the function call is like this:
342          *   $(foo,$(x),$(y))
343          *
344          * The input string for this helper should be:
345          *   foo,$(x),$(y)
346          *
347          * and split into:
348          *   new_argv[0] = 'foo'
349          *   new_argv[1] = '$(x)'
350          *   new_argv[2] = '$(y)'
351          */
352         while (*p) {
353                 if (nest == 0 && *p == ',') {
354                         *p = 0;
355                         if (new_argc >= FUNCTION_MAX_ARGS)
356                                 pperror("too many function arguments");
357                         new_argv[new_argc++] = prev;
358                         prev = p + 1;
359                 } else if (*p == '(') {
360                         nest++;
361                 } else if (*p == ')') {
362                         nest--;
363                 }
364
365                 p++;
366         }
367         new_argv[new_argc++] = prev;
368
369         /*
370          * Shift arguments
371          * new_argv[0] represents a function name or a variable name.  Put it
372          * into 'name', then shift the rest of the arguments.  This simplifies
373          * 'const' handling.
374          */
375         name = expand_string_with_args(new_argv[0], argc, argv);
376         new_argc--;
377         for (i = 0; i < new_argc; i++)
378                 new_argv[i] = expand_string_with_args(new_argv[i + 1],
379                                                       argc, argv);
380
381         /* Search for variables */
382         res = variable_expand(name, new_argc, new_argv);
383         if (res)
384                 goto free;
385
386         /* Look for built-in functions */
387         res = function_expand(name, new_argc, new_argv);
388         if (res)
389                 goto free;
390
391         /* Last, try environment variable */
392         if (new_argc == 0) {
393                 res = env_expand(name);
394                 if (res)
395                         goto free;
396         }
397
398         res = xstrdup("");
399 free:
400         for (i = 0; i < new_argc; i++)
401                 free(new_argv[i]);
402         free(name);
403 free_tmp:
404         free(tmp);
405
406         return res;
407 }
408
409 /*
410  * Expand a string that follows '$'
411  *
412  * For example, if the input string is
413  *     ($(FOO)$($(BAR)))$(BAZ)
414  * this helper evaluates
415  *     $($(FOO)$($(BAR)))
416  * and returns a new string containing the expansion (note that the string is
417  * recursively expanded), also advancing 'str' to point to the next character
418  * after the corresponding closing parenthesis, in this case, *str will be
419  *     $(BAR)
420  */
421 static char *expand_dollar_with_args(const char **str, int argc, char *argv[])
422 {
423         const char *p = *str;
424         const char *q;
425         int nest = 0;
426
427         /*
428          * In Kconfig, variable/function references always start with "$(".
429          * Neither single-letter variables as in $A nor curly braces as in ${CC}
430          * are supported.  '$' not followed by '(' loses its special meaning.
431          */
432         if (*p != '(') {
433                 *str = p;
434                 return xstrdup("$");
435         }
436
437         p++;
438         q = p;
439         while (*q) {
440                 if (*q == '(') {
441                         nest++;
442                 } else if (*q == ')') {
443                         if (nest-- == 0)
444                                 break;
445                 }
446                 q++;
447         }
448
449         if (!*q)
450                 pperror("unterminated reference to '%s': missing ')'", p);
451
452         /* Advance 'str' to after the expanded initial portion of the string */
453         *str = q + 1;
454
455         return eval_clause(p, q - p, argc, argv);
456 }
457
458 char *expand_dollar(const char **str)
459 {
460         return expand_dollar_with_args(str, 0, NULL);
461 }
462
463 static char *__expand_string(const char **str, bool (*is_end)(char c),
464                              int argc, char *argv[])
465 {
466         const char *in, *p;
467         char *expansion, *out;
468         size_t in_len, out_len;
469
470         out = xmalloc(1);
471         *out = 0;
472         out_len = 1;
473
474         p = in = *str;
475
476         while (1) {
477                 if (*p == '$') {
478                         in_len = p - in;
479                         p++;
480                         expansion = expand_dollar_with_args(&p, argc, argv);
481                         out_len += in_len + strlen(expansion);
482                         out = xrealloc(out, out_len);
483                         strncat(out, in, in_len);
484                         strcat(out, expansion);
485                         free(expansion);
486                         in = p;
487                         continue;
488                 }
489
490                 if (is_end(*p))
491                         break;
492
493                 p++;
494         }
495
496         in_len = p - in;
497         out_len += in_len;
498         out = xrealloc(out, out_len);
499         strncat(out, in, in_len);
500
501         /* Advance 'str' to the end character */
502         *str = p;
503
504         return out;
505 }
506
507 static bool is_end_of_str(char c)
508 {
509         return !c;
510 }
511
512 /*
513  * Expand variables and functions in the given string.  Undefined variables
514  * expand to an empty string.
515  * The returned string must be freed when done.
516  */
517 static char *expand_string_with_args(const char *in, int argc, char *argv[])
518 {
519         return __expand_string(&in, is_end_of_str, argc, argv);
520 }
521
522 char *expand_string(const char *in)
523 {
524         return expand_string_with_args(in, 0, NULL);
525 }
526
527 static bool is_end_of_token(char c)
528 {
529         /* Why are '.' and '/' valid characters for symbols? */
530         return !(isalnum(c) || c == '_' || c == '-' || c == '.' || c == '/');
531 }
532
533 /*
534  * Expand variables in a token.  The parsing stops when a token separater
535  * (in most cases, it is a whitespace) is encountered.  'str' is updated to
536  * point to the next character.
537  *
538  * The returned string must be freed when done.
539  */
540 char *expand_one_token(const char **str)
541 {
542         return __expand_string(str, is_end_of_token, 0, NULL);
543 }