0f3dd0cd4bf76997417e0bc734b77f90897d3ebc
[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 if there's no object file for that module */
41         if (!expect_obj_file(talloc_asprintf(list, "%s/ccan/%s", ccan_dir,mod)))
42                 return list;
43
44         obj = talloc_asprintf(list, "%s/ccan/%s.o", ccan_dir, mod);
45
46         /* Not anyone we've already included. */
47         if (strstr(list, obj))
48                 return list;
49
50         list = talloc_asprintf_append(list, " %s", obj);
51
52         /* Get that modules depends as well... */
53         assert(!safe_mode);
54         deps = get_deps(m, talloc_asprintf(list, "%s/ccan/%s", ccan_dir, mod),
55                         false, NULL);
56
57         for (i = 0; deps[i]; i++) {
58                 if (strstarts(deps[i], "ccan/"))
59                         list = add_dep(m, list, deps[i] + strlen("ccan/"));
60         }
61         return list;
62 }
63
64 static char *obj_list(const struct manifest *m, struct ccan_file *f)
65 {
66         char *list = talloc_strdup(m, "");
67         struct ccan_file *i;
68         char **lines;
69
70         /* Object files for this module. */
71         list_for_each(&m->c_files, i, list)
72                 list = talloc_asprintf_append(list, " %s", i->compiled);
73
74         /* Other ccan modules we depend on. */
75         list_for_each(&m->dep_dirs, i, list) {
76                 if (i->compiled)
77                         list = talloc_asprintf_append(list, " %s", i->compiled);
78         }
79
80         /* Other modules implied by includes. */
81         for (lines = get_ccan_file_lines(f); *lines; lines++) {
82                 unsigned preflen = strspn(*lines, " \t");
83                 if (strstarts(*lines + preflen, "#include <ccan/")) {
84                         const char *mod;
85                         unsigned modlen;
86
87                         mod = *lines + preflen + strlen("#include <ccan/");
88                         modlen = strcspn(mod, "/");
89                         mod = talloc_strndup(f, mod, modlen);
90                         /* Not ourselves. */
91                         if (streq(m->basename, mod))
92                                 continue;
93                         list = add_dep(m, list, mod);
94                 }
95         }
96
97         return list;
98 }
99
100 static char *lib_list(const struct manifest *m)
101 {
102         unsigned int i, num;
103         char **libs = get_libs(m, ".", &num, &m->info_file->compiled);
104         char *ret = talloc_strdup(m, "");
105
106         for (i = 0; i < num; i++)
107                 ret = talloc_asprintf_append(ret, "-l%s ", libs[i]);
108         return ret;
109 }
110
111 static char *compile(const void *ctx,
112                      struct manifest *m,
113                      struct ccan_file *file,
114                      bool keep)
115 {
116         char *errmsg;
117
118         file->compiled = maybe_temp_file(ctx, "", keep, file->fullname);
119         errmsg = compile_and_link(ctx, file->fullname, ccan_dir,
120                                   obj_list(m, file),
121                                   "", lib_list(m), file->compiled);
122         if (errmsg) {
123                 talloc_free(file->compiled);
124                 return errmsg;
125         }
126         return NULL;
127 }
128
129 struct score {
130         unsigned int score;
131         char *errors;
132 };
133
134 static char *start_main(char *ret)
135 {
136         return talloc_asprintf_append(ret,
137                                       "/* Fake function wrapper inserted */\n"
138                                       "int main(int argc, char *argv[])\n"
139                                       "{\n");
140 }
141
142 /* We only handle simple function definitions here. */
143 static char *add_func(char *others, const char *line)
144 {
145         const char *p, *end = strchr(line, '(') - 1;
146         while (isblank(*end)) {
147                 end--;
148                 if (end == line)
149                         return others;
150         }
151
152         for (p = end; isalnum(*p) || *p == '_'; p--) {
153                 if (p == line)
154                         return others;
155         }
156
157         return talloc_asprintf_append(others, "printf(\"%%p\", %.*s);\n",
158                                       end - p + 1, p);
159 }
160
161 static void strip_leading_whitespace(char **lines)
162 {
163         unsigned int i, min_span = -1U;
164
165         for (i = 0; lines[i]; i++) {
166                 unsigned int span = strspn(lines[i], " \t");
167                 /* All whitespace?  Ignore */
168                 if (!lines[i][span])
169                         continue;
170                 if (span < min_span)
171                         min_span = span;
172         }
173
174         for (i = 0; lines[i]; i++)
175                 if (strlen(lines[i]) >= min_span)
176                         lines[i] += min_span;
177 }
178
179 static bool looks_internal(char **lines)
180 {
181         unsigned int i;
182
183         for (i = 0; lines[i]; i++) {
184                 unsigned len = strspn(lines[i], IDENT_CHARS);
185
186                 /* The winners. */
187                 if (strstarts(lines[i], "if") && len == 2)
188                         return true;
189                 if (strstarts(lines[i], "for") && len == 3)
190                         return true;
191                 if (strstarts(lines[i], "while") && len == 5)
192                         return true;
193                 if (strstarts(lines[i], "do") && len == 2)
194                         return true;
195
196                 /* The losers. */
197                 if (strchr(lines[i], '(')) {
198                         if (strstarts(lines[i], "static"))
199                                 return false;
200                         if (strends(lines[i], ")"))
201                                 return false;
202                 }
203         }
204
205         /* No idea... Say no? */
206         return false;
207 }
208
209 /* Examples will often build on prior ones.  Try combining them. */
210 static char **combine(char **lines, char **prev)
211 {
212         unsigned int i, lines_total, prev_total, count;
213         char **ret;
214
215         if (!prev)
216                 return NULL;
217
218         strip_leading_whitespace(lines);
219
220         /* If it looks internal, put prev at start. */
221         if (looks_internal(lines)) {
222                 count = 0;
223         } else {
224                 /* Try inserting in first elided position */
225                 for (count = 0; lines[count]; count++) {
226                         if (strcmp(lines[count], "...") == 0)
227                                 break;
228                 }
229                 if (!lines[count])
230                         /* Try at start anyway? */
231                         count = 0;
232                 else
233                         count++;
234         }
235
236         for (i = 0; lines[i]; i++);
237         lines_total = i;
238
239         for (i = 0; prev[i]; i++);
240         prev_total = i;
241
242         ret = talloc_array(lines, char *, lines_total + prev_total + 1);
243         memcpy(ret, lines, count * sizeof(ret[0]));
244         memcpy(ret + count, prev, prev_total * sizeof(ret[0]));
245         memcpy(ret + count + prev_total, lines + count,
246                (lines_total - count + 1) * sizeof(ret[0]));
247         return ret;
248 }
249
250 static char *mangle(struct manifest *m, char **lines)
251 {
252         char *ret, *use_funcs = NULL;
253         bool in_function = false, fake_function = false, has_main = false;
254         unsigned int i;
255
256         ret = talloc_strdup(m, "/* Prepend a heap of headers. */\n"
257                             "#include <assert.h>\n"
258                             "#include <err.h>\n"
259                             "#include <errno.h>\n"
260                             "#include <fcntl.h>\n"
261                             "#include <limits.h>\n"
262                             "#include <stdbool.h>\n"
263                             "#include <stdint.h>\n"
264                             "#include <stdio.h>\n"
265                             "#include <stdlib.h>\n"
266                             "#include <string.h>\n"
267                             "#include <sys/stat.h>\n"
268                             "#include <sys/types.h>\n"
269                             "#include <unistd.h>\n");
270         ret = talloc_asprintf_append(ret, "/* Include header from module. */\n"
271                                      "#include <ccan/%s/%s.h>\n",
272                                      m->basename, m->basename);
273
274         ret = talloc_asprintf_append(ret, "/* Useful dummy functions. */\n"
275                                      "int somefunc(void);\n"
276                                      "int somefunc(void) { return 0; }\n");
277
278         strip_leading_whitespace(lines);
279         if (looks_internal(lines)) {
280                 /* Wrap it all in main(). */
281                 ret = start_main(ret);
282                 fake_function = true;
283                 in_function = true;
284                 has_main = true;
285         }
286
287         /* Primitive, very primitive. */
288         for (i = 0; lines[i]; i++) {
289                 /* } at start of line ends a function. */
290                 if (in_function) {
291                         if (lines[i][0] == '}')
292                                 in_function = false;
293                 } else {
294                         /* Character at start of line, with ( and no ;
295                          * == function start.  Ignore comments. */
296                         if (!isblank(lines[i][0])
297                             && strchr(lines[i], '(')
298                             && !strchr(lines[i], ';')
299                             && !strstr(lines[i], "//")) {
300                                 in_function = true;
301                                 if (strncmp(lines[i], "int main", 8) == 0)
302                                         has_main = true;
303                                 if (strncmp(lines[i], "static", 6) == 0) {
304                                         use_funcs = add_func(use_funcs,
305                                                              lines[i]);
306                                 }
307                         }
308                 }
309                 /* ... means elided code.  If followed by spaced line, means
310                  * next part is supposed to be inside a function. */
311                 if (strcmp(lines[i], "...") == 0) {
312                         if (!in_function
313                             && lines[i+1]
314                             && isblank(lines[i+1][0])) {
315                                 /* This implies we start a function here. */
316                                 ret = start_main(ret);
317                                 has_main = true;
318                                 fake_function = true;
319                                 in_function = true;
320                         }
321                         ret = talloc_asprintf_append(ret,
322                                                      "/* ... removed */\n");
323                         continue;
324                 }
325                 ret = talloc_asprintf_append(ret, "%s\n", lines[i]);
326         }
327
328         /* Need a main to link successfully. */
329         if (!has_main) {
330                 ret = talloc_asprintf_append(ret, "int main(void)\n{\n");
331                 fake_function = true;
332         }
333
334         /* Get rid of unused warnings by printing addresses of static funcs. */
335         if (use_funcs) {
336                 if (!fake_function) {
337                         ret = talloc_asprintf_append(ret,
338                                                      "int use_funcs(void);\n"
339                                                      "int use_funcs(void) {\n");
340                         fake_function = true;
341                 }
342                 ret = talloc_asprintf_append(ret, "     %s\n", use_funcs);
343         }
344
345         if (fake_function)
346                 ret = talloc_asprintf_append(ret, "return 0;\n"
347                                              "}\n");
348         return ret;
349 }
350
351 static struct ccan_file *mangle_example(struct manifest *m,
352                                         struct ccan_file *example,
353                                         char **lines,
354                                         bool keep)
355 {
356         char *name, *contents;
357         int fd;
358         struct ccan_file *f;
359
360         name = maybe_temp_file(example, ".c", keep, 
361                                talloc_asprintf(m, "%s/mangled-%s",
362                                                m->dir, example->name));
363         f = new_ccan_file(example,
364                           talloc_dirname(example, name),
365                           talloc_basename(example, name));
366         talloc_steal(f, name);
367
368         fd = open(f->fullname, O_WRONLY | O_CREAT | O_EXCL, 0600);
369         if (fd < 0)
370                 return NULL;
371
372         contents = mangle(m, lines);
373         if (write(fd, contents, strlen(contents)) != strlen(contents)) {
374                 close(fd);
375                 return NULL;
376         }
377         close(fd);
378         f->contents = talloc_steal(f, contents);
379         return f;
380 }
381
382 static void *build_examples(struct manifest *m, bool keep,
383                             unsigned int *timeleft)
384 {
385         struct ccan_file *i;
386         struct score *score = talloc(m, struct score);
387         struct ccan_file *mangle;
388         char **prev = NULL;
389
390         score->score = 0;
391         score->errors = NULL;
392
393         list_for_each(&m->examples, i, list) {
394                 char *ret;
395
396                 examples_compile.total_score++;
397                 ret = compile(score, m, i, keep);
398                 if (!ret) {
399                         prev = get_ccan_file_lines(i);
400                         score->score++;
401                         continue;
402                 }
403
404                 talloc_free(ret);
405                 mangle = mangle_example(m, i, get_ccan_file_lines(i), keep);
406                 ret = compile(score, m, mangle, keep);
407                 if (!ret) {
408                         prev = get_ccan_file_lines(i);
409                         score->score++;
410                         continue;
411                 }
412
413                 /* Try combining with previous (successful) example... */
414                 if (prev) {
415                         prev = combine(get_ccan_file_lines(i), prev);
416                         talloc_free(ret);
417
418                         /* We're going to replace this failure. */
419                         if (keep)
420                                 unlink(mangle->fullname);
421                         talloc_free(mangle);
422
423                         mangle = mangle_example(m, i, prev, keep);
424                         ret = compile(score, m, mangle, keep);
425                         if (!ret) {
426                                 score->score++;
427                                 continue;
428                         }
429                 }
430
431                 if (!score->errors)
432                         score->errors = ret;
433                 else {
434                         score->errors = talloc_append_string(score->errors,
435                                                              ret);
436                         talloc_free(ret);
437                 }
438                 /* This didn't work, so not a candidate for combining. */
439                 talloc_free(prev);
440                 prev = NULL;
441         }
442         return score;
443 }
444
445 static unsigned int score_examples(struct manifest *m, void *check_result)
446 {
447         struct score *score = check_result;
448         return score->score;
449 }
450
451 static const char *describe(struct manifest *m, void *check_result)
452 {
453         struct score *score = check_result;
454         if (verbose >= 2 && score->errors)
455                 return talloc_asprintf(m, "Compile errors building examples:\n"
456                                        "%s", score->errors);
457         return NULL;
458 }
459
460 struct ccanlint examples_compile = {
461         .key = "examples-compile",
462         .name = "Module examples compile",
463         .score = score_examples,
464         .check = build_examples,
465         .describe = describe,
466         .can_run = can_run,
467 };
468
469 REGISTER_TEST(examples_compile, &has_examples, NULL);