examples_compile.c 16 KB

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