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