htable: restore perfect bit when resizing.
[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  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the Free
7  * Software Foundation; either version 2 of the License, or (at your option)
8  * any later version.
9  *
10  *   This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
13  * more details.
14  *
15  * You should have received a copy of the GNU General Public License along with
16  * this program; if not, write to the Free Software Foundation, Inc., 51
17  * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19 #include "ccanlint.h"
20 #include "../tools.h"
21 #include <unistd.h>
22 #include <stdarg.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[2];
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 *score,
92                      unsigned int *total_score,
93                      struct manifest *m)
94 {
95         void *result;
96         unsigned int this_score, max_score, timeleft;
97         const struct dependent *d;
98         const char *skip;
99         bool bad, good;
100
101         //one less test to run through
102         list_for_each(&i->dependencies, d, node)
103                 d->dependent->num_depends--;
104
105         skip = should_skip(m, i);
106
107         if (skip) {
108         skip:
109                 if (verbose && !streq(skip, "not relevant to target"))
110                         printf("  %s: skipped (%s)\n", i->name, skip);
111
112                 /* If we're skipping this because a prereq failed, we fail. */
113                 if (i->skip_fail)
114                         *total_score += i->total_score;
115                         
116                 list_del(&i->list);
117                 list_add_tail(&finished_tests, &i->list);
118                 list_for_each(&i->dependencies, d, node) {
119                         if (d->dependent->skip)
120                                 continue;
121                         d->dependent->skip = "dependency was skipped";
122                         d->dependent->skip_fail = i->skip_fail;
123                 }
124                 return true;
125         }
126
127         timeleft = timeout ? timeout : default_timeout_ms;
128         result = i->check(m, i->keep_results, &timeleft);
129         if (timeout && timeleft == 0) {
130                 skip = "timeout";
131                 goto skip;
132         }
133
134         max_score = i->total_score;
135         if (!max_score)
136                 max_score = 1;
137
138         if (!result)
139                 this_score = max_score;
140         else if (i->score)
141                 this_score = i->score(m, result);
142         else
143                 this_score = 0;
144
145         bad = (this_score == 0);
146         good = (this_score >= max_score);
147
148         if (verbose || (!good && !quiet)) {
149                 printf("  %s: %s", i->name,
150                        bad ? "FAIL" : good ? "PASS" : "PARTIAL");
151                 if (max_score > 1)
152                         printf(" (+%u/%u)", this_score, max_score);
153                 printf("\n");
154         }
155
156         if (!quiet && result) {
157                 const char *desc;
158                 if (i->describe && (desc = i->describe(m, result)) != NULL) 
159                         printf("    %s\n", desc);
160                 if (i->handle)
161                         i->handle(m, result);
162         }
163
164         if (i->total_score) {
165                 *score += this_score;
166                 *total_score += i->total_score;
167         }
168
169         list_del(&i->list);
170         list_add_tail(&finished_tests, &i->list);
171
172         if (bad) {
173                 /* Skip any tests which depend on this one. */
174                 list_for_each(&i->dependencies, d, node) {
175                         if (d->dependent->skip)
176                                 continue;
177                         d->dependent->skip = "dependency failed";
178                         d->dependent->skip_fail = true;
179                 }
180         }
181         return good;
182 }
183
184 static void register_test(struct list_head *h, struct ccanlint *test, ...)
185 {
186         va_list ap;
187         struct ccanlint *depends;
188         struct dependent *dchild;
189
190         list_add(h, &test->list);
191
192         va_start(ap, test);
193         /* Careful: we might have been initialized by a dependent. */
194         if (test->dependencies.n.next == NULL)
195                 list_head_init(&test->dependencies);
196
197         //dependent(s) args (if any), last one is NULL
198         while ((depends = va_arg(ap, struct ccanlint *)) != NULL) {
199                 dchild = malloc(sizeof(*dchild));
200                 dchild->dependent = test;
201                 /* The thing we depend on might not be initialized yet! */
202                 if (depends->dependencies.n.next == NULL)
203                         list_head_init(&depends->dependencies);
204                 list_add_tail(&depends->dependencies, &dchild->node);
205                 test->num_depends++;
206         }
207         va_end(ap);
208 }
209
210 /**
211  * get_next_test - retrieves the next test to be processed
212  **/
213 static inline struct ccanlint *get_next_test(struct list_head *test)
214 {
215         struct ccanlint *i;
216
217         if (list_empty(test))
218                 return NULL;
219
220         list_for_each(test, i, list) {
221                 if (i->num_depends == 0)
222                         return i;
223         }
224         errx(1, "Can't make process; test dependency cycle");
225 }
226
227 static void init_tests(void)
228 {
229         const struct ccanlint *i;
230         struct btree *keys, *names;
231
232 #undef REGISTER_TEST
233 #define REGISTER_TEST(name, ...) register_test(&normal_tests, &name, __VA_ARGS__, NULL)
234 #include "generated-normal-tests"
235 #undef REGISTER_TEST
236 #define REGISTER_TEST(name, ...) register_test(&compulsory_tests, &name, __VA_ARGS__, NULL)
237 #include "generated-compulsory-tests"
238
239         /* Self-consistency check: make sure no two tests
240            have the same key or name. */
241         keys = btree_new(btree_strcmp);
242         names = btree_new(btree_strcmp);
243         list_for_each(&compulsory_tests, i, list) {
244                 if (!btree_insert(keys, i->key))
245                         errx(1, "BUG: Duplicate test key '%s'", i->key);
246                 if (!btree_insert(keys, i->name))
247                         errx(1, "BUG: Duplicate test name '%s'", i->name);
248         }
249         list_for_each(&normal_tests, i, list) {
250                 if (!btree_insert(keys, i->key))
251                         errx(1, "BUG: Duplicate test key '%s'", i->key);
252                 if (!btree_insert(keys, i->name))
253                         errx(1, "BUG: Duplicate test name '%s'", i->name);
254         }
255         btree_delete(keys);
256         btree_delete(names);
257         
258         if (!verbose)
259                 return;
260
261         printf("\nCompulsory Tests\n");
262         list_for_each(&compulsory_tests, i, list) {
263                 printf("%s depends on %u others\n", i->name, i->num_depends);
264                 if (!list_empty(&i->dependencies)) {
265                         const struct dependent *d;
266                         printf("These depend on us:\n");
267                         list_for_each(&i->dependencies, d, node)
268                                 printf("\t%s\n", d->dependent->name);
269                 }
270         }
271
272         printf("\nNormal Tests\n");
273         list_for_each(&normal_tests, i, list) {
274                 printf("%s depends on %u others\n", i->name, i->num_depends);
275                 if (!list_empty(&i->dependencies)) {
276                         const struct dependent *d;
277                         printf("These depend on us:\n");
278                         list_for_each(&i->dependencies, d, node)
279                                 printf("\t%s\n", d->dependent->name);
280                 }
281         }
282 }
283
284 static struct ccanlint *find_test(const char *key)
285 {
286         struct ccanlint *i;
287
288         list_for_each(&compulsory_tests, i, list)
289                 if (streq(i->key, key))
290                         return i;
291
292         list_for_each(&normal_tests, i, list)
293                 if (streq(i->key, key))
294                         return i;
295
296         return NULL;
297 }
298
299 static char *keep_test(const char *testname, void *unused)
300 {
301         struct ccanlint *i = find_test(testname);
302         if (!i)
303                 errx(1, "No test %s to --keep", testname);
304         i->keep_results = true;
305         return NULL;
306 }
307
308 static char *skip_test(const char *testname, void *unused)
309 {
310         btree_insert(cmdline_exclude, optarg);
311         return NULL;
312 }
313
314 static void print_tests(struct list_head *tests, const char *type)
315 {
316         struct ccanlint *i;
317
318         printf("%s tests:\n", type);
319         /* This makes them print in topological order. */
320         while ((i = get_next_test(tests)) != NULL) {
321                 const struct dependent *d;
322                 printf("   %-25s %s\n", i->key, i->name);
323                 list_del(&i->list);
324                 list_for_each(&i->dependencies, d, node)
325                         d->dependent->num_depends--;
326         }
327 }
328
329 static char *list_tests(void *arg)
330 {
331         print_tests(&compulsory_tests, "Compulsory");
332         print_tests(&normal_tests, "Normal");
333         exit(0);
334 }
335
336 static char *strip(const void *ctx, const char *line)
337 {
338         line += strcspn(line, IDENT_CHARS "-");
339         return talloc_strndup(ctx, line, strspn(line, IDENT_CHARS "-"));
340 }
341
342 static void add_info_fails(struct ccan_file *info)
343 {
344         struct doc_section *d;
345         unsigned int i;
346
347         list_for_each(get_ccan_file_docs(info), d, list) {
348                 if (!streq(d->type, "fails"))
349                         continue;
350
351                 for (i = 0; i < d->num_lines; i++)
352                         btree_insert(info_exclude, strip(info, d->lines[i]));
353                 break;
354         }
355 }
356
357 static bool depends_on(struct ccanlint *i, struct ccanlint *target)
358 {
359         const struct dependent *d;
360
361         if (i == target)
362                 return true;
363
364         list_for_each(&i->dependencies, d, node) {
365                 if (depends_on(d->dependent, target))
366                         return true;
367         }
368         return false;
369 }
370
371 /* O(N^2), who cares? */
372 static void skip_unrelated_tests(struct ccanlint *target)
373 {
374         struct ccanlint *i;
375         struct list_head *list;
376
377         foreach_ptr(list, &compulsory_tests, &normal_tests)
378                 list_for_each(list, i, list)
379                         if (!depends_on(i, target))
380                                 i->skip = "not relevant to target";
381 }
382
383 int main(int argc, char *argv[])
384 {
385         bool summary = false;
386         unsigned int score = 0, total_score = 0;
387         struct manifest *m;
388         struct ccanlint *i;
389         const char *prefix = "";
390         char *dir = talloc_getcwd(NULL), *base_dir = dir, *target = NULL;
391         
392         init_tests();
393
394         cmdline_exclude = btree_new(btree_strcmp);
395         info_exclude = btree_new(btree_strcmp);
396
397         opt_register_arg("--dir|-d", opt_set_charp, opt_show_charp, &dir,
398                          "use this directory");
399         opt_register_noarg("-n|--safe-mode", opt_set_bool, &safe_mode,
400                          "do not compile anything");
401         opt_register_noarg("-l|--list-tests", list_tests, NULL,
402                          "list tests ccanlint performs (and exit)");
403         opt_register_arg("-k|--keep <testname>", keep_test, NULL, NULL,
404                            "keep results of <testname> (can be used multiple times)");
405         opt_register_noarg("--summary|-s", opt_set_bool, &summary,
406                            "simply give one line summary");
407         opt_register_noarg("--verbose|-v", opt_inc_intval, &verbose,
408                            "verbose mode (can specify more than once)");
409         opt_register_arg("-x|--exclude <testname>", skip_test, NULL, NULL,
410                          "exclude <testname> (can be used multiple times)");
411         opt_register_arg("-t|--timeout <milleseconds>", opt_set_uintval,
412                          NULL, &timeout,
413                          "ignore (terminate) tests that are slower than this");
414         opt_register_arg("--target <testname>", opt_set_charp,
415                          NULL, &target,
416                          "only run one test (and its prerequisites)");
417         opt_register_noarg("-?|-h|--help", opt_usage_and_exit,
418                            "\nA program for checking and guiding development"
419                            " of CCAN modules.",
420                            "This usage message");
421
422         opt_parse(&argc, argv, opt_log_stderr_exit);
423
424         if (dir[0] != '/')
425                 dir = talloc_asprintf_append(NULL, "%s/%s", base_dir, dir);
426         if (dir != base_dir)
427                 prefix = talloc_append_string(talloc_basename(NULL, dir), ": ");
428         if (verbose >= 2)
429                 compile_verbose = true;
430         if (verbose >= 3)
431                 tools_verbose = true;
432
433         /* We move into temporary directory, so gcov dumps its files there. */
434         if (chdir(temp_dir(talloc_autofree_context())) != 0)
435                 err(1, "Error changing to %s temporary dir", temp_dir(NULL));
436
437         m = get_manifest(talloc_autofree_context(), dir);
438
439         /* Create a symlink from temp dir back to src dir's test directory. */
440         if (symlink(talloc_asprintf(m, "%s/test", dir),
441                     talloc_asprintf(m, "%s/test", temp_dir(NULL))) != 0)
442                 err(1, "Creating test symlink in %s", temp_dir(NULL));
443
444         if (target) {
445                 struct ccanlint *test;
446
447                 test = find_test(target);
448                 if (!test)
449                         err(1, "Unknown test to run '%s'", target);
450                 skip_unrelated_tests(test);
451         }
452
453         /* If you don't pass the compulsory tests, you get a score of 0. */
454         if (verbose)
455                 printf("Compulsory tests:\n");
456
457         while ((i = get_next_test(&compulsory_tests)) != NULL) {
458                 if (!run_test(i, summary, &score, &total_score, m)) {
459                         printf("%sTotal score: 0/%u\n", prefix, total_score);
460                         errx(1, "%s%s failed", prefix, i->name);
461                 }
462         }
463
464         add_info_fails(m->info_file);
465
466         if (verbose)
467                 printf("\nNormal tests:\n");
468         while ((i = get_next_test(&normal_tests)) != NULL)
469                 run_test(i, summary, &score, &total_score, m);
470
471         printf("%sTotal score: %u/%u\n", prefix, score, total_score);
472         return 0;
473 }