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