]> git.ozlabs.org Git - ccan/blob - tools/ccanlint/ccanlint.c
jmap: fix jmap_free, tests.
[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 }
190
191 /**
192  * get_next_test - retrieves the next test to be processed
193  **/
194 static inline struct ccanlint *get_next_test(struct list_head *test)
195 {
196         struct ccanlint *i;
197
198         if (list_empty(test))
199                 return NULL;
200
201         list_for_each(test, i, list) {
202                 if (i->num_depends == 0)
203                         return i;
204         }
205         errx(1, "Can't make process; test dependency cycle");
206 }
207
208 static struct ccanlint *find_test(const char *key)
209 {
210         struct ccanlint *i;
211
212         list_for_each(&compulsory_tests, i, list)
213                 if (streq(i->key, key))
214                         return i;
215
216         list_for_each(&normal_tests, i, list)
217                 if (streq(i->key, key))
218                         return i;
219
220         return NULL;
221 }
222
223 #undef REGISTER_TEST
224 #define REGISTER_TEST(name, ...) extern struct ccanlint name
225 #include "generated-normal-tests"
226 #include "generated-compulsory-tests"
227
228 static void init_tests(void)
229 {
230         struct ccanlint *c;
231         struct btree *keys, *names;
232         struct list_head *list;
233
234 #undef REGISTER_TEST
235 #define REGISTER_TEST(name) register_test(&normal_tests, &name)
236 #include "generated-normal-tests"
237 #undef REGISTER_TEST
238 #define REGISTER_TEST(name) register_test(&compulsory_tests, &name)
239 #include "generated-compulsory-tests"
240
241         /* Initialize dependency lists. */
242         foreach_ptr(list, &compulsory_tests, &normal_tests) {
243                 list_for_each(list, c, list) {
244                         list_head_init(&c->dependencies);
245                 }
246         }
247
248         /* Resolve dependencies. */
249         foreach_ptr(list, &compulsory_tests, &normal_tests) {
250                 list_for_each(list, c, list) {
251                         char **deps = strsplit(NULL, c->needs, " ");
252                         unsigned int i;
253
254                         for (i = 0; deps[i]; i++) {
255                                 struct ccanlint *dep;
256                                 struct dependent *dchild;
257
258                                 dep = find_test(deps[i]);
259                                 if (!dep)
260                                         errx(1, "BUG: unknown dep '%s' for %s",
261                                              deps[i], c->key);
262                                 dchild = talloc(NULL, struct dependent);
263                                 dchild->dependent = c;
264                                 list_add_tail(&dep->dependencies,
265                                               &dchild->node);
266                                 c->num_depends++;
267                         }
268                         talloc_free(deps);
269                 }
270         }
271
272         /* Self-consistency check: make sure no two tests
273            have the same key or name. */
274         keys = btree_new(btree_strcmp);
275         names = btree_new(btree_strcmp);
276         foreach_ptr(list, &compulsory_tests, &normal_tests) {
277                 list_for_each(list, c, list) {
278                         if (!btree_insert(keys, c->key))
279                                 errx(1, "BUG: Duplicate test key '%s'",
280                                      c->key);
281                         if (!btree_insert(names, c->name))
282                                 errx(1, "BUG: Duplicate test name '%s'",
283                                      c->name);
284                 }
285         }
286         btree_delete(keys);
287         btree_delete(names);
288 }
289
290 static void print_test_depends(void)
291 {
292         struct list_head *list;
293
294         foreach_ptr(list, &compulsory_tests, &normal_tests) {
295                 struct ccanlint *c;
296                 printf("\%s Tests\n",
297                        list == &compulsory_tests ? "Compulsory" : "Normal");
298
299                 list_for_each(list, c, list) {
300                         if (!list_empty(&c->dependencies)) {
301                                 const struct dependent *d;
302                                 printf("These depend on %s:\n", c->key);
303                                 list_for_each(&c->dependencies, d, node)
304                                         printf("\t%s\n", d->dependent->key);
305                         }
306                 }
307         }
308 }
309
310 static int show_tmpdir(const char *dir)
311 {
312         printf("You can find ccanlint working files in '%s'\n", dir);
313         return 0;
314 }
315
316 static char *keep_test(const char *testname, void *unused)
317 {
318         struct ccanlint *i;
319
320         if (streq(testname, "all")) {
321                 struct list_head *list;
322                 foreach_ptr(list, &compulsory_tests, &normal_tests) {
323                         list_for_each(list, i, list)
324                                 i->keep_results = true;
325                 }
326         } else {
327                 i = find_test(testname);
328                 if (!i)
329                         errx(1, "No test %s to --keep", testname);
330                 i->keep_results = true;
331         }
332
333         /* Don't automatically destroy temporary dir. */
334         talloc_set_destructor(temp_dir(NULL), show_tmpdir);
335         return NULL;
336 }
337
338 static char *skip_test(const char *testname, void *unused)
339 {
340         btree_insert(cmdline_exclude, testname);
341         return NULL;
342 }
343
344 static void print_tests(struct list_head *tests, const char *type)
345 {
346         struct ccanlint *i;
347
348         printf("%s tests:\n", type);
349         /* This makes them print in topological order. */
350         while ((i = get_next_test(tests)) != NULL) {
351                 const struct dependent *d;
352                 printf("   %-25s %s\n", i->key, i->name);
353                 list_del(&i->list);
354                 list_for_each(&i->dependencies, d, node)
355                         d->dependent->num_depends--;
356         }
357 }
358
359 static char *list_tests(void *arg)
360 {
361         print_tests(&compulsory_tests, "Compulsory");
362         print_tests(&normal_tests, "Normal");
363         exit(0);
364 }
365
366 static void test_dgraph_vertices(struct list_head *tests, const char *style)
367 {
368         const struct ccanlint *i;
369
370         list_for_each(tests, i, list) {
371                 /*
372                  * todo: escape labels in case ccanlint test keys have
373                  *       characters interpreted as GraphViz syntax.
374                  */
375                 printf("\t\"%p\" [label=\"%s\"%s]\n", i, i->key, style);
376         }
377 }
378
379 static void test_dgraph_edges(struct list_head *tests)
380 {
381         const struct ccanlint *i;
382         const struct dependent *d;
383
384         list_for_each(tests, i, list)
385                 list_for_each(&i->dependencies, d, node)
386                         printf("\t\"%p\" -> \"%p\"\n", d->dependent, i);
387 }
388
389 static char *test_dependency_graph(void *arg)
390 {
391         puts("digraph G {");
392
393         test_dgraph_vertices(&compulsory_tests, ", style=filled, fillcolor=yellow");
394         test_dgraph_vertices(&normal_tests,     "");
395
396         test_dgraph_edges(&compulsory_tests);
397         test_dgraph_edges(&normal_tests);
398
399         puts("}");
400
401         exit(0);
402 }
403
404 /* Remove empty lines. */
405 static char **collapse(char **lines, unsigned int *nump)
406 {
407         unsigned int i, j;
408         for (i = j = 0; lines[i]; i++) {
409                 if (lines[i][0])
410                         lines[j++] = lines[i];
411         }
412         if (nump)
413                 *nump = j;
414         return lines;
415 }
416
417 static void add_info_options(struct ccan_file *info, bool mark_fails)
418 {
419         struct doc_section *d;
420         unsigned int i;
421         struct ccanlint *test;
422
423         list_for_each(get_ccan_file_docs(info), d, list) {
424                 if (!streq(d->type, "ccanlint"))
425                         continue;
426
427                 for (i = 0; i < d->num_lines; i++) {
428                         char **words = collapse(strsplit(d, d->lines[i], " \t"),
429                                                 NULL);
430                         if (!words[0])
431                                 continue;
432
433                         if (strncmp(words[0], "//", 2) == 0)
434                                 continue;
435
436                         test = find_test(words[0]);
437                         if (!test) {
438                                 warnx("%s: unknown ccanlint test '%s'",
439                                       info->fullname, words[0]);
440                                 continue;
441                         }
442
443                         if (!words[1]) {
444                                 warnx("%s: no argument to test '%s'",
445                                       info->fullname, words[0]);
446                                 continue;
447                         }
448
449                         /* Known failure? */
450                         if (strcasecmp(words[1], "FAIL") == 0) {
451                                 if (mark_fails)
452                                         btree_insert(info_exclude, words[0]);
453                         } else {
454                                 if (!test->takes_options)
455                                         warnx("%s: %s doesn't take options",
456                                               info->fullname, words[0]);
457                                 /* Copy line exactly into options. */
458                                 test->options = strstr(d->lines[i], words[0])
459                                         + strlen(words[0]);
460                         }
461                 }
462         }
463 }
464
465 static bool depends_on(struct ccanlint *i, struct ccanlint *target)
466 {
467         const struct dependent *d;
468
469         if (i == target)
470                 return true;
471
472         list_for_each(&i->dependencies, d, node) {
473                 if (depends_on(d->dependent, target))
474                         return true;
475         }
476         return false;
477 }
478
479 /* O(N^2), who cares? */
480 static void skip_unrelated_tests(struct ccanlint *target)
481 {
482         struct ccanlint *i;
483         struct list_head *list;
484
485         foreach_ptr(list, &compulsory_tests, &normal_tests)
486                 list_for_each(list, i, list)
487                         if (!depends_on(i, target))
488                                 i->skip = "not relevant to target";
489 }
490
491 static char *demangle_string(char *string)
492 {
493         unsigned int i;
494         const char mapfrom[] = "abfnrtv";
495         const char mapto[] = "\a\b\f\n\r\t\v";
496
497         if (!strchr(string, '"'))
498                 return NULL;
499         string = strchr(string, '"') + 1;
500         if (!strrchr(string, '"'))
501                 return NULL;
502         *strrchr(string, '"') = '\0';
503
504         for (i = 0; i < strlen(string); i++) {
505                 if (string[i] == '\\') {
506                         char repl;
507                         unsigned len = 0;
508                         const char *p = strchr(mapfrom, string[i+1]);
509                         if (p) {
510                                 repl = mapto[p - mapfrom];
511                                 len = 1;
512                         } else if (strlen(string+i+1) >= 3) {
513                                 if (string[i+1] == 'x') {
514                                         repl = (string[i+2]-'0')*16
515                                                 + string[i+3]-'0';
516                                         len = 3;
517                                 } else if (cisdigit(string[i+1])) {
518                                         repl = (string[i+2]-'0')*8*8
519                                                 + (string[i+3]-'0')*8
520                                                 + (string[i+4]-'0');
521                                         len = 3;
522                                 }
523                         }
524                         if (len == 0) {
525                                 repl = string[i+1];
526                                 len = 1;
527                         }
528
529                         string[i] = repl;
530                         memmove(string + i + 1, string + i + len + 1,
531                                 strlen(string + i + len + 1) + 1);
532                 }
533         }
534
535         return string;
536 }
537
538
539 static void read_config_header(void)
540 {
541         char *fname = talloc_asprintf(NULL, "%s/config.h", ccan_dir);
542         char **lines;
543         unsigned int i;
544
545         config_header = grab_file(NULL, fname, NULL);
546         if (!config_header) {
547                 talloc_free(fname);
548                 return;
549         }
550
551         lines = strsplit(config_header, config_header, "\n");
552         for (i = 0; i < talloc_array_length(lines) - 1; i++) {
553                 char *sym;
554                 const char **line = (const char **)&lines[i];
555
556                 if (!get_token(line, "#"))
557                         continue;
558                 if (!get_token(line, "define"))
559                         continue;
560                 sym = get_symbol_token(lines, line);
561                 if (streq(sym, "CCAN_COMPILER") && !compiler) {
562                         compiler = demangle_string(lines[i]);
563                         if (!compiler)
564                                 errx(1, "%s:%u:could not parse CCAN_COMPILER",
565                                      fname, i+1);
566                         if (verbose > 1)
567                                 printf("%s: compiler set to '%s'\n",
568                                        fname, compiler);
569                 } else if (streq(sym, "CCAN_CFLAGS") && !cflags) {
570                         cflags = demangle_string(lines[i]);
571                         if (!cflags)
572                                 errx(1, "%s:%u:could not parse CCAN_CFLAGS",
573                                      fname, i+1);
574                         if (verbose > 1)
575                                 printf("%s: compiler flags set to '%s'\n",
576                                        fname, cflags);
577                 }
578         }
579         if (!compiler)
580                 compiler = CCAN_COMPILER;
581         if (!cflags)
582                 compiler = CCAN_CFLAGS;
583 }
584
585 static char *opt_set_const_charp(const char *arg, const char **p)
586 {
587         return opt_set_charp(arg, cast_const2(char **, p));
588 }
589
590 int main(int argc, char *argv[])
591 {
592         bool summary = false, pass = true;
593         unsigned int score = 0, total_score = 0;
594         struct manifest *m;
595         struct ccanlint *i;
596         const char *prefix = "";
597         char *dir = talloc_getcwd(NULL), *base_dir = dir, *target = NULL;
598         
599         init_tests();
600
601         cmdline_exclude = btree_new(btree_strcmp);
602         info_exclude = btree_new(btree_strcmp);
603
604         opt_register_arg("--dir|-d", opt_set_charp, opt_show_charp, &dir,
605                          "use this directory");
606         opt_register_noarg("-n|--safe-mode", opt_set_bool, &safe_mode,
607                          "do not compile anything");
608         opt_register_noarg("-l|--list-tests", list_tests, NULL,
609                          "list tests ccanlint performs (and exit)");
610         opt_register_noarg("--test-dep-graph", test_dependency_graph, NULL,
611                          "print dependency graph of tests in Graphviz .dot format");
612         opt_register_arg("-k|--keep <testname>", keep_test, NULL, NULL,
613                          "keep results of <testname>"
614                          " (can be used multiple times, or 'all')");
615         opt_register_noarg("--summary|-s", opt_set_bool, &summary,
616                            "simply give one line summary");
617         opt_register_noarg("--verbose|-v", opt_inc_intval, &verbose,
618                            "verbose mode (up to -vvvv)");
619         opt_register_arg("-x|--exclude <testname>", skip_test, NULL, NULL,
620                          "exclude <testname> (can be used multiple times)");
621         opt_register_arg("-t|--timeout <milleseconds>", opt_set_uintval,
622                          NULL, &timeout,
623                          "ignore (terminate) tests that are slower than this");
624         opt_register_arg("--target <testname>", opt_set_charp,
625                          NULL, &target,
626                          "only run one test (and its prerequisites)");
627         opt_register_arg("--compiler <compiler>", opt_set_const_charp,
628                          NULL, &compiler, "set the compiler");
629         opt_register_arg("--cflags <flags>", opt_set_const_charp,
630                          NULL, &cflags, "set the compiler flags");
631         opt_register_noarg("-?|-h|--help", opt_usage_and_exit,
632                            "\nA program for checking and guiding development"
633                            " of CCAN modules.",
634                            "This usage message");
635
636         /* We move into temporary directory, so gcov dumps its files there. */
637         if (chdir(temp_dir(talloc_autofree_context())) != 0)
638                 err(1, "Error changing to %s temporary dir", temp_dir(NULL));
639
640         opt_parse(&argc, argv, opt_log_stderr_exit);
641
642         if (dir[0] != '/')
643                 dir = talloc_asprintf_append(NULL, "%s/%s", base_dir, dir);
644         while (strends(dir, "/"))
645                 dir[strlen(dir)-1] = '\0';
646         if (dir != base_dir)
647                 prefix = talloc_append_string(talloc_basename(NULL, dir), ": ");
648         if (verbose >= 3) {
649                 compile_verbose = true;
650                 print_test_depends();
651         }
652         if (verbose >= 4)
653                 tools_verbose = true;
654
655         m = get_manifest(talloc_autofree_context(), dir);
656         read_config_header();
657
658         /* Create a symlink from temp dir back to src dir's test directory. */
659         if (symlink(talloc_asprintf(m, "%s/test", dir),
660                     talloc_asprintf(m, "%s/test", temp_dir(NULL))) != 0)
661                 err(1, "Creating test symlink in %s", temp_dir(NULL));
662
663         if (target) {
664                 struct ccanlint *test;
665
666                 test = find_test(target);
667                 if (!test)
668                         errx(1, "Unknown test to run '%s'", target);
669                 skip_unrelated_tests(test);
670         }
671
672         /* If you don't pass the compulsory tests, you get a score of 0. */
673         while ((i = get_next_test(&compulsory_tests)) != NULL) {
674                 if (!run_test(i, summary, &score, &total_score, m)) {
675                         printf("%sTotal score: 0/%u\n", prefix, total_score);
676                         errx(1, "%s%s failed", prefix, i->name);
677                 }
678         }
679
680         /* --target overrides known FAIL from _info */
681         if (m->info_file)
682                 add_info_options(m->info_file, !target);
683
684         while ((i = get_next_test(&normal_tests)) != NULL)
685                 pass &= run_test(i, summary, &score, &total_score, m);
686
687         printf("%sTotal score: %u/%u\n", prefix, score, total_score);
688         return pass ? 0 : 1;
689 }