]> git.ozlabs.org Git - ccan/blob - tools/ccanlint/tests/examples_compile.c
f9a919a1bfcf7d83748d026e79ec8eb2dd278601
[ccan] / tools / ccanlint / tests / examples_compile.c
1 #include <tools/ccanlint/ccanlint.h>
2 #include <tools/tools.h>
3 #include <ccan/talloc/talloc.h>
4 #include <ccan/str/str.h>
5 #include <sys/types.h>
6 #include <sys/stat.h>
7 #include <fcntl.h>
8 #include <stdint.h>
9 #include <string.h>
10 #include <unistd.h>
11 #include <ctype.h>
12 #include <assert.h>
13
14 static const char *can_run(struct manifest *m)
15 {
16         if (safe_mode)
17                 return "Safe mode enabled";
18         return NULL;
19 }
20
21 /* FIXME: We should build if it doesn't exist... */
22 static bool expect_obj_file(const char *dir)
23 {
24         struct manifest *dep_man;
25         bool has_c_files;
26
27         dep_man = get_manifest(dir, dir);
28
29         /* If it has C files, we expect an object file built from them. */
30         has_c_files = !list_empty(&dep_man->c_files);
31         talloc_free(dep_man);
32         return has_c_files;
33 }
34
35 static char *add_dep(const struct manifest *m, char *list, const char *mod)
36 {
37         char **deps, *obj;
38         unsigned int i;
39
40         /* Not ourselves. */
41         if (streq(m->basename, mod))
42                 return list;
43
44         /* Not if there's no object file for that module */
45         if (!expect_obj_file(talloc_asprintf(list, "%s/ccan/%s", ccan_dir,mod)))
46                 return list;
47
48         obj = talloc_asprintf(list, "%s/ccan/%s.o", ccan_dir, mod);
49
50         /* Not anyone we've already included. */
51         if (strstr(list, obj))
52                 return list;
53
54         list = talloc_asprintf_append(list, " %s", obj);
55
56         /* Get that modules depends as well... */
57         assert(!safe_mode);
58         deps = get_deps(m, talloc_asprintf(list, "%s/ccan/%s", ccan_dir, mod),
59                         false, NULL);
60
61         for (i = 0; deps[i]; i++) {
62                 if (strstarts(deps[i], "ccan/"))
63                         list = add_dep(m, list, deps[i] + strlen("ccan/"));
64         }
65         return list;
66 }
67
68 static char *obj_list(const struct manifest *m, struct ccan_file *f)
69 {
70         char *list = talloc_strdup(m, "");
71         struct ccan_file *i;
72         char **lines;
73
74         /* Object files for this module. */
75         list_for_each(&m->c_files, i, list)
76                 list = talloc_asprintf_append(list, " %s", i->compiled);
77
78         /* Other ccan modules we depend on. */
79         list_for_each(&m->dep_dirs, i, list) {
80                 if (i->compiled)
81                         list = talloc_asprintf_append(list, " %s", i->compiled);
82         }
83
84         /* Other modules implied by includes. */
85         for (lines = get_ccan_file_lines(f); *lines; lines++) {
86                 unsigned preflen = strspn(*lines, " \t");
87                 if (strstarts(*lines + preflen, "#include <ccan/")) {
88                         const char *mod;
89                         unsigned modlen;
90
91                         mod = *lines + preflen + strlen("#include <ccan/");
92                         modlen = strcspn(mod, "/");
93                         mod = talloc_strndup(f, mod, modlen);
94                         list = add_dep(m, list, mod);
95                 }
96         }
97
98         return list;
99 }
100
101 static char *lib_list(const struct manifest *m)
102 {
103         unsigned int i, num;
104         char **libs = get_libs(m, ".", &num, &m->info_file->compiled);
105         char *ret = talloc_strdup(m, "");
106
107         for (i = 0; i < num; i++)
108                 ret = talloc_asprintf_append(ret, "-l%s ", libs[i]);
109         return ret;
110 }
111
112 static char *compile(const void *ctx,
113                      struct manifest *m,
114                      struct ccan_file *file,
115                      bool keep)
116 {
117         char *errmsg;
118
119         file->compiled = maybe_temp_file(ctx, "", keep, file->fullname);
120         errmsg = compile_and_link(ctx, file->fullname, ccan_dir,
121                                   obj_list(m, file),
122                                   "", lib_list(m), file->compiled);
123         if (errmsg) {
124                 talloc_free(file->compiled);
125                 file->compiled = NULL;
126                 return errmsg;
127         }
128         return NULL;
129 }
130
131 struct score {
132         unsigned int score;
133         char *errors;
134 };
135
136 static char *start_main(char *ret, const char *why)
137 {
138         return talloc_asprintf_append(ret,
139               "/* The example %s, so fake function wrapper inserted */\n"
140               "int main(int argc, char *argv[])\n"
141               "{\n", why);
142 }
143
144 /* We only handle simple function definitions here. */
145 static char *add_func(char *others, const char *line)
146 {
147         const char *p, *end = strchr(line, '(') - 1;
148         while (isblank(*end)) {
149                 end--;
150                 if (end == line)
151                         return others;
152         }
153
154         for (p = end; isalnum(*p) || *p == '_'; p--) {
155                 if (p == line)
156                         return others;
157         }
158
159         return talloc_asprintf_append(others, "printf(\"%%p\", %.*s);\n",
160                                       (unsigned)(end - p + 1), p);
161 }
162
163 static void strip_leading_whitespace(char **lines)
164 {
165         unsigned int i, min_span = -1U;
166
167         for (i = 0; lines[i]; i++) {
168                 unsigned int span = strspn(lines[i], " \t");
169                 /* All whitespace?  Ignore */
170                 if (!lines[i][span])
171                         continue;
172                 if (span < min_span)
173                         min_span = span;
174         }
175
176         for (i = 0; lines[i]; i++)
177                 if (strlen(lines[i]) >= min_span)
178                         lines[i] += min_span;
179 }
180
181 static bool looks_internal(char **lines, char **why)
182 {
183         unsigned int i;
184         bool last_ended = true; /* Did last line finish a statement? */
185
186         for (i = 0; lines[i]; i++) {
187                 /* Skip leading whitespace. */
188                 const char *line = lines[i] + strspn(lines[i], " \t");
189                 unsigned len = strspn(line, IDENT_CHARS);
190
191                 if (!line[0] || isblank(line[0]) || strstarts(line, "//"))
192                         continue;
193
194                 /* The winners. */
195                 if (strstarts(line, "if") && len == 2) {
196                         *why = "starts with if";
197                         return true;
198                 }
199                 if (strstarts(line, "for") && len == 3) {
200                         *why = "starts with for";
201                         return true;
202                 }
203                 if (strstarts(line, "while") && len == 5) {
204                         *why = "starts with while";
205                         return true;
206                 }
207                 if (strstarts(line, "do") && len == 2) {
208                         *why = "starts with do";
209                         return true;
210                 }
211
212                 /* The losers. */
213                 if (strstarts(line, "#include")) {
214                         *why = "starts with #include";
215                         return false;
216                 }
217
218                 if (last_ended && strchr(line, '(')) {
219                         if (strstarts(line, "static")) {
220                                 *why = "starts with static and contains (";
221                                 return false;
222                         }
223                         if (strends(line, ")")) {
224                                 *why = "contains ( and ends with )";
225                                 return false;
226                         }
227                 }
228
229                 /* Single identifier then operator == inside function. */
230                 if (last_ended && len
231                     && ispunct(line[len+strspn(line+len, " ")])) {
232                         *why = "starts with identifier then punctuation";
233                         return true;
234                 }
235
236                 last_ended = (strends(line, "}")
237                               || strends(line, ";")
238                               || streq(line, "..."));
239         }
240
241         /* No idea... Say yes? */
242         *why = "gave no clues";
243         return true;
244 }
245
246 /* Examples will often build on prior ones.  Try combining them. */
247 static char **combine(const void *ctx, char **lines, char **prev)
248 {
249         unsigned int i, lines_total, prev_total, count;
250         char **ret;
251         const char *reasoning;
252         char *why = NULL;
253
254         if (!prev)
255                 return NULL;
256
257         /* If it looks internal, put prev at start. */
258         if (looks_internal(lines, &why)) {
259                 count = 0;
260                 reasoning = "seemed to belong inside a function";
261         } else {
262                 /* Try inserting in first elided position */
263                 for (count = 0; lines[count]; count++) {
264                         if (strcmp(lines[count], "...") == 0)
265                                 break;
266                 }
267                 if (!lines[count]) {
268                         /* Try at start anyway? */
269                         count = 0;
270                         reasoning = "didn't seem to belong inside"
271                                 " a function, so we prepended the previous"
272                                 " example";
273                 } else {
274                         reasoning = "didn't seem to belong inside"
275                                 " a function, so we put the previous example"
276                                 " at the first ...";
277
278                         count++;
279                 }
280         }
281
282         for (i = 0; lines[i]; i++);
283         lines_total = i;
284
285         for (i = 0; prev[i]; i++);
286         prev_total = i;
287
288         ret = talloc_array(ctx, char *, 1 +lines_total + prev_total + 1);
289         ret[0] = talloc_asprintf(ret, "/* The example %s, thus %s */\n",
290                                  why, reasoning);
291         memcpy(ret+1, lines, count * sizeof(ret[0]));
292         memcpy(ret+1 + count, prev, prev_total * sizeof(ret[0]));
293         memcpy(ret+1 + count + prev_total, lines + count,
294                (lines_total - count + 1) * sizeof(ret[0]));
295         return ret;
296 }
297
298 static char *mangle(struct manifest *m, char **lines)
299 {
300         char *ret, *use_funcs = NULL, *why;
301         bool in_function = false, fake_function = false, has_main = false;
302         unsigned int i;
303
304         ret = talloc_strdup(m, "/* Prepend a heap of headers. */\n"
305                             "#include <assert.h>\n"
306                             "#include <err.h>\n"
307                             "#include <errno.h>\n"
308                             "#include <fcntl.h>\n"
309                             "#include <limits.h>\n"
310                             "#include <stdbool.h>\n"
311                             "#include <stdint.h>\n"
312                             "#include <stdio.h>\n"
313                             "#include <stdlib.h>\n"
314                             "#include <string.h>\n"
315                             "#include <sys/stat.h>\n"
316                             "#include <sys/types.h>\n"
317                             "#include <unistd.h>\n");
318         ret = talloc_asprintf_append(ret, "/* Include header from module. */\n"
319                                      "#include <ccan/%s/%s.h>\n",
320                                      m->basename, m->basename);
321
322         ret = talloc_asprintf_append(ret, "/* Useful dummy functions. */\n"
323                                      "extern int somefunc(void);\n"
324                                      "int somefunc(void) { return 0; }\n"
325                                      "extern char somestring[];\n"
326                                      "char somestring[] = \"hello world\";\n");
327
328         if (looks_internal(lines, &why)) {
329                 /* Wrap it all in main(). */
330                 ret = start_main(ret, why);
331                 fake_function = true;
332                 in_function = true;
333                 has_main = true;
334         } else
335                 ret = talloc_asprintf_append(ret,
336                              "/* The example %s, so didn't wrap in main() */\n",
337                                      why);
338
339         /* Primitive, very primitive. */
340         for (i = 0; lines[i]; i++) {
341                 /* } at start of line ends a function. */
342                 if (in_function) {
343                         if (lines[i][0] == '}')
344                                 in_function = false;
345                 } else {
346                         /* Character at start of line, with ( and no ;
347                          * == function start.  Ignore comments. */
348                         if (!isblank(lines[i][0])
349                             && strchr(lines[i], '(')
350                             && !strchr(lines[i], ';')
351                             && !strstr(lines[i], "//")) {
352                                 in_function = true;
353                                 if (strncmp(lines[i], "int main", 8) == 0)
354                                         has_main = true;
355                                 if (strncmp(lines[i], "static", 6) == 0) {
356                                         use_funcs = add_func(use_funcs,
357                                                              lines[i]);
358                                 }
359                         }
360                 }
361                 /* ... means elided code. */
362                 if (strcmp(lines[i], "...") == 0) {
363                         if (!in_function && !has_main
364                             && looks_internal(lines + i + 1, &why)) {
365                                 /* This implies we start a function here. */
366                                 ret = start_main(ret, why);
367                                 has_main = true;
368                                 fake_function = true;
369                                 in_function = true;
370                         }
371                         ret = talloc_asprintf_append(ret,
372                                                      "/* ... removed */\n");
373                         continue;
374                 }
375                 ret = talloc_asprintf_append(ret, "%s\n", lines[i]);
376         }
377
378         if (!has_main) {
379                 ret = talloc_asprintf_append(ret,
380                              "/* Need a main to link successfully. */\n"
381                              "int main(void)\n{\n");
382                 fake_function = true;
383         }
384
385         if (use_funcs) {
386                 ret = talloc_asprintf_append(ret,
387                                              "/* Get rid of unused warnings"
388                                              " by printing addresses of"
389                                              " static funcs. */");
390                 if (!fake_function) {
391                         ret = talloc_asprintf_append(ret,
392                                                      "int use_funcs(void);\n"
393                                                      "int use_funcs(void) {\n");
394                         fake_function = true;
395                 }
396                 ret = talloc_asprintf_append(ret, "     %s\n", use_funcs);
397         }
398
399         if (fake_function)
400                 ret = talloc_asprintf_append(ret, "return 0;\n"
401                                              "}\n");
402         return ret;
403 }
404
405 static struct ccan_file *mangle_example(struct manifest *m,
406                                         struct ccan_file *example,
407                                         char **lines,
408                                         bool keep)
409 {
410         char *name, *contents;
411         int fd;
412         struct ccan_file *f;
413
414         name = maybe_temp_file(example, ".c", keep, 
415                                talloc_asprintf(m, "%s/mangled-%s",
416                                                m->dir, example->name));
417         f = new_ccan_file(example,
418                           talloc_dirname(example, name),
419                           talloc_basename(example, name));
420         talloc_steal(f, name);
421
422         fd = open(f->fullname, O_WRONLY | O_CREAT | O_EXCL, 0600);
423         if (fd < 0)
424                 return NULL;
425
426         contents = mangle(m, lines);
427         if (write(fd, contents, strlen(contents)) != strlen(contents)) {
428                 close(fd);
429                 return NULL;
430         }
431         close(fd);
432         f->contents = talloc_steal(f, contents);
433         list_add(&m->mangled_examples, &f->list);
434         return f;
435 }
436
437 static void *build_examples(struct manifest *m, bool keep,
438                             unsigned int *timeleft)
439 {
440         struct ccan_file *i;
441         struct score *score = talloc(m, struct score);
442         char **prev = NULL;
443
444         score->score = 0;
445         score->errors = talloc_strdup(score, "");
446
447         examples_compile.total_score = 0;
448         list_for_each(&m->examples, i, list) {
449                 char *ret, *ret1 = NULL, *ret2;
450                 struct ccan_file *mangle1 = NULL, *mangle2;
451
452                 examples_compile.total_score++;
453                 /* Simplify our dumb parsing. */
454                 strip_leading_whitespace(get_ccan_file_lines(i));
455                 ret = compile(i, m, i, keep);
456                 if (!ret) {
457                         prev = get_ccan_file_lines(i);
458                         score->score++;
459                         continue;
460                 }
461
462                 /* Try standalone. */
463                 mangle1 = mangle_example(m, i, get_ccan_file_lines(i), keep);
464                 ret1 = compile(i, m, mangle1, keep);
465                 if (!ret1) {
466                         prev = get_ccan_file_lines(i);
467                         score->score++;
468                         continue;
469                 }
470
471                 /* Try combining with previous (successful) example... */
472                 if (prev) {
473                         char **new = combine(i, get_ccan_file_lines(i), prev);
474
475                         mangle2 = mangle_example(m, i, new, keep);
476                         ret2 = compile(i, m, mangle1, keep);
477                         if (!ret2) {
478                                 prev = new;
479                                 score->score++;
480                                 continue;
481                         }
482                 }
483
484                 score->errors = talloc_asprintf_append(score->errors,
485                                        "%s: tried standalone example:\n"
486                                        "%s\n"
487                                        "Errors: %s\n\n",
488                                        i->name,
489                                        get_ccan_file_contents(i),
490                                        ret);
491                 score->errors = talloc_asprintf_append(score->errors,
492                                        "%s: tried adding headers, wrappers:\n"
493                                        "%s\n"
494                                        "Errors: %s\n\n",
495                                        i->name,
496                                        get_ccan_file_contents(mangle1),
497                                        ret1);
498
499                 if (mangle2) {
500                         score->errors = talloc_asprintf_append(score->errors,
501                                        "%s\n"
502                                        "%s: tried combining with"
503                                        " previous example:\n"
504                                        "Errors: %s\n\n",
505                                        i->name,
506                                        get_ccan_file_contents(mangle2),
507                                        ret2);
508                 }
509                 /* This didn't work, so not a candidate for combining. */
510                 prev = NULL;
511         }
512
513         if (strcmp(score->errors, "") == 0) {
514                 talloc_free(score);
515                 return NULL;
516         }
517         return score;
518 }
519
520 static unsigned int score_examples(struct manifest *m, void *check_result)
521 {
522         struct score *score = check_result;
523         return score->score;
524 }
525
526 static const char *describe(struct manifest *m, void *check_result)
527 {
528         struct score *score = check_result;
529         if (verbose >= 2 && score->errors)
530                 return talloc_asprintf(m, "Compile errors building examples:\n"
531                                        "%s", score->errors);
532         return NULL;
533 }
534
535 struct ccanlint examples_compile = {
536         .key = "examples-compile",
537         .name = "Module examples compile",
538         .score = score_examples,
539         .total_score = 3, /* This gets changed to # examples, if they exist */
540         .check = build_examples,
541         .describe = describe,
542         .can_run = can_run,
543 };
544
545 REGISTER_TEST(examples_compile, &has_examples, NULL);