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