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