config.h: HAVE_ASPRINTF
[ccan] / tools / configurator / configurator.c
1 /* Simple tool to create config.h.
2  * Would be much easier with ccan modules, but deliberately standalone. */
3 #include <stdio.h>
4 #include <stdbool.h>
5 #include <stdlib.h>
6 #include <unistd.h>
7 #include <err.h>
8 #include <sys/types.h>
9 #include <sys/wait.h>
10 #include <sys/stat.h>
11 #include <fcntl.h>
12 #include <string.h>
13
14 #define DEFAULT_COMPILER "cc"
15 #define DEFAULT_FLAGS "-g -Wall -Wundef -Wmissing-prototypes -Wmissing-declarations -Wstrict-prototypes -Wold-style-definition"
16
17 #define OUTPUT_FILE "configurator.out"
18 #define INPUT_FILE "configuratortest.c"
19
20 static int verbose;
21
22 enum test_style {
23         EXECUTE,
24         OUTSIDE_MAIN,
25         DEFINES_FUNC,
26         INSIDE_MAIN
27 };
28
29 struct test {
30         const char *name;
31         enum test_style style;
32         const char *depends;
33         const char *fragment;
34         bool done;
35         bool answer;
36 };
37
38 static struct test tests[] = {
39         { "HAVE_ALIGNOF", INSIDE_MAIN, NULL,
40           "return __alignof__(double) > 0 ? 0 : 1;" },
41         { "HAVE_ASPRINTF", DEFINES_FUNC, NULL,
42           "#define _GNU_SOURCE\n"
43           "#include <stdio.h>\n"
44           "static char *func(int x) {"
45           "     char *p;\n"
46           "     if (asprintf(&p, \"%u\", x) == -1) p = NULL;"
47           "     return p;\n"
48           "}" },
49         { "HAVE_ATTRIBUTE_COLD", DEFINES_FUNC, NULL,
50           "static int __attribute__((cold)) func(int x) { return x; }" },
51         { "HAVE_ATTRIBUTE_CONST", DEFINES_FUNC, NULL,
52           "static int __attribute__((const)) func(int x) { return x; }" },
53         { "HAVE_ATTRIBUTE_MAY_ALIAS", OUTSIDE_MAIN, NULL,
54           "typedef short __attribute__((__may_alias__)) short_a;" },
55         { "HAVE_ATTRIBUTE_NORETURN", DEFINES_FUNC, NULL,
56           "#include <stdlib.h>\n"
57           "static void __attribute__((noreturn)) func(int x) { exit(x); }" },
58         { "HAVE_ATTRIBUTE_PRINTF", DEFINES_FUNC, NULL,
59           "static void __attribute__((format(__printf__, 1, 2))) func(const char *fmt, ...) { }" },
60         { "HAVE_ATTRIBUTE_UNUSED", OUTSIDE_MAIN, NULL,
61           "static int __attribute__((unused)) func(int x) { return x; }" },
62         { "HAVE_ATTRIBUTE_USED", OUTSIDE_MAIN, NULL,
63           "static int __attribute__((used)) func(int x) { return x; }" },
64         { "HAVE_BIG_ENDIAN", EXECUTE, NULL,
65           "union { int i; char c[sizeof(int)]; } u;\n"
66           "u.i = 0x01020304;\n"
67           "return u.c[0] == 0x01 && u.c[1] == 0x02 && u.c[2] == 0x03 && u.c[3] == 0x04 ? 0 : 1;" },
68         { "HAVE_BSWAP_64", DEFINES_FUNC, "HAVE_BYTESWAP_H",
69           "#include <byteswap.h>\n"
70           "static int func(int x) { return bswap_64(x); }" },
71         { "HAVE_BUILTIN_CHOOSE_EXPR", INSIDE_MAIN, NULL,
72           "return __builtin_choose_expr(1, 0, \"garbage\");" },
73         { "HAVE_BUILTIN_CLZ", INSIDE_MAIN, NULL,
74           "return __builtin_clz(1) == (sizeof(int)*8 - 1) ? 0 : 1;" },
75         { "HAVE_BUILTIN_CLZL", INSIDE_MAIN, NULL,
76           "return __builtin_clzl(1) == (sizeof(long)*8 - 1) ? 0 : 1;" },
77         { "HAVE_BUILTIN_CLZLL", INSIDE_MAIN, NULL,
78           "return __builtin_clzll(1) == (sizeof(long long)*8 - 1) ? 0 : 1;" },
79         { "HAVE_BUILTIN_CONSTANT_P", INSIDE_MAIN, NULL,
80           "return __builtin_constant_p(1) ? 0 : 1;" },
81         { "HAVE_BUILTIN_EXPECT", INSIDE_MAIN, NULL,
82           "return __builtin_expect(argc == 1, 1) ? 0 : 1;" },
83         { "HAVE_BUILTIN_FFSL", INSIDE_MAIN, NULL,
84           "return __builtin_ffsl(0L) == 0 ? 0 : 1;" },
85         { "HAVE_BUILTIN_FFSLL", INSIDE_MAIN, NULL,
86           "return __builtin_ffsll(0LL) == 0 ? 0 : 1;" },
87         { "HAVE_BUILTIN_POPCOUNTL", INSIDE_MAIN, NULL,
88           "return __builtin_popcountl(255L) == 8 ? 0 : 1;" },
89         { "HAVE_BUILTIN_TYPES_COMPATIBLE_P", INSIDE_MAIN, NULL,
90           "return __builtin_types_compatible_p(char *, int) ? 1 : 0;" },
91         { "HAVE_BYTESWAP_H", OUTSIDE_MAIN, NULL,
92           "#include <byteswap.h>\n" },
93         { "HAVE_COMPOUND_LITERALS", INSIDE_MAIN, NULL,
94           "char **foo = (char *[]) { \"x\", \"y\", \"z\" };\n"
95           "return foo[0] ? 0 : 1;" },
96         { "HAVE_FOR_LOOP_DECLARATION", INSIDE_MAIN, NULL,
97           "for (int i = 0; i < argc; i++) { return 0; };\n"
98           "return 1;" },
99         { "HAVE_FLEXIBLE_ARRAY_MEMBER", OUTSIDE_MAIN, NULL,
100           "struct foo { unsigned int x; int arr[]; };" },
101         { "HAVE_GETPAGESIZE", DEFINES_FUNC, NULL,
102           "#include <unistd.h>\n"
103           "static int func(void) { return getpagesize(); }" },
104         { "HAVE_LITTLE_ENDIAN", EXECUTE, NULL,
105           "union { int i; char c[sizeof(int)]; } u;\n"
106           "u.i = 0x01020304;\n"
107           "return u.c[0] == 0x04 && u.c[1] == 0x03 && u.c[2] == 0x02 && u.c[3] == 0x01 ? 0 : 1;" },
108         { "HAVE_MMAP", DEFINES_FUNC, NULL,
109           "#include <sys/mman.h>\n"
110           "static void *func(int fd) {\n"
111           "     return mmap(0, 65536, PROT_READ, MAP_SHARED, fd, 0);\n"
112           "}" },
113         { "HAVE_NESTED_FUNCTIONS", DEFINES_FUNC, NULL,
114           "static int func(int val) {\n"
115           "     auto void add(int val2);\n"
116           "     void add(int val2) { val += val2; }\n"
117           "     add(7);\n"
118           "     return val;\n"
119           "}" },
120         { "HAVE_STATEMENT_EXPR", INSIDE_MAIN, NULL,
121           "return ({ int x = argc; x == argc ? 0 : 1; });" },
122         { "HAVE_TYPEOF", INSIDE_MAIN, NULL,
123           "__typeof__(argc) i; i = argc; return i == argc ? 0 : 1;" },
124         { "HAVE_UTIME", DEFINES_FUNC, NULL,
125           "#include <sys/types.h>\n"
126           "#include <utime.h>\n"
127           "static int func(const char *filename) {\n"
128           "     struct utimbuf times = { 0 };\n"
129           "     return utime(filename, &times);\n"
130           "}" },
131         { "HAVE_WARN_UNUSED_RESULT", DEFINES_FUNC, NULL,
132           "#include <sys/types.h>\n"
133           "#include <utime.h>\n"
134           "static __attribute__((warn_unused_result)) int func(int i) {\n"
135           "     return i + 1;\n"
136           "}" },
137 };
138
139 static char *grab_fd(int fd)
140 {
141         int ret;
142         size_t max, size = 0;
143         char *buffer;
144
145         max = 16384;
146         buffer = malloc(max+1);
147         while ((ret = read(fd, buffer + size, max - size)) > 0) {
148                 size += ret;
149                 if (size == max)
150                         buffer = realloc(buffer, max *= 2);
151         }
152         if (ret < 0)
153                 err(1, "reading from command");
154         buffer[size] = '\0';
155         return buffer;
156 }
157
158 static char *run(const char *cmd, int *exitstatus)
159 {
160         pid_t pid;
161         int p[2];
162         char *ret;
163         int status;
164
165         if (pipe(p) != 0)
166                 err(1, "creating pipe");
167
168         pid = fork();
169         if (pid == -1)
170                 err(1, "forking");
171
172         if (pid == 0) {
173                 if (dup2(p[1], STDOUT_FILENO) != STDOUT_FILENO
174                     || dup2(p[1], STDERR_FILENO) != STDERR_FILENO
175                     || close(p[0]) != 0
176                     || close(STDIN_FILENO) != 0
177                     || open("/dev/null", O_RDONLY) != STDIN_FILENO)
178                         exit(128);
179
180                 status = system(cmd);
181                 if (WIFEXITED(status))
182                         exit(WEXITSTATUS(status));
183                 /* Here's a hint... */
184                 exit(128 + WTERMSIG(status));
185         }
186
187         close(p[1]);
188         ret = grab_fd(p[0]);
189         /* This shouldn't fail... */
190         if (waitpid(pid, &status, 0) != pid)
191                 err(1, "Failed to wait for child");
192         close(p[0]);
193         if (WIFEXITED(status))
194                 *exitstatus = WEXITSTATUS(status);
195         else
196                 *exitstatus = -WTERMSIG(status);
197         return ret;
198 }
199
200 static char *connect_args(char *argv[], const char *extra)
201 {
202         unsigned int i, len = strlen(extra) + 1;
203         char *ret;
204
205         for (i = 1; argv[i]; i++)
206                 len += 1 + strlen(argv[i]);
207
208         ret = malloc(len);
209         len = 0;
210         for (i = 1; argv[i]; i++) {
211                 strcpy(ret + len, argv[i]);
212                 len += strlen(argv[i]);
213                 ret[len++] = ' ';
214         }
215         strcpy(ret + len, extra);
216         return ret;
217 }
218
219 static struct test *find_test(const char *name)
220 {
221         unsigned int i;
222
223         for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) {
224                 if (strcmp(tests[i].name, name) == 0)
225                         return &tests[i];
226         }
227         abort();
228 }
229
230 #define PRE_BOILERPLATE "/* Test program generated by configurator. */\n"
231 #define MAIN_START_BOILERPLATE "int main(int argc, char *argv[]) {\n"
232 #define USE_FUNC_BOILERPLATE "(void)func;\n"
233 #define MAIN_BODY_BOILERPLATE "return 0;\n"
234 #define MAIN_END_BOILERPLATE "}\n"
235
236 static bool run_test(const char *cmd, struct test *test)
237 {
238         char *output;
239         FILE *outf;
240         int status;
241
242         if (test->done)
243                 return test->answer;
244
245         if (test->depends && !run_test(cmd, find_test(test->depends))) {
246                 test->answer = false;
247                 test->done = true;
248                 return test->answer;
249         }
250
251         outf = fopen(INPUT_FILE, "w");
252         if (!outf)
253                 err(1, "creating %s", INPUT_FILE);
254
255         fprintf(outf, "%s", PRE_BOILERPLATE);
256         switch (test->style) {
257         case EXECUTE:
258         case INSIDE_MAIN:
259                 fprintf(outf, "%s", MAIN_START_BOILERPLATE);
260                 fprintf(outf, "%s", test->fragment);
261                 fprintf(outf, "%s", MAIN_END_BOILERPLATE);
262                 break;
263         case OUTSIDE_MAIN:
264                 fprintf(outf, "%s", test->fragment);
265                 fprintf(outf, "%s", MAIN_START_BOILERPLATE);
266                 fprintf(outf, "%s", MAIN_BODY_BOILERPLATE);
267                 fprintf(outf, "%s", MAIN_END_BOILERPLATE);
268                 break;
269         case DEFINES_FUNC:
270                 fprintf(outf, "%s", test->fragment);
271                 fprintf(outf, "%s", MAIN_START_BOILERPLATE);
272                 fprintf(outf, "%s", USE_FUNC_BOILERPLATE);
273                 fprintf(outf, "%s", MAIN_BODY_BOILERPLATE);
274                 fprintf(outf, "%s", MAIN_END_BOILERPLATE);
275                 break;
276         }
277         fclose(outf);
278
279         if (verbose > 1)
280                 if (system("cat " INPUT_FILE) == -1);
281
282         output = run(cmd, &status);
283         if (status != 0 || strstr(output, "warning")) {
284                 if (verbose)
285                         printf("Compile %s for %s, status %i: %s\n",
286                                status ? "fail" : "warning",
287                                test->name, status, output);
288                 if (test->style == EXECUTE)
289                         errx(1, "Test for %s did not compile:\n%s",
290                              test->name, output);
291                 test->answer = false;
292                 free(output);
293         } else {
294                 /* Compile succeeded. */
295                 free(output);
296                 /* We run INSIDE_MAIN tests for sanity checking. */
297                 if (test->style == EXECUTE || test->style == INSIDE_MAIN) {
298                         output = run("./" OUTPUT_FILE, &status);
299                         if (test->style == INSIDE_MAIN && status != 0)
300                                 errx(1, "Test for %s failed with %i:\n%s",
301                                      test->name, status, output);
302                         if (verbose && status)
303                                 printf("%s exited %i\n", test->name, status);
304                         free(output);
305                 }
306                 test->answer = (status == 0);
307         }
308         test->done = true;
309         return test->answer;
310 }
311
312 int main(int argc, char *argv[])
313 {
314         char *cmd;
315         char *default_args[] = { "", DEFAULT_COMPILER, DEFAULT_FLAGS, NULL };
316         unsigned int i;
317
318         if (argc > 1) {
319                 if (strcmp(argv[1], "--help") == 0) {
320                         printf("Usage: configurator [-v] [<compiler> <flags>...]\n"
321                                "  <compiler> <flags> will have \"-o <outfile> <infile.c>\" appended\n"
322                                "Default: %s %s\n",
323                                DEFAULT_COMPILER, DEFAULT_FLAGS);
324                         exit(0);
325                 }
326                 if (strcmp(argv[1], "-v") == 0) {
327                         argc--;
328                         argv++;
329                         verbose = 1;
330                 } else if (strcmp(argv[1], "-vv") == 0) {
331                         argc--;
332                         argv++;
333                         verbose = 2;
334                 }
335         }
336
337         if (argc == 1)
338                 argv = default_args;
339
340         cmd = connect_args(argv, "-o " OUTPUT_FILE " " INPUT_FILE);
341         for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++)
342                 run_test(cmd, &tests[i]);
343
344         unlink(OUTPUT_FILE);
345         unlink(INPUT_FILE);
346
347         cmd[strlen(cmd) - strlen(" -o " OUTPUT_FILE " " INPUT_FILE)] = '\0';
348         printf("/* Generated by CCAN configurator */\n"
349                "#ifndef CCAN_CONFIG_H\n"
350                "#define CCAN_CONFIG_H\n");
351         printf("#define _GNU_SOURCE /* Always use GNU extensions. */\n");
352         printf("#define CCAN_COMPILER \"%s\"\n", argv[1]);
353         printf("#define CCAN_CFLAGS \"%s\"\n\n", cmd + strlen(argv[1]) + 1);
354         for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++)
355                 printf("#define %s %u\n", tests[i].name, tests[i].answer);
356         printf("#endif /* CCAN_CONFIG_H */\n");
357         return 0;
358 }