ff9f64904bb06a7759c7c453fbf53a3dae47f5e8
[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  * c12r_err, c12r_errx functions copied from ccan/err/err.c
7  * Copyright Rusty Russell <rusty@rustcorp.com.au>. CC0 (Public domain) License.
8  *
9  * Permission is hereby granted, free of charge, to any person obtaining a copy
10  * of this software and associated documentation files (the "Software"), to deal
11  * in the Software without restriction, including without limitation the rights
12  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13  * copies of the Software, and to permit persons to whom the Software is
14  * furnished to do so, subject to the following conditions:
15  *
16  * The above copyright notice and this permission notice shall be included in
17  * all copies or substantial portions of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25  * THE SOFTWARE.
26  */
27 #define _POSIX_C_SOURCE 200809L                /* For pclose, popen, strdup */
28
29 #include <errno.h>
30 #include <stdio.h>
31 #include <stdarg.h>
32 #include <stdbool.h>
33 #include <stdlib.h>
34 #include <string.h>
35
36 #ifdef _MSC_VER
37 #define popen _popen
38 #define pclose _pclose
39 #endif
40
41 #ifdef _MSC_VER
42 #define DEFAULT_COMPILER "cl"
43 /* Note:  Dash options avoid POSIX path conversion when used under msys bash
44  *        and are therefore preferred to slash (e.g. -nologo over /nologo)
45  * Note:  Disable Warning 4200 "nonstandard extension used : zero-sized array
46  *        in struct/union" for flexible array members.
47  */
48 #define DEFAULT_FLAGS "-nologo -Zi -W4 -wd4200 " \
49         "-D_CRT_NONSTDC_NO_WARNINGS -D_CRT_SECURE_NO_WARNINGS"
50 #define DEFAULT_OUTPUT_EXE_FLAG "-Fe:"
51 #else
52 #define DEFAULT_COMPILER "cc"
53 #define DEFAULT_FLAGS "-g3 -ggdb -Wall -Wundef -Wmissing-prototypes -Wmissing-declarations -Wstrict-prototypes -Wold-style-definition"
54 #define DEFAULT_OUTPUT_EXE_FLAG "-o"
55 #endif
56
57 #define OUTPUT_FILE "configurator.out"
58 #define INPUT_FILE "configuratortest.c"
59
60 #ifdef _WIN32
61 #define DIR_SEP   "\\"
62 #else
63 #define DIR_SEP   "/"
64 #endif
65
66 static const char *progname = "";
67 static int verbose;
68
69 enum test_style {
70         OUTSIDE_MAIN            = 0x1,
71         DEFINES_FUNC            = 0x2,
72         INSIDE_MAIN             = 0x4,
73         DEFINES_EVERYTHING      = 0x8,
74         MAY_NOT_COMPILE         = 0x10,
75         EXECUTE                 = 0x8000
76 };
77
78 struct test {
79         const char *name;
80         enum test_style style;
81         const char *depends;
82         const char *link;
83         const char *fragment;
84         const char *flags;
85         const char *overrides; /* On success, force this to '1' */
86         bool done;
87         bool answer;
88 };
89
90 static struct test tests[] = {
91         { "HAVE_32BIT_OFF_T", DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE, NULL, NULL,
92           "#include <sys/types.h>\n"
93           "int main(void) {\n"
94           "     return sizeof(off_t) == 4 ? 0 : 1;\n"
95           "}\n" },
96         { "HAVE_ALIGNOF", INSIDE_MAIN, NULL, NULL,
97           "return __alignof__(double) > 0 ? 0 : 1;" },
98         { "HAVE_ASPRINTF", DEFINES_FUNC, NULL, NULL,
99           "#ifndef _GNU_SOURCE\n"
100           "#define _GNU_SOURCE\n"
101           "#endif\n"
102           "#include <stdio.h>\n"
103           "static char *func(int x) {"
104           "     char *p;\n"
105           "     if (asprintf(&p, \"%u\", x) == -1) p = NULL;"
106           "     return p;\n"
107           "}" },
108         { "HAVE_ATTRIBUTE_COLD", DEFINES_FUNC, NULL, NULL,
109           "static int __attribute__((cold)) func(int x) { return x; }" },
110         { "HAVE_ATTRIBUTE_CONST", DEFINES_FUNC, NULL, NULL,
111           "static int __attribute__((const)) func(int x) { return x; }" },
112         { "HAVE_ATTRIBUTE_PURE", DEFINES_FUNC, NULL, NULL,
113           "static int __attribute__((pure)) func(int x) { return x; }" },
114         { "HAVE_ATTRIBUTE_MAY_ALIAS", OUTSIDE_MAIN, NULL, NULL,
115           "typedef short __attribute__((__may_alias__)) short_a;" },
116         { "HAVE_ATTRIBUTE_NORETURN", DEFINES_FUNC, NULL, NULL,
117           "#include <stdlib.h>\n"
118           "static void __attribute__((noreturn)) func(int x) { exit(x); }" },
119         { "HAVE_ATTRIBUTE_PRINTF", DEFINES_FUNC, NULL, NULL,
120           "static void __attribute__((format(__printf__, 1, 2))) func(const char *fmt, ...) { (void)fmt; }" },
121         { "HAVE_ATTRIBUTE_UNUSED", OUTSIDE_MAIN, NULL, NULL,
122           "static int __attribute__((unused)) func(int x) { return x; }" },
123         { "HAVE_ATTRIBUTE_USED", OUTSIDE_MAIN, NULL, NULL,
124           "static int __attribute__((used)) func(int x) { return x; }" },
125         { "HAVE_BACKTRACE", DEFINES_FUNC, NULL, NULL,
126           "#include <execinfo.h>\n"
127           "static int func(int x) {"
128           "     void *bt[10];\n"
129           "     return backtrace(bt, 10) < x;\n"
130           "}" },
131         { "HAVE_BIG_ENDIAN", INSIDE_MAIN|EXECUTE, NULL, NULL,
132           "union { int i; char c[sizeof(int)]; } u;\n"
133           "u.i = 0x01020304;\n"
134           "return u.c[0] == 0x01 && u.c[1] == 0x02 && u.c[2] == 0x03 && u.c[3] == 0x04 ? 0 : 1;" },
135         { "HAVE_BSWAP_64", DEFINES_FUNC, "HAVE_BYTESWAP_H", NULL,
136           "#include <byteswap.h>\n"
137           "static int func(int x) { return bswap_64(x); }" },
138         { "HAVE_BUILTIN_CHOOSE_EXPR", INSIDE_MAIN, NULL, NULL,
139           "return __builtin_choose_expr(1, 0, \"garbage\");" },
140         { "HAVE_BUILTIN_CLZ", INSIDE_MAIN, NULL, NULL,
141           "return __builtin_clz(1) == (sizeof(int)*8 - 1) ? 0 : 1;" },
142         { "HAVE_BUILTIN_CLZL", INSIDE_MAIN, NULL, NULL,
143           "return __builtin_clzl(1) == (sizeof(long)*8 - 1) ? 0 : 1;" },
144         { "HAVE_BUILTIN_CLZLL", INSIDE_MAIN, NULL, NULL,
145           "return __builtin_clzll(1) == (sizeof(long long)*8 - 1) ? 0 : 1;" },
146         { "HAVE_BUILTIN_CTZ", INSIDE_MAIN, NULL, NULL,
147           "return __builtin_ctz(1 << (sizeof(int)*8 - 1)) == (sizeof(int)*8 - 1) ? 0 : 1;" },
148         { "HAVE_BUILTIN_CTZL", INSIDE_MAIN, NULL, NULL,
149           "return __builtin_ctzl(1UL << (sizeof(long)*8 - 1)) == (sizeof(long)*8 - 1) ? 0 : 1;" },
150         { "HAVE_BUILTIN_CTZLL", INSIDE_MAIN, NULL, NULL,
151           "return __builtin_ctzll(1ULL << (sizeof(long long)*8 - 1)) == (sizeof(long long)*8 - 1) ? 0 : 1;" },
152         { "HAVE_BUILTIN_CONSTANT_P", INSIDE_MAIN, NULL, NULL,
153           "return __builtin_constant_p(1) ? 0 : 1;" },
154         { "HAVE_BUILTIN_EXPECT", INSIDE_MAIN, NULL, NULL,
155           "return __builtin_expect(argc == 1, 1) ? 0 : 1;" },
156         { "HAVE_BUILTIN_FFS", INSIDE_MAIN, NULL, NULL,
157           "return __builtin_ffs(0) == 0 ? 0 : 1;" },
158         { "HAVE_BUILTIN_FFSL", INSIDE_MAIN, NULL, NULL,
159           "return __builtin_ffsl(0L) == 0 ? 0 : 1;" },
160         { "HAVE_BUILTIN_FFSLL", INSIDE_MAIN, NULL, NULL,
161           "return __builtin_ffsll(0LL) == 0 ? 0 : 1;" },
162         { "HAVE_BUILTIN_POPCOUNTL", INSIDE_MAIN, NULL, NULL,
163           "return __builtin_popcountl(255L) == 8 ? 0 : 1;" },
164         { "HAVE_BUILTIN_TYPES_COMPATIBLE_P", INSIDE_MAIN, NULL, NULL,
165           "return __builtin_types_compatible_p(char *, int) ? 1 : 0;" },
166         { "HAVE_ICCARM_INTRINSICS", DEFINES_FUNC, NULL, NULL,
167           "#include <intrinsics.h>\n"
168           "int func(int v) {\n"
169           "     return __CLZ(__RBIT(v));\n"
170           "}" },
171         { "HAVE_BYTESWAP_H", OUTSIDE_MAIN, NULL, NULL,
172           "#include <byteswap.h>\n" },
173         { "HAVE_CLOCK_GETTIME",
174           DEFINES_FUNC, "HAVE_STRUCT_TIMESPEC", NULL,
175           "#include <time.h>\n"
176           "static struct timespec func(void) {\n"
177           "     struct timespec ts;\n"
178           "     clock_gettime(CLOCK_REALTIME, &ts);\n"
179           "     return ts;\n"
180           "}\n" },
181         { "HAVE_CLOCK_GETTIME_IN_LIBRT",
182           DEFINES_FUNC,
183           "HAVE_STRUCT_TIMESPEC !HAVE_CLOCK_GETTIME",
184           "-lrt",
185           "#include <time.h>\n"
186           "static struct timespec func(void) {\n"
187           "     struct timespec ts;\n"
188           "     clock_gettime(CLOCK_REALTIME, &ts);\n"
189           "     return ts;\n"
190           "}\n",
191           /* This means HAVE_CLOCK_GETTIME, too */
192           "HAVE_CLOCK_GETTIME" },
193         { "HAVE_COMPOUND_LITERALS", INSIDE_MAIN, NULL, NULL,
194           "int *foo = (int[]) { 1, 2, 3, 4 };\n"
195           "return foo[0] ? 0 : 1;" },
196         { "HAVE_FCHDIR", DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE, NULL, NULL,
197           "#include <sys/types.h>\n"
198           "#include <sys/stat.h>\n"
199           "#include <fcntl.h>\n"
200           "#include <unistd.h>\n"
201           "int main(void) {\n"
202           "     int fd = open(\"..\", O_RDONLY);\n"
203           "     return fchdir(fd) == 0 ? 0 : 1;\n"
204           "}\n" },
205         { "HAVE_ERR_H", DEFINES_FUNC, NULL, NULL,
206           "#include <err.h>\n"
207           "static void func(int arg) {\n"
208           "     if (arg == 0)\n"
209           "             err(1, \"err %u\", arg);\n"
210           "     if (arg == 1)\n"
211           "             errx(1, \"err %u\", arg);\n"
212           "     if (arg == 3)\n"
213           "             warn(\"warn %u\", arg);\n"
214           "     if (arg == 4)\n"
215           "             warnx(\"warn %u\", arg);\n"
216           "}\n" },
217         { "HAVE_FILE_OFFSET_BITS", DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE,
218           "HAVE_32BIT_OFF_T", NULL,
219           "#define _FILE_OFFSET_BITS 64\n"
220           "#include <sys/types.h>\n"
221           "int main(void) {\n"
222           "     return sizeof(off_t) == 8 ? 0 : 1;\n"
223           "}\n" },
224         { "HAVE_FOR_LOOP_DECLARATION", INSIDE_MAIN, NULL, NULL,
225           "int ret = 1;\n"
226           "for (int i = 0; i < argc; i++) { ret = 0; };\n"
227           "return ret;" },
228         { "HAVE_FLEXIBLE_ARRAY_MEMBER", OUTSIDE_MAIN, NULL, NULL,
229           "struct foo { unsigned int x; int arr[]; };" },
230         { "HAVE_GETPAGESIZE", DEFINES_FUNC, NULL, NULL,
231           "#include <unistd.h>\n"
232           "static int func(void) { return getpagesize(); }" },
233         { "HAVE_ISBLANK", DEFINES_FUNC, NULL, NULL,
234           "#ifndef _GNU_SOURCE\n"
235           "#define _GNU_SOURCE\n"
236           "#endif\n"
237           "#include <ctype.h>\n"
238           "static int func(void) { return isblank(' '); }" },
239         { "HAVE_LITTLE_ENDIAN", INSIDE_MAIN|EXECUTE, NULL, NULL,
240           "union { int i; char c[sizeof(int)]; } u;\n"
241           "u.i = 0x01020304;\n"
242           "return u.c[0] == 0x04 && u.c[1] == 0x03 && u.c[2] == 0x02 && u.c[3] == 0x01 ? 0 : 1;" },
243         { "HAVE_MEMMEM", DEFINES_FUNC, NULL, NULL,
244           "#ifndef _GNU_SOURCE\n"
245           "#define _GNU_SOURCE\n"
246           "#endif\n"
247           "#include <string.h>\n"
248           "static void *func(void *h, size_t hl, void *n, size_t nl) {\n"
249           "return memmem(h, hl, n, nl);"
250           "}\n", },
251         { "HAVE_MEMRCHR", DEFINES_FUNC, NULL, NULL,
252           "#ifndef _GNU_SOURCE\n"
253           "#define _GNU_SOURCE\n"
254           "#endif\n"
255           "#include <string.h>\n"
256           "static void *func(void *s, int c, size_t n) {\n"
257           "return memrchr(s, c, n);"
258           "}\n", },
259         { "HAVE_MMAP", DEFINES_FUNC, NULL, NULL,
260           "#include <sys/mman.h>\n"
261           "static void *func(int fd) {\n"
262           "     return mmap(0, 65536, PROT_READ, MAP_SHARED, fd, 0);\n"
263           "}" },
264         { "HAVE_PROC_SELF_MAPS", DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE, NULL, NULL,
265           "#include <sys/types.h>\n"
266           "#include <sys/stat.h>\n"
267           "#include <fcntl.h>\n"
268           "int main(void) {\n"
269           "     return open(\"/proc/self/maps\", O_RDONLY) != -1 ? 0 : 1;\n"
270           "}\n" },
271         { "HAVE_QSORT_R_PRIVATE_LAST",
272           DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE, NULL, NULL,
273           "#ifndef _GNU_SOURCE\n"
274           "#define _GNU_SOURCE\n"
275           "#endif\n"
276           "#include <stdlib.h>\n"
277           "static int cmp(const void *lp, const void *rp, void *priv) {\n"
278           " *(unsigned int *)priv = 1;\n"
279           " return *(const int *)lp - *(const int *)rp; }\n"
280           "int main(void) {\n"
281           " int array[] = { 9, 2, 5 };\n"
282           " unsigned int called = 0;\n"
283           " qsort_r(array, 3, sizeof(int), cmp, &called);\n"
284           " return called && array[0] == 2 && array[1] == 5 && array[2] == 9 ? 0 : 1;\n"
285           "}\n" },
286         { "HAVE_STRUCT_TIMESPEC",
287           DEFINES_FUNC, NULL, NULL,
288           "#include <time.h>\n"
289           "static void func(void) {\n"
290           "     struct timespec ts;\n"
291           "     ts.tv_sec = ts.tv_nsec = 1;\n"
292           "}\n" },
293         { "HAVE_SECTION_START_STOP",
294           DEFINES_FUNC, NULL, NULL,
295           "static void *__attribute__((__section__(\"mysec\"))) p = &p;\n"
296           "static int func(void) {\n"
297           "     extern void *__start_mysec[], *__stop_mysec[];\n"
298           "     return __stop_mysec - __start_mysec;\n"
299           "}\n" },
300         { "HAVE_STACK_GROWS_UPWARDS", DEFINES_EVERYTHING|EXECUTE, NULL, NULL,
301           "#include <stddef.h>\n"
302           "static ptrdiff_t nest(const void *base, unsigned int i)\n"
303           "{\n"
304           "     if (i == 0)\n"
305           "             return (const char *)&i - (const char *)base;\n"
306           "     return nest(base, i-1);\n"
307           "}\n"
308           "int main(int argc, char *argv[]) {\n"
309           "     (void)argv;\n"
310           "     return (nest(&argc, argc) > 0) ? 0 : 1;\n"
311           "}\n" },
312         { "HAVE_STATEMENT_EXPR", INSIDE_MAIN, NULL, NULL,
313           "return ({ int x = argc; x == argc ? 0 : 1; });" },
314         { "HAVE_SYS_FILIO_H", OUTSIDE_MAIN, NULL, NULL, /* Solaris needs this for FIONREAD */
315           "#include <sys/filio.h>\n" },
316         { "HAVE_SYS_TERMIOS_H", OUTSIDE_MAIN, NULL, NULL,
317           "#include <sys/termios.h>\n" },
318         { "HAVE_SYS_UNISTD_H", OUTSIDE_MAIN, NULL, NULL,
319           "#include <sys/unistd.h>\n" },
320         { "HAVE_TYPEOF", INSIDE_MAIN, NULL, NULL,
321           "__typeof__(argc) i; i = argc; return i == argc ? 0 : 1;" },
322         { "HAVE_UNALIGNED_ACCESS", DEFINES_EVERYTHING|EXECUTE, NULL, NULL,
323           "#include <string.h>\n"
324           "int main(int argc, char *argv[]) {\n"
325           "     (void)argc;\n"
326           "     char pad[sizeof(int *) * 1];\n"
327           "     strncpy(pad, argv[0], sizeof(pad));\n"
328           "     int *x = (int *)pad, *y = (int *)(pad + 1);\n"
329           "     return *x == *y;\n"
330           "}\n" },
331         { "HAVE_UTIME", DEFINES_FUNC, NULL, NULL,
332           "#include <sys/types.h>\n"
333           "#include <utime.h>\n"
334           "static int func(const char *filename) {\n"
335           "     struct utimbuf times = { 0 };\n"
336           "     return utime(filename, &times);\n"
337           "}" },
338         { "HAVE_WARN_UNUSED_RESULT", DEFINES_FUNC, NULL, NULL,
339           "#include <sys/types.h>\n"
340           "#include <utime.h>\n"
341           "static __attribute__((warn_unused_result)) int func(int i) {\n"
342           "     return i + 1;\n"
343           "}" },
344         { "HAVE_OPENMP", INSIDE_MAIN, NULL, NULL,
345           "int i;\n"
346           "#pragma omp parallel for\n"
347           "for(i = 0; i < 0; i++) {};\n"
348           "return 0;\n",
349           "-Werror -fopenmp" },
350         { "HAVE_VALGRIND_MEMCHECK_H", OUTSIDE_MAIN, NULL, NULL,
351           "#include <valgrind/memcheck.h>\n" },
352         { "HAVE_UCONTEXT", DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE,
353           NULL, NULL,
354           "#include <ucontext.h>\n"
355           "static int x = 0;\n"
356           "static char stack[2048];\n"
357           "static ucontext_t a, b;\n"
358           "static void fn(void) {\n"
359           "     x |= 2;\n"
360           "     setcontext(&b);\n"
361           "     x |= 4;\n"
362           "}\n"
363           "int main(void) {\n"
364           "     x |= 1;\n"
365           "     getcontext(&a);\n"
366           "     a.uc_stack.ss_sp = stack;\n"
367           "     a.uc_stack.ss_size = sizeof(stack);\n"
368           "     makecontext(&a, fn, 0);\n"
369           "     swapcontext(&b, &a);\n"
370           "     return (x == 3) ? 0 : 1;\n"
371           "}\n"
372         },
373         { "HAVE_POINTER_SAFE_MAKECONTEXT", DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE,
374           "HAVE_UCONTEXT", NULL,
375           "#include <stddef.h>\n"
376           "#include <ucontext.h>\n"
377           "static int worked = 0;\n"
378           "static char stack[1024];\n"
379           "static ucontext_t a, b;\n"
380           "static void fn(void *p, void *q) {\n"
381           "     void *cp = &worked;\n"
382           "     void *cq = (void *)(~((ptrdiff_t)cp));\n"
383           "     if ((p == cp) && (q == cq))\n"
384           "             worked = 1;\n"
385           "     setcontext(&b);\n"
386           "}\n"
387           "int main(void) {\n"
388           "     void *ap = &worked;\n"
389           "     void *aq = (void *)(~((ptrdiff_t)ap));\n"
390           "     getcontext(&a);\n"
391           "     a.uc_stack.ss_sp = stack;\n"
392           "     a.uc_stack.ss_size = sizeof(stack);\n"
393           "     makecontext(&a, (void (*)(void))fn, 2, ap, aq);\n"
394           "     swapcontext(&b, &a);\n"
395           "     return worked ? 0 : 1;\n"
396           "}\n"
397         },
398 };
399
400 static void c12r_err(int eval, const char *fmt, ...)
401 {
402         int err_errno = errno;
403         va_list ap;
404
405         fprintf(stderr, "%s: ", progname);
406         va_start(ap, fmt);
407         vfprintf(stderr, fmt, ap);
408         va_end(ap);
409         fprintf(stderr, ": %s\n", strerror(err_errno));
410         exit(eval);
411 }
412
413 static void c12r_errx(int eval, const char *fmt, ...)
414 {
415         va_list ap;
416
417         fprintf(stderr, "%s: ", progname);
418         va_start(ap, fmt);
419         vfprintf(stderr, fmt, ap);
420         va_end(ap);
421         fprintf(stderr, "\n");
422         exit(eval);
423 }
424
425 static size_t fcopy(FILE *fsrc, FILE *fdst)
426 {
427         char buffer[BUFSIZ];
428         size_t rsize, wsize;
429         size_t copied = 0;
430
431         while ((rsize = fread(buffer, 1, BUFSIZ, fsrc)) > 0) {
432                 wsize = fwrite(buffer, 1, rsize, fdst);
433                 copied += wsize;
434                 if (wsize != rsize)
435                         break;
436         }
437
438         return copied;
439 }
440
441 static char *grab_stream(FILE *file)
442 {
443         size_t max, ret, size = 0;
444         char *buffer;
445
446         max = BUFSIZ;
447         buffer = malloc(max);
448         while ((ret = fread(buffer+size, 1, max - size, file)) == max - size) {
449                 size += ret;
450                 buffer = realloc(buffer, max *= 2);
451         }
452         size += ret;
453         if (ferror(file))
454                 c12r_err(1, "reading from command");
455         buffer[size] = '\0';
456         return buffer;
457 }
458
459 static char *run(const char *cmd, int *exitstatus)
460 {
461         static const char redir[] = " 2>&1";
462         size_t cmdlen;
463         char *cmdredir;
464         FILE *cmdout;
465         char *ret;
466
467         cmdlen = strlen(cmd);
468         cmdredir = malloc(cmdlen + sizeof(redir));
469         memcpy(cmdredir, cmd, cmdlen);
470         memcpy(cmdredir + cmdlen, redir, sizeof(redir));
471
472         cmdout = popen(cmdredir, "r");
473         if (!cmdout)
474                 c12r_err(1, "popen \"%s\"", cmdredir);
475
476         free(cmdredir);
477
478         ret = grab_stream(cmdout);
479         *exitstatus = pclose(cmdout);
480         return ret;
481 }
482
483 static char *connect_args(const char *argv[], const char *outflag,
484                 const char *files)
485 {
486         unsigned int i;
487         char *ret;
488         size_t len = strlen(outflag) + strlen(files) + 1;
489
490         for (i = 1; argv[i]; i++)
491                 len += 1 + strlen(argv[i]);
492
493         ret = malloc(len);
494         len = 0;
495         for (i = 1; argv[i]; i++) {
496                 strcpy(ret + len, argv[i]);
497                 len += strlen(argv[i]);
498                 if (argv[i+1] || *outflag)
499                         ret[len++] = ' ';
500         }
501         strcpy(ret + len, outflag);
502         len += strlen(outflag);
503         strcpy(ret + len, files);
504         return ret;
505 }
506
507 static struct test *find_test(const char *name)
508 {
509         unsigned int i;
510
511         for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) {
512                 if (strcmp(tests[i].name, name) == 0)
513                         return &tests[i];
514         }
515         abort();
516 }
517
518 #define PRE_BOILERPLATE "/* Test program generated by configurator. */\n"
519 #define MAIN_START_BOILERPLATE \
520         "int main(int argc, char *argv[]) {\n" \
521         "       (void)argc;\n" \
522         "       (void)argv;\n"
523 #define USE_FUNC_BOILERPLATE "(void)func;\n"
524 #define MAIN_BODY_BOILERPLATE "return 0;\n"
525 #define MAIN_END_BOILERPLATE "}\n"
526
527 static bool run_test(const char *cmd, struct test *test)
528 {
529         char *output, *newcmd;
530         FILE *outf;
531         int status;
532
533         if (test->done)
534                 return test->answer;
535
536         if (test->depends) {
537                 size_t len;
538                 const char *deps = test->depends;
539                 char *dep;
540
541                 /* Space-separated dependencies, could be ! for inverse. */
542                 while ((len = strcspn(deps, " ")) != 0) {
543                         bool positive = true;
544                         if (deps[len]) {
545                                 dep = strdup(deps);
546                                 dep[len] = '\0';
547                         } else {
548                                 dep = (char *)deps;
549                         }
550
551                         if (dep[0] == '!') {
552                                 dep++;
553                                 positive = false;
554                         }
555                         if (run_test(cmd, find_test(dep)) != positive) {
556                                 test->answer = false;
557                                 test->done = true;
558                                 return test->answer;
559                         }
560                         if (deps[len])
561                                 free(dep);
562
563                         deps += len;
564                         deps += strspn(deps, " ");
565                 }
566         }
567
568         outf = fopen(INPUT_FILE, verbose > 1 ? "w+" : "w");
569         if (!outf)
570                 c12r_err(1, "creating %s", INPUT_FILE);
571
572         fprintf(outf, "%s", PRE_BOILERPLATE);
573         switch (test->style & ~(EXECUTE|MAY_NOT_COMPILE)) {
574         case INSIDE_MAIN:
575                 fprintf(outf, "%s", MAIN_START_BOILERPLATE);
576                 fprintf(outf, "%s", test->fragment);
577                 fprintf(outf, "%s", MAIN_END_BOILERPLATE);
578                 break;
579         case OUTSIDE_MAIN:
580                 fprintf(outf, "%s", test->fragment);
581                 fprintf(outf, "%s", MAIN_START_BOILERPLATE);
582                 fprintf(outf, "%s", MAIN_BODY_BOILERPLATE);
583                 fprintf(outf, "%s", MAIN_END_BOILERPLATE);
584                 break;
585         case DEFINES_FUNC:
586                 fprintf(outf, "%s", test->fragment);
587                 fprintf(outf, "%s", MAIN_START_BOILERPLATE);
588                 fprintf(outf, "%s", USE_FUNC_BOILERPLATE);
589                 fprintf(outf, "%s", MAIN_BODY_BOILERPLATE);
590                 fprintf(outf, "%s", MAIN_END_BOILERPLATE);
591                 break;
592         case DEFINES_EVERYTHING:
593                 fprintf(outf, "%s", test->fragment);
594                 break;
595         default:
596                 abort();
597
598         }
599
600         if (verbose > 1) {
601                 fseek(outf, 0, SEEK_SET);
602                 fcopy(outf, stdout);
603         }
604
605         fclose(outf);
606
607         newcmd = strdup(cmd);
608
609         if (test->flags) {
610                 newcmd = realloc(newcmd, strlen(newcmd) + strlen(" ")
611                                 + strlen(test->flags) + 1);
612                 strcat(newcmd, " ");
613                 strcat(newcmd, test->flags);
614                 if (verbose > 1)
615                         printf("Extra flags line: %s", newcmd);
616         }
617
618         if (test->link) {
619                 newcmd = realloc(newcmd, strlen(newcmd) + strlen(" ")
620                                 + strlen(test->link) + 1);
621                 strcat(newcmd, " ");
622                 strcat(newcmd, test->link);
623                 if (verbose > 1)
624                         printf("Extra link line: %s", newcmd);
625         }
626
627         output = run(newcmd, &status);
628
629         free(newcmd);
630
631         if (status != 0 || strstr(output, "warning")) {
632                 if (verbose)
633                         printf("Compile %s for %s, status %i: %s\n",
634                                status ? "fail" : "warning",
635                                test->name, status, output);
636                 if ((test->style & EXECUTE) && !(test->style & MAY_NOT_COMPILE))
637                         c12r_errx(1, "Test for %s did not compile:\n%s",
638                                   test->name, output);
639                 test->answer = false;
640                 free(output);
641         } else {
642                 /* Compile succeeded. */
643                 free(output);
644                 /* We run INSIDE_MAIN tests for sanity checking. */
645                 if ((test->style & EXECUTE) || (test->style & INSIDE_MAIN)) {
646                         output = run("." DIR_SEP OUTPUT_FILE, &status);
647                         if (!(test->style & EXECUTE) && status != 0)
648                                 c12r_errx(1, "Test for %s failed with %i:\n%s",
649                                           test->name, status, output);
650                         if (verbose && status)
651                                 printf("%s exited %i\n", test->name, status);
652                         free(output);
653                 }
654                 test->answer = (status == 0);
655         }
656         test->done = true;
657
658         if (test->answer && test->overrides) {
659                 struct test *override = find_test(test->overrides);
660                 override->done = true;
661                 override->answer = true;
662         }
663         return test->answer;
664 }
665
666 int main(int argc, const char *argv[])
667 {
668         char *cmd;
669         unsigned int i;
670         const char *default_args[]
671                 = { "", DEFAULT_COMPILER, DEFAULT_FLAGS, NULL };
672         const char *outflag = DEFAULT_OUTPUT_EXE_FLAG;
673         const char *configurator_cc = NULL;
674         const char *orig_cc;
675
676         if (argc > 0)
677                 progname = argv[0];
678
679         while (argc > 1) {
680                 if (strcmp(argv[1], "--help") == 0) {
681                         printf("Usage: configurator [-v] [-O<outflag>] [--configurator-cc=<compiler-for-tests>] [<compiler> <flags>...]\n"
682                                "  <compiler> <flags> will have \"<outflag> <outfile> <infile.c>\" appended\n"
683                                "Default: %s %s %s\n",
684                                DEFAULT_COMPILER, DEFAULT_FLAGS,
685                                DEFAULT_OUTPUT_EXE_FLAG);
686                         exit(0);
687                 }
688                 if (strncmp(argv[1], "-O", 2) == 0) {
689                         argc--;
690                         argv++;
691                         outflag = argv[1] + 2;
692                         if (!*outflag) {
693                                 fprintf(stderr,
694                                         "%s: option requires an argument -- O\n",
695                                         argv[0]);
696                                 exit(1);
697                         }
698                 } else if (strcmp(argv[1], "-v") == 0) {
699                         argc--;
700                         argv++;
701                         verbose++;
702                 } else if (strcmp(argv[1], "-vv") == 0) {
703                         argc--;
704                         argv++;
705                         verbose += 2;
706                 } else if (strncmp(argv[1], "--configurator-cc=", 18) == 0) {
707                         configurator_cc = argv[1] + 18;
708                         argc--;
709                         argv++;
710                 } else {
711                         break;
712                 }
713         }
714
715         if (argc == 1)
716                 argv = default_args;
717
718         orig_cc = argv[1];
719         if (configurator_cc)
720                 argv[1] = configurator_cc;
721
722         cmd = connect_args(argv, outflag, OUTPUT_FILE " " INPUT_FILE);
723         for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++)
724                 run_test(cmd, &tests[i]);
725         free(cmd);
726
727         remove(OUTPUT_FILE);
728         remove(INPUT_FILE);
729
730         printf("/* Generated by CCAN configurator */\n"
731                "#ifndef CCAN_CONFIG_H\n"
732                "#define CCAN_CONFIG_H\n");
733         printf("#ifndef _GNU_SOURCE\n");
734         printf("#define _GNU_SOURCE /* Always use GNU extensions. */\n");
735         printf("#endif\n");
736         printf("#define CCAN_COMPILER \"%s\"\n", orig_cc);
737         cmd = connect_args(argv + 1, "", "");
738         printf("#define CCAN_CFLAGS \"%s\"\n", cmd);
739         free(cmd);
740         printf("#define CCAN_OUTPUT_EXE_CFLAG \"%s\"\n\n", outflag);
741         /* This one implies "#include <ccan/..." works, eg. for tdb2.h */
742         printf("#define HAVE_CCAN 1\n");
743         for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++)
744                 printf("#define %s %u\n", tests[i].name, tests[i].answer);
745         printf("#endif /* CCAN_CONFIG_H */\n");
746         return 0;
747 }