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