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