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