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