1 #include <ccan/grab_file/grab_file.h>
2 #include <ccan/str/str.h>
3 #include <ccan/str_talloc/str_talloc.h>
4 #include <ccan/talloc/talloc.h>
5 #include "read_config_header.h"
10 /* Get an identifier token. */
11 char *get_symbol_token(void *ctx, const char **line)
16 *line += strspn(*line, " \t");
17 toklen = strspn(*line, IDENT_CHARS);
20 ret = talloc_strndup(ctx, *line, toklen);
25 /* Get token if it's equal to token. */
26 bool get_token(const char **line, const char *token)
30 *line += strspn(*line, " \t");
31 if (cisalnum(token[0]) || token[0] == '_')
32 toklen = strspn(*line, IDENT_CHARS);
34 /* FIXME: real tokenizer handles ++ and other multi-chars. */
35 toklen = strlen(token);
38 if (toklen == strlen(token) && !strncmp(*line, token, toklen)) {
45 static char *demangle_string(char *string)
48 const char mapfrom[] = "abfnrtv";
49 const char mapto[] = "\a\b\f\n\r\t\v";
51 if (!strchr(string, '"'))
53 string = strchr(string, '"') + 1;
54 if (!strrchr(string, '"'))
56 *strrchr(string, '"') = '\0';
58 for (i = 0; i < strlen(string); i++) {
59 if (string[i] == '\\') {
62 const char *p = strchr(mapfrom, string[i+1]);
64 repl = mapto[p - mapfrom];
66 } else if (strlen(string+i+1) >= 3) {
67 if (string[i+1] == 'x') {
68 repl = (string[i+2]-'0')*16
71 } else if (cisdigit(string[i+1])) {
72 repl = (string[i+2]-'0')*8*8
84 memmove(string + i + 1, string + i + len + 1,
85 strlen(string + i + len + 1) + 1);
92 char *read_config_header(const char *ccan_dir,
93 const char **compiler, const char **cflags,
96 char *fname = talloc_asprintf(NULL, "%s/config.h", ccan_dir);
101 config_header = grab_file(NULL, fname, NULL);
107 lines = strsplit(config_header, config_header, "\n");
108 for (i = 0; i < talloc_array_length(lines) - 1; i++) {
110 const char **line = (const char **)&lines[i];
112 if (!get_token(line, "#"))
114 if (!get_token(line, "define"))
116 sym = get_symbol_token(lines, line);
117 if (streq(sym, "CCAN_COMPILER") && !compiler) {
118 *compiler = demangle_string(lines[i]);
120 errx(1, "%s:%u:could not parse CCAN_COMPILER",
123 printf("%s: compiler set to '%s'\n",
125 } else if (streq(sym, "CCAN_CFLAGS") && !cflags) {
126 *cflags = demangle_string(lines[i]);
128 errx(1, "%s:%u:could not parse CCAN_CFLAGS",
131 printf("%s: compiler flags set to '%s'\n",
138 *compiler = CCAN_COMPILER;
140 *cflags = CCAN_CFLAGS;
142 return config_header;