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