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