1 #include <ccan/err/err.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"
9 /* Get an identifier token. */
10 char *get_symbol_token(void *ctx, const char **line)
15 *line += strspn(*line, " \t");
16 toklen = strspn(*line, IDENT_CHARS);
19 ret = talloc_strndup(ctx, *line, toklen);
24 /* Get token if it's equal to token. */
25 bool get_token(const char **line, const char *token)
29 *line += strspn(*line, " \t");
30 if (cisalnum(token[0]) || token[0] == '_')
31 toklen = strspn(*line, IDENT_CHARS);
33 /* FIXME: real tokenizer handles ++ and other multi-chars. */
34 toklen = strlen(token);
37 if (toklen == strlen(token) && !strncmp(*line, token, toklen)) {
44 static char *demangle_string(char *string)
47 const char mapfrom[] = "abfnrtv";
48 const char mapto[] = "\a\b\f\n\r\t\v";
50 if (!strchr(string, '"'))
52 string = strchr(string, '"') + 1;
53 if (!strrchr(string, '"'))
55 *strrchr(string, '"') = '\0';
57 for (i = 0; i < strlen(string); i++) {
58 if (string[i] == '\\') {
61 const char *p = strchr(mapfrom, string[i+1]);
63 repl = mapto[p - mapfrom];
65 } else if (strlen(string+i+1) >= 3) {
66 if (string[i+1] == 'x') {
67 repl = (string[i+2]-'0')*16
70 } else if (cisdigit(string[i+1])) {
71 repl = (string[i+2]-'0')*8*8
83 memmove(string + i + 1, string + i + len + 1,
84 strlen(string + i + len + 1) + 1);
91 char *read_config_header(const char *ccan_dir,
92 const char **compiler, const char **cflags,
95 char *fname = talloc_asprintf(NULL, "%s/config.h", ccan_dir);
100 config_header = talloc_grab_file(NULL, fname, NULL);
106 lines = strsplit(config_header, config_header, "\n");
107 for (i = 0; i < talloc_array_length(lines) - 1; i++) {
109 const char **line = (const char **)&lines[i];
111 if (!get_token(line, "#"))
113 if (!get_token(line, "define"))
115 sym = get_symbol_token(lines, line);
116 if (streq(sym, "CCAN_COMPILER") && !compiler) {
117 *compiler = demangle_string(lines[i]);
119 errx(1, "%s:%u:could not parse CCAN_COMPILER",
122 printf("%s: compiler set to '%s'\n",
124 } else if (streq(sym, "CCAN_CFLAGS") && !cflags) {
125 *cflags = demangle_string(lines[i]);
127 errx(1, "%s:%u:could not parse CCAN_CFLAGS",
130 printf("%s: compiler flags set to '%s'\n",
137 *compiler = CCAN_COMPILER;
139 *cflags = CCAN_CFLAGS;
141 return config_header;