]> git.ozlabs.org Git - ccan/blob - tools/ccanlint/file_analysis.c
92c23798292c9844058374f22115b324345ae720
[ccan] / tools / ccanlint / file_analysis.c
1 #include "ccanlint.h"
2 #include <ccan/talloc/talloc.h>
3 #include <ccan/str/str.h>
4 #include <ccan/str_talloc/str_talloc.h>
5 #include <ccan/talloc_link/talloc_link.h>
6 #include <ccan/hash/hash.h>
7 #include <ccan/htable/htable_type.h>
8 #include <ccan/grab_file/grab_file.h>
9 #include <ccan/noerr/noerr.h>
10 #include <ccan/foreach/foreach.h>
11 #include <ccan/asort/asort.h>
12 #include "../tools.h"
13 #include <unistd.h>
14 #include <sys/types.h>
15 #include <sys/stat.h>
16 #include <fcntl.h>
17 #include <err.h>
18 #include <errno.h>
19 #include <dirent.h>
20 #include <ctype.h>
21 #include <stdarg.h>
22 #include <assert.h>
23
24 const char *ccan_dir;
25
26 static size_t dir_hash(const char *name)
27 {
28         return hash(name, strlen(name), 0);
29 }
30
31 static const char *manifest_name(const struct manifest *m)
32 {
33         return m->dir;
34 }
35
36 static bool dir_cmp(const struct manifest *m, const char *dir)
37 {
38         return strcmp(m->dir, dir) == 0;
39 }
40
41 HTABLE_DEFINE_TYPE(struct manifest, manifest_name, dir_hash, dir_cmp, manifest);
42 static struct htable_manifest *manifests;
43
44 const char *get_ccan_file_contents(struct ccan_file *f)
45 {
46         if (!f->contents) {
47                 f->contents = grab_file(f, f->fullname, &f->contents_size);
48                 if (!f->contents)
49                         err(1, "Reading file %s", f->fullname);
50         }
51         return f->contents;
52 }
53
54 char **get_ccan_file_lines(struct ccan_file *f)
55 {
56         if (!f->lines)
57                 f->lines = strsplit(f, get_ccan_file_contents(f), "\n");
58
59         /* FIXME: is f->num_lines necessary? */
60         f->num_lines = talloc_array_length(f->lines) - 1;
61         return f->lines;
62 }
63
64 struct list_head *get_ccan_file_docs(struct ccan_file *f)
65 {
66         if (!f->doc_sections) {
67                 get_ccan_file_lines(f);
68                 f->doc_sections = extract_doc_sections(f->lines);
69         }
70         return f->doc_sections;
71 }
72
73 struct ccan_file *new_ccan_file(const void *ctx, const char *dir, char *name)
74 {
75         struct ccan_file *f;
76
77         assert(dir[0] == '/');
78
79         f = talloc(ctx, struct ccan_file);
80         f->lines = NULL;
81         f->line_info = NULL;
82         f->doc_sections = NULL;
83         f->compiled = NULL;
84         f->name = talloc_steal(f, name);
85         f->fullname = talloc_asprintf(f, "%s/%s", dir, f->name);
86         f->contents = NULL;
87         f->cov_compiled = NULL;
88         return f;
89 }
90
91 static void add_files(struct manifest *m, const char *dir)
92 {
93         DIR *d;
94         struct dirent *ent;
95         char **subs = NULL;
96
97         if (dir[0])
98                 d = opendir(dir);
99         else
100                 d = opendir(".");
101         if (!d)
102                 err(1, "Opening directory %s", dir[0] ? dir : ".");
103
104         while ((ent = readdir(d)) != NULL) {
105                 struct stat st;
106                 struct ccan_file *f;
107                 struct list_head *dest;
108                 bool is_c_src;
109
110                 if (ent->d_name[0] == '.')
111                         continue;
112
113                 f = new_ccan_file(m, m->dir,
114                                   talloc_asprintf(m, "%s%s",
115                                                   dir, ent->d_name));
116                 if (lstat(f->name, &st) != 0)
117                         err(1, "lstat %s", f->name);
118
119                 if (S_ISDIR(st.st_mode)) {
120                         size_t len = talloc_array_length(subs);
121                         subs = talloc_realloc(m, subs, char *, len+1);
122                         subs[len] = talloc_append_string(f->name, "/");
123                         continue;
124                 }
125                 if (!S_ISREG(st.st_mode)) {
126                         talloc_free(f);
127                         continue;
128                 }
129
130                 if (streq(f->name, "_info")) {
131                         m->info_file = f;
132                         continue;
133                 }
134
135                 is_c_src = strends(f->name, ".c");
136                 if (!is_c_src && !strends(f->name, ".h")) {
137                         dest = &m->other_files;
138                 } else if (!strchr(f->name, '/')) {
139                         if (is_c_src)
140                                 dest = &m->c_files;
141                         else
142                                 dest = &m->h_files;
143                 } else if (strstarts(f->name, "test/")) {
144                         if (is_c_src) {
145                                 if (strstarts(f->name, "test/api"))
146                                         dest = &m->api_tests;
147                                 else if (strstarts(f->name, "test/run"))
148                                         dest = &m->run_tests;
149                                 else if (strstarts(f->name, "test/compile_ok"))
150                                         dest = &m->compile_ok_tests;
151                                 else if (strstarts(f->name, "test/compile_fail"))
152                                         dest = &m->compile_fail_tests;
153                                 else
154                                         dest = &m->other_test_c_files;
155                         } else
156                                 dest = &m->other_test_files;
157                 } else
158                         dest = &m->other_files;
159
160                 list_add(dest, &f->list);
161         }
162         closedir(d);
163
164         /* Before we recurse, sanity check this is a ccan module. */ 
165         if (!dir[0]) {
166                 size_t i;
167
168                 if (!m->info_file
169                     && list_empty(&m->c_files)
170                     && list_empty(&m->h_files))
171                         errx(1, "No _info, C or H files found here!");
172
173                 for (i = 0; i < talloc_array_length(subs); i++)
174                         add_files(m, subs[i]);
175         }
176         talloc_free(subs);
177 }
178
179 static int cmp_names(struct ccan_file *const *a, struct ccan_file *const *b,
180                      void *unused)
181 {
182         return strcmp((*a)->name, (*b)->name);
183 }
184
185 static void sort_files(struct list_head *list)
186 {
187         struct ccan_file **files = NULL, *f;
188         unsigned int i, num;
189
190         num = 0;
191         while ((f = list_top(list, struct ccan_file, list)) != NULL) {
192                 files = talloc_realloc(NULL, files, struct ccan_file *, num+1);
193                 files[num++] = f;
194                 list_del(&f->list);
195         }
196         asort(files, num, cmp_names, NULL);
197
198         for (i = 0; i < num; i++)
199                 list_add_tail(list, &files[i]->list);
200         talloc_free(files);
201 }
202
203 struct manifest *get_manifest(const void *ctx, const char *dir)
204 {
205         struct manifest *m;
206         char *olddir, *canon_dir;
207         unsigned int len;
208         struct list_head *list;
209
210         if (!manifests)
211                 manifests = htable_manifest_new();
212
213         olddir = talloc_getcwd(NULL);
214         if (!olddir)
215                 err(1, "Getting current directory");
216
217         if (chdir(dir) != 0)
218                 err(1, "Failed to chdir to %s", dir);
219
220         canon_dir = talloc_getcwd(olddir);
221         if (!canon_dir)
222                 err(1, "Getting current directory");
223
224         m = htable_manifest_get(manifests, canon_dir);
225         if (m)
226                 goto done;
227
228         m = talloc_linked(ctx, talloc(NULL, struct manifest));
229         m->info_file = NULL;
230         m->compiled = NULL;
231         m->dir = talloc_steal(m, canon_dir);
232         list_head_init(&m->c_files);
233         list_head_init(&m->h_files);
234         list_head_init(&m->api_tests);
235         list_head_init(&m->run_tests);
236         list_head_init(&m->compile_ok_tests);
237         list_head_init(&m->compile_fail_tests);
238         list_head_init(&m->other_test_c_files);
239         list_head_init(&m->other_test_files);
240         list_head_init(&m->other_files);
241         list_head_init(&m->examples);
242         list_head_init(&m->mangled_examples);
243         list_head_init(&m->deps);
244
245         len = strlen(m->dir);
246         while (len && m->dir[len-1] == '/')
247                 m->dir[--len] = '\0';
248
249         m->basename = strrchr(m->dir, '/');
250         if (!m->basename)
251                 errx(1, "I don't expect to be run from the root directory");
252         m->basename++;
253
254         /* We expect the ccan dir to be two levels above module dir. */
255         if (!ccan_dir) {
256                 char *p;
257                 ccan_dir = talloc_strdup(NULL, m->dir);
258                 p = strrchr(ccan_dir, '/');
259                 if (!p)
260                         errx(1, "I expect the ccan root directory in ../..");
261                 *p = '\0';
262                 p = strrchr(ccan_dir, '/');
263                 if (!p)
264                         errx(1, "I expect the ccan root directory in ../..");
265                 *p = '\0';
266         }
267
268         add_files(m, "");
269
270         /* Nicer to run tests in a predictable order. */
271         foreach_ptr(list, &m->api_tests, &m->run_tests, &m->compile_ok_tests,
272                     &m->compile_fail_tests)
273                 sort_files(list);
274
275         htable_manifest_add(manifests, m);
276
277 done:
278         if (chdir(olddir) != 0)
279                 err(1, "Returning to original directory '%s'", olddir);
280         talloc_free(olddir);
281
282         return m;
283 }
284
285
286 /**
287  * remove_comments - strip comments from a line, return copy.
288  * @line: line to copy
289  * @in_comment: are we already within a comment (from prev line).
290  * @unterminated: are we still in a comment for next line.
291  */
292 static char *remove_comments(const char *line, bool in_comment,
293                              bool *unterminated)
294 {
295         char *p, *ret = talloc_array(line, char, strlen(line) + 1);
296
297         p = ret;
298         for (;;) {
299                 if (!in_comment) {
300                         /* Find first comment. */
301                         const char *old_comment = strstr(line, "/*");
302                         const char *new_comment = strstr(line, "//");
303                         const char *comment;
304
305                         if (new_comment && old_comment)
306                                 comment = new_comment < old_comment
307                                         ? new_comment : old_comment;
308                         else if (old_comment)
309                                 comment = old_comment;
310                         else if (new_comment)
311                                 comment = new_comment;
312                         else {
313                                 /* Nothing more. */
314                                 strcpy(p, line);
315                                 *unterminated = false;
316                                 break;
317                         }
318
319                         /* Copy up to comment. */
320                         memcpy(p, line, comment - line);
321                         p += comment - line;
322                         line += comment - line + 2;
323
324                         if (comment == new_comment) {
325                                 /* We're done: goes to EOL. */
326                                 p[0] = '\0';
327                                 *unterminated = false;
328                                 break;
329                         }
330                         in_comment = true;
331                 }
332
333                 if (in_comment) {
334                         const char *end = strstr(line, "*/");
335                         if (!end) {
336                                 *unterminated = true;
337                                 p[0] = '\0';
338                                 break;
339                         }
340                         line = end+2;
341                         in_comment = false;
342                 }
343         }
344         return ret;
345 }
346
347 static bool is_empty(const char *line)
348 {
349         return strspn(line, " \t") == strlen(line);
350 }
351
352 static bool continues(const char *line)
353 {
354         /* Technically, any odd number of these.  But who cares? */
355         return strends(line, "\\");
356 }
357
358 /* Get token if it's equal to token. */
359 bool get_token(const char **line, const char *token)
360 {
361         unsigned int toklen;
362
363         *line += strspn(*line, " \t");
364         if (isalnum(token[0]) || token[0] == '_')
365                 toklen = strspn(*line, IDENT_CHARS);
366         else {
367                 /* FIXME: real tokenizer handles ++ and other multi-chars.  */
368                 toklen = strlen(token);
369         }
370
371         if (toklen == strlen(token) && !strncmp(*line, token, toklen)) {
372                 *line += toklen;
373                 return true;
374         }
375         return false;
376 }
377
378 char *get_symbol_token(void *ctx, const char **line)
379 {
380         unsigned int toklen;
381         char *ret;
382
383         *line += strspn(*line, " \t");
384         toklen = strspn(*line, IDENT_CHARS);
385         if (!toklen)
386                 return NULL;
387         ret = talloc_strndup(ctx, *line, toklen);
388         *line += toklen;
389         return ret;
390 }
391
392 static bool parse_hash_if(struct pp_conditions *cond, const char **line)
393 {
394         bool brackets, defined;
395
396         cond->inverse = get_token(line, "!");
397         defined = get_token(line, "defined");
398         brackets = get_token(line, "(");
399         cond->symbol = get_symbol_token(cond, line);
400         if (!cond->symbol)
401                 return false;
402         if (brackets && !get_token(line, ")"))
403                 return false;
404         if (!defined)
405                 cond->type = PP_COND_IF;
406         return true;
407 }
408
409 /* FIXME: Get serious! */
410 static struct pp_conditions *analyze_directive(struct ccan_file *f,
411                                                const char *line,
412                                                struct pp_conditions *parent)
413 {
414         struct pp_conditions *cond = talloc(f, struct pp_conditions);
415         bool unused;
416
417         line = remove_comments(line, false, &unused);
418
419         cond->parent = parent;
420         cond->type = PP_COND_IFDEF;
421
422         if (!get_token(&line, "#"))
423                 abort();
424
425         if (get_token(&line, "if")) {
426                 if (!parse_hash_if(cond, &line))
427                         goto unknown;
428         } else if (get_token(&line, "elif")) {
429                 /* Malformed? */
430                 if (!parent)
431                         return NULL;
432                 cond->parent = parent->parent;
433                 /* FIXME: Not quite true.  This implies !parent, but we don't
434                  * do multiple conditionals yet. */
435                 if (!parse_hash_if(cond, &line))
436                         goto unknown;
437         } else if (get_token(&line, "ifdef")) {
438                 bool brackets;
439                 cond->inverse = false;
440                 brackets = get_token(&line, "(");
441                 cond->symbol = get_symbol_token(cond, &line);
442                 if (!cond->symbol)
443                         goto unknown;
444                 if (brackets && !get_token(&line, ")"))
445                         goto unknown;
446         } else if (get_token(&line, "ifndef")) {
447                 bool brackets;
448                 cond->inverse = true;
449                 brackets = get_token(&line, "(");
450                 cond->symbol = get_symbol_token(cond, &line);
451                 if (!cond->symbol)
452                         goto unknown;
453                 if (brackets && !get_token(&line, ")"))
454                         goto unknown;
455         } else if (get_token(&line, "else")) {
456                 /* Malformed? */
457                 if (!parent)
458                         return NULL;
459
460                 *cond = *parent;
461                 cond->inverse = !cond->inverse;
462                 return cond;
463         } else if (get_token(&line, "endif")) {
464                 talloc_free(cond);
465                 /* Malformed? */
466                 if (!parent)
467                         return NULL;
468                 /* Back up one! */
469                 return parent->parent;
470         } else {
471                 /* Not a conditional. */
472                 talloc_free(cond);
473                 return parent;
474         }
475
476         if (!is_empty(line))
477                 goto unknown;
478         return cond;
479
480 unknown:
481         cond->type = PP_COND_UNKNOWN;
482         return cond;
483 }
484
485 /* This parser is rough, but OK if code is reasonably neat. */
486 struct line_info *get_ccan_line_info(struct ccan_file *f)
487 {
488         bool continued = false, in_comment = false;
489         struct pp_conditions *cond = NULL;
490         unsigned int i;
491
492         if (f->line_info)
493                 return f->line_info;
494
495         get_ccan_file_lines(f);
496         f->line_info = talloc_array(f->lines, struct line_info, f->num_lines);
497
498         for (i = 0; i < f->num_lines; continued = continues(f->lines[i++])) {
499                 char *p;
500                 bool still_doc_line;
501
502                 /* Current conditions apply to this line. */
503                 f->line_info[i].cond = cond;
504                 f->line_info[i].continued = continued;
505
506                 if (continued) {
507                         /* Same as last line. */
508                         f->line_info[i].type = f->line_info[i-1].type;
509                         /* Update in_comment. */
510                         remove_comments(f->lines[i], in_comment, &in_comment);
511                         continue;
512                 }
513
514                 /* Preprocessor directive? */
515                 if (!in_comment
516                     && f->lines[i][strspn(f->lines[i], " \t")] == '#') {
517                         f->line_info[i].type = PREPROC_LINE;
518                         cond = analyze_directive(f, f->lines[i], cond);
519                         continue;
520                 }
521
522                 still_doc_line = (in_comment
523                                   && f->line_info[i-1].type == DOC_LINE);
524
525                 p = remove_comments(f->lines[i], in_comment, &in_comment);
526                 if (is_empty(p)) {
527                         if (strstarts(f->lines[i], "/**") || still_doc_line)
528                                 f->line_info[i].type = DOC_LINE;
529                         else
530                                 f->line_info[i].type = COMMENT_LINE;
531                 } else
532                         f->line_info[i].type = CODE_LINE;
533                 talloc_free(p);
534         }
535         return f->line_info;
536 }
537
538 struct symbol {
539         struct list_node list;
540         const char *name;
541         const unsigned int *value;
542 };
543
544 static struct symbol *find_symbol(struct list_head *syms, const char *sym)
545 {
546         struct symbol *i;
547
548         list_for_each(syms, i, list)
549                 if (streq(sym, i->name))
550                         return i;
551         return NULL;
552 }
553
554 static enum line_compiled get_pp(struct pp_conditions *cond,
555                                  struct list_head *syms)
556 {
557         struct symbol *sym;
558         unsigned int val;
559         enum line_compiled parent, ret;
560
561         /* No conditions?  Easy. */
562         if (!cond)
563                 return COMPILED;
564
565         /* Check we get here at all. */
566         parent = get_pp(cond->parent, syms);
567         if (parent == NOT_COMPILED)
568                 return NOT_COMPILED;
569
570         if (cond->type == PP_COND_UNKNOWN)
571                 return MAYBE_COMPILED;
572
573         sym = find_symbol(syms, cond->symbol);
574         if (!sym)
575                 return MAYBE_COMPILED;
576
577         switch (cond->type) {
578         case PP_COND_IF:
579                 /* Undefined is 0. */
580                 val = sym->value ? *sym->value : 0;
581                 if (!val == cond->inverse)
582                         ret = COMPILED;
583                 else
584                         ret = NOT_COMPILED;
585                 break;
586
587         case PP_COND_IFDEF:
588                 if (cond->inverse == !sym->value)
589                         ret = COMPILED;
590                 else
591                         ret = NOT_COMPILED;
592                 break;
593
594         default:
595                 abort();
596         }
597
598         /* If parent didn't know, NO == NO, but YES == MAYBE. */
599         if (parent == MAYBE_COMPILED && ret == COMPILED)
600                 ret = MAYBE_COMPILED;
601         return ret;
602 }
603
604 static void add_symbol(struct list_head *head,
605                        const char *symbol, const unsigned int *value)
606 {
607         struct symbol *sym = talloc(head, struct symbol);
608         sym->name = symbol;
609         sym->value = value;
610         list_add(head, &sym->list);
611 }
612         
613 enum line_compiled get_ccan_line_pp(struct pp_conditions *cond,
614                                     const char *symbol,
615                                     const unsigned int *value,
616                                     ...)
617 {
618         enum line_compiled ret;
619         struct list_head *head;
620         va_list ap;
621
622         head = talloc(NULL, struct list_head);
623         list_head_init(head);
624
625         va_start(ap, value);
626         add_symbol(head, symbol, value);
627
628         while ((symbol = va_arg(ap, const char *)) != NULL) {
629                 value = va_arg(ap, const unsigned int *);
630                 add_symbol(head, symbol, value);
631         }
632         ret = get_pp(cond, head);
633         talloc_free(head);
634         return ret;
635 }
636
637 void score_file_error(struct score *score, struct ccan_file *f, unsigned line,
638                       const char *errorfmt, ...)
639 {
640         va_list ap;
641
642         struct file_error *fe = talloc(score, struct file_error);
643         fe->file = f;
644         fe->line = line;
645         list_add_tail(&score->per_file_errors, &fe->list);
646
647         if (!score->error)
648                 score->error = talloc_strdup(score, "");
649         
650         if (verbose < 2 && strcount(score->error, "\n") > 5)
651                 return;
652
653         if (line)
654                 score->error = talloc_asprintf_append(score->error,
655                                                       "%s:%u:",
656                                                       f->fullname, line);
657         else
658                 score->error = talloc_asprintf_append(score->error,
659                                                       "%s:", f->fullname);
660
661         va_start(ap, errorfmt);
662         score->error = talloc_vasprintf_append(score->error, errorfmt, ap);
663         va_end(ap);
664         score->error = talloc_append_string(score->error, "\n");
665
666         if (verbose < 2 && strcount(score->error, "\n") > 5)
667                 score->error = talloc_append_string(score->error,
668                                     "... more (use -vv to see them all)\n");
669 }