afb67ca8ce269dcdae605de0c1a6913f4aaa9b8f
[ccan] / tools / configurator / configurator.c
1 /* Simple tool to create config.h.
2  * Would be much easier with ccan modules, but deliberately standalone.
3  *
4  * Copyright 2011 Rusty Russell <rusty@rustcorp.com.au>.  MIT license.
5  *
6  * c12r_err, c12r_errx functions copied from ccan/err/err.c
7  * Copyright Rusty Russell <rusty@rustcorp.com.au>. CC0 (Public domain) License.
8  *
9  * Permission is hereby granted, free of charge, to any person obtaining a copy
10  * of this software and associated documentation files (the "Software"), to deal
11  * in the Software without restriction, including without limitation the rights
12  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13  * copies of the Software, and to permit persons to whom the Software is
14  * furnished to do so, subject to the following conditions:
15  *
16  * The above copyright notice and this permission notice shall be included in
17  * all copies or substantial portions of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25  * THE SOFTWARE.
26  */
27 #define _POSIX_C_SOURCE 200809L                /* For pclose, popen, strdup */
28
29 #include <errno.h>
30 #include <stdio.h>
31 #include <stdarg.h>
32 #include <stdbool.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36
37 #ifdef _MSC_VER
38 #define popen _popen
39 #define pclose _pclose
40 #endif
41
42 #ifdef _MSC_VER
43 #define DEFAULT_COMPILER "cl"
44 /* Note:  Dash options avoid POSIX path conversion when used under msys bash
45  *        and are therefore preferred to slash (e.g. -nologo over /nologo)
46  * Note:  Disable Warning 4200 "nonstandard extension used : zero-sized array
47  *        in struct/union" for flexible array members.
48  */
49 #define DEFAULT_FLAGS "-nologo -Zi -W4 -wd4200 " \
50         "-D_CRT_NONSTDC_NO_WARNINGS -D_CRT_SECURE_NO_WARNINGS"
51 #define DEFAULT_OUTPUT_EXE_FLAG "-Fe:"
52 #else
53 #define DEFAULT_COMPILER "cc"
54 #define DEFAULT_FLAGS "-g3 -ggdb -Wall -Wundef -Wmissing-prototypes -Wmissing-declarations -Wstrict-prototypes -Wold-style-definition"
55 #define DEFAULT_OUTPUT_EXE_FLAG "-o"
56 #endif
57
58 #define OUTPUT_FILE "configurator.out"
59 #define INPUT_FILE "configuratortest.c"
60
61 #ifdef _WIN32
62 #define DIR_SEP   "\\"
63 #else
64 #define DIR_SEP   "/"
65 #endif
66
67 static const char *progname = "";
68 static int verbose;
69 static bool like_a_libtool = false;
70
71 struct test {
72         const char *name;
73         /*
74          * Template style flags (pick one):
75          * OUTSIDE_MAIN:
76          * - put a simple boilerplate main below it.
77          * DEFINES_FUNC:
78          * - defines a static function called func; adds ref to avoid warnings
79          * INSIDE_MAIN:
80          * - put this inside main().
81          * DEFINES_EVERYTHING:
82          * - don't add any boilerplate at all.
83          *
84          * Execution flags:
85          * EXECUTE:
86          * - a runtime test; must compile, exit 0 means flag is set.
87          * MAY_NOT_COMPILE:
88          * - Only useful with EXECUTE: don't get upset if it doesn't compile.
89          * <nothing>:
90          * - a compile test, if it compiles must run and exit 0.
91          */
92         const char *style;
93         const char *depends;
94         const char *link;
95         const char *fragment;
96         const char *flags;
97         const char *overrides; /* On success, force this to '1' */
98         bool done;
99         bool answer;
100 };
101
102 static struct test tests[] = {
103         { "HAVE_32BIT_OFF_T", "DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE", NULL, NULL,
104           "#include <sys/types.h>\n"
105           "int main(void) {\n"
106           "     return sizeof(off_t) == 4 ? 0 : 1;\n"
107           "}\n" },
108         { "HAVE_ALIGNOF", "INSIDE_MAIN", NULL, NULL,
109           "return __alignof__(double) > 0 ? 0 : 1;" },
110         { "HAVE_ASPRINTF", "DEFINES_FUNC", NULL, NULL,
111           "#ifndef _GNU_SOURCE\n"
112           "#define _GNU_SOURCE\n"
113           "#endif\n"
114           "#include <stdio.h>\n"
115           "static char *func(int x) {"
116           "     char *p;\n"
117           "     if (asprintf(&p, \"%u\", x) == -1) \n"
118           "             p = NULL;\n"
119           "     return p;\n"
120           "}" },
121         { "HAVE_ATTRIBUTE_COLD", "DEFINES_FUNC", NULL, NULL,
122           "static int __attribute__((cold)) func(int x) { return x; }" },
123         { "HAVE_ATTRIBUTE_CONST", "DEFINES_FUNC", NULL, NULL,
124           "static int __attribute__((const)) func(int x) { return x; }" },
125         { "HAVE_ATTRIBUTE_PURE", "DEFINES_FUNC", NULL, NULL,
126           "static int __attribute__((pure)) func(int x) { return x; }" },
127         { "HAVE_ATTRIBUTE_MAY_ALIAS", "OUTSIDE_MAIN", NULL, NULL,
128           "typedef short __attribute__((__may_alias__)) short_a;" },
129         { "HAVE_ATTRIBUTE_NORETURN", "DEFINES_FUNC", NULL, NULL,
130           "#include <stdlib.h>\n"
131           "static void __attribute__((noreturn)) func(int x) { exit(x); }" },
132         { "HAVE_ATTRIBUTE_PRINTF", "DEFINES_FUNC", NULL, NULL,
133           "static void __attribute__((format(__printf__, 1, 2))) func(const char *fmt, ...) { (void)fmt; }" },
134         { "HAVE_ATTRIBUTE_UNUSED", "OUTSIDE_MAIN", NULL, NULL,
135           "static int __attribute__((unused)) func(int x) { return x; }" },
136         { "HAVE_ATTRIBUTE_USED", "OUTSIDE_MAIN", NULL, NULL,
137           "static int __attribute__((used)) func(int x) { return x; }" },
138         { "HAVE_BACKTRACE", "DEFINES_FUNC", NULL, NULL,
139           "#include <execinfo.h>\n"
140           "static int func(int x) {"
141           "     void *bt[10];\n"
142           "     return backtrace(bt, 10) < x;\n"
143           "}" },
144         { "HAVE_BIG_ENDIAN", "INSIDE_MAIN|EXECUTE", NULL, NULL,
145           "union { int i; char c[sizeof(int)]; } u;\n"
146           "u.i = 0x01020304;\n"
147           "return u.c[0] == 0x01 && u.c[1] == 0x02 && u.c[2] == 0x03 && u.c[3] == 0x04 ? 0 : 1;" },
148         { "HAVE_BSWAP_64", "DEFINES_FUNC", "HAVE_BYTESWAP_H", NULL,
149           "#include <byteswap.h>\n"
150           "static int func(int x) { return bswap_64(x); }" },
151         { "HAVE_BUILTIN_CHOOSE_EXPR", "INSIDE_MAIN", NULL, NULL,
152           "return __builtin_choose_expr(1, 0, \"garbage\");" },
153         { "HAVE_BUILTIN_CLZ", "INSIDE_MAIN", NULL, NULL,
154           "return __builtin_clz(1) == (sizeof(int)*8 - 1) ? 0 : 1;" },
155         { "HAVE_BUILTIN_CLZL", "INSIDE_MAIN", NULL, NULL,
156           "return __builtin_clzl(1) == (sizeof(long)*8 - 1) ? 0 : 1;" },
157         { "HAVE_BUILTIN_CLZLL", "INSIDE_MAIN", NULL, NULL,
158           "return __builtin_clzll(1) == (sizeof(long long)*8 - 1) ? 0 : 1;" },
159         { "HAVE_BUILTIN_CTZ", "INSIDE_MAIN", NULL, NULL,
160           "return __builtin_ctz(1 << (sizeof(int)*8 - 1)) == (sizeof(int)*8 - 1) ? 0 : 1;" },
161         { "HAVE_BUILTIN_CTZL", "INSIDE_MAIN", NULL, NULL,
162           "return __builtin_ctzl(1UL << (sizeof(long)*8 - 1)) == (sizeof(long)*8 - 1) ? 0 : 1;" },
163         { "HAVE_BUILTIN_CTZLL", "INSIDE_MAIN", NULL, NULL,
164           "return __builtin_ctzll(1ULL << (sizeof(long long)*8 - 1)) == (sizeof(long long)*8 - 1) ? 0 : 1;" },
165         { "HAVE_BUILTIN_CONSTANT_P", "INSIDE_MAIN", NULL, NULL,
166           "return __builtin_constant_p(1) ? 0 : 1;" },
167         { "HAVE_BUILTIN_EXPECT", "INSIDE_MAIN", NULL, NULL,
168           "return __builtin_expect(argc == 1, 1) ? 0 : 1;" },
169         { "HAVE_BUILTIN_FFS", "INSIDE_MAIN", NULL, NULL,
170           "return __builtin_ffs(0) == 0 ? 0 : 1;" },
171         { "HAVE_BUILTIN_FFSL", "INSIDE_MAIN", NULL, NULL,
172           "return __builtin_ffsl(0L) == 0 ? 0 : 1;" },
173         { "HAVE_BUILTIN_FFSLL", "INSIDE_MAIN", NULL, NULL,
174           "return __builtin_ffsll(0LL) == 0 ? 0 : 1;" },
175         { "HAVE_BUILTIN_POPCOUNT", "INSIDE_MAIN", NULL, NULL,
176           "return __builtin_popcount(255) == 8 ? 0 : 1;" },
177         { "HAVE_BUILTIN_POPCOUNTL", "INSIDE_MAIN", NULL, NULL,
178           "return __builtin_popcountl(255L) == 8 ? 0 : 1;" },
179         { "HAVE_BUILTIN_POPCOUNTLL", "INSIDE_MAIN", NULL, NULL,
180           "return __builtin_popcountll(255LL) == 8 ? 0 : 1;" },
181         { "HAVE_BUILTIN_TYPES_COMPATIBLE_P", "INSIDE_MAIN", NULL, NULL,
182           "return __builtin_types_compatible_p(char *, int) ? 1 : 0;" },
183         { "HAVE_ICCARM_INTRINSICS", "DEFINES_FUNC", NULL, NULL,
184           "#include <intrinsics.h>\n"
185           "int func(int v) {\n"
186           "     return __CLZ(__RBIT(v));\n"
187           "}" },
188         { "HAVE_BYTESWAP_H", "OUTSIDE_MAIN", NULL, NULL,
189           "#include <byteswap.h>\n" },
190         { "HAVE_CLOCK_GETTIME",
191           "DEFINES_FUNC", "HAVE_STRUCT_TIMESPEC", NULL,
192           "#include <time.h>\n"
193           "static struct timespec func(void) {\n"
194           "     struct timespec ts;\n"
195           "     clock_gettime(CLOCK_REALTIME, &ts);\n"
196           "     return ts;\n"
197           "}\n" },
198         { "HAVE_CLOCK_GETTIME_IN_LIBRT",
199           "DEFINES_FUNC",
200           "HAVE_STRUCT_TIMESPEC !HAVE_CLOCK_GETTIME",
201           "-lrt",
202           "#include <time.h>\n"
203           "static struct timespec func(void) {\n"
204           "     struct timespec ts;\n"
205           "     clock_gettime(CLOCK_REALTIME, &ts);\n"
206           "     return ts;\n"
207           "}\n",
208           /* This means HAVE_CLOCK_GETTIME, too */
209           "HAVE_CLOCK_GETTIME" },
210         { "HAVE_COMPOUND_LITERALS", "INSIDE_MAIN", NULL, NULL,
211           "int *foo = (int[]) { 1, 2, 3, 4 };\n"
212           "return foo[0] ? 0 : 1;" },
213         { "HAVE_FCHDIR", "DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE", NULL, NULL,
214           "#include <sys/types.h>\n"
215           "#include <sys/stat.h>\n"
216           "#include <fcntl.h>\n"
217           "#include <unistd.h>\n"
218           "int main(void) {\n"
219           "     int fd = open(\"..\", O_RDONLY);\n"
220           "     return fchdir(fd) == 0 ? 0 : 1;\n"
221           "}\n" },
222         { "HAVE_ERR_H", "DEFINES_FUNC", NULL, NULL,
223           "#include <err.h>\n"
224           "static void func(int arg) {\n"
225           "     if (arg == 0)\n"
226           "             err(1, \"err %u\", arg);\n"
227           "     if (arg == 1)\n"
228           "             errx(1, \"err %u\", arg);\n"
229           "     if (arg == 3)\n"
230           "             warn(\"warn %u\", arg);\n"
231           "     if (arg == 4)\n"
232           "             warnx(\"warn %u\", arg);\n"
233           "}\n" },
234         { "HAVE_FILE_OFFSET_BITS", "DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE",
235           "HAVE_32BIT_OFF_T", NULL,
236           "#define _FILE_OFFSET_BITS 64\n"
237           "#include <sys/types.h>\n"
238           "int main(void) {\n"
239           "     return sizeof(off_t) == 8 ? 0 : 1;\n"
240           "}\n" },
241         { "HAVE_FOR_LOOP_DECLARATION", "INSIDE_MAIN", NULL, NULL,
242           "int ret = 1;\n"
243           "for (int i = 0; i < argc; i++) { ret = 0; };\n"
244           "return ret;" },
245         { "HAVE_FLEXIBLE_ARRAY_MEMBER", "OUTSIDE_MAIN", NULL, NULL,
246           "struct foo { unsigned int x; int arr[]; };" },
247         { "HAVE_GETPAGESIZE", "DEFINES_FUNC", NULL, NULL,
248           "#include <unistd.h>\n"
249           "static int func(void) { return getpagesize(); }" },
250         { "HAVE_ISBLANK", "DEFINES_FUNC", NULL, NULL,
251           "#ifndef _GNU_SOURCE\n"
252           "#define _GNU_SOURCE\n"
253           "#endif\n"
254           "#include <ctype.h>\n"
255           "static int func(void) { return isblank(' '); }" },
256         { "HAVE_LITTLE_ENDIAN", "INSIDE_MAIN|EXECUTE", NULL, NULL,
257           "union { int i; char c[sizeof(int)]; } u;\n"
258           "u.i = 0x01020304;\n"
259           "return u.c[0] == 0x04 && u.c[1] == 0x03 && u.c[2] == 0x02 && u.c[3] == 0x01 ? 0 : 1;" },
260         { "HAVE_MEMMEM", "DEFINES_FUNC", NULL, NULL,
261           "#ifndef _GNU_SOURCE\n"
262           "#define _GNU_SOURCE\n"
263           "#endif\n"
264           "#include <string.h>\n"
265           "static void *func(void *h, size_t hl, void *n, size_t nl) {\n"
266           "return memmem(h, hl, n, nl);"
267           "}\n", },
268         { "HAVE_MEMRCHR", "DEFINES_FUNC", NULL, NULL,
269           "#ifndef _GNU_SOURCE\n"
270           "#define _GNU_SOURCE\n"
271           "#endif\n"
272           "#include <string.h>\n"
273           "static void *func(void *s, int c, size_t n) {\n"
274           "return memrchr(s, c, n);"
275           "}\n", },
276         { "HAVE_MMAP", "DEFINES_FUNC", NULL, NULL,
277           "#include <sys/mman.h>\n"
278           "static void *func(int fd) {\n"
279           "     return mmap(0, 65536, PROT_READ, MAP_SHARED, fd, 0);\n"
280           "}" },
281         { "HAVE_PROC_SELF_MAPS", "DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE", NULL, NULL,
282           "#include <sys/types.h>\n"
283           "#include <sys/stat.h>\n"
284           "#include <fcntl.h>\n"
285           "int main(void) {\n"
286           "     return open(\"/proc/self/maps\", O_RDONLY) != -1 ? 0 : 1;\n"
287           "}\n" },
288         { "HAVE_QSORT_R_PRIVATE_LAST",
289           "DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE", NULL, NULL,
290           "#ifndef _GNU_SOURCE\n"
291           "#define _GNU_SOURCE\n"
292           "#endif\n"
293           "#include <stdlib.h>\n"
294           "static int cmp(const void *lp, const void *rp, void *priv) {\n"
295           " *(unsigned int *)priv = 1;\n"
296           " return *(const int *)lp - *(const int *)rp; }\n"
297           "int main(void) {\n"
298           " int array[] = { 9, 2, 5 };\n"
299           " unsigned int called = 0;\n"
300           " qsort_r(array, 3, sizeof(int), cmp, &called);\n"
301           " return called && array[0] == 2 && array[1] == 5 && array[2] == 9 ? 0 : 1;\n"
302           "}\n" },
303         { "HAVE_STRUCT_TIMESPEC",
304           "DEFINES_FUNC", NULL, NULL,
305           "#include <time.h>\n"
306           "static void func(void) {\n"
307           "     struct timespec ts;\n"
308           "     ts.tv_sec = ts.tv_nsec = 1;\n"
309           "}\n" },
310         { "HAVE_SECTION_START_STOP",
311           "DEFINES_FUNC", NULL, NULL,
312           "static void *__attribute__((__section__(\"mysec\"))) p = &p;\n"
313           "static int func(void) {\n"
314           "     extern void *__start_mysec[], *__stop_mysec[];\n"
315           "     return __stop_mysec - __start_mysec;\n"
316           "}\n" },
317         { "HAVE_STACK_GROWS_UPWARDS", "DEFINES_EVERYTHING|EXECUTE", NULL, NULL,
318           "#include <stddef.h>\n"
319           "static ptrdiff_t nest(const void *base, unsigned int i)\n"
320           "{\n"
321           "     if (i == 0)\n"
322           "             return (const char *)&i - (const char *)base;\n"
323           "     return nest(base, i-1);\n"
324           "}\n"
325           "int main(int argc, char *argv[]) {\n"
326           "     (void)argv;\n"
327           "     return (nest(&argc, argc) > 0) ? 0 : 1;\n"
328           "}\n" },
329         { "HAVE_STATEMENT_EXPR", "INSIDE_MAIN", NULL, NULL,
330           "return ({ int x = argc; x == argc ? 0 : 1; });" },
331         { "HAVE_SYS_FILIO_H", "OUTSIDE_MAIN", NULL, NULL, /* Solaris needs this for FIONREAD */
332           "#include <sys/filio.h>\n" },
333         { "HAVE_SYS_TERMIOS_H", "OUTSIDE_MAIN", NULL, NULL,
334           "#include <sys/termios.h>\n" },
335         { "HAVE_SYS_UNISTD_H", "OUTSIDE_MAIN", NULL, NULL,
336           "#include <sys/unistd.h>\n" },
337         { "HAVE_TYPEOF", "INSIDE_MAIN", NULL, NULL,
338           "__typeof__(argc) i; i = argc; return i == argc ? 0 : 1;" },
339         { "HAVE_UNALIGNED_ACCESS", "DEFINES_EVERYTHING|EXECUTE", NULL, NULL,
340           "#include <string.h>\n"
341           "int main(int argc, char *argv[]) {\n"
342           "     (void)argc;\n"
343           "     char pad[sizeof(int *) * 1];\n"
344           "     strncpy(pad, argv[0], sizeof(pad));\n"
345           "     int *x = (int *)pad, *y = (int *)(pad + 1);\n"
346           "     return *x == *y;\n"
347           "}\n" },
348         { "HAVE_UTIME", "DEFINES_FUNC", NULL, NULL,
349           "#include <sys/types.h>\n"
350           "#include <utime.h>\n"
351           "static int func(const char *filename) {\n"
352           "     struct utimbuf times = { 0 };\n"
353           "     return utime(filename, &times);\n"
354           "}" },
355         { "HAVE_WARN_UNUSED_RESULT", "DEFINES_FUNC", NULL, NULL,
356           "#include <sys/types.h>\n"
357           "#include <utime.h>\n"
358           "static __attribute__((warn_unused_result)) int func(int i) {\n"
359           "     return i + 1;\n"
360           "}" },
361         { "HAVE_OPENMP", "INSIDE_MAIN", NULL, NULL,
362           "int i;\n"
363           "#pragma omp parallel for\n"
364           "for(i = 0; i < 0; i++) {};\n"
365           "return 0;\n",
366           "-Werror -fopenmp" },
367         { "HAVE_VALGRIND_MEMCHECK_H", "OUTSIDE_MAIN", NULL, NULL,
368           "#include <valgrind/memcheck.h>\n" },
369         { "HAVE_UCONTEXT", "DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE",
370           NULL, NULL,
371           "#include <ucontext.h>\n"
372           "static int x = 0;\n"
373           "static char stack[2048];\n"
374           "static ucontext_t a, b;\n"
375           "static void fn(void) {\n"
376           "     x |= 2;\n"
377           "     setcontext(&b);\n"
378           "     x |= 4;\n"
379           "}\n"
380           "int main(void) {\n"
381           "     x |= 1;\n"
382           "     getcontext(&a);\n"
383           "     a.uc_stack.ss_sp = stack;\n"
384           "     a.uc_stack.ss_size = sizeof(stack);\n"
385           "     makecontext(&a, fn, 0);\n"
386           "     swapcontext(&b, &a);\n"
387           "     return (x == 3) ? 0 : 1;\n"
388           "}\n"
389         },
390         { "HAVE_POINTER_SAFE_MAKECONTEXT", "DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE",
391           "HAVE_UCONTEXT", NULL,
392           "#include <stddef.h>\n"
393           "#include <ucontext.h>\n"
394           "static int worked = 0;\n"
395           "static char stack[1024];\n"
396           "static ucontext_t a, b;\n"
397           "static void fn(void *p, void *q) {\n"
398           "     void *cp = &worked;\n"
399           "     void *cq = (void *)(~((ptrdiff_t)cp));\n"
400           "     if ((p == cp) && (q == cq))\n"
401           "             worked = 1;\n"
402           "     setcontext(&b);\n"
403           "}\n"
404           "int main(void) {\n"
405           "     void *ap = &worked;\n"
406           "     void *aq = (void *)(~((ptrdiff_t)ap));\n"
407           "     getcontext(&a);\n"
408           "     a.uc_stack.ss_sp = stack;\n"
409           "     a.uc_stack.ss_size = sizeof(stack);\n"
410           "     makecontext(&a, (void (*)(void))fn, 2, ap, aq);\n"
411           "     swapcontext(&b, &a);\n"
412           "     return worked ? 0 : 1;\n"
413           "}\n"
414         },
415 };
416
417 static void c12r_err(int eval, const char *fmt, ...)
418 {
419         int err_errno = errno;
420         va_list ap;
421
422         fprintf(stderr, "%s: ", progname);
423         va_start(ap, fmt);
424         vfprintf(stderr, fmt, ap);
425         va_end(ap);
426         fprintf(stderr, ": %s\n", strerror(err_errno));
427         exit(eval);
428 }
429
430 static void c12r_errx(int eval, const char *fmt, ...)
431 {
432         va_list ap;
433
434         fprintf(stderr, "%s: ", progname);
435         va_start(ap, fmt);
436         vfprintf(stderr, fmt, ap);
437         va_end(ap);
438         fprintf(stderr, "\n");
439         exit(eval);
440 }
441
442 static void start_test(const char *what, const char *why)
443 {
444         if (like_a_libtool) {
445                 printf("%s%s... ", what, why);
446                 fflush(stdout);
447         }
448 }
449
450 static void end_test(bool result)
451 {
452         if (like_a_libtool)
453                 printf("%s\n", result ? "yes" : "no");
454 }
455
456 static size_t fcopy(FILE *fsrc, FILE *fdst)
457 {
458         char buffer[BUFSIZ];
459         size_t rsize, wsize;
460         size_t copied = 0;
461
462         while ((rsize = fread(buffer, 1, BUFSIZ, fsrc)) > 0) {
463                 wsize = fwrite(buffer, 1, rsize, fdst);
464                 copied += wsize;
465                 if (wsize != rsize)
466                         break;
467         }
468
469         return copied;
470 }
471
472 static char *grab_stream(FILE *file)
473 {
474         size_t max, ret, size = 0;
475         char *buffer;
476
477         max = BUFSIZ;
478         buffer = malloc(max);
479         while ((ret = fread(buffer+size, 1, max - size, file)) == max - size) {
480                 size += ret;
481                 buffer = realloc(buffer, max *= 2);
482         }
483         size += ret;
484         if (ferror(file))
485                 c12r_err(1, "reading from command");
486         buffer[size] = '\0';
487         return buffer;
488 }
489
490 static char *run(const char *cmd, int *exitstatus)
491 {
492         static const char redir[] = " 2>&1";
493         size_t cmdlen;
494         char *cmdredir;
495         FILE *cmdout;
496         char *ret;
497
498         cmdlen = strlen(cmd);
499         cmdredir = malloc(cmdlen + sizeof(redir));
500         memcpy(cmdredir, cmd, cmdlen);
501         memcpy(cmdredir + cmdlen, redir, sizeof(redir));
502
503         cmdout = popen(cmdredir, "r");
504         if (!cmdout)
505                 c12r_err(1, "popen \"%s\"", cmdredir);
506
507         free(cmdredir);
508
509         ret = grab_stream(cmdout);
510         *exitstatus = pclose(cmdout);
511         return ret;
512 }
513
514 static char *connect_args(const char *argv[], const char *outflag,
515                 const char *files)
516 {
517         unsigned int i;
518         char *ret;
519         size_t len = strlen(outflag) + strlen(files) + 1;
520
521         for (i = 1; argv[i]; i++)
522                 len += 1 + strlen(argv[i]);
523
524         ret = malloc(len);
525         len = 0;
526         for (i = 1; argv[i]; i++) {
527                 strcpy(ret + len, argv[i]);
528                 len += strlen(argv[i]);
529                 if (argv[i+1] || *outflag)
530                         ret[len++] = ' ';
531         }
532         strcpy(ret + len, outflag);
533         len += strlen(outflag);
534         strcpy(ret + len, files);
535         return ret;
536 }
537
538 static struct test *find_test(const char *name)
539 {
540         unsigned int i;
541
542         for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) {
543                 if (strcmp(tests[i].name, name) == 0)
544                         return &tests[i];
545         }
546         abort();
547 }
548
549 #define PRE_BOILERPLATE "/* Test program generated by configurator. */\n"
550 #define MAIN_START_BOILERPLATE \
551         "int main(int argc, char *argv[]) {\n" \
552         "       (void)argc;\n" \
553         "       (void)argv;\n"
554 #define USE_FUNC_BOILERPLATE "(void)func;\n"
555 #define MAIN_BODY_BOILERPLATE "return 0;\n"
556 #define MAIN_END_BOILERPLATE "}\n"
557
558 static bool run_test(const char *cmd, struct test *test)
559 {
560         char *output, *newcmd;
561         FILE *outf;
562         int status;
563
564         if (test->done)
565                 return test->answer;
566
567         if (test->depends) {
568                 size_t len;
569                 const char *deps = test->depends;
570                 char *dep;
571
572                 /* Space-separated dependencies, could be ! for inverse. */
573                 while ((len = strcspn(deps, " ")) != 0) {
574                         bool positive = true;
575                         if (deps[len]) {
576                                 dep = strdup(deps);
577                                 dep[len] = '\0';
578                         } else {
579                                 dep = (char *)deps;
580                         }
581
582                         if (dep[0] == '!') {
583                                 dep++;
584                                 positive = false;
585                         }
586                         if (run_test(cmd, find_test(dep)) != positive) {
587                                 test->answer = false;
588                                 test->done = true;
589                                 return test->answer;
590                         }
591                         if (deps[len])
592                                 free(dep);
593
594                         deps += len;
595                         deps += strspn(deps, " ");
596                 }
597         }
598
599         outf = fopen(INPUT_FILE, verbose > 1 ? "w+" : "w");
600         if (!outf)
601                 c12r_err(1, "creating %s", INPUT_FILE);
602
603         fprintf(outf, "%s", PRE_BOILERPLATE);
604
605         if (strstr(test->style, "INSIDE_MAIN")) {
606                 fprintf(outf, "%s", MAIN_START_BOILERPLATE);
607                 fprintf(outf, "%s", test->fragment);
608                 fprintf(outf, "%s", MAIN_END_BOILERPLATE);
609         } else if (strstr(test->style, "OUTSIDE_MAIN")) {
610                 fprintf(outf, "%s", test->fragment);
611                 fprintf(outf, "%s", MAIN_START_BOILERPLATE);
612                 fprintf(outf, "%s", MAIN_BODY_BOILERPLATE);
613                 fprintf(outf, "%s", MAIN_END_BOILERPLATE);
614         } else if (strstr(test->style, "DEFINES_FUNC")) {
615                 fprintf(outf, "%s", test->fragment);
616                 fprintf(outf, "%s", MAIN_START_BOILERPLATE);
617                 fprintf(outf, "%s", USE_FUNC_BOILERPLATE);
618                 fprintf(outf, "%s", MAIN_BODY_BOILERPLATE);
619                 fprintf(outf, "%s", MAIN_END_BOILERPLATE);
620         } else if (strstr(test->style, "DEFINES_EVERYTHING")) {
621                 fprintf(outf, "%s", test->fragment);
622         } else
623                 c12r_errx(2, "Unknown style for test %s: %s",
624                           test->name, test->style);
625
626         if (verbose > 1) {
627                 fseek(outf, 0, SEEK_SET);
628                 fcopy(outf, stdout);
629         }
630
631         fclose(outf);
632
633         newcmd = strdup(cmd);
634
635         if (test->flags) {
636                 newcmd = realloc(newcmd, strlen(newcmd) + strlen(" ")
637                                 + strlen(test->flags) + 1);
638                 strcat(newcmd, " ");
639                 strcat(newcmd, test->flags);
640                 if (verbose > 1)
641                         printf("Extra flags line: %s", newcmd);
642         }
643
644         if (test->link) {
645                 newcmd = realloc(newcmd, strlen(newcmd) + strlen(" ")
646                                 + strlen(test->link) + 1);
647                 strcat(newcmd, " ");
648                 strcat(newcmd, test->link);
649                 if (verbose > 1)
650                         printf("Extra link line: %s", newcmd);
651         }
652
653         start_test("checking for ", test->name);
654         output = run(newcmd, &status);
655
656         free(newcmd);
657
658         if (status != 0 || strstr(output, "warning")) {
659                 if (verbose)
660                         printf("Compile %s for %s, status %i: %s\n",
661                                status ? "fail" : "warning",
662                                test->name, status, output);
663                 if (strstr(test->style, "EXECUTE")
664                     && !strstr(test->style, "MAY_NOT_COMPILE"))
665                         c12r_errx(1, "Test for %s did not compile:\n%s",
666                                   test->name, output);
667                 test->answer = false;
668                 free(output);
669         } else {
670                 /* Compile succeeded. */
671                 free(output);
672                 /* We run INSIDE_MAIN tests for sanity checking. */
673                 if (strstr(test->style, "EXECUTE")
674                     || strstr(test->style, "INSIDE_MAIN")) {
675                         output = run("." DIR_SEP OUTPUT_FILE, &status);
676                         if (!strstr(test->style, "EXECUTE") && status != 0)
677                                 c12r_errx(1, "Test for %s failed with %i:\n%s",
678                                           test->name, status, output);
679                         if (verbose && status)
680                                 printf("%s exited %i\n", test->name, status);
681                         free(output);
682                 }
683                 test->answer = (status == 0);
684         }
685         test->done = true;
686         end_test(test->answer);
687
688         if (test->answer && test->overrides) {
689                 struct test *override = find_test(test->overrides);
690                 override->done = true;
691                 override->answer = true;
692         }
693         return test->answer;
694 }
695
696 int main(int argc, const char *argv[])
697 {
698         char *cmd;
699         unsigned int i;
700         const char *default_args[]
701                 = { "", DEFAULT_COMPILER, DEFAULT_FLAGS, NULL };
702         const char *outflag = DEFAULT_OUTPUT_EXE_FLAG;
703         const char *configurator_cc = NULL;
704         const char *orig_cc;
705         const char *varfile = NULL;
706         const char *headerfile = NULL;
707         FILE *outf;
708
709         if (argc > 0)
710                 progname = argv[0];
711
712         while (argc > 1) {
713                 if (strcmp(argv[1], "--help") == 0) {
714                         printf("Usage: configurator [-v] [--var-file=<filename>] [-O<outflag>] [--configurator-cc=<compiler-for-tests>] [--autotools-style] [<compiler> <flags>...]\n"
715                                "  <compiler> <flags> will have \"<outflag> <outfile> <infile.c>\" appended\n"
716                                "Default: %s %s %s\n",
717                                DEFAULT_COMPILER, DEFAULT_FLAGS,
718                                DEFAULT_OUTPUT_EXE_FLAG);
719                         exit(0);
720                 }
721                 if (strncmp(argv[1], "-O", 2) == 0) {
722                         argc--;
723                         argv++;
724                         outflag = argv[1] + 2;
725                         if (!*outflag) {
726                                 fprintf(stderr,
727                                         "%s: option requires an argument -- O\n",
728                                         argv[0]);
729                                 exit(1);
730                         }
731                 } else if (strcmp(argv[1], "-v") == 0) {
732                         argc--;
733                         argv++;
734                         verbose++;
735                 } else if (strcmp(argv[1], "-vv") == 0) {
736                         argc--;
737                         argv++;
738                         verbose += 2;
739                 } else if (strncmp(argv[1], "--configurator-cc=", 18) == 0) {
740                         configurator_cc = argv[1] + 18;
741                         argc--;
742                         argv++;
743                 } else if (strncmp(argv[1], "--var-file=", 11) == 0) {
744                         varfile = argv[1] + 11;
745                         argc--;
746                         argv++;
747                 } else if (strcmp(argv[1], "--autotools-style") == 0) {
748                         like_a_libtool = true;
749                         argc--;
750                         argv++;
751                 } else if (strncmp(argv[1], "--header-file=", 14) == 0) {
752                         headerfile = argv[1] + 14;
753                         argc--;
754                         argv++;
755                 } else if (strcmp(argv[1], "--") == 0) {
756                         break;
757                 } else if (argv[1][0] == '-') {
758                         c12r_errx(2, "Unknown option %s", argv[1]);
759                 } else {
760                         break;
761                 }
762         }
763
764         if (argc == 1)
765                 argv = default_args;
766
767         orig_cc = argv[1];
768         if (configurator_cc)
769                 argv[1] = configurator_cc;
770
771         cmd = connect_args(argv, outflag, OUTPUT_FILE " " INPUT_FILE);
772         if (like_a_libtool) {
773                 start_test("Making autoconf users comfortable", "");
774                 sleep(1);
775                 end_test(1);
776         }
777         for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++)
778                 run_test(cmd, &tests[i]);
779         free(cmd);
780
781         remove(OUTPUT_FILE);
782         remove(INPUT_FILE);
783
784         if (varfile) {
785                 FILE *vars;
786
787                 if (strcmp(varfile, "-") == 0)
788                         vars = stdout;
789                 else {
790                         start_test("Writing variables to ", varfile);
791                         vars = fopen(varfile, "a");
792                         if (!vars)
793                                 c12r_err(2, "Could not open %s", varfile);
794                 }
795                 for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++)
796                         fprintf(vars, "%s=%u\n", tests[i].name, tests[i].answer);
797                 if (vars != stdout) {
798                         if (fclose(vars) != 0)
799                                 c12r_err(2, "Closing %s", varfile);
800                         end_test(1);
801                 }
802         }
803
804         if (headerfile) {
805                 start_test("Writing header to ", headerfile);
806                 outf = fopen(headerfile, "w");
807                 if (!outf)
808                         c12r_err(2, "Could not open %s", headerfile);
809         } else
810                 outf = stdout;
811
812         fprintf(outf, "/* Generated by CCAN configurator */\n"
813                "#ifndef CCAN_CONFIG_H\n"
814                "#define CCAN_CONFIG_H\n");
815         fprintf(outf, "#ifndef _GNU_SOURCE\n");
816         fprintf(outf, "#define _GNU_SOURCE /* Always use GNU extensions. */\n");
817         fprintf(outf, "#endif\n");
818         fprintf(outf, "#define CCAN_COMPILER \"%s\"\n", orig_cc);
819         cmd = connect_args(argv + 1, "", "");
820         fprintf(outf, "#define CCAN_CFLAGS \"%s\"\n", cmd);
821         free(cmd);
822         fprintf(outf, "#define CCAN_OUTPUT_EXE_CFLAG \"%s\"\n\n", outflag);
823         /* This one implies "#include <ccan/..." works, eg. for tdb2.h */
824         fprintf(outf, "#define HAVE_CCAN 1\n");
825         for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++)
826                 fprintf(outf, "#define %s %u\n", tests[i].name, tests[i].answer);
827         fprintf(outf, "#endif /* CCAN_CONFIG_H */\n");
828
829         if (headerfile) {
830                 if (fclose(outf) != 0)
831                         c12r_err(2, "Closing %s", headerfile);
832                 end_test(1);
833         }
834
835         return 0;
836 }