ccanlint: more heuristics for compiling examples.
[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 <sys/types.h>
5 #include <sys/stat.h>
6 #include <fcntl.h>
7 #include <stdint.h>
8 #include <string.h>
9 #include <unistd.h>
10 #include <ctype.h>
11
12 static const char *can_run(struct manifest *m)
13 {
14         if (safe_mode)
15                 return "Safe mode enabled";
16         return NULL;
17 }
18
19 static char *obj_list(const struct manifest *m)
20 {
21         char *list = talloc_strdup(m, "");
22         struct ccan_file *i;
23
24         /* Object files for this module. */
25         list_for_each(&m->c_files, i, list)
26                 list = talloc_asprintf_append(list, " %s", i->compiled);
27
28         /* Other ccan modules we depend on. */
29         list_for_each(&m->dep_dirs, i, list) {
30                 if (i->compiled)
31                         list = talloc_asprintf_append(list, " %s", i->compiled);
32         }
33
34         return list;
35 }
36
37 static char *lib_list(const struct manifest *m)
38 {
39         unsigned int i, num;
40         char **libs = get_libs(m, ".", &num, &m->info_file->compiled);
41         char *ret = talloc_strdup(m, "");
42
43         for (i = 0; i < num; i++)
44                 ret = talloc_asprintf_append(ret, "-l%s ", libs[i]);
45         return ret;
46 }
47
48 static char *compile(const void *ctx,
49                      struct manifest *m,
50                      struct ccan_file *file,
51                      bool keep)
52 {
53         char *errmsg;
54
55         file->compiled = maybe_temp_file(ctx, "", keep, file->fullname);
56         errmsg = compile_and_link(ctx, file->fullname, ccan_dir,
57                                   obj_list(m), "", lib_list(m), file->compiled);
58         if (errmsg) {
59                 talloc_free(file->compiled);
60                 return errmsg;
61         }
62         return NULL;
63 }
64
65 struct score {
66         unsigned int score;
67         char *errors;
68 };
69
70 static char *start_main(char *ret)
71 {
72         return talloc_asprintf_append(ret,
73                                       "/* Fake function wrapper inserted */\n"
74                                       "int main(int argc, char *argv[])\n"
75                                       "{\n");
76 }
77
78 /* We only handle simple function definitions here. */
79 static char *add_func(char *others, const char *line)
80 {
81         const char *p, *end = strchr(line, '(') - 1;
82         while (isblank(*end)) {
83                 end--;
84                 if (end == line)
85                         return others;
86         }
87
88         for (p = end; isalnum(*p) || *p == '_'; p--) {
89                 if (p == line)
90                         return others;
91         }
92
93         return talloc_asprintf_append(others, "printf(\"%%p\", %.*s);\n",
94                                       end - p + 1, p);
95 }
96
97 static bool looks_internal(const char *p)
98 {
99         return (strncmp(p, "#", 1) != 0
100                 && strncmp(p, "static", 6) != 0
101                 && strncmp(p, "struct", 6) != 0
102                 && strncmp(p, "union", 5) != 0);
103 }
104
105 static void strip_leading_whitespace(char **lines, unsigned prefix_len)
106 {
107         unsigned int i;
108
109         for (i = 0; lines[i]; i++)
110                 if (strlen(lines[i]) >= prefix_len)
111                         lines[i] += prefix_len;
112 }
113
114 /* Examples will often build on prior ones.  Try combining them. */
115 static char **combine(char **lines, char **prev)
116 {
117         unsigned int i, lines_total, prev_total, count;
118         char **ret;
119
120         if (!prev)
121                 return NULL;
122
123         /* If it looks internal, put prev at start. */
124         if (lines[0]
125             && isblank(lines[0][0])
126             && looks_internal(lines[0] + strspn(lines[0], " \t"))) {
127                 count = 0;
128         } else {
129                 /* Try inserting in first elided position */
130                 for (count = 0; lines[count]; count++) {
131                         if (strcmp(lines[count], "...") == 0)
132                                 break;
133                 }
134                 if (!lines[count])
135                         return NULL;
136                 count++;
137         }
138
139         for (i = 0; lines[i]; i++);
140         lines_total = i;
141
142         for (i = 0; prev[i]; i++);
143         prev_total = i;
144
145         ret = talloc_array(lines, char *, lines_total + prev_total + 1);
146         memcpy(ret, lines, count * sizeof(ret[0]));
147         memcpy(ret + count, prev, prev_total * sizeof(ret[0]));
148         memcpy(ret + count + prev_total, lines + count,
149                (lines_total - count + 1) * sizeof(ret[0]));
150         return ret;
151 }
152
153 static char *mangle(struct manifest *m, char **lines)
154 {
155         char *ret, *use_funcs = NULL;
156         bool in_function = false, fake_function = false, has_main = false;
157         unsigned int i;
158
159         ret = talloc_strdup(m, "/* Prepend a heap of headers. */\n"
160                             "#include <assert.h>\n"
161                             "#include <err.h>\n"
162                             "#include <fcntl.h>\n"
163                             "#include <stdbool.h>\n"
164                             "#include <stdint.h>\n"
165                             "#include <stdio.h>\n"
166                             "#include <stdlib.h>\n"
167                             "#include <string.h>\n"
168                             "#include <sys/stat.h>\n"
169                             "#include <sys/types.h>\n"
170                             "#include <unistd.h>\n");
171         ret = talloc_asprintf_append(ret, "/* Include header from module. */\n"
172                                      "#include <ccan/%s/%s.h>\n",
173                                      m->basename, m->basename);
174
175         ret = talloc_asprintf_append(ret, "/* Useful dummy functions. */\n"
176                                      "int somefunc(void);\n"
177                                      "int somefunc(void) { return 0; }\n");
178
179         /* Starts indented? */
180         if (lines[0] && isblank(lines[0][0])) {
181                 unsigned prefix = strspn(lines[0], " \t");
182                 if (looks_internal(lines[0] + prefix)) {
183                         /* Wrap it all in main(). */
184                         ret = start_main(ret);
185                         fake_function = true;
186                         in_function = true;
187                         has_main = true;
188                 } else
189                         strip_leading_whitespace(lines, prefix);
190         }
191
192         /* Primitive, very primitive. */
193         for (i = 0; lines[i]; i++) {
194                 /* } at start of line ends a function. */
195                 if (in_function) {
196                         if (lines[i][0] == '}')
197                                 in_function = false;
198                 } else {
199                         /* Character at start of line, with ( and no ;
200                          * == function start. */
201                         if (!isblank(lines[i][0])
202                             && strchr(lines[i], '(')
203                             && !strchr(lines[i], ';')) {
204                                 in_function = true;
205                                 if (strncmp(lines[i], "int main", 8) == 0)
206                                         has_main = true;
207                                 if (strncmp(lines[i], "static", 6) == 0) {
208                                         use_funcs = add_func(use_funcs,
209                                                              lines[i]);
210                                 }
211                         }
212                 }
213                 /* ... means elided code.  If followed by spaced line, means
214                  * next part is supposed to be inside a function. */
215                 if (strcmp(lines[i], "...") == 0) {
216                         if (!in_function
217                             && lines[i+1]
218                             && isblank(lines[i+1][0])) {
219                                 /* This implies we start a function here. */
220                                 ret = start_main(ret);
221                                 has_main = true;
222                                 fake_function = true;
223                                 in_function = true;
224                         }
225                         ret = talloc_asprintf_append(ret,
226                                                      "/* ... removed */\n");
227                         continue;
228                 }
229                 ret = talloc_asprintf_append(ret, "%s\n", lines[i]);
230         }
231
232         /* Need a main to link successfully. */
233         if (!has_main) {
234                 ret = talloc_asprintf_append(ret, "int main(void)\n{\n");
235                 fake_function = true;
236         }
237
238         /* Get rid of unused warnings by printing addresses of static funcs. */
239         if (use_funcs) {
240                 if (!fake_function) {
241                         ret = talloc_asprintf_append(ret,
242                                                      "int use_funcs(void);\n"
243                                                      "int use_funcs(void) {\n");
244                         fake_function = true;
245                 }
246                 ret = talloc_asprintf_append(ret, "     %s\n", use_funcs);
247         }
248
249         if (fake_function)
250                 ret = talloc_asprintf_append(ret, "return 0;\n"
251                                              "}\n");
252         return ret;
253 }
254
255 static struct ccan_file *mangle_example(struct manifest *m,
256                                         struct ccan_file *example,
257                                         char **lines,
258                                         bool keep)
259 {
260         char *name, *contents;
261         int fd;
262         struct ccan_file *f;
263
264         name = maybe_temp_file(example, ".c", keep, 
265                                talloc_asprintf(m, "%s/mangled-%s",
266                                                m->dir, example->name));
267         f = new_ccan_file(example,
268                           talloc_dirname(example, name),
269                           talloc_basename(example, name));
270         talloc_steal(f, name);
271
272         fd = open(f->fullname, O_WRONLY | O_CREAT | O_EXCL, 0600);
273         if (fd < 0)
274                 return NULL;
275
276         contents = mangle(m, lines);
277         if (write(fd, contents, strlen(contents)) != strlen(contents)) {
278                 close(fd);
279                 return NULL;
280         }
281         close(fd);
282         return f;
283 }
284
285 static void *build_examples(struct manifest *m, bool keep,
286                             unsigned int *timeleft)
287 {
288         struct ccan_file *i;
289         struct score *score = talloc(m, struct score);
290         struct ccan_file *mangle;
291         char **prev = NULL;
292
293         score->score = 0;
294         score->errors = NULL;
295
296         list_for_each(&m->examples, i, list) {
297                 char *ret;
298
299                 examples_compile.total_score++;
300                 ret = compile(score, m, i, keep);
301                 if (!ret) {
302                         prev = get_ccan_file_lines(i);
303                         score->score++;
304                         continue;
305                 }
306
307                 talloc_free(ret);
308                 mangle = mangle_example(m, i, get_ccan_file_lines(i), keep);
309                 ret = compile(score, m, mangle, keep);
310                 if (!ret) {
311                         prev = get_ccan_file_lines(i);
312                         score->score++;
313                         continue;
314                 }
315
316                 /* Try combining with previous (successful) example... */
317                 prev = combine(get_ccan_file_lines(i), prev);
318                 if (prev) {
319                         talloc_free(ret);
320
321                         /* We're going to replace this failure. */
322                         if (keep)
323                                 unlink(mangle->fullname);
324                         talloc_free(mangle);
325
326                         mangle = mangle_example(m, i, prev, keep);
327                         ret = compile(score, m, mangle, keep);
328                         if (!ret) {
329                                 score->score++;
330                                 continue;
331                         }
332                 }
333
334                 if (!score->errors)
335                         score->errors = ret;
336                 else {
337                         score->errors = talloc_append_string(score->errors,
338                                                              ret);
339                         talloc_free(ret);
340                 }
341                 /* This didn't work, so not a candidate for combining. */
342                 talloc_free(prev);
343                 prev = NULL;
344         }
345         return score;
346 }
347
348 static unsigned int score_examples(struct manifest *m, void *check_result)
349 {
350         struct score *score = check_result;
351         return score->score;
352 }
353
354 static const char *describe(struct manifest *m, void *check_result)
355 {
356         struct score *score = check_result;
357         if (verbose >= 2 && score->errors)
358                 return talloc_asprintf(m, "Compile errors building examples:\n"
359                                        "%s", score->errors);
360         return NULL;
361 }
362
363 struct ccanlint examples_compile = {
364         .key = "examples-compile",
365         .name = "Module examples compile",
366         .score = score_examples,
367         .check = build_examples,
368         .describe = describe,
369         .can_run = can_run,
370 };
371
372 REGISTER_TEST(examples_compile, &has_examples, NULL);