]> git.ozlabs.org Git - ccan/blob - tools/ccanlint/tests/examples_compile.c
ccanlint: compile tests in parallel
[ccan] / tools / ccanlint / tests / examples_compile.c
1 #include <tools/ccanlint/ccanlint.h>
2 #include <tools/tools.h>
3 #include <ccan/talloc/talloc.h>
4 #include <ccan/cast/cast.h>
5 #include <ccan/str/str.h>
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <fcntl.h>
9 #include <stdint.h>
10 #include <string.h>
11 #include <unistd.h>
12 #include <ctype.h>
13 #include <assert.h>
14 #include <err.h>
15 #include "../compulsory_tests/build.h"
16
17 static const char *can_run(struct manifest *m)
18 {
19         if (safe_mode)
20                 return "Safe mode enabled";
21         if (list_empty(&m->examples))
22                 return "No examples to compile";
23         return NULL;
24 }
25
26 static void add_mod(struct manifest ***deps, struct manifest *m)
27 {
28         unsigned int num = talloc_get_size(*deps) / sizeof(*deps);
29         *deps = talloc_realloc(NULL, *deps, struct manifest *, num + 1);
30         (*deps)[num] = m;
31 }
32
33 static bool have_mod(struct manifest *deps[], const char *basename)
34 {
35         unsigned int i;
36
37         for (i = 0; i < talloc_get_size(deps) / sizeof(*deps); i++)
38                 if (strcmp(deps[i]->basename, basename) == 0)
39                         return true;
40         return false;
41 }
42
43 static void add_dep(struct manifest ***deps, const char *basename)
44 {
45         unsigned int i;
46         struct manifest *m;
47         char *errstr;
48
49         if (have_mod(*deps, basename))
50                 return;
51
52         m = get_manifest(*deps, talloc_asprintf(*deps, "%s/ccan/%s",
53                                                 ccan_dir, basename));
54         errstr = build_submodule(m, cflags, COMPILE_NORMAL);
55         if (errstr)
56                 errx(1, "%s", errstr);
57
58         add_mod(deps, m);
59
60         /* Get that modules depends as well... */
61         assert(!safe_mode);
62         if (m->info_file) {
63                 char **infodeps;
64
65                 infodeps = get_deps(m, m->dir, false,
66                                     &m->info_file->compiled[COMPILE_NORMAL]);
67
68                 for (i = 0; infodeps[i]; i++) {
69                         if (strstarts(infodeps[i], "ccan/"))
70                                 add_dep(deps, infodeps[i] + strlen("ccan/"));
71                 }
72         }
73 }
74
75 static char *example_obj_list(struct manifest *m, struct ccan_file *f)
76 {
77         struct manifest **deps = talloc_array(f, struct manifest *, 0);
78         char **lines, *list;
79         unsigned int i;
80
81         /* This one for a start. */
82         add_dep(&deps, m->basename);
83
84         /* Other modules implied by includes. */
85         for (lines = get_ccan_file_lines(f); *lines; lines++) {
86                 unsigned preflen = strspn(*lines, " \t");
87                 if (strstarts(*lines + preflen, "#include <ccan/")) {
88                         char *modname;
89
90                         modname = talloc_strdup(f, *lines + preflen
91                                                 + strlen("#include <ccan/"));
92                         modname[strcspn(modname, "/")] = '\0';
93                         if (!have_mod(deps, modname))
94                                 add_dep(&deps, modname);
95                 }
96         }
97
98         list = talloc_strdup(f, "");
99         for (i = 0; i < talloc_get_size(deps) / sizeof(*deps); i++) {
100                 if (deps[i]->compiled[COMPILE_NORMAL])
101                         list = talloc_asprintf_append(list, " %s",
102                                                       deps[i]->compiled
103                                                       [COMPILE_NORMAL]);
104         }
105         return list;
106 }
107
108 /* FIXME: Test with reduced features! */
109 static char *lib_list(const struct manifest *m)
110 {
111         unsigned int i, num;
112         char **libs;
113         char *ret = talloc_strdup(m, "");
114
115         libs = get_libs(m, m->dir, &num,
116                         &m->info_file->compiled[COMPILE_NORMAL]);
117         for (i = 0; i < num; i++)
118                 ret = talloc_asprintf_append(ret, "-l%s ", libs[i]);
119         return ret;
120 }
121
122 static bool compile(const void *ctx,
123                     struct manifest *m,
124                     struct ccan_file *file,
125                     bool keep, char **output)
126 {
127         file->compiled[COMPILE_NORMAL]
128                 = maybe_temp_file(ctx, "", keep, file->fullname);
129         if (!compile_and_link(ctx, file->fullname, ccan_dir,
130                               example_obj_list(m, file),
131                               compiler, cflags,
132                               lib_list(m), file->compiled[COMPILE_NORMAL],
133                               output)) {
134                 /* Don't keep failures. */
135                 if (keep)
136                         unlink(file->compiled[COMPILE_NORMAL]);
137                 talloc_free(file->compiled[COMPILE_NORMAL]);
138                 file->compiled[COMPILE_NORMAL] = NULL;
139                 return false;
140         }
141         return true;
142 }
143
144 static char *start_main(char *ret, const char *why)
145 {
146         return talloc_asprintf_append(ret,
147               "/* The example %s, so fake function wrapper inserted */\n"
148               "int main(int argc, char *argv[])\n"
149               "{\n", why);
150 }
151
152 /* We only handle simple function definitions here. */
153 static char *add_func(char *others, const char *line)
154 {
155         const char *p, *end = strchr(line, '(') - 1;
156         while (cisspace(*end)) {
157                 end--;
158                 if (end == line)
159                         return others;
160         }
161
162         for (p = end; cisalnum(*p) || *p == '_'; p--) {
163                 if (p == line)
164                         return others;
165         }
166
167         return talloc_asprintf_append(others, "printf(\"%%p\", %.*s);\n",
168                                       (unsigned)(end - p), p+1);
169 }
170
171 static void strip_leading_whitespace(char **lines)
172 {
173         unsigned int i, min_span = -1U;
174
175         for (i = 0; lines[i]; i++) {
176                 unsigned int span = strspn(lines[i], " \t");
177                 /* All whitespace?  Ignore */
178                 if (!lines[i][span])
179                         continue;
180                 if (span < min_span)
181                         min_span = span;
182         }
183
184         for (i = 0; lines[i]; i++)
185                 if (strlen(lines[i]) >= min_span)
186                         lines[i] += min_span;
187 }
188
189 static bool looks_internal(char **lines, char **why)
190 {
191         unsigned int i;
192         bool last_ended = true; /* Did last line finish a statement? */
193
194         for (i = 0; lines[i]; i++) {
195                 /* Skip leading whitespace. */
196                 const char *line = lines[i] + strspn(lines[i], " \t");
197                 unsigned len = strspn(line, IDENT_CHARS);
198
199                 if (!line[0] || cisspace(line[0]) || strstarts(line, "//"))
200                         continue;
201
202                 /* The winners. */
203                 if (strstarts(line, "if") && len == 2) {
204                         *why = cast_const(char *, "starts with if");
205                         return true;
206                 }
207                 if (strstarts(line, "for") && len == 3) {
208                         *why = cast_const(char *, "starts with for");
209                         return true;
210                 }
211                 if (strstarts(line, "while") && len == 5) {
212                         *why = cast_const(char *, "starts with while");
213                         return true;
214                 }
215                 if (strstarts(line, "do") && len == 2) {
216                         *why = cast_const(char *, "starts with do");
217                         return true;
218                 }
219
220                 /* The losers. */
221                 if (strstarts(line, "#include")) {
222                         *why = cast_const(char *, "starts with #include");
223                         return false;
224                 }
225
226                 if (last_ended && strchr(line, '(')) {
227                         if (strstarts(line, "static")) {
228                                 *why = cast_const(char *,
229                                                   "starts with static"
230                                                   " and contains (");
231                                 return false;
232                         }
233                         if (strends(line, ")")) {
234                                 *why = cast_const(char *,
235                                                   "contains ( and ends with )");
236                                 return false;
237                         }
238                 }
239
240                 /* Single identifier then operator == inside function. */
241                 if (last_ended && len
242                     && cispunct(line[len+strspn(line+len, " ")])) {
243                         *why = cast_const(char *, "starts with identifier"
244                                           " then punctuation");
245                         return true;
246                 }
247
248                 last_ended = (strends(line, "}")
249                               || strends(line, ";")
250                               || streq(line, "..."));
251         }
252
253         /* No idea... Say yes? */
254         *why = cast_const(char *, "gave no clues");
255         return true;
256 }
257
258 /* Examples will often build on prior ones.  Try combining them. */
259 static char **combine(const void *ctx, char **lines, char **prev)
260 {
261         unsigned int i, lines_total, prev_total, count;
262         char **ret;
263         const char *reasoning;
264         char *why = NULL;
265
266         if (!prev)
267                 return NULL;
268
269         /* If it looks internal, put prev at start. */
270         if (looks_internal(lines, &why)) {
271                 count = 0;
272                 reasoning = "seemed to belong inside a function";
273         } else {
274                 /* Try inserting in first elided position */
275                 for (count = 0; lines[count]; count++) {
276                         if (strcmp(lines[count], "...") == 0)
277                                 break;
278                 }
279                 if (!lines[count]) {
280                         /* Try at start anyway? */
281                         count = 0;
282                         reasoning = "didn't seem to belong inside"
283                                 " a function, so we prepended the previous"
284                                 " example";
285                 } else {
286                         reasoning = "didn't seem to belong inside"
287                                 " a function, so we put the previous example"
288                                 " at the first ...";
289
290                         count++;
291                 }
292         }
293
294         for (i = 0; lines[i]; i++);
295         lines_total = i;
296
297         for (i = 0; prev[i]; i++);
298         prev_total = i;
299
300         ret = talloc_array(ctx, char *, 1 +lines_total + prev_total + 1);
301         ret[0] = talloc_asprintf(ret, "/* The example %s, thus %s */\n",
302                                  why, reasoning);
303         memcpy(ret+1, lines, count * sizeof(ret[0]));
304         memcpy(ret+1 + count, prev, prev_total * sizeof(ret[0]));
305         memcpy(ret+1 + count + prev_total, lines + count,
306                (lines_total - count + 1) * sizeof(ret[0]));
307         return ret;
308 }
309
310 /* Only handles very simple comments. */
311 static char *strip_comment(const void *ctx, const char *orig_line)
312 {
313         char *p, *ret = talloc_strdup(ctx, orig_line);
314
315         p = strstr(ret, "/*");
316         if (!p)
317                 p = strstr(ret, "//");
318         if (p)
319                 *p = '\0';
320         return ret;
321 }
322
323 static char *mangle(struct manifest *m, char **lines)
324 {
325         char *ret, *use_funcs = NULL, *why;
326         bool in_function = false, fake_function = false, has_main = false;
327         unsigned int i;
328
329         ret = talloc_asprintf(m, 
330                               "/* Include header from module. */\n"
331                               "#include <ccan/%s/%s.h>\n"
332                               "/* Prepend a heap of headers. */\n"
333                               "#include <assert.h>\n"
334                               "#include <err.h>\n"
335                               "#include <errno.h>\n"
336                               "#include <fcntl.h>\n"
337                               "#include <limits.h>\n"
338                               "#include <stdbool.h>\n"
339                               "#include <stdint.h>\n"
340                               "#include <stdio.h>\n"
341                               "#include <stdlib.h>\n"
342                               "#include <string.h>\n"
343                               "#include <sys/stat.h>\n"
344                               "#include <sys/types.h>\n"
345                               "#include <unistd.h>\n",
346                               m->basename, m->basename);
347
348         ret = talloc_asprintf_append(ret, "/* Useful dummy functions. */\n"
349                                      "extern int somefunc(void);\n"
350                                      "int somefunc(void) { return 0; }\n"
351                                      "extern char somestring[];\n"
352                                      "char somestring[] = \"hello world\";\n");
353
354         if (looks_internal(lines, &why)) {
355                 /* Wrap it all in main(). */
356                 ret = start_main(ret, why);
357                 fake_function = true;
358                 in_function = true;
359                 has_main = true;
360         } else
361                 ret = talloc_asprintf_append(ret,
362                              "/* The example %s, so didn't wrap in main() */\n",
363                                      why);
364
365         /* Primitive, very primitive. */
366         for (i = 0; lines[i]; i++) {
367                 char *line = strip_comment(ret, lines[i]);
368
369                 /* } at start of line ends a function. */
370                 if (in_function) {
371                         if (line[0] == '}')
372                                 in_function = false;
373                 } else {
374                         /* Character at start of line, with ( and no ;
375                          * == function start.  Ignore comments. */
376                         if (!cisspace(line[0])
377                             && strchr(line, '(')
378                             && !strchr(line, ';')
379                             && !strstr(line, "//")) {
380                                 in_function = true;
381                                 if (strncmp(line, "int main", 8) == 0)
382                                         has_main = true;
383                                 if (strncmp(line, "static", 6) == 0) {
384                                         use_funcs = add_func(use_funcs,
385                                                              line);
386                                 }
387                         }
388                 }
389                 /* ... means elided code. */
390                 if (strcmp(line, "...") == 0) {
391                         if (!in_function && !has_main
392                             && looks_internal(lines + i + 1, &why)) {
393                                 /* This implies we start a function here. */
394                                 ret = start_main(ret, why);
395                                 has_main = true;
396                                 fake_function = true;
397                                 in_function = true;
398                         }
399                         ret = talloc_asprintf_append(ret,
400                                                      "/* ... removed */\n");
401                         continue;
402                 }
403                 ret = talloc_asprintf_append(ret, "%s\n", lines[i]);
404         }
405
406         if (!has_main) {
407                 ret = talloc_asprintf_append(ret,
408                              "/* Need a main to link successfully. */\n"
409                              "int main(void)\n{\n");
410                 fake_function = true;
411         }
412
413         if (use_funcs) {
414                 ret = talloc_asprintf_append(ret,
415                                              "/* Get rid of unused warnings"
416                                              " by printing addresses of"
417                                              " static funcs. */\n");
418                 if (!fake_function) {
419                         ret = talloc_asprintf_append(ret,
420                                                      "int use_funcs(void);\n"
421                                                      "int use_funcs(void) {\n");
422                         fake_function = true;
423                 }
424                 ret = talloc_asprintf_append(ret, "     %s\n", use_funcs);
425         }
426
427         if (fake_function)
428                 ret = talloc_asprintf_append(ret, "return 0;\n"
429                                              "}\n");
430         return ret;
431 }
432
433 static struct ccan_file *mangle_example(struct manifest *m,
434                                         struct ccan_file *example,
435                                         char **lines,
436                                         bool keep)
437 {
438         char *name, *contents;
439         int fd;
440         struct ccan_file *f;
441
442         name = maybe_temp_file(example, ".c", keep, 
443                                talloc_asprintf(m, "%s/mangled-%s",
444                                                m->dir, example->name));
445         f = new_ccan_file(example,
446                           talloc_dirname(example, name),
447                           talloc_basename(example, name));
448         talloc_steal(f, name);
449
450         fd = open(f->fullname, O_WRONLY | O_CREAT | O_EXCL, 0600);
451         if (fd < 0)
452                 return NULL;
453
454         contents = mangle(m, lines);
455         if (write(fd, contents, strlen(contents)) != strlen(contents)) {
456                 close(fd);
457                 return NULL;
458         }
459         close(fd);
460         f->contents = talloc_steal(f, contents);
461         list_add(&m->mangled_examples, &f->list);
462         return f;
463 }
464
465 /* If an example has expected output, it's complete and should not be
466  * included in future examples. */
467 static bool has_expected_output(char **lines)
468 {
469         unsigned int i;
470
471         for (i = 0; lines[i]; i++) {
472                 char *p = lines[i] + strspn(lines[i], " \t");
473                 if (!strstarts(p, "//"))
474                         continue;
475                 p += strspn(p, "/ ");
476                 if (strncasecmp(p, "given", strlen("given")) == 0)
477                         return true;
478         }
479         return false;
480 }
481
482 static unsigned int try_compiling(struct manifest *m,
483                                   struct ccan_file *i,
484                                   char **prev,
485                                   bool keep,
486                                   struct ccan_file *mangled[3],
487                                   bool res[3],
488                                   char *err[3],
489                                   char **lines[3])
490 {
491         unsigned int num;
492
493         /* Try standalone. */
494         mangled[0] = i;
495         res[0] = compile(i, m, mangled[0], keep, &err[0]);
496         lines[0] = get_ccan_file_lines(i);
497         if (res[0] && streq(err[0], ""))
498                 return 1;
499
500         if (prev) {
501                 lines[1] = combine(i, get_ccan_file_lines(i), prev);
502
503                 mangled[1] = mangle_example(m, i, lines[1], keep);
504                 res[1] = compile(i, m, mangled[1], keep, &err[1]);
505                 if (res[1] && streq(err[1], "")) {
506                         return 2;
507                 }
508                 num = 2;
509         } else
510                 num = 1;
511
512         /* Try standalone. */
513         lines[num] = get_ccan_file_lines(i);
514         mangled[num] = mangle_example(m, i, lines[num], keep);
515         res[num] = compile(i, m, mangled[num], keep, &err[num]);
516
517         return num+1;
518 }
519
520 static void build_examples(struct manifest *m, bool keep,
521                            unsigned int *timeleft, struct score *score)
522 {
523         struct ccan_file *i;
524         char **prev = NULL;
525         bool warnings = false;
526
527         score->total = 0;
528         score->pass = true;
529
530         list_for_each(&m->examples, i, list) {
531                 char *err[3];
532                 struct ccan_file *file[3] = { NULL, NULL, NULL };
533                 bool res[3];
534                 unsigned num, j;
535                 char **lines[3];
536                 const char *error;
537
538                 score->total++;
539
540                 /* Simplify our dumb parsing. */
541                 strip_leading_whitespace(get_ccan_file_lines(i));
542
543                 num = try_compiling(m, i, prev, keep, file, res, err, lines);
544
545                 /* First look for a compile without any warnings. */
546                 for (j = 0; j < num; j++) {
547                         if (res[j] && streq(err[j], "")) {
548                                 if (!has_expected_output(lines[j]))
549                                         prev = lines[j];
550                                 score->score++;
551                                 goto next;
552                         }
553                 }
554
555                 /* Now accept anything which succeeded. */
556                 for (j = 0; j < num; j++) {
557                         if (res[j]) {
558                                 if (!has_expected_output(lines[j]))
559                                         prev = lines[j];
560                                 score->score++;
561                                 warnings = true;
562                                 score_file_error(score, file[j], 0,
563                                                  "Compiling extracted example"
564                                                  " gave warnings:\n"
565                                                  "Example:\n"
566                                                  "%s\n"
567                                                  "Compiler:\n"
568                                                  "%s",
569                                                  get_ccan_file_contents(file[j]),
570                                                  err[j]);
571                                 goto next;
572                         }
573                 }
574
575                 score->pass = false;
576                 if (!verbose) {
577                         if (num == 3)
578                                 error = "Compiling standalone, adding headers, "
579                                         "and including previous "
580                                         "example all failed";
581                         else
582                                 error = "Standalone compile and"
583                                         " adding headers both failed";
584                 } else {
585                         if (num == 3) {
586                                 error = talloc_asprintf(score,
587                                       "Standalone example:\n"
588                                       "%s\n"
589                                       "Errors: %s\n\n"
590                                       "Combining with previous example:\n"
591                                       "%s\n"
592                                       "Errors: %s\n\n"
593                                       "Adding headers, wrappers:\n"
594                                       "%s\n"
595                                       "Errors: %s\n\n",
596                                       get_ccan_file_contents(file[0]),
597                                       err[0],
598                                       get_ccan_file_contents(file[1]),
599                                       err[1],
600                                       get_ccan_file_contents(file[2]),
601                                       err[2]);
602                         } else {
603                                 error = talloc_asprintf(score,
604                                       "Standalone example:\n"
605                                       "%s\n"
606                                       "Errors: %s\n\n"
607                                       "Adding headers, wrappers:\n"
608                                       "%s\n"
609                                       "Errors: %s\n\n",
610                                       get_ccan_file_contents(file[0]),
611                                       err[0],
612                                       get_ccan_file_contents(file[1]),
613                                       err[1]);
614                         }
615                 }
616                 score_file_error(score, i, 0, "%s", error);
617                 /* This didn't work, so not a candidate for combining. */
618                 prev = NULL;
619
620         next:
621                 ;
622         }
623
624         /* An extra point if they all compiled without warnings. */
625         if (!list_empty(&m->examples)) {
626                 score->total++;
627                 if (!warnings)
628                         score->score++;
629         }
630 }
631
632 struct ccanlint examples_compile = {
633         .key = "examples_compile",
634         .name = "Module examples compile",
635         .check = build_examples,
636         .can_run = can_run,
637         .needs = "examples_exist module_builds"
638 };
639
640 REGISTER_TEST(examples_compile);