configurator: add library testing
[ccan] / tools / configurator / configurator.c
1 /* Simple tool to create config.h.
2  * Would be much easier with ccan modules, but deliberately standalone.
3  *
4  * Copyright 2011 Rusty Russell <rusty@rustcorp.com.au>.  MIT license.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 #include <stdio.h>
25 #include <stdbool.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <err.h>
29 #include <sys/types.h>
30 #include <sys/wait.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 #include <string.h>
34
35 #define DEFAULT_COMPILER "cc"
36 #define DEFAULT_FLAGS "-g3 -ggdb -Wall -Wundef -Wmissing-prototypes -Wmissing-declarations -Wstrict-prototypes -Wold-style-definition"
37
38 #define OUTPUT_FILE "configurator.out"
39 #define INPUT_FILE "configuratortest.c"
40
41 static int verbose;
42
43 enum test_style {
44         OUTSIDE_MAIN            = 0x1,
45         DEFINES_FUNC            = 0x2,
46         INSIDE_MAIN             = 0x4,
47         DEFINES_EVERYTHING      = 0x8,
48         MAY_NOT_COMPILE         = 0x10,
49         EXECUTE                 = 0x8000
50 };
51
52 struct test {
53         const char *name;
54         enum test_style style;
55         const char *depends;
56         const char *link;
57         const char *fragment;
58         bool done;
59         bool answer;
60 };
61
62 static struct test tests[] = {
63         { "HAVE_32BIT_OFF_T", DEFINES_EVERYTHING|EXECUTE, NULL, NULL,
64           "#include <sys/types.h>\n"
65           "int main(int argc, char *argv[]) {\n"
66           "     return sizeof(off_t) == 4 ? 0 : 1;\n"
67           "}\n" },
68         { "HAVE_ALIGNOF", INSIDE_MAIN, NULL, NULL,
69           "return __alignof__(double) > 0 ? 0 : 1;" },
70         { "HAVE_ASPRINTF", DEFINES_FUNC, NULL, NULL,
71           "#define _GNU_SOURCE\n"
72           "#include <stdio.h>\n"
73           "static char *func(int x) {"
74           "     char *p;\n"
75           "     if (asprintf(&p, \"%u\", x) == -1) p = NULL;"
76           "     return p;\n"
77           "}" },
78         { "HAVE_ATTRIBUTE_COLD", DEFINES_FUNC, NULL, NULL,
79           "static int __attribute__((cold)) func(int x) { return x; }" },
80         { "HAVE_ATTRIBUTE_CONST", DEFINES_FUNC, NULL, NULL,
81           "static int __attribute__((const)) func(int x) { return x; }" },
82         { "HAVE_ATTRIBUTE_MAY_ALIAS", OUTSIDE_MAIN, NULL, NULL,
83           "typedef short __attribute__((__may_alias__)) short_a;" },
84         { "HAVE_ATTRIBUTE_NORETURN", DEFINES_FUNC, NULL, NULL,
85           "#include <stdlib.h>\n"
86           "static void __attribute__((noreturn)) func(int x) { exit(x); }" },
87         { "HAVE_ATTRIBUTE_PRINTF", DEFINES_FUNC, NULL, NULL,
88           "static void __attribute__((format(__printf__, 1, 2))) func(const char *fmt, ...) { }" },
89         { "HAVE_ATTRIBUTE_UNUSED", OUTSIDE_MAIN, NULL, NULL,
90           "static int __attribute__((unused)) func(int x) { return x; }" },
91         { "HAVE_ATTRIBUTE_USED", OUTSIDE_MAIN, NULL, NULL,
92           "static int __attribute__((used)) func(int x) { return x; }" },
93         { "HAVE_BACKTRACE", DEFINES_FUNC, NULL, NULL,
94           "#include <execinfo.h>\n"
95           "static int func(int x) {"
96           "     void *bt[10];\n"
97           "     return backtrace(bt, 10) < x;\n"
98           "}" },
99         { "HAVE_BIG_ENDIAN", INSIDE_MAIN|EXECUTE, NULL, NULL,
100           "union { int i; char c[sizeof(int)]; } u;\n"
101           "u.i = 0x01020304;\n"
102           "return u.c[0] == 0x01 && u.c[1] == 0x02 && u.c[2] == 0x03 && u.c[3] == 0x04 ? 0 : 1;" },
103         { "HAVE_BSWAP_64", DEFINES_FUNC, "HAVE_BYTESWAP_H", NULL,
104           "#include <byteswap.h>\n"
105           "static int func(int x) { return bswap_64(x); }" },
106         { "HAVE_BUILTIN_CHOOSE_EXPR", INSIDE_MAIN, NULL, NULL,
107           "return __builtin_choose_expr(1, 0, \"garbage\");" },
108         { "HAVE_BUILTIN_CLZ", INSIDE_MAIN, NULL, NULL,
109           "return __builtin_clz(1) == (sizeof(int)*8 - 1) ? 0 : 1;" },
110         { "HAVE_BUILTIN_CLZL", INSIDE_MAIN, NULL, NULL,
111           "return __builtin_clzl(1) == (sizeof(long)*8 - 1) ? 0 : 1;" },
112         { "HAVE_BUILTIN_CLZLL", INSIDE_MAIN, NULL, NULL,
113           "return __builtin_clzll(1) == (sizeof(long long)*8 - 1) ? 0 : 1;" },
114         { "HAVE_BUILTIN_CONSTANT_P", INSIDE_MAIN, NULL, NULL,
115           "return __builtin_constant_p(1) ? 0 : 1;" },
116         { "HAVE_BUILTIN_EXPECT", INSIDE_MAIN, NULL, NULL,
117           "return __builtin_expect(argc == 1, 1) ? 0 : 1;" },
118         { "HAVE_BUILTIN_FFSL", INSIDE_MAIN, NULL, NULL,
119           "return __builtin_ffsl(0L) == 0 ? 0 : 1;" },
120         { "HAVE_BUILTIN_FFSLL", INSIDE_MAIN, NULL, NULL,
121           "return __builtin_ffsll(0LL) == 0 ? 0 : 1;" },
122         { "HAVE_BUILTIN_POPCOUNTL", INSIDE_MAIN, NULL, NULL,
123           "return __builtin_popcountl(255L) == 8 ? 0 : 1;" },
124         { "HAVE_BUILTIN_TYPES_COMPATIBLE_P", INSIDE_MAIN, NULL, NULL,
125           "return __builtin_types_compatible_p(char *, int) ? 1 : 0;" },
126         { "HAVE_BYTESWAP_H", OUTSIDE_MAIN, NULL, NULL,
127           "#include <byteswap.h>\n" },
128         { "HAVE_CLOCK_GETTIME",
129           DEFINES_FUNC, "HAVE_STRUCT_TIMESPEC", NULL,
130           "#include <time.h>\n"
131           "static struct timespec func(void) {\n"
132           "     struct timespec ts;\n"
133           "     clock_gettime(CLOCK_REALTIME, &ts);\n"
134           "     return ts;\n"
135           "}\n" },
136         { "HAVE_CLOCK_GETTIME_IN_LIBRT",
137           DEFINES_FUNC,
138           "HAVE_STRUCT_TIMESPEC !HAVE_CLOCK_GETTIME",
139           "-lrt",
140           "#include <time.h>\n"
141           "static struct timespec func(void) {\n"
142           "     struct timespec ts;\n"
143           "     clock_gettime(CLOCK_REALTIME, &ts);\n"
144           "     return ts;\n"
145           "}\n" },
146         { "HAVE_COMPOUND_LITERALS", INSIDE_MAIN, NULL, NULL,
147           "int *foo = (int[]) { 1, 2, 3, 4 };\n"
148           "return foo[0] ? 0 : 1;" },
149         { "HAVE_ERR_H", DEFINES_FUNC, NULL, NULL,
150           "#include <err.h>\n"
151           "static void func(int arg) {\n"
152           "     if (arg == 0)\n"
153           "             err(1, \"err %u\", arg);\n"
154           "     if (arg == 1)\n"
155           "             errx(1, \"err %u\", arg);\n"
156           "     if (arg == 3)\n"
157           "             warn(\"warn %u\", arg);\n"
158           "     if (arg == 4)\n"
159           "             warnx(\"warn %u\", arg);\n"
160           "}\n" },
161         { "HAVE_FILE_OFFSET_BITS", DEFINES_EVERYTHING|EXECUTE,
162           "HAVE_32BIT_OFF_T", NULL,
163           "#define _FILE_OFFSET_BITS 64\n"
164           "#include <sys/types.h>\n"
165           "int main(int argc, char *argv[]) {\n"
166           "     return sizeof(off_t) == 8 ? 0 : 1;\n"
167           "}\n" },
168         { "HAVE_FOR_LOOP_DECLARATION", INSIDE_MAIN, NULL, NULL,
169           "for (int i = 0; i < argc; i++) { return 0; };\n"
170           "return 1;" },
171         { "HAVE_FLEXIBLE_ARRAY_MEMBER", OUTSIDE_MAIN, NULL, NULL,
172           "struct foo { unsigned int x; int arr[]; };" },
173         { "HAVE_GETPAGESIZE", DEFINES_FUNC, NULL, NULL,
174           "#include <unistd.h>\n"
175           "static int func(void) { return getpagesize(); }" },
176         { "HAVE_ISBLANK", DEFINES_FUNC, NULL, NULL,
177           "#define _GNU_SOURCE\n"
178           "#include <ctype.h>\n"
179           "static int func(void) { return isblank(' '); }" },
180         { "HAVE_LITTLE_ENDIAN", INSIDE_MAIN|EXECUTE, NULL, NULL,
181           "union { int i; char c[sizeof(int)]; } u;\n"
182           "u.i = 0x01020304;\n"
183           "return u.c[0] == 0x04 && u.c[1] == 0x03 && u.c[2] == 0x02 && u.c[3] == 0x01 ? 0 : 1;" },
184         { "HAVE_MEMMEM", DEFINES_FUNC, NULL, NULL,
185           "#define _GNU_SOURCE\n"
186           "#include <string.h>\n"
187           "static void *func(void *h, size_t hl, void *n, size_t nl) {\n"
188           "return memmem(h, hl, n, nl);"
189           "}\n", },
190         { "HAVE_MMAP", DEFINES_FUNC, NULL, NULL,
191           "#include <sys/mman.h>\n"
192           "static void *func(int fd) {\n"
193           "     return mmap(0, 65536, PROT_READ, MAP_SHARED, fd, 0);\n"
194           "}" },
195         { "HAVE_PROC_SELF_MAPS", DEFINES_EVERYTHING|EXECUTE, NULL, NULL,
196           "#include <sys/types.h>\n"
197           "#include <sys/stat.h>\n"
198           "#include <fcntl.h>\n"
199           "int main(void) {\n"
200           "     return open(\"/proc/self/maps\", O_RDONLY) != -1 ? 0 : 1;\n"
201           "}\n" },
202         { "HAVE_QSORT_R_PRIVATE_LAST",
203           DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE, NULL, NULL,
204           "#define _GNU_SOURCE 1\n"
205           "#include <stdlib.h>\n"
206           "static int cmp(const void *lp, const void *rp, void *priv) {\n"
207           " *(unsigned int *)priv = 1;\n"
208           " return *(const int *)lp - *(const int *)rp; }\n"
209           "int main(void) {\n"
210           " int array[] = { 9, 2, 5 };\n"
211           " unsigned int called = 0;\n"
212           " qsort_r(array, 3, sizeof(int), cmp, &called);\n"
213           " return called && array[0] == 2 && array[1] == 5 && array[2] == 9 ? 0 : 1;\n"
214           "}\n" },
215         { "HAVE_STRUCT_TIMESPEC",
216           DEFINES_FUNC, NULL, NULL,
217           "#include <time.h>\n"
218           "static void func(void) {\n"
219           "     struct timespec ts;\n"
220           "     ts.tv_sec = ts.tv_nsec = 1;\n"
221           "}\n" },
222         { "HAVE_SECTION_START_STOP",
223           DEFINES_FUNC, NULL, NULL,
224           "static void *__attribute__((__section__(\"mysec\"))) p = &p;\n"
225           "static int func(void) {\n"
226           "     extern void *__start_mysec[], *__stop_mysec[];\n"
227           "     return __stop_mysec - __start_mysec;\n"
228           "}\n" },
229         { "HAVE_STACK_GROWS_UPWARDS", DEFINES_EVERYTHING|EXECUTE, NULL, NULL,
230           "static long nest(const void *base, unsigned int i)\n"
231           "{\n"
232           "     if (i == 0)\n"
233           "             return (const char *)&i - (const char *)base;\n"
234           "     return nest(base, i-1);\n"
235           "}\n"
236           "int main(int argc, char *argv[]) {\n"
237           "     return (nest(&argc, argc) > 0) ? 0 : 1\n;"
238           "}\n" },
239         { "HAVE_STATEMENT_EXPR", INSIDE_MAIN, NULL, NULL,
240           "return ({ int x = argc; x == argc ? 0 : 1; });" },
241         { "HAVE_SYS_FILIO_H", OUTSIDE_MAIN, NULL, NULL, /* Solaris needs this for FIONREAD */
242           "#include <sys/filio.h>\n" },
243         { "HAVE_TYPEOF", INSIDE_MAIN, NULL, NULL,
244           "__typeof__(argc) i; i = argc; return i == argc ? 0 : 1;" },
245         { "HAVE_UTIME", DEFINES_FUNC, NULL, NULL,
246           "#include <sys/types.h>\n"
247           "#include <utime.h>\n"
248           "static int func(const char *filename) {\n"
249           "     struct utimbuf times = { 0 };\n"
250           "     return utime(filename, &times);\n"
251           "}" },
252         { "HAVE_WARN_UNUSED_RESULT", DEFINES_FUNC, NULL, NULL,
253           "#include <sys/types.h>\n"
254           "#include <utime.h>\n"
255           "static __attribute__((warn_unused_result)) int func(int i) {\n"
256           "     return i + 1;\n"
257           "}" },
258 };
259
260 static char *grab_fd(int fd)
261 {
262         int ret;
263         size_t max, size = 0;
264         char *buffer;
265
266         max = 16384;
267         buffer = malloc(max+1);
268         while ((ret = read(fd, buffer + size, max - size)) > 0) {
269                 size += ret;
270                 if (size == max)
271                         buffer = realloc(buffer, max *= 2);
272         }
273         if (ret < 0)
274                 err(1, "reading from command");
275         buffer[size] = '\0';
276         return buffer;
277 }
278
279 static char *run(const char *cmd, int *exitstatus)
280 {
281         pid_t pid;
282         int p[2];
283         char *ret;
284         int status;
285
286         if (pipe(p) != 0)
287                 err(1, "creating pipe");
288
289         pid = fork();
290         if (pid == -1)
291                 err(1, "forking");
292
293         if (pid == 0) {
294                 if (dup2(p[1], STDOUT_FILENO) != STDOUT_FILENO
295                     || dup2(p[1], STDERR_FILENO) != STDERR_FILENO
296                     || close(p[0]) != 0
297                     || close(STDIN_FILENO) != 0
298                     || open("/dev/null", O_RDONLY) != STDIN_FILENO)
299                         exit(128);
300
301                 status = system(cmd);
302                 if (WIFEXITED(status))
303                         exit(WEXITSTATUS(status));
304                 /* Here's a hint... */
305                 exit(128 + WTERMSIG(status));
306         }
307
308         close(p[1]);
309         ret = grab_fd(p[0]);
310         /* This shouldn't fail... */
311         if (waitpid(pid, &status, 0) != pid)
312                 err(1, "Failed to wait for child");
313         close(p[0]);
314         if (WIFEXITED(status))
315                 *exitstatus = WEXITSTATUS(status);
316         else
317                 *exitstatus = -WTERMSIG(status);
318         return ret;
319 }
320
321 static char *connect_args(const char *argv[], const char *extra)
322 {
323         unsigned int i, len = strlen(extra) + 1;
324         char *ret;
325
326         for (i = 1; argv[i]; i++)
327                 len += 1 + strlen(argv[i]);
328
329         ret = malloc(len);
330         len = 0;
331         for (i = 1; argv[i]; i++) {
332                 strcpy(ret + len, argv[i]);
333                 len += strlen(argv[i]);
334                 ret[len++] = ' ';
335         }
336         strcpy(ret + len, extra);
337         return ret;
338 }
339
340 static struct test *find_test(const char *name)
341 {
342         unsigned int i;
343
344         for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) {
345                 if (strcmp(tests[i].name, name) == 0)
346                         return &tests[i];
347         }
348         abort();
349 }
350
351 #define PRE_BOILERPLATE "/* Test program generated by configurator. */\n"
352 #define MAIN_START_BOILERPLATE "int main(int argc, char *argv[]) {\n"
353 #define USE_FUNC_BOILERPLATE "(void)func;\n"
354 #define MAIN_BODY_BOILERPLATE "return 0;\n"
355 #define MAIN_END_BOILERPLATE "}\n"
356
357 static bool run_test(const char *cmd, struct test *test)
358 {
359         char *output;
360         FILE *outf;
361         int status;
362
363         if (test->done)
364                 return test->answer;
365
366         if (test->depends) {
367                 size_t len;
368                 const char *deps = test->depends;
369                 char *dep;
370
371                 /* Space-separated dependencies, could be ! for inverse. */
372                 while ((len = strcspn(deps, " "))) {
373                         bool positive = true;
374                         if (deps[len]) {
375                                 dep = strdup(deps);
376                                 dep[len] = '\0';
377                         } else {
378                                 dep = (char *)deps;
379                         }
380
381                         if (dep[0] == '!') {
382                                 dep++;
383                                 positive = false;
384                         }
385                         if (run_test(cmd, find_test(dep)) != positive) {
386                                 test->answer = false;
387                                 test->done = true;
388                                 return test->answer;
389                         }
390                         deps += len;
391                         deps += strspn(deps, " ");
392                 }
393         }
394
395         outf = fopen(INPUT_FILE, "w");
396         if (!outf)
397                 err(1, "creating %s", INPUT_FILE);
398
399         fprintf(outf, "%s", PRE_BOILERPLATE);
400         switch (test->style & ~(EXECUTE|MAY_NOT_COMPILE)) {
401         case INSIDE_MAIN:
402                 fprintf(outf, "%s", MAIN_START_BOILERPLATE);
403                 fprintf(outf, "%s", test->fragment);
404                 fprintf(outf, "%s", MAIN_END_BOILERPLATE);
405                 break;
406         case OUTSIDE_MAIN:
407                 fprintf(outf, "%s", test->fragment);
408                 fprintf(outf, "%s", MAIN_START_BOILERPLATE);
409                 fprintf(outf, "%s", MAIN_BODY_BOILERPLATE);
410                 fprintf(outf, "%s", MAIN_END_BOILERPLATE);
411                 break;
412         case DEFINES_FUNC:
413                 fprintf(outf, "%s", test->fragment);
414                 fprintf(outf, "%s", MAIN_START_BOILERPLATE);
415                 fprintf(outf, "%s", USE_FUNC_BOILERPLATE);
416                 fprintf(outf, "%s", MAIN_BODY_BOILERPLATE);
417                 fprintf(outf, "%s", MAIN_END_BOILERPLATE);
418                 break;
419         case DEFINES_EVERYTHING:
420                 fprintf(outf, "%s", test->fragment);
421                 break;
422         default:
423                 abort();
424
425         }
426         fclose(outf);
427
428         if (verbose > 1)
429                 if (system("cat " INPUT_FILE) == -1);
430
431         if (test->link) {
432                 char *newcmd;
433                 newcmd = malloc(strlen(cmd) + strlen(" ")
434                                 + strlen(test->link) + 1);
435                 sprintf(newcmd, "%s %s", cmd, test->link);
436                 if (verbose > 1)
437                         printf("Extra link line: %s", newcmd);
438                 cmd = newcmd;
439         }
440
441         output = run(cmd, &status);
442         if (status != 0 || strstr(output, "warning")) {
443                 if (verbose)
444                         printf("Compile %s for %s, status %i: %s\n",
445                                status ? "fail" : "warning",
446                                test->name, status, output);
447                 if ((test->style & EXECUTE) && !(test->style & MAY_NOT_COMPILE))
448                         errx(1, "Test for %s did not compile:\n%s",
449                              test->name, output);
450                 test->answer = false;
451                 free(output);
452         } else {
453                 /* Compile succeeded. */
454                 free(output);
455                 /* We run INSIDE_MAIN tests for sanity checking. */
456                 if ((test->style & EXECUTE) || (test->style & INSIDE_MAIN)) {
457                         output = run("./" OUTPUT_FILE, &status);
458                         if (!(test->style & EXECUTE) && status != 0)
459                                 errx(1, "Test for %s failed with %i:\n%s",
460                                      test->name, status, output);
461                         if (verbose && status)
462                                 printf("%s exited %i\n", test->name, status);
463                         free(output);
464                 }
465                 test->answer = (status == 0);
466         }
467         test->done = true;
468         return test->answer;
469 }
470
471 int main(int argc, const char *argv[])
472 {
473         char *cmd;
474         unsigned int i;
475         const char *default_args[]
476                 = { "", DEFAULT_COMPILER, DEFAULT_FLAGS, NULL };
477
478         if (argc > 1) {
479                 if (strcmp(argv[1], "--help") == 0) {
480                         printf("Usage: configurator [-v] [<compiler> <flags>...]\n"
481                                "  <compiler> <flags> will have \"-o <outfile> <infile.c>\" appended\n"
482                                "Default: %s %s\n",
483                                DEFAULT_COMPILER, DEFAULT_FLAGS);
484                         exit(0);
485                 }
486                 if (strcmp(argv[1], "-v") == 0) {
487                         argc--;
488                         argv++;
489                         verbose = 1;
490                 } else if (strcmp(argv[1], "-vv") == 0) {
491                         argc--;
492                         argv++;
493                         verbose = 2;
494                 }
495         }
496
497         if (argc == 1)
498                 argv = default_args;
499
500         cmd = connect_args(argv, "-o " OUTPUT_FILE " " INPUT_FILE);
501         for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++)
502                 run_test(cmd, &tests[i]);
503
504         unlink(OUTPUT_FILE);
505         unlink(INPUT_FILE);
506
507         cmd[strlen(cmd) - strlen(" -o " OUTPUT_FILE " " INPUT_FILE)] = '\0';
508         printf("/* Generated by CCAN configurator */\n"
509                "#ifndef CCAN_CONFIG_H\n"
510                "#define CCAN_CONFIG_H\n");
511         printf("#ifndef _GNU_SOURCE\n");
512         printf("#define _GNU_SOURCE /* Always use GNU extensions. */\n");
513         printf("#endif\n");
514         printf("#define CCAN_COMPILER \"%s\"\n", argv[1]);
515         printf("#define CCAN_CFLAGS \"%s\"\n\n", cmd + strlen(argv[1]) + 1);
516         /* This one implies "#include <ccan/..." works, eg. for tdb2.h */
517         printf("#define HAVE_CCAN 1\n");
518         for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++)
519                 printf("#define %s %u\n", tests[i].name, tests[i].answer);
520         printf("#endif /* CCAN_CONFIG_H */\n");
521         return 0;
522 }