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