examples_compile.c 15 KB

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