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