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