examples_compile.c 16 KB

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