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