]> git.ozlabs.org Git - ccan/blob - tools/configurator/configurator.c
tools/configurator: --extra-tests to read more test descriptions from stdin.
[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 #include <unistd.h>
36
37 #ifdef _MSC_VER
38 #define popen _popen
39 #define pclose _pclose
40 #endif
41
42 #ifdef _MSC_VER
43 #define DEFAULT_COMPILER "cl"
44 /* Note:  Dash options avoid POSIX path conversion when used under msys bash
45  *        and are therefore preferred to slash (e.g. -nologo over /nologo)
46  * Note:  Disable Warning 4200 "nonstandard extension used : zero-sized array
47  *        in struct/union" for flexible array members.
48  */
49 #define DEFAULT_FLAGS "-nologo -Zi -W4 -wd4200 " \
50         "-D_CRT_NONSTDC_NO_WARNINGS -D_CRT_SECURE_NO_WARNINGS"
51 #define DEFAULT_OUTPUT_EXE_FLAG "-Fe:"
52 #else
53 #define DEFAULT_COMPILER "cc"
54 #define DEFAULT_FLAGS "-g3 -ggdb -Wall -Wundef -Wmissing-prototypes -Wmissing-declarations -Wstrict-prototypes -Wold-style-definition"
55 #define DEFAULT_OUTPUT_EXE_FLAG "-o"
56 #endif
57
58 #define OUTPUT_FILE "configurator.out"
59 #define INPUT_FILE "configuratortest.c"
60
61 #ifdef _WIN32
62 #define DIR_SEP   "\\"
63 #else
64 #define DIR_SEP   "/"
65 #endif
66
67 static const char *progname = "";
68 static int verbose;
69 static bool like_a_libtool = false;
70
71 struct test {
72         const char *name;
73         const char *desc;
74         /*
75          * Template style flags (pick one):
76          * OUTSIDE_MAIN:
77          * - put a simple boilerplate main below it.
78          * DEFINES_FUNC:
79          * - defines a static function called func; adds ref to avoid warnings
80          * INSIDE_MAIN:
81          * - put this inside main().
82          * DEFINES_EVERYTHING:
83          * - don't add any boilerplate at all.
84          *
85          * Execution flags:
86          * EXECUTE:
87          * - a runtime test; must compile, exit 0 means flag is set.
88          * MAY_NOT_COMPILE:
89          * - Only useful with EXECUTE: don't get upset if it doesn't compile.
90          * <nothing>:
91          * - a compile test, if it compiles must run and exit 0.
92          */
93         const char *style;
94         const char *depends;
95         const char *link;
96         const char *fragment;
97         const char *flags;
98         const char *overrides; /* On success, force this to '1' */
99         bool done;
100         bool answer;
101 };
102
103 /* Terminated by a NULL name */
104 static struct test *tests;
105
106 static const struct test base_tests[] = {
107         { "HAVE_32BIT_OFF_T", "off_t is 32 bits",
108           "DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE", NULL, NULL,
109           "#include <sys/types.h>\n"
110           "int main(void) {\n"
111           "     return sizeof(off_t) == 4 ? 0 : 1;\n"
112           "}\n" },
113         { "HAVE_ALIGNOF", "__alignof__ support",
114           "INSIDE_MAIN", NULL, NULL,
115           "return __alignof__(double) > 0 ? 0 : 1;" },
116         { "HAVE_ASPRINTF", "asprintf() declaration",
117           "DEFINES_FUNC", NULL, NULL,
118           "#ifndef _GNU_SOURCE\n"
119           "#define _GNU_SOURCE\n"
120           "#endif\n"
121           "#include <stdio.h>\n"
122           "static char *func(int x) {"
123           "     char *p;\n"
124           "     if (asprintf(&p, \"%u\", x) == -1) \n"
125           "             p = NULL;\n"
126           "     return p;\n"
127           "}" },
128         { "HAVE_ATTRIBUTE_COLD", "__attribute__((cold)) support",
129           "DEFINES_FUNC", NULL, NULL,
130           "static int __attribute__((cold)) func(int x) { return x; }" },
131         { "HAVE_ATTRIBUTE_CONST", "__attribute__((const)) support",
132           "DEFINES_FUNC", NULL, NULL,
133           "static int __attribute__((const)) func(int x) { return x; }" },
134         { "HAVE_ATTRIBUTE_PURE", "__attribute__((pure)) support",
135           "DEFINES_FUNC", NULL, NULL,
136           "static int __attribute__((pure)) func(int x) { return x; }" },
137         { "HAVE_ATTRIBUTE_MAY_ALIAS", "__attribute__((may_alias)) support",
138           "OUTSIDE_MAIN", NULL, NULL,
139           "typedef short __attribute__((__may_alias__)) short_a;" },
140         { "HAVE_ATTRIBUTE_NORETURN", "__attribute__((noreturn)) support",
141           "DEFINES_FUNC", NULL, NULL,
142           "#include <stdlib.h>\n"
143           "static void __attribute__((noreturn)) func(int x) { exit(x); }" },
144         { "HAVE_ATTRIBUTE_PRINTF", "__attribute__ format printf support",
145           "DEFINES_FUNC", NULL, NULL,
146           "static void __attribute__((format(__printf__, 1, 2))) func(const char *fmt, ...) { (void)fmt; }" },
147         { "HAVE_ATTRIBUTE_UNUSED", "__attribute__((unused)) support",
148           "OUTSIDE_MAIN", NULL, NULL,
149           "static int __attribute__((unused)) func(int x) { return x; }" },
150         { "HAVE_ATTRIBUTE_USED", "__attribute__((used)) support",
151           "OUTSIDE_MAIN", NULL, NULL,
152           "static int __attribute__((used)) func(int x) { return x; }" },
153         { "HAVE_BACKTRACE", "backtrace() in <execinfo.h>",
154           "DEFINES_FUNC", NULL, NULL,
155           "#include <execinfo.h>\n"
156           "static int func(int x) {"
157           "     void *bt[10];\n"
158           "     return backtrace(bt, 10) < x;\n"
159           "}" },
160         { "HAVE_BIG_ENDIAN", "big endian",
161           "INSIDE_MAIN|EXECUTE", NULL, NULL,
162           "union { int i; char c[sizeof(int)]; } u;\n"
163           "u.i = 0x01020304;\n"
164           "return u.c[0] == 0x01 && u.c[1] == 0x02 && u.c[2] == 0x03 && u.c[3] == 0x04 ? 0 : 1;" },
165         { "HAVE_BSWAP_64", "bswap64 in byteswap.h",
166           "DEFINES_FUNC", "HAVE_BYTESWAP_H", NULL,
167           "#include <byteswap.h>\n"
168           "static int func(int x) { return bswap_64(x); }" },
169         { "HAVE_BUILTIN_CHOOSE_EXPR", "__builtin_choose_expr support",
170           "INSIDE_MAIN", NULL, NULL,
171           "return __builtin_choose_expr(1, 0, \"garbage\");" },
172         { "HAVE_BUILTIN_CLZ", "__builtin_clz support",
173           "INSIDE_MAIN", NULL, NULL,
174           "return __builtin_clz(1) == (sizeof(int)*8 - 1) ? 0 : 1;" },
175         { "HAVE_BUILTIN_CLZL", "__builtin_clzl support",
176           "INSIDE_MAIN", NULL, NULL,
177           "return __builtin_clzl(1) == (sizeof(long)*8 - 1) ? 0 : 1;" },
178         { "HAVE_BUILTIN_CLZLL", "__builtin_clzll support",
179           "INSIDE_MAIN", NULL, NULL,
180           "return __builtin_clzll(1) == (sizeof(long long)*8 - 1) ? 0 : 1;" },
181         { "HAVE_BUILTIN_CTZ", "__builtin_ctz support",
182           "INSIDE_MAIN", NULL, NULL,
183           "return __builtin_ctz(1 << (sizeof(int)*8 - 1)) == (sizeof(int)*8 - 1) ? 0 : 1;" },
184         { "HAVE_BUILTIN_CTZL", "__builtin_ctzl support",
185           "INSIDE_MAIN", NULL, NULL,
186           "return __builtin_ctzl(1UL << (sizeof(long)*8 - 1)) == (sizeof(long)*8 - 1) ? 0 : 1;" },
187         { "HAVE_BUILTIN_CTZLL", "__builtin_ctzll support",
188           "INSIDE_MAIN", NULL, NULL,
189           "return __builtin_ctzll(1ULL << (sizeof(long long)*8 - 1)) == (sizeof(long long)*8 - 1) ? 0 : 1;" },
190         { "HAVE_BUILTIN_CONSTANT_P", "__builtin_constant_p support",
191           "INSIDE_MAIN", NULL, NULL,
192           "return __builtin_constant_p(1) ? 0 : 1;" },
193         { "HAVE_BUILTIN_EXPECT", "__builtin_expect support",
194           "INSIDE_MAIN", NULL, NULL,
195           "return __builtin_expect(argc == 1, 1) ? 0 : 1;" },
196         { "HAVE_BUILTIN_FFS", "__builtin_ffs support",
197           "INSIDE_MAIN", NULL, NULL,
198           "return __builtin_ffs(0) == 0 ? 0 : 1;" },
199         { "HAVE_BUILTIN_FFSL", "__builtin_ffsl support",
200           "INSIDE_MAIN", NULL, NULL,
201           "return __builtin_ffsl(0L) == 0 ? 0 : 1;" },
202         { "HAVE_BUILTIN_FFSLL", "__builtin_ffsll support",
203           "INSIDE_MAIN", NULL, NULL,
204           "return __builtin_ffsll(0LL) == 0 ? 0 : 1;" },
205         { "HAVE_BUILTIN_POPCOUNT", "__builtin_popcount support",
206           "INSIDE_MAIN", NULL, NULL,
207           "return __builtin_popcount(255) == 8 ? 0 : 1;" },
208         { "HAVE_BUILTIN_POPCOUNTL",  "__builtin_popcountl support",
209           "INSIDE_MAIN", NULL, NULL,
210           "return __builtin_popcountl(255L) == 8 ? 0 : 1;" },
211         { "HAVE_BUILTIN_POPCOUNTLL", "__builtin_popcountll support",
212           "INSIDE_MAIN", NULL, NULL,
213           "return __builtin_popcountll(255LL) == 8 ? 0 : 1;" },
214         { "HAVE_BUILTIN_TYPES_COMPATIBLE_P", "__builtin_types_compatible_p support",
215           "INSIDE_MAIN", NULL, NULL,
216           "return __builtin_types_compatible_p(char *, int) ? 1 : 0;" },
217         { "HAVE_ICCARM_INTRINSICS", "<intrinsics.h>",
218           "DEFINES_FUNC", NULL, NULL,
219           "#include <intrinsics.h>\n"
220           "int func(int v) {\n"
221           "     return __CLZ(__RBIT(v));\n"
222           "}" },
223         { "HAVE_BYTESWAP_H", "<byteswap.h>",
224           "OUTSIDE_MAIN", NULL, NULL,
225           "#include <byteswap.h>\n" },
226         { "HAVE_CLOCK_GETTIME", "clock_gettime() declaration",
227           "DEFINES_FUNC", "HAVE_STRUCT_TIMESPEC", NULL,
228           "#include <time.h>\n"
229           "static struct timespec func(void) {\n"
230           "     struct timespec ts;\n"
231           "     clock_gettime(CLOCK_REALTIME, &ts);\n"
232           "     return ts;\n"
233           "}\n" },
234         { "HAVE_CLOCK_GETTIME_IN_LIBRT", "clock_gettime() in librt",
235           "DEFINES_FUNC",
236           "HAVE_STRUCT_TIMESPEC !HAVE_CLOCK_GETTIME",
237           "-lrt",
238           "#include <time.h>\n"
239           "static struct timespec func(void) {\n"
240           "     struct timespec ts;\n"
241           "     clock_gettime(CLOCK_REALTIME, &ts);\n"
242           "     return ts;\n"
243           "}\n",
244           /* This means HAVE_CLOCK_GETTIME, too */
245           "HAVE_CLOCK_GETTIME" },
246         { "HAVE_COMPOUND_LITERALS", "compound literal support",
247           "INSIDE_MAIN", NULL, NULL,
248           "int *foo = (int[]) { 1, 2, 3, 4 };\n"
249           "return foo[0] ? 0 : 1;" },
250         { "HAVE_FCHDIR", "fchdir support",
251           "DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE", NULL, NULL,
252           "#include <sys/types.h>\n"
253           "#include <sys/stat.h>\n"
254           "#include <fcntl.h>\n"
255           "#include <unistd.h>\n"
256           "int main(void) {\n"
257           "     int fd = open(\"..\", O_RDONLY);\n"
258           "     return fchdir(fd) == 0 ? 0 : 1;\n"
259           "}\n" },
260         { "HAVE_ERR_H", "<err.h>",
261           "DEFINES_FUNC", NULL, NULL,
262           "#include <err.h>\n"
263           "static void func(int arg) {\n"
264           "     if (arg == 0)\n"
265           "             err(1, \"err %u\", arg);\n"
266           "     if (arg == 1)\n"
267           "             errx(1, \"err %u\", arg);\n"
268           "     if (arg == 3)\n"
269           "             warn(\"warn %u\", arg);\n"
270           "     if (arg == 4)\n"
271           "             warnx(\"warn %u\", arg);\n"
272           "}\n" },
273         { "HAVE_FILE_OFFSET_BITS", "_FILE_OFFSET_BITS to get 64-bit offsets",
274           "DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE",
275           "HAVE_32BIT_OFF_T", NULL,
276           "#define _FILE_OFFSET_BITS 64\n"
277           "#include <sys/types.h>\n"
278           "int main(void) {\n"
279           "     return sizeof(off_t) == 8 ? 0 : 1;\n"
280           "}\n" },
281         { "HAVE_FOR_LOOP_DECLARATION", "for loop declaration support",
282           "INSIDE_MAIN", NULL, NULL,
283           "int ret = 1;\n"
284           "for (int i = 0; i < argc; i++) { ret = 0; };\n"
285           "return ret;" },
286         { "HAVE_FLEXIBLE_ARRAY_MEMBER", "flexible array member support",
287           "OUTSIDE_MAIN", NULL, NULL,
288           "struct foo { unsigned int x; int arr[]; };" },
289         { "HAVE_GETPAGESIZE", "getpagesize() in <unistd.h>",
290           "DEFINES_FUNC", NULL, NULL,
291           "#include <unistd.h>\n"
292           "static int func(void) { return getpagesize(); }" },
293         { "HAVE_ISBLANK", "isblank() in <ctype.h>",
294           "DEFINES_FUNC", NULL, NULL,
295           "#ifndef _GNU_SOURCE\n"
296           "#define _GNU_SOURCE\n"
297           "#endif\n"
298           "#include <ctype.h>\n"
299           "static int func(void) { return isblank(' '); }" },
300         { "HAVE_LITTLE_ENDIAN", "little endian",
301           "INSIDE_MAIN|EXECUTE", NULL, NULL,
302           "union { int i; char c[sizeof(int)]; } u;\n"
303           "u.i = 0x01020304;\n"
304           "return u.c[0] == 0x04 && u.c[1] == 0x03 && u.c[2] == 0x02 && u.c[3] == 0x01 ? 0 : 1;" },
305         { "HAVE_MEMMEM", "memmem in <string.h>",
306           "DEFINES_FUNC", NULL, NULL,
307           "#ifndef _GNU_SOURCE\n"
308           "#define _GNU_SOURCE\n"
309           "#endif\n"
310           "#include <string.h>\n"
311           "static void *func(void *h, size_t hl, void *n, size_t nl) {\n"
312           "return memmem(h, hl, n, nl);"
313           "}\n", },
314         { "HAVE_MEMRCHR", "memrchr in <string.h>",
315           "DEFINES_FUNC", NULL, NULL,
316           "#ifndef _GNU_SOURCE\n"
317           "#define _GNU_SOURCE\n"
318           "#endif\n"
319           "#include <string.h>\n"
320           "static void *func(void *s, int c, size_t n) {\n"
321           "return memrchr(s, c, n);"
322           "}\n", },
323         { "HAVE_MMAP", "mmap() declaration",
324           "DEFINES_FUNC", NULL, NULL,
325           "#include <sys/mman.h>\n"
326           "static void *func(int fd) {\n"
327           "     return mmap(0, 65536, PROT_READ, MAP_SHARED, fd, 0);\n"
328           "}" },
329         { "HAVE_PROC_SELF_MAPS", "/proc/self/maps exists",
330           "DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE", NULL, NULL,
331           "#include <sys/types.h>\n"
332           "#include <sys/stat.h>\n"
333           "#include <fcntl.h>\n"
334           "int main(void) {\n"
335           "     return open(\"/proc/self/maps\", O_RDONLY) != -1 ? 0 : 1;\n"
336           "}\n" },
337         { "HAVE_QSORT_R_PRIVATE_LAST", "qsort_r cmp takes trailing arg",
338           "DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE", NULL, NULL,
339           "#ifndef _GNU_SOURCE\n"
340           "#define _GNU_SOURCE\n"
341           "#endif\n"
342           "#include <stdlib.h>\n"
343           "static int cmp(const void *lp, const void *rp, void *priv) {\n"
344           " *(unsigned int *)priv = 1;\n"
345           " return *(const int *)lp - *(const int *)rp; }\n"
346           "int main(void) {\n"
347           " int array[] = { 9, 2, 5 };\n"
348           " unsigned int called = 0;\n"
349           " qsort_r(array, 3, sizeof(int), cmp, &called);\n"
350           " return called && array[0] == 2 && array[1] == 5 && array[2] == 9 ? 0 : 1;\n"
351           "}\n" },
352         { "HAVE_STRUCT_TIMESPEC", "struct timespec declaration",
353           "DEFINES_FUNC", NULL, NULL,
354           "#include <time.h>\n"
355           "static void func(void) {\n"
356           "     struct timespec ts;\n"
357           "     ts.tv_sec = ts.tv_nsec = 1;\n"
358           "}\n" },
359         { "HAVE_SECTION_START_STOP", "__attribute__((section)) and __start/__stop",
360           "DEFINES_FUNC", NULL, NULL,
361           "static void *__attribute__((__section__(\"mysec\"))) p = &p;\n"
362           "static int func(void) {\n"
363           "     extern void *__start_mysec[], *__stop_mysec[];\n"
364           "     return __stop_mysec - __start_mysec;\n"
365           "}\n" },
366         { "HAVE_STACK_GROWS_UPWARDS", "stack grows upwards",
367           "DEFINES_EVERYTHING|EXECUTE", NULL, NULL,
368           "#include <stddef.h>\n"
369           "static ptrdiff_t nest(const void *base, unsigned int i)\n"
370           "{\n"
371           "     if (i == 0)\n"
372           "             return (const char *)&i - (const char *)base;\n"
373           "     return nest(base, i-1);\n"
374           "}\n"
375           "int main(int argc, char *argv[]) {\n"
376           "     (void)argv;\n"
377           "     return (nest(&argc, argc) > 0) ? 0 : 1;\n"
378           "}\n" },
379         { "HAVE_STATEMENT_EXPR", "statement expression support",
380           "INSIDE_MAIN", NULL, NULL,
381           "return ({ int x = argc; x == argc ? 0 : 1; });" },
382         { "HAVE_SYS_FILIO_H", "<sys/filio.h>",
383           "OUTSIDE_MAIN", NULL, NULL, /* Solaris needs this for FIONREAD */
384           "#include <sys/filio.h>\n" },
385         { "HAVE_SYS_TERMIOS_H", "<sys/termios.h>",
386           "OUTSIDE_MAIN", NULL, NULL,
387           "#include <sys/termios.h>\n" },
388         { "HAVE_SYS_UNISTD_H", "<sys/unistd.h>",
389           "OUTSIDE_MAIN", NULL, NULL,
390           "#include <sys/unistd.h>\n" },
391         { "HAVE_TYPEOF", "__typeof__ support",
392           "INSIDE_MAIN", NULL, NULL,
393           "__typeof__(argc) i; i = argc; return i == argc ? 0 : 1;" },
394         { "HAVE_UNALIGNED_ACCESS", "unaligned access to int",
395           "DEFINES_EVERYTHING|EXECUTE", NULL, NULL,
396           "#include <string.h>\n"
397           "int main(int argc, char *argv[]) {\n"
398           "     (void)argc;\n"
399           "     char pad[sizeof(int *) * 1];\n"
400           "     strncpy(pad, argv[0], sizeof(pad));\n"
401           "     int *x = (int *)pad, *y = (int *)(pad + 1);\n"
402           "     return *x == *y;\n"
403           "}\n" },
404         { "HAVE_UTIME", "utime() declaration",
405           "DEFINES_FUNC", NULL, NULL,
406           "#include <sys/types.h>\n"
407           "#include <utime.h>\n"
408           "static int func(const char *filename) {\n"
409           "     struct utimbuf times = { 0 };\n"
410           "     return utime(filename, &times);\n"
411           "}" },
412         { "HAVE_WARN_UNUSED_RESULT", "__attribute__((warn_unused_result))",
413           "DEFINES_FUNC", NULL, NULL,
414           "#include <sys/types.h>\n"
415           "#include <utime.h>\n"
416           "static __attribute__((warn_unused_result)) int func(int i) {\n"
417           "     return i + 1;\n"
418           "}" },
419         { "HAVE_OPENMP", "#pragma omp and -fopenmp support",
420           "INSIDE_MAIN", NULL, NULL,
421           "int i;\n"
422           "#pragma omp parallel for\n"
423           "for(i = 0; i < 0; i++) {};\n"
424           "return 0;\n",
425           "-Werror -fopenmp" },
426         { "HAVE_VALGRIND_MEMCHECK_H", "<valgrind/memcheck.h>",
427           "OUTSIDE_MAIN", NULL, NULL,
428           "#include <valgrind/memcheck.h>\n" },
429         { "HAVE_UCONTEXT", "working <ucontext.h",
430           "DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE",
431           NULL, NULL,
432           "#include <ucontext.h>\n"
433           "static int x = 0;\n"
434           "static char stack[2048];\n"
435           "static ucontext_t a, b;\n"
436           "static void fn(void) {\n"
437           "     x |= 2;\n"
438           "     setcontext(&b);\n"
439           "     x |= 4;\n"
440           "}\n"
441           "int main(void) {\n"
442           "     x |= 1;\n"
443           "     getcontext(&a);\n"
444           "     a.uc_stack.ss_sp = stack;\n"
445           "     a.uc_stack.ss_size = sizeof(stack);\n"
446           "     makecontext(&a, fn, 0);\n"
447           "     swapcontext(&b, &a);\n"
448           "     return (x == 3) ? 0 : 1;\n"
449           "}\n"
450         },
451         { "HAVE_POINTER_SAFE_MAKECONTEXT", "passing pointers via makecontext()",
452           "DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE",
453           "HAVE_UCONTEXT", NULL,
454           "#include <stddef.h>\n"
455           "#include <ucontext.h>\n"
456           "static int worked = 0;\n"
457           "static char stack[1024];\n"
458           "static ucontext_t a, b;\n"
459           "static void fn(void *p, void *q) {\n"
460           "     void *cp = &worked;\n"
461           "     void *cq = (void *)(~((ptrdiff_t)cp));\n"
462           "     if ((p == cp) && (q == cq))\n"
463           "             worked = 1;\n"
464           "     setcontext(&b);\n"
465           "}\n"
466           "int main(void) {\n"
467           "     void *ap = &worked;\n"
468           "     void *aq = (void *)(~((ptrdiff_t)ap));\n"
469           "     getcontext(&a);\n"
470           "     a.uc_stack.ss_sp = stack;\n"
471           "     a.uc_stack.ss_size = sizeof(stack);\n"
472           "     makecontext(&a, (void (*)(void))fn, 2, ap, aq);\n"
473           "     swapcontext(&b, &a);\n"
474           "     return worked ? 0 : 1;\n"
475           "}\n"
476         },
477 };
478
479 static void c12r_err(int eval, const char *fmt, ...)
480 {
481         int err_errno = errno;
482         va_list ap;
483
484         fprintf(stderr, "%s: ", progname);
485         va_start(ap, fmt);
486         vfprintf(stderr, fmt, ap);
487         va_end(ap);
488         fprintf(stderr, ": %s\n", strerror(err_errno));
489         exit(eval);
490 }
491
492 static void c12r_errx(int eval, const char *fmt, ...)
493 {
494         va_list ap;
495
496         fprintf(stderr, "%s: ", progname);
497         va_start(ap, fmt);
498         vfprintf(stderr, fmt, ap);
499         va_end(ap);
500         fprintf(stderr, "\n");
501         exit(eval);
502 }
503
504 static void start_test(const char *what, const char *why)
505 {
506         if (like_a_libtool) {
507                 printf("%s%s... ", what, why);
508                 fflush(stdout);
509         }
510 }
511
512 static void end_test(bool result)
513 {
514         if (like_a_libtool)
515                 printf("%s\n", result ? "yes" : "no");
516 }
517
518 static size_t fcopy(FILE *fsrc, FILE *fdst)
519 {
520         char buffer[BUFSIZ];
521         size_t rsize, wsize;
522         size_t copied = 0;
523
524         while ((rsize = fread(buffer, 1, BUFSIZ, fsrc)) > 0) {
525                 wsize = fwrite(buffer, 1, rsize, fdst);
526                 copied += wsize;
527                 if (wsize != rsize)
528                         break;
529         }
530
531         return copied;
532 }
533
534 static char *grab_stream(FILE *file)
535 {
536         size_t max, ret, size = 0;
537         char *buffer;
538
539         max = BUFSIZ;
540         buffer = malloc(max);
541         while ((ret = fread(buffer+size, 1, max - size, file)) == max - size) {
542                 size += ret;
543                 buffer = realloc(buffer, max *= 2);
544         }
545         size += ret;
546         if (ferror(file))
547                 c12r_err(1, "reading from command");
548         buffer[size] = '\0';
549         return buffer;
550 }
551
552 static char *run(const char *cmd, int *exitstatus)
553 {
554         static const char redir[] = " 2>&1";
555         size_t cmdlen;
556         char *cmdredir;
557         FILE *cmdout;
558         char *ret;
559
560         cmdlen = strlen(cmd);
561         cmdredir = malloc(cmdlen + sizeof(redir));
562         memcpy(cmdredir, cmd, cmdlen);
563         memcpy(cmdredir + cmdlen, redir, sizeof(redir));
564
565         cmdout = popen(cmdredir, "r");
566         if (!cmdout)
567                 c12r_err(1, "popen \"%s\"", cmdredir);
568
569         free(cmdredir);
570
571         ret = grab_stream(cmdout);
572         *exitstatus = pclose(cmdout);
573         return ret;
574 }
575
576 static char *connect_args(const char *argv[], const char *outflag,
577                 const char *files)
578 {
579         unsigned int i;
580         char *ret;
581         size_t len = strlen(outflag) + strlen(files) + 1;
582
583         for (i = 1; argv[i]; i++)
584                 len += 1 + strlen(argv[i]);
585
586         ret = malloc(len);
587         len = 0;
588         for (i = 1; argv[i]; i++) {
589                 strcpy(ret + len, argv[i]);
590                 len += strlen(argv[i]);
591                 if (argv[i+1] || *outflag)
592                         ret[len++] = ' ';
593         }
594         strcpy(ret + len, outflag);
595         len += strlen(outflag);
596         strcpy(ret + len, files);
597         return ret;
598 }
599
600 static struct test *find_test(const char *name)
601 {
602         unsigned int i;
603
604         for (i = 0; tests[i].name; i++) {
605                 if (strcmp(tests[i].name, name) == 0)
606                         return &tests[i];
607         }
608         c12r_errx(2, "Unknown test %s", name);
609         abort();
610 }
611
612 #define PRE_BOILERPLATE "/* Test program generated by configurator. */\n"
613 #define MAIN_START_BOILERPLATE \
614         "int main(int argc, char *argv[]) {\n" \
615         "       (void)argc;\n" \
616         "       (void)argv;\n"
617 #define USE_FUNC_BOILERPLATE "(void)func;\n"
618 #define MAIN_BODY_BOILERPLATE "return 0;\n"
619 #define MAIN_END_BOILERPLATE "}\n"
620
621 static bool run_test(const char *cmd, struct test *test)
622 {
623         char *output, *newcmd;
624         FILE *outf;
625         int status;
626
627         if (test->done)
628                 return test->answer;
629
630         if (test->depends) {
631                 size_t len;
632                 const char *deps = test->depends;
633                 char *dep;
634
635                 /* Space-separated dependencies, could be ! for inverse. */
636                 while ((len = strcspn(deps, " ")) != 0) {
637                         bool positive = true;
638                         if (deps[len]) {
639                                 dep = strdup(deps);
640                                 dep[len] = '\0';
641                         } else {
642                                 dep = (char *)deps;
643                         }
644
645                         if (dep[0] == '!') {
646                                 dep++;
647                                 positive = false;
648                         }
649                         if (run_test(cmd, find_test(dep)) != positive) {
650                                 test->answer = false;
651                                 test->done = true;
652                                 return test->answer;
653                         }
654                         if (deps[len])
655                                 free(dep);
656
657                         deps += len;
658                         deps += strspn(deps, " ");
659                 }
660         }
661
662         outf = fopen(INPUT_FILE, verbose > 1 ? "w+" : "w");
663         if (!outf)
664                 c12r_err(1, "creating %s", INPUT_FILE);
665
666         fprintf(outf, "%s", PRE_BOILERPLATE);
667
668         if (strstr(test->style, "INSIDE_MAIN")) {
669                 fprintf(outf, "%s", MAIN_START_BOILERPLATE);
670                 fprintf(outf, "%s", test->fragment);
671                 fprintf(outf, "%s", MAIN_END_BOILERPLATE);
672         } else if (strstr(test->style, "OUTSIDE_MAIN")) {
673                 fprintf(outf, "%s", test->fragment);
674                 fprintf(outf, "%s", MAIN_START_BOILERPLATE);
675                 fprintf(outf, "%s", MAIN_BODY_BOILERPLATE);
676                 fprintf(outf, "%s", MAIN_END_BOILERPLATE);
677         } else if (strstr(test->style, "DEFINES_FUNC")) {
678                 fprintf(outf, "%s", test->fragment);
679                 fprintf(outf, "%s", MAIN_START_BOILERPLATE);
680                 fprintf(outf, "%s", USE_FUNC_BOILERPLATE);
681                 fprintf(outf, "%s", MAIN_BODY_BOILERPLATE);
682                 fprintf(outf, "%s", MAIN_END_BOILERPLATE);
683         } else if (strstr(test->style, "DEFINES_EVERYTHING")) {
684                 fprintf(outf, "%s", test->fragment);
685         } else
686                 c12r_errx(2, "Unknown style for test %s: %s",
687                           test->name, test->style);
688
689         if (verbose > 1) {
690                 fseek(outf, 0, SEEK_SET);
691                 fcopy(outf, stdout);
692         }
693
694         fclose(outf);
695
696         newcmd = strdup(cmd);
697
698         if (test->flags) {
699                 newcmd = realloc(newcmd, strlen(newcmd) + strlen(" ")
700                                 + strlen(test->flags) + 1);
701                 strcat(newcmd, " ");
702                 strcat(newcmd, test->flags);
703                 if (verbose > 1)
704                         printf("Extra flags line: %s", newcmd);
705         }
706
707         if (test->link) {
708                 newcmd = realloc(newcmd, strlen(newcmd) + strlen(" ")
709                                 + strlen(test->link) + 1);
710                 strcat(newcmd, " ");
711                 strcat(newcmd, test->link);
712                 if (verbose > 1)
713                         printf("Extra link line: %s", newcmd);
714         }
715
716         start_test("checking for ", test->desc);
717         output = run(newcmd, &status);
718
719         free(newcmd);
720
721         if (status != 0 || strstr(output, "warning")) {
722                 if (verbose)
723                         printf("Compile %s for %s, status %i: %s\n",
724                                status ? "fail" : "warning",
725                                test->name, status, output);
726                 if (strstr(test->style, "EXECUTE")
727                     && !strstr(test->style, "MAY_NOT_COMPILE"))
728                         c12r_errx(1, "Test for %s did not compile:\n%s",
729                                   test->name, output);
730                 test->answer = false;
731                 free(output);
732         } else {
733                 /* Compile succeeded. */
734                 free(output);
735                 /* We run INSIDE_MAIN tests for sanity checking. */
736                 if (strstr(test->style, "EXECUTE")
737                     || strstr(test->style, "INSIDE_MAIN")) {
738                         output = run("." DIR_SEP OUTPUT_FILE, &status);
739                         if (!strstr(test->style, "EXECUTE") && status != 0)
740                                 c12r_errx(1, "Test for %s failed with %i:\n%s",
741                                           test->name, status, output);
742                         if (verbose && status)
743                                 printf("%s exited %i\n", test->name, status);
744                         free(output);
745                 }
746                 test->answer = (status == 0);
747         }
748         test->done = true;
749         end_test(test->answer);
750
751         if (test->answer && test->overrides) {
752                 struct test *override = find_test(test->overrides);
753                 override->done = true;
754                 override->answer = true;
755         }
756         return test->answer;
757 }
758
759 static char *any_field(char **fieldname)
760 {
761         char buf[1000];
762         for (;;) {
763                 char *p, *eq;
764
765                 if (!fgets(buf, sizeof(buf), stdin))
766                         return NULL;
767
768                 p = buf;
769                 /* Ignore whitespace, lines starting with # */
770                 while (*p == ' ' || *p == '\t')
771                         p++;
772                 if (*p == '#' || *p == '\n')
773                         continue;
774
775                 eq = strchr(p, '=');
776                 if (!eq)
777                         c12r_errx(2, "no = in line: %s", p);
778                 *eq = '\0';
779                 *fieldname = strdup(p);
780                 p = eq + 1;
781                 if (strlen(p) && p[strlen(p)-1] == '\n')
782                         p[strlen(p)-1] = '\0';
783                 return strdup(p);
784         }
785 }
786
787 static char *read_field(const char *name, bool compulsory)
788 {
789         char *fieldname, *value;
790
791         value = any_field(&fieldname);
792         if (!value) {
793                 if (!compulsory)
794                         return NULL;
795                 c12r_errx(2, "Could not read field %s", name);
796         }
797         if (strcmp(fieldname, name) != 0)
798                 c12r_errx(2, "Expected field %s not %s", name, fieldname);
799         return value;
800 }
801
802 /* Test descriptions from stdin:
803  * Lines starting with # or whitespace-only are ignored.
804  *
805  * First three non-ignored lines must be:
806  *  var=<varname>
807  *  desc=<description-for-autotools-style>
808  *  style=OUTSIDE_MAIN DEFINES_FUNC INSIDE_MAIN DEFINES_EVERYTHING EXECUTE MAY_NOT_COMPILE
809  *
810  * Followed by optional lines:
811  *  depends=<space-separated-testnames, ! to invert>
812  *  link=<extra args for link line>
813  *  flags=<extra args for compile line>
814  *  overrides=<testname-to-force>
815  *
816  * Finally a code line, either:
817  *  code=<oneline> OR
818  *  code=
819  *  <lines of code>
820  *  <end-comment>
821  *
822  * And <end-comment> looks like this next comment: */
823 /*END*/
824 static bool read_test(struct test *test)
825 {
826         char *field, *value;
827         char buf[1000];
828
829         memset(test, 0, sizeof(*test));
830         test->name = read_field("var", false);
831         if (!test->name)
832                 return false;
833         test->desc = read_field("desc", true);
834         test->style = read_field("style", true);
835         /* Read any optional fields. */
836         while ((value = any_field(&field)) != NULL) {
837                 if (strcmp(field, "depends") == 0)
838                         test->depends = value;
839                 else if (strcmp(field, "link") == 0)
840                         test->link = value;
841                 else if (strcmp(field, "flags") == 0)
842                         test->flags = value;
843                 else if (strcmp(field, "overrides") == 0)
844                         test->overrides = value;
845                 else if (strcmp(field, "code") == 0)
846                         break;
847                 else
848                         c12r_errx(2, "Unknown field %s in %s",
849                                   field, test->name);
850         }
851         if (!value)
852                 c12r_errx(2, "Missing code in %s", test->name);
853
854         if (strlen(value) == 0) {
855                 /* Multiline program, read to END comment */
856                 while (fgets(buf, sizeof(buf), stdin) != 0) {
857                         size_t n;
858                         if (strncmp(buf, "/*END*/", 7) == 0)
859                                 break;
860                         n = strlen(value);
861                         value = realloc(value, n + strlen(buf) + 1);
862                         strcpy(value + n, buf);
863                         n += strlen(buf);
864                 }
865         }
866         test->fragment = value;
867         return true;
868 }
869
870 static void read_tests(size_t num_tests)
871 {
872         while (read_test(tests + num_tests)) {
873                 num_tests++;
874                 tests = realloc(tests, num_tests * sizeof(tests[0]));
875         }
876 }
877
878 int main(int argc, const char *argv[])
879 {
880         char *cmd;
881         unsigned int i;
882         const char *default_args[]
883                 = { "", DEFAULT_COMPILER, DEFAULT_FLAGS, NULL };
884         const char *outflag = DEFAULT_OUTPUT_EXE_FLAG;
885         const char *configurator_cc = NULL;
886         const char *orig_cc;
887         const char *varfile = NULL;
888         const char *headerfile = NULL;
889         bool extra_tests = false;
890         FILE *outf;
891
892         if (argc > 0)
893                 progname = argv[0];
894
895         while (argc > 1) {
896                 if (strcmp(argv[1], "--help") == 0) {
897                         printf("Usage: configurator [-v] [--var-file=<filename>] [-O<outflag>] [--configurator-cc=<compiler-for-tests>] [--autotools-style] [--extra-tests] [<compiler> <flags>...]\n"
898                                "  <compiler> <flags> will have \"<outflag> <outfile> <infile.c>\" appended\n"
899                                "Default: %s %s %s\n",
900                                DEFAULT_COMPILER, DEFAULT_FLAGS,
901                                DEFAULT_OUTPUT_EXE_FLAG);
902                         exit(0);
903                 }
904                 if (strncmp(argv[1], "-O", 2) == 0) {
905                         argc--;
906                         argv++;
907                         outflag = argv[1] + 2;
908                         if (!*outflag) {
909                                 fprintf(stderr,
910                                         "%s: option requires an argument -- O\n",
911                                         argv[0]);
912                                 exit(1);
913                         }
914                 } else if (strcmp(argv[1], "-v") == 0) {
915                         argc--;
916                         argv++;
917                         verbose++;
918                 } else if (strcmp(argv[1], "-vv") == 0) {
919                         argc--;
920                         argv++;
921                         verbose += 2;
922                 } else if (strncmp(argv[1], "--configurator-cc=", 18) == 0) {
923                         configurator_cc = argv[1] + 18;
924                         argc--;
925                         argv++;
926                 } else if (strncmp(argv[1], "--var-file=", 11) == 0) {
927                         varfile = argv[1] + 11;
928                         argc--;
929                         argv++;
930                 } else if (strcmp(argv[1], "--autotools-style") == 0) {
931                         like_a_libtool = true;
932                         argc--;
933                         argv++;
934                 } else if (strncmp(argv[1], "--header-file=", 14) == 0) {
935                         headerfile = argv[1] + 14;
936                         argc--;
937                         argv++;
938                 } else if (strcmp(argv[1], "--extra-tests") == 0) {
939                         extra_tests = true;
940                         argc--;
941                         argv++;
942                 } else if (strcmp(argv[1], "--") == 0) {
943                         break;
944                 } else if (argv[1][0] == '-') {
945                         c12r_errx(2, "Unknown option %s", argv[1]);
946                 } else {
947                         break;
948                 }
949         }
950
951         if (argc == 1)
952                 argv = default_args;
953
954         /* Copy with NULL entry at end */
955         tests = calloc(sizeof(base_tests)/sizeof(base_tests[0]) + 1,
956                        sizeof(base_tests[0]));
957         memcpy(tests, base_tests, sizeof(base_tests));
958
959         if (extra_tests)
960                 read_tests(sizeof(base_tests)/sizeof(base_tests[0]));
961
962         orig_cc = argv[1];
963         if (configurator_cc)
964                 argv[1] = configurator_cc;
965
966         cmd = connect_args(argv, outflag, OUTPUT_FILE " " INPUT_FILE);
967         if (like_a_libtool) {
968                 start_test("Making autoconf users comfortable", "");
969                 sleep(1);
970                 end_test(1);
971         }
972         for (i = 0; tests[i].name; i++)
973                 run_test(cmd, &tests[i]);
974         free(cmd);
975
976         remove(OUTPUT_FILE);
977         remove(INPUT_FILE);
978
979         if (varfile) {
980                 FILE *vars;
981
982                 if (strcmp(varfile, "-") == 0)
983                         vars = stdout;
984                 else {
985                         start_test("Writing variables to ", varfile);
986                         vars = fopen(varfile, "a");
987                         if (!vars)
988                                 c12r_err(2, "Could not open %s", varfile);
989                 }
990                 for (i = 0; tests[i].name; i++)
991                         fprintf(vars, "%s=%u\n", tests[i].name, tests[i].answer);
992                 if (vars != stdout) {
993                         if (fclose(vars) != 0)
994                                 c12r_err(2, "Closing %s", varfile);
995                         end_test(1);
996                 }
997         }
998
999         if (headerfile) {
1000                 start_test("Writing header to ", headerfile);
1001                 outf = fopen(headerfile, "w");
1002                 if (!outf)
1003                         c12r_err(2, "Could not open %s", headerfile);
1004         } else
1005                 outf = stdout;
1006
1007         fprintf(outf, "/* Generated by CCAN configurator */\n"
1008                "#ifndef CCAN_CONFIG_H\n"
1009                "#define CCAN_CONFIG_H\n");
1010         fprintf(outf, "#ifndef _GNU_SOURCE\n");
1011         fprintf(outf, "#define _GNU_SOURCE /* Always use GNU extensions. */\n");
1012         fprintf(outf, "#endif\n");
1013         fprintf(outf, "#define CCAN_COMPILER \"%s\"\n", orig_cc);
1014         cmd = connect_args(argv + 1, "", "");
1015         fprintf(outf, "#define CCAN_CFLAGS \"%s\"\n", cmd);
1016         free(cmd);
1017         fprintf(outf, "#define CCAN_OUTPUT_EXE_CFLAG \"%s\"\n\n", outflag);
1018         /* This one implies "#include <ccan/..." works, eg. for tdb2.h */
1019         fprintf(outf, "#define HAVE_CCAN 1\n");
1020         for (i = 0; tests[i].name; i++)
1021                 fprintf(outf, "#define %s %u\n", tests[i].name, tests[i].answer);
1022         fprintf(outf, "#endif /* CCAN_CONFIG_H */\n");
1023
1024         if (headerfile) {
1025                 if (fclose(outf) != 0)
1026                         c12r_err(2, "Closing %s", headerfile);
1027                 end_test(1);
1028         }
1029
1030         return 0;
1031 }