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