2e5b09c2b984c252c8a2bfd9a397960af057c344
[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) \n"
106           "             p = NULL;\n"
107           "     return p;\n"
108           "}" },
109         { "HAVE_ATTRIBUTE_COLD", DEFINES_FUNC, NULL, NULL,
110           "static int __attribute__((cold)) func(int x) { return x; }" },
111         { "HAVE_ATTRIBUTE_CONST", DEFINES_FUNC, NULL, NULL,
112           "static int __attribute__((const)) func(int x) { return x; }" },
113         { "HAVE_ATTRIBUTE_PURE", DEFINES_FUNC, NULL, NULL,
114           "static int __attribute__((pure)) func(int x) { return x; }" },
115         { "HAVE_ATTRIBUTE_MAY_ALIAS", OUTSIDE_MAIN, NULL, NULL,
116           "typedef short __attribute__((__may_alias__)) short_a;" },
117         { "HAVE_ATTRIBUTE_NORETURN", DEFINES_FUNC, NULL, NULL,
118           "#include <stdlib.h>\n"
119           "static void __attribute__((noreturn)) func(int x) { exit(x); }" },
120         { "HAVE_ATTRIBUTE_PRINTF", DEFINES_FUNC, NULL, NULL,
121           "static void __attribute__((format(__printf__, 1, 2))) func(const char *fmt, ...) { (void)fmt; }" },
122         { "HAVE_ATTRIBUTE_UNUSED", OUTSIDE_MAIN, NULL, NULL,
123           "static int __attribute__((unused)) func(int x) { return x; }" },
124         { "HAVE_ATTRIBUTE_USED", OUTSIDE_MAIN, NULL, NULL,
125           "static int __attribute__((used)) func(int x) { return x; }" },
126         { "HAVE_BACKTRACE", DEFINES_FUNC, NULL, NULL,
127           "#include <execinfo.h>\n"
128           "static int func(int x) {"
129           "     void *bt[10];\n"
130           "     return backtrace(bt, 10) < x;\n"
131           "}" },
132         { "HAVE_BIG_ENDIAN", INSIDE_MAIN|EXECUTE, NULL, NULL,
133           "union { int i; char c[sizeof(int)]; } u;\n"
134           "u.i = 0x01020304;\n"
135           "return u.c[0] == 0x01 && u.c[1] == 0x02 && u.c[2] == 0x03 && u.c[3] == 0x04 ? 0 : 1;" },
136         { "HAVE_BSWAP_64", DEFINES_FUNC, "HAVE_BYTESWAP_H", NULL,
137           "#include <byteswap.h>\n"
138           "static int func(int x) { return bswap_64(x); }" },
139         { "HAVE_BUILTIN_CHOOSE_EXPR", INSIDE_MAIN, NULL, NULL,
140           "return __builtin_choose_expr(1, 0, \"garbage\");" },
141         { "HAVE_BUILTIN_CLZ", INSIDE_MAIN, NULL, NULL,
142           "return __builtin_clz(1) == (sizeof(int)*8 - 1) ? 0 : 1;" },
143         { "HAVE_BUILTIN_CLZL", INSIDE_MAIN, NULL, NULL,
144           "return __builtin_clzl(1) == (sizeof(long)*8 - 1) ? 0 : 1;" },
145         { "HAVE_BUILTIN_CLZLL", INSIDE_MAIN, NULL, NULL,
146           "return __builtin_clzll(1) == (sizeof(long long)*8 - 1) ? 0 : 1;" },
147         { "HAVE_BUILTIN_CTZ", INSIDE_MAIN, NULL, NULL,
148           "return __builtin_ctz(1 << (sizeof(int)*8 - 1)) == (sizeof(int)*8 - 1) ? 0 : 1;" },
149         { "HAVE_BUILTIN_CTZL", INSIDE_MAIN, NULL, NULL,
150           "return __builtin_ctzl(1UL << (sizeof(long)*8 - 1)) == (sizeof(long)*8 - 1) ? 0 : 1;" },
151         { "HAVE_BUILTIN_CTZLL", INSIDE_MAIN, NULL, NULL,
152           "return __builtin_ctzll(1ULL << (sizeof(long long)*8 - 1)) == (sizeof(long long)*8 - 1) ? 0 : 1;" },
153         { "HAVE_BUILTIN_CONSTANT_P", INSIDE_MAIN, NULL, NULL,
154           "return __builtin_constant_p(1) ? 0 : 1;" },
155         { "HAVE_BUILTIN_EXPECT", INSIDE_MAIN, NULL, NULL,
156           "return __builtin_expect(argc == 1, 1) ? 0 : 1;" },
157         { "HAVE_BUILTIN_FFS", INSIDE_MAIN, NULL, NULL,
158           "return __builtin_ffs(0) == 0 ? 0 : 1;" },
159         { "HAVE_BUILTIN_FFSL", INSIDE_MAIN, NULL, NULL,
160           "return __builtin_ffsl(0L) == 0 ? 0 : 1;" },
161         { "HAVE_BUILTIN_FFSLL", INSIDE_MAIN, NULL, NULL,
162           "return __builtin_ffsll(0LL) == 0 ? 0 : 1;" },
163         { "HAVE_BUILTIN_POPCOUNT", INSIDE_MAIN, NULL, NULL,
164           "return __builtin_popcount(255) == 8 ? 0 : 1;" },
165         { "HAVE_BUILTIN_POPCOUNTL", INSIDE_MAIN, NULL, NULL,
166           "return __builtin_popcountl(255L) == 8 ? 0 : 1;" },
167         { "HAVE_BUILTIN_POPCOUNTLL", INSIDE_MAIN, NULL, NULL,
168           "return __builtin_popcountll(255LL) == 8 ? 0 : 1;" },
169         { "HAVE_BUILTIN_TYPES_COMPATIBLE_P", INSIDE_MAIN, NULL, NULL,
170           "return __builtin_types_compatible_p(char *, int) ? 1 : 0;" },
171         { "HAVE_ICCARM_INTRINSICS", DEFINES_FUNC, NULL, NULL,
172           "#include <intrinsics.h>\n"
173           "int func(int v) {\n"
174           "     return __CLZ(__RBIT(v));\n"
175           "}" },
176         { "HAVE_BYTESWAP_H", OUTSIDE_MAIN, NULL, NULL,
177           "#include <byteswap.h>\n" },
178         { "HAVE_CLOCK_GETTIME",
179           DEFINES_FUNC, "HAVE_STRUCT_TIMESPEC", NULL,
180           "#include <time.h>\n"
181           "static struct timespec func(void) {\n"
182           "     struct timespec ts;\n"
183           "     clock_gettime(CLOCK_REALTIME, &ts);\n"
184           "     return ts;\n"
185           "}\n" },
186         { "HAVE_CLOCK_GETTIME_IN_LIBRT",
187           DEFINES_FUNC,
188           "HAVE_STRUCT_TIMESPEC !HAVE_CLOCK_GETTIME",
189           "-lrt",
190           "#include <time.h>\n"
191           "static struct timespec func(void) {\n"
192           "     struct timespec ts;\n"
193           "     clock_gettime(CLOCK_REALTIME, &ts);\n"
194           "     return ts;\n"
195           "}\n",
196           /* This means HAVE_CLOCK_GETTIME, too */
197           "HAVE_CLOCK_GETTIME" },
198         { "HAVE_COMPOUND_LITERALS", INSIDE_MAIN, NULL, NULL,
199           "int *foo = (int[]) { 1, 2, 3, 4 };\n"
200           "return foo[0] ? 0 : 1;" },
201         { "HAVE_FCHDIR", DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE, NULL, NULL,
202           "#include <sys/types.h>\n"
203           "#include <sys/stat.h>\n"
204           "#include <fcntl.h>\n"
205           "#include <unistd.h>\n"
206           "int main(void) {\n"
207           "     int fd = open(\"..\", O_RDONLY);\n"
208           "     return fchdir(fd) == 0 ? 0 : 1;\n"
209           "}\n" },
210         { "HAVE_ERR_H", DEFINES_FUNC, NULL, NULL,
211           "#include <err.h>\n"
212           "static void func(int arg) {\n"
213           "     if (arg == 0)\n"
214           "             err(1, \"err %u\", arg);\n"
215           "     if (arg == 1)\n"
216           "             errx(1, \"err %u\", arg);\n"
217           "     if (arg == 3)\n"
218           "             warn(\"warn %u\", arg);\n"
219           "     if (arg == 4)\n"
220           "             warnx(\"warn %u\", arg);\n"
221           "}\n" },
222         { "HAVE_FILE_OFFSET_BITS", DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE,
223           "HAVE_32BIT_OFF_T", NULL,
224           "#define _FILE_OFFSET_BITS 64\n"
225           "#include <sys/types.h>\n"
226           "int main(void) {\n"
227           "     return sizeof(off_t) == 8 ? 0 : 1;\n"
228           "}\n" },
229         { "HAVE_FOR_LOOP_DECLARATION", INSIDE_MAIN, NULL, NULL,
230           "int ret = 1;\n"
231           "for (int i = 0; i < argc; i++) { ret = 0; };\n"
232           "return ret;" },
233         { "HAVE_FLEXIBLE_ARRAY_MEMBER", OUTSIDE_MAIN, NULL, NULL,
234           "struct foo { unsigned int x; int arr[]; };" },
235         { "HAVE_GETPAGESIZE", DEFINES_FUNC, NULL, NULL,
236           "#include <unistd.h>\n"
237           "static int func(void) { return getpagesize(); }" },
238         { "HAVE_ISBLANK", DEFINES_FUNC, NULL, NULL,
239           "#ifndef _GNU_SOURCE\n"
240           "#define _GNU_SOURCE\n"
241           "#endif\n"
242           "#include <ctype.h>\n"
243           "static int func(void) { return isblank(' '); }" },
244         { "HAVE_LITTLE_ENDIAN", INSIDE_MAIN|EXECUTE, NULL, NULL,
245           "union { int i; char c[sizeof(int)]; } u;\n"
246           "u.i = 0x01020304;\n"
247           "return u.c[0] == 0x04 && u.c[1] == 0x03 && u.c[2] == 0x02 && u.c[3] == 0x01 ? 0 : 1;" },
248         { "HAVE_MEMMEM", DEFINES_FUNC, NULL, NULL,
249           "#ifndef _GNU_SOURCE\n"
250           "#define _GNU_SOURCE\n"
251           "#endif\n"
252           "#include <string.h>\n"
253           "static void *func(void *h, size_t hl, void *n, size_t nl) {\n"
254           "return memmem(h, hl, n, nl);"
255           "}\n", },
256         { "HAVE_MEMRCHR", DEFINES_FUNC, NULL, NULL,
257           "#ifndef _GNU_SOURCE\n"
258           "#define _GNU_SOURCE\n"
259           "#endif\n"
260           "#include <string.h>\n"
261           "static void *func(void *s, int c, size_t n) {\n"
262           "return memrchr(s, c, n);"
263           "}\n", },
264         { "HAVE_MMAP", DEFINES_FUNC, NULL, NULL,
265           "#include <sys/mman.h>\n"
266           "static void *func(int fd) {\n"
267           "     return mmap(0, 65536, PROT_READ, MAP_SHARED, fd, 0);\n"
268           "}" },
269         { "HAVE_PROC_SELF_MAPS", DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE, NULL, NULL,
270           "#include <sys/types.h>\n"
271           "#include <sys/stat.h>\n"
272           "#include <fcntl.h>\n"
273           "int main(void) {\n"
274           "     return open(\"/proc/self/maps\", O_RDONLY) != -1 ? 0 : 1;\n"
275           "}\n" },
276         { "HAVE_QSORT_R_PRIVATE_LAST",
277           DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE, NULL, NULL,
278           "#ifndef _GNU_SOURCE\n"
279           "#define _GNU_SOURCE\n"
280           "#endif\n"
281           "#include <stdlib.h>\n"
282           "static int cmp(const void *lp, const void *rp, void *priv) {\n"
283           " *(unsigned int *)priv = 1;\n"
284           " return *(const int *)lp - *(const int *)rp; }\n"
285           "int main(void) {\n"
286           " int array[] = { 9, 2, 5 };\n"
287           " unsigned int called = 0;\n"
288           " qsort_r(array, 3, sizeof(int), cmp, &called);\n"
289           " return called && array[0] == 2 && array[1] == 5 && array[2] == 9 ? 0 : 1;\n"
290           "}\n" },
291         { "HAVE_STRUCT_TIMESPEC",
292           DEFINES_FUNC, NULL, NULL,
293           "#include <time.h>\n"
294           "static void func(void) {\n"
295           "     struct timespec ts;\n"
296           "     ts.tv_sec = ts.tv_nsec = 1;\n"
297           "}\n" },
298         { "HAVE_SECTION_START_STOP",
299           DEFINES_FUNC, NULL, NULL,
300           "static void *__attribute__((__section__(\"mysec\"))) p = &p;\n"
301           "static int func(void) {\n"
302           "     extern void *__start_mysec[], *__stop_mysec[];\n"
303           "     return __stop_mysec - __start_mysec;\n"
304           "}\n" },
305         { "HAVE_STACK_GROWS_UPWARDS", DEFINES_EVERYTHING|EXECUTE, NULL, NULL,
306           "#include <stddef.h>\n"
307           "static ptrdiff_t nest(const void *base, unsigned int i)\n"
308           "{\n"
309           "     if (i == 0)\n"
310           "             return (const char *)&i - (const char *)base;\n"
311           "     return nest(base, i-1);\n"
312           "}\n"
313           "int main(int argc, char *argv[]) {\n"
314           "     (void)argv;\n"
315           "     return (nest(&argc, argc) > 0) ? 0 : 1;\n"
316           "}\n" },
317         { "HAVE_STATEMENT_EXPR", INSIDE_MAIN, NULL, NULL,
318           "return ({ int x = argc; x == argc ? 0 : 1; });" },
319         { "HAVE_SYS_FILIO_H", OUTSIDE_MAIN, NULL, NULL, /* Solaris needs this for FIONREAD */
320           "#include <sys/filio.h>\n" },
321         { "HAVE_SYS_TERMIOS_H", OUTSIDE_MAIN, NULL, NULL,
322           "#include <sys/termios.h>\n" },
323         { "HAVE_SYS_UNISTD_H", OUTSIDE_MAIN, NULL, NULL,
324           "#include <sys/unistd.h>\n" },
325         { "HAVE_TYPEOF", INSIDE_MAIN, NULL, NULL,
326           "__typeof__(argc) i; i = argc; return i == argc ? 0 : 1;" },
327         { "HAVE_UNALIGNED_ACCESS", DEFINES_EVERYTHING|EXECUTE, NULL, NULL,
328           "#include <string.h>\n"
329           "int main(int argc, char *argv[]) {\n"
330           "     (void)argc;\n"
331           "     char pad[sizeof(int *) * 1];\n"
332           "     strncpy(pad, argv[0], sizeof(pad));\n"
333           "     int *x = (int *)pad, *y = (int *)(pad + 1);\n"
334           "     return *x == *y;\n"
335           "}\n" },
336         { "HAVE_UTIME", DEFINES_FUNC, NULL, NULL,
337           "#include <sys/types.h>\n"
338           "#include <utime.h>\n"
339           "static int func(const char *filename) {\n"
340           "     struct utimbuf times = { 0 };\n"
341           "     return utime(filename, &times);\n"
342           "}" },
343         { "HAVE_WARN_UNUSED_RESULT", DEFINES_FUNC, NULL, NULL,
344           "#include <sys/types.h>\n"
345           "#include <utime.h>\n"
346           "static __attribute__((warn_unused_result)) int func(int i) {\n"
347           "     return i + 1;\n"
348           "}" },
349         { "HAVE_OPENMP", INSIDE_MAIN, NULL, NULL,
350           "int i;\n"
351           "#pragma omp parallel for\n"
352           "for(i = 0; i < 0; i++) {};\n"
353           "return 0;\n",
354           "-Werror -fopenmp" },
355         { "HAVE_VALGRIND_MEMCHECK_H", OUTSIDE_MAIN, NULL, NULL,
356           "#include <valgrind/memcheck.h>\n" },
357         { "HAVE_UCONTEXT", DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE,
358           NULL, NULL,
359           "#include <ucontext.h>\n"
360           "static int x = 0;\n"
361           "static char stack[2048];\n"
362           "static ucontext_t a, b;\n"
363           "static void fn(void) {\n"
364           "     x |= 2;\n"
365           "     setcontext(&b);\n"
366           "     x |= 4;\n"
367           "}\n"
368           "int main(void) {\n"
369           "     x |= 1;\n"
370           "     getcontext(&a);\n"
371           "     a.uc_stack.ss_sp = stack;\n"
372           "     a.uc_stack.ss_size = sizeof(stack);\n"
373           "     makecontext(&a, fn, 0);\n"
374           "     swapcontext(&b, &a);\n"
375           "     return (x == 3) ? 0 : 1;\n"
376           "}\n"
377         },
378         { "HAVE_POINTER_SAFE_MAKECONTEXT", DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE,
379           "HAVE_UCONTEXT", NULL,
380           "#include <stddef.h>\n"
381           "#include <ucontext.h>\n"
382           "static int worked = 0;\n"
383           "static char stack[1024];\n"
384           "static ucontext_t a, b;\n"
385           "static void fn(void *p, void *q) {\n"
386           "     void *cp = &worked;\n"
387           "     void *cq = (void *)(~((ptrdiff_t)cp));\n"
388           "     if ((p == cp) && (q == cq))\n"
389           "             worked = 1;\n"
390           "     setcontext(&b);\n"
391           "}\n"
392           "int main(void) {\n"
393           "     void *ap = &worked;\n"
394           "     void *aq = (void *)(~((ptrdiff_t)ap));\n"
395           "     getcontext(&a);\n"
396           "     a.uc_stack.ss_sp = stack;\n"
397           "     a.uc_stack.ss_size = sizeof(stack);\n"
398           "     makecontext(&a, (void (*)(void))fn, 2, ap, aq);\n"
399           "     swapcontext(&b, &a);\n"
400           "     return worked ? 0 : 1;\n"
401           "}\n"
402         },
403 };
404
405 static void c12r_err(int eval, const char *fmt, ...)
406 {
407         int err_errno = errno;
408         va_list ap;
409
410         fprintf(stderr, "%s: ", progname);
411         va_start(ap, fmt);
412         vfprintf(stderr, fmt, ap);
413         va_end(ap);
414         fprintf(stderr, ": %s\n", strerror(err_errno));
415         exit(eval);
416 }
417
418 static void c12r_errx(int eval, const char *fmt, ...)
419 {
420         va_list ap;
421
422         fprintf(stderr, "%s: ", progname);
423         va_start(ap, fmt);
424         vfprintf(stderr, fmt, ap);
425         va_end(ap);
426         fprintf(stderr, "\n");
427         exit(eval);
428 }
429
430 static size_t fcopy(FILE *fsrc, FILE *fdst)
431 {
432         char buffer[BUFSIZ];
433         size_t rsize, wsize;
434         size_t copied = 0;
435
436         while ((rsize = fread(buffer, 1, BUFSIZ, fsrc)) > 0) {
437                 wsize = fwrite(buffer, 1, rsize, fdst);
438                 copied += wsize;
439                 if (wsize != rsize)
440                         break;
441         }
442
443         return copied;
444 }
445
446 static char *grab_stream(FILE *file)
447 {
448         size_t max, ret, size = 0;
449         char *buffer;
450
451         max = BUFSIZ;
452         buffer = malloc(max);
453         while ((ret = fread(buffer+size, 1, max - size, file)) == max - size) {
454                 size += ret;
455                 buffer = realloc(buffer, max *= 2);
456         }
457         size += ret;
458         if (ferror(file))
459                 c12r_err(1, "reading from command");
460         buffer[size] = '\0';
461         return buffer;
462 }
463
464 static char *run(const char *cmd, int *exitstatus)
465 {
466         static const char redir[] = " 2>&1";
467         size_t cmdlen;
468         char *cmdredir;
469         FILE *cmdout;
470         char *ret;
471
472         cmdlen = strlen(cmd);
473         cmdredir = malloc(cmdlen + sizeof(redir));
474         memcpy(cmdredir, cmd, cmdlen);
475         memcpy(cmdredir + cmdlen, redir, sizeof(redir));
476
477         cmdout = popen(cmdredir, "r");
478         if (!cmdout)
479                 c12r_err(1, "popen \"%s\"", cmdredir);
480
481         free(cmdredir);
482
483         ret = grab_stream(cmdout);
484         *exitstatus = pclose(cmdout);
485         return ret;
486 }
487
488 static char *connect_args(const char *argv[], const char *outflag,
489                 const char *files)
490 {
491         unsigned int i;
492         char *ret;
493         size_t len = strlen(outflag) + strlen(files) + 1;
494
495         for (i = 1; argv[i]; i++)
496                 len += 1 + strlen(argv[i]);
497
498         ret = malloc(len);
499         len = 0;
500         for (i = 1; argv[i]; i++) {
501                 strcpy(ret + len, argv[i]);
502                 len += strlen(argv[i]);
503                 if (argv[i+1] || *outflag)
504                         ret[len++] = ' ';
505         }
506         strcpy(ret + len, outflag);
507         len += strlen(outflag);
508         strcpy(ret + len, files);
509         return ret;
510 }
511
512 static struct test *find_test(const char *name)
513 {
514         unsigned int i;
515
516         for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) {
517                 if (strcmp(tests[i].name, name) == 0)
518                         return &tests[i];
519         }
520         abort();
521 }
522
523 #define PRE_BOILERPLATE "/* Test program generated by configurator. */\n"
524 #define MAIN_START_BOILERPLATE \
525         "int main(int argc, char *argv[]) {\n" \
526         "       (void)argc;\n" \
527         "       (void)argv;\n"
528 #define USE_FUNC_BOILERPLATE "(void)func;\n"
529 #define MAIN_BODY_BOILERPLATE "return 0;\n"
530 #define MAIN_END_BOILERPLATE "}\n"
531
532 static bool run_test(const char *cmd, struct test *test)
533 {
534         char *output, *newcmd;
535         FILE *outf;
536         int status;
537
538         if (test->done)
539                 return test->answer;
540
541         if (test->depends) {
542                 size_t len;
543                 const char *deps = test->depends;
544                 char *dep;
545
546                 /* Space-separated dependencies, could be ! for inverse. */
547                 while ((len = strcspn(deps, " ")) != 0) {
548                         bool positive = true;
549                         if (deps[len]) {
550                                 dep = strdup(deps);
551                                 dep[len] = '\0';
552                         } else {
553                                 dep = (char *)deps;
554                         }
555
556                         if (dep[0] == '!') {
557                                 dep++;
558                                 positive = false;
559                         }
560                         if (run_test(cmd, find_test(dep)) != positive) {
561                                 test->answer = false;
562                                 test->done = true;
563                                 return test->answer;
564                         }
565                         if (deps[len])
566                                 free(dep);
567
568                         deps += len;
569                         deps += strspn(deps, " ");
570                 }
571         }
572
573         outf = fopen(INPUT_FILE, verbose > 1 ? "w+" : "w");
574         if (!outf)
575                 c12r_err(1, "creating %s", INPUT_FILE);
576
577         fprintf(outf, "%s", PRE_BOILERPLATE);
578         switch (test->style & ~(EXECUTE|MAY_NOT_COMPILE)) {
579         case INSIDE_MAIN:
580                 fprintf(outf, "%s", MAIN_START_BOILERPLATE);
581                 fprintf(outf, "%s", test->fragment);
582                 fprintf(outf, "%s", MAIN_END_BOILERPLATE);
583                 break;
584         case OUTSIDE_MAIN:
585                 fprintf(outf, "%s", test->fragment);
586                 fprintf(outf, "%s", MAIN_START_BOILERPLATE);
587                 fprintf(outf, "%s", MAIN_BODY_BOILERPLATE);
588                 fprintf(outf, "%s", MAIN_END_BOILERPLATE);
589                 break;
590         case DEFINES_FUNC:
591                 fprintf(outf, "%s", test->fragment);
592                 fprintf(outf, "%s", MAIN_START_BOILERPLATE);
593                 fprintf(outf, "%s", USE_FUNC_BOILERPLATE);
594                 fprintf(outf, "%s", MAIN_BODY_BOILERPLATE);
595                 fprintf(outf, "%s", MAIN_END_BOILERPLATE);
596                 break;
597         case DEFINES_EVERYTHING:
598                 fprintf(outf, "%s", test->fragment);
599                 break;
600         default:
601                 abort();
602
603         }
604
605         if (verbose > 1) {
606                 fseek(outf, 0, SEEK_SET);
607                 fcopy(outf, stdout);
608         }
609
610         fclose(outf);
611
612         newcmd = strdup(cmd);
613
614         if (test->flags) {
615                 newcmd = realloc(newcmd, strlen(newcmd) + strlen(" ")
616                                 + strlen(test->flags) + 1);
617                 strcat(newcmd, " ");
618                 strcat(newcmd, test->flags);
619                 if (verbose > 1)
620                         printf("Extra flags line: %s", newcmd);
621         }
622
623         if (test->link) {
624                 newcmd = realloc(newcmd, strlen(newcmd) + strlen(" ")
625                                 + strlen(test->link) + 1);
626                 strcat(newcmd, " ");
627                 strcat(newcmd, test->link);
628                 if (verbose > 1)
629                         printf("Extra link line: %s", newcmd);
630         }
631
632         output = run(newcmd, &status);
633
634         free(newcmd);
635
636         if (status != 0 || strstr(output, "warning")) {
637                 if (verbose)
638                         printf("Compile %s for %s, status %i: %s\n",
639                                status ? "fail" : "warning",
640                                test->name, status, output);
641                 if ((test->style & EXECUTE) && !(test->style & MAY_NOT_COMPILE))
642                         c12r_errx(1, "Test for %s did not compile:\n%s",
643                                   test->name, output);
644                 test->answer = false;
645                 free(output);
646         } else {
647                 /* Compile succeeded. */
648                 free(output);
649                 /* We run INSIDE_MAIN tests for sanity checking. */
650                 if ((test->style & EXECUTE) || (test->style & INSIDE_MAIN)) {
651                         output = run("." DIR_SEP OUTPUT_FILE, &status);
652                         if (!(test->style & EXECUTE) && status != 0)
653                                 c12r_errx(1, "Test for %s failed with %i:\n%s",
654                                           test->name, status, output);
655                         if (verbose && status)
656                                 printf("%s exited %i\n", test->name, status);
657                         free(output);
658                 }
659                 test->answer = (status == 0);
660         }
661         test->done = true;
662
663         if (test->answer && test->overrides) {
664                 struct test *override = find_test(test->overrides);
665                 override->done = true;
666                 override->answer = true;
667         }
668         return test->answer;
669 }
670
671 int main(int argc, const char *argv[])
672 {
673         char *cmd;
674         unsigned int i;
675         const char *default_args[]
676                 = { "", DEFAULT_COMPILER, DEFAULT_FLAGS, NULL };
677         const char *outflag = DEFAULT_OUTPUT_EXE_FLAG;
678         const char *configurator_cc = NULL;
679         const char *orig_cc;
680
681         if (argc > 0)
682                 progname = argv[0];
683
684         while (argc > 1) {
685                 if (strcmp(argv[1], "--help") == 0) {
686                         printf("Usage: configurator [-v] [-O<outflag>] [--configurator-cc=<compiler-for-tests>] [<compiler> <flags>...]\n"
687                                "  <compiler> <flags> will have \"<outflag> <outfile> <infile.c>\" appended\n"
688                                "Default: %s %s %s\n",
689                                DEFAULT_COMPILER, DEFAULT_FLAGS,
690                                DEFAULT_OUTPUT_EXE_FLAG);
691                         exit(0);
692                 }
693                 if (strncmp(argv[1], "-O", 2) == 0) {
694                         argc--;
695                         argv++;
696                         outflag = argv[1] + 2;
697                         if (!*outflag) {
698                                 fprintf(stderr,
699                                         "%s: option requires an argument -- O\n",
700                                         argv[0]);
701                                 exit(1);
702                         }
703                 } else if (strcmp(argv[1], "-v") == 0) {
704                         argc--;
705                         argv++;
706                         verbose++;
707                 } else if (strcmp(argv[1], "-vv") == 0) {
708                         argc--;
709                         argv++;
710                         verbose += 2;
711                 } else if (strncmp(argv[1], "--configurator-cc=", 18) == 0) {
712                         configurator_cc = argv[1] + 18;
713                         argc--;
714                         argv++;
715                 } else {
716                         break;
717                 }
718         }
719
720         if (argc == 1)
721                 argv = default_args;
722
723         orig_cc = argv[1];
724         if (configurator_cc)
725                 argv[1] = configurator_cc;
726
727         cmd = connect_args(argv, outflag, OUTPUT_FILE " " INPUT_FILE);
728         for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++)
729                 run_test(cmd, &tests[i]);
730         free(cmd);
731
732         remove(OUTPUT_FILE);
733         remove(INPUT_FILE);
734
735         printf("/* Generated by CCAN configurator */\n"
736                "#ifndef CCAN_CONFIG_H\n"
737                "#define CCAN_CONFIG_H\n");
738         printf("#ifndef _GNU_SOURCE\n");
739         printf("#define _GNU_SOURCE /* Always use GNU extensions. */\n");
740         printf("#endif\n");
741         printf("#define CCAN_COMPILER \"%s\"\n", orig_cc);
742         cmd = connect_args(argv + 1, "", "");
743         printf("#define CCAN_CFLAGS \"%s\"\n", cmd);
744         free(cmd);
745         printf("#define CCAN_OUTPUT_EXE_CFLAG \"%s\"\n\n", outflag);
746         /* This one implies "#include <ccan/..." works, eg. for tdb2.h */
747         printf("#define HAVE_CCAN 1\n");
748         for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++)
749                 printf("#define %s %u\n", tests[i].name, tests[i].answer);
750         printf("#endif /* CCAN_CONFIG_H */\n");
751         return 0;
752 }