]> git.ozlabs.org Git - ccan/blob - tools/ccanlint/tests/examples_compile.c
ccanlint: use traversal to trim tests we want to skip.
[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 "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                 assert(line[strlen(line)-1] != '\n');
203
204                 /* The winners. */
205                 if (strstarts(line, "if") && len == 2) {
206                         *why = cast_const(char *, "starts with if");
207                         return true;
208                 }
209                 if (strstarts(line, "for") && len == 3) {
210                         *why = cast_const(char *, "starts with for");
211                         return true;
212                 }
213                 if (strstarts(line, "while") && len == 5) {
214                         *why = cast_const(char *, "starts with while");
215                         return true;
216                 }
217                 if (strstarts(line, "do") && len == 2) {
218                         *why = cast_const(char *, "starts with do");
219                         return true;
220                 }
221
222                 /* The losers. */
223                 if (strstarts(line, "#include")) {
224                         *why = cast_const(char *, "starts with #include");
225                         return false;
226                 }
227
228                 if (last_ended && strchr(line, '(')) {
229                         if (strstarts(line, "static")) {
230                                 *why = cast_const(char *,
231                                                   "starts with static"
232                                                   " and contains (");
233                                 return false;
234                         }
235                         if (strends(line, ")")) {
236                                 *why = cast_const(char *,
237                                                   "contains ( and ends with )");
238                                 return false;
239                         }
240                 }
241
242                 /* Previously prepended. */
243                 if (strstr(line, "didn't seem to belong inside a function")) {
244                         *why = cast_const(char *, "Comment said so");
245                         return false;
246                 }
247
248                 /* Single identifier then operator == inside function. */
249                 if (last_ended && len
250                     && cispunct(line[len+strspn(line+len, " ")])) {
251                         *why = cast_const(char *, "starts with identifier"
252                                           " then punctuation");
253                         return true;
254                 }
255
256                 last_ended = (strends(line, "}")
257                               || strends(line, ";")
258                               || strends(line, "*/")
259                               || streq(line, "..."));
260         }
261
262         /* No idea... Say yes? */
263         *why = cast_const(char *, "gave no clues");
264         return true;
265 }
266
267 /* Examples will often build on prior ones.  Try combining them. */
268 static char **combine(const void *ctx, char **lines, char **prev)
269 {
270         unsigned int i, lines_total, prev_total, count;
271         char **ret;
272         const char *reasoning;
273         char *why = NULL;
274
275         if (!prev)
276                 return NULL;
277
278         /* If it looks internal, put prev at start. */
279         if (looks_internal(lines, &why)) {
280                 count = 0;
281                 reasoning = "seemed to belong inside a function";
282         } else {
283                 /* Try inserting in first elided position */
284                 for (count = 0; lines[count]; count++) {
285                         if (strcmp(lines[count], "...") == 0)
286                                 break;
287                 }
288                 if (!lines[count]) {
289                         /* Try at start anyway? */
290                         count = 0;
291                         reasoning = "didn't seem to belong inside"
292                                 " a function, so we prepended the previous"
293                                 " example";
294                 } else {
295                         reasoning = "didn't seem to belong inside"
296                                 " a function, so we put the previous example"
297                                 " at the first ...";
298
299                         count++;
300                 }
301         }
302
303         for (i = 0; lines[i]; i++);
304         lines_total = i;
305
306         for (i = 0; prev[i]; i++);
307         prev_total = i;
308
309         ret = talloc_array(ctx, char *, 1 +lines_total + prev_total + 1);
310         ret[0] = talloc_asprintf(ret, "/* The example %s, thus %s */",
311                                  why, reasoning);
312         memcpy(ret+1, lines, count * sizeof(ret[0]));
313         memcpy(ret+1 + count, prev, prev_total * sizeof(ret[0]));
314         memcpy(ret+1 + count + prev_total, lines + count,
315                (lines_total - count + 1) * sizeof(ret[0]));
316         return ret;
317 }
318
319 /* Only handles very simple comments. */
320 static char *strip_comment(const void *ctx, const char *orig_line)
321 {
322         char *p, *ret = talloc_strdup(ctx, orig_line);
323
324         p = strstr(ret, "/*");
325         if (!p)
326                 p = strstr(ret, "//");
327         if (p)
328                 *p = '\0';
329         return ret;
330 }
331
332 static char *mangle(struct manifest *m, char **lines)
333 {
334         char *ret, *use_funcs = NULL, *why;
335         bool in_function = false, fake_function = false, has_main = false;
336         unsigned int i;
337
338         ret = talloc_asprintf(m, 
339                               "/* Include header from module. */\n"
340                               "#include <ccan/%s/%s.h>\n"
341                               "/* Prepend a heap of headers. */\n"
342                               "#include <assert.h>\n"
343                               "#include <err.h>\n"
344                               "#include <errno.h>\n"
345                               "#include <fcntl.h>\n"
346                               "#include <limits.h>\n"
347                               "#include <stdbool.h>\n"
348                               "#include <stdint.h>\n"
349                               "#include <stdio.h>\n"
350                               "#include <stdlib.h>\n"
351                               "#include <string.h>\n"
352                               "#include <sys/stat.h>\n"
353                               "#include <sys/types.h>\n"
354                               "#include <unistd.h>\n",
355                               m->basename, m->basename);
356
357         ret = talloc_asprintf_append(ret, "/* Useful dummy functions. */\n"
358                                      "extern int somefunc(void);\n"
359                                      "int somefunc(void) { return 0; }\n"
360                                      "extern char somestring[];\n"
361                                      "char somestring[] = \"hello world\";\n");
362
363         if (looks_internal(lines, &why)) {
364                 /* Wrap it all in main(). */
365                 ret = start_main(ret, why);
366                 fake_function = true;
367                 in_function = true;
368                 has_main = true;
369         } else
370                 ret = talloc_asprintf_append(ret,
371                              "/* The example %s, so didn't wrap in main() */\n",
372                                      why);
373
374         /* Primitive, very primitive. */
375         for (i = 0; lines[i]; i++) {
376                 char *line = strip_comment(ret, lines[i]);
377
378                 /* } at start of line ends a function. */
379                 if (in_function) {
380                         if (line[0] == '}')
381                                 in_function = false;
382                 } else {
383                         /* Character at start of line, with ( and no ;
384                          * == function start.  Ignore comments. */
385                         if (!cisspace(line[0])
386                             && strchr(line, '(')
387                             && !strchr(line, ';')
388                             && !strstr(line, "//")) {
389                                 in_function = true;
390                                 if (strncmp(line, "int main", 8) == 0)
391                                         has_main = true;
392                                 if (strncmp(line, "static", 6) == 0) {
393                                         use_funcs = add_func(use_funcs,
394                                                              line);
395                                 }
396                         }
397                 }
398                 /* ... means elided code. */
399                 if (strcmp(line, "...") == 0) {
400                         if (!in_function && !has_main
401                             && looks_internal(lines + i + 1, &why)) {
402                                 /* This implies we start a function here. */
403                                 ret = start_main(ret, why);
404                                 has_main = true;
405                                 fake_function = true;
406                                 in_function = true;
407                         }
408                         ret = talloc_asprintf_append(ret,
409                                                      "/* ... removed */\n");
410                         continue;
411                 }
412                 ret = talloc_asprintf_append(ret, "%s\n", lines[i]);
413         }
414
415         if (!has_main) {
416                 ret = talloc_asprintf_append(ret,
417                              "/* Need a main to link successfully. */\n"
418                              "int main(void)\n{\n");
419                 fake_function = true;
420         }
421
422         if (use_funcs) {
423                 ret = talloc_asprintf_append(ret,
424                                              "/* Get rid of unused warnings"
425                                              " by printing addresses of"
426                                              " static funcs. */\n");
427                 if (!fake_function) {
428                         ret = talloc_asprintf_append(ret,
429                                                      "int use_funcs(void);\n"
430                                                      "int use_funcs(void) {\n");
431                         fake_function = true;
432                 }
433                 ret = talloc_asprintf_append(ret, "     %s\n", use_funcs);
434         }
435
436         if (fake_function)
437                 ret = talloc_asprintf_append(ret, "return 0;\n"
438                                              "}\n");
439         return ret;
440 }
441
442 static struct ccan_file *mangle_example(struct manifest *m,
443                                         struct ccan_file *example,
444                                         char **lines,
445                                         bool keep)
446 {
447         char *name, *contents;
448         int fd;
449         struct ccan_file *f;
450
451         name = maybe_temp_file(example, ".c", keep, 
452                                talloc_asprintf(m, "%s/mangled-%s",
453                                                m->dir, example->name));
454         f = new_ccan_file(example,
455                           talloc_dirname(example, name),
456                           talloc_basename(example, name));
457         talloc_steal(f, name);
458
459         fd = open(f->fullname, O_WRONLY | O_CREAT | O_EXCL, 0600);
460         if (fd < 0)
461                 return NULL;
462
463         contents = mangle(m, lines);
464         if (write(fd, contents, strlen(contents)) != strlen(contents)) {
465                 close(fd);
466                 return NULL;
467         }
468         close(fd);
469         f->contents = talloc_steal(f, contents);
470         list_add(&m->mangled_examples, &f->list);
471         return f;
472 }
473
474 /* If an example has expected output, it's complete and should not be
475  * included in future examples. */
476 static bool has_expected_output(char **lines)
477 {
478         unsigned int i;
479
480         for (i = 0; lines[i]; i++) {
481                 char *p = lines[i] + strspn(lines[i], " \t");
482                 if (!strstarts(p, "//"))
483                         continue;
484                 p += strspn(p, "/ ");
485                 if (strncasecmp(p, "given", strlen("given")) == 0)
486                         return true;
487         }
488         return false;
489 }
490
491 static unsigned int try_compiling(struct manifest *m,
492                                   struct ccan_file *i,
493                                   char **prev,
494                                   bool keep,
495                                   struct ccan_file *mangled[3],
496                                   bool res[3],
497                                   char *err[3],
498                                   char **lines[3])
499 {
500         unsigned int num;
501
502         /* Try standalone. */
503         mangled[0] = i;
504         res[0] = compile(i, m, mangled[0], keep, &err[0]);
505         lines[0] = get_ccan_file_lines(i);
506         if (res[0] && streq(err[0], ""))
507                 return 1;
508
509         if (prev) {
510                 lines[1] = combine(i, get_ccan_file_lines(i), prev);
511
512                 mangled[1] = mangle_example(m, i, lines[1], keep);
513                 res[1] = compile(i, m, mangled[1], keep, &err[1]);
514                 if (res[1] && streq(err[1], "")) {
515                         return 2;
516                 }
517                 num = 2;
518         } else
519                 num = 1;
520
521         /* Try standalone. */
522         lines[num] = get_ccan_file_lines(i);
523         mangled[num] = mangle_example(m, i, lines[num], keep);
524         res[num] = compile(i, m, mangled[num], keep, &err[num]);
525
526         return num+1;
527 }
528
529 static void build_examples(struct manifest *m, bool keep,
530                            unsigned int *timeleft, struct score *score)
531 {
532         struct ccan_file *i;
533         char **prev = NULL;
534         bool warnings = false;
535
536         score->total = 0;
537         score->pass = true;
538
539         list_for_each(&m->examples, i, list) {
540                 char *err[3];
541                 struct ccan_file *file[3] = { NULL, NULL, NULL };
542                 bool res[3];
543                 unsigned num, j;
544                 char **lines[3];
545                 const char *error;
546
547                 score->total++;
548
549                 /* Simplify our dumb parsing. */
550                 strip_leading_whitespace(get_ccan_file_lines(i));
551
552                 num = try_compiling(m, i, prev, keep, file, res, err, lines);
553
554                 /* First look for a compile without any warnings. */
555                 for (j = 0; j < num; j++) {
556                         if (res[j] && streq(err[j], "")) {
557                                 if (!has_expected_output(lines[j]))
558                                         prev = lines[j];
559                                 score->score++;
560                                 goto next;
561                         }
562                 }
563
564                 /* Now accept anything which succeeded. */
565                 for (j = 0; j < num; j++) {
566                         if (res[j]) {
567                                 if (!has_expected_output(lines[j]))
568                                         prev = lines[j];
569                                 score->score++;
570                                 warnings = true;
571                                 score_file_error(score, file[j], 0,
572                                                  "Compiling extracted example"
573                                                  " gave warnings:\n"
574                                                  "Example:\n"
575                                                  "%s\n"
576                                                  "Compiler:\n"
577                                                  "%s",
578                                                  get_ccan_file_contents(file[j]),
579                                                  err[j]);
580                                 goto next;
581                         }
582                 }
583
584                 score->pass = false;
585                 if (!verbose) {
586                         if (num == 3)
587                                 error = "Compiling standalone, adding headers, "
588                                         "and including previous "
589                                         "example all failed";
590                         else
591                                 error = "Standalone compile and"
592                                         " adding headers both failed";
593                 } else {
594                         if (num == 3) {
595                                 error = talloc_asprintf(score,
596                                       "Standalone example:\n"
597                                       "%s\n"
598                                       "Errors: %s\n\n"
599                                       "Combining with previous example:\n"
600                                       "%s\n"
601                                       "Errors: %s\n\n"
602                                       "Adding headers, wrappers:\n"
603                                       "%s\n"
604                                       "Errors: %s\n\n",
605                                       get_ccan_file_contents(file[0]),
606                                       err[0],
607                                       get_ccan_file_contents(file[1]),
608                                       err[1],
609                                       get_ccan_file_contents(file[2]),
610                                       err[2]);
611                         } else {
612                                 error = talloc_asprintf(score,
613                                       "Standalone example:\n"
614                                       "%s\n"
615                                       "Errors: %s\n\n"
616                                       "Adding headers, wrappers:\n"
617                                       "%s\n"
618                                       "Errors: %s\n\n",
619                                       get_ccan_file_contents(file[0]),
620                                       err[0],
621                                       get_ccan_file_contents(file[1]),
622                                       err[1]);
623                         }
624                 }
625                 score_file_error(score, i, 0, "%s", error);
626                 /* This didn't work, so not a candidate for combining. */
627                 prev = NULL;
628
629         next:
630                 ;
631         }
632
633         /* An extra point if they all compiled without warnings. */
634         if (!list_empty(&m->examples)) {
635                 score->total++;
636                 if (!warnings)
637                         score->score++;
638         }
639 }
640
641 struct ccanlint examples_compile = {
642         .key = "examples_compile",
643         .name = "Module examples compile",
644         .check = build_examples,
645         .can_run = can_run,
646         .needs = "examples_exist module_builds"
647 };
648
649 REGISTER_TEST(examples_compile);