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