examples_compile.c 16 KB

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