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