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