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