]> git.ozlabs.org Git - ccan/blob - tools/ccanlint/ccanlint.c
ccanlint: remove wart from info options.
[ccan] / tools / ccanlint / ccanlint.c
1 /*
2  * ccanlint: assorted checks and advice for a ccan package
3  * Copyright (C) 2008 Rusty Russell, Idris Soule
4  * Copyright (C) 2010 Rusty Russell, Idris Soule
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the Free
8  * Software Foundation; either version 2 of the License, or (at your option)
9  * any later version.
10  *
11  *   This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
14  * more details.
15  *
16  * You should have received a copy of the GNU General Public License along with
17  * this program; if not, write to the Free Software Foundation, Inc., 51
18  * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19  */
20 #include "ccanlint.h"
21 #include "../tools.h"
22 #include <unistd.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <err.h>
27 #include <ctype.h>
28 #include <ccan/btree/btree.h>
29 #include <ccan/str/str.h>
30 #include <ccan/str_talloc/str_talloc.h>
31 #include <ccan/talloc/talloc.h>
32 #include <ccan/opt/opt.h>
33 #include <ccan/foreach/foreach.h>
34 #include <ccan/grab_file/grab_file.h>
35 #include <ccan/cast/cast.h>
36 #include <ccan/tlist/tlist.h>
37
38 /* Defines struct tlist_ccanlint. */
39 TLIST_TYPE(ccanlint, struct ccanlint);
40
41 int verbose = 0;
42 static struct tlist_ccanlint tests = TLIST_INIT(tests);
43 bool safe_mode = false;
44 static bool targeting = false;
45 static struct btree *cmdline_exclude;
46 static struct btree *info_exclude;
47 static unsigned int timeout;
48
49 /* These are overridden at runtime if we can find config.h */
50 const char *compiler = NULL;
51 const char *cflags = NULL;
52
53 const char *config_header;
54
55 #if 0
56 static void indent_print(const char *string)
57 {
58         while (*string) {
59                 unsigned int line = strcspn(string, "\n");
60                 printf("\t%.*s", line, string);
61                 if (string[line] == '\n') {
62                         printf("\n");
63                         line++;
64                 }
65                 string += line;
66         }
67 }
68 #endif
69
70 bool ask(const char *question)
71 {
72         char reply[80];
73
74         printf("%s ", question);
75         fflush(stdout);
76
77         return fgets(reply, sizeof(reply), stdin) != NULL
78                 && toupper(reply[0]) == 'Y';
79 }
80
81 static const char *should_skip(struct manifest *m, struct ccanlint *i)
82 {
83         if (btree_lookup(cmdline_exclude, i->key))
84                 return "excluded on command line";
85
86         if (btree_lookup(info_exclude, i->key))
87                 return "excluded in _info file";
88         
89         if (i->skip)
90                 return i->skip;
91
92         if (i->skip_fail)
93                 return "dependency failed";
94
95         if (i->can_run)
96                 return i->can_run(m);
97         return NULL;
98 }
99
100 static bool run_test(struct ccanlint *i,
101                      bool quiet,
102                      unsigned int *running_score,
103                      unsigned int *running_total,
104                      struct manifest *m,
105                      const char *prefix)
106 {
107         unsigned int timeleft;
108         const struct dependent *d;
109         const char *skip;
110         struct score *score;
111
112         //one less test to run through
113         list_for_each(&i->dependencies, d, node)
114                 d->dependent->num_depends--;
115
116         score = talloc(m, struct score);
117         list_head_init(&score->per_file_errors);
118         score->error = NULL;
119         score->pass = false;
120         score->score = 0;
121         score->total = 1;
122
123         skip = should_skip(m, i);
124
125         if (skip) {
126         skip:
127                 if (verbose && !streq(skip, "not relevant to target"))
128                         printf("%s%s: skipped (%s)\n", prefix, i->name, skip);
129
130                 /* If we're skipping this because a prereq failed, we fail:
131                  * count it as a score of 1. */
132                 if (i->skip_fail)
133                         (*running_total)++;
134                         
135                 list_del(&i->list);
136                 list_for_each(&i->dependencies, d, node) {
137                         if (d->dependent->skip)
138                                 continue;
139                         d->dependent->skip = "dependency was skipped";
140                         d->dependent->skip_fail = i->skip_fail;
141                 }
142                 return i->skip_fail ? false : true;
143         }
144
145         timeleft = timeout ? timeout : default_timeout_ms;
146         i->check(m, i->keep_results, &timeleft, score);
147         if (timeout && timeleft == 0) {
148                 skip = "timeout";
149                 goto skip;
150         }
151
152         assert(score->score <= score->total);
153         if ((!score->pass && !quiet)
154             || (score->score < score->total && verbose)
155             || verbose > 1) {
156                 printf("%s%s (%s): %s",
157                        prefix, i->name, i->key, score->pass ? "PASS" : "FAIL");
158                 if (score->total > 1)
159                         printf(" (+%u/%u)", score->score, score->total);
160                 printf("\n");
161         }
162
163         if ((!quiet && !score->pass) || verbose) {
164                 if (score->error) {
165                         printf("%s%s", score->error,
166                                strends(score->error, "\n") ? "" : "\n");
167                 }
168         }
169         if (!quiet && score->score < score->total && i->handle)
170                 i->handle(m, score);
171
172         *running_score += score->score;
173         *running_total += score->total;
174
175         list_del(&i->list);
176
177         if (!score->pass) {
178                 /* Skip any tests which depend on this one. */
179                 list_for_each(&i->dependencies, d, node) {
180                         if (d->dependent->skip)
181                                 continue;
182                         d->dependent->skip = "dependency failed";
183                         d->dependent->skip_fail = true;
184                 }
185         }
186         return score->pass;
187 }
188
189 static void register_test(struct ccanlint *test)
190 {
191         tlist_add(&tests, test, list);
192         test->options = talloc_array(NULL, char *, 1);
193         test->options[0] = NULL;
194         test->skip = NULL;
195         test->skip_fail = false;
196 }
197
198 /**
199  * get_next_test - retrieves the next test to be processed
200  **/
201 static inline struct ccanlint *get_next_test(void)
202 {
203         struct ccanlint *i;
204
205         if (tlist_empty(&tests))
206                 return NULL;
207
208         tlist_for_each(&tests, i, list) {
209                 if (i->num_depends == 0)
210                         return i;
211         }
212         errx(1, "Can't make process; test dependency cycle");
213 }
214
215 static struct ccanlint *find_test(const char *key)
216 {
217         struct ccanlint *i;
218
219         tlist_for_each(&tests, i, list)
220                 if (streq(i->key, key))
221                         return i;
222
223         return NULL;
224 }
225
226 bool is_excluded(const char *name)
227 {
228         return btree_lookup(cmdline_exclude, name) != NULL
229                 || btree_lookup(info_exclude, name) != NULL
230                 || find_test(name)->skip != NULL;
231 }
232
233 #undef REGISTER_TEST
234 #define REGISTER_TEST(name, ...) extern struct ccanlint name
235 #include "generated-testlist"
236
237 static void init_tests(void)
238 {
239         struct ccanlint *c;
240         struct btree *keys, *names;
241
242         tlist_init(&tests);
243
244 #undef REGISTER_TEST
245 #define REGISTER_TEST(name) register_test(&name)
246 #include "generated-testlist"
247
248         /* Initialize dependency lists. */
249         tlist_for_each(&tests, c, list) {
250                 list_head_init(&c->dependencies);
251                 c->num_depends = 0;
252         }
253
254         /* Resolve dependencies. */
255         tlist_for_each(&tests, c, list) {
256                 char **deps = strsplit(NULL, c->needs, " ");
257                 unsigned int i;
258
259                 for (i = 0; deps[i]; i++) {
260                         struct ccanlint *dep;
261                         struct dependent *dchild;
262
263                         dep = find_test(deps[i]);
264                         if (!dep)
265                                 errx(1, "BUG: unknown dep '%s' for %s",
266                                      deps[i], c->key);
267                         dchild = talloc(NULL, struct dependent);
268                         dchild->dependent = c;
269                         list_add_tail(&dep->dependencies, &dchild->node);
270                         c->num_depends++;
271                 }
272                 talloc_free(deps);
273         }
274
275         /* Self-consistency check: make sure no two tests
276            have the same key or name. */
277         keys = btree_new(btree_strcmp);
278         names = btree_new(btree_strcmp);
279         tlist_for_each(&tests, c, list) {
280                 if (!btree_insert(keys, c->key))
281                         errx(1, "BUG: Duplicate test key '%s'",
282                              c->key);
283                 if (!btree_insert(names, c->name))
284                         errx(1, "BUG: Duplicate test name '%s'",
285                              c->name);
286         }
287
288         btree_delete(keys);
289         btree_delete(names);
290 }
291
292 static void print_test_depends(void)
293 {
294         struct ccanlint *c;
295         printf("Tests:\n");
296
297         tlist_for_each(&tests, c, list) {
298                 if (!list_empty(&c->dependencies)) {
299                         const struct dependent *d;
300                         printf("These depend on %s:\n", c->key);
301                         list_for_each(&c->dependencies, d, node)
302                                 printf("\t%s\n", d->dependent->key);
303                 }
304         }
305 }
306
307 static int show_tmpdir(const char *dir)
308 {
309         printf("You can find ccanlint working files in '%s'\n", dir);
310         return 0;
311 }
312
313 static char *keep_test(const char *testname, void *unused)
314 {
315         struct ccanlint *i;
316
317         init_tests();
318         if (streq(testname, "all")) {
319                 tlist_for_each(&tests, i, list)
320                         i->keep_results = true;
321         } else {
322                 i = find_test(testname);
323                 if (!i)
324                         errx(1, "No test %s to --keep", testname);
325                 i->keep_results = true;
326         }
327
328         /* Don't automatically destroy temporary dir. */
329         talloc_set_destructor(temp_dir(NULL), show_tmpdir);
330         return NULL;
331 }
332
333 static char *skip_test(const char *testname, void *unused)
334 {
335         btree_insert(cmdline_exclude, testname);
336         return NULL;
337 }
338
339 static char *list_tests(void *arg)
340 {
341         struct ccanlint *i;
342
343         init_tests();
344
345         printf("Tests:\n");
346         /* This makes them print in topological order. */
347         while ((i = get_next_test()) != NULL) {
348                 const struct dependent *d;
349                 printf("   %-25s %s\n", i->key, i->name);
350                 list_del(&i->list);
351                 list_for_each(&i->dependencies, d, node)
352                         d->dependent->num_depends--;
353         }
354         exit(0);
355 }
356
357 static void test_dgraph_vertices(const char *style)
358 {
359         const struct ccanlint *i;
360
361         tlist_for_each(&tests, i, list) {
362                 /*
363                  * todo: escape labels in case ccanlint test keys have
364                  *       characters interpreted as GraphViz syntax.
365                  */
366                 printf("\t\"%p\" [label=\"%s\"%s]\n", i, i->key, style);
367         }
368 }
369
370 static void test_dgraph_edges(void)
371 {
372         const struct ccanlint *i;
373         const struct dependent *d;
374
375         tlist_for_each(&tests, i, list)
376                 list_for_each(&i->dependencies, d, node)
377                         printf("\t\"%p\" -> \"%p\"\n", d->dependent, i);
378 }
379
380 static char *test_dependency_graph(void *arg)
381 {
382         init_tests();
383         puts("digraph G {");
384
385         test_dgraph_vertices("");
386         test_dgraph_edges();
387
388         puts("}");
389
390         exit(0);
391 }
392
393 /* Remove empty lines. */
394 static char **collapse(char **lines, unsigned int *nump)
395 {
396         unsigned int i, j;
397         for (i = j = 0; lines[i]; i++) {
398                 if (lines[i][0])
399                         lines[j++] = lines[i];
400         }
401         lines[j] = NULL;
402         if (nump)
403                 *nump = j;
404         return lines;
405 }
406
407
408 static void add_options(struct ccanlint *test, char **options,
409                         unsigned int num_options)
410 {
411         unsigned int num;
412
413         if (!test->options)
414                 num = 0;
415         else
416                 /* -1, because last one is NULL. */
417                 num = talloc_array_length(test->options) - 1;
418
419         test->options = talloc_realloc(NULL, test->options,
420                                        char *,
421                                        num + num_options + 1);
422         memcpy(&test->options[num], options, (num_options + 1)*sizeof(char *));
423 }
424
425 void add_info_options(struct ccan_file *info)
426 {
427         struct doc_section *d;
428         unsigned int i;
429         struct ccanlint *test;
430
431         list_for_each(get_ccan_file_docs(info), d, list) {
432                 if (!streq(d->type, "ccanlint"))
433                         continue;
434
435                 for (i = 0; i < d->num_lines; i++) {
436                         unsigned int num_words;
437                         char **words = collapse(strsplit(d, d->lines[i], " \t"),
438                                                 &num_words);
439                         if (num_words == 0)
440                                 continue;
441
442                         if (strncmp(words[0], "//", 2) == 0)
443                                 continue;
444
445                         test = find_test(words[0]);
446                         if (!test) {
447                                 warnx("%s: unknown ccanlint test '%s'",
448                                       info->fullname, words[0]);
449                                 continue;
450                         }
451
452                         if (!words[1]) {
453                                 warnx("%s: no argument to test '%s'",
454                                       info->fullname, words[0]);
455                                 continue;
456                         }
457
458                         /* Known failure? */
459                         if (strcasecmp(words[1], "FAIL") == 0) {
460                                 if (!targeting)
461                                         btree_insert(info_exclude, words[0]);
462                         } else {
463                                 if (!test->takes_options)
464                                         warnx("%s: %s doesn't take options",
465                                               info->fullname, words[0]);
466                                 add_options(test, words+1, num_words-1);
467                         }
468                 }
469         }
470 }
471
472 /* If options are of form "filename:<option>" they only apply to that file */
473 char **per_file_options(const struct ccanlint *test, struct ccan_file *f)
474 {
475         char **ret;
476         unsigned int i, j = 0;
477
478         /* Fast path. */
479         if (!test->options[0])
480                 return test->options;
481
482         ret = talloc_array(f, char *, talloc_array_length(test->options));
483         for (i = 0; test->options[i]; i++) {
484                 char *optname;
485
486                 if (!test->options[i] || !strchr(test->options[i], ':')) {
487                         optname = test->options[i];
488                 } else if (strstarts(test->options[i], f->name)
489                            && test->options[i][strlen(f->name)] == ':') {
490                         optname = test->options[i] + strlen(f->name) + 1;
491                 } else
492                         continue;
493
494                 /* FAIL overrides anything else. */
495                 if (streq(optname, "FAIL")) {
496                         ret = talloc_array(f, char *, 2);
497                         ret[0] = (char *)"FAIL";
498                         ret[1] = NULL;
499                         return ret;
500                 }
501                 ret[j++] = optname;
502         }
503         ret[j] = NULL;
504
505         /* Shrink it to size so talloc_array_length() works as expected. */
506         return talloc_realloc(NULL, ret, char *, j + 1);
507 }
508
509 static bool depends_on(struct ccanlint *i, struct ccanlint *target)
510 {
511         const struct dependent *d;
512
513         if (i == target)
514                 return true;
515
516         list_for_each(&i->dependencies, d, node) {
517                 if (depends_on(d->dependent, target))
518                         return true;
519         }
520         return false;
521 }
522
523 /* O(N^2), who cares? */
524 static void skip_unrelated_tests(struct ccanlint *target)
525 {
526         struct ccanlint *i;
527
528         tlist_for_each(&tests, i, list)
529                 if (!depends_on(i, target))
530                         i->skip = "not relevant to target";
531 }
532
533 static char *demangle_string(char *string)
534 {
535         unsigned int i;
536         const char mapfrom[] = "abfnrtv";
537         const char mapto[] = "\a\b\f\n\r\t\v";
538
539         if (!strchr(string, '"'))
540                 return NULL;
541         string = strchr(string, '"') + 1;
542         if (!strrchr(string, '"'))
543                 return NULL;
544         *strrchr(string, '"') = '\0';
545
546         for (i = 0; i < strlen(string); i++) {
547                 if (string[i] == '\\') {
548                         char repl;
549                         unsigned len = 0;
550                         const char *p = strchr(mapfrom, string[i+1]);
551                         if (p) {
552                                 repl = mapto[p - mapfrom];
553                                 len = 1;
554                         } else if (strlen(string+i+1) >= 3) {
555                                 if (string[i+1] == 'x') {
556                                         repl = (string[i+2]-'0')*16
557                                                 + string[i+3]-'0';
558                                         len = 3;
559                                 } else if (cisdigit(string[i+1])) {
560                                         repl = (string[i+2]-'0')*8*8
561                                                 + (string[i+3]-'0')*8
562                                                 + (string[i+4]-'0');
563                                         len = 3;
564                                 }
565                         }
566                         if (len == 0) {
567                                 repl = string[i+1];
568                                 len = 1;
569                         }
570
571                         string[i] = repl;
572                         memmove(string + i + 1, string + i + len + 1,
573                                 strlen(string + i + len + 1) + 1);
574                 }
575         }
576
577         return string;
578 }
579
580
581 static void read_config_header(void)
582 {
583         char *fname = talloc_asprintf(NULL, "%s/config.h", ccan_dir);
584         char **lines;
585         unsigned int i;
586
587         config_header = grab_file(NULL, fname, NULL);
588         if (!config_header) {
589                 talloc_free(fname);
590                 return;
591         }
592
593         lines = strsplit(config_header, config_header, "\n");
594         for (i = 0; i < talloc_array_length(lines) - 1; i++) {
595                 char *sym;
596                 const char **line = (const char **)&lines[i];
597
598                 if (!get_token(line, "#"))
599                         continue;
600                 if (!get_token(line, "define"))
601                         continue;
602                 sym = get_symbol_token(lines, line);
603                 if (streq(sym, "CCAN_COMPILER") && !compiler) {
604                         compiler = demangle_string(lines[i]);
605                         if (!compiler)
606                                 errx(1, "%s:%u:could not parse CCAN_COMPILER",
607                                      fname, i+1);
608                         if (verbose > 1)
609                                 printf("%s: compiler set to '%s'\n",
610                                        fname, compiler);
611                 } else if (streq(sym, "CCAN_CFLAGS") && !cflags) {
612                         cflags = demangle_string(lines[i]);
613                         if (!cflags)
614                                 errx(1, "%s:%u:could not parse CCAN_CFLAGS",
615                                      fname, i+1);
616                         if (verbose > 1)
617                                 printf("%s: compiler flags set to '%s'\n",
618                                        fname, cflags);
619                 }
620         }
621         if (!compiler)
622                 compiler = CCAN_COMPILER;
623         if (!cflags)
624                 compiler = CCAN_CFLAGS;
625 }
626
627 static char *opt_set_const_charp(const char *arg, const char **p)
628 {
629         return opt_set_charp(arg, cast_const2(char **, p));
630 }
631
632 int main(int argc, char *argv[])
633 {
634         bool summary = false, pass = true;
635         unsigned int i;
636         struct manifest *m;
637         struct ccanlint *t;
638         const char *prefix = "";
639         char *dir = talloc_getcwd(NULL), *base_dir = dir, *target = NULL,
640                 *testlink;
641         
642         cmdline_exclude = btree_new(btree_strcmp);
643         info_exclude = btree_new(btree_strcmp);
644
645         opt_register_early_noarg("--verbose|-v", opt_inc_intval, &verbose,
646                                  "verbose mode (up to -vvvv)");
647         opt_register_noarg("-n|--safe-mode", opt_set_bool, &safe_mode,
648                          "do not compile anything");
649         opt_register_noarg("-l|--list-tests", list_tests, NULL,
650                          "list tests ccanlint performs (and exit)");
651         opt_register_noarg("--test-dep-graph", test_dependency_graph, NULL,
652                          "print dependency graph of tests in Graphviz .dot format");
653         opt_register_arg("-k|--keep <testname>", keep_test, NULL, NULL,
654                          "keep results of <testname>"
655                          " (can be used multiple times, or 'all')");
656         opt_register_noarg("--summary|-s", opt_set_bool, &summary,
657                            "simply give one line summary");
658         opt_register_arg("-x|--exclude <testname>", skip_test, NULL, NULL,
659                          "exclude <testname> (can be used multiple times)");
660         opt_register_arg("-t|--timeout <milleseconds>", opt_set_uintval,
661                          NULL, &timeout,
662                          "ignore (terminate) tests that are slower than this");
663         opt_register_arg("--target <testname>", opt_set_charp,
664                          NULL, &target,
665                          "only run one test (and its prerequisites)");
666         opt_register_arg("--compiler <compiler>", opt_set_const_charp,
667                          NULL, &compiler, "set the compiler");
668         opt_register_arg("--cflags <flags>", opt_set_const_charp,
669                          NULL, &cflags, "set the compiler flags");
670         opt_register_noarg("-?|-h|--help", opt_usage_and_exit,
671                            "\nA program for checking and guiding development"
672                            " of CCAN modules.",
673                            "This usage message");
674
675         /* Do verbose before anything else... */
676         opt_early_parse(argc, argv, opt_log_stderr_exit);
677
678         /* We move into temporary directory, so gcov dumps its files there. */
679         if (chdir(temp_dir(talloc_autofree_context())) != 0)
680                 err(1, "Error changing to %s temporary dir", temp_dir(NULL));
681
682         opt_parse(&argc, argv, opt_log_stderr_exit);
683
684         if (verbose >= 3) {
685                 compile_verbose = true;
686                 print_test_depends();
687         }
688         if (verbose >= 4)
689                 tools_verbose = true;
690
691         /* This links back to the module's test dir. */
692         testlink = talloc_asprintf(NULL, "%s/test", temp_dir(NULL));
693
694         /* Defaults to pwd. */
695         if (argc == 1) {
696                 i = 1;
697                 goto got_dir;
698         }
699
700         for (i = 1; i < argc; i++) {
701                 unsigned int score, total_score;
702
703                 dir = argv[i];
704
705                 if (dir[0] != '/')
706                         dir = talloc_asprintf_append(NULL, "%s/%s",
707                                                      base_dir, dir);
708                 while (strends(dir, "/"))
709                         dir[strlen(dir)-1] = '\0';
710
711         got_dir:
712                 if (dir != base_dir)
713                         prefix = talloc_append_string(talloc_basename(NULL,dir),
714                                                       ": ");
715
716                 init_tests();
717
718                 if (target) {
719                         struct ccanlint *test;
720
721                         test = find_test(target);
722                         if (!test)
723                                 errx(1, "Unknown test to run '%s'", target);
724                         skip_unrelated_tests(test);
725                 }
726
727                 m = get_manifest(talloc_autofree_context(), dir);
728
729                 /* FIXME: This has to come after we've got manifest. */
730                 if (i == 1)
731                         read_config_header();
732
733                 /* Create a symlink from temp dir back to src dir's
734                  * test directory. */
735                 unlink(testlink);
736                 if (symlink(talloc_asprintf(m, "%s/test", dir), testlink) != 0)
737                         err(1, "Creating test symlink in %s", temp_dir(NULL));
738
739                 score = total_score = 0;
740                 while ((t = get_next_test()) != NULL) {
741                         if (!run_test(t, summary, &score, &total_score, m,
742                                       prefix)) {
743                                 pass = false;
744                                 if (t->compulsory) {
745                                         warnx("%s%s failed", prefix, t->name);
746                                         printf("%sTotal score: 0/%u\n",
747                                                prefix, total_score);
748                                         goto next;
749                                 }
750                         }
751                 }
752
753                 printf("%sTotal score: %u/%u\n", prefix, score, total_score);
754         next: ;
755         }
756         return pass ? 0 : 1;
757 }