]> git.ozlabs.org Git - ccan/blob - tools/configurator/configurator.c
d46a147ada14e3c8b16f53bb354be47a4491d229
[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  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 #include <stdio.h>
25 #include <stdbool.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <err.h>
29 #include <sys/types.h>
30 #include <sys/wait.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 #include <string.h>
34
35 #define DEFAULT_COMPILER "cc"
36 #define DEFAULT_FLAGS "-g -Wall -Wundef -Wmissing-prototypes -Wmissing-declarations -Wstrict-prototypes -Wold-style-definition"
37
38 #define OUTPUT_FILE "configurator.out"
39 #define INPUT_FILE "configuratortest.c"
40
41 static int verbose;
42
43 enum test_style {
44         OUTSIDE_MAIN            = 0x1,
45         DEFINES_FUNC            = 0x2,
46         INSIDE_MAIN             = 0x4,
47         DEFINES_EVERYTHING      = 0x8,
48         MAY_NOT_COMPILE         = 0x10,
49         EXECUTE                 = 0x8000
50 };
51
52 struct test {
53         const char *name;
54         enum test_style style;
55         const char *depends;
56         const char *fragment;
57         bool done;
58         bool answer;
59 };
60
61 static struct test tests[] = {
62         { "HAVE_32BIT_OFF_T", DEFINES_EVERYTHING|EXECUTE, NULL,
63           "#include <sys/types.h>\n"
64           "int main(int argc, char *argv[]) {\n"
65           "     return sizeof(off_t) == 4 ? 0 : 1;\n"
66           "}\n" },
67         { "HAVE_ALIGNOF", INSIDE_MAIN, NULL,
68           "return __alignof__(double) > 0 ? 0 : 1;" },
69         { "HAVE_ASPRINTF", DEFINES_FUNC, NULL,
70           "#define _GNU_SOURCE\n"
71           "#include <stdio.h>\n"
72           "static char *func(int x) {"
73           "     char *p;\n"
74           "     if (asprintf(&p, \"%u\", x) == -1) p = NULL;"
75           "     return p;\n"
76           "}" },
77         { "HAVE_ATTRIBUTE_COLD", DEFINES_FUNC, NULL,
78           "static int __attribute__((cold)) func(int x) { return x; }" },
79         { "HAVE_ATTRIBUTE_CONST", DEFINES_FUNC, NULL,
80           "static int __attribute__((const)) func(int x) { return x; }" },
81         { "HAVE_ATTRIBUTE_MAY_ALIAS", OUTSIDE_MAIN, NULL,
82           "typedef short __attribute__((__may_alias__)) short_a;" },
83         { "HAVE_ATTRIBUTE_NORETURN", DEFINES_FUNC, NULL,
84           "#include <stdlib.h>\n"
85           "static void __attribute__((noreturn)) func(int x) { exit(x); }" },
86         { "HAVE_ATTRIBUTE_PRINTF", DEFINES_FUNC, NULL,
87           "static void __attribute__((format(__printf__, 1, 2))) func(const char *fmt, ...) { }" },
88         { "HAVE_ATTRIBUTE_UNUSED", OUTSIDE_MAIN, NULL,
89           "static int __attribute__((unused)) func(int x) { return x; }" },
90         { "HAVE_ATTRIBUTE_USED", OUTSIDE_MAIN, NULL,
91           "static int __attribute__((used)) func(int x) { return x; }" },
92         { "HAVE_BIG_ENDIAN", INSIDE_MAIN|EXECUTE, NULL,
93           "union { int i; char c[sizeof(int)]; } u;\n"
94           "u.i = 0x01020304;\n"
95           "return u.c[0] == 0x01 && u.c[1] == 0x02 && u.c[2] == 0x03 && u.c[3] == 0x04 ? 0 : 1;" },
96         { "HAVE_BSWAP_64", DEFINES_FUNC, "HAVE_BYTESWAP_H",
97           "#include <byteswap.h>\n"
98           "static int func(int x) { return bswap_64(x); }" },
99         { "HAVE_BUILTIN_CHOOSE_EXPR", INSIDE_MAIN, NULL,
100           "return __builtin_choose_expr(1, 0, \"garbage\");" },
101         { "HAVE_BUILTIN_CLZ", INSIDE_MAIN, NULL,
102           "return __builtin_clz(1) == (sizeof(int)*8 - 1) ? 0 : 1;" },
103         { "HAVE_BUILTIN_CLZL", INSIDE_MAIN, NULL,
104           "return __builtin_clzl(1) == (sizeof(long)*8 - 1) ? 0 : 1;" },
105         { "HAVE_BUILTIN_CLZLL", INSIDE_MAIN, NULL,
106           "return __builtin_clzll(1) == (sizeof(long long)*8 - 1) ? 0 : 1;" },
107         { "HAVE_BUILTIN_CONSTANT_P", INSIDE_MAIN, NULL,
108           "return __builtin_constant_p(1) ? 0 : 1;" },
109         { "HAVE_BUILTIN_EXPECT", INSIDE_MAIN, NULL,
110           "return __builtin_expect(argc == 1, 1) ? 0 : 1;" },
111         { "HAVE_BUILTIN_FFSL", INSIDE_MAIN, NULL,
112           "return __builtin_ffsl(0L) == 0 ? 0 : 1;" },
113         { "HAVE_BUILTIN_FFSLL", INSIDE_MAIN, NULL,
114           "return __builtin_ffsll(0LL) == 0 ? 0 : 1;" },
115         { "HAVE_BUILTIN_POPCOUNTL", INSIDE_MAIN, NULL,
116           "return __builtin_popcountl(255L) == 8 ? 0 : 1;" },
117         { "HAVE_BUILTIN_TYPES_COMPATIBLE_P", INSIDE_MAIN, NULL,
118           "return __builtin_types_compatible_p(char *, int) ? 1 : 0;" },
119         { "HAVE_BYTESWAP_H", OUTSIDE_MAIN, NULL,
120           "#include <byteswap.h>\n" },
121         { "HAVE_COMPOUND_LITERALS", INSIDE_MAIN, NULL,
122           "int *foo = (int[]) { 1, 2, 3, 4 };\n"
123           "return foo[0] ? 0 : 1;" },
124         { "HAVE_FILE_OFFSET_BITS", DEFINES_EVERYTHING|EXECUTE,
125           "HAVE_32BIT_OFF_T",
126           "#define _FILE_OFFSET_BITS 64\n"
127           "#include <sys/types.h>\n"
128           "int main(int argc, char *argv[]) {\n"
129           "     return sizeof(off_t) == 8 ? 0 : 1;\n"
130           "}\n" },
131         { "HAVE_FOR_LOOP_DECLARATION", INSIDE_MAIN, NULL,
132           "for (int i = 0; i < argc; i++) { return 0; };\n"
133           "return 1;" },
134         { "HAVE_FLEXIBLE_ARRAY_MEMBER", OUTSIDE_MAIN, NULL,
135           "struct foo { unsigned int x; int arr[]; };" },
136         { "HAVE_GETPAGESIZE", DEFINES_FUNC, NULL,
137           "#include <unistd.h>\n"
138           "static int func(void) { return getpagesize(); }" },
139         { "HAVE_ISBLANK", DEFINES_FUNC, NULL,
140           "#define _GNU_SOURCE\n"
141           "#include <ctype.h>\n"
142           "static int func(void) { return isblank(' '); }" },
143         { "HAVE_LITTLE_ENDIAN", INSIDE_MAIN|EXECUTE, NULL,
144           "union { int i; char c[sizeof(int)]; } u;\n"
145           "u.i = 0x01020304;\n"
146           "return u.c[0] == 0x04 && u.c[1] == 0x03 && u.c[2] == 0x02 && u.c[3] == 0x01 ? 0 : 1;" },
147         { "HAVE_MEMMEM", DEFINES_FUNC, NULL,
148           "#define _GNU_SOURCE\n"
149           "#include <string.h>\n"
150           "static void *func(void *h, size_t hl, void *n, size_t nl) {\n"
151           "return memmem(h, hl, n, nl);"
152           "}\n", },
153         { "HAVE_MMAP", DEFINES_FUNC, NULL,
154           "#include <sys/mman.h>\n"
155           "static void *func(int fd) {\n"
156           "     return mmap(0, 65536, PROT_READ, MAP_SHARED, fd, 0);\n"
157           "}" },
158         { "HAVE_QSORT_R_PRIVATE_LAST",
159           DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE, NULL,
160           "#define _GNU_SOURCE 1\n"
161           "#include <stdlib.h>\n"
162           "static int cmp(const void *lp, const void *rp, void *priv) {\n"
163           " *(unsigned int *)priv = 1;\n"
164           " return *(const int *)lp - *(const int *)rp; }\n"
165           "int main(void) {\n"
166           " int array[] = { 9, 2, 5 };\n"
167           " unsigned int called = 0;\n"
168           " qsort_r(array, 3, sizeof(int), cmp, &called);\n"
169           " return called && array[0] == 2 && array[1] == 5 && array[2] == 9 ? 0 : 1;\n"
170           "}\n" },
171         { "HAVE_STACK_GROWS_UPWARDS", DEFINES_EVERYTHING|EXECUTE, NULL,
172           "static long nest(const void *base, unsigned int i)\n"
173           "{\n"
174           "     if (i == 0)\n"
175           "             return (const char *)&i - (const char *)base;\n"
176           "     return nest(base, i-1);\n"
177           "}\n"
178           "int main(int argc, char *argv[]) {\n"
179           "     return (nest(&argc, argc) > 0) ? 0 : 1\n;"
180           "}\n" },
181         { "HAVE_STATEMENT_EXPR", INSIDE_MAIN, NULL,
182           "return ({ int x = argc; x == argc ? 0 : 1; });" },
183         { "HAVE_TYPEOF", INSIDE_MAIN, NULL,
184           "__typeof__(argc) i; i = argc; return i == argc ? 0 : 1;" },
185         { "HAVE_UTIME", DEFINES_FUNC, NULL,
186           "#include <sys/types.h>\n"
187           "#include <utime.h>\n"
188           "static int func(const char *filename) {\n"
189           "     struct utimbuf times = { 0 };\n"
190           "     return utime(filename, &times);\n"
191           "}" },
192         { "HAVE_WARN_UNUSED_RESULT", DEFINES_FUNC, NULL,
193           "#include <sys/types.h>\n"
194           "#include <utime.h>\n"
195           "static __attribute__((warn_unused_result)) int func(int i) {\n"
196           "     return i + 1;\n"
197           "}" },
198 };
199
200 static char *grab_fd(int fd)
201 {
202         int ret;
203         size_t max, size = 0;
204         char *buffer;
205
206         max = 16384;
207         buffer = malloc(max+1);
208         while ((ret = read(fd, buffer + size, max - size)) > 0) {
209                 size += ret;
210                 if (size == max)
211                         buffer = realloc(buffer, max *= 2);
212         }
213         if (ret < 0)
214                 err(1, "reading from command");
215         buffer[size] = '\0';
216         return buffer;
217 }
218
219 static char *run(const char *cmd, int *exitstatus)
220 {
221         pid_t pid;
222         int p[2];
223         char *ret;
224         int status;
225
226         if (pipe(p) != 0)
227                 err(1, "creating pipe");
228
229         pid = fork();
230         if (pid == -1)
231                 err(1, "forking");
232
233         if (pid == 0) {
234                 if (dup2(p[1], STDOUT_FILENO) != STDOUT_FILENO
235                     || dup2(p[1], STDERR_FILENO) != STDERR_FILENO
236                     || close(p[0]) != 0
237                     || close(STDIN_FILENO) != 0
238                     || open("/dev/null", O_RDONLY) != STDIN_FILENO)
239                         exit(128);
240
241                 status = system(cmd);
242                 if (WIFEXITED(status))
243                         exit(WEXITSTATUS(status));
244                 /* Here's a hint... */
245                 exit(128 + WTERMSIG(status));
246         }
247
248         close(p[1]);
249         ret = grab_fd(p[0]);
250         /* This shouldn't fail... */
251         if (waitpid(pid, &status, 0) != pid)
252                 err(1, "Failed to wait for child");
253         close(p[0]);
254         if (WIFEXITED(status))
255                 *exitstatus = WEXITSTATUS(status);
256         else
257                 *exitstatus = -WTERMSIG(status);
258         return ret;
259 }
260
261 static char *connect_args(const char *argv[], const char *extra)
262 {
263         unsigned int i, len = strlen(extra) + 1;
264         char *ret;
265
266         for (i = 1; argv[i]; i++)
267                 len += 1 + strlen(argv[i]);
268
269         ret = malloc(len);
270         len = 0;
271         for (i = 1; argv[i]; i++) {
272                 strcpy(ret + len, argv[i]);
273                 len += strlen(argv[i]);
274                 ret[len++] = ' ';
275         }
276         strcpy(ret + len, extra);
277         return ret;
278 }
279
280 static struct test *find_test(const char *name)
281 {
282         unsigned int i;
283
284         for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) {
285                 if (strcmp(tests[i].name, name) == 0)
286                         return &tests[i];
287         }
288         abort();
289 }
290
291 #define PRE_BOILERPLATE "/* Test program generated by configurator. */\n"
292 #define MAIN_START_BOILERPLATE "int main(int argc, char *argv[]) {\n"
293 #define USE_FUNC_BOILERPLATE "(void)func;\n"
294 #define MAIN_BODY_BOILERPLATE "return 0;\n"
295 #define MAIN_END_BOILERPLATE "}\n"
296
297 static bool run_test(const char *cmd, struct test *test)
298 {
299         char *output;
300         FILE *outf;
301         int status;
302
303         if (test->done)
304                 return test->answer;
305
306         if (test->depends && !run_test(cmd, find_test(test->depends))) {
307                 test->answer = false;
308                 test->done = true;
309                 return test->answer;
310         }
311
312         outf = fopen(INPUT_FILE, "w");
313         if (!outf)
314                 err(1, "creating %s", INPUT_FILE);
315
316         fprintf(outf, "%s", PRE_BOILERPLATE);
317         switch (test->style & ~(EXECUTE|MAY_NOT_COMPILE)) {
318         case INSIDE_MAIN:
319                 fprintf(outf, "%s", MAIN_START_BOILERPLATE);
320                 fprintf(outf, "%s", test->fragment);
321                 fprintf(outf, "%s", MAIN_END_BOILERPLATE);
322                 break;
323         case OUTSIDE_MAIN:
324                 fprintf(outf, "%s", test->fragment);
325                 fprintf(outf, "%s", MAIN_START_BOILERPLATE);
326                 fprintf(outf, "%s", MAIN_BODY_BOILERPLATE);
327                 fprintf(outf, "%s", MAIN_END_BOILERPLATE);
328                 break;
329         case DEFINES_FUNC:
330                 fprintf(outf, "%s", test->fragment);
331                 fprintf(outf, "%s", MAIN_START_BOILERPLATE);
332                 fprintf(outf, "%s", USE_FUNC_BOILERPLATE);
333                 fprintf(outf, "%s", MAIN_BODY_BOILERPLATE);
334                 fprintf(outf, "%s", MAIN_END_BOILERPLATE);
335                 break;
336         case DEFINES_EVERYTHING:
337                 fprintf(outf, "%s", test->fragment);
338                 break;
339         default:
340                 abort();
341
342         }
343         fclose(outf);
344
345         if (verbose > 1)
346                 if (system("cat " INPUT_FILE) == -1);
347
348         output = run(cmd, &status);
349         if (status != 0 || strstr(output, "warning")) {
350                 if (verbose)
351                         printf("Compile %s for %s, status %i: %s\n",
352                                status ? "fail" : "warning",
353                                test->name, status, output);
354                 if ((test->style & EXECUTE) && !(test->style & MAY_NOT_COMPILE))
355                         errx(1, "Test for %s did not compile:\n%s",
356                              test->name, output);
357                 test->answer = false;
358                 free(output);
359         } else {
360                 /* Compile succeeded. */
361                 free(output);
362                 /* We run INSIDE_MAIN tests for sanity checking. */
363                 if ((test->style & EXECUTE) || (test->style & INSIDE_MAIN)) {
364                         output = run("./" OUTPUT_FILE, &status);
365                         if (!(test->style & EXECUTE) && status != 0)
366                                 errx(1, "Test for %s failed with %i:\n%s",
367                                      test->name, status, output);
368                         if (verbose && status)
369                                 printf("%s exited %i\n", test->name, status);
370                         free(output);
371                 }
372                 test->answer = (status == 0);
373         }
374         test->done = true;
375         return test->answer;
376 }
377
378 int main(int argc, const char *argv[])
379 {
380         char *cmd;
381         unsigned int i;
382         const char *default_args[]
383                 = { "", DEFAULT_COMPILER, DEFAULT_FLAGS, NULL };
384
385         if (argc > 1) {
386                 if (strcmp(argv[1], "--help") == 0) {
387                         printf("Usage: configurator [-v] [<compiler> <flags>...]\n"
388                                "  <compiler> <flags> will have \"-o <outfile> <infile.c>\" appended\n"
389                                "Default: %s %s\n",
390                                DEFAULT_COMPILER, DEFAULT_FLAGS);
391                         exit(0);
392                 }
393                 if (strcmp(argv[1], "-v") == 0) {
394                         argc--;
395                         argv++;
396                         verbose = 1;
397                 } else if (strcmp(argv[1], "-vv") == 0) {
398                         argc--;
399                         argv++;
400                         verbose = 2;
401                 }
402         }
403
404         if (argc == 1)
405                 argv = default_args;
406
407         cmd = connect_args(argv, "-o " OUTPUT_FILE " " INPUT_FILE);
408         for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++)
409                 run_test(cmd, &tests[i]);
410
411         unlink(OUTPUT_FILE);
412         unlink(INPUT_FILE);
413
414         cmd[strlen(cmd) - strlen(" -o " OUTPUT_FILE " " INPUT_FILE)] = '\0';
415         printf("/* Generated by CCAN configurator */\n"
416                "#ifndef CCAN_CONFIG_H\n"
417                "#define CCAN_CONFIG_H\n");
418         printf("#ifndef _GNU_SOURCE\n");
419         printf("#define _GNU_SOURCE /* Always use GNU extensions. */\n");
420         printf("#endif\n");
421         printf("#define CCAN_COMPILER \"%s\"\n", argv[1]);
422         printf("#define CCAN_CFLAGS \"%s\"\n\n", cmd + strlen(argv[1]) + 1);
423         for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++)
424                 printf("#define %s %u\n", tests[i].name, tests[i].answer);
425         printf("#endif /* CCAN_CONFIG_H */\n");
426         return 0;
427 }