examples_compile.c 16 KB

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